fix: 加固批量出库导入流程
This commit is contained in:
@@ -0,0 +1,535 @@
|
||||
import { JobStatus } from '@artveris/shared';
|
||||
import { ImportProcessor } from './import.processor';
|
||||
|
||||
function importRow(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 1n,
|
||||
sessionId: 'session-1',
|
||||
rowNo: 2,
|
||||
status: 'VALID',
|
||||
shortCode: '111111111111',
|
||||
batchNo: 'B1',
|
||||
outTime: new Date('2026-07-04T02:00:00.000Z'),
|
||||
outImagePaths: [],
|
||||
outImageKeys: [],
|
||||
remark: null,
|
||||
reason: null,
|
||||
preview: null,
|
||||
createdAt: new Date('2026-07-04T01:00:00.000Z'),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function traceCode(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 11n,
|
||||
shortCode: '111111111111',
|
||||
outTime: null,
|
||||
outImages: null,
|
||||
remark: null,
|
||||
batch: { batchNo: 'B1' },
|
||||
artwork: { templateId: 1, archiveNo: 'ARTVERIS-000001' },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function clone<T>(value: T): T {
|
||||
if (value instanceof Date) return new Date(value.getTime()) as T;
|
||||
if (Array.isArray(value)) return value.map((item) => clone(item)) as T;
|
||||
if (value && typeof value === 'object') {
|
||||
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, clone(item)])) as T;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function createHarness(options: {
|
||||
rows?: any[];
|
||||
code?: any;
|
||||
session?: any | null;
|
||||
traceUpdateCount?: number;
|
||||
} = {}) {
|
||||
const initialRows = options.rows ?? [importRow()];
|
||||
const defaultSession = {
|
||||
id: 'session-1',
|
||||
status: 'IMPORTING',
|
||||
fileKey: null,
|
||||
total: initialRows.length,
|
||||
validCount: initialRows.filter((row) => row.status === 'VALID').length,
|
||||
invalidCount: 0,
|
||||
error: null,
|
||||
importJobId: 'job-1',
|
||||
importRunToken: null,
|
||||
updatedAt: new Date('2026-07-04T01:00:00.000Z'),
|
||||
};
|
||||
const state: {
|
||||
session: any | null;
|
||||
rows: any[];
|
||||
code: any;
|
||||
job: any;
|
||||
} = {
|
||||
session: options.session === null ? null : { ...defaultSession, ...(options.session ?? {}) },
|
||||
rows: clone(initialRows),
|
||||
code: clone(options.code ?? traceCode()),
|
||||
job: { id: 'job-1', status: JobStatus.PENDING, resultFileUrl: null },
|
||||
};
|
||||
|
||||
const sessionMatches = (where: any) => {
|
||||
if (!state.session) return false;
|
||||
return ['id', 'status', 'fileKey', 'importJobId', 'importRunToken'].every(
|
||||
(key) => where[key] === undefined || state.session[key] === where[key],
|
||||
);
|
||||
};
|
||||
const rowMatches = (row: any, where: any) =>
|
||||
(where.id === undefined || row.id === where.id) &&
|
||||
(where.sessionId === undefined || row.sessionId === where.sessionId) &&
|
||||
(where.status === undefined || row.status === where.status);
|
||||
|
||||
const updateSessionMany = async ({ where, data }: any) => {
|
||||
if (!sessionMatches(where)) return { count: 0 };
|
||||
Object.assign(state.session, data);
|
||||
return { count: 1 };
|
||||
};
|
||||
const updateSession = async ({ where, data }: any) => {
|
||||
if (!state.session || state.session.id !== where.id) throw new Error('session not found');
|
||||
Object.assign(state.session, data);
|
||||
return clone(state.session);
|
||||
};
|
||||
const updateRowsMany = async ({ where, data }: any) => {
|
||||
let count = 0;
|
||||
for (const row of state.rows) {
|
||||
if (!rowMatches(row, where)) continue;
|
||||
Object.assign(row, data);
|
||||
count++;
|
||||
}
|
||||
return { count };
|
||||
};
|
||||
const countRows = async ({ where }: any) => state.rows.filter((row) => rowMatches(row, where)).length;
|
||||
const updateTraceCodeMany = async ({ where, data }: any) => {
|
||||
const count =
|
||||
options.traceUpdateCount ??
|
||||
(state.code.id === where.id && (where.outTime === undefined || state.code.outTime === where.outTime) ? 1 : 0);
|
||||
if (count === 1) Object.assign(state.code, data);
|
||||
return { count };
|
||||
};
|
||||
const updateJob = async ({ where, data }: any) => {
|
||||
if (state.job.id !== where.id) throw new Error('job not found');
|
||||
Object.assign(state.job, data);
|
||||
return clone(state.job);
|
||||
};
|
||||
const updateJobMany = async ({ where, data }: any) => {
|
||||
const allowedStatuses = Array.isArray(where.status?.in) ? where.status.in : null;
|
||||
const statusMatches = where.status === undefined
|
||||
|| where.status === state.job.status
|
||||
|| (allowedStatuses && allowedStatuses.includes(state.job.status));
|
||||
if (state.job.id !== where.id || !statusMatches) return { count: 0 };
|
||||
Object.assign(state.job, data);
|
||||
return { count: 1 };
|
||||
};
|
||||
|
||||
const tx = {
|
||||
outboundImportSession: {
|
||||
updateMany: jest.fn(updateSessionMany),
|
||||
update: jest.fn(updateSession),
|
||||
},
|
||||
outboundImportRow: {
|
||||
updateMany: jest.fn(updateRowsMany),
|
||||
count: jest.fn(countRows),
|
||||
},
|
||||
traceCode: {
|
||||
updateMany: jest.fn(updateTraceCodeMany),
|
||||
},
|
||||
job: {
|
||||
update: jest.fn(updateJob),
|
||||
updateMany: jest.fn(updateJobMany),
|
||||
},
|
||||
};
|
||||
const prisma = {
|
||||
outboundImportSession: {
|
||||
findUnique: jest.fn().mockImplementation(async () => clone(state.session)),
|
||||
count: jest.fn().mockImplementation(async ({ where }: any) => (sessionMatches(where) ? 1 : 0)),
|
||||
updateMany: jest.fn(updateSessionMany),
|
||||
update: jest.fn(updateSession),
|
||||
},
|
||||
outboundImportRow: {
|
||||
findMany: jest.fn().mockImplementation(async ({ where }: any) =>
|
||||
state.rows.filter((row) => rowMatches(row, where)).map((row) => clone(row)),
|
||||
),
|
||||
findUnique: jest.fn().mockImplementation(async ({ where }: any) =>
|
||||
clone(state.rows.find((row) => row.id === where.id) ?? null),
|
||||
),
|
||||
updateMany: jest.fn(updateRowsMany),
|
||||
count: jest.fn(countRows),
|
||||
},
|
||||
traceCode: {
|
||||
findUnique: jest.fn().mockImplementation(async ({ where }: any) =>
|
||||
where.shortCode === state.code.shortCode ? clone(state.code) : null,
|
||||
),
|
||||
},
|
||||
job: {
|
||||
update: jest.fn(updateJob),
|
||||
},
|
||||
$transaction: jest.fn().mockImplementation(async (operation: any) => {
|
||||
if (typeof operation !== 'function') return Promise.all(operation);
|
||||
const snapshot = clone(state);
|
||||
try {
|
||||
return await operation(tx);
|
||||
} catch (error) {
|
||||
state.session = snapshot.session;
|
||||
state.rows = snapshot.rows;
|
||||
state.code = snapshot.code;
|
||||
state.job = snapshot.job;
|
||||
throw error;
|
||||
}
|
||||
}),
|
||||
};
|
||||
const storage = {
|
||||
copyMedia: jest.fn().mockImplementation(async (items: any[]) => ({ items, keyMap: new Map() })),
|
||||
save: jest.fn().mockResolvedValue({ key: 'unused.xlsx' }),
|
||||
remove: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const jobs = {
|
||||
start: jest.fn().mockResolvedValue(undefined),
|
||||
progress: jest.fn().mockResolvedValue(undefined),
|
||||
finish: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const processor = new ImportProcessor(prisma as any, storage as any, jobs as any);
|
||||
jest.spyOn((processor as any).logger, 'log').mockImplementation(() => undefined);
|
||||
jest.spyOn((processor as any).logger, 'warn').mockImplementation(() => undefined);
|
||||
jest.spyOn((processor as any).logger, 'error').mockImplementation(() => undefined);
|
||||
|
||||
return { processor, prisma, storage, jobs, tx, state };
|
||||
}
|
||||
|
||||
async function process(processor: ImportProcessor, jobId = 'job-1'): Promise<void> {
|
||||
await processor.process({ data: { jobId, sessionId: 'session-1' } } as any);
|
||||
}
|
||||
|
||||
describe('ImportProcessor', () => {
|
||||
it('claims the persisted import job and commits the trace code, row, session and job transactionally', async () => {
|
||||
const row = importRow({ remark: 'ok' });
|
||||
const harness = createHarness({ rows: [row] });
|
||||
|
||||
await process(harness.processor);
|
||||
|
||||
expect(harness.tx.outboundImportSession.updateMany).toHaveBeenCalledWith({
|
||||
where: { id: 'session-1', status: 'IMPORTING', importJobId: 'job-1' },
|
||||
data: { importRunToken: expect.any(String) },
|
||||
});
|
||||
expect(harness.tx.traceCode.updateMany).toHaveBeenCalledWith({
|
||||
where: { id: 11n, outTime: null },
|
||||
data: {
|
||||
outTime: row.outTime,
|
||||
outImages: expect.anything(),
|
||||
remark: 'ok',
|
||||
},
|
||||
});
|
||||
expect(harness.tx.outboundImportRow.updateMany).toHaveBeenCalledWith({
|
||||
where: { id: 1n, status: 'VALID' },
|
||||
data: { status: 'IMPORTED', reason: null, outImageKeys: [] },
|
||||
});
|
||||
expect(harness.tx.outboundImportSession.update).toHaveBeenCalledWith({
|
||||
where: { id: 'session-1' },
|
||||
data: {
|
||||
status: 'IMPORTED',
|
||||
validCount: 1,
|
||||
invalidCount: 0,
|
||||
error: null,
|
||||
importRunToken: null,
|
||||
},
|
||||
});
|
||||
expect(harness.tx.job.update).toHaveBeenCalledWith({
|
||||
where: { id: 'job-1' },
|
||||
data: {
|
||||
total: 1,
|
||||
successCount: 1,
|
||||
failCount: 0,
|
||||
status: JobStatus.SUCCESS,
|
||||
resultFileUrl: '/outbound/import-sessions/session-1/result',
|
||||
error: null,
|
||||
},
|
||||
});
|
||||
expect(harness.storage.save).not.toHaveBeenCalled();
|
||||
expect(harness.jobs.finish).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('copies media, stores only the copied keys and removes the temporary source after commit', async () => {
|
||||
const row = importRow({
|
||||
outImageKeys: [{ key: 'temp/image.jpg', name: 'image.jpg', type: 'image' }],
|
||||
preview: { images: ['temp/image.jpg'] },
|
||||
});
|
||||
const harness = createHarness({ rows: [row] });
|
||||
harness.storage.copyMedia.mockImplementation(async (_items: any[], _dir: string, _baseName: string, onPlanned: any) => {
|
||||
await onPlanned(['final/image.jpg']);
|
||||
return {
|
||||
items: [{ key: 'final/image.jpg', name: 'image.jpg', type: 'image' }],
|
||||
keyMap: new Map([['temp/image.jpg', 'final/image.jpg']]),
|
||||
};
|
||||
});
|
||||
|
||||
await process(harness.processor);
|
||||
|
||||
expect(harness.storage.copyMedia).toHaveBeenCalledWith(
|
||||
[{ key: 'temp/image.jpg', name: 'image.jpg', type: 'image' }],
|
||||
'1/ARTVERIS-000001/111111111111',
|
||||
'出库实况',
|
||||
expect.any(Function),
|
||||
);
|
||||
expect(harness.tx.outboundImportRow.updateMany).toHaveBeenCalledWith({
|
||||
where: { id: 1n, status: 'VALID' },
|
||||
data: { preview: expect.objectContaining({ pendingCopiedKeys: ['final/image.jpg'] }) },
|
||||
});
|
||||
expect(harness.tx.outboundImportRow.updateMany).toHaveBeenCalledWith({
|
||||
where: { id: 1n, status: 'VALID' },
|
||||
data: {
|
||||
status: 'IMPORTED',
|
||||
reason: null,
|
||||
outImageKeys: [{ key: 'final/image.jpg', name: 'image.jpg', type: 'image' }],
|
||||
},
|
||||
});
|
||||
expect(harness.storage.remove).toHaveBeenCalledWith('temp/image.jpg');
|
||||
expect(harness.storage.remove).not.toHaveBeenCalledWith('final/image.jpg');
|
||||
expect(harness.prisma.outboundImportRow.updateMany).toHaveBeenCalledWith({
|
||||
where: { id: 1n, status: 'IMPORTED' },
|
||||
data: { preview: expect.anything() },
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects a concurrent duplicate outbound atomically and removes only the uncommitted copies', async () => {
|
||||
const row = importRow({ outImageKeys: [{ key: 'temp/image.jpg', name: 'image.jpg', type: 'image' }] });
|
||||
const harness = createHarness({ rows: [row], traceUpdateCount: 0 });
|
||||
harness.storage.copyMedia.mockImplementation(async (_items: any[], _dir: string, _baseName: string, onPlanned: any) => {
|
||||
await onPlanned(['final/image.jpg']);
|
||||
return {
|
||||
items: [{ key: 'final/image.jpg', name: 'image.jpg', type: 'image' }],
|
||||
keyMap: new Map([['temp/image.jpg', 'final/image.jpg']]),
|
||||
};
|
||||
});
|
||||
|
||||
await process(harness.processor);
|
||||
|
||||
expect(harness.storage.remove).toHaveBeenCalledWith('final/image.jpg');
|
||||
expect(harness.storage.remove).not.toHaveBeenCalledWith('temp/image.jpg');
|
||||
expect(harness.tx.outboundImportRow.updateMany).toHaveBeenCalledWith({
|
||||
where: { id: 1n, status: 'VALID' },
|
||||
data: { status: 'FAILED', reason: '该追溯码已登记出库,不可重复出库' },
|
||||
});
|
||||
expect(harness.state.session).toEqual(
|
||||
expect.objectContaining({ status: 'FAILED', validCount: 0, invalidCount: 1, importRunToken: null }),
|
||||
);
|
||||
expect(harness.state.job).toEqual(
|
||||
expect.objectContaining({
|
||||
status: JobStatus.FAILED,
|
||||
successCount: 0,
|
||||
failCount: 1,
|
||||
resultFileUrl: '/outbound/import-sessions/session-1/result',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('records all planned destination keys before copying so failed cleanup remains recoverable', async () => {
|
||||
const row = importRow({
|
||||
outImageKeys: [{ key: 'temp/first.jpg' }, { key: 'temp/second.jpg' }],
|
||||
preview: { images: ['temp/first.jpg', 'temp/second.jpg'] },
|
||||
});
|
||||
const harness = createHarness({ rows: [row] });
|
||||
harness.storage.copyMedia.mockImplementation(
|
||||
async (_items: any[], _dir: string, _baseName: string, onPlanned: any) => {
|
||||
await onPlanned(['final/first.jpg', 'final/second.jpg']);
|
||||
throw new Error('copy failed');
|
||||
},
|
||||
);
|
||||
|
||||
await expect(process(harness.processor)).resolves.toBeUndefined();
|
||||
|
||||
expect(harness.state.rows[0].preview).toEqual(expect.objectContaining({
|
||||
pendingCopiedKeys: ['final/first.jpg', 'final/second.jpg'],
|
||||
}));
|
||||
expect(harness.state.rows[0]).toEqual(expect.objectContaining({
|
||||
status: 'FAILED',
|
||||
reason: 'copy failed',
|
||||
}));
|
||||
});
|
||||
|
||||
it('rechecks the batch number before copying media or updating the trace code', async () => {
|
||||
const harness = createHarness({ code: traceCode({ batch: { batchNo: 'B2' } }) });
|
||||
|
||||
await process(harness.processor);
|
||||
|
||||
expect(harness.storage.copyMedia).not.toHaveBeenCalled();
|
||||
expect(harness.tx.traceCode.updateMany).not.toHaveBeenCalled();
|
||||
expect(harness.tx.outboundImportRow.updateMany).toHaveBeenCalledWith({
|
||||
where: { id: 1n, status: 'VALID' },
|
||||
data: { status: 'FAILED', reason: '批次编号不匹配,实际为 B2' },
|
||||
});
|
||||
});
|
||||
|
||||
it('resumes a stalled task and includes rows imported by the previous run', async () => {
|
||||
const rows = [
|
||||
importRow({ id: 1n, status: 'IMPORTED' }),
|
||||
importRow({ id: 2n, rowNo: 3, shortCode: '222222222222' }),
|
||||
];
|
||||
const harness = createHarness({ rows, code: traceCode({ id: 22n, shortCode: '222222222222' }) });
|
||||
|
||||
await process(harness.processor);
|
||||
|
||||
expect(harness.tx.traceCode.updateMany).toHaveBeenCalledTimes(1);
|
||||
expect(harness.state.session).toEqual(
|
||||
expect.objectContaining({ status: 'IMPORTED', validCount: 2, invalidCount: 0 }),
|
||||
);
|
||||
expect(harness.state.job).toEqual(
|
||||
expect.objectContaining({ status: JobStatus.SUCCESS, successCount: 2, failCount: 0 }),
|
||||
);
|
||||
});
|
||||
|
||||
it('lets a newer overlapping run win without allowing the superseded run to write or delete winner media', async () => {
|
||||
const row = importRow({
|
||||
outImageKeys: [{ key: 'temp/source.jpg', name: 'source.jpg', type: 'image' }],
|
||||
});
|
||||
const harness = createHarness({ rows: [row] });
|
||||
let releaseOldCopy!: () => void;
|
||||
let notifyOldCopyStarted!: () => void;
|
||||
const oldCopyStarted = new Promise<void>((resolve) => {
|
||||
notifyOldCopyStarted = resolve;
|
||||
});
|
||||
const oldCopyBlocked = new Promise<void>((resolve) => {
|
||||
releaseOldCopy = resolve;
|
||||
});
|
||||
harness.storage.copyMedia
|
||||
.mockImplementationOnce(async (_items: any[], _dir: string, _baseName: string, onPlanned: any) => {
|
||||
await onPlanned(['final/old.jpg']);
|
||||
notifyOldCopyStarted();
|
||||
await oldCopyBlocked;
|
||||
return {
|
||||
items: [{ key: 'final/old.jpg', name: 'old.jpg', type: 'image' }],
|
||||
keyMap: new Map([['temp/source.jpg', 'final/old.jpg']]),
|
||||
};
|
||||
})
|
||||
.mockImplementationOnce(async (_items: any[], _dir: string, _baseName: string, onPlanned: any) => {
|
||||
await onPlanned(['final/winner.jpg']);
|
||||
return {
|
||||
items: [{ key: 'final/winner.jpg', name: 'winner.jpg', type: 'image' }],
|
||||
keyMap: new Map([['temp/source.jpg', 'final/winner.jpg']]),
|
||||
};
|
||||
});
|
||||
|
||||
const oldRun = process(harness.processor);
|
||||
await oldCopyStarted;
|
||||
const winnerRun = process(harness.processor);
|
||||
await winnerRun;
|
||||
releaseOldCopy();
|
||||
await oldRun;
|
||||
|
||||
const claims = harness.tx.outboundImportSession.updateMany.mock.calls
|
||||
.map(([call]: any[]) => call)
|
||||
.filter((call: any) => call.data.importRunToken);
|
||||
expect(claims).toHaveLength(2);
|
||||
expect(claims[0].data.importRunToken).not.toBe(claims[1].data.importRunToken);
|
||||
expect(harness.tx.traceCode.updateMany).toHaveBeenCalledTimes(1);
|
||||
expect(harness.tx.outboundImportRow.updateMany).toHaveBeenCalledTimes(3);
|
||||
expect(harness.tx.outboundImportSession.update).toHaveBeenCalledTimes(1);
|
||||
expect(harness.tx.job.update).toHaveBeenCalledTimes(1);
|
||||
expect(harness.state.rows[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
status: 'IMPORTED',
|
||||
outImageKeys: [{ key: 'final/winner.jpg', name: 'winner.jpg', type: 'image' }],
|
||||
}),
|
||||
);
|
||||
expect(harness.state.session).toEqual(
|
||||
expect.objectContaining({ status: 'IMPORTED', validCount: 1, invalidCount: 0, importRunToken: null }),
|
||||
);
|
||||
expect(harness.storage.remove).toHaveBeenCalledWith('final/old.jpg');
|
||||
expect(harness.storage.remove).not.toHaveBeenCalledWith('final/winner.jpg');
|
||||
});
|
||||
|
||||
it('prevents an older run delayed in source cleanup from overwriting terminal job progress', async () => {
|
||||
const row = importRow({ outImageKeys: [{ key: 'temp/source.jpg', name: 'source.jpg', type: 'image' }] });
|
||||
const harness = createHarness({ rows: [row] });
|
||||
harness.storage.copyMedia.mockImplementation(
|
||||
async (_items: any[], _dir: string, _baseName: string, onPlanned: any) => {
|
||||
await onPlanned(['final/old.jpg']);
|
||||
return {
|
||||
items: [{ key: 'final/old.jpg', name: 'old.jpg', type: 'image' }],
|
||||
keyMap: new Map([['temp/source.jpg', 'final/old.jpg']]),
|
||||
};
|
||||
},
|
||||
);
|
||||
let releaseCleanup!: () => void;
|
||||
let notifyCleanupStarted!: () => void;
|
||||
const cleanupStarted = new Promise<void>((resolve) => { notifyCleanupStarted = resolve; });
|
||||
const cleanupBlocked = new Promise<void>((resolve) => { releaseCleanup = resolve; });
|
||||
harness.storage.remove.mockImplementationOnce(async () => {
|
||||
notifyCleanupStarted();
|
||||
await cleanupBlocked;
|
||||
});
|
||||
|
||||
const oldRun = process(harness.processor);
|
||||
await cleanupStarted;
|
||||
await process(harness.processor);
|
||||
releaseCleanup();
|
||||
await oldRun;
|
||||
|
||||
expect(harness.state.session).toEqual(expect.objectContaining({ status: 'IMPORTED', importRunToken: null }));
|
||||
expect(harness.state.job).toEqual(expect.objectContaining({
|
||||
status: JobStatus.SUCCESS,
|
||||
successCount: 1,
|
||||
failCount: 0,
|
||||
}));
|
||||
});
|
||||
|
||||
it('ignores a delivery whose job id is not the session import job', async () => {
|
||||
const harness = createHarness();
|
||||
|
||||
await process(harness.processor, 'stale-job');
|
||||
|
||||
expect(harness.jobs.start).not.toHaveBeenCalled();
|
||||
expect(harness.prisma.outboundImportRow.findMany).not.toHaveBeenCalled();
|
||||
expect(harness.tx.traceCode.updateMany).not.toHaveBeenCalled();
|
||||
expect(harness.state.session).toEqual(
|
||||
expect.objectContaining({ status: 'IMPORTING', importJobId: 'job-1', importRunToken: null }),
|
||||
);
|
||||
});
|
||||
|
||||
it('returns without mutating a terminal session when BullMQ redelivers an old job', async () => {
|
||||
const harness = createHarness({ session: { status: 'IMPORTED' } });
|
||||
|
||||
await process(harness.processor);
|
||||
|
||||
expect(harness.jobs.start).not.toHaveBeenCalled();
|
||||
expect(harness.prisma.outboundImportSession.updateMany).not.toHaveBeenCalled();
|
||||
expect(harness.prisma.outboundImportRow.findMany).not.toHaveBeenCalled();
|
||||
expect(harness.tx.job.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('marks the session, pending rows and job terminal when an owned run aborts unexpectedly', async () => {
|
||||
const harness = createHarness();
|
||||
harness.prisma.outboundImportRow.findMany.mockRejectedValueOnce(new Error('database unavailable'));
|
||||
|
||||
await expect(process(harness.processor)).rejects.toThrow('database unavailable');
|
||||
|
||||
const reason = '导入任务异常中止:database unavailable';
|
||||
expect(harness.tx.outboundImportRow.updateMany).toHaveBeenCalledWith({
|
||||
where: { sessionId: 'session-1', status: 'VALID' },
|
||||
data: { status: 'FAILED', reason },
|
||||
});
|
||||
expect(harness.state.session).toEqual(
|
||||
expect.objectContaining({
|
||||
status: 'FAILED',
|
||||
validCount: 0,
|
||||
invalidCount: 1,
|
||||
error: reason,
|
||||
importRunToken: null,
|
||||
}),
|
||||
);
|
||||
expect(harness.state.job).toEqual(
|
||||
expect.objectContaining({
|
||||
status: JobStatus.FAILED,
|
||||
successCount: 0,
|
||||
failCount: 1,
|
||||
resultFileUrl: '/outbound/import-sessions/session-1/result',
|
||||
error: reason,
|
||||
}),
|
||||
);
|
||||
expect(harness.storage.save).not.toHaveBeenCalled();
|
||||
expect(harness.jobs.finish).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user