lab5: брокер RabbitMQ, worker и асинхронная обработка
This commit is contained in:
@@ -0,0 +1,259 @@
|
||||
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 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<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 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 reconnectTimer: NodeJS.Timeout | undefined;
|
||||
private reconnectDelayMs = 1000;
|
||||
private closing = false;
|
||||
|
||||
constructor(
|
||||
config: ConfigService<AppConfig>,
|
||||
private readonly metrics: MetricsService,
|
||||
) {
|
||||
this.url = config.getOrThrow('BROKER_URL');
|
||||
this.deliveryLimit = config.getOrThrow('BROKER_DELIVERY_LIMIT');
|
||||
}
|
||||
|
||||
async publish(message: JobMessage | Buffer): Promise<void> {
|
||||
const channel = await this.ensureConnected();
|
||||
const content = Buffer.isBuffer(message)
|
||||
? message
|
||||
: Buffer.from(JSON.stringify(message));
|
||||
const options = Buffer.isBuffer(message)
|
||||
? { persistent: true, contentType: 'application/json' }
|
||||
: {
|
||||
persistent: true,
|
||||
contentType: 'application/json',
|
||||
messageId: message.job_id,
|
||||
type: message.type,
|
||||
headers: { 'x-attempt': message.attempt },
|
||||
};
|
||||
const { promise, resolve, reject } = Promise.withResolvers<void>();
|
||||
try {
|
||||
channel.publish(
|
||||
JOB_EXCHANGE,
|
||||
JOB_ROUTING_KEY,
|
||||
content,
|
||||
options,
|
||||
(error) => {
|
||||
if (error) {
|
||||
this.metrics.increment('broker.publish_failed');
|
||||
reject(new BrokerUnavailableError());
|
||||
return;
|
||||
}
|
||||
this.metrics.increment('broker.published');
|
||||
resolve();
|
||||
},
|
||||
);
|
||||
} catch {
|
||||
this.metrics.increment('broker.publish_failed');
|
||||
reject(new BrokerUnavailableError());
|
||||
}
|
||||
return promise;
|
||||
}
|
||||
|
||||
consume(prefetch: number, handler: ConsumeHandler): void {
|
||||
this.prefetch = prefetch;
|
||||
this.handler = handler;
|
||||
this.ensureConnected()
|
||||
.then(() => this.subscribe())
|
||||
.catch(() => this.scheduleReconnect());
|
||||
}
|
||||
|
||||
isConsuming(): boolean {
|
||||
return this.consumerTag !== undefined;
|
||||
}
|
||||
|
||||
async queueDepth(
|
||||
queue: string,
|
||||
): Promise<{ messages: number; consumers: number }> {
|
||||
const channel = await this.ensureConnected();
|
||||
const result = await channel.checkQueue(queue);
|
||||
return {
|
||||
messages: result.messageCount,
|
||||
consumers: result.consumerCount,
|
||||
};
|
||||
}
|
||||
|
||||
async stopConsuming(): Promise<void> {
|
||||
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);
|
||||
this.reconnectTimer = undefined;
|
||||
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();
|
||||
});
|
||||
const confirm = await connection.createConfirmChannel();
|
||||
await assertTopology(confirm, this.deliveryLimit);
|
||||
this.connection = connection;
|
||||
this.confirmChannel = confirm;
|
||||
this.reconnectDelayMs = 1000;
|
||||
clearTimeout(this.reconnectTimer);
|
||||
this.reconnectTimer = undefined;
|
||||
this.metrics.increment('broker.connected');
|
||||
if (this.handler) await this.subscribe();
|
||||
}
|
||||
|
||||
private async subscribe(): Promise<void> {
|
||||
const connection = this.connection;
|
||||
const handler = this.handler;
|
||||
if (!connection || !handler || this.consumerTag) return;
|
||||
const channel = await connection.createChannel();
|
||||
channel.on('error', (error: Error) => {
|
||||
this.metrics.increment('broker.consumer_error');
|
||||
this.logger.warn(`Broker consumer channel error: ${error.message}`);
|
||||
});
|
||||
channel.on('close', () => {
|
||||
if (this.consumeChannel !== channel) return;
|
||||
this.consumeChannel = undefined;
|
||||
this.consumerTag = undefined;
|
||||
});
|
||||
await channel.prefetch(this.prefetch);
|
||||
await assertTopology(channel, this.deliveryLimit);
|
||||
const consumer = await channel.consume(
|
||||
JOB_QUEUE,
|
||||
(message) => {
|
||||
if (!message) 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'}`,
|
||||
);
|
||||
try {
|
||||
channel.nack(message, false, true);
|
||||
} catch {
|
||||
// The channel is gone; the broker redelivers after the lease.
|
||||
}
|
||||
});
|
||||
},
|
||||
{ noAck: false },
|
||||
);
|
||||
this.consumeChannel = channel;
|
||||
this.consumerTag = consumer.consumerTag;
|
||||
}
|
||||
|
||||
private handleClose(): void {
|
||||
this.metrics.increment('broker.closed');
|
||||
this.connection = undefined;
|
||||
this.confirmChannel = undefined;
|
||||
this.consumeChannel = undefined;
|
||||
this.consumerTag = undefined;
|
||||
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().catch(() => this.scheduleReconnect());
|
||||
}, delay);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user