forked from mtusi2026/mtusi2026lab5
feat: accept uploads into staging with jobs, outbox and job processor
This commit is contained in:
@@ -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');
|
||||
|
||||
Reference in New Issue
Block a user