lab5: устойчивость очереди, восстановление job и права broker
This commit is contained in:
+216
-56
@@ -12,6 +12,7 @@ import {
|
||||
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 {
|
||||
@@ -40,6 +41,7 @@ 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;
|
||||
@@ -47,9 +49,15 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
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>,
|
||||
@@ -57,23 +65,45 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
) {
|
||||
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<void> {
|
||||
const channel = await this.ensureConnected();
|
||||
const channel = await this.withTimeout(
|
||||
this.ensureConnected(),
|
||||
this.publishTimeoutMs,
|
||||
);
|
||||
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 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<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,
|
||||
@@ -81,6 +111,10 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
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());
|
||||
@@ -91,8 +125,7 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
},
|
||||
);
|
||||
} catch {
|
||||
this.metrics.increment('broker.publish_failed');
|
||||
reject(new BrokerUnavailableError());
|
||||
fail();
|
||||
}
|
||||
return promise;
|
||||
}
|
||||
@@ -102,7 +135,7 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
this.handler = handler;
|
||||
this.ensureConnected()
|
||||
.then(() => this.subscribe())
|
||||
.catch(() => this.scheduleReconnect());
|
||||
.catch(() => this.scheduleSubscribe());
|
||||
}
|
||||
|
||||
isConsuming(): boolean {
|
||||
@@ -112,7 +145,10 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
async queueDepth(
|
||||
queue: string,
|
||||
): Promise<{ messages: number; consumers: number }> {
|
||||
const channel = await this.ensureConnected();
|
||||
const channel = await this.withTimeout(
|
||||
this.ensureConnected(),
|
||||
this.publishTimeoutMs,
|
||||
);
|
||||
const result = await channel.checkQueue(queue);
|
||||
return {
|
||||
messages: result.messageCount,
|
||||
@@ -121,6 +157,8 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
}
|
||||
|
||||
async stopConsuming(): Promise<void> {
|
||||
clearTimeout(this.subscribeTimer);
|
||||
this.subscribeTimer = undefined;
|
||||
const channel = this.consumeChannel;
|
||||
const tag = this.consumerTag;
|
||||
this.consumerTag = undefined;
|
||||
@@ -145,7 +183,11 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
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;
|
||||
@@ -184,61 +226,151 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
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();
|
||||
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 async subscribe(): Promise<void> {
|
||||
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;
|
||||
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.
|
||||
}
|
||||
});
|
||||
if (!connection || !handler || this.consumerTag)
|
||||
return Promise.resolve();
|
||||
this.subscribing = this.doSubscribe(connection, handler).finally(
|
||||
() => {
|
||||
this.subscribing = undefined;
|
||||
},
|
||||
{ noAck: false },
|
||||
);
|
||||
this.consumeChannel = channel;
|
||||
this.consumerTag = consumer.consumerTag;
|
||||
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();
|
||||
}
|
||||
@@ -253,7 +385,35 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
this.metrics.increment('broker.reconnect_scheduled');
|
||||
this.reconnectTimer = setTimeout(() => {
|
||||
this.reconnectTimer = undefined;
|
||||
this.ensureConnected().catch(() => this.scheduleReconnect());
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user