import { connect as amqpConnect, type Channel, type ChannelModel, type ConfirmChannel, type ConsumeMessage, } from 'amqplib'; 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'; export class BrokerUnavailableError extends ServiceUnavailableException { constructor() { super('Broker unavailable'); } } export type ConsumeHandler = ( message: ConsumeMessage, channel: Channel, ) => Promise; 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 | undefined; private subscribing: Promise | 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 void>(); constructor( config: ConfigService, 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', ); } async publish(message: JobMessage | Buffer): Promise { 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) ? {} : { messageId: message.job_id, type: message.type, headers: { 'x-attempt': message.attempt }, }), }; const { promise, resolve, reject } = Promise.withResolvers(); 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 { 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 { 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 { 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 { 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 { 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 { 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(promise: Promise, ms: number): Promise { const { promise: timeout, reject } = Promise.withResolvers(); const timer = setTimeout(() => reject(new BrokerUnavailableError()), ms); try { return await Promise.race([promise, timeout]); } finally { clearTimeout(timer); } } }