|
| 1 | +const amqp = require('amqp-connection-manager'); |
| 2 | +const platformLogger = require('@elastic.io/component-logger')(); |
| 3 | + |
| 4 | +const RECONNECT_TIMEOUT = 5; |
| 5 | +const RECONNECT_ATTEMPTS = 12; |
| 6 | + |
| 7 | +const validateAttemptsAndTimeout = (input, def) => { |
| 8 | + if (!input) return def; |
| 9 | + if (input && Number(input).toString() !== 'NaN' && Number(input) <= 1000 && Number(input) >= 0) { |
| 10 | + return Number(input); |
| 11 | + } |
| 12 | + throw new Error('"Reconnect Timeout" and "Reconnect Attempts" should be valid number between 0 and 1000'); |
| 13 | +}; |
| 14 | + |
| 15 | +class AMQPClient { |
| 16 | + constructor(cfg, context) { |
| 17 | + this.connection = null; |
| 18 | + this.channel = null; |
| 19 | + this.logger = context.logger || platformLogger; |
| 20 | + this.cfg = cfg; |
| 21 | + this.queueName = `eio_consumer_${process.env.ELASTICIO_FLOW_ID}_${process.env.ELASTICIO_USER_ID}`; |
| 22 | + this.retry = 0; |
| 23 | + this.context = context; |
| 24 | + this.reconnectTimeOut = validateAttemptsAndTimeout(cfg.reconnectTimeOut, RECONNECT_TIMEOUT); |
| 25 | + this.reconnectAttempts = validateAttemptsAndTimeout(cfg.reconnectAttempts, RECONNECT_ATTEMPTS); |
| 26 | + } |
| 27 | + |
| 28 | + setLogger(logger) { |
| 29 | + this.logger = logger; |
| 30 | + } |
| 31 | + |
| 32 | + init(confirmChannel = true, assertExchangeOptions, deleteQueue) { |
| 33 | + return new Promise((resolve, reject) => { |
| 34 | + this.connection = amqp.connect([this.cfg.amqpURI], { |
| 35 | + reconnectTimeInSeconds: this.reconnectTimeOut, |
| 36 | + }); |
| 37 | + this.connection.on('connect', () => { |
| 38 | + this.retry = 0; |
| 39 | + this.logger.info('Successfully connected to RabbitMQ'); |
| 40 | + resolve(); |
| 41 | + }); |
| 42 | + this.connection.on('connectFailed', ({ err }) => { |
| 43 | + this.retry += 1; |
| 44 | + if (this.retry >= this.reconnectAttempts) { |
| 45 | + const errMsg = new Error(`Connection failed after ${this.reconnectAttempts} attempts`); |
| 46 | + this.connection.emit('error', { err: errMsg }); |
| 47 | + this.context.emit('error', errMsg); |
| 48 | + delete this.connection; |
| 49 | + } else { |
| 50 | + this.logger.error(`Connection failed due to: ${err}, ${this.retry} of ${this.reconnectAttempts} retry after ${this.reconnectTimeOut}sec`); |
| 51 | + } |
| 52 | + }); |
| 53 | + this.connection.on('disconnect', ({ err }) => { this.logger.error(`Connection disconnected due to: ${err}`); }); |
| 54 | + this.connection.on('error', ({ err }) => { |
| 55 | + this.logger.error(`Connection encountered an error: ${err}`); |
| 56 | + reject(err); |
| 57 | + }); |
| 58 | + this.connection.on('blocked', ({ reason }) => { this.logger.error(`Connection blocked due to: ${reason}`); }); |
| 59 | + this.connection.on('unblocked', () => { this.logger.info('Connection unblocked'); }); |
| 60 | + this.channel = this.connection.createChannel({ |
| 61 | + confirm: confirmChannel, |
| 62 | + setup: async (channel) => { |
| 63 | + try { |
| 64 | + this.logger.debug('Asserting topic exchange...'); |
| 65 | + await channel.assertExchange(this.cfg.topic, 'topic', assertExchangeOptions); |
| 66 | + if (!confirmChannel) { |
| 67 | + this.logger.debug('Asserting queue'); |
| 68 | + await channel.assertQueue(this.queueName, { exclusive: false, durable: false }); |
| 69 | + const keys = (this.cfg.bindingKeys || '#').split(',').map((s) => s.trim()); |
| 70 | + for (const key of keys) { |
| 71 | + this.logger.debug('Binding queue to exchange...'); |
| 72 | + await channel.bindQueue(this.queueName, this.cfg.topic, key); |
| 73 | + } |
| 74 | + } |
| 75 | + if (deleteQueue) { |
| 76 | + this.logger.info(`Deleting queue ${this.queueName}`); |
| 77 | + await channel.deleteQueue(this.queueName); |
| 78 | + } |
| 79 | + this.logger.info('Successfully finished channel setup'); |
| 80 | + return channel; |
| 81 | + } catch (err) { |
| 82 | + this.logger.error(`Error on Channel setup: ${err}`); |
| 83 | + return channel; |
| 84 | + } |
| 85 | + }, |
| 86 | + }); |
| 87 | + }); |
| 88 | + } |
| 89 | + |
| 90 | + async publish(routingKey, content, options) { |
| 91 | + await this.init(); |
| 92 | + this.logger.info('Going to publish message'); |
| 93 | + await this.channel.publish(this.cfg.topic, routingKey, content, options); |
| 94 | + this.logger.info('Message published'); |
| 95 | + } |
| 96 | + |
| 97 | + async consume(onMessage, options) { |
| 98 | + this.logger.info(`Starting consuming from ${this.queueName}`); |
| 99 | + return this.channel.consume(this.queueName, onMessage, options); |
| 100 | + } |
| 101 | + |
| 102 | + async waitForConnect() { |
| 103 | + return this.channel.waitForConnect(); |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +module.exports.AMQPClient = AMQPClient; |
0 commit comments