@imqueue/core 2.0.15 → 2.0.16

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/debug.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@imqueue/core",
3
- "version": "2.0.15",
3
+ "version": "2.0.16",
4
4
  "description": "Simple JSON-based messaging queue for inter service communication",
5
5
  "keywords": [
6
6
  "message-queue",
@@ -243,6 +243,12 @@ export interface IMQOptions extends Partial<IMessageQueueConnection> {
243
243
  * @type {ClusterManager[]}
244
244
  */
245
245
  clusterManagers?: ClusterManager[];
246
+ /**
247
+ * Enables/disables verbose logging, default is false
248
+ *
249
+ * @type {boolean}
250
+ */
251
+ verbose?: boolean;
246
252
  }
247
253
  export interface EventMap {
248
254
  message: [data: any, id: string, from: string];
@@ -138,6 +138,7 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
138
138
  * @param {IMQMode} [mode]
139
139
  */
140
140
  constructor(name: string, options?: Partial<IMQOptions>, mode?: IMQMode);
141
+ private verbose;
141
142
  /**
142
143
  * Creates a subscription channel over redis and sets up channel
143
144
  * data read handler
@@ -447,7 +448,7 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
447
448
  */
448
449
  private ownWatch;
449
450
  /**
450
- * This method returns watcher lock resolver function
451
+ * This method returns a watcher lock resolver function
451
452
  *
452
453
  * @access private
453
454
  * @param {(...args: any[]) => void} resolve
package/src/RedisQueue.js CHANGED
@@ -100,6 +100,7 @@ function pack(data) {
100
100
  function unpack(data) {
101
101
  return JSON.parse((0, zlib_1.gunzipSync)(Buffer.from(data, 'binary')).toString());
102
102
  }
103
+ const IMQ_REDIS_MAX_LISTENERS_LIMIT = +(process.env.IMQ_REDIS_MAX_LISTENERS_LIMIT || 10000);
103
104
  /**
104
105
  * Class RedisQueue
105
106
  * Implements simple messaging queue over redis.
@@ -169,6 +170,12 @@ class RedisQueue extends events_1.EventEmitter {
169
170
  this.unpack = this.options.useGzip ? unpack : JSON.parse;
170
171
  /* tslint:enable */
171
172
  this.redisKey = `${this.options.host}:${this.options.port}`;
173
+ this.verbose(`Initializing queue on ${this.options.host}:${this.options.port} with prefix ${this.options.prefix} and safeDelivery = ${this.options.safeDelivery}, and safeDeliveryTtl = ${this.options.safeDeliveryTtl}, and watcherCheckDelay = ${this.options.watcherCheckDelay}, and useGzip = ${this.options.useGzip}`);
174
+ }
175
+ verbose(message) {
176
+ if (this.options.verbose) {
177
+ this.logger.info(`[IMQ-CORE][${this.name}]: ${message}`);
178
+ }
172
179
  }
173
180
  /**
174
181
  * Creates a subscription channel over redis and sets up channel
@@ -198,7 +205,9 @@ class RedisQueue extends events_1.EventEmitter {
198
205
  if (ch === fcn && typeof handler === 'function') {
199
206
  handler(JSON.parse(message));
200
207
  }
208
+ this.verbose(`Received message from ${ch} channel, data: ${JSON.stringify(message)}`);
201
209
  });
210
+ this.verbose(`Subscribed to ${channel} channel`);
202
211
  }
203
212
  /**
204
213
  * Closes subscription channel
@@ -207,12 +216,14 @@ class RedisQueue extends events_1.EventEmitter {
207
216
  */
208
217
  async unsubscribe() {
209
218
  if (this.subscription) {
219
+ this.verbose('Initialize unsubscribing...');
210
220
  if (this.subscriptionName) {
211
- this.subscription.unsubscribe(`${this.options.prefix}:${this.subscriptionName}`);
221
+ await this.subscription.unsubscribe(`${this.options.prefix}:${this.subscriptionName}`);
222
+ this.verbose(`Unsubscribed from ${this.subscriptionName} channel`);
212
223
  }
213
224
  this.subscription.removeAllListeners();
214
225
  this.subscription.disconnect(false);
215
- this.subscription.quit();
226
+ await this.subscription.quit();
216
227
  }
217
228
  this.subscriptionName = undefined;
218
229
  this.subscription = undefined;
@@ -232,7 +243,11 @@ class RedisQueue extends events_1.EventEmitter {
232
243
  if (!this.writer) {
233
244
  throw new TypeError('Writer is not connected!');
234
245
  }
235
- await this.writer.publish(`${this.options.prefix}:${toName || this.name}`, JSON.stringify(data));
246
+ const jsonData = JSON.stringify(data);
247
+ const name = toName || this.name;
248
+ await this.writer.publish(`${this.options.prefix}:${name}`, jsonData);
249
+ this.verbose(`Published message to ${name} channel, data: ${jsonData}
250
+ `);
236
251
  }
237
252
  /**
238
253
  * Initializes and starts current queue routines
@@ -250,19 +265,27 @@ class RedisQueue extends events_1.EventEmitter {
250
265
  const connPromises = [];
251
266
  // istanbul ignore next
252
267
  if (!this.reader && this.isWorker()) {
268
+ this.verbose('Initializing reader...');
253
269
  connPromises.push(this.connect('reader', this.options));
254
270
  }
255
271
  if (!this.writer) {
272
+ this.verbose('Initializing writer...');
256
273
  connPromises.push(this.connect('writer', this.options));
257
274
  }
258
275
  await Promise.all(connPromises);
276
+ this.verbose('Connections initialized');
259
277
  if (!this.signalsInitialized) {
278
+ this.verbose('Setting up OS signal handlers...');
260
279
  // istanbul ignore next
261
280
  const free = async () => {
262
281
  let exitCode = 0;
263
- setTimeout(() => process.exit(exitCode), exports.IMQ_SHUTDOWN_TIMEOUT);
282
+ setTimeout(() => {
283
+ this.verbose(`Shutting down after ${exports.IMQ_SHUTDOWN_TIMEOUT} timeout`);
284
+ process.exit(exitCode);
285
+ }, exports.IMQ_SHUTDOWN_TIMEOUT);
264
286
  try {
265
287
  if (this.watchOwner) {
288
+ this.verbose('Freeing watcher lock...');
266
289
  await this.unlock();
267
290
  }
268
291
  }
@@ -275,6 +298,7 @@ class RedisQueue extends events_1.EventEmitter {
275
298
  process.on('SIGINT', free);
276
299
  process.on('SIGABRT', free);
277
300
  this.signalsInitialized = true;
301
+ this.verbose('OS signal handlers initialized!');
278
302
  }
279
303
  await this.initWatcher();
280
304
  this.initialized = true;
@@ -304,24 +328,39 @@ class RedisQueue extends events_1.EventEmitter {
304
328
  const data = { id, message, from: this.name };
305
329
  const key = `${this.options.prefix}:${toQueue}`;
306
330
  const packet = this.pack(data);
307
- const cb = (error) => {
331
+ const cb = (error, op) => {
308
332
  // istanbul ignore next
309
- if (error && errorHandler) {
310
- errorHandler(error);
333
+ if (error) {
334
+ this.verbose(`Writer ${op} error: ${error}`);
335
+ if (errorHandler) {
336
+ errorHandler(error);
337
+ }
311
338
  }
312
339
  };
313
340
  if (delay) {
314
- this.writer.zadd(`${key}:delayed`, Date.now() + delay, packet, (err) => {
341
+ await this.writer.zadd(`${key}:delayed`, Date.now() + delay, packet, (err) => {
315
342
  // istanbul ignore next
316
343
  if (err) {
317
- cb(err);
344
+ cb(err, 'ZADD');
318
345
  return;
319
346
  }
320
- this.writer.set(`${key}:${id}:ttl`, '', 'PX', delay, 'NX', cb);
347
+ this.writer.set(`${key}:${id}:ttl`, '', 'PX', delay, 'NX', (err) => {
348
+ // istanbul ignore next
349
+ if (err) {
350
+ cb(err, 'SET');
351
+ return;
352
+ }
353
+ }).catch((err) => cb(err, 'SET'));
321
354
  });
322
355
  }
323
356
  else {
324
- this.writer.lpush(key, packet, cb);
357
+ await this.writer.lpush(key, packet, (err) => {
358
+ // istanbul ignore next
359
+ if (err) {
360
+ cb(err, 'LPUSH');
361
+ return;
362
+ }
363
+ });
325
364
  }
326
365
  return id;
327
366
  }
@@ -331,13 +370,16 @@ class RedisQueue extends events_1.EventEmitter {
331
370
  * @returns {Promise<RedisQueue>}
332
371
  */
333
372
  async stop() {
373
+ this.verbose('Stopping queue...');
334
374
  if (this.reader) {
375
+ this.verbose('Destroying reader...');
335
376
  this.reader.removeAllListeners();
336
- this.reader.quit();
377
+ await this.reader.quit();
337
378
  this.reader.disconnect(false);
338
379
  delete this.reader;
339
380
  }
340
381
  this.initialized = false;
382
+ this.verbose('Queue stopped!');
341
383
  return this;
342
384
  }
343
385
  /**
@@ -346,6 +388,7 @@ class RedisQueue extends events_1.EventEmitter {
346
388
  * @returns {Promise<void>}
347
389
  */
348
390
  async destroy() {
391
+ this.verbose('Destroying queue...');
349
392
  this.destroyed = true;
350
393
  this.removeAllListeners();
351
394
  this.cleanSafeCheckInterval();
@@ -354,6 +397,7 @@ class RedisQueue extends events_1.EventEmitter {
354
397
  await this.clear();
355
398
  this.destroyWriter();
356
399
  await this.unsubscribe();
400
+ this.verbose('Queue destroyed!');
357
401
  }
358
402
  /**
359
403
  * Clears queue data in redis
@@ -365,10 +409,12 @@ class RedisQueue extends events_1.EventEmitter {
365
409
  return this;
366
410
  }
367
411
  try {
412
+ this.verbose('Clearing expired queue keys...');
368
413
  await Promise.all([
369
414
  this.writer.del(this.key),
370
415
  this.writer.del(`${this.key}:delayed`),
371
416
  ]);
417
+ this.verbose('Expired queue keys cleared!');
372
418
  }
373
419
  catch (err) {
374
420
  // istanbul ignore next
@@ -476,10 +522,14 @@ class RedisQueue extends events_1.EventEmitter {
476
522
  */
477
523
  destroyWatcher() {
478
524
  if (this.watcher) {
525
+ this.verbose('Destroying watcher...');
479
526
  this.watcher.removeAllListeners();
480
- this.watcher.quit();
527
+ this.watcher.quit().catch(e => {
528
+ this.verbose(`Error quitting watcher: ${e}`);
529
+ });
481
530
  this.watcher.disconnect(false);
482
531
  delete RedisQueue.watchers[this.redisKey];
532
+ this.verbose('Watcher destroyed!');
483
533
  }
484
534
  }
485
535
  /**
@@ -489,10 +539,14 @@ class RedisQueue extends events_1.EventEmitter {
489
539
  */
490
540
  destroyWriter() {
491
541
  if (this.writer) {
542
+ this.verbose('Destroying writer...');
492
543
  this.writer.removeAllListeners();
493
- this.writer.quit();
544
+ this.writer.quit().catch(e => {
545
+ this.verbose(`Error quitting writer: ${e}`);
546
+ });
494
547
  this.writer.disconnect(false);
495
548
  delete RedisQueue.writers[this.redisKey];
549
+ this.verbose('Writer destroyed!');
496
550
  }
497
551
  }
498
552
  /**
@@ -505,6 +559,7 @@ class RedisQueue extends events_1.EventEmitter {
505
559
  * @returns {Promise<IRedisClient>}
506
560
  */
507
561
  async connect(channel, options, context = this) {
562
+ this.verbose(`Connecting to ${channel} channel...`);
508
563
  // istanbul ignore next
509
564
  if (context[channel]) {
510
565
  return context[channel];
@@ -519,7 +574,7 @@ class RedisQueue extends events_1.EventEmitter {
519
574
  username: options.username,
520
575
  // istanbul ignore next
521
576
  password: options.password,
522
- connectionName: this.getChannelName(context.name, options.prefix || '', channel),
577
+ connectionName: this.getChannelName(context.name + '', options.prefix || '', channel),
523
578
  retryStrategy: this.retryStrategy(context),
524
579
  autoResubscribe: true,
525
580
  enableReadyCheck: true,
@@ -528,7 +583,18 @@ class RedisQueue extends events_1.EventEmitter {
528
583
  });
529
584
  context[channel] = (0, _1.makeRedisSafe)(redis);
530
585
  context[channel].__imq = true;
531
- redis.setMaxListeners(10000);
586
+ for (const event of [
587
+ 'wait',
588
+ 'reconnecting',
589
+ 'connecting',
590
+ 'connect',
591
+ 'close',
592
+ ]) {
593
+ redis.on(event, () => {
594
+ context.verbose(`Redis Event fired: ${event}`);
595
+ });
596
+ }
597
+ redis.setMaxListeners(IMQ_REDIS_MAX_LISTENERS_LIMIT);
532
598
  redis.on('ready', this.onReadyHandler(context, channel, resolve));
533
599
  redis.on('error', this.onErrorHandler(context, channel, reject));
534
600
  redis.on('end', this.onCloseHandler(context, channel));
@@ -547,6 +613,7 @@ class RedisQueue extends events_1.EventEmitter {
547
613
  if (context.destroyed) {
548
614
  return null;
549
615
  }
616
+ this.verbose('Redis connection error, retrying...');
550
617
  return 200;
551
618
  };
552
619
  }
@@ -560,6 +627,7 @@ class RedisQueue extends events_1.EventEmitter {
560
627
  * @return {() => Promise<void>}
561
628
  */
562
629
  onReadyHandler(context, channel, resolve) {
630
+ this.verbose(`Redis ${channel} channel ready!`);
563
631
  return (async () => {
564
632
  this.logger.info('%s: %s channel connected, host %s, pid %s', context.name, channel, this.redisKey, process.pid);
565
633
  switch (channel) {
@@ -601,6 +669,7 @@ class RedisQueue extends events_1.EventEmitter {
601
669
  onErrorHandler(context, channel, reject) {
602
670
  // istanbul ignore next
603
671
  return ((err) => {
672
+ this.verbose(`Redis Error: ${err}`);
604
673
  if (this.destroyed) {
605
674
  return;
606
675
  }
@@ -620,6 +689,7 @@ class RedisQueue extends events_1.EventEmitter {
620
689
  * @return {(...args: any[]) => any}
621
690
  */
622
691
  onCloseHandler(context, channel) {
692
+ this.verbose(`Redis ${channel} is closing...`);
623
693
  // istanbul ignore next
624
694
  return (() => {
625
695
  this.initialized = false;
@@ -634,13 +704,16 @@ class RedisQueue extends events_1.EventEmitter {
634
704
  * @returns {RedisQueue}
635
705
  */
636
706
  process(msg) {
707
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
637
708
  const [queue, data] = msg;
638
709
  // istanbul ignore next
639
710
  if (!queue || queue !== this.key) {
640
711
  return this;
641
712
  }
642
713
  try {
714
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-argument
643
715
  const { id, message, from } = this.unpack(data);
716
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
644
717
  this.emit('message', message, id, from);
645
718
  }
646
719
  catch (err) {
@@ -724,6 +797,7 @@ class RedisQueue extends events_1.EventEmitter {
724
797
  if (!keys.length) {
725
798
  return;
726
799
  }
800
+ this.verbose(`Watching ${keys.length} keys: ${keys.map(key => `"${key}"`).join(', ')}`);
727
801
  for (const key of keys) {
728
802
  const kp = key.split(':');
729
803
  if (Number(kp.pop()) < now) {
@@ -742,7 +816,7 @@ class RedisQueue extends events_1.EventEmitter {
742
816
  */
743
817
  async onWatchMessage(...args) {
744
818
  try {
745
- const key = (args.pop() || '').split(':');
819
+ const key = ((args.pop() || '') + '').split(':');
746
820
  if (key.pop() !== 'ttl') {
747
821
  return;
748
822
  }
@@ -777,18 +851,21 @@ class RedisQueue extends events_1.EventEmitter {
777
851
  return this;
778
852
  }
779
853
  try {
780
- this.writer.config('SET', 'notify-keyspace-events', 'Ex');
854
+ this.writer.config('SET', 'notify-keyspace-events', 'Ex').catch(err => {
855
+ this.emitError('OnConfig', 'events config error', err);
856
+ });
781
857
  }
782
858
  catch (err) {
783
859
  this.emitError('OnConfig', 'events config error', err);
784
860
  }
785
861
  this.watcher.on('pmessage', this.onWatchMessage.bind(this));
786
- this.watcher.psubscribe('__keyevent@0__:expired', `${this.options.prefix}:delayed:*`);
862
+ this.watcher.psubscribe('__keyevent@0__:expired', `${this.options.prefix}:delayed:*`).catch(err => {
863
+ this.verbose(`Error subscribing to watcher channel: ${err}`);
864
+ });
787
865
  // watch for expired unhandled safe queues
788
866
  if (!this.safeCheckInterval) {
789
- // tslint:disable-next-line:triple-equals no-null-keyword
790
867
  if (this.options.safeDeliveryTtl != null) {
791
- this.safeCheckInterval = setInterval(async () => {
868
+ this.safeCheckInterval = setInterval((async () => {
792
869
  if (!this.writer) {
793
870
  this.cleanSafeCheckInterval();
794
871
  return;
@@ -797,7 +874,7 @@ class RedisQueue extends events_1.EventEmitter {
797
874
  await this.processWatch();
798
875
  }
799
876
  await this.processCleanup();
800
- }, this.options.safeDeliveryTtl);
877
+ }), this.options.safeDeliveryTtl);
801
878
  }
802
879
  }
803
880
  this.watcher.__ready__ = true;
@@ -810,13 +887,15 @@ class RedisQueue extends events_1.EventEmitter {
810
887
  * @returns {Promise<RedisQueue | undefined>}
811
888
  */
812
889
  async processCleanup() {
890
+ this.verbose('Cleaning up orphaned keys...');
813
891
  try {
814
892
  if (!this.options.cleanup) {
815
893
  return;
816
894
  }
817
895
  const filter = new RegExp(this.options.prefix + ':' +
818
896
  (this.options.cleanupFilter || '*').replace(/\*/g, '.*'), 'i');
819
- const clients = await this.writer.client('LIST') || '';
897
+ this.verbose(`Cleaning up keys matching ${filter}`);
898
+ const clients = (await this.writer.client('LIST')).toString() || '';
820
899
  const connectedKeys = (clients.match(RX_CLIENT_NAME) || [])
821
900
  .filter((name) => RX_CLIENT_TEST.test(name) && filter.test(name))
822
901
  .map((name) => name
@@ -825,6 +904,7 @@ class RedisQueue extends events_1.EventEmitter {
825
904
  .filter((name, i, a) => a.indexOf(name) === i);
826
905
  const keysToRemove = [];
827
906
  let cursor = '0';
907
+ this.verbose(`Found connected keys: ${connectedKeys.map(k => `"${k}"`).join(', ')}`);
828
908
  while (true) {
829
909
  const data = await this.writer.scan(cursor, 'MATCH', `${this.options.prefix}:${this.options.cleanupFilter || '*'}`, 'COUNT', '1000');
830
910
  cursor = data.shift();
@@ -837,6 +917,7 @@ class RedisQueue extends events_1.EventEmitter {
837
917
  }
838
918
  if (keysToRemove.length) {
839
919
  await this.writer.del(...keysToRemove);
920
+ this.verbose(`Keys ${keysToRemove.map(k => `"${k}"`).join(', ')} were successfully removed!`);
840
921
  }
841
922
  }
842
923
  catch (err) {
@@ -913,9 +994,7 @@ class RedisQueue extends events_1.EventEmitter {
913
994
  }
914
995
  catch (err) {
915
996
  // istanbul ignore next
916
- this.emitError('OnReadSafe', 'safe reader failed',
917
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
918
- err);
997
+ this.emitError('OnReadSafe', 'safe reader failed', err);
919
998
  }
920
999
  }
921
1000
  /**
@@ -984,6 +1063,7 @@ class RedisQueue extends events_1.EventEmitter {
984
1063
  emitError(eventName, message, err) {
985
1064
  this.emit('error', err, eventName);
986
1065
  this.logger.error(`${this.name}: ${message}, pid ${process.pid} on redis host ${this.redisKey}:`, err);
1066
+ this.verbose(`Error in event ${eventName}: ${message}, pid ${process.pid} on redis host ${this.redisKey}: ${err}`);
987
1067
  }
988
1068
  /**
989
1069
  * Acquires an owner for watcher connection to this instance of the queue
@@ -994,6 +1074,7 @@ class RedisQueue extends events_1.EventEmitter {
994
1074
  async ownWatch() {
995
1075
  const owned = await this.lock();
996
1076
  if (owned) {
1077
+ this.verbose('Watcher connection lock acquired!');
997
1078
  for (const script of Object.keys(this.scripts)) {
998
1079
  try {
999
1080
  const checksum = sha1(this.scripts[script].code);
@@ -1015,7 +1096,7 @@ class RedisQueue extends events_1.EventEmitter {
1015
1096
  }
1016
1097
  // istanbul ignore next
1017
1098
  /**
1018
- * This method returns watcher lock resolver function
1099
+ * This method returns a watcher lock resolver function
1019
1100
  *
1020
1101
  * @access private
1021
1102
  * @param {(...args: any[]) => void} resolve
@@ -1045,9 +1126,10 @@ class RedisQueue extends events_1.EventEmitter {
1045
1126
  */
1046
1127
  // istanbul ignore next
1047
1128
  async initWatcher() {
1048
- return new Promise(async (resolve, reject) => {
1129
+ return new Promise((async (resolve, reject) => {
1049
1130
  try {
1050
1131
  if (!await this.watcherCount()) {
1132
+ this.verbose('Initializing watcher...');
1051
1133
  await this.ownWatch();
1052
1134
  if (this.watchOwner && this.watcher) {
1053
1135
  resolve();
@@ -1065,7 +1147,7 @@ class RedisQueue extends events_1.EventEmitter {
1065
1147
  this.logger.error(`${this.name}: error initializing watcher, pid ${process.pid} on redis host ${this.redisKey}`, err);
1066
1148
  reject(err);
1067
1149
  }
1068
- });
1150
+ }));
1069
1151
  }
1070
1152
  }
1071
1153
  exports.RedisQueue = RedisQueue;