forked from mtusi2026/mtusi2026lab5
feat: accept uploads into staging with jobs, outbox and job processor
This commit is contained in:
@@ -3,7 +3,13 @@ import { createHash, randomUUID } from 'crypto';
|
||||
import request from 'supertest';
|
||||
import { PrismaService } from '../src/db/prisma.service';
|
||||
import { S3Service } from '../src/storage/s3.service';
|
||||
import { bearer, createTestApp, registerUser, TestUser } from './helpers';
|
||||
import {
|
||||
bearer,
|
||||
createTestApp,
|
||||
processAttachment,
|
||||
registerUser,
|
||||
TestUser,
|
||||
} from './helpers';
|
||||
import { jpeg, SAMPLE_PNG } from './images';
|
||||
|
||||
describe('Скачивание и привязка вложений (e2e)', () => {
|
||||
@@ -35,8 +41,13 @@ describe('Скачивание и привязка вложений (e2e)', () =
|
||||
.set('Authorization', bearer(user))
|
||||
.set('Content-Type', type)
|
||||
.send(body)
|
||||
.expect(201);
|
||||
return res.body;
|
||||
.expect(202);
|
||||
expect(await processAttachment(app, res.body.id)).toBe('ready');
|
||||
const ready = await request(server)
|
||||
.get(`/api/v1/attachments/${res.body.id}`)
|
||||
.set('Authorization', bearer(user))
|
||||
.expect(200);
|
||||
return ready.body;
|
||||
};
|
||||
|
||||
const get = (path: string, user: TestUser | null = bob) => {
|
||||
@@ -134,7 +145,11 @@ describe('Скачивание и привязка вложений (e2e)', () =
|
||||
it('variant: original явно, отсутствующий 404, неизвестный и повторённый 400', async () => {
|
||||
const { id } = await upload();
|
||||
await get(`/api/v1/attachments/${id}/content?variant=original`).expect(200);
|
||||
await get(`/api/v1/attachments/${id}/content?variant=thumbnail`).expect(404);
|
||||
await get(`/api/v1/attachments/${id}/content?variant=thumbnail`).expect(200);
|
||||
await app.get(PrismaService).attachmentVariant.deleteMany({
|
||||
where: { attachmentId: id, name: 'crop' },
|
||||
});
|
||||
await get(`/api/v1/attachments/${id}/content?variant=crop`).expect(404);
|
||||
await get(`/api/v1/attachments/${id}/content?variant=nonsense`).expect(400);
|
||||
await get(`/api/v1/attachments/${id}/content?variant=`).expect(400);
|
||||
await get(`/api/v1/attachments/${id}/content?variant=original&variant=original`).expect(400);
|
||||
|
||||
@@ -2,9 +2,10 @@ import { INestApplication } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import Ajv2020 from 'ajv/dist/2020';
|
||||
import { createHash, randomUUID } from 'crypto';
|
||||
import { readdirSync } from 'fs';
|
||||
import { mkdtempSync, readdirSync, rmSync } from 'fs';
|
||||
import { connect } from 'net';
|
||||
import { tmpdir } from 'os';
|
||||
import { join } from 'path';
|
||||
import request from 'supertest';
|
||||
import { PrismaService } from '../src/db/prisma.service';
|
||||
import { loadDocument } from '../src/docs/swagger';
|
||||
@@ -61,8 +62,13 @@ describe('Загрузка вложений (e2e)', () => {
|
||||
expect(res.body.error.request_id).toBe(res.headers['x-request-id']);
|
||||
};
|
||||
|
||||
const uploadTmp = mkdtempSync(join(tmpdir(), 'attachments-test-'));
|
||||
|
||||
const activeTempDirs = (): string[] =>
|
||||
readdirSync(uploadTmp).filter((name) => name.startsWith('messenger-upload-'));
|
||||
|
||||
beforeAll(async () => {
|
||||
({ app, server } = await createTestApp());
|
||||
({ app, server } = await createTestApp({ UPLOAD_TMP_DIR: uploadTmp }));
|
||||
alice = await registerUser(server, 'att_alice');
|
||||
eve = await registerUser(server, 'att_eve');
|
||||
const chat = await request(server)
|
||||
@@ -75,11 +81,12 @@ describe('Загрузка вложений (e2e)', () => {
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
rmSync(uploadTmp, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('успешная загрузка', () => {
|
||||
it('возвращает 201 Attachment по контракту и сохраняет метаданные', async () => {
|
||||
const res = await upload(SAMPLE_PNG).expect(201);
|
||||
it('возвращает 202 Attachment queued по контракту, staging и задание сохранены до ответа', async () => {
|
||||
const res = await upload(SAMPLE_PNG).expect(202);
|
||||
const document: any = loadDocument();
|
||||
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
||||
ajv.addSchema(document, 'contract');
|
||||
@@ -95,22 +102,42 @@ describe('Загрузка вложений (e2e)', () => {
|
||||
content_type: 'image/png',
|
||||
size_bytes: SAMPLE_PNG.length,
|
||||
sha256: createHash('sha256').update(SAMPLE_PNG).digest('hex'),
|
||||
status: 'ready',
|
||||
status: 'queued',
|
||||
variants: [],
|
||||
error_code: null,
|
||||
});
|
||||
const row = await app.get(PrismaService).attachment.findUnique({
|
||||
const prisma = app.get(PrismaService);
|
||||
const row = await prisma.attachment.findUnique({
|
||||
where: { id: res.body.id },
|
||||
include: { jobs: { include: { outbox: true } } },
|
||||
});
|
||||
expect(row?.objectKey).toBe(`attachments/${res.body.id}`);
|
||||
expect(JSON.stringify(res.body)).not.toContain('attachments/');
|
||||
expect(row).toMatchObject({
|
||||
status: 'queued',
|
||||
objectKey: `attachments/${res.body.id}/original`,
|
||||
stagingKey: `staging/${res.body.id}`,
|
||||
});
|
||||
expect(row!.jobs).toHaveLength(1);
|
||||
expect(row!.jobs[0]).toMatchObject({ status: 'queued', attempt: 1, pipelineVersion: 1 });
|
||||
expect(row!.jobs[0].outbox).toHaveLength(1);
|
||||
expect(row!.jobs[0].outbox[0].payload).toEqual({
|
||||
schema_version: 1,
|
||||
job_id: row!.jobs[0].id,
|
||||
type: 'attachment.process.v1',
|
||||
attachment_id: res.body.id,
|
||||
pipeline_version: 1,
|
||||
attempt: 1,
|
||||
created_at: expect.any(String),
|
||||
});
|
||||
const staged = await app.get(S3Service).getBuffer(`staging/${res.body.id}`, MAX_BYTES);
|
||||
expect(Buffer.compare(staged, SAMPLE_PNG)).toBe(0);
|
||||
expect(JSON.stringify(res.body)).not.toMatch(/attachments\/|staging\//);
|
||||
});
|
||||
|
||||
it('принимает реальный JPEG', async () => {
|
||||
const res = await upload(await jpeg(), {
|
||||
type: 'image/jpeg',
|
||||
filename: 'фото 1.jpg',
|
||||
}).expect(201);
|
||||
}).expect(202);
|
||||
expect(res.body).toMatchObject({
|
||||
content_type: 'image/jpeg',
|
||||
filename: 'фото 1.jpg',
|
||||
@@ -118,21 +145,21 @@ describe('Загрузка вложений (e2e)', () => {
|
||||
});
|
||||
|
||||
it('игнорирует параметры и регистр Content-Type', async () => {
|
||||
await upload(SAMPLE_PNG, { type: 'IMAGE/PNG; charset=binary' }).expect(201);
|
||||
await upload(SAMPLE_PNG, { type: 'IMAGE/PNG; charset=binary' }).expect(202);
|
||||
});
|
||||
|
||||
it('принимает файл ровно 10 MiB, filename ровно 255 символов и PNG с байтами после IEND', async () => {
|
||||
const exact = pngOfExactSize(MAX_BYTES);
|
||||
expect(exact.length).toBe(MAX_BYTES);
|
||||
const res = await upload(exact).expect(201);
|
||||
const res = await upload(exact).expect(202);
|
||||
expect(res.body.size_bytes).toBe(MAX_BYTES);
|
||||
await upload(SAMPLE_PNG, { filename: `${'ф'.repeat(251)}.png` }).expect(201);
|
||||
await upload(Buffer.concat([png(4, 4), Buffer.from('tail')])).expect(201);
|
||||
await upload(SAMPLE_PNG, { filename: `${'ф'.repeat(251)}.png` }).expect(202);
|
||||
await upload(Buffer.concat([png(4, 4), Buffer.from('tail')])).expect(202);
|
||||
});
|
||||
|
||||
it('принимает ровно 40 млн пикселей', async () => {
|
||||
const res = await upload(await bigPng(8000, 5000));
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.status).toBe(202);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -154,10 +181,10 @@ describe('Загрузка вложений (e2e)', () => {
|
||||
|
||||
it('посторонний и несуществующий чат — одинаковый 404, чужой файл не сохраняется', async () => {
|
||||
const prisma = app.get(PrismaService);
|
||||
const before = await prisma.attachment.count();
|
||||
const before = await prisma.attachment.count({ where: { chatId } });
|
||||
expectError(await upload(SAMPLE_PNG, { user: eve }), 404, 'not_found');
|
||||
expectError(await upload(SAMPLE_PNG, { chat: randomUUID() }), 404, 'not_found');
|
||||
expect(await prisma.attachment.count()).toBe(before);
|
||||
expect(await prisma.attachment.count({ where: { chatId } })).toBe(before);
|
||||
});
|
||||
|
||||
it('неверный UUID чата — 400', async () => {
|
||||
@@ -260,7 +287,7 @@ describe('Загрузка вложений (e2e)', () => {
|
||||
|
||||
it('оборванная загрузка не оставляет временных файлов и строк в БД', async () => {
|
||||
const prisma = app.get(PrismaService);
|
||||
const before = await prisma.attachment.count();
|
||||
const before = await prisma.attachment.count({ where: { chatId } });
|
||||
const { port } = server.address();
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const socket = connect(port, '127.0.0.1', () => {
|
||||
@@ -278,7 +305,7 @@ describe('Загрузка вложений (e2e)', () => {
|
||||
socket.on('error', reject);
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
expect(await prisma.attachment.count()).toBe(before);
|
||||
expect(await prisma.attachment.count({ where: { chatId } })).toBe(before);
|
||||
expect(activeTempDirs()).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -290,7 +317,7 @@ describe('Загрузка вложений (e2e)', () => {
|
||||
});
|
||||
try {
|
||||
const prisma = app.get(PrismaService);
|
||||
const before = await prisma.attachment.count();
|
||||
const before = await prisma.attachment.count({ where: { chatId } });
|
||||
const started = Date.now();
|
||||
const res = await request(downServer)
|
||||
.post(`/api/v1/chats/${chatId}/attachments?filename=a.png`)
|
||||
@@ -299,17 +326,17 @@ describe('Загрузка вложений (e2e)', () => {
|
||||
.send(SAMPLE_PNG);
|
||||
expectError(res, 503, 'unavailable');
|
||||
expect(Date.now() - started).toBeLessThan(3000);
|
||||
expect(await prisma.attachment.count()).toBe(before);
|
||||
expect(await prisma.attachment.count({ where: { chatId } })).toBe(before);
|
||||
} finally {
|
||||
await down.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('явный отказ INSERT после PUT удаляет объект', async () => {
|
||||
it('явный отказ транзакции после PUT удаляет объект staging', async () => {
|
||||
const prisma = app.get(PrismaService);
|
||||
const s3 = app.get(S3Service);
|
||||
const remove = jest.spyOn(s3, 'delete');
|
||||
const create = jest.spyOn(prisma.attachment, 'create').mockRejectedValueOnce(
|
||||
const create = jest.spyOn(prisma, '$transaction').mockRejectedValueOnce(
|
||||
new Prisma.PrismaClientKnownRequestError('rejected', {
|
||||
code: 'P2003',
|
||||
clientVersion: 'test',
|
||||
@@ -319,6 +346,7 @@ describe('Загрузка вложений (e2e)', () => {
|
||||
const res = await upload(SAMPLE_PNG);
|
||||
expect(res.status).toBe(500);
|
||||
expect(remove).toHaveBeenCalledTimes(1);
|
||||
expect(remove.mock.calls[0][0]).toMatch(/^staging\//);
|
||||
} finally {
|
||||
create.mockRestore();
|
||||
remove.mockRestore();
|
||||
@@ -329,7 +357,7 @@ describe('Загрузка вложений (e2e)', () => {
|
||||
const prisma = app.get(PrismaService);
|
||||
const s3 = app.get(S3Service);
|
||||
const remove = jest.spyOn(s3, 'delete');
|
||||
const create = jest.spyOn(prisma.attachment, 'create').mockRejectedValueOnce(
|
||||
const create = jest.spyOn(prisma, '$transaction').mockRejectedValueOnce(
|
||||
new Prisma.PrismaClientUnknownRequestError('server closed the connection', {
|
||||
clientVersion: 'test',
|
||||
}),
|
||||
@@ -347,7 +375,7 @@ describe('Загрузка вложений (e2e)', () => {
|
||||
const prisma = app.get(PrismaService);
|
||||
const s3 = app.get(S3Service);
|
||||
const remove = jest.spyOn(s3, 'delete');
|
||||
const create = jest.spyOn(prisma.attachment, 'create').mockRejectedValueOnce(
|
||||
const create = jest.spyOn(prisma, '$transaction').mockRejectedValueOnce(
|
||||
new Prisma.PrismaClientKnownRequestError('connection lost', {
|
||||
code: 'P1017',
|
||||
clientVersion: 'test',
|
||||
@@ -364,9 +392,6 @@ describe('Загрузка вложений (e2e)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
function activeTempDirs(): string[] {
|
||||
return readdirSync(tmpdir()).filter((name) => name.startsWith('messenger-upload-'));
|
||||
}
|
||||
|
||||
async function bigPng(width: number, height: number): Promise<Buffer> {
|
||||
const { default: sharp } = await import('sharp');
|
||||
|
||||
@@ -8,6 +8,15 @@ import { randomUUID } from 'crypto';
|
||||
import request from 'supertest';
|
||||
import { AppModule } from '../src/app.module';
|
||||
import { configureApp } from '../src/configure-app';
|
||||
import { PrismaService } from '../src/db/prisma.service';
|
||||
import { parseJobMessage } from '../src/jobs/job-message';
|
||||
import {
|
||||
JobProcessor,
|
||||
Outcome,
|
||||
ProcessorOptions,
|
||||
processorOptions,
|
||||
} from '../src/jobs/processor';
|
||||
import { S3Service } from '../src/storage/s3.service';
|
||||
|
||||
export const PASSWORD = 'Correct-Horse-Battery-42';
|
||||
|
||||
@@ -43,6 +52,30 @@ export async function createTestApp(
|
||||
return { app, server: app.getHttpServer() };
|
||||
}
|
||||
|
||||
export async function processAttachment(
|
||||
app: INestApplication,
|
||||
attachmentId: string,
|
||||
hooks: { afterStore?: () => Promise<void> } = {},
|
||||
options: Partial<ProcessorOptions> = {},
|
||||
): Promise<Outcome> {
|
||||
const prisma = app.get(PrismaService);
|
||||
const entry = await prisma.outboxEntry.findFirstOrThrow({
|
||||
where: { job: { attachmentId } },
|
||||
orderBy: { id: 'desc' },
|
||||
});
|
||||
const message = parseJobMessage(Buffer.from(JSON.stringify(entry.payload)));
|
||||
if (!message) {
|
||||
throw new Error('outbox payload does not match jobs.schema.json');
|
||||
}
|
||||
const processor = new JobProcessor(
|
||||
prisma,
|
||||
app.get(S3Service),
|
||||
{ ...processorOptions(), ...options },
|
||||
hooks,
|
||||
);
|
||||
return processor.handle(message);
|
||||
}
|
||||
|
||||
export function basic(username: string, password: string): string {
|
||||
return `Basic ${Buffer.from(`${username}:${password}`, 'utf8').toString('base64')}`;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,396 @@
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import { createHash, randomUUID } from 'crypto';
|
||||
import sharp from 'sharp';
|
||||
import request from 'supertest';
|
||||
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 } from '../src/jobs/job-store';
|
||||
import { JobProcessor, processorOptions } from '../src/jobs/processor';
|
||||
import { fitInside } 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('размеры округляются вниз, минимум 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('устаревшее сообщение, чужой 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('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)));
|
||||
}
|
||||
@@ -7,7 +7,13 @@ import request from 'supertest';
|
||||
import { reconcile } from '../src/attachments/reconciler';
|
||||
import { PrismaService } from '../src/db/prisma.service';
|
||||
import { S3Service } from '../src/storage/s3.service';
|
||||
import { bearer, createTestApp, registerUser, TestUser } from './helpers';
|
||||
import {
|
||||
bearer,
|
||||
createTestApp,
|
||||
processAttachment,
|
||||
registerUser,
|
||||
TestUser,
|
||||
} from './helpers';
|
||||
import { SAMPLE_PNG } from './images';
|
||||
|
||||
const HOUR_MS = 60 * 60 * 1000;
|
||||
@@ -100,6 +106,7 @@ describe('Сверка объектов S3 с метаданными (e2e)', ()
|
||||
sizeBytes: SAMPLE_PNG.length,
|
||||
sha256: createHash('sha256').update(SAMPLE_PNG).digest('hex'),
|
||||
objectKey: key,
|
||||
status: 'ready',
|
||||
},
|
||||
});
|
||||
const report = await reconcile(prisma, s3, {
|
||||
@@ -164,13 +171,75 @@ describe('Сверка объектов S3 с метаданными (e2e)', ()
|
||||
.set('Authorization', bearer(alice))
|
||||
.set('Content-Type', 'image/png')
|
||||
.send(SAMPLE_PNG)
|
||||
.expect(201);
|
||||
.expect(202);
|
||||
expect(await processAttachment(app, upload.body.id)).toBe('ready');
|
||||
const report = await reconcile(prisma, s3, { apply: true, graceMs: HOUR_MS });
|
||||
expect(report.fresh_skipped).toBeGreaterThanOrEqual(1);
|
||||
await request(server)
|
||||
.get(`/api/v1/attachments/${upload.body.id}/content`)
|
||||
expect(report.fresh_skipped).toBeGreaterThanOrEqual(4);
|
||||
for (const variant of ['original', 'thumbnail', 'crop', 'optimized']) {
|
||||
await request(server)
|
||||
.get(`/api/v1/attachments/${upload.body.id}/content?variant=${variant}`)
|
||||
.set('Authorization', bearer(alice))
|
||||
.expect(200);
|
||||
}
|
||||
});
|
||||
|
||||
it('после grace period объекты вложения и staging в очереди не считаются сиротами', async () => {
|
||||
const queued = await request(server)
|
||||
.post(`/api/v1/chats/${chatId}/attachments?filename=a.png`)
|
||||
.set('Authorization', bearer(alice))
|
||||
.expect(200);
|
||||
.set('Content-Type', 'image/png')
|
||||
.send(SAMPLE_PNG)
|
||||
.expect(202);
|
||||
const ready = await request(server)
|
||||
.post(`/api/v1/chats/${chatId}/attachments?filename=b.png`)
|
||||
.set('Authorization', bearer(alice))
|
||||
.set('Content-Type', 'image/png')
|
||||
.send(SAMPLE_PNG)
|
||||
.expect(202);
|
||||
expect(await processAttachment(app, ready.body.id)).toBe('ready');
|
||||
for (const id of [queued.body.id, ready.body.id]) {
|
||||
for (const prefix of [`attachments/${id}/`, `staging/${id}`]) {
|
||||
const report = await reconcile(prisma, s3, {
|
||||
apply: true,
|
||||
graceMs: HOUR_MS,
|
||||
prefix,
|
||||
now: later(),
|
||||
});
|
||||
expect(report).toMatchObject({ orphans: 0, deleted: 0 });
|
||||
}
|
||||
}
|
||||
expect(await exists(`staging/${queued.body.id}`)).toBe(true);
|
||||
expect(await exists(`staging/${ready.body.id}`)).toBe(false);
|
||||
});
|
||||
|
||||
it('staging failed-вложения удаляется после срока хранения', 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 prisma.attachment.update({
|
||||
where: { id: res.body.id },
|
||||
data: { status: 'failed', errorCode: 'invalid_image' },
|
||||
});
|
||||
const options = { graceMs: HOUR_MS, prefix: `staging/${res.body.id}`, now: later() };
|
||||
const kept = await reconcile(prisma, s3, {
|
||||
...options,
|
||||
apply: true,
|
||||
stagingRetentionMs: 3 * HOUR_MS,
|
||||
});
|
||||
expect(kept.staging_expired).toBe(0);
|
||||
expect(await exists(`staging/${res.body.id}`)).toBe(true);
|
||||
const expired = await reconcile(prisma, s3, {
|
||||
...options,
|
||||
apply: true,
|
||||
stagingRetentionMs: HOUR_MS,
|
||||
});
|
||||
expect(expired.staging_expired).toBeGreaterThanOrEqual(1);
|
||||
expect(await exists(`staging/${res.body.id}`)).toBe(false);
|
||||
const row = await prisma.attachment.findUniqueOrThrow({ where: { id: res.body.id } });
|
||||
expect(row.stagingKey).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user