@message-queue-toolkit/amqp
Version:
AMQP adapter for message-queue-toolkit
90 lines • 2.93 kB
JavaScript
import { resolveAmqpConnection } from "./amqpConnectionResolver.js";
export class AmqpConnectionManager {
config;
logger;
connectionReceivers;
connection;
reconnectsActive;
isReconnecting;
constructor(config, logger) {
this.config = config;
this.connectionReceivers = [];
this.reconnectsActive = true;
this.isReconnecting = false;
this.logger = logger;
}
async createConnection() {
const connection = await resolveAmqpConnection(this.config);
connection.on('error', (err) => {
this.logger.error(`AmqpConnectionManager: Connection error: ${err.message}`);
this.connection = undefined;
if (this.reconnectsActive && !this.isReconnecting) {
void this.reconnect();
}
});
connection.on('close', () => {
if (this.reconnectsActive && !this.isReconnecting) {
this.logger.error('AmqpConnectionManager: Connection closed unexpectedly');
if (this.reconnectsActive) {
void this.reconnect();
}
}
});
const promises = [];
this.logger.info(`Propagating new connection across ${this.connectionReceivers.length} receivers`);
for (const receiver of this.connectionReceivers) {
promises.push(receiver.receiveNewConnection(connection));
}
await Promise.all(promises);
return connection;
}
getConnectionSync() {
return this.connection;
}
async getConnection() {
if (!this.connection) {
this.connection = await this.createConnection();
}
return this.connection;
}
async reconnect() {
if (this.isReconnecting) {
return;
}
this.logger.info('AmqpConnectionManager: Start reconnecting');
this.isReconnecting = true;
const oldConnection = this.connection;
this.connection = await this.createConnection();
if (oldConnection) {
try {
await oldConnection.close();
}
catch {
// this can fail
}
}
this.isReconnecting = false;
this.logger.info('AmqpConnectionManager: Reconnect complete');
}
async init() {
this.reconnectsActive = true;
await this.getConnection();
}
async close() {
this.reconnectsActive = false;
for (const receiver of this.connectionReceivers) {
await receiver.close();
}
try {
await this.connection?.close();
}
catch {
// it's OK
}
this.connection = undefined;
}
subscribeConnectionReceiver(connectionReceiver) {
this.connectionReceivers.push(connectionReceiver);
}
}
//# sourceMappingURL=AmqpConnectionManager.js.map