lab7: базовый коммит из lab6 (bf06167)

Перенесена кодовая база и инфраструктура lab6: NestJS-приложение (API +
worker, RabbitMQ, outbox, S3, OpenTelemetry), Dockerfile, compose.yaml,
infra/{grafana,haproxy,loki,minio,otel/collector.yaml,prometheus,
rabbitmq,tempo}, docs/runbooks, стендовые скрипты, scripts/lab{4,5,6} и
contracts/extensions.openapi.json.

Задание lab7 оставлено своим: README, REPORT, COURSE, CONTRIBUTING,
MAINTAINERS, lab.json, contracts/{openapi,infrastructure,jobs.schema,
attachment-states,examples,observability,trust-matrix,README},
security/THREAT_MODEL.md, tests (включая security.py), compose.example.yaml,
infra/{openbao,otel}/README.md, .github/pull_request_template.md.
Не переносились старые evidence/lab4..lab6 (18 МБ трека lab6) и
неотслеживаемый docs/lab6.html.

Адаптации при переносе:
- docker-проект mtusi-lab6 -> mtusi-lab7, тег образа mtusi-messenger:lab7
  и папка Grafana Messenger lab7 (compose.yaml, scripts/stop-one.sh,
  .env.example, infra/README.md, infra/grafana/provisioning/dashboards),
  чтобы тома и контейнеры не пересекались с lab6;
- Makefile: сохранены BASE_URL=https://localhost:8443 и цель test-security
  из skeleton lab7, добавлены стендовые и проверочные цели lab6;
- .env.example: рабочие переменные приложения и стенда lab6 + блок
  переменных lab7 (PUBLIC_BASE_URL, TLS_*, BAO_*, ARGON2_*) из skeleton.
This commit is contained in:
2026-11-26 15:35:57 +03:00
parent 20afc2c790
commit 3418252554
198 changed files with 33745 additions and 16 deletions
+478
View File
@@ -0,0 +1,478 @@
import {
connect as amqpConnect,
type Channel,
type ChannelModel,
type ConfirmChannel,
type ConsumeMessage,
} from 'amqplib';
import {
context,
propagation,
SpanKind,
type Span,
} from '@opentelemetry/api';
import {
Injectable,
Logger,
OnModuleDestroy,
ServiceUnavailableException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { randomUUID } from 'node:crypto';
import type { AppConfig } from '../config/app-config.schema.js';
import { MetricsService } from '../metrics/metrics.service.js';
import {
assertTopology,
JOB_EXCHANGE,
JOB_QUEUE,
JOB_ROUTING_KEY,
} from './broker.topology.js';
import type { JobMessage } from './job-message.js';
import { instruments } from '../telemetry/instruments.js';
import { markSpanError, tracer } from '../telemetry/tracing.js';
export class BrokerUnavailableError extends ServiceUnavailableException {
constructor() {
super('Broker unavailable');
}
}
export type ConsumeHandler = (
message: ConsumeMessage,
channel: Channel,
) => Promise<void>;
const MAX_RECONNECT_DELAY_MS = 10_000;
@Injectable()
export class BrokerClient implements OnModuleDestroy {
private readonly logger = new Logger(BrokerClient.name);
private readonly url: string;
private readonly deliveryLimit: number;
private readonly publishTimeoutMs: number;
private connection: ChannelModel | undefined;
private confirmChannel: ConfirmChannel | undefined;
private consumeChannel: Channel | undefined;
private consumerTag: string | undefined;
private prefetch = 0;
private handler: ConsumeHandler | undefined;
private connecting: Promise<void> | undefined;
private subscribing: Promise<void> | undefined;
private reconnectTimer: NodeJS.Timeout | undefined;
private subscribeTimer: NodeJS.Timeout | undefined;
private reconnectDelayMs = 1000;
private subscribeDelayMs = 1000;
private closing = false;
// Unroutable messages are returned before their confirm; the map lets the
// return listener reject the exact publish that produced it.
private readonly returned = new Map<string, () => void>();
constructor(
config: ConfigService<AppConfig>,
private readonly metrics: MetricsService,
) {
this.url = config.getOrThrow('BROKER_URL');
this.deliveryLimit = config.getOrThrow('BROKER_DELIVERY_LIMIT');
this.publishTimeoutMs = config.getOrThrow(
'BROKER_PUBLISH_TIMEOUT_MS',
);
}
/**
* PRODUCER span around publish + broker confirm. Its context goes into the
* AMQP headers (W3C traceparent/tracestate), so the worker's CONSUMER span
* becomes its child; the body keeps the context of the transaction that
* wrote the outbox row.
*/
async publish(message: JobMessage | Buffer): Promise<void> {
const attributes = {
'messaging.system': 'rabbitmq',
'messaging.operation.type': 'send',
'messaging.operation.name': 'publish',
'messaging.destination.name': JOB_EXCHANGE,
'messaging.rabbitmq.destination.routing_key': JOB_ROUTING_KEY,
...(Buffer.isBuffer(message)
? {}
: {
'messaging.message.id': message.job_id,
'messenger.job.id': message.job_id,
'messenger.job.attempt': message.attempt,
}),
};
return tracer().startActiveSpan(
`publish ${JOB_EXCHANGE}`,
{ kind: SpanKind.PRODUCER, attributes },
async (span: Span) => {
const traceHeaders: Record<string, string> = {};
propagation.inject(context.active(), traceHeaders);
const labels = { 'messaging.destination.name': JOB_EXCHANGE };
try {
await this.publishConfirmed(message, traceHeaders);
instruments().brokerPublished.add(1, {
...labels,
outcome: 'success',
});
} catch (error) {
instruments().brokerPublished.add(1, {
...labels,
outcome: 'failed',
});
markSpanError(span, error);
throw error;
} finally {
span.end();
}
},
);
}
private async publishConfirmed(
message: JobMessage | Buffer,
traceHeaders: Record<string, string>,
): Promise<void> {
const channel = await this.withTimeout(
this.ensureConnected(),
this.publishTimeoutMs,
);
const content = Buffer.isBuffer(message)
? message
: Buffer.from(JSON.stringify(message));
const correlationId = randomUUID();
const options = {
persistent: true,
contentType: 'application/json',
mandatory: true,
correlationId,
...(Buffer.isBuffer(message)
? { headers: traceHeaders }
: {
messageId: message.job_id,
type: message.type,
headers: { 'x-attempt': message.attempt, ...traceHeaders },
}),
};
const { promise, resolve, reject } = Promise.withResolvers<void>();
let settled = false;
const fail = (): void => {
if (settled) return;
settled = true;
clearTimeout(timer);
this.returned.delete(correlationId);
this.metrics.increment('broker.publish_failed');
reject(new BrokerUnavailableError());
};
const timer = setTimeout(fail, this.publishTimeoutMs);
this.returned.set(correlationId, fail);
try {
channel.publish(
JOB_EXCHANGE,
JOB_ROUTING_KEY,
content,
options,
(error) => {
if (settled) return;
settled = true;
clearTimeout(timer);
this.returned.delete(correlationId);
if (error) {
this.metrics.increment('broker.publish_failed');
reject(new BrokerUnavailableError());
return;
}
this.metrics.increment('broker.published');
resolve();
},
);
} catch {
fail();
}
return promise;
}
consume(prefetch: number, handler: ConsumeHandler): void {
this.prefetch = prefetch;
this.handler = handler;
this.ensureConnected()
.then(() => this.subscribe())
.catch(() => this.scheduleSubscribe());
}
isConsuming(): boolean {
return this.consumerTag !== undefined;
}
async queueDepth(
queue: string,
): Promise<{ messages: number; consumers: number }> {
const channel = await this.withTimeout(
this.ensureConnected(),
this.publishTimeoutMs,
);
const result = await channel.checkQueue(queue);
return {
messages: result.messageCount,
consumers: result.consumerCount,
};
}
async stopConsuming(): Promise<void> {
clearTimeout(this.subscribeTimer);
this.subscribeTimer = undefined;
const channel = this.consumeChannel;
const tag = this.consumerTag;
this.consumerTag = undefined;
this.consumeChannel = undefined;
this.handler = undefined;
if (channel && tag) {
try {
await channel.cancel(tag);
} catch {
// The channel is already closing; there is nothing to cancel.
}
}
if (channel) {
try {
await channel.close();
} catch {
// Closing an already closed channel is harmless.
}
}
}
async onModuleDestroy(): Promise<void> {
this.closing = true;
clearTimeout(this.reconnectTimer);
clearTimeout(this.subscribeTimer);
this.reconnectTimer = undefined;
this.subscribeTimer = undefined;
for (const reject of this.returned.values()) reject();
this.returned.clear();
await this.stopConsuming();
const connection = this.connection;
this.connection = undefined;
this.confirmChannel = undefined;
if (connection) {
try {
await connection.close();
} catch {
// Shutdown is best effort; channels are already unusable.
}
}
}
private async ensureConnected(): Promise<ConfirmChannel> {
if (this.closing) throw new BrokerUnavailableError();
if (this.confirmChannel) return this.confirmChannel;
if (!this.connecting) {
this.connecting = this.connect()
.then(() => undefined)
.finally(() => {
this.connecting = undefined;
});
}
await this.connecting;
if (!this.confirmChannel) throw new BrokerUnavailableError();
return this.confirmChannel;
}
private async connect(): Promise<void> {
const connection = await amqpConnect(this.url);
connection.on('error', (error: Error) => {
this.metrics.increment('broker.error');
this.logger.warn(`Broker connection error: ${error.message}`);
});
connection.on('close', () => {
if (this.connection !== connection) return;
this.handleClose();
});
try {
const confirm = await connection.createConfirmChannel();
confirm.on('return', (message) => {
const correlationId = message.properties?.correlationId;
if (!correlationId) return;
const reject = this.returned.get(correlationId);
if (!reject) return;
this.returned.delete(correlationId);
this.logger.warn('Broker returned an unroutable job message');
reject();
});
await assertTopology(confirm, this.deliveryLimit);
confirm.on('error', (error: Error) => {
this.metrics.increment('broker.confirm_error');
this.logger.warn(`Broker confirm channel error: ${error.message}`);
});
confirm.on('close', () => this.handleConfirmClose(confirm));
this.connection = connection;
this.confirmChannel = confirm;
this.reconnectDelayMs = 1000;
clearTimeout(this.reconnectTimer);
this.reconnectTimer = undefined;
this.metrics.increment('broker.connected');
} catch (error) {
if (this.connection === connection) {
this.connection = undefined;
this.confirmChannel = undefined;
}
try {
await connection.close();
} catch {
// The connection is already unusable.
}
throw error;
}
if (this.handler)
void this.subscribe().catch(() => this.scheduleSubscribe());
}
private handleConfirmClose(confirm: ConfirmChannel): void {
if (this.confirmChannel !== confirm) return;
this.metrics.increment('broker.confirm_closed');
for (const reject of this.returned.values()) reject();
this.returned.clear();
this.confirmChannel = undefined;
const connection = this.connection;
if (connection) {
void connection.close().catch(() => this.handleClose());
} else {
this.handleClose();
}
}
private subscribe(): Promise<void> {
if (this.subscribing) return this.subscribing;
const connection = this.connection;
const handler = this.handler;
if (!connection || !handler || this.consumerTag)
return Promise.resolve();
this.subscribing = this.doSubscribe(connection, handler).finally(
() => {
this.subscribing = undefined;
},
);
return this.subscribing;
}
private async doSubscribe(
connection: ChannelModel,
handler: ConsumeHandler,
): Promise<void> {
const channel = await connection.createChannel();
try {
channel.on('error', (error: Error) => {
this.metrics.increment('broker.consumer_error');
this.logger.warn(
`Broker consumer channel error: ${error.message}`,
);
this.handleConsumerClose(channel);
});
channel.on('close', () => this.handleConsumerClose(channel));
await channel.prefetch(this.prefetch);
await assertTopology(channel, this.deliveryLimit);
if (this.handler !== handler) {
await channel.close();
return;
}
const consumer = await channel.consume(
JOB_QUEUE,
(message) => {
if (!message) {
// basic.cancel from the broker: the worker must not stay
// healthy while deaf.
this.handleConsumerClose(channel);
void channel.close().catch(() => undefined);
return;
}
handler(message, channel).catch((error: unknown) => {
this.metrics.increment('broker.handler_error');
this.logger.error(
`Job handler crashed: ${error instanceof Error ? error.message : 'unknown error'}`,
);
// Hold the message briefly instead of burning the
// quorum delivery limit in a tight nack loop.
setTimeout(() => {
try {
channel.nack(message, false, true);
} catch {
// The channel is gone; the broker redelivers after the lease.
}
}, 1000);
});
},
{ noAck: false },
);
this.consumeChannel = channel;
this.consumerTag = consumer.consumerTag;
this.subscribeDelayMs = 1000;
} catch (error) {
try {
await channel.close();
} catch {
// The channel is already unusable.
}
throw error;
}
}
private handleConsumerClose(channel: Channel): void {
if (this.consumeChannel && this.consumeChannel !== channel) return;
this.consumeChannel = undefined;
this.consumerTag = undefined;
if (!this.closing && this.handler) this.scheduleSubscribe();
}
private handleClose(): void {
this.metrics.increment('broker.closed');
clearTimeout(this.subscribeTimer);
this.subscribeTimer = undefined;
this.connection = undefined;
this.confirmChannel = undefined;
this.consumeChannel = undefined;
this.consumerTag = undefined;
for (const reject of this.returned.values()) reject();
this.returned.clear();
if (this.closing) return;
this.scheduleReconnect();
}
private scheduleReconnect(): void {
if (this.closing || this.reconnectTimer) return;
const delay = this.reconnectDelayMs;
this.reconnectDelayMs = Math.min(
this.reconnectDelayMs * 2,
MAX_RECONNECT_DELAY_MS,
);
this.metrics.increment('broker.reconnect_scheduled');
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = undefined;
this.ensureConnected()
.then(() => this.subscribe())
.catch(() => this.scheduleReconnect());
}, delay);
}
private scheduleSubscribe(): void {
if (this.closing || !this.handler || this.subscribeTimer) return;
const delay = this.subscribeDelayMs;
this.subscribeDelayMs = Math.min(
this.subscribeDelayMs * 2,
MAX_RECONNECT_DELAY_MS,
);
this.metrics.increment('broker.subscribe_scheduled');
this.subscribeTimer = setTimeout(() => {
this.subscribeTimer = undefined;
this.ensureConnected()
.then(() => this.subscribe())
.catch(() => this.scheduleSubscribe());
}, delay);
}
private async withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
const { promise: timeout, reject } = Promise.withResolvers<never>();
const timer = setTimeout(() => reject(new BrokerUnavailableError()), ms);
try {
return await Promise.race([promise, timeout]);
} finally {
clearTimeout(timer);
}
}
}