@autofleet/rabbit 3.6.1-beta-e33c35c7.0 → 4.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/coverage/clover.xml +669 -0
  2. package/coverage/coverage-final.json +9 -0
  3. package/coverage/lcov-report/base.css +224 -0
  4. package/coverage/lcov-report/block-navigation.js +87 -0
  5. package/coverage/lcov-report/favicon.png +0 -0
  6. package/coverage/lcov-report/index.html +131 -0
  7. package/coverage/lcov-report/prettify.css +1 -0
  8. package/coverage/lcov-report/prettify.js +2 -0
  9. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  10. package/coverage/lcov-report/sorter.js +196 -0
  11. package/coverage/lcov-report/src/index.html +131 -0
  12. package/coverage/lcov-report/src/index.ts.html +3826 -0
  13. package/coverage/lcov-report/src/lib/celery.ts.html +352 -0
  14. package/coverage/lcov-report/src/lib/consts.ts.html +142 -0
  15. package/coverage/lcov-report/src/lib/index.html +191 -0
  16. package/coverage/lcov-report/src/lib/rabbitError.ts.html +103 -0
  17. package/coverage/lcov-report/src/lib/redis.ts.html +133 -0
  18. package/coverage/lcov-report/src/lib/types.ts.html +268 -0
  19. package/coverage/lcov-report/src/lib/utils.ts.html +142 -0
  20. package/coverage/lcov-report/src/logger.ts.html +100 -0
  21. package/coverage/lcov.info +1076 -0
  22. package/dist/index.d.ts +15 -22
  23. package/dist/index.js +162 -281
  24. package/dist/lib/celery.js +0 -1
  25. package/dist/lib/consts.d.ts +2 -0
  26. package/dist/lib/consts.js +3 -2
  27. package/dist/lib/rabbitError.js +0 -1
  28. package/dist/lib/redis.js +0 -1
  29. package/dist/lib/types.d.ts +0 -8
  30. package/dist/lib/types.js +0 -1
  31. package/dist/lib/utils.js +0 -1
  32. package/dist/logger.js +0 -1
  33. package/dist/{mock/index.d.ts → mock.d.ts} +1 -1
  34. package/dist/{mock/index.js → mock.js} +1 -2
  35. package/package.json +16 -22
  36. package/src/index.ts +187 -329
  37. package/src/lib/consts.ts +2 -0
  38. package/src/lib/types.ts +0 -10
  39. package/src/{mock/index.ts → mock.ts} +2 -2
  40. package/tsconfig.json +2 -2
  41. package/.claude/settings.local.json +0 -3
  42. package/dist/index.js.map +0 -1
  43. package/dist/lib/celery.js.map +0 -1
  44. package/dist/lib/consts.js.map +0 -1
  45. package/dist/lib/rabbitError.js.map +0 -1
  46. package/dist/lib/redis.js.map +0 -1
  47. package/dist/lib/types.js.map +0 -1
  48. package/dist/lib/utils.js.map +0 -1
  49. package/dist/logger.js.map +0 -1
  50. package/dist/mock/index.js.map +0 -1
  51. package/dist/mock/vitest.d.ts +0 -13
  52. package/dist/mock/vitest.js +0 -18
  53. package/dist/mock/vitest.js.map +0 -1
  54. package/src/mock/vitest.ts +0 -24
  55. package/tsconfig.build.json +0 -5
  56. package/vitest.config.ts +0 -16
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  "use strict";
2
+ /* eslint-disable no-empty,consistent-return,no-async-promise-executor,@typescript-eslint/no-unused-vars */
2
3
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
5
  };
5
6
  Object.defineProperty(exports, "__esModule", { value: true });
6
7
  exports.sendCeleryTaskViaHttp = void 0;
7
- /* eslint-disable no-empty,consistent-return,no-async-promise-executor,@typescript-eslint/no-unused-vars,no-param-reassign */
8
8
  const events_1 = require("events");
9
9
  const util_1 = require("util");
10
10
  const moment_1 = __importDefault(require("moment"));
@@ -12,6 +12,7 @@ const redis_lock_1 = __importDefault(require("redis-lock"));
12
12
  const amqp_connection_manager_1 = require("amqp-connection-manager");
13
13
  const zehut_1 = require("@autofleet/zehut");
14
14
  const node_crypto_1 = require("node:crypto");
15
+ const axios_1 = __importDefault(require("axios"));
15
16
  const logger_1 = __importDefault(require("./logger"));
16
17
  const rabbitError_1 = __importDefault(require("./lib/rabbitError"));
17
18
  const redis_1 = __importDefault(require("./lib/redis"));
@@ -21,8 +22,6 @@ const types_1 = require("./lib/types");
21
22
  // const debug = nodeDebug('af-rabbitmq')
22
23
  const debug = logger_1.default.debug.bind(logger_1.default);
23
24
  const PUBLISH_TIMEOUT = 1000 * 10;
24
- // TODO: [QUORUM-PHASE-3] Delete this env var
25
- const { DISABLE_QUORUM_QUEUES, } = process.env;
26
25
  const HEARTBEAT = '60';
27
26
  class RabbitMq {
28
27
  static parseMsg(msg) {
@@ -62,52 +61,48 @@ class RabbitMq {
62
61
  this.DISCONNECT_MSG = 'rabbit: connection disconnect';
63
62
  this.RECONNECT_MSG = 'rabbit: connection disconnect - reconnecting';
64
63
  this.consumers = [];
65
- this.doesVHostExist = false;
66
- this.vhost = 'quorum-vhost';
67
- this.needsConsumerReestablishment = false;
64
+ this.isVHostExist = false;
68
65
  this.oldConsumers = [];
69
- this.oldNeedsConsumerReestablishment = false;
70
66
  this.assertVHost = async () => {
71
- if (this.doesVHostExist) {
67
+ if (this.isVHostExist) {
72
68
  return;
73
69
  }
74
- const username = process.env.RABBITMQ_USERNAME || 'guest';
75
- const password = process.env.RABBITMQ_PASSWORD || 'guest';
76
- const credentials = Buffer.from(`${username}:${password}`).toString('base64');
77
- const headers = {
78
- Authorization: `Basic ${credentials}`,
79
- 'Content-Type': 'application/json',
70
+ if (!this.options?.vhost) {
71
+ throw new Error('vhost is not defined');
72
+ }
73
+ const { vhost } = this.options;
74
+ const auth = {
75
+ auth: {
76
+ username: process.env.RABBITMQ_USERNAME || 'guest',
77
+ password: process.env.RABBITMQ_PASSWORD || 'guest',
78
+ },
80
79
  };
81
- const rabbitHost = `http://${(this.options?.rabbitHost || process.env.RABBITMQ_SERVICE_HOST || 'localhost').split(':')[0]}:15672`;
82
- const url = `${rabbitHost}/api/vhosts/${encodeURIComponent(this.vhost)}`;
80
+ const rabbitHost = `http://${(this.options.rabbitHost || process.env.RABBITMQ_SERVICE_HOST || 'localhost').split(':')[0]}:15672`;
83
81
  try {
84
- const response = await fetch(url, {
85
- method: 'GET',
86
- headers,
87
- });
88
- if (response.status === 200) {
89
- this.doesVHostExist = true;
90
- logger_1.default.info('Vhost exists', { vhost: this.vhost });
91
- return;
92
- }
93
- if (response.status !== 404) {
94
- logger_1.default.error('Failed to check vhost', { response });
95
- throw new rabbitError_1.default('Failed to check vhost');
96
- }
97
- const createResponse = await fetch(url, {
98
- method: 'PUT',
99
- headers,
100
- body: JSON.stringify({ default_queue_type: 'quorum' }),
101
- });
102
- if (!createResponse.ok) {
103
- logger_1.default.error('Failed to create vhost', { response: createResponse });
104
- throw new rabbitError_1.default('Failed to create vhost');
82
+ const response = await axios_1.default.get(`${rabbitHost}/api/vhosts/${encodeURIComponent(vhost)}`, auth);
83
+ if (response.status !== 200) {
84
+ throw new Error('Failed to check vhost');
105
85
  }
106
- this.doesVHostExist = true;
107
- logger_1.default.info('Vhost created', { vhost: this.vhost });
86
+ this.isVHostExist = true;
87
+ logger_1.default.info('Vhost exists', { vhost });
108
88
  }
109
89
  catch (error) {
110
- logger_1.default.error('Failed to check or create vhost', { error });
90
+ // If the vhost does not exist, create it
91
+ if (error instanceof axios_1.default.AxiosError && error.response?.status === 404) {
92
+ try {
93
+ await axios_1.default.put(`${rabbitHost}/api/vhosts/${encodeURIComponent(vhost)}`, {
94
+ default_queue_type: 'quorum',
95
+ }, auth);
96
+ this.isVHostExist = true;
97
+ logger_1.default.info('Vhost created', { vhost: this.options?.vhost });
98
+ return;
99
+ }
100
+ catch (createError) {
101
+ logger_1.default.error('Failed to create vhost', { error: createError });
102
+ throw createError;
103
+ }
104
+ }
105
+ logger_1.default.error('Failed to check vhost', { error });
111
106
  throw error;
112
107
  }
113
108
  };
@@ -140,11 +135,11 @@ class RabbitMq {
140
135
  await this.unlockRedisIfNeeded(releaseLock);
141
136
  if (channel && msg) {
142
137
  if (!skipRetry
143
- && (!msg.properties.headers?.[consts_1.RETRY_HEADER]
138
+ && (!msg.properties.headers[consts_1.RETRY_HEADER]
144
139
  || parseInt(msg.properties.headers[consts_1.RETRY_HEADER], 10) < options.retries)) {
145
140
  await this.sendToQueue(queue, RabbitMq.parseMsg(msg).content, options, {
146
141
  ...msg.properties.headers,
147
- [consts_1.RETRY_HEADER]: msg.properties.headers?.[consts_1.RETRY_HEADER]
142
+ [consts_1.RETRY_HEADER]: msg.properties.headers[consts_1.RETRY_HEADER]
148
143
  ? msg.properties.headers[consts_1.RETRY_HEADER] + 1
149
144
  : 1,
150
145
  });
@@ -153,7 +148,7 @@ class RabbitMq {
153
148
  const deadQueue = `${queue}-dead`;
154
149
  await this.sendToQueue(deadQueue, RabbitMq.parseMsg(msg).content, deadQueueOptions, {
155
150
  ...msg.properties.headers,
156
- [consts_1.RETRY_HEADER]: msg.properties.headers?.[consts_1.RETRY_HEADER]
151
+ [consts_1.RETRY_HEADER]: msg.properties.headers[consts_1.RETRY_HEADER]
157
152
  ? msg.properties.headers[consts_1.RETRY_HEADER] + 1
158
153
  : 1,
159
154
  });
@@ -167,34 +162,10 @@ class RabbitMq {
167
162
  });
168
163
  }
169
164
  };
170
- this.maskURL = (url) => {
171
- try {
172
- const urlObj = new URL(url);
173
- urlObj.username = '***';
174
- urlObj.password = '***';
175
- return urlObj.toString();
176
- }
177
- catch {
178
- return url;
179
- }
180
- };
181
165
  this.em = new events_1.EventEmitter();
182
- this.publishChannel = null;
166
+ this.channel = null;
183
167
  this.publishChannelSetupPromise = null;
184
- this.publishConnection = {
185
- amqpConnection: null,
186
- creatingConnection: false,
187
- connectionCreatedEventName: 'publishConnectionCreated',
188
- connectionFailedEventName: 'publishConnectionFailed',
189
- blockReconnect: false,
190
- };
191
- this.consumeConnection = {
192
- amqpConnection: null,
193
- creatingConnection: false,
194
- connectionCreatedEventName: 'consumeConnectionCreated',
195
- connectionFailedEventName: 'consumeConnectionFailed',
196
- blockReconnect: false,
197
- };
168
+ this.connection = null;
198
169
  this.creatingConnection = false;
199
170
  this.exchanges = {};
200
171
  this.queues = {};
@@ -202,6 +173,9 @@ class RabbitMq {
202
173
  this.assertExchangePromises = {};
203
174
  this.consumers = [];
204
175
  this.options = options;
176
+ if (!options?.vhost) {
177
+ this.options.vhost = process.env.VHOST_NAME || 'quorum-vhost';
178
+ }
205
179
  this.redisClient = redisConfig && (0, redis_1.default)(redisConfig);
206
180
  if (this.redisClient) {
207
181
  this.redisLock = (0, util_1.promisify)((0, redis_lock_1.default)(this.redisClient));
@@ -216,24 +190,11 @@ class RabbitMq {
216
190
  await this.gracefulShutdown('SIGINT');
217
191
  });
218
192
  }
219
- // TODO: [QUORUM-PHASE-3] Delete the old properties that we use for the old consumers and publishers
193
+ // TODO: DELETE OLD PROPERTIES
220
194
  this.oldEm = new events_1.EventEmitter();
221
- this.oldPublishChannel = null;
195
+ this.oldChannel = null;
222
196
  this.oldPublishChannelSetupPromise = null;
223
- this.oldPublishConnection = {
224
- amqpConnection: null,
225
- creatingConnection: false,
226
- connectionCreatedEventName: 'oldPublishConnectionCreated',
227
- connectionFailedEventName: 'oldPublishConnectionFailed',
228
- blockReconnect: false,
229
- };
230
- this.oldConsumeConnection = {
231
- amqpConnection: null,
232
- creatingConnection: false,
233
- connectionCreatedEventName: 'oldConsumeConnectionCreated',
234
- connectionFailedEventName: 'oldConsumeConnectionFailed',
235
- blockReconnect: false,
236
- };
197
+ this.oldConnection = null;
237
198
  this.oldCreatingConnection = false;
238
199
  this.oldExchanges = {};
239
200
  this.oldQueues = {};
@@ -242,31 +203,30 @@ class RabbitMq {
242
203
  this.oldConsumers = [];
243
204
  this.oldConsumersTags = [];
244
205
  }
245
- async getConnection(connection) {
206
+ async getConnection() {
246
207
  return new Promise(async (resolve, reject) => {
247
- const { amqpConnection: connectionLocal, creatingConnection, connectionCreatedEventName, connectionFailedEventName, blockReconnect, } = connection;
248
- if (blockReconnect) {
208
+ if (this.blockReconnect) {
249
209
  debug('rabbit: block reconnect');
250
210
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
251
211
  // @ts-ignore
252
212
  return resolve();
253
213
  }
254
- if (connectionLocal !== null) {
255
- if (this.options?.disableReconnect || connectionLocal?.isConnected()) {
214
+ if (this.connection !== null) {
215
+ if (this.options?.disableReconnect || this.connection?.isConnected()) {
256
216
  debug('rabbit: connection - is connected');
257
217
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
258
218
  // @ts-ignore
259
- return resolve(connectionLocal);
219
+ return resolve(this.connection);
260
220
  }
261
221
  debug('rabbit: connection - reconnecting');
262
222
  }
263
- if (creatingConnection) {
223
+ if (this.creatingConnection) {
264
224
  debug('rabbit: creating connection emi');
265
- this.em.once(connectionCreatedEventName, resolve);
266
- this.em.once(connectionFailedEventName, reject);
225
+ this.em.once(consts_1.CONNECTION_CREATED_CONST, resolve);
226
+ this.em.once(consts_1.CONNECTION_FAILED_CONST, reject);
267
227
  return;
268
228
  }
269
- connection.creatingConnection = true;
229
+ this.creatingConnection = true;
270
230
  let isResolved = false;
271
231
  // It is import to use it as a function and not as a variable
272
232
  // because of k8s changes the env variables
@@ -276,82 +236,61 @@ class RabbitMq {
276
236
  const password = process.env.RABBITMQ_PASSWORD || 'guest';
277
237
  const host = this.options?.rabbitHost || process.env.RABBITMQ_SERVICE_HOST || 'localhost';
278
238
  debug('rabbit: creating connection', { host, userName, HEARTBEAT });
279
- return [`amqp://${userName}:${password}@${host}/${this.vhost}?heartbeat=${HEARTBEAT}`];
239
+ return [`amqp://${userName}:${password}@${host}/${this.options?.vhost}?heartbeat=${HEARTBEAT}`];
280
240
  };
281
241
  const defaultUrls = findServers();
282
- const newConnection = await (0, amqp_connection_manager_1.connect)(defaultUrls, {
242
+ const connection = await (0, amqp_connection_manager_1.connect)(defaultUrls, {
283
243
  findServers,
284
244
  });
285
- connection.amqpConnection = newConnection;
286
- newConnection.on('error', (err) => {
245
+ this.connection = connection;
246
+ this.connection.on('error', (err) => {
287
247
  logger_1.default.error('rabbit: connection error', { err });
288
248
  if (!isResolved) {
289
249
  isResolved = true;
290
250
  reject(err);
291
- this.em.emit(connectionFailedEventName, err);
251
+ this.em.emit(consts_1.CONNECTION_FAILED_CONST, err);
292
252
  }
293
253
  });
294
- newConnection.on('connectFailed', (err) => {
254
+ this.connection.on('connectFailed', (err) => {
295
255
  this.consumersTags = [];
296
- if (typeof err.url === 'string') {
297
- err.url = this.maskURL(err.url);
298
- }
299
- logger_1.default.error('rabbit: connection connectFailed', { err, advice: 'Check if the vhost exist', vhost: this.vhost });
256
+ logger_1.default.error('rabbit: connection connectFailed', { err, advice: 'Check if the vhost exist', vhost: this.options?.vhost });
300
257
  if (!isResolved) {
301
258
  isResolved = true;
302
259
  reject(err);
303
- this.em.emit(connectionFailedEventName, err);
260
+ this.em.emit(consts_1.CONNECTION_FAILED_CONST, err);
304
261
  }
305
262
  });
306
- newConnection.on('disconnect', ({ err }) => {
307
- this.publishChannel = null;
308
- this.publishChannelSetupPromise = null;
263
+ this.connection.on('disconnect', ({ err }) => {
264
+ // this.channel = null;
309
265
  this.consumersTags = [];
310
- if (this.consumers.length > 0) {
311
- this.needsConsumerReestablishment = true;
312
- }
313
266
  debug('rabbit: connection closed');
314
267
  if (this.options?.disableReconnect) {
315
268
  logger_1.default.error(`${this.DISCONNECT_MSG}${err && ` - ${err}`}`);
316
- connection.blockReconnect = true;
269
+ this.blockReconnect = true;
317
270
  }
318
271
  else {
319
272
  logger_1.default.error(`${this.RECONNECT_MSG}${err && ` - ${err}`}`);
320
273
  }
321
274
  });
322
- newConnection.once('connect', async () => {
275
+ this.connection.once('connect', async () => {
323
276
  debug('rabbit: connection established');
324
- connection.creatingConnection = false;
325
- this.em.emit(connectionCreatedEventName, newConnection);
277
+ this.creatingConnection = false;
278
+ this.em.emit(consts_1.CONNECTION_CREATED_CONST, connection);
326
279
  isResolved = true;
327
- resolve(newConnection);
328
- // Re-establish consumers after reconnection
329
- if (connection === this.consumeConnection && this.needsConsumerReestablishment) {
330
- logger_1.default.info(`rabbit: re-establishing ${this.consumers.length} consumers after reconnection`);
331
- const reestablishPromises = this.consumers.map(async (consumer) => {
332
- try {
333
- await this.consumeFromRabbit(consumer.queue, consumer.callback, consumer.options);
334
- }
335
- catch (e) {
336
- logger_1.default.error(`rabbit: failed to re-establish consumer for queue ${consumer.queue}`, { e });
337
- }
338
- });
339
- await Promise.all(reestablishPromises);
340
- this.needsConsumerReestablishment = false;
341
- }
280
+ resolve(connection);
342
281
  });
343
282
  });
344
283
  }
345
- async getNewChannel({ name = (0, utils_1.rand)().toString(), onClose = null, options = {}, connection, }) {
346
- let localConnection;
284
+ async getNewChannel({ name = (0, utils_1.rand)().toString(), onClose = null, options = {} } = {}) {
285
+ let connection;
347
286
  try {
348
- localConnection = await this.getConnection(connection);
287
+ connection = await this.getConnection();
349
288
  }
350
289
  catch (e) {
351
290
  logger_1.default.error(`rabbit: error on get connection for new channel ${name} `, { e });
352
291
  throw e;
353
292
  }
354
- const channel = localConnection?.createChannel({ ...options });
293
+ const channel = connection.createChannel({ ...options });
355
294
  (0, events_1.once)(channel, 'close').then((args) => {
356
295
  logger_1.default.error(`rabbit: channel ${name} closed`);
357
296
  onClose?.(args);
@@ -366,39 +305,29 @@ class RabbitMq {
366
305
  throw err;
367
306
  }
368
307
  }
369
- async assertChannel({ force = false, connection }) {
370
- if (!this.publishChannelSetupPromise || force) {
308
+ async assertChannel({ force = false } = {}) {
309
+ if (!this.publishChannelSetupPromise) {
371
310
  this.publishChannelSetupPromise = new Promise(async (resolve, reject) => {
372
- if (this.publishChannel && !force && connection.amqpConnection?.isConnected()) {
373
- return resolve(this.publishChannel);
311
+ if (this.channel && !force) {
312
+ return resolve(this.channel);
374
313
  }
375
314
  try {
376
- const channel = await this.getNewChannel({ connection });
315
+ const channel = await this.getNewChannel({});
377
316
  channel.on('error', (err) => {
378
317
  logger_1.default.error('rabbit: channel error', { err });
379
- this.publishChannel = null;
380
- this.publishChannelSetupPromise = null;
381
- });
382
- channel.on('close', () => {
383
- logger_1.default.error('rabbit: channel closed');
384
- this.publishChannel = null;
385
- this.publishChannelSetupPromise = null;
386
318
  });
387
- if (this.publishConnection === connection) {
388
- this.publishChannel = channel;
389
- }
319
+ this.channel = channel;
390
320
  resolve(channel);
391
321
  }
392
322
  catch (e) {
393
- this.publishChannelSetupPromise = null;
394
323
  reject(e);
395
324
  }
396
325
  });
397
326
  }
398
327
  return this.publishChannelSetupPromise;
399
328
  }
400
- async assertExchange(exchangeName, connection) {
401
- const channel = await this.assertChannel({ connection });
329
+ async assertExchange(exchangeName, options) {
330
+ const channel = await this.assertChannel();
402
331
  if (this.exchanges[exchangeName]) {
403
332
  delete this.assertExchangePromises[exchangeName];
404
333
  return this.exchanges[exchangeName];
@@ -410,33 +339,32 @@ class RabbitMq {
410
339
  this.exchanges[exchangeName] = await this.assertExchangePromises[exchangeName];
411
340
  return this.exchanges[exchangeName];
412
341
  }
413
- // TODO: [QUORUM-PHASE-2] Change the implementation to the new one
342
+ // TODO: Change the implementation to the new one
414
343
  async getQueueLength(queue) {
415
344
  RabbitMq.validateName('queue', queue);
416
- const { oldPublishChannel: channel } = this;
345
+ const { oldChannel: channel } = this;
417
346
  if (!channel) {
418
- throw new rabbitError_1.default('channel is not defined');
347
+ throw new Error('channel is not defined');
419
348
  }
420
- debug('rabbit: getting queue length', { queue, connected: this.oldPublishConnection.amqpConnection?.isConnected() });
349
+ debug('rabbit: getting queue length', { queue, connected: this.connection?.isConnected() });
421
350
  return channel?.checkQueue(queue);
422
351
  }
423
- async deleteQueue(queue, connection) {
352
+ async deleteQueue(queue) {
424
353
  RabbitMq.validateName('queue', queue);
425
- const channel = await this.assertChannel({ connection });
354
+ const channel = await this.assertChannel();
426
355
  logger_1.default.info('rabbit: deleting queue', { queue });
427
356
  const deleteQueueRes = await channel.deleteQueue(queue);
428
357
  debug('queue deleted', deleteQueueRes);
429
358
  return deleteQueueRes;
430
359
  }
431
- // TODO: [QUORUM-PHASE-2] Change the implementation to the new one
360
+ // TODO: Change the implementation to the new one
432
361
  async bindQueue(queue, exchange) {
433
- const channel = await this.assertChannelOld({ connection: this.oldPublishConnection });
362
+ const channel = await this.assertChannelOld();
434
363
  await channel.addSetup((setupChannel) => setupChannel.bindQueue(queue, exchange, ''));
435
364
  return channel.bindQueue(queue, exchange, '');
436
365
  }
437
366
  async setupQueue(queueName, options) {
438
367
  let queue;
439
- const connection = this.publishConnection;
440
368
  const localeOptions = {
441
369
  ...options,
442
370
  durable: true,
@@ -447,7 +375,7 @@ class RabbitMq {
447
375
  },
448
376
  };
449
377
  try {
450
- const channel = await this.assertChannel({ connection });
378
+ const channel = await this.assertChannel();
451
379
  debug('assertQueue->channel.addSetup', { queueName });
452
380
  await channel.addSetup(async (setupChannel) => {
453
381
  await setupChannel.assertQueue(queueName, localeOptions);
@@ -459,8 +387,8 @@ class RabbitMq {
459
387
  logger_1.default.error('rabbit: assertQueue error', { queueName, options, error: e });
460
388
  if (!this.options?.dontRetryAssert) {
461
389
  debug('retrying assertQueue', { queueName });
462
- const channel = await this.assertChannel({ force: true, connection });
463
- await this.deleteQueue(queueName, connection);
390
+ const channel = await this.assertChannel({ force: true });
391
+ await this.deleteQueue(queueName);
464
392
  debug('retrying assertQueue->channel.addSetup', { queueName });
465
393
  await channel.addSetup((setupChannel) => setupChannel.assertQueue(queueName, localeOptions));
466
394
  debug('retrying assertQueue->channel.assertQueue', { queueName });
@@ -473,7 +401,7 @@ class RabbitMq {
473
401
  this.queues[queueName] = queue;
474
402
  return queue;
475
403
  }
476
- // TODO: [QUORUM-PHASE-3] Can be deleted after deleting the old consumers and publishers because all the queues are created us quorum queues
404
+ // TODO: Can be deleted after deleting the old consumers
477
405
  static shouldUseQuorum(queueName) {
478
406
  const envQuorumQueuesWhitelist = process.env.QUORUM_QUEUES_WHITELIST;
479
407
  if (envQuorumQueuesWhitelist === '*') {
@@ -510,18 +438,18 @@ class RabbitMq {
510
438
  }
511
439
  // Used by the microservices to consume messages from the queue
512
440
  async consume(queue, callback, options) {
513
- // TODO: [QUORUM-PHASE-3] Use only the implementation of consumeNew and delete consumeNew and consumeOld
514
- if (options?.isQuorumQueue !== false && DISABLE_QUORUM_QUEUES !== 'true') {
441
+ // TODO: USE THE IMPLEMENTATION OF THE NEW CONSUME AND DELETE THE NEW AND OLD
442
+ if (options?.isQuorumQueue !== false) {
515
443
  await this.assertVHost();
516
444
  await this.consumeNew(queue, callback, options);
517
445
  }
518
446
  await this.consumeOld(queue, callback, options);
519
447
  }
520
- // TODO: [QUORUM-PHASE-3] Delete consumeNew we do not use it anymore
448
+ // TODO: DELETE
521
449
  async consumeNew(queue, callback, options) {
522
450
  await this.consumeFromRabbit(queue, callback, options);
523
451
  }
524
- // TODO: [QUORUM-PHASE-3] Delete consumeOld we do not use it anymore
452
+ // TODO: DELETE
525
453
  async consumeOld(queue, callback, options) {
526
454
  await this.consumeFromRabbitOld(queue, callback, options);
527
455
  }
@@ -547,11 +475,11 @@ class RabbitMq {
547
475
  const { limit, deadMessageTtl, useConsumeWithLock, lockTimeout, auditContext, enableRabbitTrace, } = optionsWithDefaults;
548
476
  if (useConsumeWithLock) {
549
477
  if (!this.redisLock) {
550
- throw new rabbitError_1.default('Usage of consumeWithLock requires RedisInstance');
478
+ throw new Error('Usage of consumeWithLock requires RedisInstance');
551
479
  }
552
480
  logger_1.default.info(`rabbit: Consuming with lock from queue ${queue} with lockTimeout: ${lockTimeout}ms`);
553
481
  }
554
- const channel = await this.getNewChannel({ connection: this.consumeConnection });
482
+ const channel = await this.getNewChannel({});
555
483
  return channel.addSetup(async (confirmChannel) => {
556
484
  const q = await this.assertQueue(queue, optionsWithDefaults);
557
485
  await confirmChannel.prefetch(limit, false);
@@ -635,14 +563,10 @@ class RabbitMq {
635
563
  RabbitMq.validateName('exchange', exchange);
636
564
  RabbitMq.validateName('queue', queue);
637
565
  const { limit, deadMessageTtl } = optionsWithDefaults;
638
- // TODO: [QUORUM-PHASE-3] Delete the if statement after all the queues are created as quorum queues
639
- if (options?.isQuorumQueue !== false && DISABLE_QUORUM_QUEUES !== 'true') {
566
+ if (options?.isQuorumQueue !== false) {
640
567
  await this.assertVHost();
641
568
  await this.saveConsumer(queue, callback, options);
642
- const channel = await this.getNewChannel({
643
- name: `consume-exchange-${exchange}-queue-${queue}`,
644
- connection: this.consumeConnection,
645
- });
569
+ const channel = await this.getNewChannel({ name: `consume-exchange-${exchange}-queue-${queue}` });
646
570
  await channel.addSetup(async (c) => {
647
571
  const assertExchange = await (0, utils_1.assertExchangeFanout)(c, exchange);
648
572
  await c.assertQueue(queue);
@@ -654,12 +578,9 @@ class RabbitMq {
654
578
  ]);
655
579
  });
656
580
  }
657
- // TODO: [QUORUM-PHASE-3] Delete the old implementation
581
+ // TODO: DELETE OLD
658
582
  await this.saveConsumerOld(queue, callback, options);
659
- const channelOld = await this.getNewChannelOld({
660
- name: `consume-exchange-${exchange}-queue-${queue}-old`,
661
- connection: this.oldConsumeConnection,
662
- });
583
+ const channelOld = await this.getNewChannelOld({ name: `consume-exchange-${exchange}-queue-${queue}-old` });
663
584
  await channelOld.addSetup(async (c) => {
664
585
  const assertExchange = await (0, utils_1.assertExchangeFanout)(c, exchange);
665
586
  await c.assertQueue(queue);
@@ -672,20 +593,20 @@ class RabbitMq {
672
593
  });
673
594
  }
674
595
  // Used by the microservices to publish messages to the exchange
675
- // TODO: [QUORUM-PHASE-2] Change the implementation to the new one
596
+ // TODO: Change the implementation to the new one
676
597
  async publish(exchange, content, customHeaders) {
677
598
  return (0, utils_1.wrapSetImmediate)(async () => {
678
599
  RabbitMq.validateName('exchange', exchange);
679
- const channel = await this.assertChannelOld({ connection: this.oldPublishConnection });
680
- await this.assertExchangeOld(exchange, this.oldPublishConnection);
600
+ const channel = await this.assertChannelOld();
601
+ await this.assertExchangeOld(exchange);
681
602
  await channel.publish(exchange, '', Buffer.from(JSON.stringify(content)), RabbitMq.getPublishOptions(customHeaders));
682
603
  });
683
604
  }
684
605
  // Used by the microservices to send messages to the queue
685
- // TODO: [QUORUM-PHASE-2] Change the implementation to the new one
606
+ // TODO: Change the implementation to the new one
686
607
  async sendToQueue(queue, content, options, customHeaders) {
687
608
  try {
688
- await this.assertChannelOld({ connection: this.oldPublishConnection });
609
+ await this.assertChannelOld();
689
610
  }
690
611
  catch (e) {
691
612
  logger_1.default.error(`rabbit sendToQueue: failed to send assert channel when sending to queue ${queue}`, { e });
@@ -700,7 +621,7 @@ class RabbitMq {
700
621
  throw e;
701
622
  }
702
623
  try {
703
- const res = await this.oldPublishChannel?.sendToQueue(queue, Buffer.from(JSON.stringify(content)), RabbitMq.getPublishOptions(customHeaders));
624
+ const res = await this.oldChannel?.sendToQueue(queue, Buffer.from(JSON.stringify(content)), RabbitMq.getPublishOptions(customHeaders));
704
625
  debug(`rabbit: sending to queue ${queue}`, { res });
705
626
  return res;
706
627
  }
@@ -710,32 +631,30 @@ class RabbitMq {
710
631
  throw e;
711
632
  }
712
633
  }
713
- // TODO: [QUORUM-PHASE-2] After changing the publish from old to new change from the old to the new implementation
634
+ // TODO: After changing the publish to the new implementation change the from the old to the new
714
635
  async isConnected() {
715
- debug('rabbit: start old is connected');
716
- const oldConsumeConnection = await this.getConnectionOld(this.oldConsumeConnection);
717
- const oldPublishConnection = await this.getConnectionOld(this.oldPublishConnection);
718
- const oldIsConnected = oldConsumeConnection.isConnected() && oldPublishConnection.isConnected();
719
- if (!oldIsConnected) {
720
- logger_1.default.error('rabbit: old isConnected - false');
636
+ const connection = await this.getConnectionOld();
637
+ const isConnected = connection.isConnected();
638
+ if (!isConnected) {
639
+ logger_1.default.error('rabbit: isConnected - false');
721
640
  return false;
722
641
  }
723
- const oldChannel = await this.assertChannelOld({ connection: this.oldPublishConnection });
642
+ const channel = await this.assertChannelOld();
724
643
  try {
725
644
  await Promise.all([
726
- oldChannel.waitForConnect(),
727
- ...this.oldConsumers.map((c) => oldChannel.checkQueue(c.queue)),
645
+ channel.waitForConnect(),
646
+ ...this.oldConsumers.map((c) => channel.checkQueue(c.queue)),
728
647
  ]);
729
648
  }
730
649
  catch (e) {
731
- logger_1.default.error('rabbit: old isConnected - false');
650
+ logger_1.default.error('rabbit: isConnected - false');
732
651
  return false;
733
652
  }
734
- logger_1.default.debug('rabbit: old isConnected - true');
653
+ logger_1.default.info('rabbit: isConnected - true');
735
654
  return true;
736
655
  }
737
656
  async gracefulShutdown(signal) {
738
- // TODO: [QUORUM-PHASE-2] After changing the publish from old to new change from the old to the new implementation
657
+ // TODO: DELETE OLD
739
658
  const tagsNumber = this.consumersTags.length + this.oldConsumersTags.length;
740
659
  logger_1.default.info(`rabbit: [gracefully-shutdown] received ${signal}! canceling #${tagsNumber} tags...`);
741
660
  const cancelTagPromises = this.consumersTags.map(([channel, tag]) => channel.cancel(tag));
@@ -760,11 +679,11 @@ class RabbitMq {
760
679
  const { limit, deadMessageTtl, useConsumeWithLock, lockTimeout, auditContext, enableRabbitTrace, } = optionsWithDefaults;
761
680
  if (useConsumeWithLock) {
762
681
  if (!this.redisLock) {
763
- throw new rabbitError_1.default('Usage of consumeWithLock requires RedisInstance');
682
+ throw new Error('Usage of consumeWithLock requires RedisInstance');
764
683
  }
765
684
  logger_1.default.info(`rabbit: Consuming with lock from queue ${queue} with lockTimeout: ${lockTimeout}ms`);
766
685
  }
767
- const channel = await this.getNewChannelOld({ connection: this.oldConsumeConnection });
686
+ const channel = await this.getNewChannelOld({});
768
687
  return channel.addSetup(async (confirmChannel) => {
769
688
  const q = await this.assertQueueOld(queue, optionsWithDefaults);
770
689
  await confirmChannel.prefetch(limit, false);
@@ -842,20 +761,17 @@ class RabbitMq {
842
761
  }
843
762
  });
844
763
  }
845
- // TODO: [QUORUM-PHASE-3] Delete all the function under this line (getNewChannelOld, getConnectionOld, assertQueueOld, setupQueueOld, saveConsumerOld)
846
- async getNewChannelOld({ name = (0, utils_1.rand)().toString(), onClose = null, options = {}, connection, }) {
847
- let localConnection;
764
+ // TODO: DELETE OLD PROPERTIES UNDER THIS LINE
765
+ async getNewChannelOld({ name = (0, utils_1.rand)().toString(), onClose = null, options = {} } = {}) {
766
+ let connection;
848
767
  try {
849
- localConnection = await this.getConnectionOld(connection);
768
+ connection = await this.getConnectionOld();
850
769
  }
851
770
  catch (e) {
852
771
  logger_1.default.error(`rabbit: error on get connection for new channel ${name} `, { e });
853
772
  throw e;
854
773
  }
855
- if (!localConnection) {
856
- throw new Error(`rabbit: couldnt get connection for new channel ${name}`);
857
- }
858
- const channel = localConnection?.createChannel({ ...options });
774
+ const channel = connection.createChannel({ ...options });
859
775
  (0, events_1.once)(channel, 'close').then((args) => {
860
776
  logger_1.default.error(`rabbit: channel ${name} closed`);
861
777
  onClose?.(args);
@@ -870,31 +786,30 @@ class RabbitMq {
870
786
  throw err;
871
787
  }
872
788
  }
873
- async getConnectionOld(connection) {
789
+ async getConnectionOld() {
874
790
  return new Promise(async (resolve, reject) => {
875
- const { amqpConnection: connectionLocal, creatingConnection, connectionCreatedEventName, connectionFailedEventName, blockReconnect, } = connection;
876
- if (blockReconnect) {
791
+ if (this.oldBlockReconnect) {
877
792
  debug('rabbit: block reconnect');
878
793
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
879
794
  // @ts-ignore
880
795
  return resolve();
881
796
  }
882
- if (connectionLocal !== null) {
883
- if (this.options?.disableReconnect || connectionLocal?.isConnected()) {
797
+ if (this.oldConnection !== null) {
798
+ if (this.options?.disableReconnect || this.oldConnection?.isConnected()) {
884
799
  debug('rabbit: connection - is connected');
885
800
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
886
801
  // @ts-ignore
887
- return resolve(connectionLocal);
802
+ return resolve(this.oldConnection);
888
803
  }
889
804
  debug('rabbit: connection - reconnecting');
890
805
  }
891
- if (creatingConnection) {
806
+ if (this.oldCreatingConnection) {
892
807
  debug('rabbit: creating connection emi');
893
- this.oldEm.once(connectionCreatedEventName, resolve);
894
- this.oldEm.once(connectionFailedEventName, reject);
808
+ this.oldEm.once(consts_1.CONNECTION_CREATED_CONST, resolve);
809
+ this.oldEm.once(consts_1.CONNECTION_FAILED_CONST, reject);
895
810
  return;
896
811
  }
897
- connection.creatingConnection = true;
812
+ this.oldCreatingConnection = true;
898
813
  let isResolved = false;
899
814
  // It is import to use it as a function and not as a variable
900
815
  // because of k8s changes the env variables
@@ -907,66 +822,44 @@ class RabbitMq {
907
822
  return [`amqp://${userName}:${password}@${host}?heartbeat=${HEARTBEAT}`];
908
823
  };
909
824
  const defaultUrls = findServers();
910
- const newConnection = await (0, amqp_connection_manager_1.connect)(defaultUrls, {
825
+ const connection = await (0, amqp_connection_manager_1.connect)(defaultUrls, {
911
826
  findServers,
912
827
  });
913
- connection.amqpConnection = newConnection;
914
- newConnection.on('error', (err) => {
828
+ this.oldConnection = connection;
829
+ this.oldConnection.on('error', (err) => {
915
830
  logger_1.default.error('rabbit: connection error', { err });
916
831
  if (!isResolved) {
917
832
  isResolved = true;
918
833
  reject(err);
919
- this.oldEm.emit(connectionFailedEventName, err);
834
+ this.oldEm.emit(consts_1.CONNECTION_FAILED_CONST, err);
920
835
  }
921
836
  });
922
- newConnection.on('connectFailed', (err) => {
837
+ this.oldConnection.on('connectFailed', (err) => {
923
838
  this.oldConsumersTags = [];
924
- if (typeof err.url === 'string') {
925
- err.url = this.maskURL(err.url);
926
- }
927
839
  logger_1.default.error('rabbit: connection connectFailed', { err });
928
840
  if (!isResolved) {
929
841
  isResolved = true;
930
842
  reject(err);
931
- this.oldEm.emit(connectionFailedEventName, err);
843
+ this.oldEm.emit(consts_1.CONNECTION_FAILED_CONST, err);
932
844
  }
933
845
  });
934
- newConnection.on('disconnect', ({ err }) => {
935
- this.oldPublishChannel = null;
936
- this.oldPublishChannelSetupPromise = null;
846
+ this.oldConnection.on('disconnect', ({ err }) => {
937
847
  this.oldConsumersTags = [];
938
- if (this.oldConsumers.length > 0) {
939
- this.oldNeedsConsumerReestablishment = true;
940
- }
941
848
  debug('rabbit: connection closed');
942
849
  if (this.options?.disableReconnect) {
943
850
  logger_1.default.error(`${this.DISCONNECT_MSG}${err && ` - ${err}`}`);
944
- connection.blockReconnect = true;
851
+ this.oldBlockReconnect = true;
945
852
  }
946
853
  else {
947
854
  logger_1.default.error(`${this.RECONNECT_MSG}${err && ` - ${err}`}`);
948
855
  }
949
856
  });
950
- newConnection.once('connect', async () => {
857
+ this.oldConnection.once('connect', async () => {
951
858
  debug('rabbit: connection established');
952
- connection.creatingConnection = false;
953
- this.oldEm.emit(connectionCreatedEventName, newConnection);
859
+ this.oldCreatingConnection = false;
860
+ this.oldEm.emit(consts_1.CONNECTION_CREATED_CONST, connection);
954
861
  isResolved = true;
955
- resolve(newConnection);
956
- // Re-establish old consumers after reconnection
957
- if (connection === this.oldConsumeConnection && this.oldNeedsConsumerReestablishment) {
958
- logger_1.default.info(`rabbit: re-establishing ${this.oldConsumers.length} old consumers after reconnection`);
959
- const reestablishPromises = this.oldConsumers.map(async (consumer) => {
960
- try {
961
- await this.consumeFromRabbitOld(consumer.queue, consumer.callback, consumer.options);
962
- }
963
- catch (e) {
964
- logger_1.default.error(`rabbit: failed to re-establish old consumer for queue ${consumer.queue}`, { e });
965
- }
966
- });
967
- await Promise.all(reestablishPromises);
968
- this.oldNeedsConsumerReestablishment = false;
969
- }
862
+ resolve(connection);
970
863
  });
971
864
  });
972
865
  }
@@ -995,7 +888,6 @@ class RabbitMq {
995
888
  }
996
889
  async setupQueueOld(queueName, options) {
997
890
  let queue;
998
- const connection = this.oldPublishConnection;
999
891
  const shouldUseQuorum = RabbitMq.shouldUseQuorum(queueName);
1000
892
  const localeOptions = {
1001
893
  ...options,
@@ -1007,7 +899,7 @@ class RabbitMq {
1007
899
  },
1008
900
  };
1009
901
  try {
1010
- const channel = await this.assertChannelOld({ connection });
902
+ const channel = await this.assertChannelOld();
1011
903
  debug('assertQueue->channel.addSetup', { queueName });
1012
904
  await channel.addSetup((setupChannel) => setupChannel.assertQueue(queueName, localeOptions));
1013
905
  debug('assertQueue->channel.assertQueue', { queueName });
@@ -1017,8 +909,8 @@ class RabbitMq {
1017
909
  logger_1.default.error('rabbit: assertQueue error', { queueName, options, error: e });
1018
910
  if (!this.options?.dontRetryAssert) {
1019
911
  debug('retrying assertQueue', { queueName });
1020
- const channel = await this.assertChannelOld({ force: true, connection });
1021
- await this.deleteQueueOld(queueName, connection);
912
+ const channel = await this.assertChannelOld({ force: true });
913
+ await this.deleteQueueOld(queueName);
1022
914
  debug('retrying assertQueue->channel.addSetup', { queueName });
1023
915
  await channel.addSetup((setupChannel) => setupChannel.assertQueue(queueName, localeOptions));
1024
916
  debug('retrying assertQueue->channel.assertQueue', { queueName });
@@ -1031,47 +923,37 @@ class RabbitMq {
1031
923
  this.oldQueues[queueName] = queue;
1032
924
  return queue;
1033
925
  }
1034
- async assertChannelOld({ force = false, connection }) {
1035
- if (!this.oldPublishChannelSetupPromise || force) {
926
+ async assertChannelOld({ force = false } = {}) {
927
+ if (!this.oldPublishChannelSetupPromise) {
1036
928
  this.oldPublishChannelSetupPromise = new Promise(async (resolve, reject) => {
1037
- if (this.oldPublishChannel && !force && connection.amqpConnection?.isConnected()) {
1038
- return resolve(this.oldPublishChannel);
929
+ if (this.oldChannel && !force) {
930
+ return resolve(this.oldChannel);
1039
931
  }
1040
932
  try {
1041
- const channel = await this.getNewChannelOld({ connection });
933
+ const channel = await this.getNewChannelOld({});
1042
934
  channel.on('error', (err) => {
1043
935
  logger_1.default.error('rabbit: channel error', { err });
1044
- this.oldPublishChannel = null;
1045
- this.oldPublishChannelSetupPromise = null;
1046
936
  });
1047
- channel.on('close', () => {
1048
- logger_1.default.error('rabbit: channel closed');
1049
- this.oldPublishChannel = null;
1050
- this.oldPublishChannelSetupPromise = null;
1051
- });
1052
- if (this.oldPublishConnection === connection) {
1053
- this.oldPublishChannel = channel;
1054
- }
937
+ this.oldChannel = channel;
1055
938
  resolve(channel);
1056
939
  }
1057
940
  catch (e) {
1058
- this.oldPublishChannelSetupPromise = null;
1059
941
  reject(e);
1060
942
  }
1061
943
  });
1062
944
  }
1063
945
  return this.oldPublishChannelSetupPromise;
1064
946
  }
1065
- async deleteQueueOld(queue, connection) {
947
+ async deleteQueueOld(queue) {
1066
948
  RabbitMq.validateName('queue', queue);
1067
- const channel = await this.assertChannelOld({ connection });
949
+ const channel = await this.assertChannelOld();
1068
950
  logger_1.default.info('rabbit: deleting queue', { queue });
1069
951
  const deleteQueueRes = await channel.deleteQueue(queue);
1070
952
  debug('queue deleted', deleteQueueRes);
1071
953
  return deleteQueueRes;
1072
954
  }
1073
- async assertExchangeOld(exchangeName, connection) {
1074
- const channel = await this.assertChannelOld({ connection });
955
+ async assertExchangeOld(exchangeName, options) {
956
+ const channel = await this.assertChannelOld();
1075
957
  if (this.oldExchanges[exchangeName]) {
1076
958
  delete this.oldAssertExchangePromises[exchangeName];
1077
959
  return this.oldExchanges[exchangeName];
@@ -1087,4 +969,3 @@ class RabbitMq {
1087
969
  exports.default = RabbitMq;
1088
970
  var celery_1 = require("./lib/celery");
1089
971
  Object.defineProperty(exports, "sendCeleryTaskViaHttp", { enumerable: true, get: function () { return celery_1.sendCeleryTaskViaHttp; } });
1090
- //# sourceMappingURL=index.js.map