feat: add operator replay, fault injection scenarios and staging cleanup

This commit is contained in:
2026-11-16 14:02:27 +03:00
parent 350cc23e54
commit 3e0033fc79
9 changed files with 335 additions and 8 deletions
+32 -1
View File
@@ -7,7 +7,7 @@ import { PrismaService } from '../src/db/prisma.service';
import { jobMessage, parseJobMessage } from '../src/jobs/job-message';
import { backoffMs, recoverExpiredLeases, replayJob, republishStale } from '../src/jobs/job-store';
import { JobProcessor, processorOptions } from '../src/jobs/processor';
import { fitInside } from '../src/jobs/variants';
import { fitInside, InvalidImageError, renderVariants } from '../src/jobs/variants';
import { S3Service } from '../src/storage/s3.service';
import {
bearer,
@@ -172,6 +172,14 @@ describe('Фоновая обработка вложений (e2e)', () => {
expect([thumbnail.width, thumbnail.height]).toEqual([160, 256]);
});
it('worker ограничивает пиксели до распаковки: превышение — InvalidImageError', async () => {
const image = await sharp({ create: { width: 300, height: 200, channels: 3, background: '#000' } })
.png()
.toBuffer();
await expect(renderVariants(image, 300 * 200 - 1)).rejects.toBeInstanceOf(InvalidImageError);
await expect(renderVariants(image, 300 * 200)).resolves.toHaveLength(3);
});
it('размеры округляются вниз, минимум 1 px', () => {
expect(fitInside(320, 200, 256)).toEqual({ width: 256, height: 160 });
expect(fitInside(1000, 3, 256)).toEqual({ width: 256, height: 1 });
@@ -235,6 +243,29 @@ describe('Фоновая обработка вложений (e2e)', () => {
expect(await events(id)).toEqual(['enqueued', 'processing', 'lease_expired', 'processing', 'ready']);
});
it('worker упал после COMMIT, до ack: повтор — no-op, staging убирается при повторной доставке', async () => {
const id = await upload();
await expect(
processAttachment(app, id, {
afterCommit: async () => {
throw new Error('worker crashed');
},
}),
).rejects.toThrow('worker crashed');
expect((await metadata(id)).status).toBe('ready');
expect((await prisma.attachment.findUniqueOrThrow({ where: { id } })).stagingKey).toBe(`staging/${id}`);
const put = jest.spyOn(s3, 'putBuffer');
try {
expect(await processAttachment(app, id)).toBe('skipped');
expect(put).not.toHaveBeenCalled();
} finally {
put.mockRestore();
}
expect((await prisma.attachment.findUniqueOrThrow({ where: { id } })).stagingKey).toBeNull();
expect(await prisma.attachmentVariant.count({ where: { attachmentId: id } })).toBe(3);
expect(await events(id)).toEqual(['enqueued', 'processing', 'ready']);
});
it('сообщение потеряно брокером: queued без свежей публикации публикуется повторно один раз', async () => {
const id = await upload();
const row = await job(id);
+29
View File
@@ -241,6 +241,35 @@ describe('Сверка объектов S3 с метаданными (e2e)', ()
const row = await prisma.attachment.findUniqueOrThrow({ where: { id: res.body.id } });
expect(row.stagingKey).toBeNull();
});
it('staging ready-вложения, оставшийся после сбоя worker, удаляется без ожидания срока хранения', async () => {
const res = await request(server)
.post(`/api/v1/chats/${chatId}/attachments?filename=a.png`)
.set('Authorization', bearer(alice))
.set('Content-Type', 'image/png')
.send(SAMPLE_PNG)
.expect(202);
await expect(
processAttachment(app, res.body.id, {
afterCommit: async () => {
throw new Error('worker crashed');
},
}),
).rejects.toThrow('worker crashed');
expect(await exists(`staging/${res.body.id}`)).toBe(true);
const report = await reconcile(prisma, s3, {
apply: true,
graceMs: HOUR_MS,
prefix: `staging/${res.body.id}`,
stagingRetentionMs: 24 * HOUR_MS,
});
expect(report.staging_expired).toBeGreaterThanOrEqual(1);
expect(await exists(`staging/${res.body.id}`)).toBe(false);
await request(server)
.get(`/api/v1/attachments/${res.body.id}/content`)
.set('Authorization', bearer(alice))
.expect(200);
});
});
describe('Готовность при отказе S3 (e2e)', () => {