diff --git a/src/attachments/reconciler.ts b/src/attachments/reconciler.ts index e164e5e0..24beeda0 100644 --- a/src/attachments/reconciler.ts +++ b/src/attachments/reconciler.ts @@ -55,6 +55,7 @@ export async function reconcile( s3, (options.now ?? new Date()).getTime() - options.stagingRetentionMs, options.apply, + options.prefix, ); } for (const prefix of options.prefix ? [options.prefix] : DEFAULT_PREFIXES) { @@ -69,10 +70,11 @@ async function expireFailedStaging( s3: S3Service, before: number, apply: boolean, + prefix?: string, ): Promise { const rows = await prisma.attachment.findMany({ where: { - stagingKey: { not: null }, + stagingKey: { not: null, startsWith: prefix }, OR: [{ status: 'ready' }, { status: 'failed', updatedAt: { lt: new Date(before) } }], }, select: { id: true, stagingKey: true }, @@ -83,20 +85,30 @@ async function expireFailedStaging( } let expired = 0; for (const row of rows) { - try { - await s3.delete(row.stagingKey!); - await prisma.attachment.update({ - where: { id: row.id }, - data: { stagingKey: null }, - }); - expired++; - } catch { + const released = await prisma.attachment.updateMany({ + where: { + id: row.id, + stagingKey: row.stagingKey, + OR: [{ status: 'ready' }, { status: 'failed', updatedAt: { lt: new Date(before) } }], + }, + data: { stagingKey: null }, + }); + if (released.count === 0) { continue; } + await s3.delete(row.stagingKey!).then( + () => expired++, + () => undefined, + ); } return expired; } +function attachmentIdOf(key: string): string | null { + const match = /^attachments\/([0-9a-f-]{36})(\/|$)/.exec(key); + return match ? match[1] : null; +} + async function reconcilePrefix( prisma: ReconcilePrisma, s3: S3Service, @@ -121,12 +133,18 @@ async function reconcilePrefix( where: { objectKey: { in: keys } }, select: { objectKey: true }, }); + const ids = [...new Set(keys.map(attachmentIdOf).filter((id): id is string => id !== null))]; + const owners = ids.length + ? await prisma.attachment.findMany({ where: { id: { in: ids } }, select: { id: true } }) + : []; + const owned = new Set(owners.map((row) => row.id)); const known = new Set([ ...rows.flatMap((row) => [row.objectKey, row.stagingKey]), ...variants.map((row) => row.objectKey), ]); for (const { key } of old) { - if (known.has(key)) { + const owner = attachmentIdOf(key); + if (known.has(key) || (owner !== null && owned.has(owner))) { report.referenced++; continue; } diff --git a/src/docs/examples.ts b/src/docs/examples.ts index df383e12..0a47b5db 100644 --- a/src/docs/examples.ts +++ b/src/docs/examples.ts @@ -79,7 +79,7 @@ const INVALID_CHAT_ID = example( ); export const GUIDE = ` -Учебный мессенджер, лабораторная 3: PostgreSQL, сессии, Redis-кэш сессий. +Учебный мессенджер, лабораторная 5: PostgreSQL, сессии, Redis-кэш сессий, вложения в S3 и их фоновая обработка. Документ — обязательный контракт \`contracts/openapi.json\`, дополненный примерами запросов и ответов. **Как пройти сценарий в Swagger UI** @@ -90,8 +90,9 @@ export const GUIDE = ` 4. \`GET /api/v1/users/me\` — свой id; id второго участника — из ответа его регистрации. 5. \`POST /api/v1/chats\` с \`member_ids\` = [свой id, id собеседника] → \`chat_id\`. 6. \`POST /api/v1/chats/{chat_id}/messages\` с заголовком \`Idempotency-Key\` (любая строка из \`A-Za-z0-9._:-\`, до 128 символов). Повтор с тем же ключом и телом вернёт то же сообщение, с другим телом — 409. Затем \`GET …/messages?limit=1\` и следующая страница с \`cursor\` = \`next_cursor\`. -7. Чтобы действовать от другого пользователя: Logout в Authorize, вход им и новый token. -8. \`DELETE /api/v1/auth/sessions/current\` — logout; тот же token дальше даёт 401. +7. \`POST /api/v1/chats/{chat_id}/attachments?filename=photo.png\` с телом PNG/JPEG → 202 \`queued\`. \`GET /api/v1/attachments/{id}\` повторять, пока \`status\` не станет \`ready\` (до этого \`/content\` отвечает 409), затем \`/content?variant=thumbnail\`, \`crop\` или \`optimized\`. +8. Чтобы действовать от другого пользователя: Logout в Authorize, вход им и новый token. +9. \`DELETE /api/v1/auth/sessions/current\` — logout; тот же token дальше даёт 401. Сессия живёт \`SESSION_TTL_SECONDS\` (по умолчанию 3600 с). Пароль — 12–128 символов Unicode, двоеточие допустимо. `; diff --git a/src/jobs/job-store.ts b/src/jobs/job-store.ts index 82b38e2d..0893f9c7 100644 --- a/src/jobs/job-store.ts +++ b/src/jobs/job-store.ts @@ -187,7 +187,12 @@ export async function republishStale( return stale.length; } -export type ReplayResult = 'replayed' | 'already_ready' | 'not_failed' | 'not_found'; +export type ReplayResult = + | 'replayed' + | 'already_ready' + | 'not_failed' + | 'source_missing' + | 'not_found'; export async function replayJob( prisma: PrismaClient, @@ -203,6 +208,16 @@ export async function replayJob( if (job.status === 'ready') { return 'already_ready'; } + if (job.status !== 'failed') { + return 'not_failed'; + } + const source = await tx.attachment.updateMany({ + where: { id: job.attachmentId, status: 'failed', stagingKey: { not: null } }, + data: { status: 'queued', errorCode: null }, + }); + if (source.count === 0) { + return 'source_missing'; + } const taken = await tx.attachmentJob.updateMany({ where: { id: jobId, status: 'failed' }, data: { @@ -214,12 +229,8 @@ export async function replayJob( }, }); if (taken.count === 0) { - return 'not_failed'; + throw new Error('job changed during replay'); } - await tx.attachment.update({ - where: { id: job.attachmentId }, - data: { status: 'queued', errorCode: null }, - }); await tx.jobEvent.create({ data: { jobId, diff --git a/src/jobs/processor.ts b/src/jobs/processor.ts index 8d9603a5..a1f1a1b7 100644 --- a/src/jobs/processor.ts +++ b/src/jobs/processor.ts @@ -8,7 +8,12 @@ import { } from '../storage/s3.service'; import { JobMessage, PIPELINE_VERSION } from './job-message'; import { markFailed, retryOrFail } from './job-store'; -import { InvalidImageError, RenderedVariant, renderVariants } from './variants'; +import { + InvalidImageError, + RenderedVariant, + RenderTimeoutError, + renderVariants, +} from './variants'; export type Outcome = 'ready' | 'retry' | 'failed' | 'skipped'; @@ -136,7 +141,11 @@ export class JobProcessor { } let variants: RenderedVariant[]; try { - variants = await renderVariants(original, this.options.maxPixels); + variants = await renderVariants( + original, + this.options.maxPixels, + Math.ceil(this.options.timeoutMs / 1000), + ); } catch (error) { if (error instanceof InvalidImageError) { throw new PermanentError('invalid_image', 'image cannot be decoded'); @@ -213,7 +222,7 @@ export class JobProcessor { const reason = error instanceof PermanentError ? error.message - : error instanceof TimeoutError + : error instanceof TimeoutError || error instanceof RenderTimeoutError ? 'processing timed out' : `temporary failure: ${error instanceof Error ? error.name : 'unknown'}`; this.logger.warn(`job ${lease.id} attempt ${lease.attempt}: ${reason}`); diff --git a/src/jobs/variants.ts b/src/jobs/variants.ts index 6792aec3..158f7782 100644 --- a/src/jobs/variants.ts +++ b/src/jobs/variants.ts @@ -25,24 +25,36 @@ export class InvalidImageError extends Error { } } +export class RenderTimeoutError extends Error { + constructor() { + super('image processing exceeded its time limit'); + this.name = 'RenderTimeoutError'; + } +} + export function fitInside( width: number, height: number, box: number, ): { width: number; height: number } { - const scale = Math.min(box / width, box / height, 1); - return { - width: Math.max(1, Math.floor(width * scale)), - height: Math.max(1, Math.floor(height * scale)), - }; + if (width <= box && height <= box) { + return { width, height }; + } + if (width >= height) { + return { width: box, height: Math.max(1, Math.floor((height * box) / width)) }; + } + return { width: Math.max(1, Math.floor((width * box) / height)), height: box }; } export async function renderVariants( original: Buffer, maxPixels: number, + timeoutSeconds = 0, ): Promise { const open = (): Sharp => - sharp(original, { failOn: 'error', limitInputPixels: maxPixels }).rotate(); + sharp(original, { failOn: 'error', limitInputPixels: maxPixels }) + .timeout({ seconds: timeoutSeconds }) + .rotate(); try { const meta = await sharp(original, { limitInputPixels: maxPixels }).metadata(); if (!meta.width || !meta.height) { @@ -73,6 +85,9 @@ export async function renderVariants( if (error instanceof InvalidImageError) { throw error; } + if (error instanceof Error && /timeout/i.test(error.message)) { + throw new RenderTimeoutError(); + } throw new InvalidImageError(error instanceof Error ? error.message : 'decode failed'); } } diff --git a/test/contract.e2e-spec.ts b/test/contract.e2e-spec.ts new file mode 100644 index 00000000..da596653 --- /dev/null +++ b/test/contract.e2e-spec.ts @@ -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(); + + const call = async ( + method: 'get' | 'post' | 'delete', + template: string, + values: Record, + 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; + } = {}, + ) => { + 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))); +} diff --git a/test/images.ts b/test/images.ts index 7471222b..c8a3c687 100644 --- a/test/images.ts +++ b/test/images.ts @@ -129,7 +129,10 @@ export function corruptedJpegs(valid: Buffer): Record { 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), diff --git a/test/jobs.e2e-spec.ts b/test/jobs.e2e-spec.ts index fd8af118..a5c08bc8 100644 --- a/test/jobs.e2e-spec.ts +++ b/test/jobs.e2e-spec.ts @@ -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'); diff --git a/test/reconciler.e2e-spec.ts b/test/reconciler.e2e-spec.ts index 0c12f53a..307608c1 100644 --- a/test/reconciler.e2e-spec.ts +++ b/test/reconciler.e2e-spec.ts @@ -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`)