forked from mtusi2026/mtusi2026lab6
- api и worker отдают traces, metrics и logs по OTLP в Collector (memory_limiter, redaction, batch, ограниченная очередь и retry); хранилища: Prometheus (OTLP receiver), Loki, Tempo; Grafana с provisioning datasources и dashboard «Messenger lab6» - W3C trace context через outbox и RabbitMQ: producer/consumer spans связывают upload, публикации и попытки worker в одном trace - SLO доступности API (SLI на HAProxy) и времени до ready, multiwindow burn-rate alerts, ApiHighErrorRate, JobQueueLagGrowing, DbPoolSaturated, TelemetryExportFailing; unit-тесты promtool, runbooks - кампания трека 2 (k6, 6 отказов по расписанию), разбор и графики; проверки сигналов и истории telemetry, evidence и REPORT.md
120 lines
7.1 KiB
TypeScript
120 lines
7.1 KiB
TypeScript
// HTTP-приложение: таблица маршрутов, health-проверки и общая обработка каждого запроса.
|
||
// Наблюдаемость (lab6): server span создаёт instrumentation-http, здесь ему задаётся шаблон маршрута
|
||
// и X-Request-Id; после ответа пишется структурный access-лог с trace_id/span_id этого span.
|
||
import { randomUUID } from 'node:crypto';
|
||
import type { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from 'node:http';
|
||
import { Readable } from 'node:stream';
|
||
import { pipeline } from 'node:stream/promises';
|
||
import { context, trace } from '@opentelemetry/api';
|
||
import type { Pool } from 'pg';
|
||
import type { Config } from './config.ts';
|
||
import type { Handler, Result } from './http/context.ts';
|
||
import { notFound, toHttpError, unavailable } from './http/errors.ts';
|
||
import { downloadAttachment, getAttachment, uploadAttachment } from './modules/attachments.ts';
|
||
import { createChat, getChat, listChats } from './modules/chats.ts';
|
||
import { listMessages, sendMessage } from './modules/messages.ts';
|
||
import { createSession, deleteSession } from './modules/sessions.ts';
|
||
import { createUser, me } from './modules/users.ts';
|
||
import { log, setRoute } from './otel.ts';
|
||
import type { Storage } from './storage/s3.ts';
|
||
|
||
function send(res: ServerResponse, status: number, body?: unknown, headers?: OutgoingHttpHeaders) {
|
||
if (body instanceof Readable) {
|
||
// Байты вложения потоком из S3. Обрыв с любой стороны закрывает соединение: клиент увидит
|
||
// несовпадение с Content-Length, а не «успешно» обрезанный файл.
|
||
res.writeHead(status, headers);
|
||
pipeline(body, res).catch((err) => log('warn', 'http.stream_aborted', `передача вложения прервана: ${err.message}`));
|
||
return;
|
||
}
|
||
if (body === undefined) {
|
||
res.writeHead(status).end();
|
||
return;
|
||
}
|
||
const data = JSON.stringify(body);
|
||
res.writeHead(status, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data) }).end(data);
|
||
}
|
||
|
||
export function createApp(db: Pool, s3: Storage, config: Config, relay: { kick(): void }) {
|
||
// ready = false с момента SIGTERM: балансировщик по readiness выводит реплику из ротации.
|
||
const state = { ready: true };
|
||
|
||
// Готовность: процесс не завершается и PostgreSQL отвечает. Это единственная критичная зависимость:
|
||
// при недоступном S3 реплика остаётся в ротации, текстовые сообщения работают, вложения отвечают 503;
|
||
// при недоступном брокере загрузки принимаются (задания ждут в outbox), worker не нужен для приёма.
|
||
const readiness: Handler = async () => {
|
||
if (!state.ready) throw unavailable('Реплика завершает работу');
|
||
try {
|
||
await db.query('SELECT 1');
|
||
} catch {
|
||
throw unavailable('База данных недоступна');
|
||
}
|
||
return [200, { status: 'ok' }];
|
||
};
|
||
|
||
// Шаблон маршрута — и правило сопоставления, и label http.route метрик/имя span (без реальных UUID).
|
||
const routes = ([
|
||
['GET', '/health/live', async () => [200, { status: 'ok' }]],
|
||
['GET', '/health/ready', readiness],
|
||
['POST', '/api/v1/users', createUser],
|
||
['GET', '/api/v1/users/me', me],
|
||
['POST', '/api/v1/auth/sessions', createSession],
|
||
['DELETE', '/api/v1/auth/sessions/current', deleteSession],
|
||
['POST', '/api/v1/chats', createChat],
|
||
['GET', '/api/v1/chats', listChats],
|
||
['GET', '/api/v1/chats/{chat_id}', getChat],
|
||
['POST', '/api/v1/chats/{chat_id}/messages', sendMessage],
|
||
['GET', '/api/v1/chats/{chat_id}/messages', listMessages],
|
||
['POST', '/api/v1/chats/{chat_id}/attachments', uploadAttachment],
|
||
['GET', '/api/v1/attachments/{attachment_id}', getAttachment],
|
||
['GET', '/api/v1/attachments/{attachment_id}/content', downloadAttachment],
|
||
] as [string, string, Handler][]).map(([method, template, handler]) =>
|
||
({ method, template, handler, pattern: new RegExp(`^${template.replace(/\{\w+\}/g, '([^/]+)')}$`) }));
|
||
|
||
async function dispatch(req: IncomingMessage, matched: { route?: string }): Promise<Result> {
|
||
const url = new URL(req.url ?? '/', 'http://api');
|
||
for (const { method, template, handler, pattern } of routes) {
|
||
const m = pattern.exec(url.pathname);
|
||
if (m && req.method === method) {
|
||
matched.route = template;
|
||
setRoute(template);
|
||
return handler({ req, url, params: m.slice(1), db, s3, config, relay });
|
||
}
|
||
}
|
||
throw notFound(); // неизвестный путь или метод — тоже JSON-ошибка контракта
|
||
}
|
||
|
||
// Каждый ответ, включая ошибки и health, несёт X-Request-Id и X-Instance-Id.
|
||
function handle(req: IncomingMessage, res: ServerResponse) {
|
||
const requestId = randomUUID();
|
||
const started = performance.now();
|
||
const ctx = context.active(); // контекст server span этого запроса
|
||
trace.getSpan(ctx)?.setAttribute('messenger.request_id', requestId);
|
||
res.setHeader('X-Request-Id', requestId);
|
||
res.setHeader('X-Instance-Id', config.instanceId);
|
||
if (!state.ready) res.setHeader('Connection', 'close'); // при остановке LB не переиспользует соединение
|
||
const matched: { route?: string } = {};
|
||
// Access-лог одного запроса; health (проверки LB и Docker каждую секунду) не логируется.
|
||
// 'close' приходит и после полного ответа, и при обрыве соединения клиентом.
|
||
res.on('close', () => {
|
||
if (matched.route?.startsWith('/health/')) return;
|
||
const status = res.statusCode;
|
||
context.with(ctx, () => log(status >= 500 ? 'error' : 'info', 'http.request', `${req.method} ${matched.route ?? 'unmatched'} → ${status}`, {
|
||
request_id: requestId, 'http.request.method': req.method ?? '', 'http.route': matched.route ?? 'unmatched',
|
||
'http.response.status_code': status, duration_ms: Math.round((performance.now() - started) * 10) / 10,
|
||
...(!res.writableFinished && { aborted: true }),
|
||
}));
|
||
});
|
||
dispatch(req, matched).then(([status, body, headers]) => send(res, status, body, headers), (err) => {
|
||
const e = toHttpError(err, requestId);
|
||
if (e.status >= 500) trace.getSpan(ctx)?.recordException(err as Error);
|
||
if (e.status === 401) {
|
||
// Basic только на входе, на остальных эндпоинтах — Bearer.
|
||
res.setHeader('WWW-Authenticate', req.url === '/api/v1/auth/sessions' ? 'Basic realm="messenger", charset="UTF-8"' : 'Bearer realm="messenger"');
|
||
}
|
||
send(res, e.status, { error: { code: e.code, message: e.message, request_id: requestId } });
|
||
});
|
||
}
|
||
|
||
return { state, handle };
|
||
}
|