@autofleet/rabbit 4.0.2 → 4.1.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.
package/dist/index.js CHANGED
@@ -1,12 +1,24 @@
1
1
  "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
8
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
+ };
2
13
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
14
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
15
  };
16
+ var _RabbitMq_logger;
5
17
  Object.defineProperty(exports, "__esModule", { value: true });
6
18
  exports.sendCeleryTaskViaHttp = void 0;
7
- /* eslint-disable no-empty,consistent-return,no-async-promise-executor,@typescript-eslint/no-unused-vars,no-param-reassign */
8
- const events_1 = require("events");
9
- const util_1 = require("util");
19
+ const node_process_1 = require("node:process");
20
+ const promises_1 = require("node:timers/promises");
21
+ const node_events_1 = require("node:events");
10
22
  const moment_1 = __importDefault(require("moment"));
11
23
  const redis_lock_1 = __importDefault(require("redis-lock"));
12
24
  const amqp_connection_manager_1 = require("amqp-connection-manager");
@@ -19,20 +31,17 @@ const redis_1 = __importDefault(require("./lib/redis"));
19
31
  const utils_1 = require("./lib/utils");
20
32
  const consts_1 = require("./lib/consts");
21
33
  const types_1 = require("./lib/types");
22
- // const debug = nodeDebug('af-rabbitmq')
23
- const debug = logger_1.default.debug.bind(logger_1.default);
24
34
  const PUBLISH_TIMEOUT = 1000 * 10;
25
- // TODO: [QUORUM-PHASE-3] Delete this env var
26
- const { DISABLE_QUORUM_QUEUES_CONSUME, DISABLE_QUORUM_QUEUES_PUBLISH, } = process.env;
35
+ // TODO: [QUORUM-PHASE-3] Delete these env vars
36
+ const { DISABLE_QUORUM_QUEUES_CONSUME, DISABLE_QUORUM_QUEUES_PUBLISH, } = node_process_1.env;
27
37
  const HEARTBEAT = '60';
28
38
  class RabbitMq {
29
39
  static parseMsg(msg) {
30
- let { content } = msg;
31
- content = content.toString();
40
+ let content = msg.content.toString();
32
41
  try {
33
42
  content = JSON.parse(content);
34
43
  }
35
- catch (e) { }
44
+ catch { /* ignore error */ }
36
45
  return {
37
46
  ...msg,
38
47
  content,
@@ -44,10 +53,8 @@ class RabbitMq {
44
53
  }
45
54
  }
46
55
  static getPublishOptions(customHeaders = {}) {
47
- const trace = (0, zehut_1.getCurrentPayload)();
48
- const user = trace?.context?.get(consts_1.USER_OBJECT);
49
- const traceId = trace?.context?.get(consts_1.TRACING_HEADER);
50
- const outbreakTrace = zehut_1.outbreak.getCurrentContext();
56
+ const user = (0, zehut_1.getUser)();
57
+ const traceId = (0, zehut_1.getCurrentPayload)()?.context?.get(consts_1.TRACING_HEADER) || zehut_1.outbreak.getCurrentContext()?.context?.get(consts_1.TRACING_HEADER);
51
58
  return {
52
59
  timestamp: (0, moment_1.default)().unix(),
53
60
  timeout: PUBLISH_TIMEOUT,
@@ -55,18 +62,67 @@ class RabbitMq {
55
62
  creationTimestamp: (0, moment_1.default)().valueOf(),
56
63
  ...customHeaders,
57
64
  [consts_1.USER_TRACING_HEADER]: user?.id,
58
- [consts_1.TRACING_HEADER]: traceId || outbreakTrace?.context?.get(consts_1.TRACING_HEADER),
65
+ [consts_1.TRACING_HEADER]: traceId,
59
66
  },
60
67
  };
61
68
  }
62
69
  constructor(options = {}, redisConfig) {
70
+ this.options = options;
71
+ this.redisConfig = redisConfig;
63
72
  this.DISCONNECT_MSG = 'rabbit: connection disconnect';
64
73
  this.RECONNECT_MSG = 'rabbit: connection disconnect - reconnecting';
74
+ this.publishChannel = null;
75
+ this.publishChannelSetupPromise = null;
76
+ this.publishConnection = {
77
+ amqpConnection: null,
78
+ creatingConnection: false,
79
+ connectionCreatedEventName: 'publishConnectionCreated',
80
+ connectionFailedEventName: 'publishConnectionFailed',
81
+ blockReconnect: false,
82
+ };
83
+ this.consumeConnection = {
84
+ amqpConnection: null,
85
+ creatingConnection: false,
86
+ connectionCreatedEventName: 'consumeConnectionCreated',
87
+ connectionFailedEventName: 'consumeConnectionFailed',
88
+ blockReconnect: false,
89
+ };
90
+ this.em = new node_events_1.EventEmitter();
91
+ this.exchanges = {};
92
+ this.queues = {};
93
+ this.queueSetupPromises = {};
94
+ this.assertExchangePromises = {};
95
+ /** Array of consumers tags used for canceling consumption */
96
+ this.consumersTags = new Map();
65
97
  this.consumersToRegister = [];
66
98
  this.doesVHostExist = false;
67
99
  this.vhost = 'quorum-vhost';
68
100
  this.gracefulShutdownStarted = false;
101
+ // TODO:[QUORUM-PHASE-3] Delete the old properties that we use for the old consumers and publishers
102
+ this.oldPublishChannel = null;
103
+ this.oldPublishChannelSetupPromise = null;
104
+ this.oldPublishConnection = {
105
+ amqpConnection: null,
106
+ creatingConnection: false,
107
+ connectionCreatedEventName: 'oldPublishConnectionCreated',
108
+ connectionFailedEventName: 'oldPublishConnectionFailed',
109
+ blockReconnect: false,
110
+ };
111
+ this.oldConsumeConnection = {
112
+ amqpConnection: null,
113
+ creatingConnection: false,
114
+ connectionCreatedEventName: 'oldConsumeConnectionCreated',
115
+ connectionFailedEventName: 'oldConsumeConnectionFailed',
116
+ blockReconnect: false,
117
+ };
118
+ this.oldEm = new node_events_1.EventEmitter();
119
+ this.oldExchanges = {};
120
+ this.oldQueues = {};
121
+ this.oldQueueSetupPromises = {};
122
+ this.oldAssertExchangePromises = {};
123
+ this.oldConsumersTags = new Map();
69
124
  this.oldConsumersToRegister = [];
125
+ _RabbitMq_logger.set(this, void 0);
70
126
  this.assertVHost = async () => {
71
127
  if (this.doesVHostExist) {
72
128
  return;
@@ -87,11 +143,11 @@ class RabbitMq {
87
143
  });
88
144
  if (response.status === 200) {
89
145
  this.doesVHostExist = true;
90
- logger_1.default.info('Vhost exists', { vhost: this.vhost });
146
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").info('Vhost exists', { vhost: this.vhost });
91
147
  return;
92
148
  }
93
149
  if (response.status !== 404) {
94
- logger_1.default.error('Failed to check vhost', { response });
150
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error('Failed to check vhost', { response });
95
151
  throw new rabbitError_1.default('Failed to check vhost');
96
152
  }
97
153
  const createResponse = await fetch(url, {
@@ -100,23 +156,24 @@ class RabbitMq {
100
156
  body: JSON.stringify({ default_queue_type: 'quorum' }),
101
157
  });
102
158
  if (!createResponse.ok) {
103
- logger_1.default.error('Failed to create vhost', { response: createResponse });
159
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error('Failed to create vhost', { response: createResponse });
104
160
  throw new rabbitError_1.default('Failed to create vhost');
105
161
  }
106
162
  this.doesVHostExist = true;
107
- logger_1.default.info('Vhost created', { vhost: this.vhost });
163
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").info('Vhost created', { vhost: this.vhost });
108
164
  }
109
165
  catch (error) {
110
- logger_1.default.error('Failed to check or create vhost', { error });
166
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error('Failed to check or create vhost', { error });
111
167
  throw error;
112
168
  }
113
169
  };
114
170
  this.shouldConsumeMessageByTimestamp = async (msg) => {
115
171
  if (msg) {
116
- const { properties: { headers } } = msg;
172
+ const { headers } = msg.properties;
117
173
  const timestamp = headers?.creationTimestamp;
118
174
  if (timestamp && headers?.redisTimestampValidationKey && this.redisClient) {
119
- const lastMessageTimestamp = await this.redisClient.getAsync(headers.redisTimestampValidationKey);
175
+ const key = this.getRedisKey(headers.redisTimestampValidationKey);
176
+ const lastMessageTimestamp = await this.redisClient.get(key);
120
177
  return !lastMessageTimestamp || (parseInt(lastMessageTimestamp, 10) <= parseInt(timestamp, 10));
121
178
  }
122
179
  return true;
@@ -125,47 +182,32 @@ class RabbitMq {
125
182
  };
126
183
  this.ack = (channel, msg, shouldUpdateRedisTimestamp = false, releaseLock = null) => async (userMsg) => {
127
184
  if (msg) {
128
- debug('rabbit acking message', { deliveryTag: msg.fields.deliveryTag });
185
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('rabbit acking message', { deliveryTag: msg.fields.deliveryTag });
129
186
  await channel.ack(msg);
130
- const { properties: { headers } } = msg;
187
+ const { headers } = msg.properties;
131
188
  const timestamp = headers?.creationTimestamp;
132
189
  if (shouldUpdateRedisTimestamp && timestamp && headers?.redisTimestampValidationKey && this.redisClient) {
133
190
  const parsedTimestamp = parseInt(timestamp, 10);
134
- await this.redisClient.setAsync(headers.redisTimestampValidationKey, parsedTimestamp, 'EX', 3600);
191
+ const key = this.getRedisKey(headers.redisTimestampValidationKey);
192
+ await this.redisClient.set(key, parsedTimestamp, { EX: 3600 });
135
193
  await this.unlockRedisIfNeeded(releaseLock);
136
194
  }
137
195
  }
138
196
  };
139
197
  this.nack = (channel, queue, options, deadQueueOptions, msg, releaseLock) => async (userMsg, { skipRetry = false, } = {}) => {
140
198
  await this.unlockRedisIfNeeded(releaseLock);
141
- if (channel && msg) {
142
- if (!skipRetry
143
- && (!msg.properties.headers?.[consts_1.RETRY_HEADER]
144
- || parseInt(msg.properties.headers[consts_1.RETRY_HEADER], 10) < options.retries)) {
145
- await this.sendToQueue(queue, RabbitMq.parseMsg(msg).content, options, {
146
- ...msg.properties.headers,
147
- [consts_1.RETRY_HEADER]: msg.properties.headers?.[consts_1.RETRY_HEADER]
148
- ? msg.properties.headers[consts_1.RETRY_HEADER] + 1
149
- : 1,
150
- });
151
- }
152
- else {
153
- const deadQueue = `${queue}-dead`;
154
- await this.sendToQueue(deadQueue, RabbitMq.parseMsg(msg).content, deadQueueOptions, {
155
- ...msg.properties.headers,
156
- [consts_1.RETRY_HEADER]: msg.properties.headers?.[consts_1.RETRY_HEADER]
157
- ? msg.properties.headers[consts_1.RETRY_HEADER] + 1
158
- : 1,
159
- });
160
- }
161
- debug('rabbit nacking message', { deliveryTag: msg.fields.deliveryTag });
162
- await channel.ack(msg);
163
- }
164
- else {
165
- logger_1.default.error('no channel or msg', {
166
- msg,
167
- });
199
+ if (!channel || !msg) {
200
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error('no channel or msg', { msg });
201
+ return;
168
202
  }
203
+ const currentRetryHeader = Number.parseInt(msg.properties.headers?.[consts_1.RETRY_HEADER] || '0', 10) || 0;
204
+ const sendToDeadQueue = skipRetry || currentRetryHeader >= options.retries;
205
+ await this.sendToQueue(`${queue}${sendToDeadQueue ? '-dead' : ''}`, RabbitMq.parseMsg(msg).content, sendToDeadQueue ? deadQueueOptions : options, {
206
+ ...msg.properties.headers,
207
+ [consts_1.RETRY_HEADER]: currentRetryHeader + 1,
208
+ });
209
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('rabbit nacking message', { deliveryTag: msg.fields.deliveryTag });
210
+ await channel.ack(msg);
169
211
  };
170
212
  this.maskURL = (url) => {
171
213
  try {
@@ -178,36 +220,17 @@ class RabbitMq {
178
220
  return url;
179
221
  }
180
222
  };
181
- this.em = new events_1.EventEmitter();
182
- this.publishChannel = null;
183
- 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
- };
198
- this.creatingConnection = false;
199
- this.exchanges = {};
200
- this.queues = {};
201
- this.queueSetupPromises = {};
202
- this.assertExchangePromises = {};
203
- this.consumersToRegister = [];
204
- this.options = options;
205
- this.redisClient = redisConfig && (0, redis_1.default)(redisConfig);
206
- if (this.redisClient) {
207
- this.redisLock = (0, util_1.promisify)((0, redis_lock_1.default)(this.redisClient));
223
+ __classPrivateFieldSet(this, _RabbitMq_logger, options?.logger || logger_1.default, "f");
224
+ if (redisConfig) {
225
+ this.redisClient = (0, redis_1.default)(redisConfig).on('error', (err) => {
226
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error('rabbit: Redis error', { err, redisConfig });
227
+ });
228
+ this.redisClient.connect().catch((err) => {
229
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error('rabbit: Failed to connect to Redis', { err, redisConfig });
230
+ });
231
+ this.redisLock = (0, redis_lock_1.default)(this.redisClient);
208
232
  }
209
- this.consumersTags = new Map();
210
- logger_1.default.info(`rabbit: [gracefully-shutdown] adding gracefully shutdown for process.pid ${process.pid}`);
233
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").info(`rabbit: [gracefully-shutdown] adding gracefully shutdown for process.pid ${process.pid}`);
211
234
  if (!this.options?.dontGracefulShutdown) {
212
235
  process.on('SIGTERM', async () => {
213
236
  await this.gracefulShutdown('SIGTERM');
@@ -216,112 +239,87 @@ class RabbitMq {
216
239
  await this.gracefulShutdown('SIGINT');
217
240
  });
218
241
  }
219
- // TODO: [QUORUM-PHASE-3] Delete the old properties that we use for the old consumers and publishers
220
- this.oldEm = new events_1.EventEmitter();
221
- this.oldPublishChannel = null;
222
- 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
- };
237
- this.oldCreatingConnection = false;
238
- this.oldExchanges = {};
239
- this.oldQueues = {};
240
- this.oldQueueSetupPromises = {};
241
- this.oldAssertExchangePromises = {};
242
- this.oldConsumersToRegister = [];
243
- this.oldConsumersTags = new Map();
242
+ }
243
+ getRedisKey(key) {
244
+ return `${this.redisConfig?.prefix || ''}${key}`;
244
245
  }
245
246
  async getConnection(connection) {
246
- return new Promise(async (resolve, reject) => {
247
- const { amqpConnection: connectionLocal, creatingConnection, connectionCreatedEventName, connectionFailedEventName, blockReconnect, } = connection;
248
- if (blockReconnect) {
249
- debug('rabbit: block reconnect');
250
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
251
- // @ts-ignore
252
- return resolve();
247
+ const { amqpConnection: connectionLocal, creatingConnection, connectionCreatedEventName, connectionFailedEventName, blockReconnect, } = connection;
248
+ if (blockReconnect) {
249
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('rabbit: block reconnect');
250
+ // @ts-expect-error we are returning undefined while the function clearly expects a connection.
251
+ return undefined;
252
+ }
253
+ if (connectionLocal !== null) {
254
+ if (this.options?.disableReconnect || connectionLocal?.isConnected()) {
255
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('rabbit: connection - is connected');
256
+ return connectionLocal;
253
257
  }
254
- if (connectionLocal !== null) {
255
- if (this.options?.disableReconnect || connectionLocal?.isConnected()) {
256
- debug('rabbit: connection - is connected');
257
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
258
- // @ts-ignore
259
- return resolve(connectionLocal);
260
- }
261
- debug('rabbit: connection - reconnecting');
258
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('rabbit: connection - reconnecting');
259
+ }
260
+ if (creatingConnection) {
261
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('rabbit: creating connection emi');
262
+ const [event, value] = await Promise.race([connectionCreatedEventName, connectionFailedEventName].map((e) => (0, node_events_1.once)(this.em, e).then(([result]) => [e, result])));
263
+ if (event === connectionCreatedEventName) {
264
+ return value;
262
265
  }
263
- if (creatingConnection) {
264
- debug('rabbit: creating connection emi');
265
- this.em.once(connectionCreatedEventName, resolve);
266
- this.em.once(connectionFailedEventName, reject);
267
- return;
266
+ throw value;
267
+ }
268
+ connection.creatingConnection = true;
269
+ let isResolved = false;
270
+ // It is import to use it as a function and not as a variable
271
+ // because of k8s changes the env variables
272
+ // and we want to use the new values
273
+ const findServers = () => {
274
+ const userName = process.env.RABBITMQ_USERNAME || 'guest';
275
+ const password = process.env.RABBITMQ_PASSWORD || 'guest';
276
+ const host = this.options?.rabbitHost || process.env.RABBITMQ_SERVICE_HOST || 'localhost';
277
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('rabbit: creating connection', { host, userName, HEARTBEAT });
278
+ return [`amqp://${userName}:${password}@${host}/${this.vhost}?heartbeat=${HEARTBEAT}`];
279
+ };
280
+ const defaultUrls = findServers();
281
+ const newConnection = (0, amqp_connection_manager_1.connect)(defaultUrls, { findServers });
282
+ connection.amqpConnection = newConnection;
283
+ const { promise, reject, resolve } = (0, utils_1.createDeferredPromise)();
284
+ newConnection.on('error', (err) => {
285
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error('rabbit: connection error', { err });
286
+ if (!isResolved) {
287
+ isResolved = true;
288
+ reject(err);
289
+ this.em.emit(connectionFailedEventName, err);
268
290
  }
269
- connection.creatingConnection = true;
270
- let isResolved = false;
271
- // It is import to use it as a function and not as a variable
272
- // because of k8s changes the env variables
273
- // and we want to use the new values
274
- const findServers = () => {
275
- const userName = process.env.RABBITMQ_USERNAME || 'guest';
276
- const password = process.env.RABBITMQ_PASSWORD || 'guest';
277
- const host = this.options?.rabbitHost || process.env.RABBITMQ_SERVICE_HOST || 'localhost';
278
- debug('rabbit: creating connection', { host, userName, HEARTBEAT });
279
- return [`amqp://${userName}:${password}@${host}/${this.vhost}?heartbeat=${HEARTBEAT}`];
280
- };
281
- const defaultUrls = findServers();
282
- const newConnection = await (0, amqp_connection_manager_1.connect)(defaultUrls, {
283
- findServers,
284
- });
285
- connection.amqpConnection = newConnection;
286
- newConnection.on('error', (err) => {
287
- logger_1.default.error('rabbit: connection error', { err });
288
- if (!isResolved) {
289
- isResolved = true;
290
- reject(err);
291
- this.em.emit(connectionFailedEventName, err);
292
- }
293
- });
294
- newConnection.on('connectFailed', (err) => {
295
- this.consumersTags.clear();
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 });
300
- if (!isResolved) {
301
- isResolved = true;
302
- reject(err);
303
- this.em.emit(connectionFailedEventName, err);
304
- }
305
- });
306
- newConnection.on('disconnect', ({ err }) => {
307
- this.consumersTags.clear();
308
- debug('rabbit: connection closed');
309
- if (this.options?.disableReconnect) {
310
- logger_1.default.error(`${this.DISCONNECT_MSG}${err && ` - ${err}`}`);
311
- connection.blockReconnect = true;
312
- }
313
- else {
314
- logger_1.default.error(`${this.RECONNECT_MSG}${err && ` - ${err}`}`);
315
- }
316
- });
317
- newConnection.once('connect', async () => {
318
- debug('rabbit: connection established');
319
- connection.creatingConnection = false;
320
- this.em.emit(connectionCreatedEventName, newConnection);
291
+ });
292
+ newConnection.on('connectFailed', (err) => {
293
+ this.consumersTags.clear();
294
+ if (typeof err.url === 'string') {
295
+ err.url = this.maskURL(err.url);
296
+ }
297
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error('rabbit: connection connectFailed', { err, advice: 'Check if the vhost exist', vhost: this.vhost });
298
+ if (!isResolved) {
321
299
  isResolved = true;
322
- resolve(newConnection);
323
- });
300
+ reject(err);
301
+ this.em.emit(connectionFailedEventName, err);
302
+ }
303
+ });
304
+ newConnection.on('disconnect', ({ err }) => {
305
+ this.consumersTags.clear();
306
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('rabbit: connection closed');
307
+ if (this.options?.disableReconnect) {
308
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error(`${this.DISCONNECT_MSG}${err && ` - ${err}`}`);
309
+ connection.blockReconnect = true;
310
+ }
311
+ else {
312
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error(`${this.RECONNECT_MSG}${err && ` - ${err}`}`);
313
+ }
314
+ });
315
+ newConnection.once('connect', async () => {
316
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('rabbit: connection established');
317
+ connection.creatingConnection = false;
318
+ this.em.emit(connectionCreatedEventName, newConnection);
319
+ isResolved = true;
320
+ resolve(newConnection);
324
321
  });
322
+ return promise;
325
323
  }
326
324
  async getNewChannel({ name = (0, utils_1.rand)().toString(), onClose = null, options = {}, connection, }) {
327
325
  let localConnection;
@@ -329,46 +327,48 @@ class RabbitMq {
329
327
  localConnection = await this.getConnection(connection);
330
328
  }
331
329
  catch (e) {
332
- logger_1.default.error(`rabbit: error on get connection for new channel ${name} `, { e });
330
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error(`rabbit: error on get connection for new channel ${name} `, { e });
333
331
  throw e;
334
332
  }
335
333
  const channel = localConnection?.createChannel({ ...options });
336
- (0, events_1.once)(channel, 'close').then((args) => {
337
- logger_1.default.error(`rabbit: channel ${name} closed`);
334
+ (0, node_events_1.once)(channel, 'close').then((args) => {
335
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error(`rabbit: channel ${name} closed`);
338
336
  onClose?.(args);
339
337
  });
340
338
  try {
341
- await (0, events_1.once)(channel, 'connect');
342
- debug(`rabbit: channel ${name} CONNECTED`);
339
+ await (0, node_events_1.once)(channel, 'connect');
340
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug(`rabbit: channel ${name} CONNECTED`);
343
341
  return channel;
344
342
  }
345
343
  catch (err) {
346
- logger_1.default.error(`rabbit: channel error ${name} error`, { err });
344
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error(`rabbit: channel error ${name} error`, { err });
347
345
  throw err;
348
346
  }
349
347
  }
350
348
  async assertChannel({ force = false, connection }) {
351
- if (!this.publishChannelSetupPromise) {
352
- this.publishChannelSetupPromise = new Promise(async (resolve, reject) => {
353
- if (this.publishChannel && !force) {
354
- return resolve(this.publishChannel);
355
- }
356
- try {
357
- const channel = await this.getNewChannel({ connection });
358
- channel.on('error', (err) => {
359
- logger_1.default.error('rabbit: channel error', { err });
360
- });
361
- if (this.publishConnection === connection) {
362
- this.publishChannel = channel;
363
- }
364
- resolve(channel);
365
- }
366
- catch (e) {
367
- reject(e);
368
- }
349
+ if (this.publishChannelSetupPromise) {
350
+ return this.publishChannelSetupPromise;
351
+ }
352
+ const { promise, resolve, reject } = (0, utils_1.createDeferredPromise)();
353
+ this.publishChannelSetupPromise = promise;
354
+ if (this.publishChannel && !force) {
355
+ resolve(this.publishChannel);
356
+ return promise;
357
+ }
358
+ try {
359
+ const channel = await this.getNewChannel({ connection });
360
+ channel.on('error', (err) => {
361
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error('rabbit: channel error', { err });
369
362
  });
363
+ if (this.publishConnection === connection) {
364
+ this.publishChannel = channel;
365
+ }
366
+ resolve(channel);
367
+ }
368
+ catch (e) {
369
+ reject(e);
370
370
  }
371
- return this.publishChannelSetupPromise;
371
+ return promise;
372
372
  }
373
373
  async assertExchange(exchangeName, connection) {
374
374
  const channel = await this.assertChannel({ connection });
@@ -389,15 +389,15 @@ class RabbitMq {
389
389
  if (!channel) {
390
390
  throw new rabbitError_1.default('channel is not defined');
391
391
  }
392
- debug('rabbit: getting queue length', { queue, connected: this.publishConnection.amqpConnection?.isConnected() });
392
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('rabbit: getting queue length', { queue, connected: this.publishConnection.amqpConnection?.isConnected() });
393
393
  return channel?.checkQueue(queue);
394
394
  }
395
395
  async deleteQueue(queue, connection) {
396
396
  RabbitMq.validateName('queue', queue);
397
397
  const channel = await this.assertChannel({ connection });
398
- logger_1.default.info('rabbit: deleting queue', { queue });
398
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").info('rabbit: deleting queue', { queue });
399
399
  const deleteQueueRes = await channel.deleteQueue(queue);
400
- debug('queue deleted', deleteQueueRes);
400
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('queue deleted', deleteQueueRes);
401
401
  return deleteQueueRes;
402
402
  }
403
403
  async bindQueue(queue, exchange) {
@@ -419,22 +419,22 @@ class RabbitMq {
419
419
  };
420
420
  try {
421
421
  const channel = await this.assertChannel({ connection });
422
- debug('assertQueue->channel.addSetup', { queueName });
422
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('assertQueue->channel.addSetup', { queueName });
423
423
  await channel.addSetup(async (setupChannel) => {
424
424
  await setupChannel.assertQueue(queueName, localeOptions);
425
425
  });
426
- debug('assertQueue->channel.assertQueue', { queueName });
426
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('assertQueue->channel.assertQueue', { queueName });
427
427
  queue = await channel.assertQueue(queueName, localeOptions);
428
428
  }
429
429
  catch (e) {
430
- logger_1.default.error('rabbit: assertQueue error', { queueName, options, error: e });
430
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error('rabbit: assertQueue error', { queueName, options, error: e });
431
431
  if (!this.options?.dontRetryAssert) {
432
- debug('retrying assertQueue', { queueName });
432
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('retrying assertQueue', { queueName });
433
433
  const channel = await this.assertChannel({ force: true, connection });
434
434
  await this.deleteQueue(queueName, connection);
435
- debug('retrying assertQueue->channel.addSetup', { queueName });
435
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('retrying assertQueue->channel.addSetup', { queueName });
436
436
  await channel.addSetup((setupChannel) => setupChannel.assertQueue(queueName, localeOptions));
437
- debug('retrying assertQueue->channel.assertQueue', { queueName });
437
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('retrying assertQueue->channel.assertQueue', { queueName });
438
438
  queue = await channel.assertQueue(queueName, localeOptions);
439
439
  }
440
440
  else {
@@ -457,21 +457,19 @@ class RabbitMq {
457
457
  return false;
458
458
  }
459
459
  async assertQueue(queueName, options) {
460
+ var _a;
460
461
  RabbitMq.validateName('queue', queueName);
461
462
  if (this.queues[queueName]) {
462
463
  delete this.queueSetupPromises[queueName];
463
464
  return this.queues[queueName];
464
465
  }
465
- if (this.queueSetupPromises[queueName]) {
466
- return this.queueSetupPromises[queueName];
467
- }
468
- this.queueSetupPromises[queueName] = this.setupQueue(queueName, options);
466
+ (_a = this.queueSetupPromises)[queueName] || (_a[queueName] = this.setupQueue(queueName, options));
469
467
  return this.queueSetupPromises[queueName];
470
468
  }
471
469
  saveConsumer(queue, callback, options) {
472
470
  const isConsumerExist = this.consumersToRegister.some((consumer) => consumer.queue === queue);
473
471
  if (!isConsumerExist) {
474
- logger_1.default.info(`rabbit: consumer: ${queue} saved in consumer array`);
472
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").info(`rabbit: consumer: ${queue} saved in consumer array`);
475
473
  this.consumersToRegister.push({
476
474
  queue,
477
475
  callback,
@@ -522,19 +520,17 @@ class RabbitMq {
522
520
  if (!this.redisLock) {
523
521
  throw new rabbitError_1.default('Usage of consumeWithLock requires RedisInstance');
524
522
  }
525
- logger_1.default.info(`rabbit: Consuming with lock from queue ${queue} with lockTimeout: ${lockTimeout}ms`);
523
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").info(`rabbit: Consuming with lock from queue ${queue} with lockTimeout: ${lockTimeout}ms`);
526
524
  }
527
525
  const channel = await this.getNewChannel({ connection: this.consumeConnection });
528
526
  return channel.addSetup(async (confirmChannel) => {
529
- const q = await this.assertQueue(queue, optionsWithDefaults);
527
+ await this.assertQueue(queue, optionsWithDefaults);
530
528
  await confirmChannel.prefetch(limit, false);
531
529
  const { consumerTag } = await confirmChannel.consume(queue, async (msg) => {
532
530
  if (!msg) {
533
531
  return null;
534
532
  }
535
- const traceId = msg.properties.headers[consts_1.TRACING_HEADER];
536
- const userId = msg.properties.headers[consts_1.USER_TRACING_HEADER];
537
- const automationId = msg.properties.headers[consts_1.AUTOMATION_ID_HEADER];
533
+ const { [consts_1.TRACING_HEADER]: traceId, [consts_1.USER_TRACING_HEADER]: userId, [consts_1.AUTOMATION_ID_HEADER]: automationId } = msg.properties.headers ?? {};
538
534
  const parsedMessage = RabbitMq.parseMsg(msg);
539
535
  const releaseLock = await this.lockRedisIfNeeded(parsedMessage, optionsWithDefaults);
540
536
  const trace = (0, zehut_1.newTrace)(zehut_1.traceTypes.RABBIT);
@@ -550,7 +546,7 @@ class RabbitMq {
550
546
  ]);
551
547
  }
552
548
  catch (e) {
553
- logger_1.default.error('rabbit: failed to setRabbitTrace', { userId, e });
549
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error('rabbit: failed to setRabbitTrace', { userId, e });
554
550
  return this.nack(confirmChannel, queue, optionsWithDefaults, { messageTtl: deadMessageTtl }, msg, releaseLock)(msg);
555
551
  }
556
552
  }
@@ -576,28 +572,28 @@ class RabbitMq {
576
572
  return;
577
573
  }
578
574
  messageAcked = true;
579
- return this.ack(confirmChannel, msg, true, releaseLock)(msg);
575
+ await this.ack(confirmChannel, msg, true, releaseLock)(msg);
580
576
  };
581
577
  const localNack = async (_, nackOptions = {}) => {
582
578
  if (messageAcked) {
583
579
  return;
584
580
  }
585
- debug('rabbit localNack', { messageAcked, uniqueId, deliveryTag: msg.fields.deliveryTag });
581
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('rabbit localNack', { messageAcked, uniqueId, deliveryTag: msg.fields.deliveryTag });
586
582
  messageAcked = true;
587
- return this.nack(confirmChannel, queue, optionsWithDefaults, { messageTtl: deadMessageTtl }, msg, releaseLock)(msg, nackOptions);
583
+ await this.nack(confirmChannel, queue, optionsWithDefaults, { messageTtl: deadMessageTtl }, msg, releaseLock)(msg, nackOptions);
588
584
  };
589
585
  try {
590
- await callback(parsedMessage, localAck, localNack);
586
+ return await callback(parsedMessage, localAck, localNack);
591
587
  }
592
588
  catch (e) {
593
- await localNack(msg);
589
+ return localNack(msg);
594
590
  }
595
591
  }, types_1.CONSUMER_DEFAULT_OPTIONS);
596
592
  if (!consumerTag) {
597
- logger_1.default.error(`rabbit: failed to consume from queue ${queue}`);
593
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error(`rabbit: failed to consume from queue ${queue}`);
598
594
  }
599
595
  else {
600
- logger_1.default.info(`rabbit: adding tag ${consumerTag} to the array.`);
596
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").info(`rabbit: adding tag ${consumerTag} to the array.`);
601
597
  this.consumersTags.set(queue, { channel: confirmChannel, consumerTag });
602
598
  }
603
599
  });
@@ -607,7 +603,7 @@ class RabbitMq {
607
603
  const optionsWithDefaults = { ...consts_1.DEFAULT_OPTIONS, ...options };
608
604
  RabbitMq.validateName('exchange', exchange);
609
605
  RabbitMq.validateName('queue', queue);
610
- const { limit, deadMessageTtl } = optionsWithDefaults;
606
+ const { limit } = optionsWithDefaults;
611
607
  // TODO: [QUORUM-PHASE-3] Delete the if statement after all the queues are created as quorum queues
612
608
  if (options?.isQuorumQueue !== false && DISABLE_QUORUM_QUEUES_CONSUME !== 'true') {
613
609
  await this.saveConsumer(queue, callback, options);
@@ -648,22 +644,20 @@ class RabbitMq {
648
644
  // Used by the microservices to publish messages to the exchange
649
645
  // TODO: [QUORUM-PHASE-3] isQuorumQueue flag is not needed anymore because all the queues are created as quorum queues
650
646
  async publish(exchange, content, customHeaders, isQuorumQueue = true) {
647
+ await (0, promises_1.setImmediate)();
651
648
  if (isQuorumQueue && DISABLE_QUORUM_QUEUES_PUBLISH !== 'true') {
652
- return (0, utils_1.wrapSetImmediate)(async () => {
653
- await this.assertVHost();
654
- RabbitMq.validateName('exchange', exchange);
655
- const channel = await this.assertChannel({ connection: this.publishConnection });
656
- await this.assertExchange(exchange, this.publishConnection);
657
- await channel.publish(exchange, '', Buffer.from(JSON.stringify(content)), RabbitMq.getPublishOptions(customHeaders));
658
- });
659
- }
660
- // TODO: [QUORUM-PHASE-3] Delete the old implementation
661
- return (0, utils_1.wrapSetImmediate)(async () => {
649
+ await this.assertVHost();
662
650
  RabbitMq.validateName('exchange', exchange);
663
- const channel = await this.assertChannelOld({ connection: this.oldPublishConnection });
664
- await this.assertExchangeOld(exchange, this.oldPublishConnection);
651
+ const channel = await this.assertChannel({ connection: this.publishConnection });
652
+ await this.assertExchange(exchange, this.publishConnection);
665
653
  await channel.publish(exchange, '', Buffer.from(JSON.stringify(content)), RabbitMq.getPublishOptions(customHeaders));
666
- });
654
+ return;
655
+ }
656
+ // TODO: [QUORUM-PHASE-3] Delete the old implementation
657
+ RabbitMq.validateName('exchange', exchange);
658
+ const channel = await this.assertChannelOld({ connection: this.oldPublishConnection });
659
+ await this.assertExchangeOld(exchange, this.oldPublishConnection);
660
+ await channel.publish(exchange, '', Buffer.from(JSON.stringify(content)), RabbitMq.getPublishOptions(customHeaders));
667
661
  }
668
662
  // Used by the microservices to send messages to the queue
669
663
  // TODO: [QUORUM-PHASE-3] isQuorumQueue flag is not needed anymore because all the queues are created as quorum queues
@@ -674,7 +668,7 @@ class RabbitMq {
674
668
  await this.assertChannel({ connection: this.publishConnection });
675
669
  }
676
670
  catch (e) {
677
- logger_1.default.error(`rabbit sendToQueue: failed to send assert channel when sending to queue ${queue}`, { e });
671
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error(`rabbit sendToQueue: failed to send assert channel when sending to queue ${queue}`, { e });
678
672
  throw e;
679
673
  }
680
674
  try {
@@ -682,17 +676,17 @@ class RabbitMq {
682
676
  await this.assertQueue(queue, options);
683
677
  }
684
678
  catch (e) {
685
- logger_1.default.error(`rabbit sendToQueue: failed to assert queue ${queue}`, { e });
679
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error(`rabbit sendToQueue: failed to assert queue ${queue}`, { e });
686
680
  throw e;
687
681
  }
688
682
  try {
689
683
  const res = await this.publishChannel?.sendToQueue(queue, Buffer.from(JSON.stringify(content)), RabbitMq.getPublishOptions(customHeaders));
690
- debug(`rabbit: sending to queue ${queue}`, { res });
684
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug(`rabbit: sending to queue ${queue}`, { res });
691
685
  return res;
692
686
  }
693
687
  catch (e) {
694
688
  const isConnected = await this.isConnected();
695
- logger_1.default.error(`rabbit sendToQueue: failed to send to queue ${queue}, isConnected: ${isConnected}`, { e });
689
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error(`rabbit sendToQueue: failed to send to queue ${queue}, isConnected: ${isConnected}`, { e });
696
690
  throw e;
697
691
  }
698
692
  }
@@ -701,7 +695,7 @@ class RabbitMq {
701
695
  await this.assertChannelOld({ connection: this.oldPublishConnection });
702
696
  }
703
697
  catch (e) {
704
- logger_1.default.error(`rabbit sendToQueue: failed to send assert channel when sending to queue ${queue}`, { e });
698
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error(`rabbit sendToQueue: failed to send assert channel when sending to queue ${queue}`, { e });
705
699
  throw e;
706
700
  }
707
701
  try {
@@ -709,17 +703,17 @@ class RabbitMq {
709
703
  await this.assertQueueOld(queue, options);
710
704
  }
711
705
  catch (e) {
712
- logger_1.default.error(`rabbit sendToQueue: failed to assert queue ${queue}`, { e });
706
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error(`rabbit sendToQueue: failed to assert queue ${queue}`, { e });
713
707
  throw e;
714
708
  }
715
709
  try {
716
710
  const res = await this.oldPublishChannel?.sendToQueue(queue, Buffer.from(JSON.stringify(content)), RabbitMq.getPublishOptions(customHeaders));
717
- debug(`rabbit: sending to queue ${queue}`, { res });
711
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug(`rabbit: sending to queue ${queue}`, { res });
718
712
  return res;
719
713
  }
720
714
  catch (e) {
721
715
  const isConnected = await this.isConnectedOld();
722
- logger_1.default.error(`rabbit sendToQueue: failed to send to queue ${queue}, isConnected: ${isConnected}`, { e });
716
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error(`rabbit sendToQueue: failed to send to queue ${queue}, isConnected: ${isConnected}`, { e });
723
717
  throw e;
724
718
  }
725
719
  }
@@ -729,24 +723,21 @@ class RabbitMq {
729
723
  // TODO:[QUORUM-PHASE-3] Remove the condition
730
724
  if (!this.gracefulShutdownStarted) {
731
725
  if (DISABLE_QUORUM_QUEUES_CONSUME !== 'true' || DISABLE_QUORUM_QUEUES_PUBLISH !== 'true') {
732
- debug('rabbit: start is connected');
726
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('rabbit: start is connected');
733
727
  const [consumeConnection, publishConnection] = await Promise.all([
734
728
  this.getConnection(this.consumeConnection),
735
729
  this.getConnection(this.publishConnection),
736
730
  ]);
737
731
  isConnected = consumeConnection.isConnected() && publishConnection.isConnected();
738
732
  if (!isConnected) {
739
- logger_1.default.error('rabbit: isConnected - false');
733
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error('rabbit: isConnected - false');
740
734
  return false;
741
735
  }
742
736
  try {
743
- const unRegisteredConsumers = this.consumersToRegister.filter((c) => {
744
- const doesConsumerExist = this.consumersTags.get(c.queue);
745
- return !doesConsumerExist;
746
- });
737
+ const unRegisteredConsumers = this.consumersToRegister.filter((c) => !this.consumersTags.get(c.queue));
747
738
  if (unRegisteredConsumers.length > 0) {
748
739
  const queueNames = unRegisteredConsumers.map((c) => c.queue);
749
- logger_1.default.error('rabbit: found unregistered consumers for queues', {
740
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error('rabbit: found unregistered consumers for queues', {
750
741
  count: queueNames.length,
751
742
  queues: queueNames,
752
743
  });
@@ -757,33 +748,33 @@ class RabbitMq {
757
748
  await Promise.all(this.consumersToRegister.map((c) => channel.checkQueue(c.queue)));
758
749
  }
759
750
  catch (e) {
760
- logger_1.default.error('rabbit: isConnected - false', { msg: e.message });
751
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error('rabbit: isConnected - false', { msg: e.message });
761
752
  return false;
762
753
  }
763
754
  }
764
755
  // TODO:[QUORUM-PHASE-3] Delete the old is connected and adjust the return value to return true
765
756
  isConnected = await this.isConnectedOld();
766
757
  }
767
- logger_1.default.debug(`rabbit: isConnected - ${isConnected}`);
758
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug(`rabbit: isConnected - ${isConnected}`);
768
759
  return isConnected;
769
760
  }
770
761
  async gracefulShutdown(signal) {
771
762
  // TODO: [QUORUM-PHASE-3] Delete the old implementation they are not needed anymore
772
763
  this.gracefulShutdownStarted = true;
773
764
  const tagsNumber = this.consumersTags.size + this.oldConsumersTags.size;
774
- logger_1.default.info(`rabbit: [gracefully-shutdown] received ${signal}! canceling #${tagsNumber} tags...`);
775
- const cancelTagPromises = [...this.consumersTags].map(([_, { channel, consumerTag }]) => channel.cancel(consumerTag));
776
- const cancelTagPromisesOld = [...this.oldConsumersTags].map(([_, { channel, consumerTag }]) => channel.cancel(consumerTag));
765
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").info(`rabbit: [gracefully-shutdown] received ${signal}! canceling #${tagsNumber} tags...`);
766
+ const cancelTagPromises = [...this.consumersTags].map(([, { channel, consumerTag }]) => channel.cancel(consumerTag));
767
+ const cancelTagPromisesOld = [...this.oldConsumersTags].map(([, { channel, consumerTag }]) => channel.cancel(consumerTag));
777
768
  // Clean the array to avoid race
778
769
  this.consumersTags.clear();
779
770
  this.oldConsumersTags.clear();
780
771
  const results = await Promise.allSettled([...cancelTagPromises, ...cancelTagPromisesOld]);
781
772
  const rejected = results.filter((p) => p.status === 'rejected');
782
773
  if (rejected.length > 0) {
783
- logger_1.default.warn(`rabbit: [gracefully-shutdown] #${rejected.length}/${tagsNumber} tags failed to cancel: ${rejected}`);
774
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").warn(`rabbit: [gracefully-shutdown] #${rejected.length}/${tagsNumber} tags failed to cancel: ${rejected}`);
784
775
  }
785
776
  else {
786
- logger_1.default.info('rabbit: [gracefully-shutdown] all tags successfully canceled.');
777
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").info('rabbit: [gracefully-shutdown] all tags successfully canceled.');
787
778
  }
788
779
  }
789
780
  async consumeFromRabbitOld(queue, callback, options) {
@@ -795,19 +786,17 @@ class RabbitMq {
795
786
  if (!this.redisLock) {
796
787
  throw new rabbitError_1.default('Usage of consumeWithLock requires RedisInstance');
797
788
  }
798
- logger_1.default.info(`rabbit: Consuming with lock from queue ${queue} with lockTimeout: ${lockTimeout}ms`);
789
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").info(`rabbit: Consuming with lock from queue ${queue} with lockTimeout: ${lockTimeout}ms`);
799
790
  }
800
791
  const channel = await this.getNewChannelOld({ connection: this.oldConsumeConnection });
801
792
  return channel.addSetup(async (confirmChannel) => {
802
- const q = await this.assertQueueOld(queue, optionsWithDefaults);
793
+ await this.assertQueueOld(queue, optionsWithDefaults);
803
794
  await confirmChannel.prefetch(limit, false);
804
795
  const { consumerTag } = await confirmChannel.consume(queue, async (msg) => {
805
796
  if (!msg) {
806
797
  return null;
807
798
  }
808
- const traceId = msg.properties.headers[consts_1.TRACING_HEADER];
809
- const userId = msg.properties.headers[consts_1.USER_TRACING_HEADER];
810
- const automationId = msg.properties.headers[consts_1.AUTOMATION_ID_HEADER];
799
+ const { [consts_1.TRACING_HEADER]: traceId, [consts_1.USER_TRACING_HEADER]: userId, [consts_1.AUTOMATION_ID_HEADER]: automationId } = msg.properties.headers ?? {};
811
800
  const parsedMessage = RabbitMq.parseMsg(msg);
812
801
  const releaseLock = await this.lockRedisIfNeeded(parsedMessage, optionsWithDefaults);
813
802
  const trace = (0, zehut_1.newTrace)(zehut_1.traceTypes.RABBIT);
@@ -823,7 +812,7 @@ class RabbitMq {
823
812
  ]);
824
813
  }
825
814
  catch (e) {
826
- logger_1.default.error('rabbit: failed to setRabbitTrace', { userId, e });
815
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error('rabbit: failed to setRabbitTrace', { userId, e });
827
816
  return this.nack(confirmChannel, queue, optionsWithDefaults, { messageTtl: deadMessageTtl }, msg, releaseLock)(msg);
828
817
  }
829
818
  }
@@ -849,28 +838,28 @@ class RabbitMq {
849
838
  return;
850
839
  }
851
840
  messageAcked = true;
852
- return this.ack(confirmChannel, msg, true, releaseLock)(msg);
841
+ await this.ack(confirmChannel, msg, true, releaseLock)(msg);
853
842
  };
854
843
  const localNack = async (_, nackOptions = {}) => {
855
844
  if (messageAcked) {
856
845
  return;
857
846
  }
858
- debug('rabbit localNack', { messageAcked, uniqueId, deliveryTag: msg.fields.deliveryTag });
847
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('rabbit localNack', { messageAcked, uniqueId, deliveryTag: msg.fields.deliveryTag });
859
848
  messageAcked = true;
860
- return this.nack(confirmChannel, queue, optionsWithDefaults, { messageTtl: deadMessageTtl }, msg, releaseLock)(msg, nackOptions);
849
+ await this.nack(confirmChannel, queue, optionsWithDefaults, { messageTtl: deadMessageTtl }, msg, releaseLock)(msg, nackOptions);
861
850
  };
862
851
  try {
863
- await callback(parsedMessage, localAck, localNack);
852
+ return await callback(parsedMessage, localAck, localNack);
864
853
  }
865
854
  catch (e) {
866
- await localNack(msg);
855
+ return localNack(msg);
867
856
  }
868
857
  }, types_1.CONSUMER_DEFAULT_OPTIONS);
869
858
  if (!consumerTag) {
870
- logger_1.default.error(`rabbit: failed to consume from queue ${queue} old`);
859
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error(`rabbit: failed to consume from queue ${queue} old`);
871
860
  }
872
861
  else {
873
- logger_1.default.info(`rabbit: adding tag ${consumerTag} to the array old`);
862
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").info(`rabbit: adding tag ${consumerTag} to the array old`);
874
863
  this.oldConsumersTags.set(queue, { channel: confirmChannel, consumerTag });
875
864
  }
876
865
  });
@@ -882,107 +871,105 @@ class RabbitMq {
882
871
  localConnection = await this.getConnectionOld(connection);
883
872
  }
884
873
  catch (e) {
885
- logger_1.default.error(`rabbit: error on get connection for new channel ${name} `, { e });
874
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error(`rabbit: error on get connection for new channel ${name} `, { e });
886
875
  throw e;
887
876
  }
888
877
  if (!localConnection) {
889
878
  throw new Error(`rabbit: couldnt get connection for new channel ${name}`);
890
879
  }
891
880
  const channel = localConnection?.createChannel({ ...options });
892
- (0, events_1.once)(channel, 'close').then((args) => {
893
- logger_1.default.error(`rabbit: channel ${name} closed`);
881
+ (0, node_events_1.once)(channel, 'close').then((args) => {
882
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error(`rabbit: channel ${name} closed`);
894
883
  onClose?.(args);
895
884
  });
896
885
  try {
897
- await (0, events_1.once)(channel, 'connect');
898
- debug(`rabbit: channel ${name} CONNECTED`);
886
+ await (0, node_events_1.once)(channel, 'connect');
887
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug(`rabbit: channel ${name} CONNECTED`);
899
888
  return channel;
900
889
  }
901
890
  catch (err) {
902
- logger_1.default.error(`rabbit: channel error ${name} error`, { err });
891
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error(`rabbit: channel error ${name} error`, { err });
903
892
  throw err;
904
893
  }
905
894
  }
906
895
  async getConnectionOld(connection) {
907
- return new Promise(async (resolve, reject) => {
908
- const { amqpConnection: connectionLocal, creatingConnection, connectionCreatedEventName, connectionFailedEventName, blockReconnect, } = connection;
909
- if (blockReconnect) {
910
- debug('rabbit: block reconnect');
896
+ const { amqpConnection: connectionLocal, creatingConnection, connectionCreatedEventName, connectionFailedEventName, blockReconnect, } = connection;
897
+ if (blockReconnect) {
898
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('rabbit: block reconnect');
899
+ // @ts-expect-error we are returning undefined while the function clearly expects a connection.
900
+ return undefined;
901
+ }
902
+ if (connectionLocal !== null) {
903
+ if (this.options?.disableReconnect || connectionLocal?.isConnected()) {
904
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('rabbit: connection - is connected');
911
905
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
912
906
  // @ts-ignore
913
- return resolve();
907
+ return connectionLocal;
914
908
  }
915
- if (connectionLocal !== null) {
916
- if (this.options?.disableReconnect || connectionLocal?.isConnected()) {
917
- debug('rabbit: connection - is connected');
918
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
919
- // @ts-ignore
920
- return resolve(connectionLocal);
921
- }
922
- debug('rabbit: connection - reconnecting');
909
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('rabbit: connection - reconnecting');
910
+ }
911
+ if (creatingConnection) {
912
+ const [event, value] = await Promise.race([connectionCreatedEventName, connectionFailedEventName].map((e) => (0, node_events_1.once)(this.oldEm, e).then(([result]) => [e, result])));
913
+ if (event === connectionCreatedEventName) {
914
+ return value;
923
915
  }
924
- if (creatingConnection) {
925
- debug('rabbit: creating connection emi');
926
- this.oldEm.once(connectionCreatedEventName, resolve);
927
- this.oldEm.once(connectionFailedEventName, reject);
928
- return;
916
+ throw value;
917
+ }
918
+ connection.creatingConnection = true;
919
+ let isResolved = false;
920
+ // It is import to use it as a function and not as a variable
921
+ // because of k8s changes the env variables
922
+ // and we want to use the new values
923
+ const findServers = () => {
924
+ const userName = process.env.RABBITMQ_USERNAME || 'guest';
925
+ const password = process.env.RABBITMQ_PASSWORD || 'guest';
926
+ const host = this.options?.rabbitHost || process.env.RABBITMQ_SERVICE_HOST || 'localhost';
927
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('rabbit: creating connection', { host, userName, HEARTBEAT });
928
+ return [`amqp://${userName}:${password}@${host}?heartbeat=${HEARTBEAT}`];
929
+ };
930
+ const defaultUrls = findServers();
931
+ const newConnection = await (0, amqp_connection_manager_1.connect)(defaultUrls, { findServers });
932
+ connection.amqpConnection = newConnection;
933
+ const { promise, reject, resolve } = (0, utils_1.createDeferredPromise)();
934
+ newConnection.on('error', (err) => {
935
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").error('rabbit: connection error', { err });
936
+ if (!isResolved) {
937
+ isResolved = true;
938
+ reject(err);
939
+ this.oldEm.emit(connectionFailedEventName, err);
929
940
  }
930
- connection.creatingConnection = true;
931
- let isResolved = false;
932
- // It is import to use it as a function and not as a variable
933
- // because of k8s changes the env variables
934
- // and we want to use the new values
935
- const findServers = () => {
936
- const userName = process.env.RABBITMQ_USERNAME || 'guest';
937
- const password = process.env.RABBITMQ_PASSWORD || 'guest';
938
- const host = this.options?.rabbitHost || process.env.RABBITMQ_SERVICE_HOST || 'localhost';
939
- debug('rabbit: creating connection', { host, userName, HEARTBEAT });
940
- return [`amqp://${userName}:${password}@${host}?heartbeat=${HEARTBEAT}`];
941
- };
942
- const defaultUrls = findServers();
943
- const newConnection = await (0, amqp_connection_manager_1.connect)(defaultUrls, {
944
- findServers,
945
- });
946
- connection.amqpConnection = newConnection;
947
- newConnection.on('error', (err) => {
948
- logger_1.default.error('rabbit: connection error', { err });
949
- if (!isResolved) {
950
- isResolved = true;
951
- reject(err);
952
- this.oldEm.emit(connectionFailedEventName, err);
953
- }
954
- });
955
- newConnection.on('connectFailed', (err) => {
956
- this.oldConsumersTags.clear();
957
- if (typeof err.url === 'string') {
958
- err.url = this.maskURL(err.url);
959
- }
960
- logger_1.default.error('rabbit: connection connectFailed', { err });
961
- if (!isResolved) {
962
- isResolved = true;
963
- reject(err);
964
- this.oldEm.emit(connectionFailedEventName, err);
965
- }
966
- });
967
- newConnection.on('disconnect', ({ err }) => {
968
- this.oldConsumersTags.clear();
969
- debug('rabbit: connection closed');
970
- if (this.options?.disableReconnect) {
971
- logger_1.default.error(`${this.DISCONNECT_MSG}${err && ` - ${err}`}`);
972
- connection.blockReconnect = true;
973
- }
974
- else {
975
- logger_1.default.error(`${this.RECONNECT_MSG}${err && ` - ${err}`}`);
976
- }
977
- });
978
- newConnection.once('connect', async () => {
979
- debug('rabbit: connection established');
980
- connection.creatingConnection = false;
981
- this.oldEm.emit(connectionCreatedEventName, newConnection);
941
+ });
942
+ newConnection.on('connectFailed', (err) => {
943
+ this.oldConsumersTags.clear();
944
+ if (typeof err.url === 'string') {
945
+ err.url = this.maskURL(err.url);
946
+ }
947
+ logger_1.default.error('rabbit: connection connectFailed', { err });
948
+ if (!isResolved) {
982
949
  isResolved = true;
983
- resolve(newConnection);
984
- });
950
+ reject(err);
951
+ this.oldEm.emit(connectionFailedEventName, err);
952
+ }
985
953
  });
954
+ newConnection.on('disconnect', ({ err }) => {
955
+ this.oldConsumersTags.clear();
956
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('rabbit: connection closed');
957
+ if (this.options?.disableReconnect) {
958
+ logger_1.default.error(`${this.DISCONNECT_MSG}${err && ` - ${err}`}`);
959
+ connection.blockReconnect = true;
960
+ }
961
+ else {
962
+ logger_1.default.error(`${this.RECONNECT_MSG}${err && ` - ${err}`}`);
963
+ }
964
+ });
965
+ newConnection.once('connect', async () => {
966
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('rabbit: connection established');
967
+ connection.creatingConnection = false;
968
+ this.oldEm.emit(connectionCreatedEventName, newConnection);
969
+ isResolved = true;
970
+ resolve(newConnection);
971
+ });
972
+ return promise;
986
973
  }
987
974
  saveConsumerOld(queue, callback, options) {
988
975
  const isConsumerExist = this.oldConsumersToRegister.some((consumer) => consumer.queue === queue);
@@ -996,15 +983,13 @@ class RabbitMq {
996
983
  }
997
984
  }
998
985
  async assertQueueOld(queueName, options) {
986
+ var _a;
999
987
  RabbitMq.validateName('queue', queueName);
1000
988
  if (this.oldQueues[queueName]) {
1001
989
  delete this.oldQueueSetupPromises[queueName];
1002
990
  return this.oldQueues[queueName];
1003
991
  }
1004
- if (this.oldQueueSetupPromises[queueName]) {
1005
- return this.oldQueueSetupPromises[queueName];
1006
- }
1007
- this.oldQueueSetupPromises[queueName] = this.setupQueueOld(queueName, options);
992
+ (_a = this.oldQueueSetupPromises)[queueName] || (_a[queueName] = this.setupQueueOld(queueName, options));
1008
993
  return this.oldQueueSetupPromises[queueName];
1009
994
  }
1010
995
  async setupQueueOld(queueName, options) {
@@ -1022,20 +1007,20 @@ class RabbitMq {
1022
1007
  };
1023
1008
  try {
1024
1009
  const channel = await this.assertChannelOld({ connection });
1025
- debug('assertQueue->channel.addSetup', { queueName });
1010
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('assertQueue->channel.addSetup', { queueName });
1026
1011
  await channel.addSetup((setupChannel) => setupChannel.assertQueue(queueName, localeOptions));
1027
- debug('assertQueue->channel.assertQueue', { queueName });
1012
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('assertQueue->channel.assertQueue', { queueName });
1028
1013
  queue = await channel.assertQueue(queueName, localeOptions);
1029
1014
  }
1030
1015
  catch (e) {
1031
1016
  logger_1.default.error('rabbit: assertQueue error', { queueName, options, error: e });
1032
1017
  if (!this.options?.dontRetryAssert) {
1033
- debug('retrying assertQueue', { queueName });
1018
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('retrying assertQueue', { queueName });
1034
1019
  const channel = await this.assertChannelOld({ force: true, connection });
1035
1020
  await this.deleteQueueOld(queueName, connection);
1036
- debug('retrying assertQueue->channel.addSetup', { queueName });
1021
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('retrying assertQueue->channel.addSetup', { queueName });
1037
1022
  await channel.addSetup((setupChannel) => setupChannel.assertQueue(queueName, localeOptions));
1038
- debug('retrying assertQueue->channel.assertQueue', { queueName });
1023
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('retrying assertQueue->channel.assertQueue', { queueName });
1039
1024
  queue = await channel.assertQueue(queueName, localeOptions);
1040
1025
  }
1041
1026
  else {
@@ -1046,34 +1031,36 @@ class RabbitMq {
1046
1031
  return queue;
1047
1032
  }
1048
1033
  async assertChannelOld({ force = false, connection }) {
1049
- if (!this.oldPublishChannelSetupPromise) {
1050
- this.oldPublishChannelSetupPromise = new Promise(async (resolve, reject) => {
1051
- if (this.oldPublishChannel && !force) {
1052
- return resolve(this.oldPublishChannel);
1053
- }
1054
- try {
1055
- const channel = await this.getNewChannelOld({ connection });
1056
- channel.on('error', (err) => {
1057
- logger_1.default.error('rabbit: channel error', { err });
1058
- });
1059
- if (this.oldPublishConnection === connection) {
1060
- this.oldPublishChannel = channel;
1061
- }
1062
- resolve(channel);
1063
- }
1064
- catch (e) {
1065
- reject(e);
1066
- }
1034
+ if (this.oldPublishChannelSetupPromise) {
1035
+ return this.oldPublishChannelSetupPromise;
1036
+ }
1037
+ const { promise, resolve, reject } = (0, utils_1.createDeferredPromise)();
1038
+ this.oldPublishChannelSetupPromise = promise;
1039
+ if (this.oldPublishChannel && !force) {
1040
+ resolve(this.oldPublishChannel);
1041
+ return promise;
1042
+ }
1043
+ try {
1044
+ const channel = await this.getNewChannelOld({ connection });
1045
+ channel.on('error', (err) => {
1046
+ logger_1.default.error('rabbit: channel error', { err });
1067
1047
  });
1048
+ if (this.oldPublishConnection === connection) {
1049
+ this.oldPublishChannel = channel;
1050
+ }
1051
+ resolve(channel);
1068
1052
  }
1069
- return this.oldPublishChannelSetupPromise;
1053
+ catch (e) {
1054
+ reject(e);
1055
+ }
1056
+ return promise;
1070
1057
  }
1071
1058
  async deleteQueueOld(queue, connection) {
1072
1059
  RabbitMq.validateName('queue', queue);
1073
1060
  const channel = await this.assertChannelOld({ connection });
1074
1061
  logger_1.default.info('rabbit: deleting queue', { queue });
1075
1062
  const deleteQueueRes = await channel.deleteQueue(queue);
1076
- debug('queue deleted', deleteQueueRes);
1063
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('queue deleted', deleteQueueRes);
1077
1064
  return deleteQueueRes;
1078
1065
  }
1079
1066
  async assertExchangeOld(exchangeName, connection) {
@@ -1091,7 +1078,7 @@ class RabbitMq {
1091
1078
  }
1092
1079
  async isConnectedOld() {
1093
1080
  if (!this.gracefulShutdownStarted) {
1094
- debug('rabbit: start is connected old');
1081
+ __classPrivateFieldGet(this, _RabbitMq_logger, "f").debug('rabbit: start is connected old');
1095
1082
  const [oldConsumeConnection, oldPublishConnection] = await Promise.all([
1096
1083
  this.getConnectionOld(this.oldConsumeConnection),
1097
1084
  this.getConnectionOld(this.oldPublishConnection),
@@ -1102,10 +1089,7 @@ class RabbitMq {
1102
1089
  return false;
1103
1090
  }
1104
1091
  try {
1105
- const unRegisteredConsumersOld = this.consumersToRegister.filter((c) => {
1106
- const doesConsumerExist = this.consumersTags.get(c.queue);
1107
- return !doesConsumerExist;
1108
- });
1092
+ const unRegisteredConsumersOld = this.consumersToRegister.filter((c) => !this.consumersTags.get(c.queue));
1109
1093
  if (unRegisteredConsumersOld.length > 0) {
1110
1094
  const queueNames = unRegisteredConsumersOld.map((c) => c.queue);
1111
1095
  logger_1.default.error('rabbit: found unregistered consumers for queues old', {
@@ -1126,6 +1110,7 @@ class RabbitMq {
1126
1110
  return true;
1127
1111
  }
1128
1112
  }
1113
+ _RabbitMq_logger = new WeakMap();
1129
1114
  exports.default = RabbitMq;
1130
1115
  var celery_1 = require("./lib/celery");
1131
1116
  Object.defineProperty(exports, "sendCeleryTaskViaHttp", { enumerable: true, get: function () { return celery_1.sendCeleryTaskViaHttp; } });