@imqueue/core 2.0.22 → 2.0.24

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@imqueue/core",
3
- "version": "2.0.22",
3
+ "version": "2.0.24",
4
4
  "description": "Simple JSON-based messaging queue for inter service communication",
5
5
  "keywords": [
6
6
  "message-queue",
@@ -107,6 +107,12 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
107
107
  * Will store check interval reference
108
108
  */
109
109
  private safeCheckInterval;
110
+ /**
111
+ * Internal per-channel reconnection state
112
+ */
113
+ private reconnectTimers;
114
+ private reconnectAttempts;
115
+ private reconnecting;
110
116
  /**
111
117
  * This queue instance unique key (identifier), for internal use
112
118
  */
@@ -274,6 +280,12 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
274
280
  * @access private
275
281
  */
276
282
  private destroyWriter;
283
+ /**
284
+ * Destroys any channel
285
+ *
286
+ * @access private
287
+ */
288
+ private destroyChannel;
277
289
  /**
278
290
  * Establishes a given connection channel by its name
279
291
  *
@@ -287,11 +299,18 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
287
299
  /**
288
300
  * Builds and returns redis reconnection strategy
289
301
  *
290
- * @param {RedisQueue} context
291
302
  * @returns {() => (number | void | null)}
292
303
  * @private
293
304
  */
294
305
  private retryStrategy;
306
+ /**
307
+ * Schedules custom reconnection for a given channel with capped
308
+ * exponential backoff
309
+ *
310
+ * @param {RedisConnectionChannel} channel
311
+ * @private
312
+ */
313
+ private scheduleReconnect;
295
314
  /**
296
315
  * Builds and returns connection ready state handler
297
316
  *
package/src/RedisQueue.js CHANGED
@@ -140,6 +140,12 @@ class RedisQueue extends events_1.EventEmitter {
140
140
  * @type {boolean}
141
141
  */
142
142
  this.signalsInitialized = false;
143
+ /**
144
+ * Internal per-channel reconnection state
145
+ */
146
+ this.reconnectTimers = {};
147
+ this.reconnectAttempts = {};
148
+ this.reconnecting = {};
143
149
  /**
144
150
  * LUA scripts for redis
145
151
  *
@@ -217,13 +223,18 @@ class RedisQueue extends events_1.EventEmitter {
217
223
  async unsubscribe() {
218
224
  if (this.subscription) {
219
225
  this.verbose('Initialize unsubscribing...');
220
- if (this.subscriptionName) {
221
- this.subscription.unsubscribe(`${this.options.prefix}:${this.subscriptionName}`);
222
- this.verbose(`Unsubscribed from ${this.subscriptionName} channel`);
226
+ try {
227
+ if (this.subscriptionName) {
228
+ await this.subscription.unsubscribe(`${this.options.prefix}:${this.subscriptionName}`);
229
+ this.verbose(`Unsubscribed from ${this.subscriptionName} channel`);
230
+ }
231
+ this.subscription.removeAllListeners();
232
+ this.subscription.quit();
233
+ this.subscription.disconnect(false);
234
+ }
235
+ catch (error) {
236
+ this.verbose(`Unsubscribe error: ${error}`);
223
237
  }
224
- this.subscription.removeAllListeners();
225
- this.subscription.disconnect(false);
226
- this.subscription.quit();
227
238
  }
228
239
  this.subscriptionName = undefined;
229
240
  this.subscription = undefined;
@@ -373,9 +384,7 @@ class RedisQueue extends events_1.EventEmitter {
373
384
  this.verbose('Stopping queue...');
374
385
  if (this.reader) {
375
386
  this.verbose('Destroying reader...');
376
- this.reader.removeAllListeners();
377
- this.reader.quit();
378
- this.reader.disconnect(false);
387
+ this.destroyChannel('reader', this);
379
388
  delete this.reader;
380
389
  }
381
390
  this.initialized = false;
@@ -523,11 +532,7 @@ class RedisQueue extends events_1.EventEmitter {
523
532
  destroyWatcher() {
524
533
  if (this.watcher) {
525
534
  this.verbose('Destroying watcher...');
526
- this.watcher.removeAllListeners();
527
- this.watcher.quit().catch(e => {
528
- this.verbose(`Error quitting watcher: ${e}`);
529
- });
530
- this.watcher.disconnect(false);
535
+ this.destroyChannel('watcher', this);
531
536
  delete RedisQueue.watchers[this.redisKey];
532
537
  this.verbose('Watcher destroyed!');
533
538
  }
@@ -540,15 +545,32 @@ class RedisQueue extends events_1.EventEmitter {
540
545
  destroyWriter() {
541
546
  if (this.writer) {
542
547
  this.verbose('Destroying writer...');
543
- this.writer.removeAllListeners();
544
- this.writer.quit().catch(e => {
545
- this.verbose(`Error quitting writer: ${e}`);
546
- });
547
- this.writer.disconnect(false);
548
+ this.destroyChannel('writer', this);
548
549
  delete RedisQueue.writers[this.redisKey];
549
550
  this.verbose('Writer destroyed!');
550
551
  }
551
552
  }
553
+ /**
554
+ * Destroys any channel
555
+ *
556
+ * @access private
557
+ */
558
+ destroyChannel(channel, context = this) {
559
+ const client = context[channel];
560
+ if (client) {
561
+ try {
562
+ client.removeAllListeners();
563
+ client.quit().then(() => {
564
+ client.disconnect(false);
565
+ }).catch(e => {
566
+ this.verbose(`Error quitting ${channel}: ${e}`);
567
+ });
568
+ }
569
+ catch (error) {
570
+ this.verbose(`Error destroying ${channel}: ${error}`);
571
+ }
572
+ }
573
+ }
552
574
  /**
553
575
  * Establishes a given connection channel by its name
554
576
  *
@@ -575,7 +597,7 @@ class RedisQueue extends events_1.EventEmitter {
575
597
  // istanbul ignore next
576
598
  password: options.password,
577
599
  connectionName: this.getChannelName(context.name + '', options.prefix || '', channel),
578
- retryStrategy: this.retryStrategy(context),
600
+ retryStrategy: this.retryStrategy(),
579
601
  autoResubscribe: true,
580
602
  enableOfflineQueue: true,
581
603
  autoResendUnfulfilledCommands: true,
@@ -605,19 +627,76 @@ class RedisQueue extends events_1.EventEmitter {
605
627
  /**
606
628
  * Builds and returns redis reconnection strategy
607
629
  *
608
- * @param {RedisQueue} context
609
630
  * @returns {() => (number | void | null)}
610
631
  * @private
611
632
  */
612
- retryStrategy(context) {
633
+ retryStrategy() {
613
634
  return () => {
614
- if (context.destroyed) {
615
- return null;
616
- }
617
- this.verbose('Redis connection error, retrying...');
618
635
  return null;
619
636
  };
620
637
  }
638
+ /**
639
+ * Schedules custom reconnection for a given channel with capped
640
+ * exponential backoff
641
+ *
642
+ * @param {RedisConnectionChannel} channel
643
+ * @private
644
+ */
645
+ scheduleReconnect(channel) {
646
+ if (this.destroyed) {
647
+ return;
648
+ }
649
+ if (this.reconnecting[channel]) {
650
+ return;
651
+ }
652
+ this.reconnecting[channel] = true;
653
+ const attempts = (this.reconnectAttempts[channel] || 0) + 1;
654
+ this.reconnectAttempts[channel] = attempts;
655
+ const base = Math.min(30000, 1000 * Math.pow(2, attempts - 1));
656
+ const jitter = Math.floor(base * 0.2 * Math.random());
657
+ const delay = base + jitter;
658
+ this.verbose(`Scheduling ${channel} reconnect in ${delay} ms (attempt ${attempts})`);
659
+ if (this.reconnectTimers[channel]) {
660
+ clearTimeout(this.reconnectTimers[channel]);
661
+ }
662
+ this.reconnectTimers[channel] = setTimeout(async () => {
663
+ if (this.destroyed) {
664
+ this.reconnecting[channel] = false;
665
+ return;
666
+ }
667
+ try {
668
+ switch (channel) {
669
+ case 'watcher':
670
+ this.destroyWatcher();
671
+ break;
672
+ case 'writer':
673
+ this.destroyWriter();
674
+ break;
675
+ case 'reader':
676
+ this.destroyChannel(channel, this);
677
+ this.reader = undefined;
678
+ break;
679
+ case 'subscription':
680
+ this.destroyChannel(channel, this);
681
+ this.subscription = undefined;
682
+ break;
683
+ }
684
+ await this.connect(channel, this.options);
685
+ this.reconnectAttempts[channel] = 0;
686
+ this.reconnecting[channel] = false;
687
+ if (this.reconnectTimers[channel]) {
688
+ clearTimeout(this.reconnectTimers[channel]);
689
+ this.reconnectTimers[channel] = undefined;
690
+ }
691
+ this.verbose(`Reconnected ${channel} channel`);
692
+ }
693
+ catch (err) {
694
+ this.reconnecting[channel] = false;
695
+ this.verbose(`Reconnect ${channel} failed: ${err}`);
696
+ this.scheduleReconnect(channel);
697
+ }
698
+ }, delay);
699
+ }
621
700
  /**
622
701
  * Builds and returns connection ready state handler
623
702
  *
@@ -676,9 +755,12 @@ class RedisQueue extends events_1.EventEmitter {
676
755
  }
677
756
  this.logger.error(`${context.name}: error connecting redis host ${this.redisKey} on ${channel}, pid ${process.pid}:`, err);
678
757
  if (!this.initialized) {
679
- this.initialized = false;
680
758
  reject(err);
681
759
  }
760
+ else {
761
+ // Try to recover the channel using our reconnection routine
762
+ this.scheduleReconnect(channel);
763
+ }
682
764
  });
683
765
  }
684
766
  /**
@@ -695,6 +777,9 @@ class RedisQueue extends events_1.EventEmitter {
695
777
  return (() => {
696
778
  this.initialized = false;
697
779
  this.logger.warn('%s: redis connection %s closed on host %s, pid %s!', context.name, channel, this.redisKey, process.pid);
780
+ if (!this.destroyed) {
781
+ this.scheduleReconnect(channel);
782
+ }
698
783
  });
699
784
  }
700
785
  /**
@@ -1200,4 +1285,10 @@ __decorate([
1200
1285
  __metadata("design:paramtypes", []),
1201
1286
  __metadata("design:returntype", void 0)
1202
1287
  ], RedisQueue.prototype, "destroyWriter", null);
1288
+ __decorate([
1289
+ (0, _1.profile)(),
1290
+ __metadata("design:type", Function),
1291
+ __metadata("design:paramtypes", [String, RedisQueue]),
1292
+ __metadata("design:returntype", void 0)
1293
+ ], RedisQueue.prototype, "destroyChannel", null);
1203
1294
  //# sourceMappingURL=RedisQueue.js.map