Commit e6bd1afe by chenwq

fix(materialCache): 修复素材文件被系统清理后未自动重新下载的问题

App端可能因系统清理导致本地保存的素材文件丢失,但缓存中仍保留失效路径。
新增 savedFileExists 函数,通过 plus.io 或 uni.getFileInfo 校验文件是否真实存在。
在内存读取、异步读取和后台缓存环节校验本地文件,若不存在则清除记录并触发重新下载。
补充相关单元测试,验证文件丢失后的在线读取与后台缓存自动修复逻辑。
1 parent dba9f2b3
......@@ -2,8 +2,9 @@ const assert = require('assert')
function createUni(options = {}) {
const storage = new Map()
const calls = { downloadFile: 0, saveFile: 0, removeSavedFile: 0, request: 0, arrayBufferToBase64: 0 }
const calls = { downloadFile: 0, saveFile: 0, removeSavedFile: 0, getFileInfo: 0, request: 0, arrayBufferToBase64: 0 }
const pendingDownloads = []
const savedFiles = new Set()
let savedIndex = 0
const api = {
calls,
......@@ -35,10 +36,18 @@ function createUni(options = {}) {
return
}
savedIndex++
success({ savedFilePath: `_doc/uniapp_save/material-${savedIndex}.jpg`, tempFilePath })
const savedFilePath = `_doc/uniapp_save/material-${savedIndex}.jpg`
savedFiles.add(savedFilePath)
success({ savedFilePath, tempFilePath })
},
removeSavedFile({ success }) {
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() {
......@@ -51,6 +60,7 @@ function createUni(options = {}) {
}
}
api.releaseDownloads = () => pendingDownloads.splice(0).forEach(complete => complete())
api.removeSavedFileFromSystem = filePath => savedFiles.delete(filePath)
return api
}
......@@ -84,13 +94,36 @@ async function run() {
await materialCache.cacheMaterialImages(sourceKey, base)
assert.equal(uni.calls.downloadFile, 1, '同一地址再次缓存应复用已保存文件')
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')
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, 2, '文件路径记录丢失后应重新下载修复')
assert.equal(uni.calls.removeSavedFile, 1, '修复成功后应清理旧文件')
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'
......@@ -98,13 +131,13 @@ async function run() {
const changedDisplay = await materialCache.hydrateSourceImages(sourceKey, changed, {
moduleIds: [101], toolIds: [], isCurrent: () => true
})
assert.equal(uni.calls.downloadFile, 3, '图片地址变化后应下载新文件')
assert.equal(uni.calls.removeSavedFile, 2, '新文件成功后应删除旧文件')
assert.equal(changedDisplay.moduleList[0].contentPicUrl, '_doc/uniapp_save/material-3.jpg')
assert.equal(uni.calls.downloadFile, 5, '图片地址变化后应下载新文件')
assert.equal(uni.calls.removeSavedFile, 3, '新文件成功后应删除旧文件')
assert.equal(changedDisplay.moduleList[0].contentPicUrl, '_doc/uniapp_save/material-5.jpg')
const withoutImages = { id: 'source-1', moduleList: [], toolList: [] }
await materialCache.cacheMaterialImages(sourceKey, withoutImages)
assert.equal(uni.calls.removeSavedFile, 3, '接口删除图片后应清理不再使用的文件')
assert.equal(uni.calls.removeSavedFile, 4, '接口删除图片后应清理不再使用的文件')
const failOptions = { failSaveCount: 1 }
global.uni = createUni(failOptions)
......
......@@ -81,6 +81,27 @@ function removeSavedFile(filePath) {
})
}
// 文件路径记录不等于文件仍存在:App 可能因系统清理而丢失保存的素材文件。
function savedFileExists(filePath) {
if (!isLocalImage(filePath)) return Promise.resolve(false)
if (typeof plus !== 'undefined' && plus.io?.resolveLocalFileSystemURL) {
return new Promise(resolve => {
try {
plus.io.resolveLocalFileSystemURL(filePath, () => resolve(true), () => resolve(false))
} catch (error) {
resolve(false)
}
})
}
if (typeof uni.getFileInfo === 'function') {
return new Promise(resolve => {
uni.getFileInfo({ filePath, success: () => resolve(true), fail: () => resolve(false) })
})
}
// 不支持文件查询的运行环境沿用路径缓存,避免影响非 App 端原有行为。
return Promise.resolve(true)
}
function forgetImage(key) {
const cached = imageMemory.get(key)
if (cached) imageMemoryBytes -= cached.length * 2
......@@ -136,10 +157,15 @@ function drainImageReads() {
if (job.invalidated) { retryInvalidatedRead(job); continue }
activeImageReads++
subscribers[0].metrics.storageReads++
read(job.key).catch(() => null).then(value => {
read(job.key).catch(() => null).then(async value => {
if (pendingImageReads.get(job.key) === job) pendingImageReads.delete(job.key)
if (job.invalidated) { retryInvalidatedRead(job); return }
const image = isLocalImage(value) ? value : null
let image = isLocalImage(value) ? value : null
if (image && !await savedFileExists(image)) {
image = null
// 删除无效路径,后续在线读取和后台缓存都可重新下载。
await remove(job.key)
}
if (image && job.epoch === imageMemoryEpoch && job.subscribers.some(subscriber => subscriber.isCurrent())) {
rememberImage(job.key, image)
}
......@@ -156,10 +182,16 @@ function readImage(key, isCurrent, metrics) {
if (!isCurrent()) return Promise.resolve(null)
const image = imageMemory.get(key)
if (image) {
imageMemory.delete(key)
imageMemory.set(key, image)
metrics.memoryHits++
return Promise.resolve(image)
return savedFileExists(image).then(exists => {
if (!exists) {
forgetImage(key)
return null
}
imageMemory.delete(key)
imageMemory.set(key, image)
metrics.memoryHits++
return image
})
}
return new Promise(resolve => {
let job = pendingImageReads.get(key)
......@@ -478,13 +510,15 @@ async function cacheMaterialImages(key, base) {
const target = imageKey(key, id, slot.key)
const previous = urls[slotName]
const storedPath = await read(target)
const storedFilePath = isLocalImage(storedPath) && await savedFileExists(storedPath) ? storedPath : ''
if (isLocalImage(storedPath) && !storedFilePath) await remove(target)
const recorded = previous && previous.url === slot.url && previous.key === target &&
isLocalImage(previous.path) && storedPath === previous.path
isLocalImage(previous.path) && storedFilePath === previous.path
// 同一素材位置上 URL 与已保存文件一致时,跳过重复下载。
if (recorded || isLocalImage(storedPath)) {
if (recorded || storedFilePath) {
// 首屏补齐过的位置补记到 storage,下次冷启动同样能跳过。
if (!recorded) {
urls[slotName] = { url: slot.url, path: storedPath, key: target }
urls[slotName] = { url: slot.url, path: storedFilePath, key: target }
urlsChanged = true
}
return true
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!