@imqueue/core 2.0.26 → 3.0.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.
Files changed (49) hide show
  1. package/.oxfmtrc.json +9 -0
  2. package/.oxlintrc.json +20 -0
  3. package/README.md +73 -63
  4. package/debug_getter.d.ts +1 -9
  5. package/index.d.ts +0 -1
  6. package/index.js +8 -9
  7. package/package.json +20 -67
  8. package/scripts/strip-comment-coverage.mjs +397 -0
  9. package/src/ClusterManager.d.ts +12 -3
  10. package/src/ClusterManager.js +21 -10
  11. package/src/ClusteredRedisQueue.d.ts +45 -14
  12. package/src/ClusteredRedisQueue.js +186 -168
  13. package/src/IMessageQueue.d.ts +89 -96
  14. package/src/IMessageQueue.js +2 -2
  15. package/src/RedisQueue.d.ts +193 -97
  16. package/src/RedisQueue.js +1328 -1068
  17. package/src/UDPClusterManager.d.ts +100 -26
  18. package/src/UDPClusterManager.js +225 -70
  19. package/src/UDPWorker.d.ts +53 -1
  20. package/src/UDPWorker.js +79 -40
  21. package/src/{promisify.d.ts → helpers/buildOptions.d.ts} +8 -15
  22. package/src/helpers/buildOptions.js +39 -0
  23. package/src/{copyEventEmitter.d.ts → helpers/copyEventEmitter.d.ts} +1 -1
  24. package/src/{copyEventEmitter.js → helpers/copyEventEmitter.js} +3 -4
  25. package/src/helpers/envInt.d.ts +32 -0
  26. package/src/helpers/envInt.js +39 -0
  27. package/src/helpers/escapeRegExp.d.ts +30 -0
  28. package/src/helpers/escapeRegExp.js +36 -0
  29. package/src/helpers/index.d.ts +31 -0
  30. package/src/helpers/index.js +48 -0
  31. package/src/helpers/pack.d.ts +7 -0
  32. package/src/helpers/pack.js +37 -0
  33. package/src/helpers/randomInt.d.ts +31 -0
  34. package/src/helpers/randomInt.js +37 -0
  35. package/src/helpers/sha1.d.ts +7 -0
  36. package/src/helpers/sha1.js +39 -0
  37. package/src/helpers/unpack.d.ts +7 -0
  38. package/src/helpers/unpack.js +37 -0
  39. package/src/index.d.ts +1 -14
  40. package/src/index.js +1 -19
  41. package/src/profile.d.ts +28 -38
  42. package/src/profile.js +100 -95
  43. package/src/redis.d.ts +1 -1
  44. package/src/redis.js +4 -2
  45. package/typedoc.json +19 -0
  46. package/eslint.config.mjs +0 -98
  47. package/src/promisify.js +0 -106
  48. package/src/uuid.d.ts +0 -6
  49. package/src/uuid.js +0 -65
@@ -1,11 +1,4 @@
1
1
  "use strict";
2
- var __asyncValues = (this && this.__asyncValues) || function (o) {
3
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
4
- var m = o[Symbol.asyncIterator], i;
5
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
6
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
7
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
8
- };
9
2
  Object.defineProperty(exports, "__esModule", { value: true });
10
3
  exports.ClusteredRedisQueue = void 0;
11
4
  /*!
@@ -31,72 +24,111 @@ exports.ClusteredRedisQueue = void 0;
31
24
  * purchase a proprietary commercial license. Please contact us at
32
25
  * <support@imqueue.com> to get commercial licensing options.
33
26
  */
34
- const events_1 = require("events");
27
+ const node_events_1 = require("node:events");
28
+ const helpers_1 = require("./helpers");
35
29
  const _1 = require(".");
30
+ /**
31
+ * Time (ms) send() waits for the first cluster server to become available
32
+ * before rejecting, when the cluster is still empty. Configurable via the
33
+ * IMQ_SEND_INIT_TIMEOUT environment variable, defaults to 30,000.
34
+ */
35
+ const SEND_INIT_TIMEOUT = +(process.env.IMQ_SEND_INIT_TIMEOUT || 0) || 30000;
36
36
  /**
37
37
  * Class ClusteredRedisQueue
38
- * Implements the possibility to scale queues horizontally between several
38
+ Implements the possibility to scale queues horizontally between several
39
39
  * redis instances.
40
40
  */
41
41
  class ClusteredRedisQueue {
42
+ name;
43
+ /**
44
+ * Logger instance associated with this queue instance
45
+ *
46
+ * @type {ILogger}
47
+ */
48
+ logger;
49
+ /**
50
+ * RedisQueue instances collection
51
+ *
52
+ * @type {RedisQueue[]}
53
+ */
54
+ imqs = [];
55
+ /**
56
+ * Options associated with this queue instance
57
+ *
58
+ * @type {IMQOptions}
59
+ */
60
+ options;
61
+ /**
62
+ * Part of options without cluster definitions - which are generic for
63
+ * RedisQueue instances
64
+ *
65
+ * @type {IMQOptions}
66
+ */
67
+ mqOptions;
68
+ /**
69
+ * Cluster servers option definitions
70
+ *
71
+ * @type {IMessageQueueConnection[]}
72
+ */
73
+ servers = [];
74
+ /**
75
+ * Current queue index (round-robin)
76
+ *
77
+ * @type {number}
78
+ */
79
+ currentQueue = 0;
80
+ /**
81
+ * Time (ms) send() waits for the first server when the cluster is empty
82
+ */
83
+ sendInitTimeout = SEND_INIT_TIMEOUT;
84
+ /**
85
+ * Total length of RedisQueue instances
86
+ *
87
+ * @type {number}
88
+ */
89
+ imqLength = 0;
90
+ /**
91
+ * Template EventEmitter instance used to replicate queue EventEmitters when
92
+ * dynamically modifying the cluster
93
+ * @type {EventEmitter}
94
+ * @private
95
+ */
96
+ templateEmitter;
97
+ /**
98
+ * Cluster EventEmitter instance used to notify about changes of
99
+ * cluster servers
100
+ * @type {EventEmitter}
101
+ * @private
102
+ */
103
+ clusterEmitter;
104
+ state = {
105
+ started: false,
106
+ subscription: null,
107
+ };
108
+ initializedClusters = [];
42
109
  /**
43
110
  * Class constructor
44
111
  *
45
- * @constructor
46
112
  * @param {string} name
47
113
  * @param {Partial<IMQOptions>} options
48
- * @param {IMQMode} [mode]
114
+ * @param {IMQMode} [_mode]
49
115
  */
50
- constructor(name, options, mode = _1.IMQMode.BOTH) {
51
- var _a, _b;
116
+ constructor(name, options, _mode = _1.IMQMode.BOTH) {
52
117
  this.name = name;
53
- /**
54
- * RedisQueue instances collection
55
- *
56
- * @type {RedisQueue[]}
57
- */
58
- this.imqs = [];
59
- /**
60
- * Cluster servers option definitions
61
- *
62
- * @type {IMessageQueueConnection[]}
63
- */
64
- // tslint:disable-next-line:completed-docs
65
- this.servers = [];
66
- /**
67
- * Current queue index (round-robin)
68
- *
69
- * @type {number}
70
- */
71
- this.currentQueue = 0;
72
- // noinspection TypeScriptFieldCanBeMadeReadonly
73
- /**
74
- * Total length of RedisQueue instances
75
- *
76
- * @type {number}
77
- */
78
- this.imqLength = 0;
79
- this.state = {
80
- started: false,
81
- subscription: null,
82
- };
83
- this.initializedClusters = [];
84
- this.templateEmitter = new events_1.EventEmitter();
85
- this.clusterEmitter = new events_1.EventEmitter();
86
- this.options = (0, _1.buildOptions)(_1.DEFAULT_IMQ_OPTIONS, options);
87
- // istanbul ignore next
118
+ this.templateEmitter = new node_events_1.EventEmitter();
119
+ this.clusterEmitter = new node_events_1.EventEmitter();
120
+ this.options = (0, helpers_1.buildOptions)(_1.DEFAULT_IMQ_OPTIONS, options);
88
121
  this.logger = this.options.logger || console;
89
- if (!this.options.cluster && !((_a = this.options.clusterManagers) === null || _a === void 0 ? void 0 : _a.length)) {
90
- throw new TypeError('ClusteredRedisQueue: cluster ' +
91
- 'configuration is missing!');
122
+ if (!this.options.cluster && !this.options.clusterManagers?.length) {
123
+ throw new TypeError('ClusteredRedisQueue: cluster ' + 'configuration is missing!');
92
124
  }
93
- this.mqOptions = Object.assign({}, this.options);
94
- const cluster = [...this.mqOptions.cluster || []];
125
+ this.mqOptions = { ...this.options };
126
+ const cluster = [...(this.mqOptions.cluster || [])];
95
127
  delete this.mqOptions.cluster;
96
128
  for (const server of cluster) {
97
129
  this.addServerWithQueueInitializing(server, false);
98
130
  }
99
- if ((_b = this.options.clusterManagers) === null || _b === void 0 ? void 0 : _b.length) {
131
+ if (this.options.clusterManagers?.length) {
100
132
  this.verbose('Initializing cluster managers...');
101
133
  for (const manager of this.options.clusterManagers) {
102
134
  this.initializedClusters.push(manager.init({
@@ -128,30 +160,66 @@ class ClusteredRedisQueue {
128
160
  return await this.batch('stop', 'Stopping clustered redis message queue...');
129
161
  }
130
162
  /**
131
- * Sends a message to given queue name with the given data.
163
+ * Sends a message to a given queue name with the given data.
132
164
  * Supposed to be an async function.
133
165
  *
134
- * @param {string} toQueue - queue name to which message should be sent to
166
+ * @param {string} toQueue - queue name to which a message should be sent to
135
167
  * @param {JsonObject} message - message data
136
168
  * @param {number} [delay] - if specified, a message will be handled in the
137
- * target queue after a specified period of time in milliseconds.
169
+ target queue after a specified period of time in milliseconds.
138
170
  * @param {(err: Error) => void} [errorHandler] - callback called only when
139
- * internal error occurs during message send execution.
171
+ internal error occurs during message send execution.
140
172
  * @returns {Promise<string>} - message identifier
141
173
  */
142
174
  async send(toQueue, message, delay, errorHandler) {
143
175
  if (!this.imqLength) {
144
- return await new Promise(resolve => this.clusterEmitter.once('initialized', async ({ imq }) => {
145
- resolve(await imq.send(toQueue, message, delay, errorHandler));
146
- }));
176
+ return this.sendWhenInitialized(toQueue, message, delay, errorHandler);
147
177
  }
148
- if (this.currentQueue >= this.imqLength) {
149
- this.currentQueue = 0;
178
+ const imq = this.selectQueue();
179
+ return imq.send(toQueue, message, delay, errorHandler);
180
+ }
181
+ /**
182
+ * Picks the next queue for a round-robin send, preferring an instance
183
+ * whose redis connection is currently ready so messages are not routed
184
+ * to a host that is known to be down. Falls back to the plain
185
+ * round-robin pick when no instance reports are ready.
186
+ *
187
+ * @returns {RedisQueue}
188
+ */
189
+ selectQueue() {
190
+ const count = this.imqLength;
191
+ const start = this.currentQueue % count;
192
+ for (let offset = 0; offset < count; offset++) {
193
+ const index = (start + offset) % count;
194
+ const candidate = this.imqs[index];
195
+ if (candidate.available) {
196
+ this.currentQueue = index + 1;
197
+ return candidate;
198
+ }
150
199
  }
151
- const imq = this.imqs[this.currentQueue];
152
- const id = await imq.send(toQueue, message, delay, errorHandler);
153
- this.currentQueue++;
154
- return id;
200
+ this.currentQueue = start + 1;
201
+ return this.imqs[start];
202
+ }
203
+ /**
204
+ * Sends a message once the first cluster server becomes available.
205
+ * Rejects (rather than hanging forever) if none appears within the
206
+ * configured timeout and propagates any sent failure.
207
+ *
208
+ * @returns {Promise<string>}
209
+ */
210
+ sendWhenInitialized(toQueue, message, delay, errorHandler) {
211
+ return new Promise((resolve, reject) => {
212
+ const onInitialized = ({ imq }) => {
213
+ clearTimeout(timer);
214
+ imq.send(toQueue, message, delay, errorHandler).then(resolve, reject);
215
+ };
216
+ const timer = setTimeout(() => {
217
+ this.clusterEmitter.removeListener('initialized', onInitialized);
218
+ reject(new Error('ClusteredRedisQueue: no cluster server became ' +
219
+ 'available to send the message'));
220
+ }, this.sendInitTimeout);
221
+ this.clusterEmitter.once('initialized', onInitialized);
222
+ });
155
223
  }
156
224
  /**
157
225
  * Safely destroys the current queue, unregistered all set event
@@ -161,44 +229,17 @@ class ClusteredRedisQueue {
161
229
  * @returns {Promise<void>}
162
230
  */
163
231
  async destroy() {
164
- var _a, e_1, _b, _c, _d, e_2, _e, _f;
165
- var _g;
166
232
  this.state.started = false;
167
233
  await this.batch('destroy', 'Destroying clustered redis message queue...');
168
- if (!((_g = this.options.clusterManagers) === null || _g === void 0 ? void 0 : _g.length)) {
234
+ if (!this.options.clusterManagers?.length) {
169
235
  return;
170
236
  }
171
- try {
172
- for (var _h = true, _j = __asyncValues(this.options.clusterManagers), _k; _k = await _j.next(), _a = _k.done, !_a; _h = true) {
173
- _c = _k.value;
174
- _h = false;
175
- const manager = _c;
176
- try {
177
- for (var _l = true, _m = (e_2 = void 0, __asyncValues(this.initializedClusters)), _o; _o = await _m.next(), _d = _o.done, !_d; _l = true) {
178
- _f = _o.value;
179
- _l = false;
180
- const cluster = _f;
181
- await manager.remove(cluster);
182
- }
183
- }
184
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
185
- finally {
186
- try {
187
- if (!_l && !_d && (_e = _m.return)) await _e.call(_m);
188
- }
189
- finally { if (e_2) throw e_2.error; }
190
- }
237
+ for (const manager of this.options.clusterManagers) {
238
+ for (const cluster of this.initializedClusters) {
239
+ await manager.remove(cluster);
191
240
  }
192
241
  }
193
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
194
- finally {
195
- try {
196
- if (!_h && !_a && (_b = _j.return)) await _b.call(_j);
197
- }
198
- finally { if (e_1) throw e_1.error; }
199
- }
200
242
  }
201
- // noinspection JSUnusedGlobalSymbols
202
243
  /**
203
244
  * Clears queue data in queue host application.
204
245
  * Supposed to be an async function.
@@ -224,122 +265,100 @@ class ClusteredRedisQueue {
224
265
  /**
225
266
  * Batch imq action processing on all registered imqs at once
226
267
  *
227
- * @access private
228
268
  * @param {string} action
229
269
  * @param {string} message
230
- * @return {Promise<this>}
270
+ * @returns {Promise<this>}
231
271
  */
232
272
  async batch(action, message) {
233
273
  this.logger.info(message);
234
274
  const promises = [];
235
275
  for (const imq of this.imqs) {
236
- promises.push(imq[action]());
276
+ const run = imq[action];
277
+ promises.push(run.call(imq));
237
278
  }
238
279
  await Promise.all(promises);
239
280
  return this;
240
281
  }
241
- /* tslint:disable */
242
282
  // EventEmitter interface
243
- // istanbul ignore next
244
- on(...args) {
283
+ /**
284
+ * Applies the named EventEmitter method to every underlying emitter,
285
+ * forwarding the call across the whole cluster. Dispatch is reflective
286
+ * (method chosen by name), so a single contained cast bridges the dynamic
287
+ * call while the public method signatures below stay fully typed.
288
+ *
289
+ * @template K - EventEmitter method name
290
+ * @param {K} method - name of the EventEmitter method to invoke
291
+ * @param {any[]} args - arguments to pass to the method
292
+ * @returns {unknown[]} - results from each emitter call
293
+ */
294
+ applyToEmitters(method, args) {
295
+ const results = [];
245
296
  for (const imq of this.eventEmitters()) {
246
- imq.on.apply(imq, args);
297
+ const fn = imq[method];
298
+ results.push(fn.apply(imq, args));
247
299
  }
300
+ return results;
301
+ }
302
+ on(...args) {
303
+ this.applyToEmitters('on', args);
248
304
  return this;
249
305
  }
250
- // istanbul ignore next
251
- // noinspection JSUnusedGlobalSymbols
252
306
  off(...args) {
253
- for (const imq of this.eventEmitters()) {
254
- imq.off.apply(imq, args);
255
- }
307
+ this.applyToEmitters('off', args);
256
308
  return this;
257
309
  }
258
- // istanbul ignore next
259
310
  once(...args) {
260
- for (const imq of this.eventEmitters()) {
261
- imq.once.apply(imq, args);
262
- }
311
+ this.applyToEmitters('once', args);
263
312
  return this;
264
313
  }
265
- // istanbul ignore next
266
314
  addListener(...args) {
267
- for (const imq of this.eventEmitters()) {
268
- imq.addListener.apply(imq, args);
269
- }
315
+ this.applyToEmitters('addListener', args);
270
316
  return this;
271
317
  }
272
- // istanbul ignore next
273
318
  removeListener(...args) {
274
- for (const imq of this.eventEmitters()) {
275
- imq.removeListener.apply(imq, args);
276
- }
319
+ this.applyToEmitters('removeListener', args);
277
320
  return this;
278
321
  }
279
- // istanbul ignore next
280
322
  removeAllListeners(...args) {
281
- for (const imq of this.eventEmitters()) {
282
- imq.removeAllListeners.apply(imq, args);
283
- }
323
+ this.applyToEmitters('removeAllListeners', args);
284
324
  return this;
285
325
  }
286
- // istanbul ignore next
287
326
  prependListener(...args) {
288
- for (const imq of this.eventEmitters()) {
289
- imq.prependListener.apply(imq, args);
290
- }
327
+ this.applyToEmitters('prependListener', args);
291
328
  return this;
292
329
  }
293
- // istanbul ignore next
294
330
  prependOnceListener(...args) {
295
- for (const imq of this.eventEmitters()) {
296
- imq.prependOnceListener.apply(imq, args);
297
- }
331
+ this.applyToEmitters('prependOnceListener', args);
298
332
  return this;
299
333
  }
300
- // istanbul ignore next
301
334
  setMaxListeners(...args) {
302
- for (const imq of this.eventEmitters()) {
303
- imq.setMaxListeners.apply(imq, args);
304
- }
335
+ this.applyToEmitters('setMaxListeners', args);
305
336
  return this;
306
337
  }
307
- // istanbul ignore next
338
+ // Aggregates listeners across every underlying emitter, so the result is
339
+ // an untyped union rather than Node's per-emitter conditional listener type.
308
340
  listeners(...args) {
309
- let listeners = [];
310
- for (const imq of this.eventEmitters()) {
311
- listeners = listeners.concat(imq.listeners.apply(imq, args));
312
- }
313
- return listeners;
341
+ return this.applyToEmitters('listeners', args).flat();
314
342
  }
315
- // istanbul ignore next
316
343
  rawListeners(...args) {
317
- let rawListeners = [];
318
- for (const imq of this.eventEmitters()) {
319
- rawListeners = rawListeners.concat(imq.rawListeners.apply(imq, args));
320
- }
321
- return rawListeners;
344
+ return this.applyToEmitters('rawListeners', args).flat();
322
345
  }
323
- // istanbul ignore next
324
346
  getMaxListeners() {
325
347
  return this.templateEmitter.getMaxListeners();
326
348
  }
327
- // istanbul ignore next
328
349
  emit(...args) {
329
- for (const imq of this.eventEmitters()) {
330
- imq.emit.apply(imq, args);
331
- }
350
+ this.applyToEmitters('emit', args);
332
351
  return true;
333
352
  }
334
- // istanbul ignore next
335
- eventNames(...args) {
336
- return this.templateEmitter.eventNames.apply(this.imqs[0], args);
353
+ eventNames() {
354
+ const source = this.imqs[0] || this.templateEmitter;
355
+ return source.eventNames();
337
356
  }
338
- // istanbul ignore next
339
357
  listenerCount(...args) {
340
- return this.templateEmitter.listenerCount.apply(this.imqs[0], args);
358
+ const source = this.imqs[0] || this.templateEmitter;
359
+ const fn = source.listenerCount;
360
+ return fn.apply(source, args);
341
361
  }
342
- // istanbul ignore next
343
362
  async publish(data, toName) {
344
363
  const promises = [];
345
364
  for (const imq of this.imqs) {
@@ -347,7 +366,6 @@ class ClusteredRedisQueue {
347
366
  }
348
367
  await Promise.all(promises);
349
368
  }
350
- // istanbul ignore next
351
369
  async subscribe(channel, handler) {
352
370
  this.state.subscription = { channel, handler };
353
371
  const promises = [];
@@ -356,7 +374,6 @@ class ClusteredRedisQueue {
356
374
  }
357
375
  await Promise.all(promises);
358
376
  }
359
- // istanbul ignore next
360
377
  async unsubscribe() {
361
378
  this.state.subscription = null;
362
379
  const promises = [];
@@ -390,7 +407,9 @@ class ClusteredRedisQueue {
390
407
  const imqToRemove = remove.imq;
391
408
  if (imqToRemove) {
392
409
  this.imqs = this.imqs.filter(imq => imqToRemove.redisKey !== imq.redisKey);
393
- imqToRemove.destroy().catch();
410
+ imqToRemove
411
+ .destroy()
412
+ .catch((err) => this.verbose(`Error destroying removed server: ${err}`));
394
413
  }
395
414
  this.imqLength = this.imqs.length;
396
415
  this.servers = this.servers.filter(existing => !ClusteredRedisQueue.matchServers(existing, server));
@@ -409,8 +428,9 @@ class ClusteredRedisQueue {
409
428
  host: server.host,
410
429
  port: server.port,
411
430
  };
412
- const opts = Object.assign(Object.assign({}, this.mqOptions), newServer);
431
+ const opts = { ...this.mqOptions, ...newServer };
413
432
  const imq = new _1.RedisQueue(this.name, opts);
433
+ (0, helpers_1.copyEventEmitter)(this.templateEmitter, imq);
414
434
  if (initializeQueue) {
415
435
  this.initializeQueue(imq).then(() => {
416
436
  this.clusterEmitter.emit('initialized', {
@@ -430,7 +450,6 @@ class ClusteredRedisQueue {
430
450
  return [...this.imqs, this.templateEmitter];
431
451
  }
432
452
  async initializeQueue(imq) {
433
- (0, _1.copyEventEmitter)(this.templateEmitter, imq);
434
453
  this.verbose(`Initializing queue with state: ${JSON.stringify(this.state)}`);
435
454
  if (this.state.started) {
436
455
  await imq.start();
@@ -443,8 +462,7 @@ class ClusteredRedisQueue {
443
462
  return this.servers.find(existing => ClusteredRedisQueue.matchServers(existing, server));
444
463
  }
445
464
  static matchServers(source, target) {
446
- const sameAddress = target.host === source.host
447
- && target.port === source.port;
465
+ const sameAddress = target.host === source.host && target.port === source.port;
448
466
  if (!target.id && !source.id) {
449
467
  return sameAddress;
450
468
  }