Files
ilya.tyunin 6889e77ab4 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.
2026-11-09 16:44:21 +03:00

188 lines
5.0 KiB
TypeScript

import { randomUUID } from 'node:crypto';
import { Pool } from 'pg';
import { expect } from 'vitest';
import type { Chat } from '../../src/chats/chat.js';
import type { ApiErrorBody } from '../../src/common/errors/api-error.js';
import type { Message } from '../../src/messages/message.js';
import type { Attachment } from '../../src/attachments/attachment.js';
import type { User } from '../../src/users/user.js';
export const baseUrl = (
process.env.API_BASE_URL ?? 'http://localhost:8080'
).replace(/\/+$/u, '');
export const password = 'integration:пароль🔐';
const runId = randomUUID().replaceAll('-', '').slice(0, 10);
let sequence = 0;
export type Actor = { user: User; token: string };
export type HttpResult<T> = { body: T; response: Response };
export function database(): Pool {
return new Pool({
connectionString: process.env.DATABASE_URL,
connectionTimeoutMillis: 5000,
});
}
export async function http<T = unknown>(
path: string,
init: RequestInit = {},
): Promise<HttpResult<T>> {
const response = await fetch(`${baseUrl}${path}`, init);
const text = await response.text();
let body: unknown = undefined;
if (text) {
try {
body = JSON.parse(text);
} catch {
body = text;
}
}
return { body: body as T, response };
}
export function json(
body: unknown,
headers: Record<string, string> = {},
): RequestInit {
return {
method: 'POST',
headers: { 'content-type': 'application/json', ...headers },
body: JSON.stringify(body),
};
}
export function bearer(token: string): Record<string, string> {
return { authorization: `Bearer ${token}` };
}
export function expectError(
result: HttpResult<ApiErrorBody>,
status: number,
code: string,
): void {
expect(result.response.status).toBe(status);
expect(result.body.error.code).toBe(code);
expect(result.body.error.request_id).toBe(
result.response.headers.get('x-request-id'),
);
}
export async function actor(): Promise<Actor> {
const username = `e2e_${runId}_${sequence++}`.slice(0, 32);
const created = await http<User>(
'/api/v1/users',
json({ username, display_name: 'Attachments e2e', password }),
);
expect(created.response.status).toBe(201);
const basic = Buffer.from(`${username}:${password}`, 'utf8').toString(
'base64',
);
const session = await http<{ token: string }>('/api/v1/auth/sessions', {
method: 'POST',
headers: { authorization: `Basic ${basic}` },
});
expect(session.response.status).toBe(201);
return { user: created.body, token: session.body.token };
}
export async function createChat(
owner: Actor,
members: Actor[],
): Promise<Chat> {
const result = await http<Chat>(
'/api/v1/chats',
json(
{
title: 'attachments',
member_ids: [owner.user.id, ...members.map((m) => m.user.id)],
},
bearer(owner.token),
),
);
expect(result.response.status).toBe(201);
return result.body;
}
/** `query` is sent verbatim so tests can craft malformed filename parameters. */
export function uploadRaw(
token: string,
chatId: string,
query: string,
body: Buffer | undefined,
contentType = 'image/png',
): Promise<HttpResult<Attachment & ApiErrorBody>> {
return http(`/api/v1/chats/${chatId}/attachments${query}`, {
method: 'POST',
headers: { ...bearer(token), 'content-type': contentType },
body: body as BodyInit | undefined,
});
}
export function upload(
token: string,
chatId: string,
body: Buffer | undefined,
options: { filename?: string; contentType?: string } = {},
) {
return uploadRaw(
token,
chatId,
`?filename=${encodeURIComponent(options.filename ?? 'picture.png')}`,
body,
options.contentType ?? 'image/png',
);
}
/**
* Lab5 uploads answer 202 before the worker runs. Poll metadata until ready;
* a failed attachment is a test failure, never a silent timeout.
*/
export async function waitReady(
token: string,
attachmentId: string,
timeoutMs = 60_000,
): Promise<Attachment> {
const deadline = Date.now() + timeoutMs;
for (;;) {
const result = await http<Attachment>(
`/api/v1/attachments/${attachmentId}`,
{ headers: bearer(token) },
);
expect(result.response.status).toBe(200);
if (result.body.status === 'failed')
throw new Error(
`attachment ${attachmentId} failed: ${result.body.error_code ?? 'unknown'}`,
);
if (result.body.status === 'ready') return result.body;
if (Date.now() >= deadline)
throw new Error(
`attachment ${attachmentId} did not become ready within ${timeoutMs}ms`,
);
await new Promise((resolve) => setTimeout(resolve, 200));
}
}
export async function download(
token: string,
attachmentId: string,
): Promise<{ response: Response; bytes: Buffer }> {
const response = await fetch(
`${baseUrl}/api/v1/attachments/${attachmentId}/content`,
{ headers: bearer(token) },
);
return { response, bytes: Buffer.from(await response.arrayBuffer()) };
}
export function postMessage(
token: string,
chatId: string,
body: unknown,
key = randomUUID().replaceAll('-', ''),
) {
return http<Message & ApiErrorBody>(
`/api/v1/chats/${chatId}/messages`,
json(body, { ...bearer(token), 'idempotency-key': key }),
);
}