Files
mtusi2026lab7/app/src/jobs/broker.client.ts
T

703 lines
20 KiB
TypeScript

import {
connect as amqpConnect,
credentials as amqpCredentials,
type Channel,
type ChannelModel,
type ConfirmChannel,
type ConsumeMessage,
type Options,
} from 'amqplib';
import {
context,
propagation,
SpanKind,
type Span,
} from '@opentelemetry/api';
import {
Inject,
Injectable,
Logger,
OnModuleDestroy,
Optional,
ServiceUnavailableException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { randomUUID } from 'node:crypto';
import { URL } from 'node:url';
import type { AppConfig } from '../config/app-config.schema.js';
import { MetricsService } from '../metrics/metrics.service.js';
import { RuntimeSecretsStore } from '../openbao/runtime-secrets.service.js';
import { TlsMaterialManager } from '../security/tls-material.js';
import { instruments } from '../telemetry/instruments.js';
import { markSpanError, tracer } from '../telemetry/tracing.js';
import {
assertTopology,
JOB_EXCHANGE,
JOB_QUEUE,
JOB_ROUTING_KEY,
} from './broker.topology.js';
import type { JobMessage } from './job-message.js';
export class BrokerUnavailableError extends ServiceUnavailableException {
constructor() {
super('Broker unavailable');
}
}
export type BrokerRole = 'producer' | 'consumer' | 'both';
export type BrokerAuthMechanism = 'external' | 'plain';
export type ConsumeHandler = (
message: ConsumeMessage,
channel: Channel,
) => Promise<void>;
const MAX_RECONNECT_DELAY_MS = 10_000;
function isAmqpAuthError(error: unknown): boolean {
if (!(error instanceof Error)) return false;
return (
error.message.includes('ACCESS_REFUSED') ||
error.message.includes('403')
);
}
function parseBrokerUrl(urlString: string | undefined): {
protocol?: string;
hostname?: string;
port?: number;
vhost?: string;
username?: string;
password?: string;
} {
if (!urlString) return {};
try {
const parsed = new URL(urlString);
const rawPath = parsed.pathname.replace(/^\/+/u, '');
const vhost = rawPath ? decodeURIComponent(rawPath) : undefined;
return {
protocol: parsed.protocol.replace(/:$/u, ''),
hostname: parsed.hostname || undefined,
port: parsed.port ? Number(parsed.port) : undefined,
vhost,
username: parsed.username
? decodeURIComponent(parsed.username)
: undefined,
password: parsed.password
? decodeURIComponent(parsed.password)
: undefined,
};
} catch {
return {};
}
}
export type AmqpConnectFn = (
url: string | Options.Connect,
socketOptions?: unknown,
) => Promise<ChannelModel>;
@Injectable()
export class BrokerClient implements OnModuleDestroy {
private readonly logger = new Logger(BrokerClient.name);
private readonly rawUrl: string | undefined;
private readonly host: string;
private readonly port: number;
private readonly vhost: string;
private readonly urlUser: string | undefined;
private readonly urlPass: string | undefined;
private readonly role: BrokerRole;
private readonly authMechanism: BrokerAuthMechanism;
private readonly passiveTopology: boolean;
private readonly deliveryLimit: number;
private readonly publishTimeoutMs: number;
private readonly connectFn: AmqpConnectFn;
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;
private readonly returned = new Map<string, () => void>();
private readonly onRotate: () => void;
constructor(
private readonly config: ConfigService<AppConfig>,
private readonly metrics: MetricsService,
@Optional() @Inject(TlsMaterialManager) private readonly tls?: TlsMaterialManager,
@Optional() @Inject(RuntimeSecretsStore) private readonly secrets?: RuntimeSecretsStore,
connectOverride?: AmqpConnectFn,
) {
const getOpt = <K extends keyof AppConfig>(key: K): AppConfig[K] | undefined =>
typeof config.get === 'function' ? config.get(key) : undefined;
this.rawUrl = getOpt('BROKER_URL');
const parsed = parseBrokerUrl(this.rawUrl);
const tlsEnabled =
this.tls?.enabled ??
(Boolean(getOpt('TLS_ENABLED')) || parsed.protocol === 'amqps');
this.host = getOpt('BROKER_HOST') ?? parsed.hostname ?? 'broker';
this.port =
getOpt('BROKER_PORT') ?? parsed.port ?? (tlsEnabled ? 5671 : 5672);
this.vhost = getOpt('BROKER_VHOST') ?? parsed.vhost ?? 'messenger';
this.urlUser = parsed.username;
this.urlPass = parsed.password;
this.role = getOpt('BROKER_ROLE') ?? 'both';
this.authMechanism =
getOpt('BROKER_AUTH_MECHANISM') ??
(tlsEnabled ? 'external' : 'plain');
this.passiveTopology = getOpt('BROKER_PASSIVE_TOPOLOGY') ?? tlsEnabled;
this.deliveryLimit = config.getOrThrow('BROKER_DELIVERY_LIMIT');
this.publishTimeoutMs = config.getOrThrow('BROKER_PUBLISH_TIMEOUT_MS');
this.connectFn =
connectOverride ??
((target, sockOpts) =>
amqpConnect(target, sockOpts as Record<string, unknown>));
this.onRotate = () => {
void this.forceReconnect('rotation');
};
this.tls?.on('reloaded', this.onRotate);
this.secrets?.on('rotated:broker', this.onRotate);
}
async publish(message: JobMessage | Buffer): Promise<void> {
if (this.role === 'consumer') {
throw new BrokerUnavailableError();
}
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.ensureConfirmChannel(),
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 {
if (this.role === 'producer') {
throw new Error('BrokerClient configured as producer cannot consume');
}
this.prefetch = prefetch;
this.handler = handler;
this.ensureConnection()
.then(() => this.subscribe())
.catch(() => this.scheduleSubscribe());
}
isConsuming(): boolean {
return this.consumerTag !== undefined;
}
/**
* Queries queue depth using a short-lived plain channel on the active
* connection — NEVER requires `confirmChannel` or `write`/`configure`
* permissions, so `BROKER_ROLE=consumer` (worker LeaseReaper) works cleanly
* and a denied `checkQueue` cannot terminate `consumeChannel` or `confirmChannel`.
*/
async queueDepth(
queue: string,
): Promise<{ messages: number; consumers: number }> {
const connection = await this.withTimeout(
this.ensureConnection(),
this.publishTimeoutMs,
);
const channel = await this.withTimeout(
connection.createChannel(),
this.publishTimeoutMs,
);
channel.on('error', () => {
// Channel-level errors (e.g. 403/404) are handled by the rejected checkQueue promise.
});
try {
const result = await this.withTimeout(
channel.checkQueue(queue),
this.publishTimeoutMs,
);
return {
messages: result.messageCount,
consumers: result.consumerCount,
};
} finally {
try {
await channel.close();
} catch {
// Already closed by broker on channel exception.
}
}
}
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.
}
}
if (channel) {
try {
await channel.close();
} catch {
// Closing an already closed channel is harmless.
}
}
}
async onModuleDestroy(): Promise<void> {
this.closing = true;
this.tls?.off('reloaded', this.onRotate);
this.secrets?.off('rotated:broker', this.onRotate);
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.
}
}
}
private async forceReconnect(reason: string): Promise<void> {
if (this.closing) return;
const connection = this.connection;
if (!connection) return;
this.logger.log(`Closing AMQP connection for reconnect (${reason})`);
try {
await connection.close();
} catch {
this.handleClose();
}
}
private async ensureConnection(): Promise<ChannelModel> {
if (this.closing) throw new BrokerUnavailableError();
if (this.connection) return this.connection;
if (!this.connecting) {
this.connecting = this.connect()
.then(() => undefined)
.finally(() => {
this.connecting = undefined;
});
}
await this.connecting;
if (!this.connection) throw new BrokerUnavailableError();
return this.connection;
}
private async ensureConfirmChannel(): Promise<ConfirmChannel> {
await this.ensureConnection();
if (!this.confirmChannel) throw new BrokerUnavailableError();
return this.confirmChannel;
}
private buildConnectArgs(): {
target: string | Options.Connect;
socketOptions?: Record<string, unknown>;
} {
const tlsEnabled = this.tls?.enabled ?? false;
if (tlsEnabled) {
if (!this.tls?.ca || !this.tls.clientCert || !this.tls.clientKey) {
throw new Error(
'Broker AMQPS mTLS requires CA, client certificate, and client key',
);
}
const socketOptions = {
ca: this.tls.ca,
cert: this.tls.clientCert,
key: this.tls.clientKey,
servername: this.host,
rejectUnauthorized: true,
minVersion: 'TLSv1.2',
};
if (this.authMechanism === 'external') {
return {
target: {
protocol: 'amqps',
hostname: this.host,
port: this.port,
vhost: this.vhost,
credentials: amqpCredentials.external(),
},
socketOptions,
};
}
const creds = this.secrets?.getBrokerCredentials();
return {
target: {
protocol: 'amqps',
hostname: this.host,
port: this.port,
vhost: this.vhost,
username: creds?.user ?? this.urlUser,
password: creds?.password ?? this.urlPass,
},
socketOptions,
};
}
if (this.rawUrl) return { target: this.rawUrl };
const creds = this.secrets?.getBrokerCredentials();
return {
target: {
protocol: 'amqp',
hostname: this.host,
port: this.port,
vhost: this.vhost,
username: creds?.user ?? this.urlUser,
password: creds?.password ?? this.urlPass,
},
};
}
private async connect(): Promise<void> {
const { target, socketOptions } = this.buildConnectArgs();
let connection: ChannelModel;
try {
connection = await this.connectFn(target, socketOptions);
} catch (error) {
if (isAmqpAuthError(error)) {
void this.secrets?.refreshNow('broker_auth_error');
}
throw error;
}
connection.on('error', (error: Error) => {
this.metrics.increment('broker.error');
if (isAmqpAuthError(error)) {
void this.secrets?.refreshNow('broker_auth_error');
}
this.logger.warn(`Broker connection error: ${error.message}`);
});
connection.on('close', () => {
if (this.connection !== connection) return;
this.handleClose();
});
try {
let confirm: ConfirmChannel | undefined;
if (this.role !== 'consumer') {
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();
});
if (this.passiveTopology) {
await confirm.checkExchange(JOB_EXCHANGE);
} else {
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 (isAmqpAuthError(error)) {
void this.secrets?.refreshNow('broker_auth_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');
if (isAmqpAuthError(error)) {
void this.secrets?.refreshNow('broker_auth_error');
}
this.logger.warn(
`Broker consumer channel error: ${error.message}`,
);
this.handleConsumerClose(channel);
});
channel.on('close', () => this.handleConsumerClose(channel));
await channel.prefetch(this.prefetch);
if (this.passiveTopology) {
await channel.checkQueue(JOB_QUEUE);
} else {
await assertTopology(channel, this.deliveryLimit);
}
if (this.handler !== handler) {
await channel.close();
return;
}
const consumer = await channel.consume(
JOB_QUEUE,
(message) => {
if (!message) {
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'}`,
);
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) {
if (isAmqpAuthError(error)) {
void this.secrets?.refreshNow('broker_auth_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.ensureConnection()
.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.ensureConnection()
.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);
}
}
}