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,187 @@
|
||||
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 }),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/** Keeps every segment through the SOS header and drops the scan data. */
|
||||
export function jpegWithoutScanData(jpeg: Buffer): Buffer {
|
||||
let offset = 2;
|
||||
for (;;) {
|
||||
const marker = jpeg[offset + 1];
|
||||
offset += 2 + jpeg.readUInt16BE(offset + 2);
|
||||
if (marker === 0xda) break;
|
||||
}
|
||||
return Buffer.concat([jpeg.subarray(0, offset), Buffer.from([0xff, 0xd9])]);
|
||||
}
|
||||
|
||||
/** Inserts `count` APP13 segments of ~64 KiB right after SOI (Photoshop-style metadata). */
|
||||
export function jpegWithMetadata(jpeg: Buffer, count: number): Buffer {
|
||||
const payload = Buffer.alloc(65_533, 0x20);
|
||||
const segment = Buffer.concat([
|
||||
Buffer.from([0xff, 0xed, 0xff, 0xff]),
|
||||
payload,
|
||||
]);
|
||||
return Buffer.concat([
|
||||
jpeg.subarray(0, 2),
|
||||
...Array.from({ length: count }, () => segment),
|
||||
jpeg.subarray(2),
|
||||
]);
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { once } from 'node:events';
|
||||
import { crc32, createDeflate, deflateSync } from 'node:zlib';
|
||||
|
||||
const SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
|
||||
function chunk(type: string, data: Buffer): Buffer {
|
||||
const head = Buffer.alloc(8);
|
||||
head.writeUInt32BE(data.length, 0);
|
||||
head.write(type, 4, 'latin1');
|
||||
const crc = Buffer.alloc(4);
|
||||
crc.writeUInt32BE(crc32(Buffer.concat([head.subarray(4), data])) >>> 0, 0);
|
||||
return Buffer.concat([head, data, crc]);
|
||||
}
|
||||
|
||||
export function buildPng(options: {
|
||||
width: number;
|
||||
height: number;
|
||||
colorType: number;
|
||||
bitDepth: number;
|
||||
idat: Buffer;
|
||||
}): Buffer {
|
||||
const ihdr = Buffer.alloc(13);
|
||||
ihdr.writeUInt32BE(options.width, 0);
|
||||
ihdr.writeUInt32BE(options.height, 4);
|
||||
ihdr[8] = options.bitDepth;
|
||||
ihdr[9] = options.colorType;
|
||||
return Buffer.concat([
|
||||
SIGNATURE,
|
||||
chunk('IHDR', ihdr),
|
||||
chunk('IDAT', options.idat),
|
||||
chunk('IEND', Buffer.alloc(0)),
|
||||
]);
|
||||
}
|
||||
|
||||
/** Inserts a private ancillary chunk before IEND to reach exactly `size` bytes. */
|
||||
export function padPngTo(png: Buffer, size: number): Buffer {
|
||||
const extra = size - png.length;
|
||||
if (extra === 0) return png;
|
||||
if (extra < 12) throw new Error('PNG padding needs at least 12 bytes');
|
||||
const iend = png.length - 12;
|
||||
return Buffer.concat([
|
||||
png.subarray(0, iend),
|
||||
chunk('prVt', Buffer.alloc(extra - 12)),
|
||||
png.subarray(iend),
|
||||
]);
|
||||
}
|
||||
|
||||
/** 8000x5001 grayscale 1-bit, all-zero rows: tiny file, 40 008 000 pixels. */
|
||||
export function pixelBombPng(): Buffer {
|
||||
const width = 8000;
|
||||
const height = 5001;
|
||||
const row = Buffer.alloc(1 + Math.ceil(width / 8));
|
||||
const raw = Buffer.alloc(row.length * height);
|
||||
return buildPng({
|
||||
width,
|
||||
height,
|
||||
colorType: 0,
|
||||
bitDepth: 1,
|
||||
idat: deflateSync(raw, { level: 9 }),
|
||||
});
|
||||
}
|
||||
|
||||
const NOISE_WIDTH = 1024;
|
||||
const NOISE_ROW = 1 + NOISE_WIDTH * 3;
|
||||
|
||||
function noiseOfHeight(height: number): Buffer {
|
||||
const raw = randomBytes(NOISE_ROW * height);
|
||||
for (let row = 0; row < height; row += 1) raw[row * NOISE_ROW] = 0;
|
||||
return buildPng({
|
||||
width: NOISE_WIDTH,
|
||||
height,
|
||||
colorType: 2,
|
||||
bitDepth: 8,
|
||||
idat: deflateSync(raw, { level: 0 }),
|
||||
});
|
||||
}
|
||||
|
||||
/** Incompressible, structurally valid PNG of exactly `size` bytes. */
|
||||
export function noisePng(size: number): Buffer {
|
||||
let height = Math.max(1, Math.floor(size / NOISE_ROW));
|
||||
for (;;) {
|
||||
const png = noiseOfHeight(height);
|
||||
if (png.length > size) {
|
||||
height -= 1;
|
||||
if (height < 1) throw new Error('size is too small for noisePng');
|
||||
continue;
|
||||
}
|
||||
const extra = size - png.length;
|
||||
if (extra > 0 && extra < 12) {
|
||||
height -= 1;
|
||||
continue;
|
||||
}
|
||||
return padPngTo(png, size);
|
||||
}
|
||||
}
|
||||
|
||||
/** Valid signature, IHDR, CRCs and IEND around a zlib stream of random bytes. */
|
||||
export function pngWithGarbageIdat(): Buffer {
|
||||
return buildPng({
|
||||
width: 320,
|
||||
height: 200,
|
||||
colorType: 2,
|
||||
bitDepth: 8,
|
||||
idat: randomBytes(5000),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 8000x5000 RGBA 16-bit (8 bytes/pixel, 40 000 000 px — the pixel limit):
|
||||
* the heaviest decode a valid upload can ask for. Rows are streamed into the
|
||||
* compressor, so the 320 MB raw image is never allocated here.
|
||||
*/
|
||||
export async function maxPixelsRgba16Png(): Promise<Buffer> {
|
||||
const width = 8000;
|
||||
const height = 5000;
|
||||
// First row: a gradient; every next row uses filter "Up" with zero
|
||||
// deltas, i.e. repeats it — a valid image that compresses well.
|
||||
const first = Buffer.alloc(1 + width * 8);
|
||||
for (let x = 0; x < width; x += 1)
|
||||
first.writeUInt16BE((x * 8) & 0xffff, 1 + x * 8);
|
||||
const repeat = Buffer.alloc(1 + width * 8);
|
||||
repeat[0] = 2;
|
||||
const deflate = createDeflate({ level: 1 });
|
||||
const chunks: Buffer[] = [];
|
||||
deflate.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||
const ended = once(deflate, 'end');
|
||||
for (let y = 0; y < height; y += 1)
|
||||
if (!deflate.write(y === 0 ? first : repeat))
|
||||
await once(deflate, 'drain');
|
||||
deflate.end();
|
||||
await ended;
|
||||
return buildPng({
|
||||
width,
|
||||
height,
|
||||
colorType: 6,
|
||||
bitDepth: 16,
|
||||
idat: Buffer.concat(chunks),
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user