fix: close cleanup and replay races, integer thumbnail sizing, sharp deadline, contract tests

This commit is contained in:
2026-11-16 16:56:50 +03:00
parent 3e0033fc79
commit 484119a6a9
9 changed files with 437 additions and 28 deletions
+68
View File
@@ -2,6 +2,7 @@ import { INestApplication } from '@nestjs/common';
import { createHash, randomUUID } from 'crypto';
import sharp from 'sharp';
import request from 'supertest';
import { reconcile } from '../src/attachments/reconciler';
import { ApiError } from '../src/common/filters/api-error';
import { PrismaService } from '../src/db/prisma.service';
import { jobMessage, parseJobMessage } from '../src/jobs/job-message';
@@ -180,6 +181,22 @@ describe('Фоновая обработка вложений (e2e)', () => {
await expect(renderVariants(image, 300 * 200)).resolves.toHaveLength(3);
});
it('размеры считаются целочисленно: 319×200 → 256×160, перебор совпадает с точной формулой', () => {
expect(fitInside(319, 200, 256)).toEqual({ width: 256, height: 160 });
for (let width = 1; width <= 3000; width++) {
for (const height of [1, 7, 100, 199, 200, 256, 257, 333, 1000, 2999]) {
const longest = BigInt(Math.max(width, height));
const expected =
width <= 256 && height <= 256
? { width, height }
: width >= height
? { width: 256, height: Math.max(1, Number((BigInt(height) * 256n) / longest)) }
: { width: Math.max(1, Number((BigInt(width) * 256n) / longest)), height: 256 };
expect(fitInside(width, height, 256)).toEqual(expected);
}
}
});
it('размеры округляются вниз, минимум 1 px', () => {
expect(fitInside(320, 200, 256)).toEqual({ width: 256, height: 160 });
expect(fitInside(1000, 3, 256)).toEqual({ width: 256, height: 1 });
@@ -354,6 +371,57 @@ describe('Фоновая обработка вложений (e2e)', () => {
expect(replayed.detail).toBe('by test-operator; previous retry_exhausted after attempt 2');
});
it('lease истёк на последней попытке — failed retry_exhausted, а не вечный processing', async () => {
const id = await upload();
await prisma.attachmentJob.updateMany({ where: { attachmentId: id }, data: { maxAttempts: 1 } });
await expect(
processAttachment(app, id, {
afterStore: async () => {
throw new Error('worker crashed');
},
}),
).rejects.toThrow('worker crashed');
await recoverExpiredLeases(prisma, new Date(Date.now() + 10 * 60 * 1000));
expect(await job(id)).toMatchObject({ status: 'failed', errorCode: 'retry_exhausted', leaseOwner: null });
expect(await metadata(id)).toMatchObject({ status: 'failed', error_code: 'retry_exhausted' });
});
it('replay и очистка staging не теряют исходник ни при каком порядке', async () => {
const fail = async () => {
const id = await upload();
await prisma.attachmentJob.updateMany({
where: { attachmentId: id },
data: { status: 'failed', errorCode: 'retry_exhausted' },
});
await prisma.attachment.update({
where: { id },
data: { status: 'failed', errorCode: 'retry_exhausted' },
});
return id;
};
const expire = (id: string) =>
reconcile(prisma, s3, {
apply: true,
graceMs: 0,
prefix: `staging/${id}`,
stagingRetentionMs: 0,
now: new Date(Date.now() + 1000),
});
const replayedFirst = await fail();
expect(await replayJob(prisma, (await job(replayedFirst)).id, 'test-operator')).toBe('replayed');
await expire(replayedFirst);
expect(await s3.getBuffer(`staging/${replayedFirst}`, MAX_BYTES)).toHaveLength(SAMPLE_PNG.length);
expect(await processAttachment(app, replayedFirst)).toBe('ready');
const expiredFirst = await fail();
await expire(expiredFirst);
await expect(s3.getBuffer(`staging/${expiredFirst}`, MAX_BYTES)).rejects.toThrow('missing');
expect(await replayJob(prisma, (await job(expiredFirst)).id, 'test-operator')).toBe('source_missing');
expect(await job(expiredFirst)).toMatchObject({ status: 'failed' });
expect(await metadata(expiredFirst)).toMatchObject({ status: 'failed' });
});
it('replay задания в очереди не создаёт дубль', async () => {
const id = await upload();
expect(await replayJob(prisma, (await job(id)).id, 'test-operator')).toBe('not_failed');