@imqueue/core 2.0.10 → 2.0.13

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.10",
3
+ "version": "2.0.13",
4
4
  "description": "Simple JSON-based messaging queue for inter service communication",
5
5
  "keywords": [
6
6
  "message-queue",
@@ -75,7 +75,7 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
75
75
  *
76
76
  * @type {number}
77
77
  */
78
- private queueLength;
78
+ private imqLength;
79
79
  /**
80
80
  * Template EventEmitter instance used to replicate queue EventEmitters when
81
81
  * dynamically modifying the cluster
@@ -143,6 +143,7 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
143
143
  * @returns {Promise<ClusteredRedisQueue>}
144
144
  */
145
145
  clear(): Promise<ClusteredRedisQueue>;
146
+ queueLength(): Promise<number>;
146
147
  /**
147
148
  * Batch imq action processing on all registered imqs at once
148
149
  *
@@ -75,7 +75,7 @@ class ClusteredRedisQueue {
75
75
  *
76
76
  * @type {number}
77
77
  */
78
- this.queueLength = 0;
78
+ this.imqLength = 0;
79
79
  this.state = {
80
80
  started: false,
81
81
  subscription: null,
@@ -139,12 +139,12 @@ class ClusteredRedisQueue {
139
139
  * @returns {Promise<string>} - message identifier
140
140
  */
141
141
  async send(toQueue, message, delay, errorHandler) {
142
- if (!this.queueLength) {
142
+ if (!this.imqLength) {
143
143
  return await new Promise(resolve => this.clusterEmitter.once('initialized', async ({ imq }) => {
144
144
  resolve(await imq.send(toQueue, message, delay, errorHandler));
145
145
  }));
146
146
  }
147
- if (this.currentQueue >= this.queueLength) {
147
+ if (this.currentQueue >= this.imqLength) {
148
148
  this.currentQueue = 0;
149
149
  }
150
150
  const imq = this.imqs[this.currentQueue];
@@ -207,6 +207,14 @@ class ClusteredRedisQueue {
207
207
  async clear() {
208
208
  return await this.batch('clear', 'Clearing clustered redis message queue...');
209
209
  }
210
+ async queueLength() {
211
+ const promises = [];
212
+ for (const imq of this.imqs) {
213
+ promises.push(imq.queueLength());
214
+ }
215
+ const lengths = await Promise.all(promises);
216
+ return lengths.reduce((total, length) => total + length, 0);
217
+ }
210
218
  /**
211
219
  * Batch imq action processing on all registered imqs at once
212
220
  *
@@ -376,7 +384,7 @@ class ClusteredRedisQueue {
376
384
  this.imqs = this.imqs.filter(imq => imqToRemove.redisKey !== imq.redisKey);
377
385
  imqToRemove.destroy().catch();
378
386
  }
379
- this.queueLength = this.imqs.length;
387
+ this.imqLength = this.imqs.length;
380
388
  this.servers = this.servers.filter(existing => !ClusteredRedisQueue.matchServers(existing, server));
381
389
  this.clusterEmitter.emit('remove', {
382
390
  server: remove,
@@ -407,7 +415,7 @@ class ClusteredRedisQueue {
407
415
  this.imqs.push(imq);
408
416
  this.servers.push(newServer);
409
417
  this.clusterEmitter.emit('add', { server: newServer, imq });
410
- this.queueLength = this.imqs.length;
418
+ this.imqLength = this.imqs.length;
411
419
  return newServer;
412
420
  }
413
421
  eventEmitters() {
@@ -369,4 +369,11 @@ export interface IMessageQueue extends EventEmitter<EventMap> {
369
369
  * @returns {Promise<IMessageQueue>}
370
370
  */
371
371
  clear(): Promise<IMessageQueue>;
372
+ /**
373
+ * Retrieves the current count of messages in the queue.
374
+ * Supposed to be an async function.
375
+ *
376
+ * @returns {Promise<number>}
377
+ */
378
+ queueLength(): Promise<number>;
372
379
  }
@@ -194,11 +194,17 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
194
194
  */
195
195
  destroy(): Promise<void>;
196
196
  /**
197
- * Clears queue data in redis;
197
+ * Clears queue data in redis
198
198
  *
199
199
  * @returns {Promise<void>}
200
200
  */
201
201
  clear(): Promise<RedisQueue>;
202
+ /**
203
+ * Retrieves the current count of messages in the queue
204
+ *
205
+ * @returns {Promise<number>}
206
+ */
207
+ queueLength(): Promise<number>;
202
208
  /**
203
209
  * Returns true if publisher mode is enabled on this queue, false otherwise.
204
210
  *
package/src/RedisQueue.js CHANGED
@@ -356,7 +356,7 @@ class RedisQueue extends events_1.EventEmitter {
356
356
  await this.unsubscribe();
357
357
  }
358
358
  /**
359
- * Clears queue data in redis;
359
+ * Clears queue data in redis
360
360
  *
361
361
  * @returns {Promise<void>}
362
362
  */
@@ -378,6 +378,17 @@ class RedisQueue extends events_1.EventEmitter {
378
378
  }
379
379
  return this;
380
380
  }
381
+ /**
382
+ * Retrieves the current count of messages in the queue
383
+ *
384
+ * @returns {Promise<number>}
385
+ */
386
+ async queueLength() {
387
+ if (!this.writer) {
388
+ return 0;
389
+ }
390
+ return this.writer.llen(this.key);
391
+ }
381
392
  /**
382
393
  * Returns true if publisher mode is enabled on this queue, false otherwise.
383
394
  *
@@ -512,6 +523,8 @@ class RedisQueue extends events_1.EventEmitter {
512
523
  retryStrategy: this.retryStrategy(context),
513
524
  autoResubscribe: true,
514
525
  enableReadyCheck: true,
526
+ enableOfflineQueue: true,
527
+ autoResendUnfulfilledCommands: true,
515
528
  });
516
529
  context[channel] = (0, _1.makeRedisSafe)(redis);
517
530
  context[channel].__imq = true;
@@ -1080,6 +1093,12 @@ __decorate([
1080
1093
  __metadata("design:paramtypes", []),
1081
1094
  __metadata("design:returntype", Promise)
1082
1095
  ], RedisQueue.prototype, "clear", null);
1096
+ __decorate([
1097
+ (0, _1.profile)(),
1098
+ __metadata("design:type", Function),
1099
+ __metadata("design:paramtypes", []),
1100
+ __metadata("design:returntype", Promise)
1101
+ ], RedisQueue.prototype, "queueLength", null);
1083
1102
  __decorate([
1084
1103
  (0, _1.profile)(),
1085
1104
  __metadata("design:type", Function),
@@ -59,16 +59,9 @@ export declare class UDPClusterManager extends ClusterManager {
59
59
  private readonly options;
60
60
  private workerKey;
61
61
  private worker;
62
- static selectNetworkInterface(options?: any): string;
63
62
  constructor(options?: Partial<UDPClusterManagerOptions>);
64
63
  private static free;
65
64
  private startWorkerListener;
66
- static processMessageOnClusterForAll(self: UDPClusterManager, message: any): Promise<void>;
67
- static processMessageOnCluster(cluster: any, message: any, aliveTimeoutCorrection?: number): void;
68
- static serverAliveWait(cluster: any, server: any, aliveTimeoutCorrection?: number, message?: any): void;
69
- static parseBroadcastedMessage(input: Buffer): any;
70
- startListening(options?: any): void;
71
- listenBroadcastedMessages(_options: any): void;
72
65
  destroy(): Promise<void>;
73
66
  static destroySocket(key: string, socket?: any): Promise<void>;
74
67
  private static destroyWorker;
@@ -27,8 +27,6 @@ exports.UDPClusterManager = exports.DEFAULT_UDP_CLUSTER_MANAGER_OPTIONS = void 0
27
27
  const ClusterManager_1 = require("./ClusterManager");
28
28
  const worker_threads_1 = require("worker_threads");
29
29
  const path = require("path");
30
- const dgram_1 = require("dgram");
31
- const os_1 = require("os");
32
30
  process.setMaxListeners(10000);
33
31
  exports.DEFAULT_UDP_CLUSTER_MANAGER_OPTIONS = {
34
32
  port: 63000,
@@ -36,30 +34,6 @@ exports.DEFAULT_UDP_CLUSTER_MANAGER_OPTIONS = {
36
34
  aliveTimeoutCorrection: 5000,
37
35
  };
38
36
  class UDPClusterManager extends ClusterManager_1.ClusterManager {
39
- // Selects a network interface address matching the broadcast prefix; falls back to 0.0.0.0
40
- static selectNetworkInterface(options = {}) {
41
- const interfaces = (0, os_1.networkInterfaces)();
42
- const broadcastAddress = options.broadcastAddress || options.address;
43
- const limited = options.limitedBroadcastAddress || options.limitedAddress;
44
- const defaultAddress = '0.0.0.0';
45
- if (!broadcastAddress || broadcastAddress === limited) {
46
- return defaultAddress;
47
- }
48
- for (const key in interfaces) {
49
- if (!interfaces[key]) {
50
- continue;
51
- }
52
- for (const net of interfaces[key]) {
53
- const shouldBeSelected = net.family === 'IPv4'
54
- && typeof net.address === 'string'
55
- && net.address.startsWith(String(broadcastAddress).replace(/\.255/g, ''));
56
- if (shouldBeSelected) {
57
- return net.address;
58
- }
59
- }
60
- }
61
- return defaultAddress;
62
- }
63
37
  constructor(options) {
64
38
  super();
65
39
  this.options = Object.assign(Object.assign({}, exports.DEFAULT_UDP_CLUSTER_MANAGER_OPTIONS), options || {});
@@ -70,158 +44,47 @@ class UDPClusterManager extends ClusterManager_1.ClusterManager {
70
44
  }
71
45
  static async free() {
72
46
  const workerKeys = Object.keys(UDPClusterManager.workers);
73
- const socketKeys = Object.keys(UDPClusterManager.sockets || {});
74
- await Promise.all([
75
- ...workerKeys.map(workerKey => UDPClusterManager.destroyWorker(workerKey, UDPClusterManager.workers[workerKey])),
76
- ...socketKeys.map(socketKey => UDPClusterManager.destroySocket(socketKey, UDPClusterManager.sockets[socketKey])),
77
- ]);
78
- // clear sockets map
79
- for (const key of socketKeys) {
80
- delete UDPClusterManager.sockets[key];
81
- }
47
+ await Promise.all(workerKeys.map(workerKey => UDPClusterManager.destroyWorker(workerKey, UDPClusterManager.workers[workerKey])));
82
48
  }
83
49
  startWorkerListener() {
84
50
  this.workerKey = `${this.options.address}:${this.options.port}`;
85
51
  if (UDPClusterManager.workers[this.workerKey]) {
86
52
  this.worker = UDPClusterManager.workers[this.workerKey];
87
- }
88
- else {
89
- this.worker = new worker_threads_1.Worker(path.join(__dirname, './UDPWorker.js'), {
90
- workerData: this.options,
91
- });
92
- this.worker.on('message', message => {
93
- var _a;
94
- const [className, method] = (_a = message.type) === null || _a === void 0 ? void 0 : _a.split(':');
95
- if (className !== 'cluster') {
96
- return;
97
- }
98
- return this.anyCluster(cluster => {
99
- const clusterMethod = cluster[method];
100
- if (!clusterMethod) {
101
- return;
102
- }
103
- clusterMethod(message.server);
104
- });
105
- });
106
- UDPClusterManager.workers[this.workerKey] = this.worker;
107
- }
108
- // Legacy in-process UDP listener for unit tests
109
- {
110
- let socket = UDPClusterManager.sockets[this.workerKey];
111
- if (!socket) {
112
- socket = (0, dgram_1.createSocket)({ type: 'udp4', reuseAddr: true, reusePort: true });
113
- const address = UDPClusterManager.selectNetworkInterface(this.options);
114
- UDPClusterManager.sockets[this.workerKey] = socket.bind(this.options.port, address);
115
- }
116
- socket.on('message', (buffer) => {
117
- try {
118
- const [name, id, type, addr = '', timeout = '0'] = buffer.toString().split('\t');
119
- const [host, port] = addr.split(':');
120
- const message = {
121
- id,
122
- name,
123
- type: String(type || '').toLowerCase(),
124
- host,
125
- port: parseInt(port, 10),
126
- timeout: parseFloat(timeout) * 1000,
127
- };
128
- UDPClusterManager.processMessageOnClusterForAll(this, message);
129
- }
130
- catch ( /* ignore parse errors in tests */_a) { /* ignore parse errors in tests */ }
131
- });
132
- }
133
- }
134
- // Backwards-compatible helpers used by unit tests for branch coverage
135
- // Process a message across all initialized clusters
136
- static async processMessageOnClusterForAll(self, message) {
137
- await self.anyCluster(cluster => UDPClusterManager.processMessageOnCluster(cluster, message, self.options.aliveTimeoutCorrection));
138
- }
139
- // Process a single message on the provided cluster instance
140
- static processMessageOnCluster(cluster, message, aliveTimeoutCorrection = 0) {
141
- if (!cluster || !message) {
142
53
  return;
143
54
  }
144
- const type = String(message.type || '').toLowerCase();
145
- if (type === 'up') {
146
- const existing = typeof cluster.find === 'function'
147
- ? cluster.find(message, true)
148
- : undefined;
149
- if (existing) {
150
- UDPClusterManager.serverAliveWait(cluster, existing, aliveTimeoutCorrection, message);
151
- }
152
- else if (typeof cluster.add === 'function') {
153
- cluster.add(message);
154
- }
155
- }
156
- else if (type === 'down') {
157
- if (typeof cluster.remove === 'function') {
158
- cluster.remove(message);
55
+ this.worker = new worker_threads_1.Worker(path.join(__dirname, './UDPWorker.js'), {
56
+ workerData: this.options,
57
+ });
58
+ this.worker.on('message', message => {
59
+ var _a;
60
+ const [className, method] = (_a = message.type) === null || _a === void 0 ? void 0 : _a.split(':');
61
+ if (className !== 'cluster') {
62
+ return;
159
63
  }
160
- }
161
- }
162
- // Starts a timer to verify that the server stays alive; returns early if timeout is non-positive
163
- static serverAliveWait(cluster, server, aliveTimeoutCorrection = 0, message) {
164
- const baseTimeout = message && typeof message.timeout === 'number'
165
- ? message.timeout
166
- : 0;
167
- const effective = baseTimeout + (aliveTimeoutCorrection !== null && aliveTimeoutCorrection !== void 0 ? aliveTimeoutCorrection : 0);
168
- if (effective <= 0) {
169
- return;
170
- }
171
- server.timer = setTimeout(() => {
172
- // On timer, if server still present, remove it
173
- try {
174
- const exists = typeof (cluster === null || cluster === void 0 ? void 0 : cluster.find) === 'function'
175
- ? cluster.find(message || server, true)
176
- : server;
177
- if (exists && typeof (cluster === null || cluster === void 0 ? void 0 : cluster.remove) === 'function') {
64
+ return this.anyCluster(cluster => {
65
+ if (method === 'add') {
178
66
  try {
179
- const maybePromise = cluster.remove(message || server);
180
- if (maybePromise && typeof maybePromise.then === 'function') {
181
- maybePromise.catch(() => { });
67
+ const existing = typeof cluster.find === 'function'
68
+ ? cluster.find(message.server, true)
69
+ : undefined;
70
+ if (existing) {
71
+ return;
182
72
  }
183
73
  }
184
- catch ( /* ignore sync errors */_a) { /* ignore sync errors */ }
74
+ catch ( /* ignore */_a) { /* ignore */ }
185
75
  }
186
- }
187
- catch ( /* ignore in tests */_b) { /* ignore in tests */ }
188
- }, effective);
189
- // Avoid keeping the event loop alive
190
- try {
191
- if (server.timer && typeof server.timer.unref === 'function') {
192
- server.timer.unref();
193
- }
194
- }
195
- catch ( /* ignore */_a) { /* ignore */ }
196
- }
197
- // Parses a UDP broadcast message Buffer into a normalized object
198
- static parseBroadcastedMessage(input) {
199
- const [name, id, type, address = '', timeout = '0',] = input.toString().split('\t');
200
- const [host, port] = address.split(':');
201
- return {
202
- id,
203
- name,
204
- type: String(type || '').toLowerCase(),
205
- host,
206
- port: parseInt(port, 10),
207
- timeout: parseFloat(timeout) * 1000,
208
- };
209
- }
210
- // Backwards-compatible method used by tests to trigger listening
211
- startListening(options = {}) {
212
- this.listenBroadcastedMessages(options);
213
- }
214
- // Placeholder for test spying; real listening is initialized in constructor
215
- listenBroadcastedMessages(_options) {
216
- // no-op: socket listeners are set up in startWorkerListener
76
+ const clusterMethod = cluster[method];
77
+ if (!clusterMethod) {
78
+ return;
79
+ }
80
+ clusterMethod(message.server);
81
+ });
82
+ });
83
+ UDPClusterManager.workers[this.workerKey] = this.worker;
217
84
  }
218
85
  async destroy() {
219
86
  await UDPClusterManager.destroyWorker(this.workerKey, this.worker);
220
87
  }
221
- // Cleans up and destroys a given UDP socket reference if present.
222
- // - Removes all listeners (propagates error if removal throws)
223
- // - If socket has close(): waits for close callback, then unrefs and deletes from map
224
- // - If no close(): resolves immediately
225
88
  static async destroySocket(key, socket) {
226
89
  if (!socket) {
227
90
  return;
@@ -232,7 +95,6 @@ class UDPClusterManager extends ClusterManager_1.ClusterManager {
232
95
  }
233
96
  }
234
97
  catch (e) {
235
- // Reject when removeAllListeners throws inside try-block
236
98
  throw e;
237
99
  }
238
100
  if (typeof socket.close !== 'function') {
@@ -254,7 +116,7 @@ class UDPClusterManager extends ClusterManager_1.ClusterManager {
254
116
  if (!worker) {
255
117
  return;
256
118
  }
257
- return new Promise((resolve) => {
119
+ return new Promise(resolve => {
258
120
  const timeout = setTimeout(() => {
259
121
  worker.terminate();
260
122
  resolve();
@@ -273,6 +135,5 @@ class UDPClusterManager extends ClusterManager_1.ClusterManager {
273
135
  }
274
136
  exports.UDPClusterManager = UDPClusterManager;
275
137
  UDPClusterManager.workers = {};
276
- // Map of active sockets keyed by `${address}:${port}` for cleanup
277
138
  UDPClusterManager.sockets = {};
278
139
  //# sourceMappingURL=UDPClusterManager.js.map