materialCache.fileCache.test.js 16.6 KB
const assert = require('assert')
const waitForSourceLog = () => new Promise(resolve => setTimeout(resolve, 2050))

function createUni(options = {}) {
  const storage = new Map()
  const calls = { downloadFile: 0, downloadUrls: [], saveFile: 0, removeSavedFile: 0, getFileInfo: 0, request: 0, arrayBufferToBase64: 0, logs: [] }
  const pendingDownloads = []
  const savedFiles = new Set()
  let savedIndex = 0
  const api = {
    calls,
    storage,
    $logger: {
      info(message) { calls.logs.push(message) }
    },
    getNetworkType({ success }) { success({ networkType: 'wifi' }) },
    getStorage({ key, success, fail }) {
      if (storage.has(key)) success({ data: storage.get(key) })
      else fail({ errMsg: 'not found' })
    },
    setStorage({ key, data, success }) {
      storage.set(key, data)
      success({})
    },
    removeStorage({ key, success }) {
      storage.delete(key)
      success({})
    },
    downloadFile({ url, success }) {
      calls.downloadFile++
      calls.downloadUrls.push(url)
      const complete = () => success({
        statusCode: 200,
        tempFilePath: `_doc/temp/${encodeURIComponent(url)}.jpg`,
        header: options.downloadHeader || {}
      })
      if (options.deferDownloads) pendingDownloads.push(complete)
      else complete()
    },
    saveFile({ tempFilePath, success, fail }) {
      calls.saveFile++
      if (options.failSaveCount > 0) {
        options.failSaveCount--
        fail({ errMsg: 'disk full' })
        return
      }
      savedIndex++
      const savedFilePath = `_doc/uniapp_save/material-${savedIndex}.jpg`
      savedFiles.add(savedFilePath)
      success({ savedFilePath, tempFilePath })
    },
    getFileInfo({ filePath, success, fail }) {
      calls.getFileInfo++
      if (savedFiles.has(filePath)) success({ size: 1 })
      else fail({ errMsg: 'file not found' })
    },
    removeSavedFile({ filePath, success }) {
      calls.removeSavedFile++
      savedFiles.delete(filePath)
      success({})
    },
    request() {
      calls.request++
      throw new Error('素材图片不应再通过 arraybuffer 下载')
    },
    arrayBufferToBase64() {
      calls.arrayBufferToBase64++
      throw new Error('素材图片不应再转换为 Base64')
    }
  }
  api.releaseDownloads = () => pendingDownloads.splice(0).forEach(complete => complete())
  api.removeSavedFileFromSystem = filePath => savedFiles.delete(filePath)
  return api
}

async function run() {
  global.uni = createUni()
  const modulePath = require.resolve('../utils/materialCache.js')
  delete require.cache[modulePath]
  const materialCache = require(modulePath)
  const sourceKey = materialCache.getSourceKey('shop-1', 'scene-1', { brandId: 10, subBrandId: 20 })
  const url = 'https://example.test/large.jpg'
  const base = {
    id: 'source-1',
    moduleList: [{ id: 101, contentPicUrl: url }],
    toolList: []
  }

  await materialCache.cacheMaterialImages(sourceKey, base)
  const display = await materialCache.hydrateSourceImages(sourceKey, base, {
    moduleIds: [101],
    toolIds: [],
    isCurrent: () => true
  })
  await waitForSourceLog()

  assert.equal(uni.calls.downloadFile, 1, '首次缓存应下载一次文件')
  assert.equal(uni.calls.saveFile, 1, '首次缓存应保存一次文件')
  assert.equal(uni.calls.request, 0, '不应使用 arraybuffer 下载')
  assert.equal(uni.calls.arrayBufferToBase64, 0, '不应进行 Base64 转码')
  assert.equal(display.moduleList[0].contentPicUrl, '_doc/uniapp_save/material-1.jpg')
  assert.ok([...uni.storage.values()].every(value => !String(value).startsWith('data:image/')), 'storage 不应保存 Base64 图片')
  assert.equal(uni.calls.logs.length, 1, '同一次读取只应输出一条 OSS 来源汇总')
  const ossLog = uni.calls.logs[0]
  assert.ok(ossLog.startsWith('[素材来源汇总] OSS=1 | 文件=0 | OSS失败=0\nOSS明细:\n素材1 | '), '首次展示应计入分行的 OSS 汇总')
  assert.ok(/开始下载时间=\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}/.test(ossLog), 'OSS 明细应包含开始下载时间')
  assert.ok(/下载成功时间=\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}/.test(ossLog), 'OSS 明细应包含下载成功时间')
  assert.ok(ossLog.includes(`OSS路径=${url}`) && ossLog.includes('文件读取路径=_doc/uniapp_save/material-1.jpg'),
    'OSS 明细应包含 OSS 地址和文件读取路径')
  assert.ok(!ossLog.includes('下载状态=200') && !ossLog.includes('临时路径='), '成功明细不应包含状态 200 和临时路径')

  await materialCache.cacheMaterialImages(sourceKey, base)
  assert.equal(uni.calls.downloadFile, 1, '同一地址再次缓存应复用已保存文件')
  uni.calls.logs.length = 0
  materialCache.clearImageMemory()
  await Promise.all([1, 2, 3].map(() => materialCache.hydrateSourceImages(sourceKey, base, {
    moduleIds: [101], toolIds: [], isCurrent: () => true
  })))
  await waitForSourceLog()
  assert.deepEqual(uni.calls.logs, ['[素材来源汇总] OSS=0 | 文件=1 | OSS失败=0'],
    '短时间重复读取同一图片应去重并合并为一条文件来源汇总')

  const missingFilePath = display.moduleList[0].contentPicUrl
  uni.removeSavedFileFromSystem(missingFilePath)
  materialCache.clearImageMemory()
  const missingDisplay = await materialCache.hydrateSourceImages(sourceKey, base, {
    moduleIds: [101],
    toolIds: [],
    isCurrent: () => true
  })
  assert.equal(missingDisplay.moduleList[0].contentPicUrl, url, '文件被系统清理后不应继续返回失效路径')
  const repairedDisplay = await materialCache.hydrateSourceImages(sourceKey, base, {
    moduleIds: [101],
    toolIds: [],
    allowDownload: true,
    isCurrent: () => true
  })
  assert.equal(uni.calls.downloadFile, 2, '文件被系统清理后在线读取应自动重新下载')
  assert.equal(repairedDisplay.moduleList[0].contentPicUrl, '_doc/uniapp_save/material-2.jpg')
  await waitForSourceLog()
  uni.calls.logs.length = 0

  uni.removeSavedFileFromSystem(repairedDisplay.moduleList[0].contentPicUrl)
  materialCache.clearImageMemory()
  await materialCache.cacheMaterialImages(sourceKey, base)
  assert.equal(uni.calls.downloadFile, 3, '后台缓存发现文件被系统清理后应重新下载')

  const savedPathKey = [...uni.storage.keys()].find(key => key.startsWith('material_file_v1_'))
  assert.ok(savedPathKey, '应保存图片文件路径')
  uni.storage.delete(savedPathKey)
  materialCache.clearImageMemory()
  await materialCache.cacheMaterialImages(sourceKey, base)
  assert.equal(uni.calls.downloadFile, 4, '文件路径记录丢失后应重新下载修复')
  assert.equal(uni.calls.removeSavedFile, 2, '修复成功后应清理旧文件')

  const changed = JSON.parse(JSON.stringify(base))
  changed.moduleList[0].contentPicUrl = 'https://example.test/large-v2.jpg'
  await materialCache.cacheMaterialImages(sourceKey, changed)
  const changedDisplay = await materialCache.hydrateSourceImages(sourceKey, changed, {
    moduleIds: [101], toolIds: [], isCurrent: () => true
  })
  await waitForSourceLog()
  assert.equal(uni.calls.downloadFile, 5, '图片地址变化后应下载新文件')
  assert.equal(uni.calls.removeSavedFile, 3, '新文件成功后应删除旧文件')
  assert.equal(changedDisplay.moduleList[0].contentPicUrl, '_doc/uniapp_save/material-5.jpg')
  assert.ok(uni.calls.logs.some(message => message.startsWith('[素材来源汇总] OSS=1 | 文件=0 | OSS失败=0\nOSS明细:')),
    '更新后的图片首次展示时应计入带成功明细的 OSS 汇总')

  const withoutImages = { id: 'source-1', moduleList: [], toolList: [] }
  await materialCache.cacheMaterialImages(sourceKey, withoutImages)
  assert.equal(uni.calls.removeSavedFile, 4, '接口删除图片后应清理不再使用的文件')

  const failOptions = { failSaveCount: 1 }
  global.uni = createUni(failOptions)
  delete require.cache[modulePath]
  const retryCache = require(modulePath)
  const retryKey = retryCache.getSourceKey('shop-2', 'scene-1', { brandId: 10, subBrandId: 20 })
  await retryCache.cacheMaterialImages(retryKey, base)
  assert.equal(uni.calls.downloadFile, 1)
  assert.equal(uni.calls.saveFile, 1)
  await waitForSourceLog()
  assert.equal(uni.calls.logs.length, 1, 'OSS 下载或保存失败应输出一条失败汇总')
  assert.ok(uni.calls.logs[0].startsWith('[素材来源汇总] OSS=0 | 文件=0 | OSS失败=1\nOSS失败明细:\n素材1 | '),
    'OSS 失败明细应单独分行')
  assert.ok(uni.calls.logs[0].includes('下载状态=disk full') && uni.calls.logs[0].includes(`OSS路径=${url}`),
    'OSS 失败明细应包含失败状态和地址')
  assert.ok(/开始下载时间=.+下载失败时间=/.test(uni.calls.logs[0]), 'OSS 失败明细应包含开始和失败时间')
  await retryCache.cacheMaterialImages(retryKey, base)
  assert.equal(uni.calls.downloadFile, 2, '保存失败后再次缓存必须重试下载')
  assert.equal(uni.calls.saveFile, 2, '保存失败后再次缓存必须重试保存')

  global.uni = createUni({ deferDownloads: true })
  delete require.cache[modulePath]
  const concurrentCache = require(modulePath)
  const concurrentKey = concurrentCache.getSourceKey('shop-3', 'scene-1', { brandId: 10, subBrandId: 20 })
  const older = concurrentCache.cacheMaterialImages(concurrentKey, base)
  await new Promise(resolve => setImmediate(resolve))
  const newer = concurrentCache.cacheMaterialImages(concurrentKey, base)
  await new Promise(resolve => setImmediate(resolve))
  assert.equal(uni.calls.downloadFile, 1, '连续切换时同一图片应共享一次下载')
  uni.releaseDownloads()
  await Promise.all([older, newer])
  concurrentCache.clearImageMemory()
  const concurrentDisplay = await concurrentCache.hydrateSourceImages(concurrentKey, base, {
    moduleIds: [101], toolIds: [], isCurrent: () => true
  })
  assert.equal(concurrentDisplay.moduleList[0].contentPicUrl, '_doc/uniapp_save/material-1.jpg',
    '过期任务不能删除新任务正在复用的文件')
  assert.equal(uni.calls.removeSavedFile, 0, '共享文件不应被过期任务清理')

  global.uni = createUni({ deferDownloads: true })
  delete require.cache[modulePath]
  const switchedCache = require(modulePath)
  const switchedKey = switchedCache.getSourceKey('shop-4', 'scene-1', { brandId: 10, subBrandId: 20 })
  const oldBrand = switchedCache.cacheMaterialImages(switchedKey, base)
  await new Promise(resolve => setImmediate(resolve))
  const newBrand = JSON.parse(JSON.stringify(base))
  newBrand.moduleList[0].contentPicUrl = 'https://example.test/other-brand.jpg'
  await switchedCache.saveSourceCache(switchedKey, newBrand)
  uni.releaseDownloads()
  await oldBrand
  assert.equal(uni.calls.removeSavedFile, 1, '新配置保存后应清理过期下载文件')
  const newBrandTask = switchedCache.cacheMaterialImages(switchedKey, newBrand)
  await new Promise(resolve => setImmediate(resolve))
  assert.equal(uni.calls.downloadFile, 2, '新配置应下载自己的图片')
  uni.releaseDownloads()
  await newBrandTask
  switchedCache.clearImageMemory()
  const switchedDisplay = await switchedCache.hydrateSourceImages(switchedKey, newBrand, {
    moduleIds: [101], toolIds: [], isCurrent: () => true
  })
  assert.equal(switchedDisplay.moduleList[0].contentPicUrl, '_doc/uniapp_save/material-2.jpg')
  assert.equal(uni.calls.removeSavedFile, 1, '清理过期文件时不应误删新文件')

  // 车型切换的首屏只读取一张关键图片,剩余图片留给后台补齐,不能阻塞页面替换。
  global.uni = createUni()
  delete require.cache[modulePath]
  const progressiveCache = require(modulePath)
  const progressiveKey = progressiveCache.getSourceKey('shop-5', 'scene-1', { brandId: 10, subBrandId: 20 })
  const multiImageSource = {
    id: 'source-5',
    moduleList: [{
      id: 501,
      thumbnail: 'https://example.test/thumb.jpg',
      contentPicUrl: 'https://example.test/content.jpg',
      receptionSourceDetailList: [{ detailUrl: 'https://example.test/detail.jpg' }]
    }],
    toolList: []
  }
  await progressiveCache.cacheMaterialImages(progressiveKey, multiImageSource)
  progressiveCache.clearImageMemory()
  const firstScreen = await progressiveCache.hydrateSourceImages(progressiveKey, multiImageSource, {
    moduleIds: [501], toolIds: [], maxImages: 1, hideUnloadedImages: true, isCurrent: () => true
  })
  const firstModule = firstScreen.moduleList[0]
  const firstSavedCount = [firstModule.thumbnail, firstModule.contentPicUrl, firstModule.receptionSourceDetailList[0].detailUrl]
    .filter(value => value.startsWith('_doc/uniapp_save/')).length
  assert.equal(firstSavedCount, 1, '首屏只应读取一张关键图片')
  assert.ok([firstModule.thumbnail, firstModule.contentPicUrl, firstModule.receptionSourceDetailList[0].detailUrl]
    .filter(value => !value.startsWith('_doc/uniapp_save/')).every(value => value === ''), '未准备好的图片不应直接使用网络链接')
  const fullScreen = await progressiveCache.hydrateSourceImages(progressiveKey, multiImageSource, {
    moduleIds: [501], toolIds: [], isCurrent: () => true
  })
  const fullModule = fullScreen.moduleList[0]
  assert.ok([fullModule.thumbnail, fullModule.contentPicUrl, fullModule.receptionSourceDetailList[0].detailUrl]
    .every(value => value.startsWith('_doc/uniapp_save/')), '后台补齐时应恢复全部图片')
  await waitForSourceLog()
  assert.equal(uni.calls.logs.length, 1, '同一车型的分批读取应合并成一条日志')
  assert.ok(uni.calls.logs[0].startsWith('[素材来源汇总] OSS=3 | 文件=0 | OSS失败=0\nOSS明细:'),
    '合并日志应按图片去重并保留 OSS 明细')
  assert.equal((uni.calls.logs[0].match(/^素材\d+ \|/gm) || []).length, 3, '每张 OSS 图片应单独占一行')

  global.uni = createUni()
  delete require.cache[modulePath]
  const trimmedUrlCache = require(modulePath)
  const trimmedUrlKey = trimmedUrlCache.getSourceKey('shop-6', 'scene-1')
  const cleanUrl = 'https://example.test/trailing-space.jpg'
  const sourceWithSpaces = {
    id: 'source-6',
    moduleList: [{ id: 601, thumbnail: `  ${cleanUrl}  ` }],
    toolList: []
  }
  await trimmedUrlCache.cacheMaterialImages(trimmedUrlKey, sourceWithSpaces)
  assert.deepEqual(uni.calls.downloadUrls, [cleanUrl], '图片地址下载前应清除首尾空格')
  assert.ok([...uni.storage.values()].some(value => value && value[Object.keys(value)[0]]?.url === cleanUrl),
    '图片 URL 缓存应保存清理后的地址')

  // OSS 把 ?V=1 作为对象名的一部分时,下载地址必须保持编码原样;验证格式时再解码识别 .webp。
  global.uni = createUni({ downloadHeader: { 'Content-Type': 'application/octet-stream' } })
  const nativeDownloads = []
  global.plus = {
    downloader: {
      createDownload(url, options, complete) {
        const task = {
          filename: options.filename,
          getResponseHeader: () => 'application/octet-stream',
          start() {
            nativeDownloads.push({ url, filename: options.filename })
            complete(task, 200)
          },
          abort() {}
        }
        return task
      }
    },
    io: {
      resolveLocalFileSystemURL(path, success) { success({ fullPath: path }) }
    }
  }
  delete require.cache[modulePath]
  const encodedUrlCache = require(modulePath)
  const encodedUrlKey = encodedUrlCache.getSourceKey('shop-7', 'scene-1')
  const encodedWebpUrl = 'https://dj-oss-fastdfs.glsx.com.cn/weapp/resource/app-zyzs/media/byd/8-1.webp%3FV%3D1'
  const encodedSource = {
    id: 'source-7',
    moduleList: [
      { id: 701, contentPicUrl: encodedWebpUrl },
      { id: 702, contentPicUrl: encodedWebpUrl }
    ],
    toolList: []
  }
  await encodedUrlCache.cacheMaterialImages(encodedUrlKey, encodedSource)
  assert.deepEqual(nativeDownloads.map(item => item.url), [encodedWebpUrl], '特殊 OSS 地址下载时不能还原或改写转义内容')
  assert.ok(nativeDownloads[0].filename.startsWith('_doc/material_') && nativeDownloads[0].filename.endsWith('.webp'),
    'App 端应使用不含问号的安全文件名直接持久化')
  assert.equal(uni.calls.downloadFile, 0, '特殊 OSS 地址在 App 端不应再生成有问题的临时文件路径')
  assert.equal(uni.calls.saveFile, 0, '原生下载已经持久化,不应再次调用 saveFile')
  const encodedDisplay = await encodedUrlCache.hydrateSourceImages(encodedUrlKey, encodedSource, {
    moduleIds: [701, 702], toolIds: [], isCurrent: () => true
  })
  assert.equal(encodedDisplay.moduleList[0].contentPicUrl, nativeDownloads[0].filename,
    '特殊 OSS 图片保存后应能从本地文件展示')
  assert.equal(encodedDisplay.moduleList[1].contentPicUrl, nativeDownloads[0].filename,
    '相同 OSS 地址出现在多个位置时应复用同一份本地文件')
  delete global.plus
  console.log('PASS material file cache')
}

run().catch(error => {
  console.error(error.stack || error)
  process.exitCode = 1
})