Files
mtusi2026lab6/test/jobs.e2e-spec.ts
T

514 lines
23 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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';
import { backoffMs, recoverExpiredLeases, replayJob, republishStale } from '../src/jobs/job-store';
import { JobProcessor, processorOptions } from '../src/jobs/processor';
import { fitInside, InvalidImageError, renderVariants } from '../src/jobs/variants';
import { S3Service } from '../src/storage/s3.service';
import {
bearer,
createTestApp,
processAttachment,
registerUser,
TestUser,
} from './helpers';
import { SAMPLE_PNG } from './images';
const MAX_BYTES = 10 * 1024 * 1024;
describe('Фоновая обработка вложений (e2e)', () => {
let app: INestApplication;
let server: any;
let prisma: PrismaService;
let s3: S3Service;
let alice: TestUser;
let eve: TestUser;
let chatId: string;
const upload = async (body: Buffer = SAMPLE_PNG, type = 'image/png') => {
const res = await request(server)
.post(`/api/v1/chats/${chatId}/attachments?filename=a.png`)
.set('Authorization', bearer(alice))
.set('Content-Type', type)
.send(body)
.expect(202);
return res.body.id as string;
};
const metadata = async (id: string) =>
(await request(server).get(`/api/v1/attachments/${id}`).set('Authorization', bearer(alice)).expect(200)).body;
const content = (id: string, variant = 'original', user = alice) =>
request(server)
.get(`/api/v1/attachments/${id}/content?variant=${variant}`)
.set('Authorization', bearer(user))
.buffer(true)
.parse(binaryParser);
const job = (attachmentId: string) =>
prisma.attachmentJob.findFirstOrThrow({ where: { attachmentId } });
const makeDue = (attachmentId: string) =>
prisma.attachmentJob.updateMany({ where: { attachmentId }, data: { nextAttemptAt: new Date() } });
const events = async (attachmentId: string) =>
(
await prisma.jobEvent.findMany({
where: { job: { attachmentId } },
orderBy: { id: 'asc' },
})
).map((event) => event.event);
const sendMessage = (attachmentIds: string[]) =>
request(server)
.post(`/api/v1/chats/${chatId}/messages`)
.set('Authorization', bearer(alice))
.set('Idempotency-Key', randomUUID())
.send({ text: '', attachment_ids: attachmentIds });
beforeAll(async () => {
({ app, server } = await createTestApp());
prisma = app.get(PrismaService);
s3 = app.get(S3Service);
alice = await registerUser(server, 'job_alice');
eve = await registerUser(server, 'job_eve');
const chat = await request(server)
.post('/api/v1/chats')
.set('Authorization', bearer(alice))
.send({ title: 'Jobs', member_ids: [alice.id] })
.expect(201);
chatId = chat.body.id;
});
afterAll(async () => {
await app.close();
});
describe('до обработки', () => {
it('queued: метаданные доступны, content любого варианта — 409, сообщение с вложением создаётся', async () => {
const id = await upload();
expect(await metadata(id)).toMatchObject({ status: 'queued', variants: [], error_code: null });
for (const variant of ['original', 'thumbnail', 'crop', 'optimized']) {
const res = await content(id, variant).expect(409);
expect(JSON.parse(res.body.toString()).error.code).toBe('conflict');
}
await content(id, 'original', eve).expect(404);
await content(id, 'nonsense').expect(400);
const message = await sendMessage([id]).expect(201);
expect(message.body.attachment_ids).toEqual([id]);
});
});
describe('результат worker', () => {
it('ready: оригинал неизменен, thumbnail 256×160 JPEG, crop 128×128 JPEG, optimized WebP без увеличения', async () => {
const id = await upload();
expect(await processAttachment(app, id)).toBe('ready');
const meta = await metadata(id);
expect(meta.status).toBe('ready');
expect(meta.error_code).toBeNull();
expect(meta.variants.map((v: any) => [v.name, v.content_type, v.width, v.height])).toEqual([
['thumbnail', 'image/jpeg', 256, 160],
['crop', 'image/jpeg', 128, 128],
['optimized', 'image/webp', 320, 200],
]);
const original = await content(id).expect(200);
expect(Buffer.compare(original.body, SAMPLE_PNG)).toBe(0);
for (const variant of meta.variants) {
const res = await content(id, variant.name).expect(200);
expect(res.headers['content-type']).toBe(variant.content_type);
expect(res.body.length).toBe(variant.size_bytes);
expect(createHash('sha256').update(res.body).digest('hex')).toBe(variant.sha256);
const actual = await sharp(res.body).metadata();
expect([actual.format, actual.width, actual.height, actual.exif]).toEqual([
variant.content_type.split('/')[1],
variant.width,
variant.height,
undefined,
]);
}
const row = await prisma.attachment.findUniqueOrThrow({ where: { id } });
expect(row.stagingKey).toBeNull();
await expect(s3.getBuffer(`staging/${id}`, MAX_BYTES)).rejects.toThrow('missing');
expect(await events(id)).toEqual(['enqueued', 'processing', 'ready']);
});
it('маленький исходник не увеличивается в thumbnail/optimized, crop — увеличивается', async () => {
const small = await sharp({ create: { width: 100, height: 50, channels: 3, background: '#123456' } })
.png()
.toBuffer();
const id = await upload(small);
expect(await processAttachment(app, id)).toBe('ready');
const sizes = (await metadata(id)).variants.map((v: any) => [v.name, v.width, v.height]);
expect(sizes).toEqual([
['thumbnail', 100, 50],
['crop', 128, 128],
['optimized', 100, 50],
]);
});
it('прозрачность компонуется на белый, EXIF orientation применяется', async () => {
const transparent = await sharp({
create: { width: 40, height: 20, channels: 4, background: { r: 0, g: 0, b: 0, alpha: 0 } },
})
.png()
.toBuffer();
const alphaId = await upload(transparent);
expect(await processAttachment(app, alphaId)).toBe('ready');
const thumb = await content(alphaId, 'thumbnail').expect(200);
const { data } = await sharp(thumb.body).raw().toBuffer({ resolveWithObject: true });
expect(Math.min(...data)).toBeGreaterThanOrEqual(250);
const rotated = await sharp({ create: { width: 320, height: 200, channels: 3, background: '#808080' } })
.jpeg()
.withMetadata({ orientation: 6 })
.toBuffer();
const rotatedId = await upload(rotated, 'image/jpeg');
expect(await processAttachment(app, rotatedId)).toBe('ready');
const thumbnail = (await metadata(rotatedId)).variants.find((v: any) => v.name === 'thumbnail');
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('размеры считаются целочисленно: 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 });
expect(fitInside(333, 1000, 256)).toEqual({ width: 85, height: 256 });
expect(fitInside(10, 10, 256)).toEqual({ width: 10, height: 10 });
});
});
describe('идемпотентность и повторная доставка', () => {
it('повтор уже ready-задания — no-op: второго набора вариантов нет, объекты не меняются', async () => {
const id = await upload();
expect(await processAttachment(app, id)).toBe('ready');
const before = await prisma.attachmentVariant.findMany({ where: { attachmentId: id } });
const put = jest.spyOn(s3, 'putBuffer');
try {
expect(await processAttachment(app, id)).toBe('skipped');
expect(put).not.toHaveBeenCalled();
} finally {
put.mockRestore();
}
const after = await prisma.attachmentVariant.findMany({ where: { attachmentId: id } });
expect(after).toEqual(before);
expect(after).toHaveLength(3);
});
it('пока lease действует, второй обработчик того же job не запускается', async () => {
const id = await upload();
let concurrent: string | undefined;
const outcome = await processAttachment(app, id, {
afterStore: async () => {
concurrent = await processAttachment(app, id);
},
});
expect([outcome, concurrent]).toEqual(['ready', 'skipped']);
});
it('worker упал после записи объектов, до COMMIT/ack: lease истекает, повтор завершает тот же результат', async () => {
const id = await upload();
await expect(
processAttachment(app, id, {
afterStore: async () => {
throw new Error('worker crashed');
},
}),
).rejects.toThrow('worker crashed');
expect(await job(id)).toMatchObject({ status: 'processing', attempt: 1 });
expect((await metadata(id)).status).toBe('processing');
const stored = await s3.getBuffer(`attachments/${id}/v1/thumbnail.jpg`, MAX_BYTES);
expect(await recoverExpiredLeases(prisma)).toBe(0);
const future = new Date(Date.now() + 10 * 60 * 1000);
expect(await recoverExpiredLeases(prisma, future)).toBeGreaterThanOrEqual(1);
expect(await job(id)).toMatchObject({ status: 'queued', attempt: 2 });
await makeDue(id);
expect(await processAttachment(app, id)).toBe('ready');
const variants = await prisma.attachmentVariant.findMany({ where: { attachmentId: id } });
expect(variants).toHaveLength(3);
const thumbnail = variants.find((v) => v.name === 'thumbnail')!;
expect(thumbnail.sha256).toBe(createHash('sha256').update(stored).digest('hex'));
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);
const later = new Date(Date.now() + 10 * 60 * 1000);
expect(await republishStale(prisma, 5 * 60 * 1000, later)).toBe(0);
await prisma.outboxEntry.updateMany({
where: { jobId: row.id },
data: { publishedAt: new Date() },
});
expect(await republishStale(prisma, 5 * 60 * 1000, new Date())).toBe(0);
expect(await republishStale(prisma, 5 * 60 * 1000, later)).toBeGreaterThanOrEqual(1);
expect(await prisma.outboxEntry.count({ where: { jobId: row.id } })).toBe(2);
expect(await republishStale(prisma, 5 * 60 * 1000, later)).toBe(0);
expect(await prisma.outboxEntry.count({ where: { jobId: row.id } })).toBe(2);
expect(await processAttachment(app, id)).toBe('ready');
expect(await events(id)).toEqual(['enqueued', 'republished', 'processing', 'ready']);
});
it('устаревшее сообщение, чужой attachment_id и другая pipeline_version игнорируются', async () => {
const id = await upload();
const row = await job(id);
const processor = new JobProcessor(prisma, s3, processorOptions());
const base = jobMessage(row, new Date());
expect(await processor.handle({ ...base, attachment_id: randomUUID() })).toBe('skipped');
expect(await processor.handle({ ...base, pipeline_version: 2 })).toBe('skipped');
expect(await processor.handle({ ...base, job_id: randomUUID() })).toBe('skipped');
expect((await job(id)).status).toBe('queued');
});
});
describe('ошибки, повторы и replay', () => {
it('временная ошибка S3: повтор с backoff, до срока задание не берётся, затем ready', async () => {
const id = await upload();
const put = jest
.spyOn(s3, 'putBuffer')
.mockRejectedValueOnce(new ApiError('unavailable', 'object storage unavailable'));
try {
expect(await processAttachment(app, id)).toBe('retry');
} finally {
put.mockRestore();
}
const retried = await job(id);
expect(retried).toMatchObject({ status: 'queued', attempt: 2, lastError: 'temporary failure: ApiError' });
expect(retried.nextAttemptAt.getTime()).toBeGreaterThan(Date.now());
expect((await metadata(id)).status).toBe('queued');
const outbox = await prisma.outboxEntry.findMany({ where: { jobId: retried.id }, orderBy: { id: 'asc' } });
expect(outbox).toHaveLength(2);
expect(outbox[1].availableAt).toEqual(retried.nextAttemptAt);
expect((outbox[1].payload as any).attempt).toBe(2);
expect((outbox[1].payload as any).job_id).toBe(retried.id);
expect(await processAttachment(app, id)).toBe('skipped');
await makeDue(id);
expect(await processAttachment(app, id)).toBe('ready');
expect(await events(id)).toEqual(['enqueued', 'processing', 'retry_scheduled', 'processing', 'ready']);
});
it('попытки исчерпаны — failed retry_exhausted; replay явно возвращает в очередь и доводит до ready', async () => {
const id = await upload();
await prisma.attachmentJob.updateMany({ where: { attachmentId: id }, data: { maxAttempts: 2 } });
const put = jest
.spyOn(s3, 'putBuffer')
.mockRejectedValue(new ApiError('unavailable', 'object storage unavailable'));
try {
expect(await processAttachment(app, id)).toBe('retry');
await makeDue(id);
expect(await processAttachment(app, id)).toBe('failed');
} finally {
put.mockRestore();
}
expect(await metadata(id)).toMatchObject({ status: 'failed', error_code: 'retry_exhausted', variants: [] });
const failed = await job(id);
expect(failed).toMatchObject({ status: 'failed', errorCode: 'retry_exhausted', attempt: 2 });
await sendMessage([id]).expect(409);
expect(await replayJob(prisma, failed.id, 'test-operator')).toBe('replayed');
expect(await job(id)).toMatchObject({ status: 'queued', attempt: 1, errorCode: null });
expect(await metadata(id)).toMatchObject({ status: 'queued', error_code: null });
expect(await processAttachment(app, id)).toBe('ready');
const outboxBefore = await prisma.outboxEntry.count({ where: { jobId: failed.id } });
expect(await replayJob(prisma, failed.id, 'test-operator')).toBe('already_ready');
expect(await prisma.outboxEntry.count({ where: { jobId: failed.id } })).toBe(outboxBefore);
expect(await replayJob(prisma, randomUUID(), 'test-operator')).toBe('not_found');
const replayed = await prisma.jobEvent.findFirstOrThrow({ where: { jobId: failed.id, event: 'replayed' } });
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');
expect(await prisma.outboxEntry.count({ where: { job: { attachmentId: id } } })).toBe(1);
});
it('нераспаковываемое изображение — постоянная ошибка: сразу failed invalid_image без повторов', async () => {
const id = await upload();
const garbage = Buffer.concat([SAMPLE_PNG.subarray(0, 64), Buffer.alloc(512, 7)]);
const sha256 = createHash('sha256').update(garbage).digest('hex');
await s3.putBuffer(`staging/${id}`, garbage, 'image/png', sha256);
await prisma.attachment.update({ where: { id }, data: { sizeBytes: garbage.length, sha256 } });
expect(await processAttachment(app, id)).toBe('failed');
expect(await metadata(id)).toMatchObject({ status: 'failed', error_code: 'invalid_image', variants: [] });
expect(await job(id)).toMatchObject({ status: 'failed', attempt: 1, errorCode: 'invalid_image' });
await content(id).expect(409);
await sendMessage([id]).expect(409);
expect(await prisma.attachment.findUniqueOrThrow({ where: { id } })).toMatchObject({
stagingKey: `staging/${id}`,
});
});
it('staging подменён — failed checksum_mismatch; staging пропал — failed staging_missing', async () => {
const changed = await upload();
const other = await sharp({ create: { width: 8, height: 8, channels: 3, background: '#ff0000' } })
.png()
.toBuffer();
await s3.putBuffer(`staging/${changed}`, other, 'image/png', createHash('sha256').update(other).digest('hex'));
expect(await processAttachment(app, changed)).toBe('failed');
expect((await metadata(changed)).error_code).toBe('checksum_mismatch');
const missing = await upload();
await s3.delete(`staging/${missing}`);
expect(await processAttachment(app, missing)).toBe('failed');
expect((await metadata(missing)).error_code).toBe('staging_missing');
});
it('превышение времени обработки — временная ошибка с повтором', async () => {
const id = await upload();
const slow = jest
.spyOn(s3, 'getBuffer')
.mockImplementationOnce(() => new Promise((resolve) => setTimeout(() => resolve(SAMPLE_PNG), 500)));
try {
expect(await processAttachment(app, id, {}, { timeoutMs: 50 })).toBe('retry');
} finally {
slow.mockRestore();
}
expect((await job(id)).lastError).toBe('processing timed out');
});
});
describe('формат сообщения и backoff', () => {
it('сообщение соответствует jobs.schema.json, лишние/неверные поля отклоняются', () => {
const valid = jobMessage(
{ id: randomUUID(), attachmentId: randomUUID(), pipelineVersion: 1, attempt: 1 },
new Date(),
);
const encode = (value: unknown) => Buffer.from(JSON.stringify(value));
expect(parseJobMessage(encode(valid))).toEqual(valid);
for (const bad of [
{ ...valid, url: 'http://evil' },
{ ...valid, job_id: 'nope' },
{ ...valid, type: 'other' },
{ ...valid, attempt: 0 },
{ ...valid, schema_version: 2 },
{ ...valid, created_at: 'yesterday' },
[valid],
]) {
expect(parseJobMessage(encode(bad))).toBeNull();
}
expect(parseJobMessage(Buffer.from('{bad'))).toBeNull();
});
it('backoff растёт экспоненциально с jitter и ограничен сверху', () => {
expect(backoffMs(1, () => 0)).toBe(500);
expect(backoffMs(1, () => 1)).toBe(1000);
expect(backoffMs(3, () => 0)).toBe(2000);
expect(backoffMs(3, () => 1)).toBe(4000);
expect(backoffMs(20, () => 1)).toBe(30000);
expect(backoffMs(20, () => 0)).toBe(15000);
});
});
});
function binaryParser(res: any, done: (error: Error | null, body: Buffer) => void): void {
const chunks: Buffer[] = [];
res.on('data', (chunk: Buffer) => chunks.push(chunk));
res.on('end', () => done(null, Buffer.concat(chunks)));
}