forked from mtusi2026/mtusi2026lab6
lab6: базовый коммит из lab5 (0790599)
Перенесено дерево lab5 целиком: NestJS-приложение (API + worker,
RabbitMQ, outbox, S3), Dockerfile, compose.yaml, infra/{haproxy,minio,
rabbitmq}, стендовые скрипты, scripts/lab4, scripts/lab5,
evidence/lab4, evidence/lab5 и contracts/extensions.openapi.json.
Задание lab6 оставлено своим: README, REPORT, COURSE, lab.json,
contracts/{openapi,infrastructure,jobs.schema,attachment-states,
examples,observability}, tests, compose.example.yaml, infra/otel,
.github/pull_request_template.md.
Адаптации при переносе:
- docker-проект mtusi-lab5 -> mtusi-lab6 и тег образа
mtusi-messenger:lab6 (compose.yaml, scripts/stop-one.sh, .env.example,
infra/README.md), чтобы тома и контейнеры не пересекались с lab5;
- Makefile: цели lab5 сохранены целиком (skeleton lab6 не отличается
от skeleton lab5);
- .env.example: переменные приложения и стенда lab5 + блок lab6
(OTEL_*) из skeleton.
This commit is contained in:
@@ -0,0 +1,133 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { Readable } from 'node:stream';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { AttachmentRow } from './attachment.js';
|
||||
import { AttachmentsService } from './attachments.service.js';
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const png = readFileSync(join(here, '../../../tests/fixtures/sample.png'));
|
||||
const lostReply = () =>
|
||||
Object.assign(new Error('Connection terminated unexpectedly'), {});
|
||||
|
||||
const settings: Record<string, number> = {
|
||||
MAX_UPLOAD_BYTES: 10_485_760,
|
||||
MAX_IMAGE_PIXELS: 40_000_000,
|
||||
UPLOAD_TIMEOUT_MS: 10_000,
|
||||
PIPELINE_VERSION: 1,
|
||||
JOB_MAX_ATTEMPTS: 5,
|
||||
};
|
||||
|
||||
function setup(
|
||||
repository: Record<string, unknown>,
|
||||
jobs: Record<string, unknown> = {},
|
||||
) {
|
||||
const storage = {
|
||||
objectKey: (id: string) => `attachments/${id}/original`,
|
||||
stagingKey: (id: string) => `staging/${id}/original`,
|
||||
putStream: vi.fn(async (_key: string, body: Readable) => {
|
||||
for await (const _chunk of body) {
|
||||
// drain like S3 does
|
||||
}
|
||||
}),
|
||||
delete: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const service = new AttachmentsService(
|
||||
{ getOrThrow: (key: string) => settings[key] } as never,
|
||||
{
|
||||
insertPending: vi.fn(),
|
||||
deleteClaimed: vi.fn(),
|
||||
...repository,
|
||||
} as never,
|
||||
{ acceptUpload: vi.fn(), ...jobs } as never,
|
||||
{ kick: vi.fn() } as never,
|
||||
{ point: vi.fn() } as never,
|
||||
storage as never,
|
||||
{ getForUser: vi.fn() } as never,
|
||||
{ increment: vi.fn(), add: vi.fn() } as never,
|
||||
{ verify: vi.fn() } as never,
|
||||
{
|
||||
run: (_user: string, work: () => Promise<unknown>) => work(),
|
||||
} as never,
|
||||
);
|
||||
const upload = () =>
|
||||
service.uploadProxy(
|
||||
'chat',
|
||||
{ id: 'user' } as never,
|
||||
'a.png',
|
||||
'image/png',
|
||||
String(png.length),
|
||||
Readable.from([png]),
|
||||
);
|
||||
return { storage, upload };
|
||||
}
|
||||
|
||||
const readyRow = (id: string): AttachmentRow => ({
|
||||
id,
|
||||
chat_id: 'chat',
|
||||
owner_id: 'user',
|
||||
filename: 'a.png',
|
||||
content_type: 'image/png',
|
||||
upload_mode: 'proxy',
|
||||
status: 'ready',
|
||||
object_key: `attachments/${id}/original`,
|
||||
staging_key: `staging/${id}/original`,
|
||||
size_bytes: png.length,
|
||||
sha256: 'a'.repeat(64),
|
||||
width: 320,
|
||||
height: 200,
|
||||
error_code: null,
|
||||
ready_pipeline_version: 1,
|
||||
expires_at: null,
|
||||
created_at: new Date(),
|
||||
updated_at: new Date(),
|
||||
});
|
||||
|
||||
describe('AttachmentsService compensation', () => {
|
||||
it('keeps the object and answers 202 when the job commit reply was lost', async () => {
|
||||
const { storage, upload } = setup(
|
||||
{
|
||||
claimForCompensation: vi.fn().mockResolvedValue(false),
|
||||
findById: vi.fn((id: string) => Promise.resolve(readyRow(id))),
|
||||
},
|
||||
{ acceptUpload: vi.fn().mockRejectedValue(lostReply()) },
|
||||
);
|
||||
const attachment = await upload();
|
||||
expect(attachment.status).toBe('ready');
|
||||
expect(storage.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('deletes nothing while PostgreSQL is unreachable', async () => {
|
||||
const { storage, upload } = setup(
|
||||
{
|
||||
claimForCompensation: vi.fn().mockRejectedValue(lostReply()),
|
||||
findById: vi.fn().mockRejectedValue(lostReply()),
|
||||
},
|
||||
{ acceptUpload: vi.fn().mockRejectedValue(lostReply()) },
|
||||
);
|
||||
await expect(upload()).rejects.toThrow();
|
||||
expect(storage.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('deletes the object only after claiming the pending row', async () => {
|
||||
const order: string[] = [];
|
||||
const { storage, upload } = setup(
|
||||
{
|
||||
claimForCompensation: vi.fn(async () => {
|
||||
order.push('claim');
|
||||
return true;
|
||||
}),
|
||||
deleteClaimed: vi.fn(async () => {
|
||||
order.push('delete-row');
|
||||
}),
|
||||
},
|
||||
{ acceptUpload: vi.fn().mockRejectedValue(lostReply()) },
|
||||
);
|
||||
storage.delete.mockImplementation(async () => {
|
||||
order.push('delete-object');
|
||||
});
|
||||
await expect(upload()).rejects.toThrow();
|
||||
expect(order).toEqual(['claim', 'delete-object', 'delete-row']);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user