forked from mtusi2026/mtusi2026lab6
chore: port lab5 solution as lab6 base
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import amqp, { Channel, Connection } from 'amqplib';
|
||||
import { readFileSync } from 'fs';
|
||||
|
||||
export const JOB_QUEUE = 'attachment.jobs';
|
||||
export const DEAD_LETTER_QUEUE = 'attachment.jobs.dlq';
|
||||
const DELIVERY_LIMIT = 20;
|
||||
const RECONNECT_MAX_MS = 10000;
|
||||
|
||||
export function brokerUrl(): string {
|
||||
const file = process.env.BROKER_URL_FILE;
|
||||
const url = file ? readFileSync(file, 'utf8').trim() : process.env.BROKER_URL;
|
||||
if (!url) {
|
||||
throw new Error('BROKER_URL_FILE or BROKER_URL must be set');
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
export async function assertTopology(channel: Channel): Promise<void> {
|
||||
await channel.assertQueue(DEAD_LETTER_QUEUE, {
|
||||
durable: true,
|
||||
arguments: { 'x-queue-type': 'quorum' },
|
||||
});
|
||||
await channel.assertQueue(JOB_QUEUE, {
|
||||
durable: true,
|
||||
arguments: {
|
||||
'x-queue-type': 'quorum',
|
||||
'x-delivery-limit': DELIVERY_LIMIT,
|
||||
'x-dead-letter-exchange': '',
|
||||
'x-dead-letter-routing-key': DEAD_LETTER_QUEUE,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function connectWithRetry(
|
||||
logger: Logger,
|
||||
stopping: () => boolean,
|
||||
): Promise<Connection | null> {
|
||||
let delay = 500;
|
||||
while (!stopping()) {
|
||||
try {
|
||||
const connection = await amqp.connect(brokerUrl(), { timeout: 5000 });
|
||||
logger.log('connected to broker');
|
||||
return connection;
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message.split(' ')[0] : 'unknown';
|
||||
logger.warn(`broker unavailable (${reason}), retry in ${delay} ms`);
|
||||
await sleep(delay);
|
||||
delay = Math.min(RECONNECT_MAX_MS, delay * 2);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
Reference in New Issue
Block a user