fix(materials): clean up unreferenced replaced ZIPs
This commit is contained in:
parent
fc8e53a0fa
commit
318c8da1f4
@ -2,7 +2,7 @@
|
||||
|
||||
import { execFile } from 'child_process'
|
||||
import { writeFileSync } from 'fs'
|
||||
import { mkdtemp, rm, writeFile } from 'fs/promises'
|
||||
import { access, mkdir, mkdtemp, readFile, rm, writeFile } from 'fs/promises'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import sharp from 'sharp'
|
||||
@ -10,7 +10,10 @@ import sharp from 'sharp'
|
||||
jest.mock('child_process', () => ({ ...jest.requireActual('child_process'), execFile: jest.fn() }))
|
||||
jest.mock('@/lib/material-authorization', () => ({ canManageMaterial: jest.fn() }))
|
||||
jest.mock('@/lib/material-log', () => ({ createMaterialLog: jest.fn().mockResolvedValue(undefined) }))
|
||||
jest.mock('@/lib/file-cleanup', () => ({ deleteFileIfUnreferenced: jest.fn().mockResolvedValue({ success: true }) }))
|
||||
jest.mock('@/lib/file-cleanup', () => ({
|
||||
...jest.requireActual('@/lib/file-cleanup'),
|
||||
deleteFileIfUnreferenced: jest.fn().mockResolvedValue({ success: true }),
|
||||
}))
|
||||
jest.mock('@/lib/material-upload-cross-process-lock', () => ({ acquireTaskMaterialCompletionLock: jest.fn() }))
|
||||
jest.mock('@/lib/material-type-mapper', () => ({ isProductPackageType: jest.fn(() => true) }))
|
||||
jest.mock('@/lib/task-detail-full-set', () => ({ deriveTaskDetailIsFullSet: jest.fn(() => false) }))
|
||||
@ -42,7 +45,10 @@ jest.mock('@/lib/zip-entry-reader', () => ({
|
||||
extractZipEntriesToDirectory: jest.fn(),
|
||||
listZipEntries: jest.fn(),
|
||||
}))
|
||||
jest.mock('@/lib/upload-paths', () => ({ resolveStoredUploadPath: jest.fn((value: string) => value) }))
|
||||
jest.mock('@/lib/upload-paths', () => ({
|
||||
...jest.requireActual('@/lib/upload-paths'),
|
||||
resolveStoredUploadPath: jest.fn((value: string) => value),
|
||||
}))
|
||||
jest.mock('@/lib/prisma', () => ({
|
||||
prisma: {
|
||||
user: { findUnique: jest.fn().mockResolvedValue({ isSuperAdmin: false }) },
|
||||
@ -66,6 +72,7 @@ jest.mock('@/lib/prisma', () => ({
|
||||
taskDetailChangeRequest: {
|
||||
updateMany: jest.fn(),
|
||||
},
|
||||
$queryRaw: jest.fn(),
|
||||
$transaction: jest.fn(),
|
||||
},
|
||||
}))
|
||||
@ -76,6 +83,7 @@ import { queueTaskDetailBarcodeImagesUpdatedNotification } from '@/lib/external-
|
||||
import { acquireTaskMaterialCompletionLock } from '@/lib/material-upload-cross-process-lock'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { uploadPublicDisplayToS3 } from '@/lib/public-display'
|
||||
import { deleteStoredUploadFileFromRemote } from '@/lib/remote-upload-sync'
|
||||
import {
|
||||
canUserAccessPrivateTaskDetail,
|
||||
canUserEditTaskDetailAssets,
|
||||
@ -98,6 +106,8 @@ const mockUploadPreview = uploadPublicDisplayToS3 as jest.Mock
|
||||
const mockCreateZipFromFiles = createZipFromFiles as jest.Mock
|
||||
const mockCreateZipFromZips = createZipFromZips as jest.Mock
|
||||
const mockCleanupConsumedUploadSession = cleanupConsumedUploadSession as jest.Mock
|
||||
const mockDeleteRemoteArchive = deleteStoredUploadFileFromRemote as jest.Mock
|
||||
const mockReferenceQuery = prisma.$queryRaw as unknown as jest.Mock
|
||||
const mockGetOwnedUploadSession = getOwnedUploadSession as jest.Mock
|
||||
const mockGetUploadedFile = getUploadedFile as jest.Mock
|
||||
const mockCreateWorkspace = createTaskDetailEditWorkspace as jest.Mock
|
||||
@ -133,10 +143,14 @@ const material = {
|
||||
|
||||
describe('task-detail asset edit batch data-plane', () => {
|
||||
let tempRoot: string
|
||||
let previousUploadRoot: string | undefined
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.clearAllMocks()
|
||||
tempRoot = await mkdtemp(path.join(os.tmpdir(), 'task-detail-batch-'))
|
||||
previousUploadRoot = process.env.UPLOAD_DIR
|
||||
process.env.UPLOAD_DIR = tempRoot
|
||||
mockReferenceQuery.mockReset().mockResolvedValue([])
|
||||
|
||||
mockCanManageMaterial.mockResolvedValue(true)
|
||||
mockCanAccessPrivateTaskDetail.mockResolvedValue(false)
|
||||
@ -182,6 +196,8 @@ describe('task-detail asset edit batch data-plane', () => {
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
if (previousUploadRoot === undefined) delete process.env.UPLOAD_DIR
|
||||
else process.env.UPLOAD_DIR = previousUploadRoot
|
||||
await rm(tempRoot, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
@ -432,9 +448,31 @@ describe('task-detail asset edit batch data-plane', () => {
|
||||
}
|
||||
})
|
||||
|
||||
test.each([false, true])('已获取素材替换三张 SKU 图:总包重建失败=%s,正式版本整体切换', async (rebuildFails) => {
|
||||
test.each([
|
||||
{ label: '新包生效', rebuildFails: false, commitFails: false, sharedAll: false },
|
||||
{ label: '旧总包仍被引用', rebuildFails: false, commitFails: false, sharedAll: true },
|
||||
{ label: '总包重建失败', rebuildFails: true, commitFails: false, sharedAll: false },
|
||||
{ label: '审批事务未提交', rebuildFails: false, commitFails: true, sharedAll: false },
|
||||
])('已获取素材替换三张 SKU 图:$label', async ({ rebuildFails, commitFails, sharedAll }) => {
|
||||
const fetchedAt = new Date('2026-09-22T09:54:50.875Z')
|
||||
;(prisma.material.findFirst as jest.Mock).mockResolvedValue({ ...material, taskStatus: 'fetched', taskFetchedAt: fetchedAt })
|
||||
;(prisma.material.findFirst as jest.Mock).mockResolvedValue({
|
||||
...material, taskStatus: 'fetched', taskFetchedAt: fetchedAt, zipFilePath: '/uploads/materials/all-old.zip',
|
||||
})
|
||||
const archiveDir = path.join(tempRoot, 'materials')
|
||||
const archivePath = (name: string) => path.join(archiveDir, name)
|
||||
await mkdir(archiveDir)
|
||||
for (const name of ['main-old.zip', 'sku-old.zip', 'detail-old.zip', 'all-old.zip', 'sku-new.zip', 'all-new.zip']) {
|
||||
await writeFile(archivePath(name), name)
|
||||
}
|
||||
if (sharedAll) {
|
||||
mockReferenceQuery.mockResolvedValue([{ sources: [archivePath('all-old.zip')], derived: false }])
|
||||
}
|
||||
if (commitFails) {
|
||||
;(prisma.$transaction as jest.Mock).mockImplementationOnce(async (callback) => {
|
||||
await callback(prisma)
|
||||
throw new Error('审批事务未提交')
|
||||
})
|
||||
}
|
||||
const images = await Promise.all([1, 2, 3].map(async (index) => ({
|
||||
id: `sku-${index}`, name: `sku-${index}.png`,
|
||||
source: await createSolidImage(`sku-${index}.png`, 80, 80),
|
||||
@ -468,16 +506,32 @@ describe('task-detail asset edit batch data-plane', () => {
|
||||
materialId: 'material-1', operatorUserId: 'operator-1', approvalRequestId: 'request-atomic',
|
||||
operations: images.map(({ id }, index) => ({ kind: 'replace', assetId: id, uploadId: `upload-${index}` })),
|
||||
})
|
||||
if (rebuildFails) {
|
||||
await expect(editing).rejects.toThrow('总包重建失败')
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled()
|
||||
expect(prisma.material.update).not.toHaveBeenCalled()
|
||||
expect(prisma.materialAsset.update).not.toHaveBeenCalled()
|
||||
if (rebuildFails || commitFails) {
|
||||
await expect(editing).rejects.toThrow(rebuildFails ? '总包重建失败' : '审批事务未提交')
|
||||
if (rebuildFails) {
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled()
|
||||
expect(prisma.material.update).not.toHaveBeenCalled()
|
||||
expect(prisma.materialAsset.update).not.toHaveBeenCalled()
|
||||
}
|
||||
expect(mockReferenceQuery).not.toHaveBeenCalled()
|
||||
for (const name of ['sku-old.zip', 'all-old.zip']) {
|
||||
await expect(readFile(archivePath(name), 'utf8')).resolves.toBe(name)
|
||||
expect(mockDeleteRemoteArchive).not.toHaveBeenCalledWith('uploads/materials/' + name)
|
||||
}
|
||||
expect(mockQueueSkuNotification).not.toHaveBeenCalled()
|
||||
expect(mockCleanupConsumedUploadSession).not.toHaveBeenCalled()
|
||||
return
|
||||
}
|
||||
await expect(editing).resolves.toMatchObject({ success: true, appliedCount: 3, entryCount: 3 })
|
||||
await expect(access(archivePath('sku-old.zip'))).rejects.toMatchObject({ code: 'ENOENT' })
|
||||
if (sharedAll) await expect(readFile(archivePath('all-old.zip'), 'utf8')).resolves.toBe('all-old.zip')
|
||||
else await expect(access(archivePath('all-old.zip'))).rejects.toMatchObject({ code: 'ENOENT' })
|
||||
for (const name of ['main-old.zip', 'detail-old.zip', 'sku-new.zip', 'all-new.zip']) {
|
||||
await expect(readFile(archivePath(name), 'utf8')).resolves.toBe(name)
|
||||
}
|
||||
expect(mockDeleteRemoteArchive.mock.calls.flat().sort()).toEqual(
|
||||
sharedAll ? ['uploads/materials/sku-old.zip'] : ['uploads/materials/all-old.zip', 'uploads/materials/sku-old.zip'],
|
||||
)
|
||||
const rebuiltImages = mockCreateZipFromFiles.mock.calls[0][0] as Array<{ path: string; name: string }>
|
||||
for (const image of images) {
|
||||
expect(rebuiltImages).toContainEqual(expect.objectContaining({ name: image.name, path: image.replacement.filePath }))
|
||||
|
||||
@ -5,7 +5,8 @@ import {
|
||||
canManageMaterial,
|
||||
} from '@/lib/material-authorization'
|
||||
import { createMaterialLog } from '@/lib/material-log'
|
||||
import { deleteFileIfUnreferenced } from '@/lib/file-cleanup'
|
||||
import { deleteFileIfUnreferenced, deleteLocalFile } from '@/lib/file-cleanup'
|
||||
import { findPurgeFileReferences, identifyPurgeFile, purgeFileIdentity, type PurgeFile } from '@/lib/material-purge-files'
|
||||
import {
|
||||
acquireTaskMaterialCompletionLock,
|
||||
} from '@/lib/material-upload-cross-process-lock'
|
||||
@ -35,7 +36,7 @@ import {
|
||||
extractZipEntriesToDirectory,
|
||||
listZipEntries,
|
||||
} from '@/lib/zip-entry-reader'
|
||||
import { resolveStoredUploadPath } from '@/lib/upload-paths'
|
||||
import { buildStoredUploadPath, resolveStoredUploadPath } from '@/lib/upload-paths'
|
||||
import { execFile } from 'child_process'
|
||||
import { readFile, stat, writeFile } from 'fs/promises'
|
||||
import path from 'path'
|
||||
@ -123,6 +124,7 @@ interface EditContext {
|
||||
authorName: string | null
|
||||
categoryName: string | null
|
||||
currentPreviewUrl: string | null
|
||||
currentZipFilePath: string
|
||||
wasFullSet: boolean
|
||||
operatorUserId: string
|
||||
approvalRequestId?: string
|
||||
@ -593,6 +595,7 @@ async function loadEditContext(options: {
|
||||
authorName: true,
|
||||
categoryName: true,
|
||||
previewUrl: true,
|
||||
zipFilePath: true,
|
||||
isFullSet: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
@ -707,6 +710,7 @@ async function loadEditContext(options: {
|
||||
authorName: material.authorName,
|
||||
categoryName: material.categoryName,
|
||||
currentPreviewUrl: material.previewUrl,
|
||||
currentZipFilePath: material.zipFilePath,
|
||||
wasFullSet: Boolean(material.isFullSet),
|
||||
operatorUserId: options.operatorUserId,
|
||||
approvalRequestId: options.approvalRequestId,
|
||||
@ -795,6 +799,7 @@ async function loadEditContext(options: {
|
||||
authorName: material.authorName,
|
||||
categoryName: material.categoryName,
|
||||
currentPreviewUrl: material.previewUrl,
|
||||
currentZipFilePath: material.zipFilePath,
|
||||
wasFullSet: Boolean(material.isFullSet),
|
||||
operatorUserId: options.operatorUserId,
|
||||
approvalRequestId: options.approvalRequestId,
|
||||
@ -2704,18 +2709,47 @@ async function commitRebuild(
|
||||
return { nextIsFullSet }
|
||||
}
|
||||
|
||||
async function cleanupReplacedZipFiles(storedPaths: string[]) {
|
||||
const files = new Map<string, PurgeFile>()
|
||||
for (const storedPath of storedPaths) {
|
||||
try {
|
||||
const file = identifyPurgeFile(storedPath)
|
||||
if (file?.storage !== 'local' || !file.key.toLowerCase().endsWith('.zip')) continue
|
||||
files.set(purgeFileIdentity(file), { ...file, outcome: 'pending' })
|
||||
} catch (error) {
|
||||
console.warn('[task-detail-asset-edit] 无法识别旧压缩包路径:', storedPath, error)
|
||||
}
|
||||
}
|
||||
|
||||
// 回收站中的素材仍可恢复,也会保留对 ZIP 的引用。
|
||||
const references = await findPurgeFileReferences(prisma, Array.from(files.values()))
|
||||
await Promise.all(Array.from(files, async ([identity, file]) => {
|
||||
if (references.has(identity)) return
|
||||
const storedPath = buildStoredUploadPath(file.key)
|
||||
try {
|
||||
const removed = await deleteLocalFile(storedPath)
|
||||
if (!removed.success) throw new Error(removed.error || '本地旧压缩包清理失败')
|
||||
await deleteStoredUploadFileFromRemote(storedPath)
|
||||
} catch (error) {
|
||||
console.warn('[task-detail-asset-edit] 旧压缩包清理失败:', storedPath, error)
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
async function cleanupAfterCommit(rebuilds: GroupRebuild[], newAllZip: RebuiltZip | null) {
|
||||
const { context } = rebuilds[0]
|
||||
const staleStoredPaths = rebuilds.flatMap((item) => {
|
||||
const zip = context.groupZipAssets[item.context.group]
|
||||
return zip && zip.fileUrl !== item.newGroupZip?.filePath ? [zip.fileUrl] : []
|
||||
})
|
||||
if (context.allZipAsset && context.allZipAsset.fileUrl !== newAllZip?.filePath) {
|
||||
staleStoredPaths.push(context.allZipAsset.fileUrl)
|
||||
for (const previousPath of [context.allZipAsset?.fileUrl, context.currentZipFilePath]) {
|
||||
if (previousPath && previousPath !== newAllZip?.filePath) staleStoredPaths.push(previousPath)
|
||||
}
|
||||
|
||||
await Promise.allSettled([
|
||||
...staleStoredPaths.map((storedPath) => deleteStoredUploadFileFromRemote(storedPath)),
|
||||
cleanupReplacedZipFiles(staleStoredPaths).catch((error) => {
|
||||
console.warn('[task-detail-asset-edit] 旧压缩包引用检查失败:', error)
|
||||
}),
|
||||
...rebuilds.flatMap((item) => item.db.removedPreviewUrls.map(({ url }) =>
|
||||
deleteFileIfUnreferenced(url, { excludeMaterialIds: [context.materialId] }),
|
||||
)),
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user