@imqueue/core 2.0.25 → 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 +46 -14
  12. package/src/ClusteredRedisQueue.js +196 -169
  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 -1070
  17. package/src/UDPClusterManager.d.ts +110 -26
  18. package/src/UDPClusterManager.js +227 -70
  19. package/src/UDPWorker.d.ts +53 -1
  20. package/src/UDPWorker.js +87 -46
  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
package/src/RedisQueue.js CHANGED
@@ -1,19 +1,43 @@
1
1
  "use strict";
2
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
- return c > 3 && r && Object.defineProperty(target, key, r), r;
2
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
3
+ var useValue = arguments.length > 2;
4
+ for (var i = 0; i < initializers.length; i++) {
5
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
6
+ }
7
+ return useValue ? value : void 0;
8
+ };
9
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
10
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
11
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
12
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
13
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
14
+ var _, done = false;
15
+ for (var i = decorators.length - 1; i >= 0; i--) {
16
+ var context = {};
17
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
18
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
19
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
20
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
21
+ if (kind === "accessor") {
22
+ if (result === void 0) continue;
23
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
24
+ if (_ = accept(result.get)) descriptor.get = _;
25
+ if (_ = accept(result.set)) descriptor.set = _;
26
+ if (_ = accept(result.init)) initializers.unshift(_);
27
+ }
28
+ else if (_ = accept(result)) {
29
+ if (kind === "field") initializers.unshift(_);
30
+ else descriptor[key] = _;
31
+ }
32
+ }
33
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
34
+ done = true;
7
35
  };
8
- var __metadata = (this && this.__metadata) || function (k, v) {
9
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
36
+ var __importDefault = (this && this.__importDefault) || function (mod) {
37
+ return (mod && mod.__esModule) ? mod : { "default": mod };
10
38
  };
11
39
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.RedisQueue = exports.IMQ_SHUTDOWN_TIMEOUT = exports.DEFAULT_IMQ_OPTIONS = void 0;
13
- exports.sha1 = sha1;
14
- exports.intrand = intrand;
15
- exports.pack = pack;
16
- exports.unpack = unpack;
40
+ exports.RedisQueue = exports.IMQ_CONNECTION_QUIT_TIMEOUT = exports.IMQ_SHUTDOWN_TIMEOUT = exports.DEFAULT_IMQ_OPTIONS = void 0;
17
41
  /*!
18
42
  * Fast messaging queue over Redis
19
43
  *
@@ -37,15 +61,39 @@ exports.unpack = unpack;
37
61
  * purchase a proprietary commercial license. Please contact us at
38
62
  * <support@imqueue.com> to get commercial licensing options.
39
63
  */
40
- const crypto = require("crypto");
41
- const events_1 = require("events");
42
- const os = require("os");
43
- const zlib_1 = require("zlib");
64
+ const node_events_1 = require("node:events");
65
+ const node_crypto_1 = require("node:crypto");
66
+ const node_os_1 = require("node:os");
44
67
  const _1 = require(".");
45
- const redis_1 = require("./redis");
68
+ const helpers_1 = require("./helpers");
69
+ const redis_1 = __importDefault(require("./redis"));
46
70
  const RX_CLIENT_NAME = /name=(\S+)/g;
47
71
  const RX_CLIENT_TEST = /:(reader|writer|watcher)/;
48
72
  const RX_CLIENT_CLEAN = /:(reader|writer|watcher).*$/;
73
+ /** Base delay (ms) for the exponential reconnection backoff */
74
+ const RECONNECT_BASE_DELAY = 1000;
75
+ /** Upper cap (ms) for the exponential reconnection backoff */
76
+ const RECONNECT_MAX_DELAY = 30000;
77
+ /** SCAN batch size used while sweeping keys */
78
+ const SCAN_COUNT = '1000';
79
+ /**
80
+ * ioredis retry strategy that disables the built-in reconnection — this
81
+ * queue performs its own capped-backoff reconnection instead.
82
+ *
83
+ * @returns {null}
84
+ */
85
+ function noRetryStrategy() {
86
+ return null;
87
+ }
88
+ /**
89
+ * Resolves after the given number of milliseconds.
90
+ *
91
+ * @param {number} ms
92
+ * @returns {Promise<void>}
93
+ */
94
+ function delay(ms) {
95
+ return new Promise(resolve => setTimeout(resolve, ms));
96
+ }
49
97
  exports.DEFAULT_IMQ_OPTIONS = {
50
98
  host: 'localhost',
51
99
  port: 6379,
@@ -57,640 +105,909 @@ exports.DEFAULT_IMQ_OPTIONS = {
57
105
  safeDeliveryTtl: 5000,
58
106
  useGzip: false,
59
107
  watcherCheckDelay: 5000,
108
+ handleSignals: true,
60
109
  };
61
- exports.IMQ_SHUTDOWN_TIMEOUT = +(process.env.IMQ_SHUTDOWN_TIMEOUT || 1000);
62
- /**
63
- * Returns SHA1 hash sum of the given string
64
- *
65
- * @param {string} str
66
- * @returns {string}
67
- */
68
- function sha1(str) {
69
- const sha = crypto.createHash('sha1');
70
- sha.update(str);
71
- return sha.digest('hex');
72
- }
73
- /**
74
- * Returns random integer between given min and max
75
- *
76
- * @param {number} min
77
- * @param {number} max
78
- * @returns {number}
79
- */
80
- function intrand(min, max) {
81
- return Math.floor(Math.random() * (max - min + 1)) + min;
82
- }
83
- /**
84
- * Compress given data and returns binary string
85
- *
86
- * @param {any} data
87
- * @returns {string}
88
- */
89
- // istanbul ignore next
90
- function pack(data) {
91
- return (0, zlib_1.gzipSync)(JSON.stringify(data)).toString('binary');
92
- }
110
+ exports.IMQ_SHUTDOWN_TIMEOUT = (0, helpers_1.envInt)('IMQ_SHUTDOWN_TIMEOUT', 1000);
93
111
  /**
94
- * Decompress binary string and returns plain data
95
- *
96
- * @param {string} data
97
- * @returns {any}
112
+ * Grace period (ms) for a graceful QUIT to complete before a channel is
113
+ * forcibly disconnected. A reader blocked on an infinite BRPOP/BLMOVE can
114
+ * never let QUIT through, so without this the socket would leak and keep
115
+ * the process alive.
98
116
  */
99
- // istanbul ignore next
100
- function unpack(data) {
101
- return JSON.parse((0, zlib_1.gunzipSync)(Buffer.from(data, 'binary')).toString());
102
- }
103
- const IMQ_REDIS_MAX_LISTENERS_LIMIT = +(process.env.IMQ_REDIS_MAX_LISTENERS_LIMIT || 10000);
117
+ exports.IMQ_CONNECTION_QUIT_TIMEOUT = (0, helpers_1.envInt)('IMQ_CONNECTION_QUIT_TIMEOUT', 1000);
118
+ const IMQ_REDIS_MAX_LISTENERS_LIMIT = (0, helpers_1.envInt)('IMQ_REDIS_MAX_LISTENERS_LIMIT', 10000);
104
119
  /**
105
120
  * Class RedisQueue
106
- * Implements simple messaging queue over redis.
121
+ * Implements a simple messaging queue over redis.
107
122
  */
108
- class RedisQueue extends events_1.EventEmitter {
109
- /**
110
- * @constructor
111
- * @param {string} name
112
- * @param {IMQOptions} [options]
113
- * @param {IMQMode} [mode]
114
- */
115
- constructor(name, options, mode = _1.IMQMode.BOTH) {
116
- super();
117
- this.name = name;
118
- this.mode = mode;
123
+ let RedisQueue = (() => {
124
+ let _classSuper = node_events_1.EventEmitter;
125
+ let _instanceExtraInitializers = [];
126
+ let _stop_decorators;
127
+ let _destroy_decorators;
128
+ let _clear_decorators;
129
+ let _queueLength_decorators;
130
+ let _destroyWatcher_decorators;
131
+ let _destroyWriter_decorators;
132
+ let _destroyChannel_decorators;
133
+ return class RedisQueue extends _classSuper {
134
+ static {
135
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
136
+ _stop_decorators = [(0, _1.profile)()];
137
+ _destroy_decorators = [(0, _1.profile)()];
138
+ _clear_decorators = [(0, _1.profile)()];
139
+ _queueLength_decorators = [(0, _1.profile)()];
140
+ _destroyWatcher_decorators = [(0, _1.profile)()];
141
+ _destroyWriter_decorators = [(0, _1.profile)()];
142
+ _destroyChannel_decorators = [(0, _1.profile)()];
143
+ __esDecorate(this, null, _stop_decorators, { kind: "method", name: "stop", static: false, private: false, access: { has: obj => "stop" in obj, get: obj => obj.stop }, metadata: _metadata }, null, _instanceExtraInitializers);
144
+ __esDecorate(this, null, _destroy_decorators, { kind: "method", name: "destroy", static: false, private: false, access: { has: obj => "destroy" in obj, get: obj => obj.destroy }, metadata: _metadata }, null, _instanceExtraInitializers);
145
+ __esDecorate(this, null, _clear_decorators, { kind: "method", name: "clear", static: false, private: false, access: { has: obj => "clear" in obj, get: obj => obj.clear }, metadata: _metadata }, null, _instanceExtraInitializers);
146
+ __esDecorate(this, null, _queueLength_decorators, { kind: "method", name: "queueLength", static: false, private: false, access: { has: obj => "queueLength" in obj, get: obj => obj.queueLength }, metadata: _metadata }, null, _instanceExtraInitializers);
147
+ __esDecorate(this, null, _destroyWatcher_decorators, { kind: "method", name: "destroyWatcher", static: false, private: false, access: { has: obj => "destroyWatcher" in obj, get: obj => obj.destroyWatcher }, metadata: _metadata }, null, _instanceExtraInitializers);
148
+ __esDecorate(this, null, _destroyWriter_decorators, { kind: "method", name: "destroyWriter", static: false, private: false, access: { has: obj => "destroyWriter" in obj, get: obj => obj.destroyWriter }, metadata: _metadata }, null, _instanceExtraInitializers);
149
+ __esDecorate(this, null, _destroyChannel_decorators, { kind: "method", name: "destroyChannel", static: false, private: false, access: { has: obj => "destroyChannel" in obj, get: obj => obj.destroyChannel }, metadata: _metadata }, null, _instanceExtraInitializers);
150
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
151
+ }
152
+ name = __runInitializers(this, _instanceExtraInitializers);
153
+ mode;
154
+ /**
155
+ * Writer connections collection
156
+ *
157
+ * @type {{}}
158
+ */
159
+ static writers = {};
160
+ /**
161
+ * Watcher connections collection
162
+ *
163
+ * @type {{}}
164
+ */
165
+ static watchers = {};
166
+ /**
167
+ * Number of started queue instances per shared writer connection key
168
+ *
169
+ * @type {{}}
170
+ */
171
+ static writerRefs = {};
172
+ /**
173
+ * All started queue instances within the current process
174
+ *
175
+ * @type {Set<RedisQueue>}
176
+ */
177
+ static instances = new Set();
178
+ /**
179
+ * True when process-level signal handlers were bound
180
+ *
181
+ * @type {boolean}
182
+ */
183
+ static signalsBound = false;
184
+ /**
185
+ * @event message (message: JsonObject, id: string, from: string)
186
+ */
187
+ /**
188
+ * This queue instance options
189
+ *
190
+ * @type {IMQOptions}
191
+ */
192
+ options;
193
+ /**
194
+ * Reader connection associated with this queue instance
195
+ *
196
+ * @type {IRedisClient}
197
+ */
198
+ reader;
199
+ /**
200
+ * Channel connection associated with this queue instance
201
+ * Specially designed for client subscriptions to server-emitted events
202
+ *
203
+ * @type {IRedisClient}
204
+ */
205
+ subscription;
206
+ /**
207
+ * Channel name for subscriptions
208
+ *
209
+ * @type {string}
210
+ */
211
+ subscriptionName;
119
212
  /**
120
213
  * Init state for this queue instance
121
214
  *
122
215
  * @type {boolean}
123
216
  */
124
- this.initialized = false;
217
+ initialized = false;
125
218
  /**
126
219
  * Signals if the queue was destroyed
127
220
  *
128
221
  * @type {boolean}
129
222
  */
130
- this.destroyed = false;
223
+ destroyed = false;
131
224
  /**
132
225
  * True if the current instance owns a watcher connection, false otherwise
133
226
  *
134
227
  * @type {boolean}
135
228
  */
136
- this.watchOwner = false;
229
+ watchOwner = false;
137
230
  /**
138
- * Signals initialization state
231
+ * Subscription handlers registered through subscribe(). Kept to be
232
+ * able to restore the subscription after a connection replacement.
139
233
  *
140
- * @type {boolean}
234
+ * @type {Array<(data: JsonObject) => void>}
235
+ */
236
+ subscriptionHandlers = [];
237
+ /**
238
+ * Will store check interval reference
239
+ */
240
+ safeCheckInterval;
241
+ /**
242
+ * Periodic watcher existence check interval reference
243
+ */
244
+ watcherCheckInterval;
245
+ /**
246
+ * Guards overlapping watcher check runs
247
+ */
248
+ watcherCheckBusy = false;
249
+ /**
250
+ * Connected client keys seen during the previous cleanup sweep. Used
251
+ * to give temporarily disconnected clients one sweep of grace before
252
+ * removing their keys.
253
+ */
254
+ lastConnectedKeys = [];
255
+ /**
256
+ * True while this instance holds a reference to the shared writer
141
257
  */
142
- this.signalsInitialized = false;
258
+ writerAcquired = false;
143
259
  /**
144
260
  * Internal per-channel reconnection state
145
261
  */
146
- this.reconnectTimers = {};
147
- this.reconnectAttempts = {};
148
- this.reconnecting = {};
262
+ reconnectTimers = {};
263
+ reconnectAttempts = {};
264
+ reconnecting = {};
265
+ /**
266
+ * This queue instance unique key (identifier), for internal use
267
+ */
268
+ redisKey;
149
269
  /**
150
- * LUA scripts for redis
270
+ * Lua scripts for redis
151
271
  *
152
272
  * @type {{moveDelayed: {code: string}}}
153
273
  */
154
- // tslint:disable-next-line:completed-docs
155
- this.scripts = {
274
+ scripts = {
156
275
  moveDelayed: {
157
- code: 'local messages = redis.call(' +
158
- '"zrangebyscore", KEYS[1], "-inf", ARGV[1]) ' +
159
- 'local count = table.getn(messages) ' +
160
- 'local message ' +
161
- 'local i = 1 ' +
162
- 'if count > 0 then ' +
163
- 'while messages[i] do ' +
164
- 'redis.call("lpush", KEYS[2], messages[i]) ' +
165
- 'i = i + 1 ' +
166
- 'end ' +
167
- 'redis.call("zremrangebyscore", KEYS[1], ' +
168
- '"-inf", ARGV[1]) ' +
169
- 'end ' +
170
- 'return count',
276
+ code: `
277
+ local messages = redis.call(
278
+ "zrangebyscore", KEYS[1], "-inf", ARGV[1])
279
+ local count = table.getn(messages)
280
+ local message
281
+ local i = 1
282
+ if count > 0 then
283
+ while messages[i] do
284
+ redis.call("lpush", KEYS[2], messages[i])
285
+ i = i + 1
286
+ end
287
+ redis.call("zremrangebyscore", KEYS[1],
288
+ "-inf", ARGV[1])
289
+ end
290
+ return count
291
+ `,
171
292
  },
172
293
  };
173
- this.options = (0, _1.buildOptions)(exports.DEFAULT_IMQ_OPTIONS, options);
174
- /* tslint:disable */
175
- this.pack = this.options.useGzip ? pack : JSON.stringify;
176
- this.unpack = this.options.useGzip ? unpack : JSON.parse;
177
- /* tslint:enable */
178
- this.redisKey = `${this.options.host}:${this.options.port}`;
179
- 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}`);
180
- }
181
- verbose(message) {
182
- if (this.options.verbose) {
183
- this.logger.info(`[IMQ-CORE][${this.name}]: ${message}`);
184
- }
185
- }
186
- /**
187
- * Creates a subscription channel over redis and sets up channel
188
- * data read handler
189
- *
190
- * @param {string} channel
191
- * @param {(data: JsonObject) => any} handler
192
- * @return {Promise<void>}
193
- */
194
- async subscribe(channel, handler) {
195
- // istanbul ignore next
196
- if (!channel) {
197
- throw new TypeError(`${channel}: No subscription channel name provided!`);
294
+ /**
295
+ * Serializes a given data object into string
296
+ *
297
+ * @param {unknown} data
298
+ * @returns {string}
299
+ */
300
+ pack;
301
+ /**
302
+ * Deserialize string data into an object
303
+ *
304
+ * @param {string} data
305
+ * @returns {unknown}
306
+ */
307
+ unpack;
308
+ /**
309
+ * @param {string} name
310
+ * @param {IMQOptions} [options]
311
+ * @param {IMQMode} [mode]
312
+ */
313
+ constructor(name, options, mode = _1.IMQMode.BOTH) {
314
+ super();
315
+ this.name = name;
316
+ this.mode = mode;
317
+ this.options = (0, helpers_1.buildOptions)(exports.DEFAULT_IMQ_OPTIONS, options);
318
+ this.pack = this.options.useGzip ? helpers_1.pack : JSON.stringify;
319
+ this.unpack = this.options.useGzip ? helpers_1.unpack : JSON.parse;
320
+ this.redisKey = `${this.options.host}:${this.options.port}`;
321
+ for (const script of Object.keys(this.scripts)) {
322
+ this.scripts[script].checksum = (0, helpers_1.sha1)(this.scripts[script].code);
323
+ }
324
+ 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}`);
198
325
  }
199
- // istanbul ignore next
200
- if (this.subscriptionName && this.subscriptionName !== channel) {
201
- throw new TypeError(`Invalid channel name provided: expected "${this.subscriptionName}", but "${channel}" given instead!`);
326
+ verbose(message) {
327
+ if (this.options.verbose) {
328
+ this.logger.info(`[IMQ-CORE][${this.name}]: ${message}`);
329
+ }
202
330
  }
203
- else if (!this.subscriptionName) {
204
- this.subscriptionName = channel;
331
+ /**
332
+ * Creates a subscription channel over redis and sets up channel
333
+ * data read handler
334
+ *
335
+ * @param {string} channel
336
+ * @param {(data: JsonObject) => void} handler
337
+ * @returns {Promise<void>}
338
+ */
339
+ async subscribe(channel, handler) {
340
+ if (!channel) {
341
+ throw new TypeError(`${channel}: No subscription channel name provided!`);
342
+ }
343
+ if (this.subscriptionName && this.subscriptionName !== channel) {
344
+ throw new TypeError(`Invalid channel name provided: expected "${this.subscriptionName}", but "${channel}" given instead!`);
345
+ }
346
+ else if (!this.subscriptionName) {
347
+ this.subscriptionName = channel;
348
+ }
349
+ const fcn = `${this.options.prefix}:${this.subscriptionName}`;
350
+ const chan = await this.connect('subscription', this.options);
351
+ await chan.subscribe(fcn);
352
+ this.attachSubscriptionHandler(chan, handler);
353
+ this.subscriptionHandlers.push(handler);
354
+ this.verbose(`Subscribed to ${channel} channel`);
205
355
  }
206
- const fcn = `${this.options.prefix}:${this.subscriptionName}`;
207
- const chan = await this.connect('subscription', this.options);
208
- await chan.subscribe(fcn);
209
- // istanbul ignore next
210
- chan.on('message', (ch, message) => {
211
- if (ch === fcn && typeof handler === 'function') {
212
- handler(JSON.parse(message));
213
- }
214
- this.verbose(`Received message from ${ch} channel, data: ${JSON.stringify(message)}`);
215
- });
216
- this.verbose(`Subscribed to ${channel} channel`);
217
- }
218
- /**
219
- * Closes subscription channel
220
- *
221
- * @return {Promise<void>}
222
- */
223
- async unsubscribe() {
224
- if (this.subscription) {
225
- this.verbose('Initialize unsubscribing...');
226
- try {
227
- if (this.subscriptionName) {
228
- await this.subscription.unsubscribe(`${this.options.prefix}:${this.subscriptionName}`);
229
- this.verbose(`Unsubscribed from ${this.subscriptionName} channel`);
356
+ /**
357
+ * Attaches a subscription message handler to a given channel
358
+ * connection
359
+ *
360
+ * @param {IRedisClient} chan
361
+ * @param {(data: JsonObject) => void} handler
362
+ */
363
+ attachSubscriptionHandler(chan, handler) {
364
+ const fcn = `${this.options.prefix}:${this.subscriptionName}`;
365
+ chan.on('message', (ch, message) => {
366
+ if (ch === fcn && typeof handler === 'function') {
367
+ handler(JSON.parse(message));
230
368
  }
231
- this.subscription.removeAllListeners();
232
- this.subscription.quit();
233
- this.subscription.disconnect(false);
369
+ this.verbose(`Received message from ${ch} channel, data: ${JSON.stringify(message)}`);
370
+ });
371
+ }
372
+ /**
373
+ * Restores the subscription state on a freshly created subscription
374
+ * connection. Used after a connection replacement on reconnection,
375
+ * otherwise the new connection would silently stay unsubscribed.
376
+ *
377
+ * @returns {Promise<void>}
378
+ */
379
+ async restoreSubscription() {
380
+ const chan = this.subscription;
381
+ if (!chan ||
382
+ !this.subscriptionName ||
383
+ !this.subscriptionHandlers.length) {
384
+ return;
234
385
  }
235
- catch (error) {
236
- this.verbose(`Unsubscribe error: ${error}`);
386
+ const fcn = `${this.options.prefix}:${this.subscriptionName}`;
387
+ await chan.subscribe(fcn);
388
+ for (const handler of this.subscriptionHandlers) {
389
+ this.attachSubscriptionHandler(chan, handler);
237
390
  }
391
+ this.verbose(`Restored subscription to ${this.subscriptionName}`);
238
392
  }
239
- this.subscriptionName = undefined;
240
- this.subscription = undefined;
241
- }
242
- /**
243
- * Publishes a message to this queue subscription channel for currently
244
- * subscribed clients.
245
- *
246
- * If toName specified will publish to PubSub with a different name. This
247
- * can be used to implement broadcasting some messages to other subscribers
248
- * on other PubSub channels.
249
- *
250
- * @param {string} [toName]
251
- * @param {JsonObject} data
252
- */
253
- async publish(data, toName) {
254
- if (!this.writer) {
255
- throw new TypeError('Writer is not connected!');
393
+ /**
394
+ * Closes subscription channel
395
+ *
396
+ * @returns {Promise<void>}
397
+ */
398
+ async unsubscribe() {
399
+ if (this.subscription) {
400
+ this.verbose('Initialize unsubscribing...');
401
+ try {
402
+ if (this.subscriptionName) {
403
+ await this.subscription.unsubscribe(`${this.options.prefix}:${this.subscriptionName}`);
404
+ this.verbose(`Unsubscribed from ${this.subscriptionName} channel`);
405
+ }
406
+ this.subscription.removeAllListeners();
407
+ await this.subscription.quit().catch(error => {
408
+ this.verbose(`Unsubscribe quit error: ${error}`);
409
+ });
410
+ this.subscription.disconnect(false);
411
+ }
412
+ catch (error) {
413
+ this.verbose(`Unsubscribe error: ${error}`);
414
+ }
415
+ }
416
+ this.subscriptionName = undefined;
417
+ this.subscription = undefined;
418
+ this.subscriptionHandlers = [];
256
419
  }
257
- const jsonData = JSON.stringify(data);
258
- const name = toName || this.name;
259
- await this.writer.publish(`${this.options.prefix}:${name}`, jsonData);
260
- this.verbose(`Published message to ${name} channel, data: ${jsonData}
420
+ /**
421
+ * Publishes a message to this queue subscription channel for currently
422
+ * subscribed clients.
423
+ *
424
+ * If toName specified will publish to PubSub with a different name. This
425
+ * can be used to implement broadcasting some messages to other subscribers
426
+ * on other PubSub channels.
427
+ *
428
+ * @param {string} [toName]
429
+ * @param {JsonObject} data
430
+ */
431
+ async publish(data, toName) {
432
+ if (!this.writer) {
433
+ throw new TypeError('Writer is not connected!');
434
+ }
435
+ const jsonData = JSON.stringify(data);
436
+ const name = toName || this.name;
437
+ await this.writer.publish(`${this.options.prefix}:${name}`, jsonData);
438
+ this.verbose(`Published message to ${name} channel, data: ${jsonData}
261
439
  `);
262
- }
263
- /**
264
- * Initializes and starts current queue routines
265
- *
266
- * @returns {Promise<RedisQueue>}
267
- */
268
- async start() {
269
- if (!this.name) {
270
- throw new TypeError(`${this.name}: No queue name provided!`);
271
440
  }
272
- if (this.initialized) {
441
+ /**
442
+ * Initializes and starts current queue routines
443
+ *
444
+ * @returns {Promise<RedisQueue>}
445
+ */
446
+ async start() {
447
+ if (!this.name) {
448
+ throw new TypeError(`${this.name}: No queue name provided!`);
449
+ }
450
+ if (this.initialized) {
451
+ return this;
452
+ }
453
+ this.destroyed = false;
454
+ const connPromises = [];
455
+ if (!this.reader && this.isWorker()) {
456
+ this.verbose('Initializing reader...');
457
+ connPromises.push(this.connect('reader', this.options));
458
+ }
459
+ if (!this.writer) {
460
+ this.verbose('Initializing writer...');
461
+ connPromises.push(this.connect('writer', this.options));
462
+ }
463
+ await Promise.all(connPromises);
464
+ this.verbose('Connections initialized');
465
+ RedisQueue.instances.add(this);
466
+ if (this.options.handleSignals !== false) {
467
+ RedisQueue.bindSignals();
468
+ }
469
+ if (!this.writerAcquired) {
470
+ RedisQueue.writerRefs[this.redisKey] =
471
+ (RedisQueue.writerRefs[this.redisKey] || 0) + 1;
472
+ this.writerAcquired = true;
473
+ }
474
+ await this.initWatcher();
475
+ this.startWatcherCheck();
476
+ this.initialized = true;
273
477
  return this;
274
478
  }
275
- this.destroyed = false;
276
- const connPromises = [];
277
- // istanbul ignore next
278
- if (!this.reader && this.isWorker()) {
279
- this.verbose('Initializing reader...');
280
- connPromises.push(this.connect('reader', this.options));
281
- }
282
- if (!this.writer) {
283
- this.verbose('Initializing writer...');
284
- connPromises.push(this.connect('writer', this.options));
285
- }
286
- await Promise.all(connPromises);
287
- this.verbose('Connections initialized');
288
- if (!this.signalsInitialized) {
289
- this.verbose('Setting up OS signal handlers...');
290
- // istanbul ignore next
291
- const free = async () => {
292
- let exitCode = 0;
293
- setTimeout(() => {
294
- this.verbose(`Shutting down after ${exports.IMQ_SHUTDOWN_TIMEOUT} timeout`);
295
- process.exit(exitCode);
296
- }, exports.IMQ_SHUTDOWN_TIMEOUT);
297
- try {
298
- if (this.watchOwner) {
299
- this.verbose('Freeing watcher lock...');
300
- await this.unlock();
301
- }
302
- }
303
- catch (err) {
304
- this.logger.error(err);
305
- exitCode = 1;
306
- }
479
+ /**
480
+ * Binds process-level signal handlers once per process. On shutdown
481
+ * signals, frees watcher locks held by any queue instance and exits.
482
+ */
483
+ static bindSignals() {
484
+ if (RedisQueue.signalsBound) {
485
+ return;
486
+ }
487
+ RedisQueue.signalsBound = true;
488
+ const free = () => {
489
+ void RedisQueue.freeAndExit();
307
490
  };
308
491
  process.on('SIGTERM', free);
309
492
  process.on('SIGINT', free);
310
493
  process.on('SIGABRT', free);
311
- this.signalsInitialized = true;
312
- this.verbose('OS signal handlers initialized!');
313
- }
314
- await this.initWatcher();
315
- this.initialized = true;
316
- return this;
317
- }
318
- /**
319
- * Sends a given message to a given queue (by name)
320
- *
321
- * @param {string} toQueue
322
- * @param {JsonObject} message
323
- * @param {number} [delay]
324
- * @param {(err: Error) => void} [errorHandler]
325
- * @returns {Promise<RedisQueue>}
326
- */
327
- async send(toQueue, message, delay, errorHandler) {
328
- if (!this.isPublisher()) {
329
- throw new TypeError('IMQ: Unable to publish in WORKER only mode!');
330
494
  }
331
- // istanbul ignore next
332
- if (!this.writer) {
333
- await this.start();
495
+ /**
496
+ * Frees watcher locks held by all started queue instances and exits
497
+ * the process, forcing exit after IMQ_SHUTDOWN_TIMEOUT at the latest.
498
+ *
499
+ * @returns {Promise<void>}
500
+ */
501
+ static async freeAndExit() {
502
+ let exitCode = 0;
503
+ const timer = setTimeout(() => {
504
+ process.exit(exitCode || 1);
505
+ }, exports.IMQ_SHUTDOWN_TIMEOUT);
506
+ await Promise.all([...RedisQueue.instances]
507
+ .filter(queue => queue.watchOwner)
508
+ .map(queue => queue.unlock().catch(err => {
509
+ queue.logger.error(err);
510
+ exitCode = 1;
511
+ })));
512
+ clearTimeout(timer);
513
+ process.exit(exitCode);
334
514
  }
335
- if (!this.writer) {
336
- throw new TypeError('IMQ: unable to initialize queue!');
515
+ /**
516
+ * Starts a periodic check ensuring a watcher connection exists across
517
+ * the queue network, re-electing an owner when the previous one died.
518
+ * Also serves as a polling fallback moving due to delayed messages when
519
+ * keyspace notifications are unavailable.
520
+ */
521
+ startWatcherCheck() {
522
+ if (this.watcherCheckInterval || !this.options.watcherCheckDelay) {
523
+ return;
524
+ }
525
+ this.watcherCheckInterval = setInterval(this.runWatcherCheck.bind(this), this.options.watcherCheckDelay);
526
+ this.watcherCheckInterval.unref();
337
527
  }
338
- const id = (0, _1.uuid)();
339
- const data = { id, message, from: this.name };
340
- const key = `${this.options.prefix}:${toQueue}`;
341
- const packet = this.pack(data);
342
- const cb = (error, op) => {
343
- // istanbul ignore next
344
- if (error) {
345
- this.verbose(`Writer ${op} error: ${error}`);
346
- if (errorHandler) {
347
- errorHandler(error);
528
+ /**
529
+ * A single watcher-existence check tick: re-elects a watcher owner when
530
+ * none exists and moves due to delayed messages as a keyspace-notification
531
+ * fallback. Errors are contained so the interval never crashes.
532
+ *
533
+ * @returns {Promise<void>}
534
+ */
535
+ async runWatcherCheck() {
536
+ if (this.watcherCheckBusy || this.destroyed || !this.writer) {
537
+ return;
538
+ }
539
+ this.watcherCheckBusy = true;
540
+ try {
541
+ if (!(await this.watcherCount())) {
542
+ await this.initWatcher();
543
+ }
544
+ if (this.isWorker()) {
545
+ await this.processDelayed(this.key);
348
546
  }
349
547
  }
350
- };
351
- if (delay) {
352
- this.writer.zadd(`${key}:delayed`, Date.now() + delay, packet, (err) => {
353
- // istanbul ignore next
354
- if (err) {
355
- cb(err, 'ZADD');
356
- return;
548
+ catch (err) {
549
+ this.verbose(`Watcher check error: ${err}`);
550
+ }
551
+ finally {
552
+ this.watcherCheckBusy = false;
553
+ }
554
+ }
555
+ /**
556
+ * Stops the periodic watcher check
557
+ */
558
+ stopWatcherCheck() {
559
+ if (this.watcherCheckInterval) {
560
+ clearInterval(this.watcherCheckInterval);
561
+ this.watcherCheckInterval = undefined;
562
+ }
563
+ }
564
+ /**
565
+ * Sends a given message to a given queue (by name)
566
+ *
567
+ * @param {string} toQueue
568
+ * @param {JsonObject} message
569
+ * @param {number} [delay]
570
+ * @param {(err: Error) => void} [errorHandler]
571
+ * @returns {Promise<RedisQueue>}
572
+ */
573
+ async send(toQueue, message, delay, errorHandler) {
574
+ if (!this.isPublisher()) {
575
+ throw new TypeError('IMQ: Unable to publish in WORKER only mode!');
576
+ }
577
+ if (!this.writer) {
578
+ await this.start();
579
+ }
580
+ if (!this.writer) {
581
+ throw new TypeError('IMQ: unable to initialize queue!');
582
+ }
583
+ const id = (0, node_crypto_1.randomUUID)();
584
+ const data = { id, message, from: this.name };
585
+ const key = `${this.options.prefix}:${toQueue}`;
586
+ const packet = this.pack(data);
587
+ const onWriteError = (error, op) => {
588
+ if (error) {
589
+ this.verbose(`Writer ${op} error: ${error}`);
590
+ if (errorHandler) {
591
+ errorHandler(error instanceof Error
592
+ ? error
593
+ : new Error(String(error)));
594
+ }
357
595
  }
358
- this.writer.set(`${key}:${id}:ttl`, '', 'PX', delay, 'NX', (err) => {
359
- // istanbul ignore next
596
+ };
597
+ if (delay) {
598
+ this.writer.zadd(`${key}:delayed`, Date.now() + delay, packet, (err) => {
360
599
  if (err) {
361
- cb(err, 'SET');
600
+ onWriteError(err, 'ZADD');
362
601
  return;
363
602
  }
364
- }).catch((err) => cb(err, 'SET'));
365
- });
366
- }
367
- else {
368
- this.writer.lpush(key, packet, (err) => {
369
- // istanbul ignore next
370
- if (err) {
371
- cb(err, 'LPUSH');
372
- return;
603
+ this.writer
604
+ .set(`${key}:${id}:ttl`, '', 'PX', delay, 'NX', (err) => {
605
+ if (err) {
606
+ onWriteError(err, 'SET');
607
+ return;
608
+ }
609
+ })
610
+ .catch((err) => onWriteError(err, 'SET'));
611
+ });
612
+ }
613
+ else {
614
+ const result = this.writer.lpush(key, packet, (err) => {
615
+ if (err) {
616
+ onWriteError(err, 'LPUSH');
617
+ }
618
+ });
619
+ // guard against unhandled rejections from promise-returning
620
+ // client implementations in fire-and-forget mode
621
+ if (result && typeof result.catch === 'function') {
622
+ result.catch((err) => onWriteError(err, 'LPUSH'));
373
623
  }
374
- });
375
- }
376
- return id;
377
- }
378
- /**
379
- * Stops current queue routines
380
- *
381
- * @returns {Promise<RedisQueue>}
382
- */
383
- async stop() {
384
- this.verbose('Stopping queue...');
385
- if (this.reader) {
386
- this.verbose('Destroying reader...');
387
- this.destroyChannel('reader', this);
388
- delete this.reader;
624
+ }
625
+ return id;
389
626
  }
390
- this.initialized = false;
391
- this.verbose('Queue stopped!');
392
- return this;
393
- }
394
- /**
395
- * Gracefully destroys this queue
396
- *
397
- * @returns {Promise<void>}
398
- */
399
- async destroy() {
400
- this.verbose('Destroying queue...');
401
- this.destroyed = true;
402
- this.removeAllListeners();
403
- this.cleanSafeCheckInterval();
404
- this.destroyWatcher();
405
- await this.stop();
406
- await this.clear();
407
- this.destroyWriter();
408
- await this.unsubscribe();
409
- this.verbose('Queue destroyed!');
410
- }
411
- /**
412
- * Clears queue data in redis
413
- *
414
- * @returns {Promise<void>}
415
- */
416
- async clear() {
417
- if (!this.writer) {
627
+ /**
628
+ * Stops current queue routines
629
+ *
630
+ * @returns {Promise<RedisQueue>}
631
+ */
632
+ async stop() {
633
+ this.verbose('Stopping queue...');
634
+ if (this.reader) {
635
+ this.verbose('Destroying reader...');
636
+ this.destroyChannel('reader');
637
+ delete this.reader;
638
+ }
639
+ this.initialized = false;
640
+ this.verbose('Queue stopped!');
418
641
  return this;
419
642
  }
420
- try {
421
- this.verbose('Clearing expired queue keys...');
422
- await Promise.all([
423
- this.writer.del(this.key),
424
- this.writer.del(`${this.key}:delayed`),
425
- ]);
426
- this.verbose('Expired queue keys cleared!');
427
- }
428
- catch (err) {
429
- // istanbul ignore next
430
- if (this.initialized) {
431
- this.logger.error(`${context.name}: error clearing the redis queue host ${this.redisKey} on writer, pid ${process.pid}:`, err);
643
+ /**
644
+ * Gracefully destroys this queue handle. Does not remove queue data
645
+ * from redis unless clearData is explicitly set to true, so that
646
+ * destroying one handle (e.g., on scale-down) never wipes messages
647
+ * still pending for other producers/consumers.
648
+ *
649
+ * @param {boolean} [clearData] - when true, also clears queue data
650
+ * @returns {Promise<void>}
651
+ */
652
+ async destroy(clearData = false) {
653
+ this.verbose('Destroying queue...');
654
+ this.destroyed = true;
655
+ RedisQueue.instances.delete(this);
656
+ this.removeAllListeners();
657
+ this.cleanSafeCheckInterval();
658
+ this.stopWatcherCheck();
659
+ if (this.watchOwner) {
660
+ await this.unlock().catch(err => this.verbose(`Unlock error: ${err}`));
661
+ this.destroyWatcher();
662
+ this.watchOwner = false;
432
663
  }
664
+ await this.stop();
665
+ if (clearData) {
666
+ await this.clear();
667
+ }
668
+ this.destroyWriter();
669
+ await this.unsubscribe();
670
+ this.verbose('Queue destroyed!');
433
671
  }
434
- return this;
435
- }
436
- /**
437
- * Retrieves the current count of messages in the queue
438
- *
439
- * @returns {Promise<number>}
440
- */
441
- async queueLength() {
442
- if (!this.writer) {
443
- return 0;
444
- }
445
- return this.writer.llen(this.key);
446
- }
447
- /**
448
- * Returns true if publisher mode is enabled on this queue, false otherwise.
449
- *
450
- * @return {boolean}
451
- */
452
- isPublisher() {
453
- return this.mode === _1.IMQMode.BOTH || this.mode === _1.IMQMode.PUBLISHER;
454
- }
455
- /**
456
- * Returns true if worker mode is enabled on this queue, false otherwise.
457
- *
458
- * @return {boolean}
459
- */
460
- isWorker() {
461
- return this.mode === _1.IMQMode.BOTH || this.mode === _1.IMQMode.WORKER;
462
- }
463
- // noinspection JSMethodCanBeStatic
464
- /**
465
- * Writer connection associated with this queue instance
466
- *
467
- * @type {IRedisClient}
468
- */
469
- get writer() {
470
- return RedisQueue.writers[this.redisKey];
471
- }
472
- // noinspection JSUnusedLocalSymbols
473
- /**
474
- * Writer connection setter.
475
- *
476
- * @param {IRedisClient} conn
477
- */
478
- // noinspection JSUnusedLocalSymbols,JSUnusedLocalSymbols
479
- set writer(conn) {
480
- RedisQueue.writers[this.redisKey] = conn;
481
- }
482
- /**
483
- * Watcher connection instance associated with this queue instance
484
- *
485
- * @type {IRedisClient}
486
- */
487
- get watcher() {
488
- return RedisQueue.watchers[this.redisKey];
489
- }
490
- // noinspection JSUnusedLocalSymbols
491
- /**
492
- * Watcher setter sets the watcher connection property for this
493
- * queue instance
494
- *
495
- * @param {IRedisClient} conn
496
- */
497
- // noinspection JSUnusedLocalSymbols
498
- set watcher(conn) {
499
- RedisQueue.watchers[this.redisKey] = conn;
500
- }
501
- /**
502
- * Logger instance associated with the current queue instance
503
- * @type {ILogger}
504
- */
505
- get logger() {
506
- // istanbul ignore next
507
- return this.options.logger || console;
508
- }
509
- /**
510
- * Return a lock key for watcher connection
511
- *
512
- * @access private
513
- * @returns {string}
514
- */
515
- get lockKey() {
516
- return `${this.options.prefix}:watch:lock`;
517
- }
518
- /**
519
- * Returns current queue key
520
- *
521
- * @access private
522
- * @returns {string}
523
- */
524
- get key() {
525
- return `${this.options.prefix}:${this.name}`;
526
- }
527
- /**
528
- * Destroys watcher channel
529
- *
530
- * @access private
531
- */
532
- destroyWatcher() {
533
- if (this.watcher) {
534
- this.verbose('Destroying watcher...');
535
- this.destroyChannel('watcher', this);
536
- delete RedisQueue.watchers[this.redisKey];
537
- this.verbose('Watcher destroyed!');
538
- }
539
- }
540
- /**
541
- * Destroys writer channel
542
- *
543
- * @access private
544
- */
545
- destroyWriter() {
546
- if (this.writer) {
547
- this.verbose('Destroying writer...');
548
- this.destroyChannel('writer', this);
549
- delete RedisQueue.writers[this.redisKey];
550
- this.verbose('Writer destroyed!');
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) {
672
+ /**
673
+ * Clears queue data in redis
674
+ *
675
+ * @returns {Promise<void>}
676
+ */
677
+ async clear() {
678
+ if (!this.writer) {
679
+ return this;
680
+ }
561
681
  try {
562
- client.removeAllListeners();
563
- client.quit().then(() => {
564
- client.disconnect(false);
565
- }).catch(e => {
566
- this.verbose(`Error quitting ${channel}: ${e}`);
567
- });
682
+ this.verbose('Clearing expired queue keys...');
683
+ await Promise.all([
684
+ this.writer.del(this.key),
685
+ this.writer.del(`${this.key}:delayed`),
686
+ ]);
687
+ this.verbose('Expired queue keys cleared!');
568
688
  }
569
- catch (error) {
570
- this.verbose(`Error destroying ${channel}: ${error}`);
689
+ catch (err) {
690
+ if (this.initialized) {
691
+ this.logger.error(`${this.name}: error clearing the redis queue host ${this.redisKey} on writer, pid ${process.pid}:`, err);
692
+ }
571
693
  }
694
+ return this;
572
695
  }
573
- }
574
- /**
575
- * Establishes a given connection channel by its name
576
- *
577
- * @access private
578
- * @param {RedisConnectionChannel} channel
579
- * @param {IMQOptions} options
580
- * @param {any} context
581
- * @returns {Promise<IRedisClient>}
582
- */
583
- async connect(channel, options, context = this) {
584
- this.verbose(`Connecting to ${channel} channel...`);
585
- // istanbul ignore next
586
- if (context[channel]) {
587
- return context[channel];
696
+ /**
697
+ * Retrieves the current count of messages in the queue
698
+ *
699
+ * @returns {Promise<number>}
700
+ */
701
+ async queueLength() {
702
+ if (!this.writer) {
703
+ return 0;
704
+ }
705
+ return this.writer.llen(this.key);
588
706
  }
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,
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
- });
707
+ /**
708
+ * Returns true if publisher mode is enabled on this queue, false otherwise.
709
+ *
710
+ * @returns {boolean}
711
+ */
712
+ isPublisher() {
713
+ return this.mode === _1.IMQMode.BOTH || this.mode === _1.IMQMode.PUBLISHER;
620
714
  }
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;
715
+ /**
716
+ * Returns true if worker mode is enabled on this queue, false otherwise.
717
+ *
718
+ * @returns {boolean}
719
+ */
720
+ isWorker() {
721
+ return this.mode === _1.IMQMode.BOTH || this.mode === _1.IMQMode.WORKER;
636
722
  }
637
- return context[channel];
638
- }
639
- // istanbul ignore next
640
- /**
641
- * Builds and returns redis reconnection strategy
642
- *
643
- * @returns {() => (number | void | null)}
644
- * @private
645
- */
646
- retryStrategy() {
647
- return () => {
648
- return null;
649
- };
650
- }
651
- /**
652
- * Schedules custom reconnection for a given channel with capped
653
- * exponential backoff
654
- *
655
- * @param {RedisConnectionChannel} channel
656
- * @private
657
- */
658
- scheduleReconnect(channel) {
659
- if (this.destroyed) {
660
- return;
723
+ /**
724
+ * Returns false only when this queue is known to be unable to accept
725
+ * writes right now — i.e., it has a writer connection currently
726
+ * in a non-ready (reconnecting/closed) state. A queue that has not yet
727
+ * connected is considered available, since a sending lazily connects it.
728
+ * Used for health-aware routing in the clustered queue.
729
+ *
730
+ * @returns {boolean}
731
+ */
732
+ get available() {
733
+ return !this.writer || this.writer.status === 'ready';
661
734
  }
662
- if (this.reconnecting[channel]) {
663
- return;
735
+ /**
736
+ * Writer connection associated with this queue instance
737
+ *
738
+ * @type {IRedisClient}
739
+ */
740
+ get writer() {
741
+ return RedisQueue.writers[this.redisKey];
664
742
  }
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]);
743
+ /**
744
+ * Writer connection setter.
745
+ *
746
+ * @param {IRedisClient} conn
747
+ */
748
+ set writer(conn) {
749
+ RedisQueue.writers[this.redisKey] = conn;
674
750
  }
675
- this.reconnectTimers[channel] = setTimeout(async () => {
676
- if (this.destroyed) {
677
- this.reconnecting[channel] = false;
678
- return;
679
- }
680
- try {
681
- switch (channel) {
682
- case 'watcher':
751
+ /**
752
+ * Watcher connection instance associated with this queue instance
753
+ *
754
+ * @type {IRedisClient}
755
+ */
756
+ get watcher() {
757
+ return RedisQueue.watchers[this.redisKey];
758
+ }
759
+ /**
760
+ * Watcher setter sets the watcher connection property for this
761
+ * queue instance
762
+ *
763
+ * @param {IRedisClient} conn
764
+ */
765
+ set watcher(conn) {
766
+ RedisQueue.watchers[this.redisKey] = conn;
767
+ }
768
+ /**
769
+ * Returns the connection currently bound to the given channel, if any.
770
+ *
771
+ * @param {RedisConnectionChannel} channel
772
+ * @returns {IRedisClient | undefined}
773
+ */
774
+ connectionOf(channel) {
775
+ switch (channel) {
776
+ case 'reader':
777
+ return this.reader;
778
+ case 'writer':
779
+ return this.writer;
780
+ case 'watcher':
781
+ return this.watcher;
782
+ case 'subscription':
783
+ return this.subscription;
784
+ }
785
+ }
786
+ /**
787
+ * Binds the given connection to the given channel.
788
+ *
789
+ * @param {RedisConnectionChannel} channel
790
+ * @param {IRedisClient} conn
791
+ */
792
+ bindConnection(channel, conn) {
793
+ switch (channel) {
794
+ case 'reader':
795
+ this.reader = conn;
796
+ break;
797
+ case 'writer':
798
+ this.writer = conn;
799
+ break;
800
+ case 'watcher':
801
+ this.watcher = conn;
802
+ break;
803
+ case 'subscription':
804
+ this.subscription = conn;
805
+ break;
806
+ }
807
+ }
808
+ /**
809
+ * Logger instance associated with the current queue instance
810
+ * @type {ILogger}
811
+ */
812
+ get logger() {
813
+ return this.options.logger || console;
814
+ }
815
+ /**
816
+ * Return a lock key for watcher connection
817
+ *
818
+ * @returns {string}
819
+ */
820
+ get lockKey() {
821
+ return `${this.options.prefix}:watch:lock`;
822
+ }
823
+ /**
824
+ * Returns current queue key
825
+ *
826
+ * @returns {string}
827
+ */
828
+ get key() {
829
+ return `${this.options.prefix}:${this.name}`;
830
+ }
831
+ /**
832
+ * Destroys watcher channel
833
+ */
834
+ destroyWatcher() {
835
+ if (this.watcher) {
836
+ this.verbose('Destroying watcher...');
837
+ this.destroyChannel('watcher');
838
+ delete RedisQueue.watchers[this.redisKey];
839
+ this.verbose('Watcher destroyed!');
840
+ }
841
+ }
842
+ /**
843
+ * Destroys writer channel
844
+ */
845
+ destroyWriter(release = true) {
846
+ if (release && this.writerAcquired) {
847
+ this.writerAcquired = false;
848
+ RedisQueue.writerRefs[this.redisKey] = Math.max(0, (RedisQueue.writerRefs[this.redisKey] || 1) - 1);
849
+ if (RedisQueue.writerRefs[this.redisKey] > 0) {
850
+ // the shared writer connection is still used by other
851
+ // queue instances within this process
852
+ this.verbose('Writer is still in use, skipping destroy...');
853
+ return;
854
+ }
855
+ }
856
+ if (this.writer) {
857
+ this.verbose('Destroying writer...');
858
+ this.destroyChannel('writer');
859
+ delete RedisQueue.writers[this.redisKey];
860
+ this.verbose('Writer destroyed!');
861
+ }
862
+ }
863
+ /**
864
+ * Destroys any channel
865
+ */
866
+ destroyChannel(channel) {
867
+ const client = this.connectionOf(channel);
868
+ if (!client) {
869
+ return;
870
+ }
871
+ try {
872
+ client.removeAllListeners();
873
+ let disconnected = false;
874
+ const forceDisconnect = () => {
875
+ if (disconnected) {
876
+ return;
877
+ }
878
+ disconnected = true;
879
+ try {
880
+ client.disconnect(false);
881
+ }
882
+ catch (error) {
883
+ this.verbose(`Error disconnecting ${channel}: ${error}`);
884
+ }
885
+ };
886
+ // graceful quit for idle connections, but a reader blocked on an
887
+ // infinite BRPOP/BLMOVE never lets QUIT through, so guarantee a
888
+ // forced disconnect after a short grace period to avoid leaking
889
+ // the socket (which would keep the process alive)
890
+ client.quit().then(forceDisconnect, forceDisconnect);
891
+ const timer = setTimeout(forceDisconnect, exports.IMQ_CONNECTION_QUIT_TIMEOUT);
892
+ // the grace timer itself must not keep the process alive; while
893
+ // the leaked socket keeps the loop running the timer still fires
894
+ timer.unref();
895
+ }
896
+ catch (error) {
897
+ this.verbose(`Error destroying ${channel}: ${error}`);
898
+ }
899
+ }
900
+ /**
901
+ * Establishes a given connection channel by its name
902
+ *
903
+ * @param {RedisConnectionChannel} channel
904
+ * @param {IMQOptions} options
905
+ * @returns {Promise<IRedisClient>}
906
+ */
907
+ async connect(channel, options) {
908
+ this.verbose(`Connecting to ${channel} channel...`);
909
+ const existing = this.connectionOf(channel);
910
+ if (existing) {
911
+ return existing;
912
+ }
913
+ const redis = new redis_1.default({
914
+ port: options.port || 6379,
915
+ host: options.host || 'localhost',
916
+ username: options.username,
917
+ password: options.password,
918
+ connectionName: this.getChannelName(this.name, options.prefix || '', channel),
919
+ retryStrategy: noRetryStrategy,
920
+ autoResubscribe: true,
921
+ enableOfflineQueue: true,
922
+ autoResendUnfulfilledCommands: true,
923
+ offlineQueue: true,
924
+ maxRetriesPerRequest: null,
925
+ enableReadyCheck: channel !== 'subscription',
926
+ lazyConnect: true,
927
+ });
928
+ this.bindConnection(channel, redis);
929
+ redis.__imq = true;
930
+ for (const event of [
931
+ 'wait',
932
+ 'reconnecting',
933
+ 'connecting',
934
+ 'connect',
935
+ 'close',
936
+ ]) {
937
+ redis.on(event, () => this.verbose(`Redis Event fired: ${event}`));
938
+ }
939
+ redis.setMaxListeners(IMQ_REDIS_MAX_LISTENERS_LIMIT);
940
+ redis.on('error', this.onErrorHandler(channel));
941
+ redis.on('end', this.onCloseHandler(channel));
942
+ await redis.connect();
943
+ this.logger.info('%s: %s channel connected, host %s, pid %s', this.name, channel, this.redisKey, process.pid);
944
+ switch (channel) {
945
+ case 'reader':
946
+ this.read();
947
+ break;
948
+ case 'writer':
949
+ await this.processDelayed(this.key);
950
+ break;
951
+ case 'watcher':
952
+ await this.initWatcher();
953
+ break;
954
+ case 'subscription':
955
+ await this.restoreSubscription();
956
+ break;
957
+ }
958
+ return redis;
959
+ }
960
+ /**
961
+ * Schedules custom reconnection for a given channel with capped
962
+ * exponential backoff
963
+ *
964
+ * @param {RedisConnectionChannel} channel
965
+ * @private
966
+ */
967
+ scheduleReconnect(channel) {
968
+ if (this.destroyed || this.reconnecting[channel]) {
969
+ return;
970
+ }
971
+ const attempts = (this.reconnectAttempts[channel] || 0) + 1;
972
+ const delayMs = Math.min(RECONNECT_MAX_DELAY, RECONNECT_BASE_DELAY * 2 ** (attempts - 1));
973
+ this.reconnecting[channel] = true;
974
+ this.reconnectAttempts[channel] = attempts;
975
+ this.verbose(`Scheduling ${channel} reconnect in ${delayMs} ms ` +
976
+ `(attempt ${attempts})`);
977
+ if (this.reconnectTimers[channel]) {
978
+ clearTimeout(this.reconnectTimers[channel]);
979
+ }
980
+ this.reconnectTimers[channel] = setTimeout(this.reconnectNow.bind(this, channel), delayMs);
981
+ }
982
+ /**
983
+ * Performs a single reconnection attempt for the given channel,
984
+ * rescheduling itself on failure. Errors are handled internally, so the
985
+ * scheduled timer never produces an unhandled rejection.
986
+ *
987
+ * @param {RedisConnectionChannel} channel
988
+ * @returns {Promise<void>}
989
+ */
990
+ async reconnectNow(channel) {
991
+ if (this.destroyed) {
992
+ this.reconnecting[channel] = false;
993
+ return;
994
+ }
995
+ try {
996
+ switch (channel) {
997
+ case 'watcher':
683
998
  this.destroyWatcher();
684
999
  break;
685
1000
  case 'writer':
686
- this.destroyWriter();
1001
+ // replace the broken shared connection without
1002
+ // releasing this instance's reference to it
1003
+ this.destroyWriter(false);
687
1004
  break;
688
1005
  case 'reader':
689
- this.destroyChannel(channel, this);
1006
+ this.destroyChannel(channel);
690
1007
  this.reader = undefined;
691
1008
  break;
692
1009
  case 'subscription':
693
- this.destroyChannel(channel, this);
1010
+ this.destroyChannel(channel);
694
1011
  this.subscription = undefined;
695
1012
  break;
696
1013
  }
@@ -708,571 +1025,512 @@ class RedisQueue extends events_1.EventEmitter {
708
1025
  this.verbose(`Reconnect ${channel} failed: ${err}`);
709
1026
  this.scheduleReconnect(channel);
710
1027
  }
711
- }, delay);
712
- }
713
- // noinspection JSMethodCanBeStatic
714
- /**
715
- * Generates channel name
716
- *
717
- * @param {string} contextName
718
- * @param {string} prefix
719
- * @param {RedisConnectionChannel} name
720
- * @return {string}
721
- */
722
- getChannelName(contextName, prefix, name) {
723
- const uniqueSuffix = `pid:${process.pid}:host:${os.hostname()}`;
724
- return `${prefix}:${contextName}:${name}:${uniqueSuffix}`;
725
- }
726
- /**
727
- * Builds and returns connection error handler
728
- *
729
- * @access private
730
- * @param {RedisQueue} context
731
- * @param {RedisConnectionChannel} channel
732
- * @return {(err: Error) => void}
733
- */
734
- onErrorHandler(context, channel) {
735
- // istanbul ignore next
736
- return ((error) => {
737
- var _a;
738
- this.verbose(`Redis Error: ${error}`);
739
- if (this.destroyed) {
740
- return;
741
- }
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);
747
- }
748
- });
749
- }
750
- /**
751
- * Builds and returns redis connection close handler
752
- *
753
- * @access private
754
- * @param {RedisQueue} context
755
- * @param {RedisConnectionChannel} channel
756
- * @return {(...args: any[]) => any}
757
- */
758
- onCloseHandler(context, channel) {
759
- this.verbose(`Redis ${channel} is closing...`);
760
- // istanbul ignore next
761
- return (() => {
762
- this.initialized = false;
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
- }
767
- });
768
- }
769
- /**
770
- * Processes given redis-queue message
771
- *
772
- * @access private
773
- * @param {[any, any]} msg
774
- * @returns {RedisQueue}
775
- */
776
- process(msg) {
777
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
778
- const [queue, data] = msg;
779
- // istanbul ignore next
780
- if (!queue || queue !== this.key) {
781
- return this;
782
- }
783
- try {
784
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-argument
785
- const { id, message, from } = this.unpack(data);
786
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
787
- this.emit('message', message, id, from);
788
1028
  }
789
- catch (err) {
790
- // istanbul ignore next
791
- this.emitError('OnMessage', 'process error - message is invalid', err);
1029
+ /**
1030
+ * Generates channel name
1031
+ *
1032
+ * @param {string} contextName
1033
+ * @param {string} prefix
1034
+ * @param {RedisConnectionChannel} name
1035
+ * @returns {string}
1036
+ */
1037
+ getChannelName(contextName, prefix, name) {
1038
+ const uniqueSuffix = `pid:${process.pid}:host:${(0, node_os_1.hostname)()}`;
1039
+ return `${prefix}:${contextName}:${name}:${uniqueSuffix}`;
792
1040
  }
793
- return this;
794
- }
795
- /**
796
- * Returns the number of established watcher connections on redis
797
- *
798
- * @access private
799
- * @returns {Promise<number>}
800
- */
801
- // istanbul ignore next
802
- async watcherCount() {
803
- if (!this.writer) {
804
- return 0;
1041
+ /**
1042
+ * Builds and returns connection error handler
1043
+ *
1044
+ * @param {RedisConnectionChannel} channel
1045
+ * @returns {(err: Error) => void}
1046
+ */
1047
+ onErrorHandler(channel) {
1048
+ return (error) => {
1049
+ this.verbose(`Redis Error: ${error}`);
1050
+ if (this.destroyed) {
1051
+ return;
1052
+ }
1053
+ this.logger.error(`${this.name}: error connecting redis host ${this.redisKey} on ${channel}, pid ${process.pid}:`, error);
1054
+ if (error.code === 'ECONNREFUSED' ||
1055
+ error.code === 'ETIMEDOUT' ||
1056
+ this.connectionOf(channel)?.status !== 'ready') {
1057
+ this.scheduleReconnect(channel);
1058
+ }
1059
+ };
805
1060
  }
806
- const rx = new RegExp(`\\bname=${this.options.prefix}:[\\S]+?:watcher:`);
807
- const list = await this.writer.client('LIST');
808
- if (!list || !list.split) {
809
- return 0;
1061
+ /**
1062
+ * Builds and returns redis connection close handler
1063
+ *
1064
+ * @param {RedisConnectionChannel} channel
1065
+ * @returns {() => void}
1066
+ */
1067
+ onCloseHandler(channel) {
1068
+ this.verbose(`Redis ${channel} is closing...`);
1069
+ return () => {
1070
+ this.initialized = false;
1071
+ this.logger.warn('%s: redis connection %s closed on host %s, pid %s!', this.name, channel, this.redisKey, process.pid);
1072
+ if (!this.destroyed) {
1073
+ this.scheduleReconnect(channel);
1074
+ }
1075
+ };
810
1076
  }
811
- return list.split(/\r?\n/).filter(client => rx.test(client)).length;
812
- }
813
- /**
814
- * Processes delayed a message by its given redis key
815
- *
816
- * @access private
817
- * @param {string} key
818
- * @returns {Promise<void>}
819
- */
820
- async processDelayed(key) {
821
- try {
822
- if (this.scripts.moveDelayed.checksum) {
823
- await this.writer.evalsha(this.scripts.moveDelayed.checksum, 2, `${key}:delayed`, key, Date.now());
1077
+ /**
1078
+ * Processes given redis-queue message
1079
+ *
1080
+ * @param {[string, string]} msg
1081
+ * @returns {RedisQueue}
1082
+ */
1083
+ process(msg) {
1084
+ const [queue, data] = msg;
1085
+ if (!queue || queue !== this.key) {
1086
+ return this;
1087
+ }
1088
+ try {
1089
+ const { id, message, from } = this.unpack(data);
1090
+ this.emit('message', message, id, from);
824
1091
  }
1092
+ catch (err) {
1093
+ this.emitError('OnMessage', 'process error - message is invalid', err);
1094
+ }
1095
+ return this;
825
1096
  }
826
- catch (err) {
827
- this.emitError('OnProcessDelayed', 'error processing delayed queue', err);
1097
+ /**
1098
+ * Returns the number of established watcher connections on redis
1099
+ *
1100
+ * @returns {Promise<number>}
1101
+ */
1102
+ async watcherCount() {
1103
+ if (!this.writer) {
1104
+ return 0;
1105
+ }
1106
+ const rx = new RegExp(`\\bname=${(0, helpers_1.escapeRegExp)(this.options.prefix || '')}:\\S+?:watcher:`);
1107
+ const list = (await this.writer.client('LIST'));
1108
+ if (!list || !list.split) {
1109
+ return 0;
1110
+ }
1111
+ return list.split(/\r?\n/).filter(client => rx.test(client)).length;
828
1112
  }
829
- }
830
- // istanbul ignore next
831
- /**
832
- * Watch routine
833
- *
834
- * @access private
835
- * @return {Promise<void>}
836
- */
837
- async processWatch() {
838
- const now = Date.now();
839
- let cursor = '0';
840
- while (true) {
1113
+ /**
1114
+ * Processes delayed a message by its given redis key
1115
+ *
1116
+ * @param {string} key
1117
+ * @returns {Promise<void>}
1118
+ */
1119
+ async processDelayed(key) {
841
1120
  try {
842
- const data = await this.writer.scan(cursor, 'MATCH', `${this.options.prefix}:*:worker:*`, 'COUNT', '1000');
843
- cursor = data.shift();
844
- const keys = data.shift() || [];
845
- await this.processKeys(keys, now);
846
- if (cursor === '0') {
1121
+ if (!this.scripts.moveDelayed.checksum || !this.writer) {
847
1122
  return;
848
1123
  }
1124
+ try {
1125
+ await this.writer.evalsha(this.scripts.moveDelayed.checksum, 2, `${key}:delayed`, key, Date.now());
1126
+ }
1127
+ catch (err) {
1128
+ // the script may not be cached on the redis host (fresh
1129
+ // host, restart, non-owner instance) - fall back to EVAL,
1130
+ // which caches it as a side effect
1131
+ if (err instanceof Error && /NOSCRIPT/.test(err.message)) {
1132
+ await this.writer.eval(this.scripts.moveDelayed.code, 2, `${key}:delayed`, key, Date.now());
1133
+ }
1134
+ else {
1135
+ throw err;
1136
+ }
1137
+ }
849
1138
  }
850
1139
  catch (err) {
851
- this.emitError('OnSafeDelivery', 'safe queue message delivery problem', err);
852
- this.cleanSafeCheckInterval();
853
- return;
1140
+ this.emitError('OnProcessDelayed', 'error processing delayed queue', err);
854
1141
  }
855
1142
  }
856
- }
857
- // istanbul ignore next
858
- /**
859
- * Process given keys from a message queue
860
- *
861
- * @access private
862
- * @param {string[]} keys
863
- * @param {number} now
864
- * @return {Promise<void>}
865
- */
866
- async processKeys(keys, now) {
867
- if (!keys.length) {
868
- return;
869
- }
870
- this.verbose(`Watching ${keys.length} keys: ${keys.map(key => `"${key}"`).join(', ')}`);
871
- for (const key of keys) {
872
- const kp = key.split(':');
873
- if (Number(kp.pop()) < now) {
874
- continue;
1143
+ /**
1144
+ * Watch routine
1145
+ *
1146
+ * @returns {Promise<void>}
1147
+ */
1148
+ async processWatch() {
1149
+ const now = Date.now();
1150
+ let cursor = '0';
1151
+ while (true) {
1152
+ try {
1153
+ const [next, keys] = await this.writer.scan(cursor, 'MATCH', `${this.options.prefix}:*:worker:*`, 'COUNT', SCAN_COUNT);
1154
+ cursor = next;
1155
+ await this.processKeys(keys, now);
1156
+ if (cursor === '0') {
1157
+ return;
1158
+ }
1159
+ }
1160
+ catch (err) {
1161
+ this.emitError('OnSafeDelivery', 'safe queue message delivery problem', err);
1162
+ this.cleanSafeCheckInterval();
1163
+ return;
1164
+ }
875
1165
  }
876
- await this.writer.rpoplpush(key, `${kp.shift()}:${kp.shift()}`);
877
1166
  }
878
- }
879
- // istanbul ignore next
880
- /**
881
- * Watch message processor
882
- *
883
- * @access private
884
- * @param {...any[]} args
885
- * @return {Promise<void>}
886
- */
887
- async onWatchMessage(...args) {
888
- try {
889
- const key = (args.pop() || '').split(':');
890
- if (key.pop() !== 'ttl') {
1167
+ /**
1168
+ * Process given keys from a message queue
1169
+ *
1170
+ * @param {string[]} keys
1171
+ * @param {number} now
1172
+ * @returns {Promise<void>}
1173
+ */
1174
+ async processKeys(keys, now) {
1175
+ if (!keys.length) {
891
1176
  return;
892
1177
  }
893
- key.pop(); // msg id
894
- await this.processDelayed(key.join(':'));
895
- }
896
- catch (err) {
897
- this.emitError('OnWatch', 'watch error', err);
1178
+ this.verbose(`Watching ${keys.length} keys: ${keys
1179
+ .map(key => `"${key}"`)
1180
+ .join(', ')}`);
1181
+ for (const key of keys) {
1182
+ const kp = key.split(':');
1183
+ // the last key segment is the worker's lease deadline: only
1184
+ // re-queue messages of workers whose lease has expired (the
1185
+ // worker died mid-processing); fresh leases belong to live
1186
+ // workers and must not be touched
1187
+ if (Number(kp.pop()) >= now) {
1188
+ continue;
1189
+ }
1190
+ await this.writer.lmove(key, `${kp.shift()}:${kp.shift()}`, 'RIGHT', 'LEFT');
1191
+ }
898
1192
  }
899
- }
900
- // istanbul ignore next
901
- /**
902
- * Clears safe check interval
903
- *
904
- * @access private
905
- */
906
- cleanSafeCheckInterval() {
907
- if (this.safeCheckInterval) {
908
- clearInterval(this.safeCheckInterval);
909
- delete this.safeCheckInterval;
1193
+ /**
1194
+ * Watch message processor
1195
+ *
1196
+ * @param {...any[]} args
1197
+ * @returns {Promise<void>}
1198
+ */
1199
+ async onWatchMessage(...args) {
1200
+ try {
1201
+ const key = (args.pop() || '').split(':');
1202
+ if (key.pop() !== 'ttl') {
1203
+ return;
1204
+ }
1205
+ key.pop(); // msg id
1206
+ await this.processDelayed(key.join(':'));
1207
+ }
1208
+ catch (err) {
1209
+ this.emitError('OnWatch', 'watch error', err);
1210
+ }
910
1211
  }
911
- }
912
- /**
913
- * Setups watch a process on delayed messages
914
- *
915
- * @access private
916
- * @returns {RedisQueue}
917
- */
918
- // istanbul ignore next
919
- watch() {
920
- if (!this.writer || !this.watcher || this.watcher.__ready__) {
921
- return this;
1212
+ /**
1213
+ * Clears safe check interval
1214
+ */
1215
+ cleanSafeCheckInterval() {
1216
+ if (this.safeCheckInterval) {
1217
+ clearInterval(this.safeCheckInterval);
1218
+ delete this.safeCheckInterval;
1219
+ }
922
1220
  }
923
- try {
924
- this.writer.config('SET', 'notify-keyspace-events', 'Ex').catch(err => {
1221
+ /**
1222
+ * Setups watch a process on delayed messages
1223
+ *
1224
+ * @returns {RedisQueue}
1225
+ */
1226
+ watch() {
1227
+ if (!this.writer || !this.watcher || this.watcher.__ready__) {
1228
+ return this;
1229
+ }
1230
+ try {
1231
+ this.writer
1232
+ .config('SET', 'notify-keyspace-events', 'Ex')
1233
+ .catch((err) => this.emitError('OnConfig', 'events config error', err));
1234
+ }
1235
+ catch (err) {
925
1236
  this.emitError('OnConfig', 'events config error', err);
926
- });
927
- }
928
- catch (err) {
929
- this.emitError('OnConfig', 'events config error', err);
930
- }
931
- this.watcher.on('pmessage', this.onWatchMessage.bind(this));
932
- this.watcher.psubscribe('__keyevent@0__:expired', `${this.options.prefix}:delayed:*`).catch(err => {
933
- this.verbose(`Error subscribing to watcher channel: ${err}`);
934
- });
935
- // watch for expired unhandled safe queues
936
- if (!this.safeCheckInterval) {
937
- if (this.options.safeDeliveryTtl != null) {
938
- this.safeCheckInterval = setInterval((async () => {
939
- if (!this.writer) {
940
- this.cleanSafeCheckInterval();
941
- return;
942
- }
943
- if (this.options.safeDelivery) {
944
- await this.processWatch();
945
- }
946
- await this.processCleanup();
947
- }), this.options.safeDeliveryTtl);
948
1237
  }
1238
+ this.watcher.on('pmessage', this.onWatchMessage.bind(this));
1239
+ this.watcher
1240
+ .psubscribe('__keyevent@0__:expired', `${this.options.prefix}:delayed:*`)
1241
+ .catch((err) => this.verbose(`Error subscribing to watcher channel: ${err}`));
1242
+ // watch for expired unhandled safe queues
1243
+ if (!this.safeCheckInterval && this.options.safeDeliveryTtl != null) {
1244
+ this.safeCheckInterval = setInterval(this.runSafeCheck.bind(this), this.options.safeDeliveryTtl);
1245
+ // maintenance timer must not keep the process alive on its own
1246
+ this.safeCheckInterval.unref();
1247
+ }
1248
+ this.watcher.__ready__ = true;
1249
+ return this;
949
1250
  }
950
- this.watcher.__ready__ = true;
951
- return this;
952
- }
953
- /**
954
- * Cleans up orphaned keys from redis
955
- *
956
- * @access private
957
- * @returns {Promise<RedisQueue | undefined>}
958
- */
959
- async processCleanup() {
960
- this.verbose('Cleaning up orphaned keys...');
961
- try {
962
- if (!this.options.cleanup) {
1251
+ /**
1252
+ * A single safe-delivery maintenance tick: recovers messages from dead
1253
+ * workers (when safe delivery is on) and prunes orphaned keys.
1254
+ *
1255
+ * @returns {Promise<void>}
1256
+ */
1257
+ async runSafeCheck() {
1258
+ if (!this.writer) {
1259
+ this.cleanSafeCheckInterval();
963
1260
  return;
964
1261
  }
965
- const filter = new RegExp(this.options.prefix + ':' +
966
- (this.options.cleanupFilter || '*').replace(/\*/g, '.*'), 'i');
967
- this.verbose(`Cleaning up keys matching ${filter}`);
968
- const clients = (await this.writer.client('LIST')).toString() || '';
969
- const connectedKeys = (clients.match(RX_CLIENT_NAME) || [])
970
- .filter((name) => RX_CLIENT_TEST.test(name) && filter.test(name))
971
- .map((name) => name
972
- .replace(/^name=/, '')
973
- .replace(RX_CLIENT_CLEAN, ''))
974
- .filter((name, i, a) => a.indexOf(name) === i);
975
- const keysToRemove = [];
976
- let cursor = '0';
977
- this.verbose(`Found connected keys: ${connectedKeys.map(k => `"${k}"`).join(', ')}`);
978
- while (true) {
979
- const data = await this.writer.scan(cursor, 'MATCH', `${this.options.prefix}:${this.options.cleanupFilter || '*'}`, 'COUNT', '1000');
980
- cursor = data.shift();
981
- const keys = data.shift() || [];
982
- keysToRemove.push(...keys.filter(key => key !== this.lockKey &&
983
- connectedKeys.every(connectedKey => key.indexOf(connectedKey) === -1)));
984
- if (cursor === '0') {
985
- break;
986
- }
1262
+ if (this.options.safeDelivery) {
1263
+ await this.processWatch();
987
1264
  }
988
- if (keysToRemove.length) {
989
- await this.writer.del(...keysToRemove);
990
- this.verbose(`Keys ${keysToRemove.map(k => `"${k}"`).join(', ')} were successfully removed!`);
991
- }
992
- }
993
- catch (err) {
994
- this.logger.warn('Clean-up error occurred:', err);
1265
+ await this.processCleanup();
995
1266
  }
996
- return this;
997
- }
998
- // noinspection JSUnusedLocalSymbols
999
- /**
1000
- * Unreliable but fast way of message handling by the queue
1001
- */
1002
- async readUnsafe() {
1003
- try {
1004
- const key = this.key;
1005
- while (true) {
1006
- if (!this.reader) {
1007
- break;
1267
+ /**
1268
+ * Cleans up orphaned keys from redis
1269
+ *
1270
+ * @returns {Promise<RedisQueue | undefined>}
1271
+ */
1272
+ async processCleanup() {
1273
+ this.verbose('Cleaning up orphaned keys...');
1274
+ try {
1275
+ if (!this.options.cleanup) {
1276
+ return;
1008
1277
  }
1009
- try {
1010
- const msg = await this.reader.brpop(key, 0);
1011
- if (msg) {
1012
- this.process(msg);
1278
+ const filter = new RegExp((0, helpers_1.escapeRegExp)(this.options.prefix || '') +
1279
+ ':' +
1280
+ (0, helpers_1.escapeRegExp)(this.options.cleanupFilter || '*').replace(/\\\*/g, '.*'), 'i');
1281
+ this.verbose(`Cleaning up keys matching ${filter}`);
1282
+ const clients = (await this.writer.client('LIST')).toString() || '';
1283
+ const connectedKeys = (clients.match(RX_CLIENT_NAME) || [])
1284
+ .filter((name) => RX_CLIENT_TEST.test(name) && filter.test(name))
1285
+ .map((name) => name.replace(/^name=/, '').replace(RX_CLIENT_CLEAN, ''))
1286
+ .filter((name, i, a) => a.indexOf(name) === i);
1287
+ // clients seen connected during the previous sweep get one
1288
+ // sweep of grace: a client merely reconnecting (the
1289
+ // backoff can reach tens of seconds) must not have any keys
1290
+ // deleted from under it
1291
+ const knownKeys = connectedKeys.concat(this.lastConnectedKeys.filter(key => !connectedKeys.includes(key)));
1292
+ this.lastConnectedKeys = connectedKeys;
1293
+ const keysToRemove = [];
1294
+ let cursor = '0';
1295
+ this.verbose(`Found connected keys: ${knownKeys
1296
+ .map(k => `"${k}"`)
1297
+ .join(', ')}`);
1298
+ while (true) {
1299
+ const [next, keys] = await this.writer.scan(cursor, 'MATCH', `${this.options.prefix}:${this.options.cleanupFilter || '*'}`, 'COUNT', SCAN_COUNT);
1300
+ cursor = next;
1301
+ keysToRemove.push(...keys.filter(key => key !== this.lockKey &&
1302
+ knownKeys.every(connectedKey => key.indexOf(connectedKey) === -1)));
1303
+ if (cursor === '0') {
1304
+ break;
1013
1305
  }
1014
1306
  }
1015
- catch (err) {
1016
- // istanbul ignore next
1017
- // eslint-disable-next-line @typescript-eslint/no-unsafe-call
1018
- if (err.message.match(/Stream connection ended/)) {
1307
+ if (keysToRemove.length) {
1308
+ await this.writer.del(...keysToRemove);
1309
+ this.verbose(`Keys ${keysToRemove
1310
+ .map(k => `"${k}"`)
1311
+ .join(', ')} were successfully removed!`);
1312
+ }
1313
+ }
1314
+ catch (err) {
1315
+ this.logger.warn('Clean-up error occurred:', err);
1316
+ }
1317
+ return this;
1318
+ }
1319
+ /**
1320
+ * Unreliable but fast way of message handling by the queue
1321
+ */
1322
+ async readUnsafe() {
1323
+ try {
1324
+ const key = this.key;
1325
+ while (true) {
1326
+ if (!this.reader) {
1019
1327
  break;
1020
1328
  }
1021
- // istanbul ignore next
1022
- // noinspection ExceptionCaughtLocallyJS
1023
- throw err;
1329
+ try {
1330
+ const msg = await this.reader.brpop(key, 0);
1331
+ if (msg) {
1332
+ this.process(msg);
1333
+ }
1334
+ }
1335
+ catch (err) {
1336
+ // a closed/ended reader connection means the queue is
1337
+ // stopping, reconnecting, or being destroyed - end the
1338
+ // loop quietly; reconnection (if any) is driven by the
1339
+ // connection close handler, not by this loop
1340
+ if (this.destroyed ||
1341
+ !this.reader ||
1342
+ (err instanceof Error &&
1343
+ /Stream connection ended|Connection is closed/i.test(err.message))) {
1344
+ break;
1345
+ }
1346
+ throw err;
1347
+ }
1024
1348
  }
1025
1349
  }
1350
+ catch (err) {
1351
+ this.emitError('OnReadUnsafe', 'unsafe reader failed', err);
1352
+ }
1026
1353
  }
1027
- catch (err) {
1028
- // istanbul ignore next
1029
- this.emitError('OnReadUnsafe', 'unsafe reader failed', err);
1030
- }
1031
- }
1032
- // noinspection JSUnusedLocalSymbols
1033
- /**
1034
- * Reliable but slow method of message handling by message queue
1035
- */
1036
- async readSafe() {
1037
- try {
1354
+ /**
1355
+ * Reliable but slow method of message handling by message queue.
1356
+ *
1357
+ * Uses a bounded blocking pop so the lease deadline embedded into the
1358
+ * worker key never goes stale: with an infinite block a message
1359
+ * arriving long after the pop started would be born with an already
1360
+ * expired lease and be immediately re-queued by the watcher.
1361
+ */
1362
+ async readSafe() {
1038
1363
  const key = this.key;
1364
+ // blocking timeout in seconds, at most half of the lease ttl, so
1365
+ // a claimed message always has at least half the ttl remaining
1366
+ const timeout = Math.max(0.1, Number(this.options.safeDeliveryTtl) / 2000);
1039
1367
  while (true) {
1040
- const expire = Date.now() +
1041
- Number(this.options.safeDeliveryTtl);
1042
- const workerKey = `${key}:worker:${(0, _1.uuid)()}:${expire}`;
1043
- if (!this.reader || !this.writer) {
1368
+ if (!this.reader || !this.writer || this.destroyed) {
1044
1369
  break;
1045
1370
  }
1371
+ const expire = Date.now() + Number(this.options.safeDeliveryTtl);
1372
+ const workerKey = `${key}:worker:${(0, node_crypto_1.randomUUID)()}:${expire}`;
1373
+ let msg;
1046
1374
  try {
1047
- await this.reader.brpoplpush(this.key, workerKey, 0);
1048
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
1375
+ msg = await this.reader.blmove(this.key, workerKey, 'RIGHT', 'LEFT', timeout);
1049
1376
  }
1050
- catch (_) {
1051
- // istanbul ignore next
1377
+ catch {
1378
+ // reader connection ended (stop/reconnect)
1052
1379
  break;
1053
1380
  }
1054
- const msgArr = await this.writer.lrange(workerKey, -1, 1);
1055
- if (!msgArr || (msgArr === null || msgArr === void 0 ? void 0 : msgArr.length) !== 1) {
1056
- // noinspection ExceptionCaughtLocallyJS
1057
- throw new Error('Wrong messages count');
1381
+ if (msg === null || msg === undefined) {
1382
+ // blocking pop timed out: regenerate the lease and retry
1383
+ continue;
1384
+ }
1385
+ try {
1386
+ this.process([key, msg]);
1387
+ this.writer
1388
+ .del(workerKey)
1389
+ .catch(e => this.logger.warn('OnReadSafe: del error', e));
1390
+ }
1391
+ catch (err) {
1392
+ // a single message failure must never kill the read loop
1393
+ this.emitError('OnReadSafe', 'safe reader failed', err);
1058
1394
  }
1059
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1060
- const [msg] = msgArr;
1061
- this.process([key, msg]);
1062
- this.writer.del(workerKey).catch(e => this.logger.warn('OnReadSafe: del error', e));
1063
1395
  }
1064
1396
  }
1065
- catch (err) {
1066
- // istanbul ignore next
1067
- this.emitError('OnReadSafe', 'safe reader failed', err);
1068
- }
1069
- }
1070
- /**
1071
- * Initializes a read process on the redis message queue
1072
- *
1073
- * @returns {RedisQueue}
1074
- */
1075
- read() {
1076
- // istanbul ignore next
1077
- if (!this.reader) {
1078
- this.logger.error(`${this.name}: reader connection is not initialized, pid ${process.pid} on redis host ${this.redisKey}!`);
1397
+ /**
1398
+ * Initializes a read process on the redis message queue
1399
+ *
1400
+ * @returns {RedisQueue}
1401
+ */
1402
+ read() {
1403
+ if (!this.reader) {
1404
+ this.logger.error(`${this.name}: reader connection is not initialized, pid ${process.pid} on redis host ${this.redisKey}!`);
1405
+ return this;
1406
+ }
1407
+ const runReader = this.options.safeDelivery
1408
+ ? this.readSafe
1409
+ : this.readUnsafe;
1410
+ process.nextTick(runReader.bind(this));
1079
1411
  return this;
1080
1412
  }
1081
- const readMethod = this.options.safeDelivery
1082
- ? 'readSafe'
1083
- : 'readUnsafe';
1084
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
1085
- process.nextTick(this[readMethod].bind(this));
1086
- return this;
1087
- }
1088
- /**
1089
- * Checks if the watcher connection is locked
1090
- *
1091
- * @access private
1092
- * @returns {Promise<boolean>}
1093
- */
1094
- async isLocked() {
1095
- if (this.writer) {
1096
- return Boolean(Number(await this.writer.exists(this.lockKey)));
1413
+ /**
1414
+ * Checks if the watcher connection is locked
1415
+ *
1416
+ * @returns {Promise<boolean>}
1417
+ */
1418
+ async isLocked() {
1419
+ if (this.writer) {
1420
+ return Boolean(Number(await this.writer.exists(this.lockKey)));
1421
+ }
1422
+ return false;
1097
1423
  }
1098
- return false;
1099
- }
1100
- /**
1101
- * Locks watcher connection
1102
- *
1103
- * @access private
1104
- * @returns {Promise<boolean>}
1105
- */
1106
- async lock() {
1107
- if (this.writer) {
1108
- return Boolean(Number(await this.writer.setnx(this.lockKey, '')));
1424
+ /**
1425
+ * Locks watcher connection
1426
+ *
1427
+ * @returns {Promise<boolean>}
1428
+ */
1429
+ async lock() {
1430
+ if (this.writer) {
1431
+ return Boolean(Number(await this.writer.setnx(this.lockKey, '')));
1432
+ }
1433
+ return false;
1109
1434
  }
1110
- return false;
1111
- }
1112
- /**
1113
- * Unlocks watcher connection
1114
- *
1115
- * @access private
1116
- * @returns {Promise<boolean>}
1117
- */
1118
- async unlock() {
1119
- if (this.writer) {
1120
- return Boolean(Number(await this.writer.del(this.lockKey)));
1435
+ /**
1436
+ * Unlocks watcher connection
1437
+ *
1438
+ * @returns {Promise<boolean>}
1439
+ */
1440
+ async unlock() {
1441
+ if (this.writer) {
1442
+ return Boolean(Number(await this.writer.del(this.lockKey)));
1443
+ }
1444
+ return false;
1121
1445
  }
1122
- return false;
1123
- }
1124
- // istanbul ignore next
1125
- /**
1126
- * Emits error
1127
- *
1128
- * @access private
1129
- * @param {string} eventName
1130
- * @param {string} message
1131
- * @param {Error} err
1132
- */
1133
- emitError(eventName, message, err) {
1134
- this.emit('error', err, eventName);
1135
- this.logger.error(`${this.name}: ${message}, pid ${process.pid} on redis host ${this.redisKey}:`, err);
1136
- this.verbose(`Error in event ${eventName}: ${message}, pid ${process.pid} on redis host ${this.redisKey}: ${err}`);
1137
- }
1138
- /**
1139
- * Acquires an owner for watcher connection to this instance of the queue
1140
- *
1141
- * @returns {Promise<void>}
1142
- */
1143
- // istanbul ignore next
1144
- async ownWatch() {
1145
- const owned = await this.lock();
1146
- if (owned) {
1147
- this.verbose('Watcher connection lock acquired!');
1148
- for (const script of Object.keys(this.scripts)) {
1149
- try {
1150
- const checksum = sha1(this.scripts[script].code);
1151
- this.scripts[script].checksum = checksum;
1152
- const scriptExists = await this.writer.script('EXISTS', checksum);
1153
- const loaded = (scriptExists || []).shift();
1154
- if (!loaded) {
1155
- await this.writer.script('LOAD', this.scripts[script].code);
1156
- }
1157
- }
1158
- catch (err) {
1159
- this.emitError('OnScriptLoad', 'script load error', err);
1160
- }
1446
+ /**
1447
+ * Emits error
1448
+ *
1449
+ * @param {string} eventName
1450
+ * @param {string} message
1451
+ * @param {unknown} err
1452
+ */
1453
+ emitError(eventName, message, err) {
1454
+ const error = err instanceof Error ? err : new Error(String(err));
1455
+ // emitting 'error' with no listeners attached would throw and
1456
+ // crash the process from a background routine - always log, but
1457
+ // only emit when someone actually listens
1458
+ if (this.listenerCount('error') > 0) {
1459
+ this.emit('error', error, eventName);
1161
1460
  }
1162
- this.watchOwner = true;
1163
- await this.connect('watcher', this.options);
1164
- this.watch();
1461
+ this.logger.error(`${this.name}: ${message}, pid ${process.pid} on redis host ${this.redisKey}:`, err);
1462
+ this.verbose(`Error in event ${eventName}: ${message}, pid ${process.pid} on redis host ${this.redisKey}: ${err}`);
1165
1463
  }
1166
- }
1167
- // istanbul ignore next
1168
- /**
1169
- * This method returns a watcher lock resolver function
1170
- *
1171
- * @access private
1172
- * @param {(...args: any[]) => void} resolve
1173
- * @param {(...args: any[]) => void} reject
1174
- * @return {() => Promise<any>}
1175
- */
1176
- watchLockResolver(resolve, reject) {
1177
- return (async () => {
1178
- try {
1179
- const noWatcher = !await this.watcherCount();
1180
- if (await this.isLocked() && noWatcher) {
1181
- await this.unlock();
1182
- await this.ownWatch();
1464
+ /**
1465
+ * Acquires an owner for watcher connection to this instance of the queue
1466
+ *
1467
+ * @returns {Promise<void>}
1468
+ */
1469
+ async ownWatch() {
1470
+ const owned = await this.lock();
1471
+ if (owned) {
1472
+ this.verbose('Watcher connection lock acquired!');
1473
+ for (const script of Object.keys(this.scripts)) {
1474
+ try {
1475
+ // checksums are pre-computed at construction time
1476
+ const checksum = this.scripts[script].checksum;
1477
+ const scriptExists = (await this.writer.script('EXISTS', checksum));
1478
+ const loaded = (scriptExists || []).shift();
1479
+ if (!loaded) {
1480
+ await this.writer.script('LOAD', this.scripts[script].code);
1481
+ }
1482
+ }
1483
+ catch (err) {
1484
+ this.emitError('OnScriptLoad', 'script load error', err);
1485
+ }
1183
1486
  }
1184
- resolve();
1487
+ this.watchOwner = true;
1488
+ await this.connect('watcher', this.options);
1489
+ this.watch();
1185
1490
  }
1186
- catch (err) {
1187
- reject(err);
1491
+ }
1492
+ /**
1493
+ * Attempts to take over an orphaned watcher lock: if the lock is held
1494
+ * but no watcher connection is actually alive, releases and re-acquires
1495
+ * ownership. Used to resolve a possible watcher deadlock.
1496
+ *
1497
+ * @returns {Promise<void>}
1498
+ */
1499
+ async resolveWatchLock() {
1500
+ const noWatcher = !(await this.watcherCount());
1501
+ if ((await this.isLocked()) && noWatcher) {
1502
+ await this.unlock();
1503
+ await this.ownWatch();
1188
1504
  }
1189
- });
1190
- }
1191
- /**
1192
- * Initializes a single watcher connection across all queues with the same
1193
- * prefix.
1194
- *
1195
- * @returns {Promise<void>}
1196
- */
1197
- // istanbul ignore next
1198
- async initWatcher() {
1199
- return new Promise((async (resolve, reject) => {
1505
+ }
1506
+ /**
1507
+ * Initializes a single watcher connection across all queues with the same
1508
+ * prefix.
1509
+ *
1510
+ * @returns {Promise<void>}
1511
+ */
1512
+ async initWatcher() {
1200
1513
  try {
1201
- if (!await this.watcherCount()) {
1202
- this.verbose('Initializing watcher...');
1203
- await this.ownWatch();
1204
- if (this.watchOwner && this.watcher) {
1205
- resolve();
1206
- }
1207
- else {
1208
- // check for possible deadlock to resolve
1209
- setTimeout(this.watchLockResolver(resolve, reject), intrand(1, 50));
1210
- }
1514
+ if (await this.watcherCount()) {
1515
+ return;
1211
1516
  }
1212
- else {
1213
- resolve();
1517
+ this.verbose('Initializing watcher...');
1518
+ await this.ownWatch();
1519
+ if (this.watchOwner && this.watcher) {
1520
+ return;
1214
1521
  }
1522
+ // another instance may hold the lock while its watcher died:
1523
+ // wait a small random interval (to avoid a thundering herd) and
1524
+ // try to resolve the possible deadlock
1525
+ await delay((0, helpers_1.randomInt)(1, 50));
1526
+ await this.resolveWatchLock();
1215
1527
  }
1216
1528
  catch (err) {
1217
1529
  this.logger.error(`${this.name}: error initializing watcher, pid ${process.pid} on redis host ${this.redisKey}`, err);
1218
- reject(err);
1530
+ throw err;
1219
1531
  }
1220
- }));
1221
- }
1222
- }
1532
+ }
1533
+ };
1534
+ })();
1223
1535
  exports.RedisQueue = RedisQueue;
1224
- /**
1225
- * Writer connections collection
1226
- *
1227
- * @type {{}}
1228
- */
1229
- RedisQueue.writers = {};
1230
- /**
1231
- * Watcher connections collection
1232
- *
1233
- * @type {{}}
1234
- */
1235
- RedisQueue.watchers = {};
1236
- __decorate([
1237
- (0, _1.profile)(),
1238
- __metadata("design:type", Function),
1239
- __metadata("design:paramtypes", []),
1240
- __metadata("design:returntype", Promise)
1241
- ], RedisQueue.prototype, "stop", null);
1242
- __decorate([
1243
- (0, _1.profile)(),
1244
- __metadata("design:type", Function),
1245
- __metadata("design:paramtypes", []),
1246
- __metadata("design:returntype", Promise)
1247
- ], RedisQueue.prototype, "destroy", null);
1248
- __decorate([
1249
- (0, _1.profile)(),
1250
- __metadata("design:type", Function),
1251
- __metadata("design:paramtypes", []),
1252
- __metadata("design:returntype", Promise)
1253
- ], RedisQueue.prototype, "clear", null);
1254
- __decorate([
1255
- (0, _1.profile)(),
1256
- __metadata("design:type", Function),
1257
- __metadata("design:paramtypes", []),
1258
- __metadata("design:returntype", Promise)
1259
- ], RedisQueue.prototype, "queueLength", null);
1260
- __decorate([
1261
- (0, _1.profile)(),
1262
- __metadata("design:type", Function),
1263
- __metadata("design:paramtypes", []),
1264
- __metadata("design:returntype", void 0)
1265
- ], RedisQueue.prototype, "destroyWatcher", null);
1266
- __decorate([
1267
- (0, _1.profile)(),
1268
- __metadata("design:type", Function),
1269
- __metadata("design:paramtypes", []),
1270
- __metadata("design:returntype", void 0)
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);
1278
1536
  //# sourceMappingURL=RedisQueue.js.map