Commit f2c96300 by chenwq

优化素材加载逻辑,增加素材来源日志记录和错误处理

1 parent 8c0d8801
...@@ -24,6 +24,9 @@ ...@@ -24,6 +24,9 @@
<script type='text/ecmascript-6'> <script type='text/ecmascript-6'>
import materialCache from '@/utils/materialCache' import materialCache from '@/utils/materialCache'
// uni-popup 调用 close 后会保留 300ms 退场动画;多留一帧,确保刷新素材前弹层已真正移除。
const POPUP_CLOSE_WAIT = 320
export default { export default {
name: 'CarBrands', name: 'CarBrands',
props: { props: {
...@@ -225,12 +228,17 @@ export default { ...@@ -225,12 +228,17 @@ export default {
oneCarBrand: selectItem.carBrand, oneCarBrand: selectItem.carBrand,
oneCarBrandId: selectItem.carBrandId oneCarBrandId: selectItem.carBrandId
}) })
// 页面刷新会重建当前素材组件;必须先让车系弹窗完成关闭,不能把浮层遗留到新页面里。 // 页面刷新会重建当前素材组件;先结束返回品牌列表的状态,再关闭两个弹层。
const popupWasOpen = !!(
this.$refs.carBoxVisible?.$refs?.tips?.showPopup ||
this.$refs.carBrandListVisible?.$refs?.tips?.showPopup
)
this.carBrandListOff = false
this.$refs.carBoxVisible?.close() this.$refs.carBoxVisible?.close()
this.$refs.carBrandListVisible?.close() this.$refs.carBrandListVisible?.close()
this.carBrandListOff = false
this.$store.dispatch('setCarBrandOpenStatus', false) this.$store.dispatch('setCarBrandOpenStatus', false)
await this.$nextTick() // nextTick 只等待页面更新,不会等待弹窗的 300ms 退场动画。
if (popupWasOpen) await new Promise(resolve => setTimeout(resolve, POPUP_CLOSE_WAIT))
if (linkage) { if (linkage) {
uni.$logger.local.info(`选择车: uni.$logger.local.info(`选择车:
carModel:${item.name}, carModel:${item.name},
......
const assert = require('assert') const assert = require('assert')
const waitForSourceLog = () => new Promise(resolve => setTimeout(resolve, 2050))
function createUni(options = {}) { function createUni(options = {}) {
const storage = new Map() const storage = new Map()
const calls = { downloadFile: 0, saveFile: 0, removeSavedFile: 0, getFileInfo: 0, request: 0, arrayBufferToBase64: 0 } const calls = { downloadFile: 0, downloadUrls: [], saveFile: 0, removeSavedFile: 0, getFileInfo: 0, request: 0, arrayBufferToBase64: 0, logs: [] }
const pendingDownloads = [] const pendingDownloads = []
const savedFiles = new Set() const savedFiles = new Set()
let savedIndex = 0 let savedIndex = 0
const api = { const api = {
calls, calls,
storage, storage,
$logger: {
info(message) { calls.logs.push(message) }
},
getNetworkType({ success }) { success({ networkType: 'wifi' }) }, getNetworkType({ success }) { success({ networkType: 'wifi' }) },
getStorage({ key, success, fail }) { getStorage({ key, success, fail }) {
if (storage.has(key)) success({ data: storage.get(key) }) if (storage.has(key)) success({ data: storage.get(key) })
...@@ -24,7 +28,12 @@ function createUni(options = {}) { ...@@ -24,7 +28,12 @@ function createUni(options = {}) {
}, },
downloadFile({ url, success }) { downloadFile({ url, success }) {
calls.downloadFile++ calls.downloadFile++
const complete = () => success({ statusCode: 200, tempFilePath: `_doc/temp/${encodeURIComponent(url)}.jpg` }) calls.downloadUrls.push(url)
const complete = () => success({
statusCode: 200,
tempFilePath: `_doc/temp/${encodeURIComponent(url)}.jpg`,
header: options.downloadHeader || {}
})
if (options.deferDownloads) pendingDownloads.push(complete) if (options.deferDownloads) pendingDownloads.push(complete)
else complete() else complete()
}, },
...@@ -83,6 +92,7 @@ async function run() { ...@@ -83,6 +92,7 @@ async function run() {
toolIds: [], toolIds: [],
isCurrent: () => true isCurrent: () => true
}) })
await waitForSourceLog()
assert.equal(uni.calls.downloadFile, 1, '首次缓存应下载一次文件') assert.equal(uni.calls.downloadFile, 1, '首次缓存应下载一次文件')
assert.equal(uni.calls.saveFile, 1, '首次缓存应保存一次文件') assert.equal(uni.calls.saveFile, 1, '首次缓存应保存一次文件')
...@@ -90,9 +100,25 @@ async function run() { ...@@ -90,9 +100,25 @@ async function run() {
assert.equal(uni.calls.arrayBufferToBase64, 0, '不应进行 Base64 转码') assert.equal(uni.calls.arrayBufferToBase64, 0, '不应进行 Base64 转码')
assert.equal(display.moduleList[0].contentPicUrl, '_doc/uniapp_save/material-1.jpg') 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.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) await materialCache.cacheMaterialImages(sourceKey, base)
assert.equal(uni.calls.downloadFile, 1, '同一地址再次缓存应复用已保存文件') 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 const missingFilePath = display.moduleList[0].contentPicUrl
uni.removeSavedFileFromSystem(missingFilePath) uni.removeSavedFileFromSystem(missingFilePath)
...@@ -111,6 +137,8 @@ async function run() { ...@@ -111,6 +137,8 @@ async function run() {
}) })
assert.equal(uni.calls.downloadFile, 2, '文件被系统清理后在线读取应自动重新下载') assert.equal(uni.calls.downloadFile, 2, '文件被系统清理后在线读取应自动重新下载')
assert.equal(repairedDisplay.moduleList[0].contentPicUrl, '_doc/uniapp_save/material-2.jpg') 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) uni.removeSavedFileFromSystem(repairedDisplay.moduleList[0].contentPicUrl)
materialCache.clearImageMemory() materialCache.clearImageMemory()
...@@ -131,9 +159,12 @@ async function run() { ...@@ -131,9 +159,12 @@ async function run() {
const changedDisplay = await materialCache.hydrateSourceImages(sourceKey, changed, { const changedDisplay = await materialCache.hydrateSourceImages(sourceKey, changed, {
moduleIds: [101], toolIds: [], isCurrent: () => true moduleIds: [101], toolIds: [], isCurrent: () => true
}) })
await waitForSourceLog()
assert.equal(uni.calls.downloadFile, 5, '图片地址变化后应下载新文件') assert.equal(uni.calls.downloadFile, 5, '图片地址变化后应下载新文件')
assert.equal(uni.calls.removeSavedFile, 3, '新文件成功后应删除旧文件') assert.equal(uni.calls.removeSavedFile, 3, '新文件成功后应删除旧文件')
assert.equal(changedDisplay.moduleList[0].contentPicUrl, '_doc/uniapp_save/material-5.jpg') 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: [] } const withoutImages = { id: 'source-1', moduleList: [], toolList: [] }
await materialCache.cacheMaterialImages(sourceKey, withoutImages) await materialCache.cacheMaterialImages(sourceKey, withoutImages)
...@@ -147,6 +178,13 @@ async function run() { ...@@ -147,6 +178,13 @@ async function run() {
await retryCache.cacheMaterialImages(retryKey, base) await retryCache.cacheMaterialImages(retryKey, base)
assert.equal(uni.calls.downloadFile, 1) assert.equal(uni.calls.downloadFile, 1)
assert.equal(uni.calls.saveFile, 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) await retryCache.cacheMaterialImages(retryKey, base)
assert.equal(uni.calls.downloadFile, 2, '保存失败后再次缓存必须重试下载') assert.equal(uni.calls.downloadFile, 2, '保存失败后再次缓存必须重试下载')
assert.equal(uni.calls.saveFile, 2, '保存失败后再次缓存必须重试保存') assert.equal(uni.calls.saveFile, 2, '保存失败后再次缓存必须重试保存')
...@@ -226,6 +264,75 @@ async function run() { ...@@ -226,6 +264,75 @@ async function run() {
const fullModule = fullScreen.moduleList[0] const fullModule = fullScreen.moduleList[0]
assert.ok([fullModule.thumbnail, fullModule.contentPicUrl, fullModule.receptionSourceDetailList[0].detailUrl] assert.ok([fullModule.thumbnail, fullModule.contentPicUrl, fullModule.receptionSourceDetailList[0].detailUrl]
.every(value => value.startsWith('_doc/uniapp_save/')), '后台补齐时应恢复全部图片') .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') console.log('PASS material file cache')
} }
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!