@imqueue/core 2.0.22 → 2.0.25

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.25",
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,21 +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;
295
306
  /**
296
- * Builds and returns connection ready state handler
307
+ * Schedules custom reconnection for a given channel with capped
308
+ * exponential backoff
297
309
  *
298
- * @access private
299
- * @param {RedisQueue} context
300
310
  * @param {RedisConnectionChannel} channel
301
- * @param {(...args: any[]) => void} resolve
302
- * @return {() => Promise<void>}
311
+ * @private
303
312
  */
304
- private onReadyHandler;
313
+ private scheduleReconnect;
305
314
  /**
306
315
  * Generates channel name
307
316
  *
@@ -317,7 +326,6 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
317
326
  * @access private
318
327
  * @param {RedisQueue} context
319
328
  * @param {RedisConnectionChannel} channel
320
- * @param {(...args: any[]) => void} reject
321
329
  * @return {(err: Error) => void}
322
330
  */
323
331
  private onErrorHandler;
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
  *
@@ -564,86 +586,129 @@ class RedisQueue extends events_1.EventEmitter {
564
586
  if (context[channel]) {
565
587
  return context[channel];
566
588
  }
567
- return new Promise((resolve, reject) => {
568
- const redis = new redis_1.default({
569
- // istanbul ignore next
570
- port: options.port || 6379,
571
- // istanbul ignore next
572
- host: options.host || 'localhost',
573
- // istanbul ignore next
574
- username: options.username,
575
- // istanbul ignore next
576
- password: options.password,
577
- connectionName: this.getChannelName(context.name + '', options.prefix || '', channel),
578
- retryStrategy: this.retryStrategy(context),
579
- autoResubscribe: true,
580
- enableOfflineQueue: true,
581
- autoResendUnfulfilledCommands: true,
582
- offlineQueue: true,
583
- maxRetriesPerRequest: null,
584
- });
585
- context[channel] = redis;
586
- context[channel].__imq = true;
587
- for (const event of [
588
- 'wait',
589
- 'reconnecting',
590
- 'connecting',
591
- 'connect',
592
- 'close',
593
- ]) {
594
- redis.on(event, () => {
595
- context.verbose(`Redis Event fired: ${event}`);
596
- });
597
- }
598
- redis.setMaxListeners(IMQ_REDIS_MAX_LISTENERS_LIMIT);
599
- redis.on('ready', this.onReadyHandler(context, channel, resolve));
600
- redis.on('error', this.onErrorHandler(context, channel, reject));
601
- redis.on('end', this.onCloseHandler(context, channel));
589
+ const redis = new redis_1.default({
590
+ // istanbul ignore next
591
+ port: options.port || 6379,
592
+ // istanbul ignore next
593
+ host: options.host || 'localhost',
594
+ // istanbul ignore next
595
+ username: options.username,
596
+ // istanbul ignore next
597
+ password: options.password,
598
+ connectionName: this.getChannelName(context.name + '', options.prefix || '', channel),
599
+ retryStrategy: this.retryStrategy(),
600
+ autoResubscribe: true,
601
+ enableOfflineQueue: true,
602
+ autoResendUnfulfilledCommands: true,
603
+ offlineQueue: true,
604
+ maxRetriesPerRequest: null,
605
+ enableReadyCheck: channel !== 'subscription',
606
+ lazyConnect: true,
602
607
  });
608
+ context[channel] = redis;
609
+ context[channel].__imq = true;
610
+ for (const event of [
611
+ 'wait',
612
+ 'reconnecting',
613
+ 'connecting',
614
+ 'connect',
615
+ 'close',
616
+ ]) {
617
+ redis.on(event, () => {
618
+ context.verbose(`Redis Event fired: ${event}`);
619
+ });
620
+ }
621
+ redis.setMaxListeners(IMQ_REDIS_MAX_LISTENERS_LIMIT);
622
+ redis.on('error', this.onErrorHandler(context, channel));
623
+ redis.on('end', this.onCloseHandler(context, channel));
624
+ await redis.connect();
625
+ this.logger.info('%s: %s channel connected, host %s, pid %s', context.name, channel, this.redisKey, process.pid);
626
+ switch (channel) {
627
+ case 'reader':
628
+ this.read();
629
+ break;
630
+ case 'writer':
631
+ await this.processDelayed(this.key);
632
+ break;
633
+ case 'watcher':
634
+ await this.initWatcher();
635
+ break;
636
+ }
637
+ return context[channel];
603
638
  }
604
639
  // istanbul ignore next
605
640
  /**
606
641
  * Builds and returns redis reconnection strategy
607
642
  *
608
- * @param {RedisQueue} context
609
643
  * @returns {() => (number | void | null)}
610
644
  * @private
611
645
  */
612
- retryStrategy(context) {
646
+ retryStrategy() {
613
647
  return () => {
614
- if (context.destroyed) {
615
- return null;
616
- }
617
- this.verbose('Redis connection error, retrying...');
618
648
  return null;
619
649
  };
620
650
  }
621
651
  /**
622
- * Builds and returns connection ready state handler
652
+ * Schedules custom reconnection for a given channel with capped
653
+ * exponential backoff
623
654
  *
624
- * @access private
625
- * @param {RedisQueue} context
626
655
  * @param {RedisConnectionChannel} channel
627
- * @param {(...args: any[]) => void} resolve
628
- * @return {() => Promise<void>}
656
+ * @private
629
657
  */
630
- onReadyHandler(context, channel, resolve) {
631
- this.verbose(`Redis ${channel} channel ready!`);
632
- return (async () => {
633
- this.logger.info('%s: %s channel connected, host %s, pid %s', context.name, channel, this.redisKey, process.pid);
634
- switch (channel) {
635
- case 'reader':
636
- this.read();
637
- break;
638
- case 'writer':
639
- await this.processDelayed(this.key);
640
- break;
641
- case 'watcher':
642
- await this.initWatcher();
643
- break;
658
+ scheduleReconnect(channel) {
659
+ if (this.destroyed) {
660
+ return;
661
+ }
662
+ if (this.reconnecting[channel]) {
663
+ return;
664
+ }
665
+ this.reconnecting[channel] = true;
666
+ const attempts = (this.reconnectAttempts[channel] || 0) + 1;
667
+ this.reconnectAttempts[channel] = attempts;
668
+ const base = Math.min(30000, 1000 * Math.pow(2, attempts - 1));
669
+ const jitter = Math.floor(base * 0.2 * Math.random());
670
+ const delay = base + jitter;
671
+ this.verbose(`Scheduling ${channel} reconnect in ${delay} ms (attempt ${attempts})`);
672
+ if (this.reconnectTimers[channel]) {
673
+ clearTimeout(this.reconnectTimers[channel]);
674
+ }
675
+ this.reconnectTimers[channel] = setTimeout(async () => {
676
+ if (this.destroyed) {
677
+ this.reconnecting[channel] = false;
678
+ return;
644
679
  }
645
- resolve(context[channel]);
646
- });
680
+ try {
681
+ switch (channel) {
682
+ case 'watcher':
683
+ this.destroyWatcher();
684
+ break;
685
+ case 'writer':
686
+ this.destroyWriter();
687
+ break;
688
+ case 'reader':
689
+ this.destroyChannel(channel, this);
690
+ this.reader = undefined;
691
+ break;
692
+ case 'subscription':
693
+ this.destroyChannel(channel, this);
694
+ this.subscription = undefined;
695
+ break;
696
+ }
697
+ await this.connect(channel, this.options);
698
+ this.reconnectAttempts[channel] = 0;
699
+ this.reconnecting[channel] = false;
700
+ if (this.reconnectTimers[channel]) {
701
+ clearTimeout(this.reconnectTimers[channel]);
702
+ this.reconnectTimers[channel] = undefined;
703
+ }
704
+ this.verbose(`Reconnected ${channel} channel`);
705
+ }
706
+ catch (err) {
707
+ this.reconnecting[channel] = false;
708
+ this.verbose(`Reconnect ${channel} failed: ${err}`);
709
+ this.scheduleReconnect(channel);
710
+ }
711
+ }, delay);
647
712
  }
648
713
  // noinspection JSMethodCanBeStatic
649
714
  /**
@@ -664,20 +729,21 @@ class RedisQueue extends events_1.EventEmitter {
664
729
  * @access private
665
730
  * @param {RedisQueue} context
666
731
  * @param {RedisConnectionChannel} channel
667
- * @param {(...args: any[]) => void} reject
668
732
  * @return {(err: Error) => void}
669
733
  */
670
- onErrorHandler(context, channel, reject) {
734
+ onErrorHandler(context, channel) {
671
735
  // istanbul ignore next
672
- return ((err) => {
673
- this.verbose(`Redis Error: ${err}`);
736
+ return ((error) => {
737
+ var _a;
738
+ this.verbose(`Redis Error: ${error}`);
674
739
  if (this.destroyed) {
675
740
  return;
676
741
  }
677
- this.logger.error(`${context.name}: error connecting redis host ${this.redisKey} on ${channel}, pid ${process.pid}:`, err);
678
- if (!this.initialized) {
679
- this.initialized = false;
680
- reject(err);
742
+ this.logger.error(`${context.name}: error connecting redis host ${this.redisKey} on ${channel}, pid ${process.pid}:`, error);
743
+ if (error.code === 'ECONNREFUSED' ||
744
+ error.code === 'ETIMEDOUT' ||
745
+ ((_a = context[channel]) === null || _a === void 0 ? void 0 : _a.status) !== 'ready') {
746
+ this.scheduleReconnect(channel);
681
747
  }
682
748
  });
683
749
  }
@@ -695,6 +761,9 @@ class RedisQueue extends events_1.EventEmitter {
695
761
  return (() => {
696
762
  this.initialized = false;
697
763
  this.logger.warn('%s: redis connection %s closed on host %s, pid %s!', context.name, channel, this.redisKey, process.pid);
764
+ if (!this.destroyed) {
765
+ this.scheduleReconnect(channel);
766
+ }
698
767
  });
699
768
  }
700
769
  /**
@@ -1200,4 +1269,10 @@ __decorate([
1200
1269
  __metadata("design:paramtypes", []),
1201
1270
  __metadata("design:returntype", void 0)
1202
1271
  ], RedisQueue.prototype, "destroyWriter", null);
1272
+ __decorate([
1273
+ (0, _1.profile)(),
1274
+ __metadata("design:type", Function),
1275
+ __metadata("design:paramtypes", [String, RedisQueue]),
1276
+ __metadata("design:returntype", void 0)
1277
+ ], RedisQueue.prototype, "destroyChannel", null);
1203
1278
  //# sourceMappingURL=RedisQueue.js.map