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 = { body: T; response: Response }; export function database(): Pool { return new Pool({ connectionString: process.env.DATABASE_URL, connectionTimeoutMillis: 5000, }); } export async function http( path: string, init: RequestInit = {}, ): Promise> { 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 = {}, ): RequestInit { return { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify(body), }; } export function bearer(token: string): Record { return { authorization: `Bearer ${token}` }; } export function expectError( result: HttpResult, 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 { const username = `e2e_${runId}_${sequence++}`.slice(0, 32); const created = await http( '/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 { const result = await http( '/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> { 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 { const deadline = Date.now() + timeoutMs; for (;;) { const result = await http( `/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( `/api/v1/chats/${chatId}/messages`, json(body, { ...bearer(token), 'idempotency-key': key }), ); }