@seidor-cloud-produtos/orbit-backend-lib 2.0.128 → 2.0.131

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.
@@ -31,8 +31,6 @@ export default class AmqpQueue implements QueueConnection {
31
31
  private static instance;
32
32
  private vHost;
33
33
  private connection;
34
- private isConnected;
35
- private reconnectionPromise?;
36
34
  private messagesInMemory;
37
35
  private channels;
38
36
  protected socketOptions?: SocketOptions;
@@ -119,8 +117,6 @@ export default class AmqpQueue implements QueueConnection {
119
117
  * Quando a conexão fecha, a lib tenta reconectar em loop e, ao
120
118
  * reconectar, reativa consumidores e reenvia mensagens em memória.
121
119
  */
122
- private getActiveConnection;
123
- private scheduleReconnection;
124
120
  private treatReconnection;
125
121
  /**
126
122
  * Reinscreve todos os consumidores registrados anteriormente.
@@ -20,8 +20,6 @@ class AmqpQueue {
20
20
  static instance;
21
21
  vHost;
22
22
  connection;
23
- isConnected = false;
24
- reconnectionPromise;
25
23
  messagesInMemory = [];
26
24
  channels = new Map();
27
25
  socketOptions;
@@ -59,12 +57,11 @@ class AmqpQueue {
59
57
  const urlConnection = `${this.uri}${buildedVhost}`;
60
58
  this.connection = await amqplib_1.default.connect(urlConnection, this.socketOptions);
61
59
  this.vHost = vHost;
62
- this.isConnected = true;
63
- this.connection.on('error', async () => {
64
- return await this.scheduleReconnection(vHost);
60
+ this.connection.on('error', async (e) => {
61
+ return await this.treatReconnection(vHost);
65
62
  });
66
63
  this.connection.on('close', async () => {
67
- return await this.scheduleReconnection(vHost);
64
+ return await this.treatReconnection(vHost);
68
65
  });
69
66
  if (process.env.NODE_ENV !== 'test') {
70
67
  this.logger.info(`⚙️ PROCESS ${this.vHost} PID: `, process.pid);
@@ -77,9 +74,6 @@ class AmqpQueue {
77
74
  retryCount >= this.socketOptions?.retry?.maxCount) {
78
75
  throw e;
79
76
  }
80
- if (retryCount === 0) {
81
- await this.close().catch(() => null);
82
- }
83
77
  this.logger.info(`Retrying connection in... ${this.socketOptions.retry.intervalMs || 0}ms`);
84
78
  await (0, timeout_1.sleep)(this.socketOptions.retry.intervalMs);
85
79
  return await this.connect(vHost, retryCount + 1);
@@ -89,7 +83,6 @@ class AmqpQueue {
89
83
  * Fecha a conexão atual com o broker.
90
84
  */
91
85
  async close() {
92
- this.isConnected = false;
93
86
  this.connection.removeAllListeners('close');
94
87
  await this.connection.close();
95
88
  if (process.env.NODE_ENV !== 'test') {
@@ -98,8 +91,7 @@ class AmqpQueue {
98
91
  }
99
92
  async get(queueName, options) {
100
93
  try {
101
- const connection = await this.getActiveConnection();
102
- const channel = await connection.createChannel();
94
+ const channel = await this.connection.createChannel();
103
95
  const rawMessage = await channel.get(queueName, options);
104
96
  if (!rawMessage) {
105
97
  await channel.close();
@@ -149,8 +141,7 @@ class AmqpQueue {
149
141
  */
150
142
  async on(queueName, callback) {
151
143
  try {
152
- const connection = await this.getActiveConnection();
153
- const channel = await connection.createChannel();
144
+ const channel = await this.connection.createChannel();
154
145
  this.channels.set(queueName, callback);
155
146
  await channel.prefetch(callback.getSimultaneity());
156
147
  await channel.consume(queueName, async (message) => {
@@ -259,8 +250,7 @@ class AmqpQueue {
259
250
  }
260
251
  }
261
252
  async publishToServerWaitForConfirms(exchangeName, domainEvent, buildedConfigs) {
262
- const connection = await this.getActiveConnection();
263
- const channel = await connection.createConfirmChannel();
253
+ const channel = await this.connection.createConfirmChannel();
264
254
  channel.publish(exchangeName, domainEvent.name || '', Buffer.from(JSON.stringify(domainEvent)), {
265
255
  persistent: true,
266
256
  ...buildedConfigs,
@@ -269,8 +259,7 @@ class AmqpQueue {
269
259
  await channel.close();
270
260
  }
271
261
  async publishToServer(exchangeName, domainEvent, buildedConfigs) {
272
- const connection = await this.getActiveConnection();
273
- const channel = await connection.createChannel();
262
+ const channel = await this.connection.createChannel();
274
263
  channel.publish(exchangeName, domainEvent.name || '', Buffer.from(JSON.stringify(domainEvent)), {
275
264
  persistent: true,
276
265
  ...buildedConfigs,
@@ -288,8 +277,7 @@ class AmqpQueue {
288
277
  */
289
278
  async createConsumers(queueName, configs) {
290
279
  try {
291
- const connection = await this.getActiveConnection();
292
- const channel = await connection.createChannel();
280
+ const channel = await this.connection.createChannel();
293
281
  await channel.assertExchange(configs.exchangeName, configs.exchangeType, {
294
282
  durable: true,
295
283
  });
@@ -358,29 +346,10 @@ class AmqpQueue {
358
346
  * Quando a conexão fecha, a lib tenta reconectar em loop e, ao
359
347
  * reconectar, reativa consumidores e reenvia mensagens em memória.
360
348
  */
361
- async getActiveConnection() {
362
- if (!this.isConnected && this.reconnectionPromise) {
363
- await this.reconnectionPromise;
364
- }
365
- if (!this.connection) {
366
- throw new infra_error_1.default('RabbitMQ connection is not available!');
367
- }
368
- return this.connection;
369
- }
370
- async scheduleReconnection(vHost) {
371
- this.isConnected = false;
372
- if (!this.reconnectionPromise) {
373
- this.reconnectionPromise = this.treatReconnection(vHost).finally(() => {
374
- this.reconnectionPromise = undefined;
375
- });
376
- }
377
- return await this.reconnectionPromise;
378
- }
379
349
  async treatReconnection(vHost) {
380
- this.isConnected = false;
381
350
  this.logger.info('⛔ Connection Error!!');
382
351
  this.logger.info(`🔄 Try connection to the vHost ${vHost}`);
383
- AmqpQueue.instance = await this.connect(vHost);
352
+ await this.connect(vHost);
384
353
  await this.reconnectionChannels();
385
354
  await this.publishMessagesOfMemory();
386
355
  }
@@ -389,13 +358,14 @@ class AmqpQueue {
389
358
  */
390
359
  async reconnectionChannels() {
391
360
  for (const [queueName, callback] of this.channels) {
392
- await this.on(queueName, callback);
361
+ this.on(queueName, callback);
393
362
  }
394
363
  }
395
364
  /**
396
365
  * Publica novamente mensagens que falharam e ficaram em memória.
397
366
  */
398
367
  async publishMessagesOfMemory() {
368
+ this.logger.info('Publishing messages in memory...', JSON.stringify(this.messagesInMemory));
399
369
  if (this.messagesInMemory.length > 0) {
400
370
  while (this.messagesInMemory.length > 0) {
401
371
  const data = this.messagesInMemory.shift();
@@ -333,36 +333,6 @@ const createLogger = () => ({
333
333
  },
334
334
  ]);
335
335
  });
336
- (0, vitest_1.it)('should wait for an in-flight reconnection before publishing', async () => {
337
- let finishReconnection;
338
- const oldConnection = createConnection();
339
- const channel = createChannel();
340
- const newConnection = createConnection(channel);
341
- const queue = new amqp_lib_1.default(undefined, 'amqp://broker', createLogger());
342
- const event = { name: 'domain.event' };
343
- queue['connection'] = oldConnection;
344
- queue['vHost'] = 'jobs';
345
- queue['isConnected'] = false;
346
- queue['reconnectionPromise'] = new Promise(resolve => {
347
- finishReconnection = () => {
348
- queue['connection'] = newConnection;
349
- queue['isConnected'] = true;
350
- resolve();
351
- };
352
- });
353
- const publishPromise = queue.publish('exchange', event);
354
- await Promise.resolve();
355
- (0, vitest_1.expect)(oldConnection.createChannel).not.toHaveBeenCalled();
356
- (0, vitest_1.expect)(newConnection.createChannel).not.toHaveBeenCalled();
357
- finishReconnection();
358
- await publishPromise;
359
- (0, vitest_1.expect)(oldConnection.createChannel).not.toHaveBeenCalled();
360
- (0, vitest_1.expect)(newConnection.createChannel).toHaveBeenCalledTimes(1);
361
- (0, vitest_1.expect)(channel.publish).toHaveBeenCalledWith('exchange', 'domain.event', Buffer.from(JSON.stringify(event)), {
362
- persistent: true,
363
- expiration: FOURTEEN_DAYS_IN_MS,
364
- });
365
- });
366
336
  (0, vitest_1.it)('should not store messages when storeMessageOnError is false', async () => {
367
337
  const queue = new amqp_lib_1.default(undefined, 'amqp://broker', createLogger());
368
338
  queue['publishToServer'] = vitest_1.vi.fn().mockRejectedValue(new Error('fail'));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seidor-cloud-produtos/orbit-backend-lib",
3
- "version": "2.0.128",
3
+ "version": "2.0.131",
4
4
  "description": "Internal lib for backend components",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",