feat: 更新静态出库模板与大包上传

This commit is contained in:
Nixevol
2026-07-14 10:04:33 +08:00
parent 9644f5c128
commit 2250869244
36 changed files with 1378 additions and 461 deletions
+7 -1
View File
@@ -3,6 +3,12 @@
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
"deleteOutDir": true,
"assets": [
{
"include": "assets/templates/*.zip",
"watchAssets": true
}
]
}
}
+4 -1
View File
@@ -22,6 +22,7 @@
"dependencies": {
"@artveris/shared": "workspace:*",
"@aws-sdk/client-s3": "^3.700.0",
"@aws-sdk/lib-storage": "^3.1075.0",
"@aws-sdk/s3-request-presigner": "^3.700.0",
"@nestjs/bullmq": "^10.2.3",
"@nestjs/common": "^10.4.15",
@@ -42,12 +43,14 @@
"dayjs": "^1.11.13",
"exceljs": "^4.4.0",
"ioredis": "^5.4.2",
"multer": "2.2.0",
"nanoid": "^3.3.8",
"prisma": "^5.22.0",
"qrcode": "^1.5.4",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"sharp": "^0.33.5"
"sharp": "^0.33.5",
"unzipper": "0.10.14"
},
"devDependencies": {
"@nestjs/cli": "^10.4.9",
+11
View File
@@ -0,0 +1,11 @@
# 出库批量导入模板维护
`outbound-import-template.zip` 是后台“下载模板包”接口直接返回的静态文件。需要调整 Excel 文案、样式或示例图片时,解压修改后重新压缩并替换该文件即可,不需要修改接口代码。
模板必须与批量导入解析契约保持一致:
- ZIP 根目录必须且只能包含一个 `.xlsx` 文件;存在出库图时,图片放在 `images/` 目录。
- xlsx 第一张工作表是实际导入表,表头必须使用共享常量 `OUTBOUND_IMPORT_COLUMNS` 定义的列名。
- 实际导入表不要预置示例数据;示例可放在后续工作表。
- 单个 xlsx、单张图片均不得超过 100MB;图片仅支持 JPG、JPEG、PNG、WebP,且不得超过 4000 万像素,不支持多帧图片。
- 更新后运行 `pnpm --filter @artveris/api exec jest --runInBand src/outbound/outbound.service.spec.ts`,测试会校验 ZIP 结构、表头、说明和示例图片。
+3 -1
View File
@@ -116,7 +116,9 @@ async function bootstrap(): Promise<void> {
SwaggerModule.setup('api/docs', app, document);
const port = config.get<number>('port') || 3000;
await app.listen(port);
const server = await app.listen(port);
// 大包不设体积上限,但所有请求仍需在一小时内完成接收,避免慢连接无限占用。
server.requestTimeout = 60 * 60 * 1000;
logger.log(`${installing ? 'Install server' : 'API'} started: http://localhost:${port}/api`);
logger.log(`Swagger: http://localhost:${port}/api/docs`);
}
@@ -1,5 +1,6 @@
import AdmZip from 'adm-zip';
import * as ExcelJS from 'exceljs';
import { writeFile } from 'fs/promises';
import sharp from 'sharp';
import { JobStatus, OUTBOUND_IMPORT_COLUMNS } from '@artveris/shared';
import { ImportPreviewProcessor } from './import-preview.processor';
@@ -12,6 +13,7 @@ interface ZipOptions {
rows?: SheetCell[][];
images?: Record<string, Buffer>;
sparseRow?: number;
comment?: string;
}
async function buildZip(options: ZipOptions = {}): Promise<Buffer> {
@@ -24,6 +26,7 @@ async function buildZip(options: ZipOptions = {}): Promise<Buffer> {
const zip = new AdmZip();
zip.addFile('outbound.xlsx', Buffer.from(await workbook.xlsx.writeBuffer()));
for (const [path, data] of Object.entries(options.images ?? {})) zip.addFile(path, data);
if (options.comment) zip.addZipComment(options.comment);
return zip.toBuffer();
}
@@ -35,6 +38,12 @@ async function png(): Promise<Buffer> {
return sharp({ create: { width: 8, height: 8, channels: 4, background: '#ffffff' } }).png().toBuffer();
}
async function oversizedPng(): Promise<Buffer> {
return sharp({ create: { width: 6325, height: 6325, channels: 3, background: '#000000' } })
.png({ compressionLevel: 9, palette: true })
.toBuffer();
}
function traceCode(shortCode: string, batchNo = 'B1') {
return { id: BigInt(shortCode), shortCode, outTime: null, outImages: null, batch: { batchNo } };
}
@@ -74,7 +83,9 @@ function createHarness(zipBuffer: Buffer, codes: any[] = []) {
),
};
const storage = {
read: jest.fn().mockResolvedValue(zipBuffer),
downloadToFile: jest.fn().mockImplementation(async (_key: string, filePath: string) => {
await writeFile(filePath, zipBuffer);
}),
save: jest.fn().mockImplementation(async (_data: Buffer, name: string) => {
savedSequence += 1;
return { key: `temp/${savedSequence}-${name}`, url: `/uploads/${savedSequence}-${name}`, name };
@@ -83,6 +94,7 @@ function createHarness(zipBuffer: Buffer, codes: any[] = []) {
};
const jobs = {
start: jest.fn().mockResolvedValue(undefined),
progress: jest.fn().mockResolvedValue({ count: 1 }),
finish: jest.fn().mockResolvedValue(undefined),
};
const processor = new ImportPreviewProcessor(prisma as any, storage as any, jobs as any);
@@ -96,6 +108,18 @@ async function process(processor: ImportPreviewProcessor): Promise<void> {
}
describe('ImportPreviewProcessor', () => {
it('accepts a valid ZIP with a long archive comment', async () => {
const zip = await buildZip({
rows: [['111111111111', 'B1', '2026-07-04 10:00', '', '']],
comment: 'x'.repeat(100),
});
const harness = createHarness(zip, [traceCode('111111111111')]);
await process(harness.processor);
expect(harness.persistedRows[0]).toMatchObject({ status: 'VALID' });
});
it('interprets an Excel date cell as a Shanghai wall-clock value', async () => {
const zip = await buildZip({
rows: [['111111111111', 'B1', new Date('2026-07-04T10:00:00.000Z'), '', '']],
@@ -187,7 +211,7 @@ describe('ImportPreviewProcessor', () => {
await process(harness.processor);
expect(harness.storage.save).not.toHaveBeenCalled();
expect(harness.storage.remove).not.toHaveBeenCalled();
expect(harness.storage.remove).toHaveBeenCalledWith('zip-key');
expect(harness.persistedRows[0]).toMatchObject({
status: 'INVALID',
reason: '图片不存在:images/missing.jpg',
@@ -216,6 +240,33 @@ describe('ImportPreviewProcessor', () => {
});
});
it('cleans a saved image when the preview heartbeat loses ownership after the storage write', async () => {
const zip = await buildZip({
rows: [['111111111111', 'B1', '2026-07-04 10:00', 'images/front.jpg', '']],
images: { 'images/front.jpg': await jpeg() },
});
const harness = createHarness(zip, [traceCode('111111111111')]);
let now = 0;
const clock = jest.spyOn(Date, 'now').mockImplementation(() => now);
harness.storage.save.mockImplementationOnce(async () => {
now = 61_000;
return { key: 'temp/saved-before-heartbeat.jpg', url: '/uploads/saved.jpg', name: 'front.jpg' };
});
harness.jobs.progress.mockResolvedValueOnce({ count: 1 }).mockResolvedValueOnce({ count: 0 });
try {
await process(harness.processor);
} finally {
clock.mockRestore();
}
expect(harness.storage.remove).toHaveBeenCalledWith('temp/saved-before-heartbeat.jpg');
expect(harness.persistedRows[0]).toMatchObject({
status: 'INVALID',
reason: '导入预览任务状态已变化',
outImageKeys: null,
});
});
it('does not replace rows when a stalled preview worker loses the session claim', async () => {
const zip = await buildZip({
rows: [['111111111111', 'B1', '2026-07-04 10:00', 'images/front.jpg', '']],
@@ -249,7 +300,7 @@ describe('ImportPreviewProcessor', () => {
await process(harness.processor);
expect(harness.storage.read).not.toHaveBeenCalled();
expect(harness.storage.downloadToFile).not.toHaveBeenCalled();
expect(harness.jobs.start).not.toHaveBeenCalled();
expect(harness.jobs.finish).toHaveBeenCalledWith('job-1', {
status: JobStatus.SUCCESS,
@@ -257,6 +308,7 @@ describe('ImportPreviewProcessor', () => {
failCount: 0,
error: null,
});
expect(harness.storage.remove).toHaveBeenCalledWith('zip-key');
});
it('keeps images referenced by rows when the preview transaction result is unknown', async () => {
@@ -302,6 +354,22 @@ describe('ImportPreviewProcessor', () => {
});
});
it('rejects an image over 40 million pixels with a localized error', async () => {
const zip = await buildZip({
rows: [['111111111111', 'B1', '2026-07-04 10:00', 'images/oversized.png', '']],
images: { 'images/oversized.png': await oversizedPng() },
});
const harness = createHarness(zip, [traceCode('111111111111')]);
await process(harness.processor);
expect(harness.storage.save).not.toHaveBeenCalled();
expect(harness.persistedRows[0]).toMatchObject({
status: 'INVALID',
reason: '图片像素尺寸超过限制:images/oversized.png',
});
});
it('rejects a worksheet whose declared row count exceeds the limit', async () => {
const zip = await buildZip({ sparseRow: OUTBOUND_IMPORT_MAX_ROWS + 2 });
const harness = createHarness(zip);
+125 -33
View File
@@ -1,8 +1,9 @@
import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Logger } from '@nestjs/common';
import { Job } from 'bullmq';
import AdmZip from 'adm-zip';
import { mkdtemp, rm } from 'fs/promises';
import * as ExcelJS from 'exceljs';
import { join } from 'path';
import sharp from 'sharp';
import { JobStatus, OUTBOUND_IMPORT_COLUMNS, QUEUE_NAMES, TRACE_CODE_PATTERN } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
@@ -11,10 +12,13 @@ import { JobsService } from '../jobs/jobs.service';
import { isOutbound } from './outbound.util';
import {
assertArchiveLimits,
assertArchiveActualSize,
assertStoredImageBudget,
assertZipEntryCount,
canonicalImagePath,
cellToString,
ensureOutboundImportTempDir,
inspectZipFile,
mimeOfImagePath,
normalizeImagePath,
OUTBOUND_IMPORT_MAX_COLUMNS,
@@ -22,14 +26,19 @@ import {
OUTBOUND_IMPORT_MAX_IMAGE_SIZE,
OUTBOUND_IMPORT_MAX_IMAGES_PER_ROW,
OUTBOUND_IMPORT_MAX_ROWS,
OUTBOUND_IMPORT_MAX_UNCOMPRESSED_SIZE,
OUTBOUND_IMPORT_STORAGE_TIMEOUT_MS,
OUTBOUND_IMPORT_PREVIEW_TEMP_PREFIX,
OUTBOUND_IMPORT_TEMP_DIR,
OUTBOUND_IMPORT_MAX_XLSX_ENTRIES,
OUTBOUND_IMPORT_MAX_XLSX_SIZE,
OUTBOUND_IMPORT_MAX_XLSX_UNCOMPRESSED_SIZE,
OUTBOUND_IMPORT_MAX_ZIP_ENTRIES,
parseOutboundDate,
readArchiveEntryBuffer,
} from './outbound-import.util';
const unzipper: any = require('unzipper');
interface PreviewJobData {
jobId: string;
sessionId: string;
@@ -48,6 +57,11 @@ interface StoredImage {
type: string;
}
interface ArchivedImage {
path: string;
entry: { stream: () => NodeJS.ReadableStream };
}
@Processor(QUEUE_NAMES.IMPORT_OUTBOUND_PREVIEW)
export class ImportPreviewProcessor extends WorkerHost {
private readonly logger = new Logger(ImportPreviewProcessor.name);
@@ -64,6 +78,7 @@ export class ImportPreviewProcessor extends WorkerHost {
const { jobId, sessionId, fileKey } = job.data;
const createdImageKeys = new Set<string>();
let rowsPersisted = false;
let workingDir = '';
try {
const session = await this.prisma.outboundImportSession.findUnique({
where: { id: sessionId },
@@ -78,6 +93,9 @@ export class ImportPreviewProcessor extends WorkerHost {
},
});
if (!session) {
await this.storage.remove(fileKey).catch((error) =>
this.logger.warn(`清理无会话出库导入 ZIP 失败:${fileKey} ${(error as Error).message}`),
);
await this.jobs
.finish(jobId, { status: JobStatus.FAILED, error: '导入预览会话不存在' })
.catch(() => undefined);
@@ -99,6 +117,7 @@ export class ImportPreviewProcessor extends WorkerHost {
failCount: session.invalidCount,
error: session.error,
});
await this.removeSourceArchive(sessionId, session.fileKey || fileKey);
return;
}
if (session.fileKey !== fileKey) {
@@ -117,47 +136,77 @@ export class ImportPreviewProcessor extends WorkerHost {
return jobClaim.count === 1;
});
if (!started) return;
const buffer = await this.storage.read(fileKey);
assertZipEntryCount(buffer, OUTBOUND_IMPORT_MAX_ZIP_ENTRIES, 'ZIP ');
const zip = new AdmZip(buffer);
const entries = zip.getEntries();
let lastHeartbeatAt = Date.now();
const heartbeat = async (successCount: number, failCount: number, force = false) => {
if (!force && Date.now() - lastHeartbeatAt < 60_000) return;
const touched = await this.jobs.progress(jobId, successCount, failCount);
if (touched.count !== 1) throw new Error('导入预览任务状态已变化');
lastHeartbeatAt = Date.now();
};
await ensureOutboundImportTempDir();
workingDir = await mkdtemp(join(OUTBOUND_IMPORT_TEMP_DIR, OUTBOUND_IMPORT_PREVIEW_TEMP_PREFIX));
const archivePath = join(workingDir, 'source.zip');
await this.storage.downloadToFile(fileKey, archivePath, {
requestTimeoutMs: OUTBOUND_IMPORT_STORAGE_TIMEOUT_MS,
});
await heartbeat(0, 0, true);
const archiveTailSize = await inspectZipFile(archivePath, OUTBOUND_IMPORT_MAX_ZIP_ENTRIES, 'ZIP ');
const archive = await unzipper.Open.file(archivePath, { tailSize: archiveTailSize });
const entries: any[] = archive.files;
assertArchiveLimits(
entries,
entries.map((entry) => ({
isDirectory: entry.type === 'Directory',
header: { size: Number(entry.uncompressedSize) },
})),
OUTBOUND_IMPORT_MAX_ZIP_ENTRIES,
OUTBOUND_IMPORT_MAX_UNCOMPRESSED_SIZE,
undefined,
'ZIP ',
);
const files = entries.filter((entry) => !entry.isDirectory);
const xlsxEntries = files.filter((entry) => entry.entryName.replace(/\\/g, '/').toLowerCase().endsWith('.xlsx'));
const files = entries.filter((entry) => entry.type === 'File');
const xlsxEntries = files.filter((entry) => entry.path.replace(/\\/g, '/').toLowerCase().endsWith('.xlsx'));
if (xlsxEntries.length !== 1) throw new Error('ZIP 中必须且只能包含一个 xlsx 文件');
const xlsxName = xlsxEntries[0].entryName.replace(/\\/g, '/');
const xlsxName = xlsxEntries[0].path.replace(/\\/g, '/');
if (xlsxName.includes('/')) throw new Error('xlsx 文件必须位于 ZIP 根目录');
if (Number(xlsxEntries[0].uncompressedSize) > OUTBOUND_IMPORT_MAX_XLSX_SIZE) {
throw new Error('xlsx 文件超过 100MB');
}
const xlsxBuffer = xlsxEntries[0].getData();
if (xlsxBuffer.length > OUTBOUND_IMPORT_MAX_XLSX_SIZE) throw new Error('xlsx 文件超过 10MB');
assertZipEntryCount(xlsxBuffer, OUTBOUND_IMPORT_MAX_XLSX_ENTRIES, 'xlsx ');
const xlsxArchive = new AdmZip(xlsxBuffer);
const xlsxBuffer = await readArchiveEntryBuffer(
xlsxEntries[0],
OUTBOUND_IMPORT_MAX_XLSX_SIZE,
'xlsx 文件超过 100MB',
() => heartbeat(0, 0),
);
const xlsxTailSize = assertZipEntryCount(xlsxBuffer, OUTBOUND_IMPORT_MAX_XLSX_ENTRIES, 'xlsx ');
const xlsxArchive = await unzipper.Open.buffer(xlsxBuffer, { tailSize: xlsxTailSize });
const xlsxLimitEntries = xlsxArchive.files.map((entry: any) => ({
isDirectory: entry.type === 'Directory',
header: { size: Number(entry.uncompressedSize) },
stream: () => entry.stream(),
}));
assertArchiveLimits(
xlsxArchive.getEntries(),
xlsxLimitEntries,
OUTBOUND_IMPORT_MAX_XLSX_ENTRIES,
OUTBOUND_IMPORT_MAX_XLSX_UNCOMPRESSED_SIZE,
'xlsx ',
);
await assertArchiveActualSize(
xlsxLimitEntries,
OUTBOUND_IMPORT_MAX_XLSX_UNCOMPRESSED_SIZE,
'xlsx ',
() => heartbeat(0, 0),
);
const imageEntries = new Map<string, { path: string; data: Buffer }>();
let extractedSize = xlsxBuffer.length;
const imageEntries = new Map<string, ArchivedImage>();
for (const entry of files) {
const name = entry.entryName.replace(/\\/g, '/');
const name = entry.path.replace(/\\/g, '/');
if (name === xlsxName || name === '说明.txt') continue;
const path = normalizeImagePath(name);
const canonical = canonicalImagePath(path);
if (imageEntries.has(canonical)) throw new Error(`ZIP 中存在重复图片路径:${path}`);
const data = entry.getData();
extractedSize += data.length;
if (extractedSize > OUTBOUND_IMPORT_MAX_UNCOMPRESSED_SIZE) throw new Error('ZIP 解压后总大小超过限制');
if (data.length > OUTBOUND_IMPORT_MAX_IMAGE_SIZE) throw new Error(`图片超过 10MB:${path}`);
imageEntries.set(canonical, { path, data });
if (Number(entry.uncompressedSize) > OUTBOUND_IMPORT_MAX_IMAGE_SIZE) throw new Error(`图片超过 100MB:${path}`);
imageEntries.set(canonical, { path, entry });
}
const workbook = new ExcelJS.Workbook();
@@ -226,7 +275,6 @@ export class ImportPreviewProcessor extends WorkerHost {
let valid = 0;
let invalid = 0;
let imageReferenceCount = 0;
let storedImageBytes = 0;
const validatedImagePaths = new Set<string>();
for (const { rowNo, values } of sheetRows) {
@@ -270,7 +318,7 @@ export class ImportPreviewProcessor extends WorkerHost {
}
const imagePaths = rawImagePaths.map(normalizeImagePath);
const imagePathSet = new Set<string>();
const images: Array<{ path: string; data: Buffer }> = [];
const images: ArchivedImage[] = [];
for (const path of imagePaths) {
const canonical = canonicalImagePath(path);
if (imagePathSet.has(canonical)) throw new Error(`同一行重复引用图片:${path}`);
@@ -279,16 +327,29 @@ export class ImportPreviewProcessor extends WorkerHost {
if (!image) throw new Error(`图片不存在:${path}`);
images.push(image);
}
const rowImageBytes = images.reduce((sum, image) => sum + image.data.length, 0);
imageReferenceCount += images.length;
storedImageBytes += rowImageBytes;
assertStoredImageBudget(imageReferenceCount, storedImageBytes);
assertStoredImageBudget(imageReferenceCount);
for (const image of images) {
const path = image.path;
const canonical = canonicalImagePath(path);
if (validatedImagePaths.has(canonical)) continue;
const metadata = await sharp(image.data, { limitInputPixels: OUTBOUND_IMPORT_MAX_IMAGE_PIXELS }).metadata();
const data = await readArchiveEntryBuffer(
image.entry as any,
OUTBOUND_IMPORT_MAX_IMAGE_SIZE,
`图片超过 100MB:${path}`,
() => heartbeat(valid, invalid),
);
let metadata;
try {
metadata = await sharp(data, { limitInputPixels: OUTBOUND_IMPORT_MAX_IMAGE_PIXELS }).metadata();
} catch (error) {
if (/pixel limit/i.test((error as Error).message)) {
throw new Error(`图片像素尺寸超过限制:${path}`);
}
throw error;
}
await heartbeat(valid, invalid);
const expectedFormat = path.toLowerCase().endsWith('.png')
? 'png'
: path.toLowerCase().endsWith('.webp')
@@ -305,13 +366,21 @@ export class ImportPreviewProcessor extends WorkerHost {
const imageItems: StoredImage[] = [];
result.outImageKeys = imageItems;
for (const image of images) {
const data = await readArchiveEntryBuffer(
image.entry as any,
OUTBOUND_IMPORT_MAX_IMAGE_SIZE,
`图片超过 100MB:${image.path}`,
() => heartbeat(valid, invalid),
);
const saved = await this.storage.save(
image.data,
data,
image.path.split('/').pop() || 'outbound.jpg',
mimeOfImagePath(image.path),
{ requestTimeoutMs: OUTBOUND_IMPORT_STORAGE_TIMEOUT_MS },
);
createdImageKeys.add(saved.key);
imageItems.push({ key: saved.key, url: saved.url, name: saved.name, type: 'image' });
await heartbeat(valid, invalid);
}
Object.assign(result, {
@@ -339,6 +408,7 @@ export class ImportPreviewProcessor extends WorkerHost {
invalid++;
}
rows.push(result);
await heartbeat(valid, invalid);
}
await this.prisma.$transaction(async (tx) => {
@@ -369,6 +439,7 @@ export class ImportPreviewProcessor extends WorkerHost {
});
}, { timeout: 60_000 });
rowsPersisted = true;
await this.removeSourceArchive(sessionId, fileKey);
} catch (error) {
const message = (error as Error).message;
if (!rowsPersisted) {
@@ -396,7 +467,7 @@ export class ImportPreviewProcessor extends WorkerHost {
}
}
}
await this.prisma
const failed = await this.prisma
.$transaction(async (tx) => {
const failed = await tx.outboundImportSession.updateMany({
where: { id: sessionId, status: 'PARSING', previewJobId: jobId },
@@ -405,9 +476,30 @@ export class ImportPreviewProcessor extends WorkerHost {
if (failed.count === 1) {
await tx.job.update({ where: { id: jobId }, data: { status: JobStatus.FAILED, error: message } });
}
return failed.count === 1;
})
.catch(() => undefined);
.catch(() => false);
if (failed) await this.removeSourceArchive(sessionId, fileKey);
this.logger.error(`导入预览失败:${message}`);
} finally {
if (workingDir) {
await rm(workingDir, { recursive: true, force: true }).catch((error) =>
this.logger.warn(`清理出库导入 Worker 临时目录失败:${workingDir} ${(error as Error).message}`),
);
}
}
}
private async removeSourceArchive(sessionId: string, fileKey: string): Promise<void> {
if (!fileKey) return;
try {
await this.storage.remove(fileKey);
await this.prisma.outboundImportSession.updateMany({
where: { id: sessionId, fileKey },
data: { fileKey: null },
});
} catch (error) {
this.logger.warn(`清理出库导入原始 ZIP 失败:${fileKey} ${(error as Error).message}`);
}
}
}
@@ -273,6 +273,7 @@ describe('ImportProcessor', () => {
'1/ARTVERIS-000001/111111111111',
'出库实况',
expect.any(Function),
{ requestTimeoutMs: 3_600_000 },
);
expect(harness.tx.outboundImportRow.updateMany).toHaveBeenCalledWith({
where: { id: 1n, status: 'VALID' },
+2 -1
View File
@@ -8,6 +8,7 @@ import { PrismaService } from '../prisma/prisma.service';
import { StorageService } from '../storage/storage.service';
import { JobsService } from '../jobs/jobs.service';
import { isOutbound } from './outbound.util';
import { OUTBOUND_IMPORT_STORAGE_TIMEOUT_MS } from './outbound-import.util';
interface ImportJobData {
jobId: string;
@@ -237,7 +238,7 @@ export class ImportProcessor extends WorkerHost {
});
if (registered.count !== 1) throw new ImportRunSupersededError();
});
});
}, { requestTimeoutMs: OUTBOUND_IMPORT_STORAGE_TIMEOUT_MS });
sourceKeys = [...copied.keyMap.keys()];
copiedKeys = [...copied.keyMap.values()];
imageItems = copied.items.map((item) => ({
@@ -257,6 +257,43 @@ describe('OutboundImportCleanupService', () => {
expect(previewQueue.add).not.toHaveBeenCalled();
});
it('uses a longer stale window for large preview processing jobs', async () => {
await service.requeuePendingImports();
expect(prisma.job.findMany).toHaveBeenCalledWith(expect.objectContaining({
where: expect.objectContaining({
OR: expect.arrayContaining([
{
type: JobType.IMPORT_OUTBOUND_PREVIEW,
status: JobStatus.PROCESSING,
updatedAt: { lt: new Date('2026-07-13T06:00:00.000Z') },
},
]),
}),
}));
});
it('removes a raw ZIP as soon as its preview session is terminal', async () => {
prisma.outboundImportSession.findMany.mockResolvedValue([{
id: 'session-ready',
status: OutboundImportSessionStatus.READY,
fileKey: '.private/import.zip',
}]);
prisma.outboundImportSession.updateMany.mockResolvedValue({ count: 1 });
await service.cleanupTerminalArchiveFiles();
expect(storage.remove).toHaveBeenCalledWith('.private/import.zip');
expect(prisma.outboundImportSession.updateMany).toHaveBeenCalledWith({
where: {
id: 'session-ready',
status: OutboundImportSessionStatus.READY,
fileKey: '.private/import.zip',
},
data: { fileKey: null },
});
});
it('retries a failed BullMQ preview job without creating a duplicate', async () => {
const queued = { getState: jest.fn().mockResolvedValue('failed'), retry: jest.fn().mockResolvedValue(undefined) };
prisma.job.findMany.mockResolvedValue([{
@@ -9,9 +9,17 @@ import {
Prisma,
} from '@prisma/client';
import { Queue } from 'bullmq';
import { readdir, rm } from 'fs/promises';
import { join } from 'path';
import { QUEUE_NAMES } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { StorageService } from '../storage/storage.service';
import {
ensureOutboundImportTempDir,
OUTBOUND_IMPORT_TEMP_DIR,
OUTBOUND_IMPORT_UPLOAD_TEMP_PREFIX,
OUTBOUND_IMPORT_PREVIEW_TEMP_PREFIX,
} from './outbound-import.util';
function collectImageKeys(value: Prisma.JsonValue | null): string[] {
if (!Array.isArray(value)) return [];
@@ -33,6 +41,9 @@ function collectPreviewKeys(value: Prisma.JsonValue | null): string[] {
return [...collectImageKeys(preview.images ?? null), ...pending];
}
const IMPORT_PROCESSING_STALE_MS = 15 * 60_000;
const PREVIEW_PROCESSING_STALE_MS = 2 * 60 * 60_000;
@Injectable()
export class OutboundImportCleanupService implements OnModuleInit {
private readonly logger = new Logger(OutboundImportCleanupService.name);
@@ -45,9 +56,52 @@ export class OutboundImportCleanupService implements OnModuleInit {
) {}
async onModuleInit(): Promise<void> {
await this.cleanupOrphanedLocalTempFiles();
await this.cleanupTerminalArchiveFiles();
await this.requeuePendingImports();
}
private async cleanupOrphanedLocalTempFiles(): Promise<void> {
await ensureOutboundImportTempDir();
const entries = await readdir(OUTBOUND_IMPORT_TEMP_DIR, { withFileTypes: true });
let removed = 0;
for (const entry of entries) {
if (!entry.name.startsWith(OUTBOUND_IMPORT_UPLOAD_TEMP_PREFIX)
&& !entry.name.startsWith(OUTBOUND_IMPORT_PREVIEW_TEMP_PREFIX)) continue;
try {
await rm(join(OUTBOUND_IMPORT_TEMP_DIR, entry.name), { recursive: true, force: true });
removed++;
} catch (error) {
this.logger.warn(`清理遗留出库导入临时文件失败:${entry.name} ${(error as Error).message}`);
}
}
if (removed) this.logger.log(`已清理遗留出库导入临时文件:${removed}`);
}
@Cron(CronExpression.EVERY_HOUR)
async cleanupTerminalArchiveFiles(): Promise<void> {
const sessions = await this.prisma.outboundImportSession.findMany({
where: {
fileKey: { not: null },
status: { not: OutboundImportSessionStatus.PARSING },
},
select: { id: true, status: true, fileKey: true },
take: 50,
});
for (const session of sessions) {
if (!session.fileKey) continue;
try {
await this.storage.remove(session.fileKey);
await this.prisma.outboundImportSession.updateMany({
where: { id: session.id, status: session.status, fileKey: session.fileKey },
data: { fileKey: null },
});
} catch (error) {
this.logger.warn(`清理终态出库导入 ZIP 失败:${session.fileKey} ${(error as Error).message}`);
}
}
}
@Cron(CronExpression.EVERY_MINUTE)
async requeuePendingImports(): Promise<void> {
const now = Date.now();
@@ -56,7 +110,16 @@ export class OutboundImportCleanupService implements OnModuleInit {
type: { in: [JobType.IMPORT_OUTBOUND, JobType.IMPORT_OUTBOUND_PREVIEW] },
OR: [
{ status: JobStatus.PENDING, updatedAt: { lt: new Date(now - 30_000) } },
{ status: JobStatus.PROCESSING, updatedAt: { lt: new Date(now - 15 * 60_000) } },
{
type: JobType.IMPORT_OUTBOUND,
status: JobStatus.PROCESSING,
updatedAt: { lt: new Date(now - IMPORT_PROCESSING_STALE_MS) },
},
{
type: JobType.IMPORT_OUTBOUND_PREVIEW,
status: JobStatus.PROCESSING,
updatedAt: { lt: new Date(now - PREVIEW_PROCESSING_STALE_MS) },
},
],
},
orderBy: { createdAt: 'asc' },
@@ -1,14 +1,23 @@
import {
assertArchiveActualSize,
assertArchiveLimits,
assertStoredImageBudget,
assertZipEntryCount,
canonicalImagePath,
cellToString,
inspectZipFile,
mimeOfImagePath,
normalizeImagePath,
OUTBOUND_IMPORT_MAX_IMAGE_SIZE,
OUTBOUND_IMPORT_MAX_XLSX_SIZE,
parseOutboundDate,
readArchiveEntryBuffer,
} from './outbound-import.util';
import AdmZip from 'adm-zip';
import { mkdtemp, rm, writeFile } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
import { Readable } from 'stream';
describe('outbound import utilities', () => {
describe('parseOutboundDate', () => {
@@ -99,6 +108,41 @@ describe('parseOutboundDate', () => {
expect(() => assertZipEntryCount(buffer, 1, 'ZIP')).toThrow('ZIP文件数量超过限制(最多 1 个)');
expect(() => assertZipEntryCount(Buffer.from('not a zip'), 2, 'ZIP')).toThrow('ZIP文件结构无效');
});
it('locates the real end record behind a long ZIP comment on disk', async () => {
const zip = new AdmZip();
zip.addFile('one.txt', Buffer.from('1'));
zip.addZipComment('x'.repeat(100));
const buffer = zip.toBuffer();
const dir = await mkdtemp(join(tmpdir(), 'artveris-zip-inspect-'));
const filePath = join(dir, 'commented.zip');
await writeFile(filePath, buffer);
try {
expect(assertZipEntryCount(buffer, 1, 'ZIP')).toBe(122);
await expect(inspectZipFile(filePath, 1, 'ZIP')).resolves.toBe(122);
} finally {
await rm(dir, { recursive: true, force: true });
}
});
it('reads the real entry count from a ZIP64 end record', () => {
const buffer = Buffer.alloc(56 + 20 + 22);
buffer.writeUInt32LE(0x06064b50, 0);
buffer.writeBigUInt64LE(44n, 4);
buffer.writeBigUInt64LE(2n, 24);
buffer.writeBigUInt64LE(2n, 32);
buffer.writeUInt32LE(0x07064b50, 56);
buffer.writeBigUInt64LE(0n, 64);
buffer.writeUInt32LE(1, 72);
buffer.writeUInt32LE(0x06054b50, 76);
buffer.writeUInt16LE(0xffff, 84);
buffer.writeUInt16LE(0xffff, 86);
buffer.writeUInt32LE(0xffffffff, 88);
buffer.writeUInt32LE(0xffffffff, 92);
expect(assertZipEntryCount(buffer, 2, 'ZIP')).toBe(22);
expect(() => assertZipEntryCount(buffer, 1, 'ZIP')).toThrow('ZIP文件数量超过限制(最多 1 个)');
});
});
describe('assertArchiveLimits', () => {
@@ -121,6 +165,10 @@ describe('parseOutboundDate', () => {
).not.toThrow();
});
it('validates entry metadata without imposing an aggregate byte limit when none is configured', () => {
expect(() => assertArchiveLimits([file(100 * 1024 * 1024), file(100 * 1024 * 1024)], 2, undefined, 'ZIP')).not.toThrow();
});
it.each([-1, Number.NaN, Number.POSITIVE_INFINITY, 1.5, Number.MAX_SAFE_INTEGER + 1])(
'rejects an invalid entry size: %s',
(size) => {
@@ -143,7 +191,33 @@ describe('cellToString', () => {
describe('assertStoredImageBudget', () => {
it('rejects output amplification by repeated image references', () => {
expect(() => assertStoredImageBudget(20_001, 1)).toThrow('出库图片引用总数超过限制');
expect(() => assertStoredImageBudget(1, 200 * 1024 * 1024 + 1)).toThrow('出库图片按引用累计大小超过限制');
expect(() => assertStoredImageBudget(20_001)).toThrow('出库图片引用总数超过限制');
});
});
describe('streamed archive limits', () => {
const streamed = (...chunks: Buffer[]) => ({
isDirectory: false,
header: { size: chunks.reduce((total, chunk) => total + chunk.length, 0) },
stream: () => Readable.from(chunks),
});
it('allows the exact entry byte limit and rejects the next byte before concatenation', async () => {
await expect(readArchiveEntryBuffer(streamed(Buffer.from('ab'), Buffer.from('c')), 3, 'too large'))
.resolves.toEqual(Buffer.from('abc'));
await expect(readArchiveEntryBuffer(streamed(Buffer.from('ab'), Buffer.from('cd')), 3, 'too large'))
.rejects.toThrow('too large');
});
it('measures actual expanded bytes instead of trusting declared archive sizes', async () => {
const disguised = { ...streamed(Buffer.from('abcd')), header: { size: 1 } };
await expect(assertArchiveActualSize([disguised], 3, 'xlsx '))
.rejects.toThrow('xlsx 解压后总大小超过限制');
});
});
it('allows 100MB for one image and one xlsx file', () => {
expect(OUTBOUND_IMPORT_MAX_IMAGE_SIZE).toBe(100 * 1024 * 1024);
expect(OUTBOUND_IMPORT_MAX_XLSX_SIZE).toBe(100 * 1024 * 1024);
});
+163 -20
View File
@@ -1,40 +1,129 @@
import { mkdir, open } from 'fs/promises';
import { tmpdir } from 'os';
import { resolve } from 'path';
import { Readable } from 'stream';
export const OUTBOUND_IMPORT_MAX_ROWS = 10_000;
export const OUTBOUND_IMPORT_MAX_COLUMNS = 64;
export const OUTBOUND_IMPORT_MAX_ZIP_ENTRIES = 20_002;
export const OUTBOUND_IMPORT_MAX_UNCOMPRESSED_SIZE = 120 * 1024 * 1024;
export const OUTBOUND_IMPORT_MAX_XLSX_SIZE = 10 * 1024 * 1024;
export const OUTBOUND_IMPORT_MAX_XLSX_SIZE = 100 * 1024 * 1024;
export const OUTBOUND_IMPORT_MAX_XLSX_ENTRIES = 256;
export const OUTBOUND_IMPORT_MAX_XLSX_UNCOMPRESSED_SIZE = 50 * 1024 * 1024;
export const OUTBOUND_IMPORT_MAX_IMAGE_SIZE = 10 * 1024 * 1024;
export const OUTBOUND_IMPORT_MAX_XLSX_UNCOMPRESSED_SIZE = 500 * 1024 * 1024;
export const OUTBOUND_IMPORT_MAX_IMAGE_SIZE = 100 * 1024 * 1024;
export const OUTBOUND_IMPORT_MAX_IMAGES_PER_ROW = 20;
export const OUTBOUND_IMPORT_MAX_IMAGE_PIXELS = 40_000_000;
export const OUTBOUND_IMPORT_MAX_IMAGE_REFERENCES = 20_000;
export const OUTBOUND_IMPORT_MAX_STORED_IMAGE_SIZE = 200 * 1024 * 1024;
export const OUTBOUND_IMPORT_STORAGE_TIMEOUT_MS = 60 * 60 * 1000;
export const OUTBOUND_IMPORT_TEMP_DIR = resolve(process.env.ARTVERIS_OUTBOUND_TEMP_DIR || tmpdir());
export const OUTBOUND_IMPORT_UPLOAD_TEMP_PREFIX = 'artveris-outbound-upload-';
export const OUTBOUND_IMPORT_PREVIEW_TEMP_PREFIX = 'artveris-outbound-preview-';
const ARCHIVE_PROGRESS_INTERVAL_BYTES = 8 * 1024 * 1024;
const ZIP_END_RECORD_MAX_SIZE = 65_557;
const ZIP_END_RECORD_MIN_SIZE = 22;
const ZIP64_LOCATOR_SIZE = 20;
const ZIP64_END_RECORD_MIN_SIZE = 56;
const ZIP_END_SIGNATURE = 0x06054b50;
const ZIP64_LOCATOR_SIGNATURE = 0x07064b50;
const ZIP64_END_SIGNATURE = 0x06064b50;
export async function ensureOutboundImportTempDir(): Promise<void> {
await mkdir(OUTBOUND_IMPORT_TEMP_DIR, { recursive: true });
}
interface ArchiveEntryLike {
isDirectory: boolean;
header: { size: number };
}
export function assertZipEntryCount(buffer: Buffer, maxEntries: number, label: string): void {
const minEndOffset = Math.max(0, buffer.length - 65_557);
for (let offset = buffer.length - 22; offset >= minEndOffset; offset--) {
if (buffer.readUInt32LE(offset) !== 0x06054b50) continue;
interface ArchiveStreamEntryLike extends ArchiveEntryLike {
stream: () => Readable;
}
function findZipEndRecordOffset(buffer: Buffer, label: string): number {
const minEndOffset = Math.max(0, buffer.length - ZIP_END_RECORD_MAX_SIZE);
for (let offset = buffer.length - ZIP_END_RECORD_MIN_SIZE; offset >= minEndOffset; offset--) {
if (buffer.readUInt32LE(offset) !== ZIP_END_SIGNATURE) continue;
const commentLength = buffer.readUInt16LE(offset + 20);
if (offset + 22 + commentLength !== buffer.length) continue;
const entries = buffer.readUInt16LE(offset + 10);
if (entries === 0xffff || entries > maxEntries) {
throw new Error(`${label}文件数量超过限制(最多 ${maxEntries} 个)`);
}
return;
if (offset + ZIP_END_RECORD_MIN_SIZE + commentLength !== buffer.length) continue;
return offset;
}
throw new Error(`${label}文件结构无效`);
}
function assertZipEntryCountValue(entries: bigint, maxEntries: number, label: string): void {
if (entries > BigInt(maxEntries)) {
throw new Error(`${label}文件数量超过限制(最多 ${maxEntries} 个)`);
}
}
function usesZip64(buffer: Buffer, endOffset: number): boolean {
return buffer.readUInt16LE(endOffset + 10) === 0xffff
|| buffer.readUInt32LE(endOffset + 12) === 0xffffffff
|| buffer.readUInt32LE(endOffset + 16) === 0xffffffff;
}
function readZip64EntryCount(buffer: Buffer, endOffset: number, label: string): bigint {
const locatorOffset = endOffset - ZIP64_LOCATOR_SIZE;
if (locatorOffset < 0 || buffer.readUInt32LE(locatorOffset) !== ZIP64_LOCATOR_SIGNATURE) {
throw new Error(`${label}文件结构无效`);
}
const recordOffset = buffer.readBigUInt64LE(locatorOffset + 8);
if (recordOffset > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error(`${label}文件结构无效`);
const offset = Number(recordOffset);
if (offset < 0 || offset + ZIP64_END_RECORD_MIN_SIZE > buffer.length) throw new Error(`${label}文件结构无效`);
if (buffer.readUInt32LE(offset) !== ZIP64_END_SIGNATURE) throw new Error(`${label}文件结构无效`);
return buffer.readBigUInt64LE(offset + 32);
}
export function assertZipEntryCount(buffer: Buffer, maxEntries: number, label: string): number {
const endOffset = findZipEndRecordOffset(buffer, label);
const entries = usesZip64(buffer, endOffset)
? readZip64EntryCount(buffer, endOffset, label)
: BigInt(buffer.readUInt16LE(endOffset + 10));
assertZipEntryCountValue(entries, maxEntries, label);
return buffer.length - endOffset;
}
export async function inspectZipFile(filePath: string, maxEntries: number, label: string): Promise<number> {
const file = await open(filePath, 'r');
try {
const { size } = await file.stat();
if (size < ZIP_END_RECORD_MIN_SIZE) throw new Error(`${label}文件结构无效`);
const tailLength = Math.min(size, ZIP_END_RECORD_MAX_SIZE);
const tail = Buffer.allocUnsafe(tailLength);
const tailRead = await file.read(tail, 0, tailLength, size - tailLength);
if (tailRead.bytesRead !== tailLength) throw new Error(`${label}文件结构无效`);
const relativeEndOffset = findZipEndRecordOffset(tail, label);
const absoluteEndOffset = size - tailLength + relativeEndOffset;
let entries: bigint;
if (usesZip64(tail, relativeEndOffset)) {
const locator = Buffer.allocUnsafe(ZIP64_LOCATOR_SIZE);
if (absoluteEndOffset < ZIP64_LOCATOR_SIZE) throw new Error(`${label}文件结构无效`);
const locatorRead = await file.read(locator, 0, locator.length, absoluteEndOffset - ZIP64_LOCATOR_SIZE);
if (locatorRead.bytesRead !== locator.length) throw new Error(`${label}文件结构无效`);
if (locator.readUInt32LE(0) !== ZIP64_LOCATOR_SIGNATURE) throw new Error(`${label}文件结构无效`);
const recordOffset = locator.readBigUInt64LE(8);
if (recordOffset > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error(`${label}文件结构无效`);
const record = Buffer.allocUnsafe(ZIP64_END_RECORD_MIN_SIZE);
const recordRead = await file.read(record, 0, record.length, Number(recordOffset));
if (recordRead.bytesRead !== record.length) throw new Error(`${label}文件结构无效`);
if (record.readUInt32LE(0) !== ZIP64_END_SIGNATURE) throw new Error(`${label}文件结构无效`);
entries = record.readBigUInt64LE(32);
} else {
entries = BigInt(tail.readUInt16LE(relativeEndOffset + 10));
}
assertZipEntryCountValue(entries, maxEntries, label);
return size - absoluteEndOffset;
} finally {
await file.close();
}
}
export function assertArchiveLimits(
entries: ArchiveEntryLike[],
maxEntries: number,
maxUncompressedSize: number,
maxUncompressedSize: number | undefined,
label: string,
): void {
if (entries.length > maxEntries) {
@@ -46,18 +135,72 @@ export function assertArchiveLimits(
const size = Number(entry.header?.size ?? 0);
if (!Number.isSafeInteger(size) || size < 0) throw new Error(`${label}包含无效文件大小`);
total += size;
if (total > maxUncompressedSize) {
if (maxUncompressedSize !== undefined && total > maxUncompressedSize) {
throw new Error(`${label}解压后总大小超过限制`);
}
}
}
export function assertStoredImageBudget(referenceCount: number, totalBytes: number): void {
export function assertStoredImageBudget(referenceCount: number): void {
if (referenceCount > OUTBOUND_IMPORT_MAX_IMAGE_REFERENCES) {
throw new Error(`出库图片引用总数超过限制(最多 ${OUTBOUND_IMPORT_MAX_IMAGE_REFERENCES} 张)`);
}
if (totalBytes > OUTBOUND_IMPORT_MAX_STORED_IMAGE_SIZE) {
throw new Error(`出库图片按引用累计大小超过限制(最多 ${OUTBOUND_IMPORT_MAX_STORED_IMAGE_SIZE / 1024 / 1024}MB)`);
}
export async function readArchiveEntryBuffer(
entry: Pick<ArchiveStreamEntryLike, 'stream'>,
maxBytes: number,
overflowMessage: string,
onProgress?: () => Promise<void>,
): Promise<Buffer> {
const stream = entry.stream();
const chunks: Buffer[] = [];
let total = 0;
let progressBytes = 0;
try {
for await (const chunk of stream) {
const data = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
total += data.length;
if (total > maxBytes) throw new Error(overflowMessage);
chunks.push(data);
progressBytes += data.length;
if (onProgress && progressBytes >= ARCHIVE_PROGRESS_INTERVAL_BYTES) {
progressBytes = 0;
await onProgress();
}
}
} catch (error) {
stream.destroy();
throw error;
}
return Buffer.concat(chunks, total);
}
export async function assertArchiveActualSize(
entries: ArchiveStreamEntryLike[],
maxUncompressedSize: number,
label: string,
onProgress?: () => Promise<void>,
): Promise<void> {
let total = 0;
let progressBytes = 0;
for (const entry of entries) {
const stream = entry.stream();
try {
for await (const chunk of stream) {
const size = Buffer.isBuffer(chunk) ? chunk.length : Buffer.byteLength(chunk);
total += size;
if (total > maxUncompressedSize) throw new Error(`${label}解压后总大小超过限制`);
progressBytes += size;
if (onProgress && progressBytes >= ARCHIVE_PROGRESS_INTERVAL_BYTES) {
progressBytes = 0;
await onProgress();
}
}
} catch (error) {
stream.destroy();
throw error;
}
}
}
+20 -3
View File
@@ -12,14 +12,25 @@ import {
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiBearerAuth, ApiConsumes, ApiOperation, ApiTags } from '@nestjs/swagger';
import { randomUUID } from 'crypto';
import { Response } from 'express';
import { MAX_OUTBOUND_IMPORT_SIZE, RoleType } from '@artveris/shared';
import { mkdirSync } from 'fs';
import { diskStorage } from 'multer';
import { RoleType } from '@artveris/shared';
import { OutboundService } from './outbound.service';
import { OutboundDto } from './dto/outbound.dto';
import { QueryImportRowsDto } from './dto/import-session.dto';
import { Roles } from '../common/decorators/roles.decorator';
import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator';
import { parseBigId } from '../common/utils/bigint.util';
import { OUTBOUND_IMPORT_TEMP_DIR, OUTBOUND_IMPORT_UPLOAD_TEMP_PREFIX } from './outbound-import.util';
mkdirSync(OUTBOUND_IMPORT_TEMP_DIR, { recursive: true });
const outboundImportDiskStorage = diskStorage({
destination: OUTBOUND_IMPORT_TEMP_DIR,
filename: (_req, _file, callback) => callback(null, `${OUTBOUND_IMPORT_UPLOAD_TEMP_PREFIX}${randomUUID()}.upload`),
});
@ApiTags('出库与上链')
@ApiBearerAuth()
@@ -44,7 +55,10 @@ export class OutboundController {
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '上传 ZIP 并异步解析预览' })
@ApiConsumes('multipart/form-data')
@UseInterceptors(FileInterceptor('file', { limits: { fileSize: MAX_OUTBOUND_IMPORT_SIZE } }))
@UseInterceptors(FileInterceptor('file', {
storage: outboundImportDiskStorage,
limits: { files: 1, fields: 1, fieldSize: 128 },
}))
preview(
@UploadedFile() file: Express.Multer.File,
@Body('requestId') requestId: string | undefined,
@@ -88,7 +102,10 @@ export class OutboundController {
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '兼容旧入口:上传 ZIP 并异步解析预览' })
@ApiConsumes('multipart/form-data')
@UseInterceptors(FileInterceptor('file', { limits: { fileSize: MAX_OUTBOUND_IMPORT_SIZE } }))
@UseInterceptors(FileInterceptor('file', {
storage: outboundImportDiskStorage,
limits: { files: 1, fields: 0 },
}))
import(@UploadedFile() file: Express.Multer.File, @CurrentUser() user: AuthUser) {
return this.outboundService.startImport(file, user.id);
}
+89 -6
View File
@@ -1,5 +1,12 @@
import { JobStatus, JobType, RoleType } from '@artveris/shared';
import AdmZip from 'adm-zip';
import * as ExcelJS from 'exceljs';
import { access, mkdtemp, rm, writeFile } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
import sharp from 'sharp';
import { JobStatus, JobType, OUTBOUND_IMPORT_COLUMNS, RoleType } from '@artveris/shared';
import { OutboundService } from './outbound.service';
import { OUTBOUND_IMPORT_STORAGE_TIMEOUT_MS } from './outbound-import.util';
function readySession(overrides: Record<string, unknown> = {}) {
return {
@@ -40,7 +47,7 @@ function createHarness(session = readySession()) {
$transaction: jest.fn().mockImplementation(async (callback: (client: typeof tx) => unknown) => callback(tx)),
};
const storage = {
savePrivate: jest.fn().mockResolvedValue({ key: '.private/import.zip' }),
savePrivateFile: jest.fn().mockResolvedValue({ key: '.private/import.zip' }),
remove: jest.fn().mockResolvedValue(undefined),
};
const importQueue = {
@@ -62,7 +69,7 @@ describe('OutboundService.startPreview', () => {
const file = {
originalname: 'outbound.zip',
size: 3,
buffer: Buffer.from('zip'),
path: 'E:\\nonexistent-artveris-test\\outbound.upload',
} as Express.Multer.File;
it('persists the request, session and preview job before enqueueing', async () => {
@@ -73,10 +80,11 @@ describe('OutboundService.startPreview', () => {
jobId: 'preview-job',
});
expect(harness.storage.savePrivate).toHaveBeenCalledWith(
file.buffer,
expect(harness.storage.savePrivateFile).toHaveBeenCalledWith(
file.path,
'outbound.zip',
'application/zip',
{ requestTimeoutMs: OUTBOUND_IMPORT_STORAGE_TIMEOUT_MS },
);
expect(harness.tx.outboundImportSession.create).toHaveBeenCalledWith({
data: expect.objectContaining({ requestId: 'request_1234567890', fileKey: '.private/import.zip', createdBy: 7 }),
@@ -92,6 +100,32 @@ describe('OutboundService.startPreview', () => {
);
});
it('accepts a ZIP whose declared size is larger than the former 30MB limit', async () => {
const harness = createHarness();
const largeFile = { ...file, size: 31 * 1024 * 1024 } as Express.Multer.File;
await expect(harness.service.startPreview(largeFile, 7, 'request_1234567890')).resolves.toEqual({
sessionId: 'preview-session',
jobId: 'preview-job',
});
expect(harness.storage.savePrivateFile).toHaveBeenCalledTimes(1);
});
it('removes the Multer disk file after the upload has been persisted', async () => {
const harness = createHarness();
const dir = await mkdtemp(join(tmpdir(), 'artveris-outbound-upload-test-'));
const filePath = join(dir, 'upload.tmp');
await writeFile(filePath, Buffer.from('zip'));
try {
await harness.service.startPreview({ ...file, path: filePath } as Express.Multer.File, 7, 'request_1234567890');
await expect(access(filePath)).rejects.toMatchObject({ code: 'ENOENT' });
} finally {
await rm(dir, { recursive: true, force: true });
}
});
it('returns the persisted request when the client retries after losing the response', async () => {
const harness = createHarness();
harness.prisma.outboundImportSession.findUnique.mockResolvedValue({
@@ -105,7 +139,7 @@ describe('OutboundService.startPreview', () => {
jobId: 'existing-job',
});
expect(harness.storage.savePrivate).not.toHaveBeenCalled();
expect(harness.storage.savePrivateFile).not.toHaveBeenCalled();
expect(harness.prisma.$transaction).not.toHaveBeenCalled();
});
@@ -165,6 +199,55 @@ describe('OutboundService.startPreview', () => {
});
});
describe('OutboundService.generateTemplate', () => {
it('returns the maintained static ZIP with an empty import sheet and valid examples', async () => {
const harness = createHarness();
const res = { setHeader: jest.fn(), end: jest.fn() };
await harness.service.generateTemplate(res as any);
const archive = res.end.mock.calls[0][0] as Buffer;
const zip = new AdmZip(archive);
const names = zip.getEntries().filter((entry) => !entry.isDirectory).map((entry) => entry.entryName).sort();
expect(names).toEqual([
'images/out-001.jpg',
'images/out-002.png',
'images/out-003.jpg',
'outbound-import-template.xlsx',
'说明.txt',
]);
const workbook = new ExcelJS.Workbook();
await workbook.xlsx.load(zip.readFile('outbound-import-template.xlsx')! as unknown as ArrayBuffer);
expect(workbook.worksheets.map((sheet) => sheet.name)).toEqual(['导入模板', '填写示例', '字段说明']);
const importSheet = workbook.getWorksheet('导入模板')!;
expect(importSheet.rowCount).toBe(1);
expect(importSheet.getRow(1).values).toEqual([
undefined,
...OUTBOUND_IMPORT_COLUMNS.map((column) => column.header),
]);
expect(importSheet.getCell('A1').fill).toMatchObject({ fgColor: { argb: 'FF1F4E78' } });
expect(importSheet.getCell('A1').font).toMatchObject({ bold: true, color: { argb: 'FFFFFFFF' } });
expect(importSheet.views[0]).toMatchObject({ state: 'frozen', ySplit: 1 });
const exampleSheet = workbook.getWorksheet('填写示例')!;
expect(exampleSheet.getCell('A2').text).toMatch(/^\d{12}$/);
expect(exampleSheet.getCell('D3').text).toContain('images/out-002.png;images/out-003.jpg');
expect(workbook.getWorksheet('字段说明')?.rowCount).toBe(OUTBOUND_IMPORT_COLUMNS.length + 1);
const instructions = zip.readAsText('说明.txt');
expect(instructions).toContain('单个 xlsx 最大 100MB');
expect(instructions).toContain('单张图片最大 100MB');
expect(instructions).toContain('支持 JPG、JPEG、PNG、WebP;最多 4000 万像素');
expect(instructions).toContain('不会自动触发区块链上链');
await expect(sharp(zip.readFile('images/out-001.jpg')!).metadata()).resolves.toMatchObject({ format: 'jpeg' });
await expect(sharp(zip.readFile('images/out-002.png')!).metadata()).resolves.toMatchObject({ format: 'png' });
await expect(sharp(zip.readFile('images/out-003.jpg')!).metadata()).resolves.toMatchObject({ format: 'jpeg' });
expect(res.setHeader).toHaveBeenCalledWith('Content-Type', 'application/zip');
expect(res.setHeader).toHaveBeenCalledWith('Content-Length', String(archive.length));
});
});
describe('OutboundService.commitSession', () => {
it('atomically claims a valid READY session, creates one job and enqueues it', async () => {
const harness = createHarness();
+31 -72
View File
@@ -2,17 +2,15 @@ import { Injectable, Logger } from '@nestjs/common';
import { InjectQueue } from '@nestjs/bullmq';
import { Queue } from 'bullmq';
import { randomUUID } from 'crypto';
import { readFile, rm } from 'fs/promises';
import { resolve } from 'path';
import { Response } from 'express';
import * as ExcelJS from 'exceljs';
import AdmZip from 'adm-zip';
import sharp from 'sharp';
import { Prisma, RoleType } from '@prisma/client';
import {
ErrorCode,
JobStatus,
JobType,
MAX_OUTBOUND_IMPORT_SIZE,
OUTBOUND_IMPORT_COLUMNS,
QUEUE_NAMES,
} from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
@@ -24,8 +22,10 @@ import { AuthUser } from '../common/decorators/current-user.decorator';
import { OutboundDto } from './dto/outbound.dto';
import { QueryImportRowsDto } from './dto/import-session.dto';
import { isOutbound } from './outbound.util';
import { OUTBOUND_IMPORT_STORAGE_TIMEOUT_MS } from './outbound-import.util';
const SESSION_TTL_DAYS = 2;
const OUTBOUND_IMPORT_TEMPLATE_PATH = resolve(__dirname, '..', 'assets', 'templates', 'outbound-import-template.zip');
function jsonArray<T>(value: unknown): T[] {
return Array.isArray(value) ? (value as T[]) : [];
@@ -124,76 +124,34 @@ export class OutboundService {
}
async generateTemplate(res: Response): Promise<void> {
const wb = new ExcelJS.Workbook();
const ws = wb.addWorksheet('导入模板');
ws.columns = OUTBOUND_IMPORT_COLUMNS.map((c) => ({ header: c.header, key: c.key, width: c.key === 'outImages' ? 36 : 22 }));
ws.getRow(1).font = { bold: true };
ws.getColumn('shortCode').numFmt = '@';
ws.addRow({
shortCode: '请替换为真实追溯码',
batchNo: 'B20260704001',
outTime: '2026-07-04 10:00',
outImages: 'images/out-001.jpg',
remark: '单图示例',
});
ws.addRow({
shortCode: '请替换为真实追溯码',
batchNo: 'B20260704001',
outTime: '2026-07-04 11:00',
outImages: 'images/out-002.png;images/out-003.jpg',
remark: '多图示例',
});
const note = wb.addWorksheet('字段说明');
note.columns = [
{ header: '列名', key: 'header', width: 18 },
{ header: '是否必填', key: 'required', width: 12 },
{ header: '说明', key: 'note', width: 70 },
];
note.getRow(1).font = { bold: true };
OUTBOUND_IMPORT_COLUMNS.forEach((c) =>
note.addRow({ header: c.header, required: c.required ? '是' : '否', note: c.note }),
);
const zip = new AdmZip();
zip.addFile('outbound-import-template.xlsx', Buffer.from(await wb.xlsx.writeBuffer()));
zip.addFile(
'说明.txt',
Buffer.from(
[
'出库批量导入说明',
'',
'1. ZIP 根目录必须包含一个 xlsx 文件和 images 文件夹。',
'2. 出库实况图路径填写 images/xxx.jpg,多张图片使用英文分号 ; 分隔。',
'3. 不允许使用绝对路径、..、反斜杠或 images 目录之外的路径。',
'4. 上传 ZIP 后系统会先预览校验,确认无误后才正式导入。',
'5. 链上哈希、存证链接和上链时间由天河链接口返回后自动写入,不在导入模板中手工填写。',
].join('\r\n'),
'utf8',
),
);
zip.addFile('images/out-001.jpg', await this.sampleImage('#13a8a8'));
zip.addFile('images/out-002.png', await this.sampleImage('#3b82f6', 'png'));
zip.addFile('images/out-003.jpg', await this.sampleImage('#f59e0b'));
let archive: Buffer;
try {
archive = await readFile(OUTBOUND_IMPORT_TEMPLATE_PATH);
} catch (error) {
this.logger.error(`读取出库导入模板失败:${(error as Error).message}`);
throw new BusinessException(ErrorCode.INTERNAL_ERROR, '出库导入模板暂不可用');
}
res.setHeader('Content-Type', 'application/zip');
res.setHeader('Content-Disposition', 'attachment; filename="outbound-import-template.zip"');
res.end(zip.toBuffer());
}
private sampleImage(color: string, format: 'jpeg' | 'png' = 'jpeg') {
const img = sharp({
create: {
width: 720,
height: 480,
channels: 3,
background: color,
},
});
return format === 'png' ? img.png().toBuffer() : img.jpeg({ quality: 86 }).toBuffer();
res.setHeader('Content-Length', String(archive.length));
res.setHeader('Cache-Control', 'no-cache');
res.end(archive);
}
async startPreview(file: Express.Multer.File, userId: number, requestId?: string) {
try {
return await this.startPreviewFromUpload(file, userId, requestId);
} finally {
if (file?.path) {
await rm(file.path, { force: true }).catch((error) =>
this.logger.warn(`清理出库导入上传临时文件失败:${file.path} ${(error as Error).message}`),
);
}
}
}
private async startPreviewFromUpload(file: Express.Multer.File, userId: number, requestId?: string) {
const normalizedRequestId = (requestId || '').trim();
if (normalizedRequestId && !/^[A-Za-z0-9_-]{16,64}$/.test(normalizedRequestId)) {
throw new BusinessException(ErrorCode.BAD_REQUEST, '导入请求标识格式无效');
@@ -209,13 +167,14 @@ export class OutboundService {
if (!file) throw new BusinessException(ErrorCode.BAD_REQUEST, '请上传导入 ZIP 文件');
const name = (file.originalname || '').toLowerCase();
if (!name.endsWith('.zip')) throw new BusinessException(ErrorCode.FILE_TYPE_NOT_ALLOWED, '仅支持 ZIP 文件');
const fileSize = file.size || file.buffer?.length || 0;
const fileSize = file.size || 0;
if (!fileSize) throw new BusinessException(ErrorCode.BAD_REQUEST, '导入 ZIP 文件不能为空');
if (fileSize > MAX_OUTBOUND_IMPORT_SIZE) throw new BusinessException(ErrorCode.FILE_TOO_LARGE, 'ZIP 文件不能超过 30MB');
const saved = await this.storage.savePrivate(
file.buffer,
if (!file.path) throw new BusinessException(ErrorCode.INTERNAL_ERROR, '导入 ZIP 临时文件不存在');
const saved = await this.storage.savePrivateFile(
file.path,
file.originalname || 'outbound-import.zip',
'application/zip',
{ requestTimeoutMs: OUTBOUND_IMPORT_STORAGE_TIMEOUT_MS },
);
let created: { sessionId: string; jobId: string; fileKey: string };
try {
+25 -1
View File
@@ -1,4 +1,4 @@
import { mkdtempSync, rmSync } from 'fs';
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { LocalDriver } from './local.driver';
@@ -39,4 +39,28 @@ describe('LocalDriver', () => {
'https://cdn.example.com/assets/2026/07/file.jpg',
);
});
it('copies large-file uploads and downloads through disk paths', async () => {
const driver = createDriver();
const workingDir = mkdtempSync(join(tmpdir(), 'artveris-storage-stream-'));
tempDirs.push(workingDir);
const source = join(workingDir, 'source.zip');
const target = join(workingDir, 'target.zip');
writeFileSync(source, Buffer.from('streamed-zip'));
await driver.putFile('.private/import.zip', source, 12);
await driver.getFile('.private/import.zip', target);
expect(readFileSync(target).toString()).toBe('streamed-zip');
});
it('copies a stored file without removing the source', async () => {
const driver = createDriver();
await driver.put('temp/source.jpg', Buffer.from('image'));
await driver.copy('temp/source.jpg', 'final/copied.jpg');
await expect(driver.get('temp/source.jpg')).resolves.toEqual(Buffer.from('image'));
await expect(driver.get('final/copied.jpg')).resolves.toEqual(Buffer.from('image'));
});
});
+31 -17
View File
@@ -1,6 +1,7 @@
import { existsSync, mkdirSync, readdirSync, statSync, writeFileSync, rmSync, readFileSync } from 'fs';
import { existsSync } from 'fs';
import { copyFile, mkdir, readFile, readdir, rm, writeFile } from 'fs/promises';
import { dirname, join, relative, resolve } from 'path';
import { PutOptions, StorageDriver } from './storage.types';
import { PutOptions, StorageDriver, StorageRequestOptions } from './storage.types';
export interface LocalDriverOptions {
localDir: string;
@@ -27,36 +28,49 @@ export class LocalDriver implements StorageDriver {
async put(key: string, buffer: Buffer, _options?: PutOptions): Promise<void> {
const full = this.fullPath(key);
mkdirSync(dirname(full), { recursive: true });
writeFileSync(full, buffer);
await mkdir(dirname(full), { recursive: true });
await writeFile(full, buffer);
}
async get(key: string): Promise<Buffer> {
return readFileSync(this.fullPath(key));
async putFile(key: string, filePath: string, _size: number, _options?: PutOptions): Promise<void> {
const full = this.fullPath(key);
await mkdir(dirname(full), { recursive: true });
await copyFile(filePath, full);
}
async copy(sourceKey: string, targetKey: string, _options?: PutOptions): Promise<void> {
const target = this.fullPath(targetKey);
await mkdir(dirname(target), { recursive: true });
await copyFile(this.fullPath(sourceKey), target);
}
async get(key: string, _options?: StorageRequestOptions): Promise<Buffer> {
return readFile(this.fullPath(key));
}
async getFile(key: string, filePath: string, _options?: StorageRequestOptions): Promise<void> {
await mkdir(dirname(filePath), { recursive: true });
await copyFile(this.fullPath(key), filePath);
}
async remove(key: string): Promise<void> {
const full = this.fullPath(key);
if (existsSync(full)) {
rmSync(full, { force: true });
}
await rm(this.fullPath(key), { force: true });
}
async list(): Promise<string[]> {
if (!existsSync(this.root)) return [];
const keys: string[] = [];
const walk = (dir: string) => {
for (const name of readdirSync(dir)) {
const full = join(dir, name);
const st = statSync(full);
if (st.isDirectory()) {
walk(full);
const walk = async (dir: string): Promise<void> => {
for (const entry of await readdir(dir, { withFileTypes: true })) {
const full = join(dir, entry.name);
if (entry.isDirectory()) {
await walk(full);
} else {
keys.push(relative(this.root, full).replace(/\\/g, '/'));
}
}
};
walk(this.root);
await walk(this.root);
return keys;
}
+98 -3
View File
@@ -1,11 +1,14 @@
import { Upload } from '@aws-sdk/lib-storage';
import { OssDriver } from './oss.driver';
jest.mock('@aws-sdk/lib-storage', () => ({ Upload: jest.fn() }));
describe('OssDriver request timeout', () => {
beforeEach(() => jest.clearAllMocks());
afterEach(() => jest.useRealTimers());
it('aborts a storage request that never returns', async () => {
jest.useFakeTimers();
const driver = new OssDriver({
function createDriver(): OssDriver {
return new OssDriver({
endpoint: 'http://127.0.0.1:9000',
region: 'us-east-1',
bucket: 'artveris',
@@ -13,6 +16,11 @@ describe('OssDriver request timeout', () => {
accessKeySecret: 'test',
cdnBaseUrl: '',
});
}
it('aborts a storage request that never returns', async () => {
jest.useFakeTimers();
const driver = createDriver();
(driver as any).client.send = jest.fn((_command: unknown, options: { abortSignal: AbortSignal }) =>
new Promise((_resolve, reject) => {
options.abortSignal.addEventListener('abort', () => reject(new Error('request aborted')));
@@ -25,4 +33,91 @@ describe('OssDriver request timeout', () => {
await assertion;
});
it('honors a longer timeout for a large private import', async () => {
jest.useFakeTimers();
const driver = createDriver();
let signal: AbortSignal | undefined;
(driver as any).client.send = jest.fn((_command: unknown, options: { abortSignal: AbortSignal }) => {
signal = options.abortSignal;
return new Promise((_resolve, reject) => {
options.abortSignal.addEventListener('abort', () => reject(new Error('request aborted')));
});
});
const upload = driver.put('large.zip', Buffer.from('zip'), { requestTimeoutMs: 120_000 });
const assertion = expect(upload).rejects.toThrow('request aborted');
await jest.advanceTimersByTimeAsync(60_000);
expect(signal?.aborted).toBe(false);
await jest.advanceTimersByTimeAsync(60_000);
await assertion;
});
it('uses managed multipart upload for a file-backed private import', async () => {
const done = jest.fn().mockResolvedValue(undefined);
(Upload as unknown as jest.Mock).mockImplementationOnce(() => ({ done }));
const driver = createDriver();
await driver.putFile('large.zip', __filename, 6 * 1024 * 1024, {
contentType: 'application/zip',
visibility: 'private',
requestTimeoutMs: 3_600_000,
});
expect(Upload).toHaveBeenCalledWith(expect.objectContaining({
client: expect.any(Object),
queueSize: 2,
leavePartsOnError: false,
abortController: expect.any(AbortController),
params: expect.objectContaining({
Bucket: 'artveris',
Key: 'large.zip',
ContentLength: 6 * 1024 * 1024,
ContentType: 'application/zip',
ACL: 'private',
}),
}));
expect(done).toHaveBeenCalledTimes(1);
});
it('aborts a multipart upload when its extended timeout expires', async () => {
jest.useFakeTimers();
(Upload as unknown as jest.Mock).mockImplementationOnce(({ abortController }) => ({
done: () => new Promise((_resolve, reject) => {
abortController.signal.addEventListener('abort', () => reject(new Error('multipart aborted')));
}),
}));
const driver = createDriver();
const upload = driver.putFile('large.zip', __filename, 6 * 1024 * 1024, { requestTimeoutMs: 120_000 });
const assertion = expect(upload).rejects.toThrow('multipart aborted');
await jest.advanceTimersByTimeAsync(60_000);
expect(((Upload as unknown as jest.Mock).mock.calls[0][0].abortController as AbortController).signal.aborted).toBe(false);
await jest.advanceTimersByTimeAsync(60_000);
await assertion;
});
it('copies an object server-side with an encoded source key and caller timeout', async () => {
const driver = createDriver();
const send = jest.fn().mockResolvedValue({});
(driver as any).client.send = send;
await driver.copy('临时/a b.jpg', 'final/image.jpg', {
contentType: 'image/jpeg',
cacheControl: 'public, max-age=31536000, immutable',
requestTimeoutMs: 3_600_000,
});
const command = send.mock.calls[0][0];
expect(command.constructor.name).toBe('CopyObjectCommand');
expect(command.input).toMatchObject({
Bucket: 'artveris',
Key: 'final/image.jpg',
CopySource: 'artveris/%E4%B8%B4%E6%97%B6/a%20b.jpg',
MetadataDirective: 'REPLACE',
ContentType: 'image/jpeg',
});
});
});
+62 -7
View File
@@ -1,11 +1,15 @@
import {
CopyObjectCommand,
DeleteObjectCommand,
GetObjectCommand,
ListObjectsV2Command,
PutObjectCommand,
S3Client,
} from '@aws-sdk/client-s3';
import { PutOptions, StorageDriver } from './storage.types';
import { Upload } from '@aws-sdk/lib-storage';
import { createReadStream, createWriteStream } from 'fs';
import { pipeline } from 'stream/promises';
import { PutOptions, StorageDriver, StorageRequestOptions } from './storage.types';
export interface OssDriverOptions {
endpoint: string;
@@ -27,6 +31,7 @@ export class OssDriver implements StorageDriver {
region: opts.region || 'us-east-1',
endpoint: opts.endpoint || undefined,
forcePathStyle: true,
requestChecksumCalculation: 'WHEN_REQUIRED',
credentials: {
accessKeyId: opts.accessKeyId,
secretAccessKey: opts.accessKeySecret,
@@ -34,11 +39,14 @@ export class OssDriver implements StorageDriver {
});
}
private async withRequestTimeout<T>(operation: (signal: AbortSignal) => Promise<T>): Promise<T> {
private async withRequestTimeout<T>(
operation: (signal: AbortSignal, controller: AbortController) => Promise<T>,
timeoutMs = this.requestTimeoutMs,
): Promise<T> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), this.requestTimeoutMs);
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
return await operation(controller.signal);
return await operation(controller.signal, controller);
} finally {
clearTimeout(timer);
}
@@ -55,10 +63,47 @@ export class OssDriver implements StorageDriver {
ACL: options?.visibility === 'private' ? 'private' : undefined,
}),
{ abortSignal },
));
), options?.requestTimeoutMs);
}
async get(key: string): Promise<Buffer> {
async putFile(key: string, filePath: string, size: number, options?: PutOptions): Promise<void> {
await this.withRequestTimeout(async (_abortSignal, abortController) => {
const upload = new Upload({
client: this.client,
params: {
Bucket: this.opts.bucket,
Key: key,
Body: createReadStream(filePath),
ContentLength: size,
ContentType: options?.contentType,
CacheControl: options?.cacheControl,
ACL: options?.visibility === 'private' ? 'private' : undefined,
},
queueSize: 2,
leavePartsOnError: false,
abortController,
});
await upload.done();
}, options?.requestTimeoutMs);
}
async copy(sourceKey: string, targetKey: string, options?: PutOptions): Promise<void> {
const copySource = `${encodeURIComponent(this.opts.bucket)}/${sourceKey.split('/').map(encodeURIComponent).join('/')}`;
await this.withRequestTimeout((abortSignal) => this.client.send(
new CopyObjectCommand({
Bucket: this.opts.bucket,
Key: targetKey,
CopySource: copySource,
MetadataDirective: 'REPLACE',
ContentType: options?.contentType,
CacheControl: options?.cacheControl,
ACL: options?.visibility === 'private' ? 'private' : undefined,
}),
{ abortSignal },
), options?.requestTimeoutMs);
}
async get(key: string, options?: StorageRequestOptions): Promise<Buffer> {
return this.withRequestTimeout(async (abortSignal) => {
const res = await this.client.send(
new GetObjectCommand({ Bucket: this.opts.bucket, Key: key }),
@@ -66,7 +111,17 @@ export class OssDriver implements StorageDriver {
);
const bytes = await res.Body!.transformToByteArray();
return Buffer.from(bytes);
});
}, options?.requestTimeoutMs);
}
async getFile(key: string, filePath: string, options?: StorageRequestOptions): Promise<void> {
await this.withRequestTimeout(async (abortSignal) => {
const res = await this.client.send(
new GetObjectCommand({ Bucket: this.opts.bucket, Key: key }),
{ abortSignal },
);
await pipeline(res.Body as NodeJS.ReadableStream, createWriteStream(filePath));
}, options?.requestTimeoutMs);
}
async remove(key: string): Promise<void> {
+59 -10
View File
@@ -1,4 +1,7 @@
import { StorageService } from './storage.service';
import { mkdtemp, rm, writeFile } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
function createHarness() {
const config = {
@@ -10,7 +13,10 @@ function createHarness() {
const service = new StorageService(config as any, settings as any);
const driver = {
get: jest.fn().mockResolvedValue(Buffer.from('image')),
getFile: jest.fn().mockResolvedValue(undefined),
put: jest.fn().mockResolvedValue(undefined),
putFile: jest.fn().mockResolvedValue(undefined),
copy: jest.fn().mockResolvedValue(undefined),
remove: jest.fn().mockResolvedValue(undefined),
getPublicUrl: jest.fn((key: string) => `/uploads/${key}`),
};
@@ -31,22 +37,23 @@ describe('StorageService.copyMedia', () => {
const target = copied.keyMap.get('temp/source.jpg');
expect(target).toMatch(/^1\/archive\/code\/出库实况_/);
expect(driver.get).toHaveBeenCalledWith('temp/source.jpg');
expect(driver.put).toHaveBeenCalledWith(target, expect.any(Buffer), expect.any(Object));
expect(driver.copy).toHaveBeenCalledWith('temp/source.jpg', target, expect.any(Object));
expect(driver.get).not.toHaveBeenCalled();
expect(driver.put).not.toHaveBeenCalled();
expect(driver.remove).not.toHaveBeenCalledWith('temp/source.jpg');
});
it('cleans copied destinations when a later image copy fails', async () => {
const { service, driver } = createHarness();
driver.get.mockResolvedValueOnce(Buffer.from('first')).mockRejectedValueOnce(new Error('read failed'));
driver.copy.mockResolvedValueOnce(undefined).mockRejectedValueOnce(new Error('copy failed'));
await expect(service.copyMedia(
[{ key: 'temp/first.jpg' }, { key: 'temp/second.jpg' }],
'1/archive/code',
'出库实况',
)).rejects.toThrow('read failed');
)).rejects.toThrow('copy failed');
const copiedTarget = driver.put.mock.calls[0][0];
const copiedTarget = driver.copy.mock.calls[0][1];
expect(driver.remove).toHaveBeenCalledWith(copiedTarget);
expect(driver.remove.mock.calls.map(([key]) => key)).toHaveLength(2);
expect(driver.remove).not.toHaveBeenCalledWith('temp/first.jpg');
@@ -56,9 +63,8 @@ describe('StorageService.copyMedia', () => {
it('publishes every destination key before the first storage copy begins', async () => {
const { service, driver } = createHarness();
const events: string[] = [];
driver.get.mockImplementation(async (key: string) => {
events.push(`read:${key}`);
return Buffer.from(key);
driver.copy.mockImplementation(async (key: string) => {
events.push(`copy:${key}`);
});
await service.copyMedia(
@@ -72,7 +78,7 @@ describe('StorageService.copyMedia', () => {
);
expect(events[0]).toBe('planned:2');
expect(events.slice(1)).toEqual(['read:temp/first.jpg', 'read:temp/second.jpg']);
expect(events.slice(1)).toEqual(['copy:temp/first.jpg', 'copy:temp/second.jpg']);
});
});
@@ -91,6 +97,49 @@ describe('StorageService.savePrivate', () => {
);
});
it('streams a private import from disk without loading it into a Buffer', async () => {
const { service, driver } = createHarness();
const dir = await mkdtemp(join(tmpdir(), 'artveris-storage-test-'));
const filePath = join(dir, 'import.zip');
await writeFile(filePath, Buffer.from('large-zip-placeholder'));
try {
const saved = await service.savePrivateFile(
filePath,
'import.zip',
'application/zip',
{ requestTimeoutMs: 3_600_000 },
);
expect(saved).toMatchObject({ url: '', size: 21, mime: 'application/zip' });
expect(driver.putFile).toHaveBeenCalledWith(
saved.key,
filePath,
21,
expect.objectContaining({ visibility: 'private', requestTimeoutMs: 3_600_000 }),
);
expect(driver.put).not.toHaveBeenCalled();
} finally {
await rm(dir, { recursive: true, force: true });
}
});
it('passes an extended request timeout only when the caller requests it', async () => {
const { service, driver } = createHarness();
const saved = await service.savePrivate(
Buffer.from('zip'),
'import.zip',
'application/zip',
{ requestTimeoutMs: 3_600_000 },
);
expect(driver.put).toHaveBeenCalledWith(
saved.key,
expect.any(Buffer),
expect.objectContaining({ requestTimeoutMs: 3_600_000 }),
);
});
it('preserves private visibility when restoring a private storage key', async () => {
const { service, driver } = createHarness();
@@ -119,7 +168,7 @@ describe('StorageService.savePrivate', () => {
describe('StorageService.relocateMedia', () => {
it('does not delete any source when copying the media set fails', async () => {
const { service, driver } = createHarness();
driver.get.mockResolvedValueOnce(Buffer.from('first')).mockRejectedValueOnce(new Error('missing source'));
driver.copy.mockResolvedValueOnce(undefined).mockRejectedValueOnce(new Error('missing source'));
await expect(service.relocateMedia(
[{ key: 'temp/first.jpg' }, { key: 'temp/missing.jpg' }],
+62 -14
View File
@@ -1,13 +1,15 @@
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { createHash } from 'crypto';
import { createReadStream } from 'fs';
import { stat } from 'fs/promises';
import dayjs from 'dayjs';
import { nanoid } from 'nanoid';
import { extname } from 'path';
import { SettingsService } from '../settings/settings.service';
import { LocalDriver } from './local.driver';
import { OssDriver } from './oss.driver';
import { SavedFile, StorageDriver } from './storage.types';
import { SavedFile, StorageDriver, StorageRequestOptions } from './storage.types';
export const STATIC_ASSET_CACHE_CONTROL = 'public, max-age=31536000, immutable';
const STORAGE_EXCLUSIVE_WAIT_MS = 120_000;
@@ -173,13 +175,25 @@ export class StorageService implements OnModuleInit {
return `${dayjs().format('YYYY/MM/DD')}/${hash.slice(0, 16)}-${nanoid()}${ext}`;
}
async save(buffer: Buffer, originalName: string, mime?: string): Promise<SavedFile> {
private async buildFileHash(filePath: string): Promise<string> {
const hash = createHash('sha256');
for await (const chunk of createReadStream(filePath)) hash.update(chunk as Buffer);
return hash.digest('hex');
}
async save(
buffer: Buffer,
originalName: string,
mime?: string,
requestOptions: StorageRequestOptions = {},
): Promise<SavedFile> {
const hash = this.buildHash(buffer);
const key = this.buildKey(originalName, hash, mime);
const url = await this.withDriverOperation(async (driver) => {
await driver.put(key, buffer, {
contentType: mime || storageContentType(key),
cacheControl: STATIC_ASSET_CACHE_CONTROL,
...requestOptions,
});
return driver.getPublicUrl(key);
});
@@ -193,13 +207,19 @@ export class StorageService implements OnModuleInit {
};
}
async savePrivate(buffer: Buffer, originalName: string, mime?: string): Promise<SavedFile> {
async savePrivate(
buffer: Buffer,
originalName: string,
mime?: string,
requestOptions: StorageRequestOptions = {},
): Promise<SavedFile> {
const hash = this.buildHash(buffer);
const key = `.private/${this.buildKey(originalName, hash, mime)}`;
await this.withDriverOperation((driver) => driver.put(key, buffer, {
contentType: mime || storageContentType(key),
cacheControl: 'private, no-store',
visibility: 'private',
...requestOptions,
}));
return {
key,
@@ -211,6 +231,31 @@ export class StorageService implements OnModuleInit {
};
}
async savePrivateFile(
filePath: string,
originalName: string,
mime?: string,
requestOptions: StorageRequestOptions = {},
): Promise<SavedFile> {
const file = await stat(filePath);
const hash = await this.buildFileHash(filePath);
const key = `.private/${this.buildKey(originalName, hash, mime)}`;
await this.withDriverOperation((driver) => driver.putFile(key, filePath, file.size, {
contentType: mime || storageContentType(key),
cacheControl: 'private, no-store',
visibility: 'private',
...requestOptions,
}));
return {
key,
url: '',
name: originalName,
size: file.size,
mime: mime || 'application/octet-stream',
hash,
};
}
async putKey(key: string, buffer: Buffer, mime?: string): Promise<string> {
const isPrivate = key.startsWith('.private/');
return this.withDriverOperation(async (driver) => {
@@ -229,15 +274,13 @@ export class StorageService implements OnModuleInit {
return `${base}_${suffix}${ext || '.jpg'}`;
}
async copyKey(oldKey: string, newKey: string): Promise<string> {
async copyKey(oldKey: string, newKey: string, requestOptions: StorageRequestOptions = {}): Promise<string> {
if (!oldKey || oldKey === newKey) return oldKey;
await this.withDriverOperation(async (driver) => {
const buffer = await driver.get(oldKey);
await driver.put(newKey, buffer, {
contentType: storageContentType(newKey),
cacheControl: STATIC_ASSET_CACHE_CONTROL,
});
});
await this.withDriverOperation((driver) => driver.copy(oldKey, newKey, {
contentType: storageContentType(newKey),
cacheControl: STATIC_ASSET_CACHE_CONTROL,
...requestOptions,
}));
return newKey;
}
@@ -285,12 +328,13 @@ export class StorageService implements OnModuleInit {
dir: string,
baseName: string,
onPlanned?: (targetKeys: string[]) => Promise<void>,
requestOptions: StorageRequestOptions = {},
): Promise<{ items: T[]; changed: boolean; keyMap: Map<string, string> }> {
return this.organizeMedia(
items,
dir,
baseName,
(oldKey, newKey) => this.copyKey(oldKey, newKey),
(oldKey, newKey) => this.copyKey(oldKey, newKey, requestOptions),
onPlanned,
);
}
@@ -354,8 +398,12 @@ export class StorageService implements OnModuleInit {
return this.driver.getPublicUrl(key);
}
read(key: string): Promise<Buffer> {
return this.withDriverOperation((driver) => driver.get(key));
read(key: string, requestOptions?: StorageRequestOptions): Promise<Buffer> {
return this.withDriverOperation((driver) => driver.get(key, requestOptions));
}
downloadToFile(key: string, filePath: string, requestOptions?: StorageRequestOptions): Promise<void> {
return this.withDriverOperation((driver) => driver.getFile(key, filePath, requestOptions));
}
async remove(key: string): Promise<void> {
+9 -2
View File
@@ -1,4 +1,8 @@
export interface PutOptions {
export interface StorageRequestOptions {
requestTimeoutMs?: number;
}
export interface PutOptions extends StorageRequestOptions {
contentType?: string;
cacheControl?: string;
visibility?: 'public' | 'private';
@@ -6,7 +10,10 @@ export interface PutOptions {
export interface StorageDriver {
put(key: string, buffer: Buffer, options?: PutOptions): Promise<void>;
get(key: string): Promise<Buffer>;
putFile(key: string, filePath: string, size: number, options?: PutOptions): Promise<void>;
copy(sourceKey: string, targetKey: string, options?: PutOptions): Promise<void>;
get(key: string, options?: StorageRequestOptions): Promise<Buffer>;
getFile(key: string, filePath: string, options?: StorageRequestOptions): Promise<void>;
remove(key: string): Promise<void>;
getPublicUrl(key: string): string;
list?(): Promise<string[]>;