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},
......
...@@ -70,7 +70,10 @@ ...@@ -70,7 +70,10 @@
</view> </view>
</template> </template>
<view v-if="materialLoading" class="material-loading-mask" @click.stop> <view v-if="materialLoading" class="material-loading-mask" @click.stop>
正在加载车型素材… <view class="material-loading-content">
<view class="material-loading-spinner"></view>
<text>图片加载中…</text>
</view>
</view> </view>
<template v-if="type != 'preview'"> <template v-if="type != 'preview'">
<template v-if="backZindex"> <template v-if="backZindex">
...@@ -609,10 +612,12 @@ export default { ...@@ -609,10 +612,12 @@ export default {
const keepVisible = this.hasVisibleMaterial() const keepVisible = this.hasVisibleMaterial()
this._offlineSource = null this._offlineSource = null
if (!keepVisible) this.offlineReadyId = '' if (!keepVisible) this.offlineReadyId = ''
// 已有图片时代表正在切换车型,立即显示;首次进页面则等真正开始读图时再显示,避免网络探测期间一直遮挡页面。
if (keepVisible) this.startMaterialLoading() if (keepVisible) this.startMaterialLoading()
else this.materialLoading = false else this.materialLoading = false
const requestId = this._sourceRequestId = (this._sourceRequestId || 0) + 1 const requestId = this._sourceRequestId = (this._sourceRequestId || 0) + 1
const isCurrent = () => !!this.id && !this._sourceDisposed && !this._isDestroyed && requestId === this._sourceRequestId const isCurrent = () => !!this.id && !this._sourceDisposed && !this._isDestroyed && requestId === this._sourceRequestId
try {
const { shopMerchantId, sceneType, currentCarInfo } = this, const { shopMerchantId, sceneType, currentCarInfo } = this,
{ carBrandId, carChildsBrandId } = currentCarInfo || {}, { carBrandId, carChildsBrandId } = currentCarInfo || {},
params = { params = {
...@@ -674,6 +679,10 @@ export default { ...@@ -674,6 +679,10 @@ export default {
// 当前请求失败后结束提示,避免弱网下提示一直停留。 // 当前请求失败后结束提示,避免弱网下提示一直停留。
if (isCurrent()) this.finishMaterialLoading() if (isCurrent()) this.finishMaterialLoading()
} }
} finally {
// 无素材、接口异常和图片失败都必须结束 loading;过期请求不能关闭新请求的 loading。
if (isCurrent()) this.finishMaterialLoading()
}
}, },
getSourceTarget (data) { getSourceTarget (data) {
const modules = data.moduleList || [] const modules = data.moduleList || []
...@@ -706,15 +715,18 @@ export default { ...@@ -706,15 +715,18 @@ export default {
async loadOfflineMaterial (materialId = this.id, { deferViewInfo = false, criticalOnly = false } = {}) { async loadOfflineMaterial (materialId = this.id, { deferViewInfo = false, criticalOnly = false } = {}) {
const source = this._offlineSource const source = this._offlineSource
if (!source || !this.id) return if (!source || !this.id) return
// 文件夹切换会直接进入这里;文件读取和 OSS 下载使用同一套 loading 生命周期。
this.startMaterialLoading()
const imageRequestId = this._offlineImageRequestId = (this._offlineImageRequestId || 0) + 1 const imageRequestId = this._offlineImageRequestId = (this._offlineImageRequestId || 0) + 1
const isCurrent = () => this._offlineSource === source && !!this.id && const isCurrent = () => this._offlineSource === source && !!this.id &&
!this._sourceDisposed && source.requestId === this._sourceRequestId && imageRequestId === this._offlineImageRequestId !this._sourceDisposed && source.requestId === this._sourceRequestId && imageRequestId === this._offlineImageRequestId
if (!deferViewInfo) this.offlineReadyId = '' if (!deferViewInfo) this.offlineReadyId = ''
try {
const display = await materialCache.hydrateSourceImages(source.key, source.base, { const display = await materialCache.hydrateSourceImages(source.key, source.base, {
moduleIds: [materialId], toolIds: criticalOnly ? [] : [materialId], carKey: source.carKey, isCurrent, moduleIds: [materialId], toolIds: criticalOnly ? [] : [materialId], carKey: source.carKey, isCurrent,
maxImages: criticalOnly ? 1 : undefined, maxImages: criticalOnly ? 1 : undefined,
hideUnloadedImages: criticalOnly, hideUnloadedImages: criticalOnly,
// 在线时缺失的图片按需补齐,避免渲染出原始 URL。 // 在线时缺失的图片按需补齐,避免组件绕过缓存直接读取 OSS。
allowDownload: source.online !== false, allowDownload: source.online !== false,
onMetrics: metrics => { if (isCurrent()) console.log('setPageData images', { materialId, carKey: source.carKey, ...metrics }) } onMetrics: metrics => { if (isCurrent()) console.log('setPageData images', { materialId, carKey: source.carKey, ...metrics }) }
}) })
...@@ -726,10 +738,15 @@ export default { ...@@ -726,10 +738,15 @@ export default {
} else this.moduleList = Object.freeze(display.moduleList) } else this.moduleList = Object.freeze(display.moduleList)
this.applyOfflineTools(display.toolList) this.applyOfflineTools(display.toolList)
this.offlineReadyId = materialId this.offlineReadyId = materialId
this.finishMaterialLoading()
if (criticalOnly) this.loadRemainingOfflineMaterial(materialId, source, imageRequestId) if (criticalOnly) this.loadRemainingOfflineMaterial(materialId, source, imageRequestId)
// 文件夹已打开时才需要补齐工具图标,不占用当前素材的首图读取。 // 文件夹已打开时才需要补齐工具图标,不占用当前素材的首图读取。
if (this.$refs.toolRef?.show === false) this.loadOfflineTools(true) if (this.$refs.toolRef?.show === false) this.loadOfflineTools(true)
} catch (error) {
if (isCurrent()) console.warn('当前素材图片加载失败', error?.message || error)
} finally {
// 当前图片无论来自文件还是 OSS,读取成功或失败后都结束 loading。
if (isCurrent()) this.finishMaterialLoading()
}
}, },
async loadRemainingOfflineMaterial (materialId, source, imageRequestId) { async loadRemainingOfflineMaterial (materialId, source, imageRequestId) {
const isCurrent = () => this._offlineSource === source && !!this.id && const isCurrent = () => this._offlineSource === source && !!this.id &&
...@@ -948,16 +965,38 @@ export default { ...@@ -948,16 +965,38 @@ export default {
} }
.material-loading-mask { .material-loading-mask {
position: fixed; position: fixed;
left: 50%; left: 0;
top: toRpx(64); right: 0;
transform: translateX(-50%); top: 0;
z-index: 12; bottom: 0;
padding: toRpx(12) toRpx(28); z-index: 999;
border-radius: toRpx(32); display: flex;
align-items: center;
justify-content: center;
background: rgba(0, 0, 0, 0.12);
.material-loading-content {
display: flex;
align-items: center;
padding: toRpx(20) toRpx(32);
border-radius: toRpx(16);
color: #ffffff; color: #ffffff;
font-size: toRpx(26); font-size: toRpx(28);
line-height: toRpx(36); line-height: toRpx(40);
background: rgba(0, 0, 0, 0.56); background: rgba(0, 0, 0, 0.68);
}
.material-loading-spinner {
width: toRpx(32);
height: toRpx(32);
margin-right: toRpx(16);
border: toRpx(4) solid rgba(255, 255, 255, 0.35);
border-top-color: #ffffff;
border-radius: 50%;
animation: material-loading-rotate 0.8s linear infinite;
}
}
@keyframes material-loading-rotate {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
} }
.pen-box { .pen-box {
position: fixed; position: fixed;
......
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!