diff --git a/furniture-3d-system/.gitignore b/furniture-3d-system/.gitignore index 4801205e..1002fe45 100644 --- a/furniture-3d-system/.gitignore +++ b/furniture-3d-system/.gitignore @@ -44,6 +44,7 @@ next-env.d.ts /src/generated/prisma .database-backups/ .master-data-audits/ +.storage-migration-audits/ .master-data-cleanup/ # local workspace artifacts diff --git a/furniture-3d-system/package.json b/furniture-3d-system/package.json index 0f0bc724..526ec923 100644 --- a/furniture-3d-system/package.json +++ b/furniture-3d-system/package.json @@ -26,6 +26,8 @@ "open-platform:seed": "tsx scripts/seed-open-platform-demo.ts", "type-check": "node scripts/run-type-check.js", "storage:verify-config": "tsx scripts/verify-object-storage-config.ts", + "storage:migrate-historical-assets": "tsx scripts/migrate-historical-assets-to-qiniu.ts", + "storage:migrate-historical-assets:apply": "tsx scripts/migrate-historical-assets-to-qiniu.ts --apply", "demo:create": "node scripts/create-demo-data.js", "demo:setup": "npm run prisma:push && npm run demo:create", "demo:update": "node scripts/update-demo-models.js", diff --git a/furniture-3d-system/scripts/migrate-historical-assets-to-qiniu.ts b/furniture-3d-system/scripts/migrate-historical-assets-to-qiniu.ts new file mode 100644 index 00000000..7eb47796 --- /dev/null +++ b/furniture-3d-system/scripts/migrate-historical-assets-to-qiniu.ts @@ -0,0 +1,1115 @@ +import { loadEnvConfig } from '@next/env' +import { createHash } from 'node:crypto' +import { mkdir, readFile, stat, writeFile } from 'node:fs/promises' +import fs from 'node:fs' +import path from 'node:path' + +type PrismaSingleton = typeof import('../src/lib/prisma')['prisma'] +type StorageModule = typeof import('../src/lib/storage') + +type LegacyReferenceKind = 'legacy-s3' | 'non-integrated-asset' | 'material-texture' +type SourceType = 'http' | 'local' +type RecordType = 'AssetVariant' | 'Material' | 'IntakeNonIntegratedProduct' | 'AssetSkuSyncEvent' + +const NON_INTEGRATED_RUNTIME_ASSET_PREFIX = '/api/intake/non-integrated/assets' +const NON_INTEGRATED_LEGACY_ASSET_PREFIX = '/non-integrated-test-assets' +const DEFAULT_LEGACY_S3_HOSTS = ['s3.jiansun.vip', '192.168.58.20'] +const AUDIT_DIR = '.storage-migration-audits' + +let prisma: PrismaSingleton | null = null + +export interface LegacyReferencePlan { + kind: LegacyReferenceKind + oldValue: string + targetKey: string + source: { + type: SourceType + url?: string + filePath?: string + } + contentType: string + notes: string[] +} + +interface CliOptions { + apply: boolean + includeDeleted: boolean + includeEventSnapshots: boolean + skipSourceCheck: boolean + forceUpload: boolean + limit: number | null + concurrency: number + batchSize: number + auditDir: string +} + +interface MigrationReference extends LegacyReferencePlan { + id: string + recordType: RecordType + recordId: string + label: string + fieldPath: string + directField?: string + canApply: boolean + targetObjectKey?: string + targetUrl?: string +} + +interface ObjectTask { + targetKey: string + targetObjectKey: string + targetUrl: string + kind: LegacyReferenceKind + source: LegacyReferencePlan['source'] + contentType: string + oldValues: string[] + references: string[] + notes: string[] + sourceCheck?: SourceCheckResult + targetExistsBefore?: boolean | null + uploadStatus?: 'dry-run' | 'skipped-existing' | 'uploaded' | 'failed' + verified?: boolean + error?: string + bytes?: number + sha256?: string +} + +interface SourceCheckResult { + checked: boolean + exists: boolean + size: number | null + contentType: string | null + error?: string +} + +interface AuditReport { + schema: 'qiniu_historical_assets_migration_audit' + schemaVersion: '2026-06-03.v1' + startedAt: string + finishedAt?: string + mode: 'dry-run' | 'apply' + status: 'running' | 'completed' | 'failed' + options: CliOptions + database: { + identity: string | null + } + storage?: { + provider: string + accessMode: string + bucketName: string + filePathPrefix: string + publicEndpoint: string + } + counts: Record + warnings: string[] + references: MigrationReference[] + objects: ObjectTask[] + recordSnapshots: Array<{ + recordType: RecordType + recordId: string + label: string + original: unknown + }> + updates: Array<{ + recordType: RecordType + recordId: string + fields: string[] + applied: boolean + reason?: string + }> + error?: string +} + +function readFlag(name: string): boolean { + return process.argv.includes(name) +} + +function readOption(name: string): string | null { + const direct = process.argv.find((arg) => arg.startsWith(`${name}=`)) + if (direct) return direct.slice(name.length + 1).trim() || null + + const index = process.argv.findIndex((arg) => arg === name) + if (index >= 0) { + const next = process.argv[index + 1] + if (next && !next.startsWith('--')) return next.trim() || null + } + + return null +} + +function parsePositiveInteger(value: string | null, fallback: number): number { + const parsed = value ? Number(value) : fallback + return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : fallback +} + +function resolveOptions(): CliOptions { + const limitInput = readOption('--limit') + const limit = limitInput ? parsePositiveInteger(limitInput, 0) : null + + return { + apply: readFlag('--apply'), + includeDeleted: readFlag('--include-deleted'), + includeEventSnapshots: readFlag('--include-event-snapshots'), + skipSourceCheck: readFlag('--skip-source-check'), + forceUpload: readFlag('--force-upload'), + limit, + concurrency: parsePositiveInteger(readOption('--concurrency'), 3), + batchSize: parsePositiveInteger(readOption('--batch-size'), 25), + auditDir: readOption('--audit-dir') || AUDIT_DIR, + } +} + +function normalizeUrlPath(value: string): string { + try { + return decodeURIComponent(value) + } catch { + return value + } +} + +function stripHashAndQuery(value: string): string { + return value.split('#', 1)[0]?.split('?', 1)[0] ?? '' +} + +function extractPathname(value: string): string { + const normalized = value.trim() + if (!normalized) return '' + if (/^https?:\/\//i.test(normalized)) { + try { + return new URL(normalized).pathname + } catch { + return normalized + } + } + return normalized +} + +function normalizeRelativeKey(value: string): string { + return value + .trim() + .replace(/\\/g, '/') + .replace(/^\/+/, '') + .split('/') + .filter((part) => part && part !== '.' && part !== '..') + .join('/') +} + +function contentTypeFromPath(value: string): string { + const extension = path.extname(value).toLowerCase() + const map: Record = { + '.glb': 'model/gltf-binary', + '.gltf': 'model/gltf+json', + '.obj': 'model/obj', + '.mtl': 'text/plain', + '.fbx': 'application/octet-stream', + '.stl': 'model/stl', + '.png': 'image/png', + '.jpg': 'image/jpeg', + '.jpeg': 'image/jpeg', + '.webp': 'image/webp', + '.gif': 'image/gif', + '.svg': 'image/svg+xml', + '.pdf': 'application/pdf', + '.ppt': 'application/vnd.ms-powerpoint', + '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + '.xls': 'application/vnd.ms-excel', + '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + '.zip': 'application/zip', + '.rar': 'application/vnd.rar', + '.7z': 'application/x-7z-compressed', + '.mp4': 'video/mp4', + '.mov': 'video/quicktime', + } + return map[extension] || 'application/octet-stream' +} + +function legacyS3Hosts(): string[] { + const configured = process.env.LEGACY_S3_HOSTS + ?.split(',') + .map((item) => item.trim().toLowerCase()) + .filter(Boolean) + + return configured && configured.length > 0 ? configured : DEFAULT_LEGACY_S3_HOSTS +} + +function isLegacyS3Url(value: string): boolean { + if (!/^https?:\/\//i.test(value)) return false + try { + const parsed = new URL(value) + const host = parsed.hostname.toLowerCase() + return legacyS3Hosts().some((candidate) => host === candidate || host.endsWith(`.${candidate}`)) + } catch { + return false + } +} + +function buildLegacyS3TargetPath(value: string): string { + const parsed = new URL(value) + let relativePath = normalizeRelativeKey(normalizeUrlPath(parsed.pathname)) + const marker = 'furniture-3d-system/' + const markerIndex = relativePath.indexOf(marker) + if (markerIndex >= 0) { + relativePath = relativePath.slice(markerIndex + marker.length) + } + return `migrated/s3/${relativePath}` +} + +function extractNonIntegratedRelativePath(value: string): string { + const pathname = normalizeUrlPath(stripHashAndQuery(extractPathname(value))) + if (pathname.startsWith(`${NON_INTEGRATED_RUNTIME_ASSET_PREFIX}/`)) { + return normalizeRelativeKey(pathname.slice(NON_INTEGRATED_RUNTIME_ASSET_PREFIX.length + 1)) + } + if (pathname.startsWith(`${NON_INTEGRATED_LEGACY_ASSET_PREFIX}/`)) { + return normalizeRelativeKey(pathname.slice(NON_INTEGRATED_LEGACY_ASSET_PREFIX.length + 1)) + } + return '' +} + +function resolveNonIntegratedLocalFile(relativePath: string, cwd: string): string { + const configuredBase = process.env.NON_INTEGRATED_ASSET_DIR?.trim() + const privateBase = configuredBase + ? path.resolve(configuredBase) + : path.join(cwd, '.data', 'non-integrated-assets') + const privatePath = path.resolve(privateBase, relativePath) + if (privatePath.startsWith(privateBase) && fs.existsSync(privatePath)) { + return privatePath + } + + const publicBase = path.join(cwd, 'public', 'non-integrated-test-assets') + return path.resolve(publicBase, relativePath) +} + +function buildMaterialTexturePlan(value: string, cwd: string): LegacyReferencePlan | null { + const pathname = normalizeUrlPath(stripHashAndQuery(extractPathname(value))) + const relativePath = normalizeRelativeKey(pathname) + if (!relativePath.startsWith('materials/textures/')) return null + + return { + kind: 'material-texture', + oldValue: value, + targetKey: relativePath, + source: { + type: 'local', + filePath: path.join(cwd, 'public', ...relativePath.split('/')), + }, + contentType: contentTypeFromPath(relativePath), + notes: [], + } +} + +export function classifyLegacyReference(value: string, cwd = process.cwd()): LegacyReferencePlan | null { + const normalized = value.trim() + if (!normalized) return null + if (normalized.startsWith('/api/storage/object')) return null + + if (isLegacyS3Url(normalized)) { + const targetKey = buildLegacyS3TargetPath(normalized) + return { + kind: 'legacy-s3', + oldValue: normalized, + targetKey, + source: { type: 'http', url: normalized }, + contentType: contentTypeFromPath(targetKey), + notes: [], + } + } + + const nonIntegratedRelativePath = extractNonIntegratedRelativePath(normalized) + if (nonIntegratedRelativePath) { + const segments = nonIntegratedRelativePath.split('/').filter(Boolean) + const notes = + segments.length < 3 + ? ['非集成附件相对路径不足 3 段,迁移后只能走登录态对象代理,无法按产品和分类做精确校验。'] + : [] + + return { + kind: 'non-integrated-asset', + oldValue: normalized, + targetKey: `non-integrated-assets/${nonIntegratedRelativePath}`, + source: { + type: 'local', + filePath: resolveNonIntegratedLocalFile(nonIntegratedRelativePath, cwd), + }, + contentType: contentTypeFromPath(nonIntegratedRelativePath), + notes, + } + } + + return buildMaterialTexturePlan(normalized, cwd) +} + +function referenceId(recordType: RecordType, recordId: string, fieldPath: string, oldValue: string): string { + return createHash('sha1') + .update(`${recordType}:${recordId}:${fieldPath}:${oldValue}`) + .digest('hex') +} + +function collectJsonReferences( + input: unknown, + context: { + recordType: RecordType + recordId: string + label: string + basePath: string + cwd: string + canApply: boolean + }, +): MigrationReference[] { + const references: MigrationReference[] = [] + + function visit(value: unknown, fieldPath: string) { + if (typeof value === 'string') { + const plan = classifyLegacyReference(value, context.cwd) + if (plan) { + references.push({ + ...plan, + id: referenceId(context.recordType, context.recordId, fieldPath, plan.oldValue), + recordType: context.recordType, + recordId: context.recordId, + label: context.label, + fieldPath, + canApply: context.canApply, + }) + } + return + } + + if (Array.isArray(value)) { + value.forEach((item, index) => visit(item, `${fieldPath}[${index}]`)) + return + } + + if (value && typeof value === 'object') { + Object.entries(value as Record).forEach(([key, child]) => { + visit(child, `${fieldPath}.${key}`) + }) + } + } + + visit(input, context.basePath) + return references +} + +export function replaceLegacyStringsInJson( + input: unknown, + replacements: Map, +): { value: unknown; changed: boolean } { + if (typeof input === 'string') { + const replacement = replacements.get(input) + return replacement ? { value: replacement, changed: true } : { value: input, changed: false } + } + + if (Array.isArray(input)) { + let changed = false + const value = input.map((item) => { + const next = replaceLegacyStringsInJson(item, replacements) + changed ||= next.changed + return next.value + }) + return { value, changed } + } + + if (input && typeof input === 'object') { + let changed = false + const value: Record = {} + Object.entries(input as Record).forEach(([key, child]) => { + const next = replaceLegacyStringsInJson(child, replacements) + changed ||= next.changed + value[key] = next.value + }) + return { value, changed } + } + + return { value: input, changed: false } +} + +async function runWithConcurrency( + items: T[], + concurrency: number, + worker: (item: T, index: number) => Promise, +) { + const running = new Set>() + for (let index = 0; index < items.length; index += 1) { + const promise = worker(items[index], index).finally(() => running.delete(promise)) + running.add(promise) + if (running.size >= concurrency) { + await Promise.race(running) + } + } + await Promise.all(running) +} + +async function checkSource(source: LegacyReferencePlan['source']): Promise { + if (source.type === 'local') { + const filePath = source.filePath || '' + try { + const fileStat = await stat(filePath) + return { + checked: true, + exists: fileStat.isFile(), + size: fileStat.size, + contentType: contentTypeFromPath(filePath), + } + } catch (error) { + return { + checked: true, + exists: false, + size: null, + contentType: null, + error: error instanceof Error ? error.message : String(error), + } + } + } + + const url = source.url || '' + try { + let response = await fetch(url, { method: 'HEAD' }) + if (!response.ok || response.status === 405) { + response = await fetch(url, { headers: { range: 'bytes=0-0' } }) + } + return { + checked: true, + exists: response.ok || response.status === 206, + size: Number(response.headers.get('content-length')) || null, + contentType: response.headers.get('content-type'), + error: response.ok || response.status === 206 ? undefined : `HTTP ${response.status}`, + } + } catch (error) { + return { + checked: true, + exists: false, + size: null, + contentType: null, + error: error instanceof Error ? error.message : String(error), + } + } +} + +async function readSourceBuffer( + task: ObjectTask, +): Promise<{ buffer: Buffer; contentType: string }> { + if (task.source.type === 'local') { + const filePath = task.source.filePath || '' + const buffer = await readFile(filePath) + return { buffer, contentType: task.contentType || contentTypeFromPath(filePath) } + } + + const url = task.source.url || '' + const response = await fetch(url) + if (!response.ok) { + throw new Error(`源文件下载失败 HTTP ${response.status}: ${url}`) + } + return { + buffer: Buffer.from(await response.arrayBuffer()), + contentType: response.headers.get('content-type') || task.contentType, + } +} + +function databaseIdentity(databaseUrl: string | undefined): string | null { + if (!databaseUrl) return null + try { + const parsed = new URL(databaseUrl) + return [ + parsed.protocol.replace(/:$/, ''), + parsed.username.toLowerCase(), + parsed.hostname.toLowerCase(), + parsed.port, + parsed.pathname.replace(/^\//, '').toLowerCase(), + (parsed.searchParams.get('schema') || parsed.searchParams.get('currentSchema') || '').toLowerCase(), + ].join('|') + } catch { + return 'unparseable' + } +} + +function countBy>(items: T[], field: keyof T): Record { + return items.reduce>((acc, item) => { + const key = String(item[field] ?? 'unknown') + acc[key] = (acc[key] || 0) + 1 + return acc + }, {}) +} + +function addDirectReference( + references: MigrationReference[], + params: { + recordType: RecordType + recordId: string + label: string + fieldPath: string + directField: string + value: string | null | undefined + cwd: string + }, +) { + const value = params.value?.trim() + if (!value) return + const plan = classifyLegacyReference(value, params.cwd) + if (!plan) return + references.push({ + ...plan, + id: referenceId(params.recordType, params.recordId, params.fieldPath, plan.oldValue), + recordType: params.recordType, + recordId: params.recordId, + label: params.label, + fieldPath: params.fieldPath, + directField: params.directField, + canApply: true, + }) +} + +async function collectReferences( + options: CliOptions, + cwd: string, +): Promise<{ + references: MigrationReference[] + snapshots: AuditReport['recordSnapshots'] + payloadByProductId: Map + payloadByEventId: Map +}> { + if (!prisma) throw new Error('Prisma client 未初始化。') + const references: MigrationReference[] = [] + const snapshots: AuditReport['recordSnapshots'] = [] + const payloadByProductId = new Map() + const payloadByEventId = new Map() + const take = options.limit ? { take: options.limit } : {} + + const [assetVariants, materials, intakeProducts, syncEvents] = await Promise.all([ + prisma.assetVariant.findMany({ + where: options.includeDeleted ? undefined : { deletedAt: null }, + select: { id: true, code: true, name: true, modelUrl: true, thumbnailUrl: true }, + orderBy: { updatedAt: 'desc' }, + ...take, + }), + prisma.material.findMany({ + select: { id: true, code: true, name: true, textureUrl: true, thumbnailUrl: true, normalMapUrl: true }, + orderBy: { updatedAt: 'desc' }, + ...take, + }), + prisma.intakeNonIntegratedProduct.findMany({ + where: options.includeDeleted ? undefined : { deletedAt: null }, + select: { id: true, spu: true, brand: true, payload: true }, + orderBy: { updatedAt: 'desc' }, + ...take, + }), + prisma.assetSkuSyncEvent.findMany({ + select: { id: true, assetVariantId: true, reason: true, payload: true }, + orderBy: { createdAt: 'desc' }, + ...take, + }), + ]) + + for (const variant of assetVariants) { + const label = `${variant.code} ${variant.name}`.trim() + const before = references.length + addDirectReference(references, { + recordType: 'AssetVariant', + recordId: variant.id, + label, + fieldPath: 'modelUrl', + directField: 'modelUrl', + value: variant.modelUrl, + cwd, + }) + addDirectReference(references, { + recordType: 'AssetVariant', + recordId: variant.id, + label, + fieldPath: 'thumbnailUrl', + directField: 'thumbnailUrl', + value: variant.thumbnailUrl, + cwd, + }) + if (references.length > before) { + snapshots.push({ + recordType: 'AssetVariant', + recordId: variant.id, + label, + original: { modelUrl: variant.modelUrl, thumbnailUrl: variant.thumbnailUrl }, + }) + } + } + + for (const material of materials) { + const label = `${material.code} ${material.name}`.trim() + const before = references.length + for (const field of ['textureUrl', 'thumbnailUrl', 'normalMapUrl'] as const) { + addDirectReference(references, { + recordType: 'Material', + recordId: material.id, + label, + fieldPath: field, + directField: field, + value: material[field], + cwd, + }) + } + if (references.length > before) { + snapshots.push({ + recordType: 'Material', + recordId: material.id, + label, + original: { + textureUrl: material.textureUrl, + thumbnailUrl: material.thumbnailUrl, + normalMapUrl: material.normalMapUrl, + }, + }) + } + } + + for (const product of intakeProducts) { + const label = `${product.spu} ${product.brand}`.trim() + const productReferences = collectJsonReferences(product.payload, { + recordType: 'IntakeNonIntegratedProduct', + recordId: product.id, + label, + basePath: 'payload', + cwd, + canApply: true, + }) + if (productReferences.length > 0) { + references.push(...productReferences) + payloadByProductId.set(product.id, product.payload) + snapshots.push({ + recordType: 'IntakeNonIntegratedProduct', + recordId: product.id, + label, + original: product.payload, + }) + } + } + + for (const event of syncEvents) { + if (event.payload === null || event.payload === undefined) { + continue + } + const label = `${event.assetVariantId} ${event.reason}`.trim() + const eventReferences = collectJsonReferences(event.payload, { + recordType: 'AssetSkuSyncEvent', + recordId: event.id, + label, + basePath: 'payload', + cwd, + canApply: options.includeEventSnapshots, + }) + if (eventReferences.length > 0) { + references.push(...eventReferences) + payloadByEventId.set(event.id, event.payload) + snapshots.push({ + recordType: 'AssetSkuSyncEvent', + recordId: event.id, + label, + original: event.payload, + }) + } + } + + return { references, snapshots, payloadByProductId, payloadByEventId } +} + +function enrichReferences( + references: MigrationReference[], + storage: StorageModule, +): MigrationReference[] { + return references.map((reference) => { + const targetObjectKey = storage.normalizeObjectStorageKey(reference.targetKey) + return { + ...reference, + targetObjectKey, + targetUrl: storage.buildStableObjectAccessUrl(reference.targetKey), + } + }) +} + +function buildObjectTasks(references: MigrationReference[]): ObjectTask[] { + const byTargetKey = new Map() + for (const reference of references) { + const targetObjectKey = reference.targetObjectKey || reference.targetKey + const targetUrl = reference.targetUrl || '' + const taskKey = targetObjectKey + const existing = byTargetKey.get(taskKey) + if (existing) { + existing.oldValues = Array.from(new Set([...existing.oldValues, reference.oldValue])) + existing.references.push(reference.id) + existing.notes = Array.from(new Set([...existing.notes, ...reference.notes])) + continue + } + + byTargetKey.set(taskKey, { + targetKey: reference.targetKey, + targetObjectKey, + targetUrl, + kind: reference.kind, + source: reference.source, + contentType: reference.contentType, + oldValues: [reference.oldValue], + references: [reference.id], + notes: reference.notes, + }) + } + + return Array.from(byTargetKey.values()).sort((a, b) => + a.targetObjectKey.localeCompare(b.targetObjectKey), + ) +} + +async function inspectTargets( + tasks: ObjectTask[], + storage: StorageModule, + options: CliOptions, +) { + await runWithConcurrency(tasks, options.concurrency, async (task) => { + if (!options.skipSourceCheck) { + task.sourceCheck = await checkSource(task.source) + } else { + task.sourceCheck = { checked: false, exists: false, size: null, contentType: null } + } + + try { + task.targetExistsBefore = await storage.doesObjectExist(task.targetKey) + } catch (error) { + task.targetExistsBefore = null + task.notes.push( + `目标对象存在性检查失败:${error instanceof Error ? error.message : String(error)}`, + ) + } + }) +} + +async function uploadAndVerifyObjects( + tasks: ObjectTask[], + storage: StorageModule, + options: CliOptions, +) { + await runWithConcurrency(tasks, options.concurrency, async (task) => { + if (!options.apply) { + task.uploadStatus = 'dry-run' + task.verified = Boolean(task.targetExistsBefore) + return + } + + try { + if (task.targetExistsBefore && !options.forceUpload) { + task.uploadStatus = 'skipped-existing' + } else { + const source = await readSourceBuffer(task) + task.bytes = source.buffer.length + task.sha256 = createHash('sha256').update(source.buffer).digest('hex') + await storage.uploadBufferToObjectStorage(source.buffer, task.targetKey, source.contentType) + task.uploadStatus = 'uploaded' + } + + task.verified = await storage.doesObjectExist(task.targetKey) + if (!task.verified) { + throw new Error('上传后目标对象 doesObjectExist=false') + } + } catch (error) { + task.uploadStatus = 'failed' + task.verified = false + task.error = error instanceof Error ? error.message : String(error) + } + }) +} + +function buildReplacementMap(tasks: ObjectTask[], apply: boolean): Map { + const replacements = new Map() + for (const task of tasks) { + const canReplace = apply ? task.verified : true + if (!canReplace) continue + for (const oldValue of task.oldValues) { + replacements.set(oldValue, task.targetUrl) + } + } + return replacements +} + +function chunk(items: T[], size: number): T[][] { + const chunks: T[][] = [] + for (let index = 0; index < items.length; index += size) { + chunks.push(items.slice(index, index + size)) + } + return chunks +} + +async function applyDatabaseUpdates(params: { + references: MigrationReference[] + replacements: Map + payloadByProductId: Map + payloadByEventId: Map + options: CliOptions + report: AuditReport +}) { + if (!prisma) throw new Error('Prisma client 未初始化。') + const { references, replacements, payloadByProductId, payloadByEventId, options, report } = params + const directUpdates = new Map }>() + + for (const reference of references) { + if (!reference.canApply) { + report.updates.push({ + recordType: reference.recordType, + recordId: reference.recordId, + fields: [reference.fieldPath], + applied: false, + reason: '历史事件快照默认只扫描;如确认需要改快照,请追加 --include-event-snapshots。', + }) + continue + } + + const replacement = replacements.get(reference.oldValue) + if (!replacement) continue + if (!reference.directField) continue + + const key = `${reference.recordType}:${reference.recordId}` + const existing = directUpdates.get(key) || { + recordType: reference.recordType, + recordId: reference.recordId, + data: {}, + } + existing.data[reference.directField] = replacement + directUpdates.set(key, existing) + } + + const operations: any[] = [] + for (const update of directUpdates.values()) { + if (update.recordType === 'AssetVariant') { + operations.push( + prisma.assetVariant.update({ where: { id: update.recordId }, data: update.data }) as never, + ) + } + if (update.recordType === 'Material') { + operations.push( + prisma.material.update({ where: { id: update.recordId }, data: update.data }) as never, + ) + } + report.updates.push({ + recordType: update.recordType, + recordId: update.recordId, + fields: Object.keys(update.data), + applied: options.apply, + }) + } + + for (const [recordId, payload] of payloadByProductId) { + const next = replaceLegacyStringsInJson(payload, replacements) + if (!next.changed) continue + operations.push( + prisma.intakeNonIntegratedProduct.update({ + where: { id: recordId }, + data: { payload: next.value as never }, + }) as never, + ) + report.updates.push({ + recordType: 'IntakeNonIntegratedProduct', + recordId, + fields: ['payload'], + applied: options.apply, + }) + } + + if (options.includeEventSnapshots) { + for (const [recordId, payload] of payloadByEventId) { + const next = replaceLegacyStringsInJson(payload, replacements) + if (!next.changed) continue + operations.push( + prisma.assetSkuSyncEvent.update({ + where: { id: recordId }, + data: { payload: next.value as never }, + }) as never, + ) + report.updates.push({ + recordType: 'AssetSkuSyncEvent', + recordId, + fields: ['payload'], + applied: options.apply, + }) + } + } + + if (!options.apply || operations.length === 0) return + + for (const batch of chunk(operations, options.batchSize)) { + await prisma.$transaction(batch as never) + } +} + +function createEmptyReport(options: CliOptions): AuditReport { + return { + schema: 'qiniu_historical_assets_migration_audit', + schemaVersion: '2026-06-03.v1', + startedAt: new Date().toISOString(), + mode: options.apply ? 'apply' : 'dry-run', + status: 'running', + options, + database: { + identity: databaseIdentity(process.env.DATABASE_URL), + }, + counts: {}, + warnings: [], + references: [], + objects: [], + recordSnapshots: [], + updates: [], + } +} + +async function writeAuditReport(report: AuditReport, auditDir: string) { + report.finishedAt = new Date().toISOString() + await mkdir(auditDir, { recursive: true }) + const stamp = report.startedAt.replace(/[:.]/g, '-') + const mode = report.mode === 'apply' ? 'apply' : 'dry-run' + const filePath = path.join(auditDir, `${stamp}-historical-assets-${mode}.json`) + await writeFile(filePath, JSON.stringify(report, null, 2), 'utf8') + console.log(`[storage-migration] 审计报告已写入:${filePath}`) +} + +function printSummary(report: AuditReport) { + const missingSources = report.objects.filter( + (task) => task.sourceCheck?.checked && !task.sourceCheck.exists && !task.targetExistsBefore, + ).length + const failedUploads = report.objects.filter((task) => task.uploadStatus === 'failed').length + const skippedEvents = report.references.filter( + (reference) => reference.recordType === 'AssetSkuSyncEvent' && !reference.canApply, + ).length + + console.log( + JSON.stringify( + { + mode: report.mode, + references: report.references.length, + objects: report.objects.length, + missingSources, + failedUploads, + plannedOrAppliedUpdates: report.updates.filter((item) => item.applied).length, + dryRunPlannedUpdates: + report.mode === 'dry-run' ? report.updates.filter((item) => !item.reason).length : 0, + skippedEventSnapshotReferences: skippedEvents, + }, + null, + 2, + ), + ) +} + +function serializeError(error: unknown): string { + if (!(error instanceof Error)) { + return String(error) + } + + const errorRecord = error as Error & Record + if (errorRecord.code === 'ECONNREFUSED') { + return '数据库连接被拒绝(ECONNREFUSED)。请先确认 DATABASE_URL 指向的 PostgreSQL 已启动,再重新执行 dry-run。' + } + + const details: Record = { + name: error.name, + message: error.message, + } + for (const key of ['code', 'clientVersion', 'meta', 'cause']) { + if (errorRecord[key] !== undefined) { + details[key] = errorRecord[key] + } + } + if (error.stack) { + details.stack = error.stack + } + + return JSON.stringify(details, null, 2) +} + +async function main() { + loadEnvConfig(process.cwd()) + const options = resolveOptions() + const auditDir = path.resolve(process.cwd(), options.auditDir) + const report = createEmptyReport({ ...options, auditDir }) + + try { + const [prismaModule, storage] = await Promise.all([ + import('../src/lib/prisma'), + import('../src/lib/storage'), + ]) + prisma = prismaModule.prisma + + report.storage = { + provider: storage.getStorageProvider(), + accessMode: storage.getStorageAccessMode(), + bucketName: storage.getStorageBucketName(), + filePathPrefix: storage.getStorageFilePathPrefix(), + publicEndpoint: storage.getStoragePublicEndpoint(), + } + + if (storage.getStorageProvider() !== 'qiniu') { + throw new Error('当前 STORAGE_PROVIDER 不是 qiniu,禁止执行七牛历史迁移。') + } + + const collected = await collectReferences(options, process.cwd()) + report.references = enrichReferences(collected.references, storage) + report.recordSnapshots = collected.snapshots + report.objects = buildObjectTasks(report.references) + + await inspectTargets(report.objects, storage, options) + await uploadAndVerifyObjects(report.objects, storage, options) + const replacements = buildReplacementMap(report.objects, options.apply) + await applyDatabaseUpdates({ + references: report.references, + replacements, + payloadByProductId: collected.payloadByProductId, + payloadByEventId: collected.payloadByEventId, + options, + report, + }) + + report.counts = { + referenceTotal: report.references.length, + objectTotal: report.objects.length, + ...Object.fromEntries( + Object.entries(countBy(report.references, 'recordType')).map(([key, value]) => [ + `record.${key}`, + value, + ]), + ), + ...Object.fromEntries( + Object.entries(countBy(report.references, 'kind')).map(([key, value]) => [ + `kind.${key}`, + value, + ]), + ), + sourceMissing: report.objects.filter( + (task) => task.sourceCheck?.checked && !task.sourceCheck.exists && !task.targetExistsBefore, + ).length, + targetExistsBefore: report.objects.filter((task) => task.targetExistsBefore).length, + uploadFailed: report.objects.filter((task) => task.uploadStatus === 'failed').length, + updateTotal: report.updates.filter((item) => item.applied || !item.reason).length, + } + + for (const task of report.objects) { + for (const note of task.notes) { + report.warnings.push(`${task.targetObjectKey}: ${note}`) + } + } + + if (report.counts.uploadFailed > 0) { + throw new Error(`存在 ${report.counts.uploadFailed} 个对象上传或验证失败,已阻止后续收口。`) + } + + report.status = 'completed' + printSummary(report) + } catch (error) { + report.status = 'failed' + report.error = serializeError(error) + console.error('[storage-migration] 执行失败:', report.error) + process.exitCode = 1 + } finally { + await writeAuditReport(report, auditDir) + await prisma?.$disconnect() + } +} + +function isMainModule() { + const entry = process.argv[1] ? path.basename(process.argv[1]) : '' + return entry === 'migrate-historical-assets-to-qiniu.ts' || entry === 'migrate-historical-assets-to-qiniu.js' +} + +if (isMainModule()) { + void main() +} diff --git a/furniture-3d-system/src/app/api/intake/non-integrated/[id]/document-preview/route.ts b/furniture-3d-system/src/app/api/intake/non-integrated/[id]/document-preview/route.ts index 9bdda5f2..5ed802b3 100644 --- a/furniture-3d-system/src/app/api/intake/non-integrated/[id]/document-preview/route.ts +++ b/furniture-3d-system/src/app/api/intake/non-integrated/[id]/document-preview/route.ts @@ -17,7 +17,7 @@ import { NextRequest } from "next/server"; import { buildNonIntegratedDocumentPreviewUrl, getNonIntegratedAssetDirectory, - resolveNonIntegratedAssetFilePath, + materializeNonIntegratedAssetFile, } from "@/app/intake/non-integrated/nonIntegratedAssetServer"; import { NON_INTEGRATED_DOCUMENT_PREVIEW_DIRECTORY } from "@/app/intake/non-integrated/nonIntegratedAssetUrl"; import { AppError, ErrorCode } from "@/server/core/errors"; @@ -286,37 +286,47 @@ export async function POST(request: NextRequest, context: RouteContext) { throw error; } - const sourceFilePath = resolveNonIntegratedAssetFilePath(selectedFileUrl); - - if (!sourceFilePath || !existsSync(sourceFilePath)) { - return jsonError(ErrorCode.FILE_NOT_FOUND, "The document file to preview was not found.", 404, requestId); - } - - const extension = path.extname(sourceFilePath).toLowerCase(); - if (!DOCUMENT_PREVIEW_EXTENSIONS.has(extension)) { - return jsonError( - ErrorCode.FILE_TYPE_NOT_ALLOWED, - "Only PDF, PPT, or PPTX files can be converted to image previews.", - 400, - requestId, - ); - } - - const sourceStat = await stat(sourceFilePath); - const cacheKey = createHash("sha1") - .update(`${sourceFilePath}:${sourceStat.size}:${sourceStat.mtimeMs}:jpg-v4`) - .digest("hex"); - const cacheDirectory = path.join(DOCUMENT_PREVIEW_DIR, cacheKey); - const cachedUrls = await listCachedPreviewUrls(cacheKey, cacheDirectory); - - if (cachedUrls.length > 0) { - return jsonSuccess({ imageUrls: cachedUrls }, 200, requestId); - } - let tempDirectory = ""; + let cacheDirectory = ""; try { tempDirectory = await mkdtemp(path.join(tmpdir(), "non-integrated-document-preview-")); + const materializedFile = await materializeNonIntegratedAssetFile( + selectedFileUrl, + tempDirectory, + ); + + if (!materializedFile || !existsSync(materializedFile.filePath)) { + return jsonError(ErrorCode.FILE_NOT_FOUND, "The document file to preview was not found.", 404, requestId); + } + + const sourceFilePath = materializedFile.filePath; + const extension = path.extname(sourceFilePath).toLowerCase(); + if (!DOCUMENT_PREVIEW_EXTENSIONS.has(extension)) { + return jsonError( + ErrorCode.FILE_TYPE_NOT_ALLOWED, + "Only PDF, PPT, or PPTX files can be converted to image previews.", + 400, + requestId, + ); + } + + const sourceStat = await stat(sourceFilePath); + const cacheTimestamp = materializedFile.isTemporary + ? "object-storage" + : String(sourceStat.mtimeMs); + const cacheKey = createHash("sha1") + .update( + `${materializedFile.cacheIdentity}:${sourceStat.size}:${cacheTimestamp}:jpg-v5`, + ) + .digest("hex"); + cacheDirectory = path.join(DOCUMENT_PREVIEW_DIR, cacheKey); + const cachedUrls = await listCachedPreviewUrls(cacheKey, cacheDirectory); + + if (cachedUrls.length > 0) { + return jsonSuccess({ imageUrls: cachedUrls }, 200, requestId); + } + const pdfFilePath = PRESENTATION_EXTENSIONS.has(extension) ? await convertPresentationToPdf({ sourceFilePath, @@ -335,7 +345,9 @@ export async function POST(request: NextRequest, context: RouteContext) { return jsonSuccess({ imageUrls }, 200, requestId); } catch (error) { - await rm(cacheDirectory, { recursive: true, force: true }).catch(() => undefined); + if (cacheDirectory) { + await rm(cacheDirectory, { recursive: true, force: true }).catch(() => undefined); + } return jsonError( ErrorCode.FILE_UPLOAD_FAILED, diff --git a/furniture-3d-system/src/app/api/intake/non-integrated/[id]/presentation-preview/route.ts b/furniture-3d-system/src/app/api/intake/non-integrated/[id]/presentation-preview/route.ts index 21a30b20..5ca0b4bd 100644 --- a/furniture-3d-system/src/app/api/intake/non-integrated/[id]/presentation-preview/route.ts +++ b/furniture-3d-system/src/app/api/intake/non-integrated/[id]/presentation-preview/route.ts @@ -9,7 +9,7 @@ import { NextRequest } from 'next/server' import { buildNonIntegratedPresentationPreviewUrl, getNonIntegratedAssetDirectory, - resolveNonIntegratedAssetFilePath, + materializeNonIntegratedAssetFile, } from '@/app/intake/non-integrated/nonIntegratedAssetServer' import { NON_INTEGRATED_PRESENTATION_PREVIEW_DIRECTORY } from '@/app/intake/non-integrated/nonIntegratedAssetUrl' import { AppError, ErrorCode } from '@/server/core/errors' @@ -71,42 +71,51 @@ export async function POST(request: NextRequest, context: RouteContext) { throw error } - const sourceFilePath = resolveNonIntegratedAssetFilePath(selectedFileUrl) - - if (!sourceFilePath || !existsSync(sourceFilePath)) { - return jsonError(ErrorCode.FILE_NOT_FOUND, 'The PPT file to preview was not found.', 404, requestId) - } - - const extension = path.extname(sourceFilePath).toLowerCase() - if (!PRESENTATION_EXTENSIONS.has(extension)) { - return jsonError( - ErrorCode.FILE_TYPE_NOT_ALLOWED, - 'Only PPT or PPTX files can be previewed here.', - 400, - requestId, - ) - } - - const sourceStat = await stat(sourceFilePath) - const cacheKey = createHash('sha1') - .update(`${sourceFilePath}:${sourceStat.size}:${sourceStat.mtimeMs}`) - .digest('hex') - const cachedFileName = `${cacheKey}.pdf` - const cachedFilePath = path.join(PRESENTATION_PREVIEW_DIR, cachedFileName) - const pdfUrl = buildNonIntegratedPresentationPreviewUrl(cachedFileName) - - if (existsSync(cachedFilePath)) { - return jsonSuccess({ pdfUrl }, 200, requestId) - } - - if (!existsSync(PRESENTATION_PREVIEW_DIR)) { - await mkdir(PRESENTATION_PREVIEW_DIR, { recursive: true }) - } - let tempDirectory = '' try { tempDirectory = await mkdtemp(path.join(tmpdir(), 'non-integrated-presentation-preview-')) + const materializedFile = await materializeNonIntegratedAssetFile( + selectedFileUrl, + tempDirectory, + ) + + if (!materializedFile || !existsSync(materializedFile.filePath)) { + return jsonError(ErrorCode.FILE_NOT_FOUND, 'The PPT file to preview was not found.', 404, requestId) + } + + const sourceFilePath = materializedFile.filePath + const extension = path.extname(sourceFilePath).toLowerCase() + if (!PRESENTATION_EXTENSIONS.has(extension)) { + return jsonError( + ErrorCode.FILE_TYPE_NOT_ALLOWED, + 'Only PPT or PPTX files can be previewed here.', + 400, + requestId, + ) + } + + const sourceStat = await stat(sourceFilePath) + const cacheTimestamp = materializedFile.isTemporary + ? 'object-storage' + : String(sourceStat.mtimeMs) + const cacheKey = createHash('sha1') + .update( + `${materializedFile.cacheIdentity}:${sourceStat.size}:${cacheTimestamp}:pdf-v2`, + ) + .digest('hex') + const cachedFileName = `${cacheKey}.pdf` + const cachedFilePath = path.join(PRESENTATION_PREVIEW_DIR, cachedFileName) + const pdfUrl = buildNonIntegratedPresentationPreviewUrl(cachedFileName) + + if (existsSync(cachedFilePath)) { + return jsonSuccess({ pdfUrl }, 200, requestId) + } + + if (!existsSync(PRESENTATION_PREVIEW_DIR)) { + await mkdir(PRESENTATION_PREVIEW_DIR, { recursive: true }) + } + const tempSourcePath = path.join(tempDirectory, `source${extension}`) const tempOutputPath = path.join(tempDirectory, 'source.pdf') diff --git a/furniture-3d-system/src/app/api/intake/non-integrated/presentation-preview/route.test.ts b/furniture-3d-system/src/app/api/intake/non-integrated/presentation-preview/route.test.ts index bbfd62ae..6cd18dde 100644 --- a/furniture-3d-system/src/app/api/intake/non-integrated/presentation-preview/route.test.ts +++ b/furniture-3d-system/src/app/api/intake/non-integrated/presentation-preview/route.test.ts @@ -10,7 +10,7 @@ const mockMkdir = jest.fn() const mockMkdtemp = jest.fn() const mockRm = jest.fn() const mockStat = jest.fn() -const mockResolveNonIntegratedAssetFilePath = jest.fn() +const mockMaterializeNonIntegratedAssetFile = jest.fn() const mockBuildNonIntegratedPresentationPreviewUrl = jest.fn( () => '/non-integrated/presentation-previews/cache.pdf', ) @@ -42,8 +42,8 @@ jest.mock('@/app/intake/non-integrated/nonIntegratedAssetServer', () => ({ buildNonIntegratedPresentationPreviewUrl: (...args: unknown[]) => mockBuildNonIntegratedPresentationPreviewUrl(...args), getNonIntegratedAssetDirectory: (...args: unknown[]) => mockGetNonIntegratedAssetDirectory(...args), - resolveNonIntegratedAssetFilePath: (...args: unknown[]) => - mockResolveNonIntegratedAssetFilePath(...args), + materializeNonIntegratedAssetFile: (...args: unknown[]) => + mockMaterializeNonIntegratedAssetFile(...args), })) jest.mock('@/app/intake/non-integrated/nonIntegratedAssetUrl', () => ({ @@ -96,7 +96,11 @@ describe('POST /api/intake/non-integrated/presentation-preview', () => { })) mockGetNonIntegratedAssetDirectory.mockReturnValue('D:/mock/non-integrated') - mockResolveNonIntegratedAssetFilePath.mockReturnValue('D:/mock/non-integrated/uploads/slides.pptx') + mockMaterializeNonIntegratedAssetFile.mockResolvedValue({ + filePath: 'D:/mock/non-integrated/uploads/slides.pptx', + cacheIdentity: 'D:/mock/non-integrated/uploads/slides.pptx', + isTemporary: false, + }) mockBuildNonIntegratedPresentationPreviewUrl.mockReturnValue('/non-integrated/presentation-previews/cache.pdf') mockExistsSync.mockImplementation((filePath: string) => filePath === 'D:/mock/non-integrated/uploads/slides.pptx', @@ -120,8 +124,9 @@ describe('POST /api/intake/non-integrated/presentation-preview', () => { }), ) - expect(mockResolveNonIntegratedAssetFilePath).toHaveBeenCalledWith( + expect(mockMaterializeNonIntegratedAssetFile).toHaveBeenCalledWith( '/intake/non-integrated/uploads/slides.pptx', + 'D:/temp/non-integrated-presentation-preview-1', ) expect(mockCopyFile).toHaveBeenCalledWith( 'D:/mock/non-integrated/uploads/slides.pptx', diff --git a/furniture-3d-system/src/app/api/intake/non-integrated/presentation-preview/route.ts b/furniture-3d-system/src/app/api/intake/non-integrated/presentation-preview/route.ts index 8d31bdb7..4af4b7ca 100644 --- a/furniture-3d-system/src/app/api/intake/non-integrated/presentation-preview/route.ts +++ b/furniture-3d-system/src/app/api/intake/non-integrated/presentation-preview/route.ts @@ -9,7 +9,7 @@ import { NextRequest } from 'next/server' import { buildNonIntegratedPresentationPreviewUrl, getNonIntegratedAssetDirectory, - resolveNonIntegratedAssetFilePath, + materializeNonIntegratedAssetFile, } from '@/app/intake/non-integrated/nonIntegratedAssetServer' import { NON_INTEGRATED_PRESENTATION_PREVIEW_DIRECTORY } from '@/app/intake/non-integrated/nonIntegratedAssetUrl' import { ErrorCode } from '@/server/core/errors' @@ -31,41 +31,51 @@ export async function POST(request: NextRequest) { async ({ requestId }) => { const payload = (await request.json().catch(() => null)) as { fileUrl?: string } | null const fileUrl = typeof payload?.fileUrl === 'string' ? payload.fileUrl : '' - const sourceFilePath = resolveNonIntegratedAssetFilePath(fileUrl) if (!fileUrl) { return jsonError(ErrorCode.VALIDATION_REQUIRED_FIELD, '请先提供需要预览的 PPT 文件。', 400, requestId) } - if (!sourceFilePath || !existsSync(sourceFilePath)) { - return jsonError(ErrorCode.FILE_NOT_FOUND, '没有找到需要预览的 PPT 文件。', 404, requestId) - } - - const extension = path.extname(sourceFilePath).toLowerCase() - if (!PRESENTATION_EXTENSIONS.has(extension)) { - return jsonError(ErrorCode.FILE_TYPE_NOT_ALLOWED, '当前文件不是 PPT 或 PPTX,无法生成原样预览。', 400, requestId) - } - - const sourceStat = await stat(sourceFilePath) - const cacheKey = createHash('sha1') - .update(`${sourceFilePath}:${sourceStat.size}:${sourceStat.mtimeMs}`) - .digest('hex') - const cachedFileName = `${cacheKey}.pdf` - const cachedFilePath = path.join(PRESENTATION_PREVIEW_DIR, cachedFileName) - const pdfUrl = buildNonIntegratedPresentationPreviewUrl(cachedFileName) - - if (existsSync(cachedFilePath)) { - return jsonSuccess({ pdfUrl }, 200, requestId) - } - - if (!existsSync(PRESENTATION_PREVIEW_DIR)) { - await mkdir(PRESENTATION_PREVIEW_DIR, { recursive: true }) - } - let tempDirectory = '' try { tempDirectory = await mkdtemp(path.join(tmpdir(), 'non-integrated-presentation-preview-')) + const materializedFile = await materializeNonIntegratedAssetFile( + fileUrl, + tempDirectory, + ) + + if (!materializedFile || !existsSync(materializedFile.filePath)) { + return jsonError(ErrorCode.FILE_NOT_FOUND, '没有找到需要预览的 PPT 文件。', 404, requestId) + } + + const sourceFilePath = materializedFile.filePath + const extension = path.extname(sourceFilePath).toLowerCase() + if (!PRESENTATION_EXTENSIONS.has(extension)) { + return jsonError(ErrorCode.FILE_TYPE_NOT_ALLOWED, '当前文件不是 PPT 或 PPTX,无法生成原样预览。', 400, requestId) + } + + const sourceStat = await stat(sourceFilePath) + const cacheTimestamp = materializedFile.isTemporary + ? 'object-storage' + : String(sourceStat.mtimeMs) + const cacheKey = createHash('sha1') + .update( + `${materializedFile.cacheIdentity}:${sourceStat.size}:${cacheTimestamp}:pdf-v2`, + ) + .digest('hex') + const cachedFileName = `${cacheKey}.pdf` + const cachedFilePath = path.join(PRESENTATION_PREVIEW_DIR, cachedFileName) + const pdfUrl = buildNonIntegratedPresentationPreviewUrl(cachedFileName) + + if (existsSync(cachedFilePath)) { + return jsonSuccess({ pdfUrl }, 200, requestId) + } + + if (!existsSync(PRESENTATION_PREVIEW_DIR)) { + await mkdir(PRESENTATION_PREVIEW_DIR, { recursive: true }) + } + const tempSourcePath = path.join(tempDirectory, `source${extension}`) const tempOutputPath = path.join(tempDirectory, 'source.pdf') diff --git a/furniture-3d-system/src/app/api/storage/object/route.test.ts b/furniture-3d-system/src/app/api/storage/object/route.test.ts index c525bd07..b96bfdce 100644 --- a/furniture-3d-system/src/app/api/storage/object/route.test.ts +++ b/furniture-3d-system/src/app/api/storage/object/route.test.ts @@ -5,7 +5,9 @@ import { NextRequest } from 'next/server' const mockHandleRequest: any = jest.fn() const mockJsonError: any = jest.fn() const mockCreateObjectReadUrl: any = jest.fn() +const mockGetStorageFilePathPrefix: any = jest.fn() const mockFetch: any = jest.fn() +const mockAssertCanDownload: any = jest.fn() jest.mock('@/server/core/response', () => ({ handleRequest: (...args: unknown[]) => mockHandleRequest(...args), @@ -14,6 +16,13 @@ jest.mock('@/server/core/response', () => ({ jest.mock('@/lib/storage', () => ({ createObjectReadUrl: (...args: unknown[]) => mockCreateObjectReadUrl(...args), + getStorageFilePathPrefix: (...args: unknown[]) => mockGetStorageFilePathPrefix(...args), +})) + +jest.mock('@/server/services/intake-non-integrated-product.service', () => ({ + intakeNonIntegratedProductService: { + assertCanDownload: (...args: unknown[]) => mockAssertCanDownload(...args), + }, })) const { GET } = require('./route') @@ -53,6 +62,8 @@ describe('GET /api/storage/object', () => { mockCreateObjectReadUrl.mockImplementation( (key: string) => `https://cdn.example.com/${key}?token=signed`, ) + mockGetStorageFilePathPrefix.mockReturnValue('') + mockAssertCanDownload.mockResolvedValue(undefined) }) it('proxies a signed HTTPS storage URL instead of redirecting the browser cross-origin', async () => { @@ -158,4 +169,40 @@ describe('GET /api/storage/object', () => { }), ) }) + + it('keeps scoped download permission for migrated non-integrated assets', async () => { + mockGetStorageFilePathPrefix.mockReturnValue('prod/') + const upstreamBody = new Response('pdf-bytes').body + mockFetch.mockResolvedValue({ + ok: true, + status: 200, + body: upstreamBody, + headers: { + get: jest.fn((name: string) => { + const headers: Record = { + 'content-type': 'application/pdf', + } + return headers[name.toLowerCase()] ?? null + }), + }, + }) + const request = { + nextUrl: new URL( + 'http://localhost/api/storage/object?key=prod%2Fnon-integrated-assets%2FSZ0230%2F%E4%BA%A7%E5%93%81%E6%A8%A1%E5%9E%8B%2Ffile.pdf', + ), + headers: { get: jest.fn(() => null) }, + } as NextRequest + + const response = await GET(request) + + expect(mockAssertCanDownload).toHaveBeenCalledWith( + 'SZ0230', + { id: 'user-1', role: 'ADMIN' }, + '产品模型', + ) + expect(mockCreateObjectReadUrl).toHaveBeenCalledWith( + 'prod/non-integrated-assets/SZ0230/产品模型/file.pdf', + ) + expect(response.status).toBe(200) + }) }) diff --git a/furniture-3d-system/src/app/api/storage/object/route.ts b/furniture-3d-system/src/app/api/storage/object/route.ts index 9f35eabd..017c1077 100644 --- a/furniture-3d-system/src/app/api/storage/object/route.ts +++ b/furniture-3d-system/src/app/api/storage/object/route.ts @@ -1,11 +1,12 @@ import { NextRequest, NextResponse } from 'next/server' -import { ErrorCode } from '@/server/core/errors' +import { AppError, ErrorCode } from '@/server/core/errors' import { handleRequest, jsonError } from '@/server/core/response' -import { createObjectReadUrl } from '@/lib/storage' +import { createObjectReadUrl, getStorageFilePathPrefix } from '@/lib/storage' import { buildObjectReadResponse, ObjectReadProxyError, } from '@/lib/object-storage-read-response' +import { intakeNonIntegratedProductService } from '@/server/services/intake-non-integrated-product.service' export const dynamic = 'force-dynamic' @@ -18,10 +19,34 @@ function normalizeRequestKey(value: string | null): string | null { return key.replace(/^\/+/, '') } +function stripConfiguredStoragePrefix(key: string) { + const prefix = getStorageFilePathPrefix() + if (prefix && key.startsWith(prefix)) { + return key.slice(prefix.length) + } + + return key +} + +function parseNonIntegratedObjectScope(key: string) { + const normalizedKey = stripConfiguredStoragePrefix(key) + const prefix = 'non-integrated-assets/' + if (!normalizedKey.startsWith(prefix)) return null + + const relativePath = normalizedKey.slice(prefix.length) + const parts = relativePath.split('/').map((part) => part.trim()).filter(Boolean) + if (parts.length < 3) return null + + const [productId, category] = parts + if (!productId || !category) return null + + return { productId, category } +} + export async function GET(request: NextRequest) { return handleRequest( request, - async ({ request, requestId }) => { + async ({ request, requestId, user }) => { const key = normalizeRequestKey(request.nextUrl.searchParams.get('key')) if (!key) { return jsonError( @@ -32,6 +57,22 @@ export async function GET(request: NextRequest) { ) } + const nonIntegratedScope = parseNonIntegratedObjectScope(key) + if (nonIntegratedScope) { + try { + await intakeNonIntegratedProductService.assertCanDownload( + nonIntegratedScope.productId, + user, + nonIntegratedScope.category, + ) + } catch (error) { + if (error instanceof AppError) { + return jsonError(error.code, error.message, error.statusCode, requestId) + } + throw error + } + } + const readUrl = createObjectReadUrl(key) try { return (await buildObjectReadResponse(readUrl, request)) as unknown as NextResponse diff --git a/furniture-3d-system/src/app/intake/non-integrated/nonIntegratedAssetServer.ts b/furniture-3d-system/src/app/intake/non-integrated/nonIntegratedAssetServer.ts index aa9d72f6..e2fc007a 100644 --- a/furniture-3d-system/src/app/intake/non-integrated/nonIntegratedAssetServer.ts +++ b/furniture-3d-system/src/app/intake/non-integrated/nonIntegratedAssetServer.ts @@ -1,4 +1,6 @@ +import { randomUUID } from "crypto"; import { existsSync } from "fs"; +import { mkdir, writeFile } from "fs/promises"; import path from "path"; import { NON_INTEGRATED_ASSET_DIRECTORY_NAME, @@ -7,8 +9,16 @@ import { buildNonIntegratedAssetUrl, extractNonIntegratedAssetRelativePath, } from "./nonIntegratedAssetUrl"; +import { createObjectReadUrl, normalizeObjectStorageKey } from "@/lib/storage"; const NON_INTEGRATED_PRIVATE_ASSET_DIRECTORY_NAME = "non-integrated-assets"; +const OBJECT_STORAGE_ROUTE_PATH = "/api/storage/object"; + +export type MaterializedNonIntegratedAssetFile = { + filePath: string; + cacheIdentity: string; + isTemporary: boolean; +}; function resolveInsideBase(baseDirectory: string, relativePath: string) { const base = path.resolve(baseDirectory); @@ -69,6 +79,75 @@ export function resolveNonIntegratedAssetFilePath( return resolveNonIntegratedAssetRelativeFilePath(relativePath, cwd); } +export function extractObjectStorageKeyFromUrl(value: string) { + const normalizedValue = value.trim(); + if (!normalizedValue) return ""; + + try { + const parsed = new URL(normalizedValue, "http://storage.local"); + if (parsed.pathname !== OBJECT_STORAGE_ROUTE_PATH) { + return ""; + } + + const rawKey = parsed.searchParams.get("key")?.trim(); + if (!rawKey) return ""; + + return normalizeObjectStorageKey(rawKey); + } catch { + return ""; + } +} + +function buildSafeMaterializedFileName(objectKey: string) { + const extension = path.extname(objectKey).replace(/[^a-zA-Z0-9.]/g, ""); + const baseName = + path + .basename(objectKey, extension) + .replace(/[^a-zA-Z0-9\u4e00-\u9fa5_-]/g, "-") + .replace(/-+/g, "-") + .slice(0, 80) || "object-storage-file"; + + return `${baseName}-${randomUUID()}${extension}`; +} + +export async function materializeNonIntegratedAssetFile( + fileUrl: string, + tempDirectory: string, + cwd = process.cwd(), +): Promise { + const localPath = resolveNonIntegratedAssetFilePath(fileUrl, cwd); + if (localPath && existsSync(localPath)) { + return { + filePath: localPath, + cacheIdentity: localPath, + isTemporary: false, + }; + } + + const objectKey = extractObjectStorageKeyFromUrl(fileUrl); + if (!objectKey) { + return null; + } + + const response = await fetch(createObjectReadUrl(objectKey)); + if (!response.ok) { + return null; + } + + await mkdir(tempDirectory, { recursive: true }); + const filePath = path.join( + tempDirectory, + buildSafeMaterializedFileName(objectKey), + ); + await writeFile(filePath, Buffer.from(await response.arrayBuffer())); + + return { + filePath, + cacheIdentity: objectKey, + isTemporary: true, + }; +} + export function buildNonIntegratedPresentationPreviewUrl(fileName: string) { return buildNonIntegratedAssetUrl( `${NON_INTEGRATED_PRESENTATION_PREVIEW_DIRECTORY}/${fileName}`, diff --git a/furniture-3d-system/tests/scripts/migrate-historical-assets-to-qiniu.test.ts b/furniture-3d-system/tests/scripts/migrate-historical-assets-to-qiniu.test.ts new file mode 100644 index 00000000..f4742fea --- /dev/null +++ b/furniture-3d-system/tests/scripts/migrate-historical-assets-to-qiniu.test.ts @@ -0,0 +1,85 @@ +import { + classifyLegacyReference, + replaceLegacyStringsInJson, +} from '../../scripts/migrate-historical-assets-to-qiniu' + +describe('migrate-historical-assets-to-qiniu helpers', () => { + it('maps legacy S3 furniture paths into migrated object keys', () => { + const plan = classifyLegacyReference( + 'https://s3.jiansun.vip/furniture-3d-system/asset-center/board/demo.obj', + 'D:/workspace', + ) + + expect(plan).toMatchObject({ + kind: 'legacy-s3', + targetKey: 'migrated/s3/asset-center/board/demo.obj', + source: { + type: 'http', + }, + contentType: 'model/obj', + }) + }) + + it('maps non-integrated runtime assets into the private object namespace', () => { + const plan = classifyLegacyReference( + '/api/intake/non-integrated/assets/SZ0230/%E4%BA%A7%E5%93%81%E6%A8%A1%E5%9E%8B/file.pdf', + 'D:/workspace', + ) + + expect(plan).toMatchObject({ + kind: 'non-integrated-asset', + targetKey: 'non-integrated-assets/SZ0230/产品模型/file.pdf', + source: { + type: 'local', + }, + contentType: 'application/pdf', + }) + }) + + it('maps material texture URLs to the same object-storage namespace', () => { + const plan = classifyLegacyReference( + '/materials/textures/material-library/oak.webp', + 'D:/workspace', + ) + + expect(plan).toMatchObject({ + kind: 'material-texture', + targetKey: 'materials/textures/material-library/oak.webp', + source: { + type: 'local', + }, + contentType: 'image/webp', + }) + }) + + it('replaces matching legacy strings inside nested JSON without touching other values', () => { + const replacements = new Map([ + ['/api/intake/non-integrated/assets/SZ0230/产品模型/file.pdf', '/api/storage/object?key=prod%2Fnon-integrated-assets%2FSZ0230%2F%E4%BA%A7%E5%93%81%E6%A8%A1%E5%9E%8B%2Ffile.pdf'], + ]) + + const result = replaceLegacyStringsInJson( + { + uploadFiles: [ + { + dataUrl: '/api/intake/non-integrated/assets/SZ0230/产品模型/file.pdf', + name: 'file.pdf', + }, + ], + untouched: '/uploads/legacy-local-file.pdf', + }, + replacements, + ) + + expect(result.changed).toBe(true) + expect(result.value).toEqual({ + uploadFiles: [ + { + dataUrl: + '/api/storage/object?key=prod%2Fnon-integrated-assets%2FSZ0230%2F%E4%BA%A7%E5%93%81%E6%A8%A1%E5%9E%8B%2Ffile.pdf', + name: 'file.pdf', + }, + ], + untouched: '/uploads/legacy-local-file.pdf', + }) + }) +})