forked from mtusi2026/mtusi2026lab5
fix: close cleanup and replay races, integer thumbnail sizing, sharp deadline, contract tests
This commit is contained in:
@@ -0,0 +1,241 @@
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import Ajv2020 from 'ajv/dist/2020';
|
||||
import { randomUUID } from 'crypto';
|
||||
import request from 'supertest';
|
||||
import { PrismaService } from '../src/db/prisma.service';
|
||||
import { loadDocument } from '../src/docs/swagger';
|
||||
import {
|
||||
basic,
|
||||
bearer,
|
||||
createTestApp,
|
||||
PASSWORD,
|
||||
processAttachment,
|
||||
registerUser,
|
||||
TestUser,
|
||||
} from './helpers';
|
||||
import { jpeg, SAMPLE_PNG } from './images';
|
||||
|
||||
const CONTRACT_ID = 'https://contract.local/openapi.json';
|
||||
|
||||
describe('Все ответы соответствуют контракту: коды, схемы, заголовки (e2e)', () => {
|
||||
let app: INestApplication;
|
||||
let server: any;
|
||||
let alice: TestUser;
|
||||
let bob: TestUser;
|
||||
let eve: TestUser;
|
||||
const document: any = loadDocument();
|
||||
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
||||
ajv.addSchema(document, CONTRACT_ID);
|
||||
const covered = new Set<string>();
|
||||
|
||||
const call = async (
|
||||
method: 'get' | 'post' | 'delete',
|
||||
template: string,
|
||||
values: Record<string, string>,
|
||||
expected: number,
|
||||
{
|
||||
user,
|
||||
auth,
|
||||
query = '',
|
||||
body,
|
||||
raw,
|
||||
type,
|
||||
headers = {},
|
||||
}: {
|
||||
user?: TestUser | null;
|
||||
auth?: string;
|
||||
query?: string;
|
||||
body?: unknown;
|
||||
raw?: Buffer | string;
|
||||
type?: string;
|
||||
headers?: Record<string, string>;
|
||||
} = {},
|
||||
) => {
|
||||
const path = template.replace(/\{(\w+)\}/g, (_, name) => values[name]);
|
||||
let req = request(server)[method](path + query).buffer(true).parse(binaryParser);
|
||||
if (user) {
|
||||
req = req.set('Authorization', bearer(user));
|
||||
}
|
||||
if (auth) {
|
||||
req = req.set('Authorization', auth);
|
||||
}
|
||||
for (const [name, value] of Object.entries(headers)) {
|
||||
req = req.set(name, value);
|
||||
}
|
||||
if (type) {
|
||||
req = req.set('Content-Type', type);
|
||||
}
|
||||
const res = raw !== undefined ? await req.send(raw) : body !== undefined ? await req.send(body as object) : await req;
|
||||
const operation = document.paths[template][method];
|
||||
const label = `${method.toUpperCase()} ${template} -> ${res.status}`;
|
||||
expect({ label, status: res.status }).toEqual({ label, status: expected });
|
||||
expect({ label, declared: String(res.status) in operation.responses }).toEqual({ label, declared: true });
|
||||
expect({ label, requestId: Boolean(res.headers['x-request-id']) }).toEqual({ label, requestId: true });
|
||||
expect({ label, instanceId: Boolean(res.headers['x-instance-id']) }).toEqual({ label, instanceId: true });
|
||||
const declared = operation.responses[String(res.status)];
|
||||
const content = declared.content ?? {};
|
||||
const type_ = (res.headers['content-type'] ?? '').split(';')[0];
|
||||
if (res.status === 204) {
|
||||
expect({ label, length: res.body.length }).toEqual({ label, length: 0 });
|
||||
} else if (content['application/json']) {
|
||||
expect({ label, type: type_ }).toEqual({ label, type: 'application/json' });
|
||||
const json = JSON.parse(res.body.toString('utf8'));
|
||||
const schema = content['application/json'].schema;
|
||||
const validate = ajv.compile(schema.$ref ? { $ref: CONTRACT_ID + schema.$ref } : schema);
|
||||
const valid = validate(json);
|
||||
expect({ label, valid, errors: validate.errors }).toEqual({ label, valid: true, errors: null });
|
||||
if (json && typeof json === 'object' && 'error' in json) {
|
||||
expect({ label, same: json.error.request_id === res.headers['x-request-id'] }).toEqual({ label, same: true });
|
||||
}
|
||||
} else {
|
||||
expect({ label, type: Object.keys(content).includes(type_) }).toEqual({ label, type: true });
|
||||
}
|
||||
covered.add(label);
|
||||
return res.status === 204 || !content['application/json'] ? res.body : JSON.parse(res.body.toString('utf8'));
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
({ app, server } = await createTestApp());
|
||||
alice = await registerUser(server, 'ct_alice');
|
||||
bob = await registerUser(server, 'ct_bob');
|
||||
eve = await registerUser(server, 'ct_eve');
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('health, пользователи и сессии', async () => {
|
||||
await call('get', '/health/live', {}, 200);
|
||||
await call('get', '/health/ready', {}, 200);
|
||||
const username = `ct_${randomUUID().slice(0, 8)}`;
|
||||
await call('post', '/api/v1/users', {}, 201, { body: { username, display_name: 'C', password: PASSWORD } });
|
||||
await call('post', '/api/v1/users', {}, 409, { body: { username, display_name: 'C', password: PASSWORD } });
|
||||
await call('post', '/api/v1/users', {}, 400, { body: { username: 'BAD NAME', display_name: 'C', password: PASSWORD } });
|
||||
await call('post', '/api/v1/users', {}, 400, { raw: '{bad', type: 'application/json' });
|
||||
await call('post', '/api/v1/auth/sessions', {}, 201, { auth: basic(username, PASSWORD) });
|
||||
await call('post', '/api/v1/auth/sessions', {}, 401, { auth: basic(username, 'wrong-password-123') });
|
||||
await call('post', '/api/v1/auth/sessions', {}, 400, {
|
||||
auth: basic(username, PASSWORD),
|
||||
body: { username },
|
||||
});
|
||||
await call('get', '/api/v1/users/me', {}, 200, { user: alice });
|
||||
await call('get', '/api/v1/users/me', {}, 401);
|
||||
await call('get', '/api/v1/users/me', {}, 401, { auth: basic(username, PASSWORD) });
|
||||
const temp = await registerUser(server, 'ct_tmp');
|
||||
await call('delete', '/api/v1/auth/sessions/current', {}, 204, { user: temp });
|
||||
await call('delete', '/api/v1/auth/sessions/current', {}, 401, { user: temp });
|
||||
});
|
||||
|
||||
it('чаты и сообщения', async () => {
|
||||
const chat = await call('post', '/api/v1/chats', {}, 201, {
|
||||
user: alice,
|
||||
body: { title: 'Contract', member_ids: [alice.id, bob.id] },
|
||||
});
|
||||
await call('post', '/api/v1/chats', {}, 400, { user: alice, body: { title: 'x', member_ids: [bob.id] } });
|
||||
await call('post', '/api/v1/chats', {}, 401, { body: { title: 'x', member_ids: [] } });
|
||||
await call('get', '/api/v1/chats', {}, 200, { user: bob, query: '?limit=1' });
|
||||
await call('get', '/api/v1/chats', {}, 400, { user: bob, query: '?limit=0' });
|
||||
await call('get', '/api/v1/chats', {}, 400, { user: bob, query: '?cursor=garbage' });
|
||||
const ids = { chat_id: chat.id };
|
||||
await call('get', '/api/v1/chats/{chat_id}', ids, 200, { user: bob });
|
||||
await call('get', '/api/v1/chats/{chat_id}', ids, 404, { user: eve });
|
||||
await call('get', '/api/v1/chats/{chat_id}', { chat_id: 'nope' }, 400, { user: bob });
|
||||
const key = randomUUID();
|
||||
const send = (status: number, body: unknown, user: TestUser = alice, idem: string | null = randomUUID()) =>
|
||||
call('post', '/api/v1/chats/{chat_id}/messages', ids, status, {
|
||||
user,
|
||||
body,
|
||||
headers: idem ? { 'Idempotency-Key': idem } : {},
|
||||
});
|
||||
await send(201, { text: 'привет' }, alice, key);
|
||||
await send(201, { text: 'привет' }, alice, key);
|
||||
await send(201, { text: 'второе' }, bob);
|
||||
await send(409, { text: 'другое' }, alice, key);
|
||||
await send(400, { text: 'без ключа' }, alice, null);
|
||||
await send(400, { text: '' });
|
||||
await send(400, { text: 'x', sender_id: alice.id });
|
||||
await send(404, { text: 'x' }, eve);
|
||||
await send(404, { text: 'x', attachment_ids: [randomUUID()] });
|
||||
const page = await call('get', '/api/v1/chats/{chat_id}/messages', ids, 200, { user: bob, query: '?limit=1' });
|
||||
await call('get', '/api/v1/chats/{chat_id}/messages', ids, 200, {
|
||||
user: bob,
|
||||
query: `?limit=1&cursor=${encodeURIComponent(page.next_cursor)}`,
|
||||
});
|
||||
await call('get', '/api/v1/chats/{chat_id}/messages', ids, 400, { user: bob, query: '?limit=101' });
|
||||
await call('get', '/api/v1/chats/{chat_id}/messages', ids, 404, { user: eve });
|
||||
});
|
||||
|
||||
it('вложения во всех состояниях', async () => {
|
||||
const chat = await call('post', '/api/v1/chats', {}, 201, {
|
||||
user: alice,
|
||||
body: { title: 'Files', member_ids: [alice.id, bob.id] },
|
||||
});
|
||||
const ids = { chat_id: chat.id };
|
||||
const upload = (status: number, body: Buffer, type = 'image/png', query = '?filename=a.png', user: TestUser | null = alice) =>
|
||||
call('post', '/api/v1/chats/{chat_id}/attachments', ids, status, { user, raw: body, type, query });
|
||||
const queued = await upload(202, SAMPLE_PNG);
|
||||
expect(queued.status).toBe('queued');
|
||||
await upload(202, await jpeg(), 'image/jpeg');
|
||||
await upload(400, SAMPLE_PNG, 'image/png', '?filename=../a.png');
|
||||
await upload(415, SAMPLE_PNG, 'image/jpeg');
|
||||
await upload(415, Buffer.from('text'), 'text/plain');
|
||||
await upload(413, Buffer.alloc(10 * 1024 * 1024 + 1), 'image/png');
|
||||
await upload(404, SAMPLE_PNG, 'image/png', '?filename=a.png', eve);
|
||||
await upload(401, SAMPLE_PNG, 'image/png', '?filename=a.png', null);
|
||||
|
||||
const one = { attachment_id: queued.id };
|
||||
const meta = '/api/v1/attachments/{attachment_id}';
|
||||
const content = '/api/v1/attachments/{attachment_id}/content';
|
||||
expect((await call('get', meta, one, 200, { user: bob })).status).toBe('queued');
|
||||
await call('get', content, one, 409, { user: bob });
|
||||
await call('get', content, one, 409, { user: bob, query: '?variant=thumbnail' });
|
||||
await call('post', '/api/v1/chats/{chat_id}/messages', ids, 201, {
|
||||
user: alice,
|
||||
body: { text: '', attachment_ids: [queued.id] },
|
||||
headers: { 'Idempotency-Key': randomUUID() },
|
||||
});
|
||||
|
||||
expect(await processAttachment(app, queued.id)).toBe('ready');
|
||||
const ready = await call('get', meta, one, 200, { user: bob });
|
||||
expect(ready.variants.map((v: any) => v.name)).toEqual(['thumbnail', 'crop', 'optimized']);
|
||||
for (const variant of ['', '?variant=original', '?variant=thumbnail', '?variant=crop', '?variant=optimized']) {
|
||||
await call('get', content, one, 200, { user: bob, query: variant });
|
||||
}
|
||||
await call('get', content, one, 400, { user: bob, query: '?variant=huge' });
|
||||
await call('get', content, one, 404, { user: eve });
|
||||
await call('get', meta, one, 404, { user: eve });
|
||||
await call('get', meta, { attachment_id: 'nope' }, 400, { user: bob });
|
||||
await call('get', meta, one, 401);
|
||||
|
||||
const broken = await upload(202, SAMPLE_PNG);
|
||||
const prisma = app.get(PrismaService);
|
||||
await prisma.attachmentJob.updateMany({ where: { attachmentId: broken.id }, data: { maxAttempts: 1 } });
|
||||
await prisma.attachment.update({ where: { id: broken.id }, data: { sha256: 'f'.repeat(64) } });
|
||||
expect(await processAttachment(app, broken.id)).toBe('failed');
|
||||
const failed = await call('get', meta, { attachment_id: broken.id }, 200, { user: bob });
|
||||
expect(failed).toMatchObject({ status: 'failed', error_code: 'checksum_mismatch', variants: [] });
|
||||
await call('get', content, { attachment_id: broken.id }, 409, { user: bob });
|
||||
await call('post', '/api/v1/chats/{chat_id}/messages', ids, 409, {
|
||||
user: alice,
|
||||
body: { text: '', attachment_ids: [broken.id] },
|
||||
headers: { 'Idempotency-Key': randomUUID() },
|
||||
});
|
||||
});
|
||||
|
||||
it('каждая операция контракта вызвана хотя бы раз', () => {
|
||||
const operations = Object.entries(document.paths).flatMap(([path, ops]: [string, any]) =>
|
||||
Object.keys(ops)
|
||||
.filter((method) => ['get', 'post', 'delete'].includes(method))
|
||||
.map((method) => `${method.toUpperCase()} ${path}`),
|
||||
);
|
||||
const called = new Set([...covered].map((label) => label.split(' -> ')[0]));
|
||||
expect(operations.filter((operation) => !called.has(operation))).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
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)));
|
||||
}
|
||||
@@ -129,7 +129,10 @@ export function corruptedJpegs(valid: Buffer): Record<string, Buffer> {
|
||||
for (let i = 800; i < garbled.length - 2; i += 3) {
|
||||
garbled[i] = 0x55;
|
||||
}
|
||||
const foreignComponent = Buffer.from(valid);
|
||||
foreignComponent[foreignComponent.indexOf(Buffer.from([0xff, 0xda])) + 5] = 250;
|
||||
return {
|
||||
'компонент SOS отсутствует в SOF': foreignComponent,
|
||||
'27 байт без таблиц и данных': JPEG_WITHOUT_DATA,
|
||||
'половина файла': valid.subarray(0, valid.length >> 1),
|
||||
'без последних 20 байт': valid.subarray(0, valid.length - 20),
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -6,6 +6,7 @@ import { join } from 'path';
|
||||
import request from 'supertest';
|
||||
import { reconcile } from '../src/attachments/reconciler';
|
||||
import { PrismaService } from '../src/db/prisma.service';
|
||||
import { replayJob } from '../src/jobs/job-store';
|
||||
import { S3Service } from '../src/storage/s3.service';
|
||||
import {
|
||||
bearer,
|
||||
@@ -242,6 +243,48 @@ describe('Сверка объектов S3 с метаданными (e2e)', ()
|
||||
expect(row.stagingKey).toBeNull();
|
||||
});
|
||||
|
||||
it('объекты вариантов без строк у существующего вложения не удаляются: replay после сверки доводит до ready', 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);
|
||||
const id = res.body.id;
|
||||
await expect(
|
||||
processAttachment(app, id, {
|
||||
afterStore: async () => {
|
||||
throw new Error('worker crashed');
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow('worker crashed');
|
||||
const job = await prisma.attachmentJob.findFirstOrThrow({ where: { attachmentId: id } });
|
||||
await prisma.attachmentJob.update({
|
||||
where: { id: job.id },
|
||||
data: { status: 'failed', errorCode: 'retry_exhausted', leaseOwner: null, leaseUntil: null },
|
||||
});
|
||||
await prisma.attachment.update({
|
||||
where: { id },
|
||||
data: { status: 'failed', errorCode: 'retry_exhausted' },
|
||||
});
|
||||
expect(await prisma.attachmentVariant.count({ where: { attachmentId: id } })).toBe(0);
|
||||
const report = await reconcile(prisma, s3, {
|
||||
apply: true,
|
||||
graceMs: HOUR_MS,
|
||||
prefix: `attachments/${id}/`,
|
||||
now: later(),
|
||||
});
|
||||
expect(report).toMatchObject({ scanned: 4, referenced: 4, orphans: 0, deleted: 0 });
|
||||
expect(await replayJob(prisma, job.id, 'test-operator')).toBe('replayed');
|
||||
expect(await processAttachment(app, id)).toBe('ready');
|
||||
for (const variant of ['original', 'thumbnail', 'crop', 'optimized']) {
|
||||
await request(server)
|
||||
.get(`/api/v1/attachments/${id}/content?variant=${variant}`)
|
||||
.set('Authorization', bearer(alice))
|
||||
.expect(200);
|
||||
}
|
||||
});
|
||||
|
||||
it('staging ready-вложения, оставшийся после сбоя worker, удаляется без ожидания срока хранения', async () => {
|
||||
const res = await request(server)
|
||||
.post(`/api/v1/chats/${chatId}/attachments?filename=a.png`)
|
||||
|
||||
Reference in New Issue
Block a user