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
@@ -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 {