@imqueue/core 3.2.4 → 3.3.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.
package/src/RedisQueue.js CHANGED
@@ -73,8 +73,6 @@ const SCAN_COUNT = '1000';
73
73
  /**
74
74
  * ioredis retry strategy that disables the built-in reconnection — this
75
75
  * queue performs its own capped-backoff reconnection instead.
76
- *
77
- * @returns {null}
78
76
  */
79
77
  function noRetryStrategy() {
80
78
  return null;
@@ -82,12 +80,25 @@ function noRetryStrategy() {
82
80
  /**
83
81
  * Resolves after the given number of milliseconds.
84
82
  *
85
- * @param {number} ms
86
- * @returns {Promise<void>}
83
+ * @param ms - number of milliseconds to wait
87
84
  */
88
85
  function delay(ms) {
89
86
  return new Promise(resolve => setTimeout(resolve, ms));
90
87
  }
88
+ /**
89
+ * Default option values applied to every queue instance: `localhost:6379`,
90
+ * prefix `imq`, `console` as the logger, cleanup off with filter `'*'`, safe
91
+ * delivery off with a 5000 ms lease TTL, gzip off, a 5000 ms watcher check
92
+ * interval, and process signal handling on.
93
+ *
94
+ * @remarks
95
+ * Constructor options are shallow-merged over this object, so passing an explicit
96
+ * `undefined` overrides a default rather than falling back to it.
97
+ *
98
+ * The object is exported live and is not frozen — mutating it changes the
99
+ * defaults for every queue constructed afterwards in the process. Prefer
100
+ * per-instance options.
101
+ */
91
102
  export const DEFAULT_IMQ_OPTIONS = {
92
103
  host: 'localhost',
93
104
  port: 6379,
@@ -101,18 +112,63 @@ export const DEFAULT_IMQ_OPTIONS = {
101
112
  watcherCheckDelay: 5000,
102
113
  handleSignals: true,
103
114
  };
115
+ /**
116
+ * Time in milliseconds allowed for releasing watcher locks when a shutdown
117
+ * signal is received, before the process is force-exited. Defaults to 1000;
118
+ * override with the `IMQ_SHUTDOWN_TIMEOUT` environment variable.
119
+ *
120
+ * @remarks
121
+ * This is not a drain period — running `message` handlers are not awaited.
122
+ * The value is read once when the module is loaded, and a non-numeric value falls
123
+ * back to the default. Relevant only while {@link IMQOptions.handleSignals} is
124
+ * enabled.
125
+ */
104
126
  export const IMQ_SHUTDOWN_TIMEOUT = envInt('IMQ_SHUTDOWN_TIMEOUT', 1000);
105
127
  /**
106
128
  * Grace period (ms) for a graceful QUIT to complete before a channel is
107
129
  * forcibly disconnected. A reader blocked on an infinite BRPOP/BLMOVE can
108
130
  * never let QUIT through, so without this the socket would leak and keep
109
131
  * the process alive.
132
+ *
133
+ * @remarks
134
+ * Defaults to 1000; override with the `IMQ_CONNECTION_QUIT_TIMEOUT` environment
135
+ * variable, which is read once when the module is loaded. Applies to the writer,
136
+ * watcher and subscription channels — the reader is disconnected immediately
137
+ * without attempting `QUIT`.
110
138
  */
111
139
  export const IMQ_CONNECTION_QUIT_TIMEOUT = envInt('IMQ_CONNECTION_QUIT_TIMEOUT', 1000);
112
140
  const IMQ_REDIS_MAX_LISTENERS_LIMIT = envInt('IMQ_REDIS_MAX_LISTENERS_LIMIT', 10000);
113
141
  /**
114
- * Class RedisQueue
115
- * Implements a simple messaging queue over redis.
142
+ * Redis-backed message queue with at-least-once delivery — the default
143
+ * {@link IMessageQueue} implementation, and what {@link IMQ.create} returns for a
144
+ * single-server configuration.
145
+ *
146
+ * @remarks
147
+ * Connection model: the reader is per instance and exists only in
148
+ * {@link IMQMode.BOTH} or {@link IMQMode.WORKER} mode, while the writer and
149
+ * watcher connections are shared per `host:port` across every queue in the
150
+ * process and reference-counted. Exactly one queue per key prefix is elected as
151
+ * the watcher through a `<prefix>:watch:lock` key, and that owner also releases
152
+ * delayed messages, recovers abandoned safe-delivery hand-offs and — when
153
+ * {@link IMQOptions.cleanup} is on — prunes orphaned keys.
154
+ *
155
+ * Lifecycle: {@link RedisQueue.start} is required before consuming or
156
+ * publishing, while {@link RedisQueue.send} starts the queue lazily.
157
+ * {@link RedisQueue.stop} only stops consuming; use
158
+ * {@link RedisQueue.destroy} to release the watcher lock, the timers and the
159
+ * connections.
160
+ *
161
+ * Reconnection is handled by the queue itself — ioredis's own retry strategy is
162
+ * disabled in favour of a capped exponential backoff from 1 s to 30 s per
163
+ * channel.
164
+ *
165
+ * Events (typed by {@link EventMap}): `message`, with the payload, the message id
166
+ * and the sending queue's name; and `error`, with the error and the name of the
167
+ * internal routine that caught it (`OnMessage`, `OnProcessDelayed`,
168
+ * `OnSafeDelivery`, `OnWatch`, `OnConfig`, `OnScriptLoad`, `OnReadUnsafe` or
169
+ * `OnReadSafe`). Background errors are emitted only when at least one `error`
170
+ * listener is attached — otherwise they are logged and swallowed, so attach one
171
+ * if you need to observe them.
116
172
  */
117
173
  let RedisQueue = (() => {
118
174
  let _classSuper = EventEmitter;
@@ -147,85 +203,63 @@ let RedisQueue = (() => {
147
203
  mode;
148
204
  /**
149
205
  * Writer connections collection
150
- *
151
- * @type {{}}
152
206
  */
153
207
  static writers = {};
154
208
  /**
155
209
  * Watcher connections collection
156
- *
157
- * @type {{}}
158
210
  */
159
211
  static watchers = {};
160
212
  /**
161
213
  * Number of started queue instances per shared writer connection key
162
- *
163
- * @type {{}}
164
214
  */
165
215
  static writerRefs = {};
166
216
  /**
167
217
  * All started queue instances within the current process
168
- *
169
- * @type {Set<RedisQueue>}
170
218
  */
171
219
  static instances = new Set();
172
220
  /**
173
221
  * True when process-level signal handlers were bound
174
- *
175
- * @type {boolean}
176
222
  */
177
223
  static signalsBound = false;
178
224
  /**
179
- * @event message (message: JsonObject, id: string, from: string)
180
- */
181
- /**
182
- * This queue instance options
225
+ * The effective options for this queue: {@link DEFAULT_IMQ_OPTIONS} merged
226
+ * with the values passed to the constructor.
183
227
  *
184
- * @type {IMQOptions}
228
+ * @remarks
229
+ * Treat this as read-only configuration. Some options are captured at
230
+ * construction time — `useGzip`, `host` and `port` — so changing them here has
231
+ * no effect, while `safeDelivery`, `safeDeliveryTtl`, `cleanup`,
232
+ * `cleanupFilter` and `verbose` are re-read at runtime.
185
233
  */
186
234
  options;
187
235
  /**
188
236
  * Reader connection associated with this queue instance
189
- *
190
- * @type {IRedisClient}
191
237
  */
192
238
  reader;
193
239
  /**
194
240
  * Channel connection associated with this queue instance
195
241
  * Specially designed for client subscriptions to server-emitted events
196
- *
197
- * @type {IRedisClient}
198
242
  */
199
243
  subscription;
200
244
  /**
201
245
  * Channel name for subscriptions
202
- *
203
- * @type {string}
204
246
  */
205
247
  subscriptionName;
206
248
  /**
207
249
  * Init state for this queue instance
208
- *
209
- * @type {boolean}
210
250
  */
211
251
  initialized = false;
212
252
  /**
213
253
  * Signals if the queue was destroyed
214
- *
215
- * @type {boolean}
216
254
  */
217
255
  destroyed = false;
218
256
  /**
219
257
  * True if the current instance owns a watcher connection, false otherwise
220
- *
221
- * @type {boolean}
222
258
  */
223
259
  watchOwner = false;
224
260
  /**
225
261
  * Subscription handlers registered through subscribe(). Kept to be
226
262
  * able to restore the subscription after a connection replacement.
227
- *
228
- * @type {Array<(data: JsonObject) => void>}
229
263
  */
230
264
  subscriptionHandlers = [];
231
265
  /**
@@ -257,13 +291,19 @@ let RedisQueue = (() => {
257
291
  reconnectAttempts = {};
258
292
  reconnecting = {};
259
293
  /**
260
- * This queue instance unique key (identifier), for internal use
294
+ * The `host:port` address of the redis server this queue talks to.
295
+ *
296
+ * @remarks
297
+ * This is not an instance identifier. It is deliberately shared by every
298
+ * queue in the process that targets the same server, and is the key under
299
+ * which the writer and watcher connections (and the writer reference count)
300
+ * are stored. It includes neither the key prefix nor the credentials, so two
301
+ * queues differing only in those share the same underlying connections — the
302
+ * first one created wins.
261
303
  */
262
304
  redisKey;
263
305
  /**
264
306
  * Lua scripts for redis
265
- *
266
- * @type {{moveDelayed: {code: string}}}
267
307
  */
268
308
  scripts = {
269
309
  moveDelayed: {
@@ -288,23 +328,44 @@ let RedisQueue = (() => {
288
328
  /**
289
329
  * Serializes a given data object into string
290
330
  *
291
- * @param {unknown} data
292
- * @returns {string}
331
+ * @param data -
293
332
  */
294
333
  pack;
295
334
  /**
296
335
  * Deserialize string data into an object
297
336
  *
298
- * @param {string} data
299
- * @returns {unknown}
337
+ * @param data -
300
338
  */
301
339
  unpack;
302
340
  /**
303
- * @param {string} name
304
- * @param {IMQOptions} [options]
305
- * @param {IMQMode} [mode]
341
+ * Creates a queue handle. No connection is opened here — call
342
+ * {@link RedisQueue.start}, or {@link RedisQueue.send}, which starts the
343
+ * queue implicitly.
344
+ *
345
+ * @param name - queue name; the underlying Redis list key becomes
346
+ * `<prefix>:<name>`
347
+ * @param options - partial options merged over {@link DEFAULT_IMQ_OPTIONS}
348
+ * @param mode - whether this handle produces, consumes, or both; defaults to
349
+ * {@link IMQMode.BOTH}
350
+ *
351
+ * @remarks
352
+ * The constructor performs no I/O. It resolves the effective options, selects
353
+ * the serializer pair from {@link IMQOptions.useGzip} once, and derives
354
+ * the `host:port` key under which the shared connections are stored — so
355
+ * changing `useGzip`, `host` or `port` on `options` afterwards has no effect.
306
356
  */
307
- constructor(name, options, mode = IMQMode.BOTH) {
357
+ constructor(
358
+ /**
359
+ * The queue name. The underlying redis list key is `<prefix>:<name>`, the
360
+ * same name is the default pub/sub channel used by
361
+ * {@link RedisQueue.publish}, and it is the `from` value carried by
362
+ * messages this queue sends.
363
+ *
364
+ * @remarks
365
+ * Assign it before {@link RedisQueue.start} — a running reader keeps
366
+ * consuming the key it was started with.
367
+ */
368
+ name, options, mode = IMQMode.BOTH) {
308
369
  super();
309
370
  this.name = name;
310
371
  this.mode = mode;
@@ -324,11 +385,26 @@ let RedisQueue = (() => {
324
385
  }
325
386
  /**
326
387
  * Creates a subscription channel over redis and sets up channel
327
- * data read handler
388
+ * data read handler. The effective Redis channel is `<prefix>:<channel>`.
389
+ *
390
+ * @param channel - channel name within this queue's prefix namespace
391
+ * @param handler - invoked with the parsed payload of each published message
392
+ * @throws TypeError when no channel name is given, or when a different
393
+ * channel name is supplied while a subscription is already open — an
394
+ * instance supports exactly one channel until
395
+ * {@link RedisQueue.unsubscribe} resets it
328
396
  *
329
- * @param {string} channel
330
- * @param {(data: JsonObject) => void} handler
331
- * @returns {Promise<void>}
397
+ * @remarks
398
+ * Calling this again with the same channel adds another handler rather than
399
+ * replacing the existing one, and every handler is invoked for each message.
400
+ *
401
+ * A dedicated subscription connection is created on demand, so
402
+ * {@link RedisQueue.start} is not required, and the subscription is
403
+ * re-established automatically after a reconnect.
404
+ *
405
+ * Payloads are parsed as plain JSON ({@link IMQOptions.useGzip} does not
406
+ * apply to pub/sub). Neither a parse error nor an exception thrown by the
407
+ * handler is contained by the queue, so handlers should not throw.
332
408
  */
333
409
  async subscribe(channel, handler) {
334
410
  if (!channel) {
@@ -351,8 +427,8 @@ let RedisQueue = (() => {
351
427
  * Attaches a subscription message handler to a given channel
352
428
  * connection
353
429
  *
354
- * @param {IRedisClient} chan
355
- * @param {(data: JsonObject) => void} handler
430
+ * @param chan -
431
+ * @param handler -
356
432
  */
357
433
  attachSubscriptionHandler(chan, handler) {
358
434
  const fcn = `${this.options.prefix}:${this.subscriptionName}`;
@@ -367,8 +443,6 @@ let RedisQueue = (() => {
367
443
  * Restores the subscription state on a freshly created subscription
368
444
  * connection. Used after a connection replacement on reconnection,
369
445
  * otherwise the new connection would silently stay unsubscribed.
370
- *
371
- * @returns {Promise<void>}
372
446
  */
373
447
  async restoreSubscription() {
374
448
  const chan = this.subscription;
@@ -385,9 +459,14 @@ let RedisQueue = (() => {
385
459
  this.verbose(`Restored subscription to ${this.subscriptionName}`);
386
460
  }
387
461
  /**
388
- * Closes subscription channel
462
+ * Closes the subscription connection and forgets the channel name together
463
+ * with every handler registered through {@link RedisQueue.subscribe}.
389
464
  *
390
- * @returns {Promise<void>}
465
+ * @remarks
466
+ * A later {@link RedisQueue.subscribe} must register its handlers again, and
467
+ * may use a different channel name. A no-op when the queue was never
468
+ * subscribed, and it never rejects — failures during unsubscribe are logged
469
+ * only. Called automatically by {@link RedisQueue.destroy}.
391
470
  */
392
471
  async unsubscribe() {
393
472
  if (this.subscription) {
@@ -419,8 +498,20 @@ let RedisQueue = (() => {
419
498
  * can be used to implement broadcasting some messages to other subscribers
420
499
  * on other PubSub channels.
421
500
  *
422
- * @param {string} [toName]
423
- * @param {JsonObject} data
501
+ * @param data - payload to publish as a channel message
502
+ * @param toName - optional different pub/sub name to publish to; must be a
503
+ * bare name inside the same prefix namespace, not a full Redis channel
504
+ * key
505
+ * @throws TypeError when the queue has no writer connection
506
+ *
507
+ * @remarks
508
+ * Unlike {@link RedisQueue.send}, this does not start the queue
509
+ * implicitly, so {@link RedisQueue.start} must have completed first. It is
510
+ * allowed in any {@link IMQMode}, including `WORKER`.
511
+ *
512
+ * The payload is always plain JSON — {@link IMQOptions.useGzip} applies to
513
+ * queue messages only. Redis pub/sub drops the message silently when nobody
514
+ * is subscribed.
424
515
  */
425
516
  async publish(data, toName) {
426
517
  if (!this.writer) {
@@ -433,9 +524,25 @@ let RedisQueue = (() => {
433
524
  `);
434
525
  }
435
526
  /**
436
- * Initializes and starts current queue routines
527
+ * Initializes and starts current queue routines: opens the writer (and, in
528
+ * {@link IMQMode.BOTH} or {@link IMQMode.WORKER} mode, the reader), joins
529
+ * watcher election and starts the periodic watcher check.
530
+ *
531
+ * @returns this queue instance
532
+ * @throws TypeError when the queue was constructed without a name
533
+ *
534
+ * @remarks
535
+ * Idempotent — a second call on a started queue resolves immediately — and
536
+ * the queue can be restarted after {@link RedisQueue.stop}.
437
537
  *
438
- * @returns {Promise<RedisQueue>}
538
+ * Unless {@link IMQOptions.handleSignals} is false, this installs
539
+ * process-level SIGTERM/SIGINT/SIGABRT handlers that release watcher locks
540
+ * and then exit the process without waiting for in-flight handlers.
541
+ *
542
+ * If watcher initialization fails the returned promise rejects, but the
543
+ * writer connection, the instance registration and any acquired watcher lock
544
+ * remain in place — call {@link RedisQueue.destroy} to clean up after a
545
+ * failed start.
439
546
  */
440
547
  async start() {
441
548
  if (!this.name) {
@@ -489,8 +596,6 @@ let RedisQueue = (() => {
489
596
  /**
490
597
  * Frees watcher locks held by all started queue instances and exits
491
598
  * the process, forcing exit after IMQ_SHUTDOWN_TIMEOUT at the latest.
492
- *
493
- * @returns {Promise<void>}
494
599
  */
495
600
  static async freeAndExit() {
496
601
  let exitCode = 0;
@@ -523,8 +628,6 @@ let RedisQueue = (() => {
523
628
  * A single watcher-existence check tick: re-elects a watcher owner when
524
629
  * none exists and moves due to delayed messages as a keyspace-notification
525
630
  * fallback. Errors are contained so the interval never crashes.
526
- *
527
- * @returns {Promise<void>}
528
631
  */
529
632
  async runWatcherCheck() {
530
633
  if (this.watcherCheckBusy || this.destroyed || !this.writer) {
@@ -556,13 +659,32 @@ let RedisQueue = (() => {
556
659
  }
557
660
  }
558
661
  /**
559
- * Sends a given message to a given queue (by name)
560
- *
561
- * @param {string} toQueue
562
- * @param {JsonObject} message
563
- * @param {number} [delay]
564
- * @param {(err: Error) => void} [errorHandler]
565
- * @returns {Promise<RedisQueue>}
662
+ * Sends a given message to a given queue (by name).
663
+ *
664
+ * @param toQueue - name of the destination queue
665
+ * @param message - message payload; must be a JSON object
666
+ * @param delay - if specified, the message becomes available in the target
667
+ * queue only after this many milliseconds. This is a minimum, not a
668
+ * schedule — the message is released by the watcher, so availability
669
+ * may lag by up to {@link IMQOptions.watcherCheckDelay}. A delay of
670
+ * `0` or `undefined` sends immediately.
671
+ * @param errorHandler - invoked when the write to Redis fails; this is the
672
+ * only way to observe such a failure, since the returned promise does
673
+ * not reject for it
674
+ * @returns the identifier assigned to the message. It is generated locally
675
+ * before the write is issued, so it is available even if the write
676
+ * later fails.
677
+ * @throws TypeError when the queue is in {@link IMQMode.WORKER}-only mode, or
678
+ * when a writer connection cannot be established
679
+ *
680
+ * @remarks
681
+ * The returned promise resolves as soon as the write has been dispatched —
682
+ * the Redis reply is not awaited — so a resolved promise is not evidence that
683
+ * the message was enqueued.
684
+ *
685
+ * Starts the queue implicitly when it has not been started yet, which has
686
+ * process-wide side effects: it may install signal handlers and make this
687
+ * instance the watcher owner.
566
688
  */
567
689
  async send(toQueue, message, delay, errorHandler) {
568
690
  if (!this.isPublisher()) {
@@ -619,9 +741,23 @@ let RedisQueue = (() => {
619
741
  return id;
620
742
  }
621
743
  /**
622
- * Stops current queue routines
744
+ * Stops consuming messages by tearing down this instance's reader
745
+ * connection.
746
+ *
747
+ * @returns this queue instance
623
748
  *
624
- * @returns {Promise<RedisQueue>}
749
+ * @remarks
750
+ * The queue remains usable as a producer: the shared writer, any held watcher
751
+ * lock, the watcher-check and maintenance intervals, the subscription
752
+ * connection and the process signal handlers all stay in place, and
753
+ * {@link RedisQueue.start} can resume consumption. Use
754
+ * {@link RedisQueue.destroy} to release resources — an instance that is only
755
+ * stopped stays registered in a process-wide registry and is not
756
+ * garbage-collected.
757
+ *
758
+ * The reader socket is dropped immediately rather than closed with a graceful
759
+ * `QUIT`, so Redis stops treating it as a consumer at once and cannot hand it
760
+ * a message the torn-down read loop would drop.
625
761
  */
626
762
  async stop() {
627
763
  this.verbose('Stopping queue...');
@@ -640,8 +776,23 @@ let RedisQueue = (() => {
640
776
  * destroying one handle (e.g., on scale-down) never wipes messages
641
777
  * still pending for other producers/consumers.
642
778
  *
643
- * @param {boolean} [clearData] - when true, also clears queue data
644
- * @returns {Promise<void>}
779
+ * @param clearData - when true, also clears queue data
780
+ *
781
+ * @remarks
782
+ * The writer connection is shared per `host:port` and reference-counted, so
783
+ * it stays open while another started instance in the process still uses it.
784
+ *
785
+ * All event listeners are removed, including the caller's `message` and
786
+ * `error` handlers — and because {@link RedisQueue.start} can revive the
787
+ * instance, re-register them if you restart it or messages will be consumed
788
+ * and silently discarded.
789
+ *
790
+ * With `clearData` set, only the main and delayed keys are removed: messages
791
+ * currently leased to a worker key under {@link IMQOptions.safeDelivery} are
792
+ * not, and the watcher will re-queue them once their lease expires — so
793
+ * messages can reappear after a clearing destroy.
794
+ *
795
+ * Never rejects; unlock and clear failures are logged.
645
796
  */
646
797
  async destroy(clearData = false) {
647
798
  this.verbose('Destroying queue...');
@@ -664,9 +815,17 @@ let RedisQueue = (() => {
664
815
  this.verbose('Queue destroyed!');
665
816
  }
666
817
  /**
667
- * Clears queue data in redis
818
+ * Deletes this queue's message list and its delayed-message set from redis.
668
819
  *
669
- * @returns {Promise<void>}
820
+ * @returns this queue instance
821
+ *
822
+ * @remarks
823
+ * A no-op that resolves successfully when the queue has no writer connection.
824
+ * In-flight messages held in worker keys under
825
+ * {@link IMQOptions.safeDelivery} are not removed and may be re-queued by the
826
+ * watcher after their lease expires, so this does not guarantee the queue
827
+ * stays empty. Errors are logged rather than thrown, so success cannot be
828
+ * inferred from a resolved promise.
670
829
  */
671
830
  async clear() {
672
831
  if (!this.writer) {
@@ -688,9 +847,16 @@ let RedisQueue = (() => {
688
847
  return this;
689
848
  }
690
849
  /**
691
- * Retrieves the current count of messages in the queue
850
+ * Returns the number of messages currently waiting in this queue's main list.
851
+ *
852
+ * @returns count of messages waiting to be consumed
692
853
  *
693
- * @returns {Promise<number>}
854
+ * @remarks
855
+ * Delayed messages that are not yet due, and messages currently leased to a
856
+ * worker under {@link IMQOptions.safeDelivery}, are not counted — so this
857
+ * is not the amount of outstanding work. Returns `0` when the queue has no
858
+ * writer connection, which makes "disconnected" indistinguishable from
859
+ * "empty"; it never throws.
694
860
  */
695
861
  async queueLength() {
696
862
  if (!this.writer) {
@@ -700,16 +866,12 @@ let RedisQueue = (() => {
700
866
  }
701
867
  /**
702
868
  * Returns true if publisher mode is enabled on this queue, false otherwise.
703
- *
704
- * @returns {boolean}
705
869
  */
706
870
  isPublisher() {
707
871
  return this.mode === IMQMode.BOTH || this.mode === IMQMode.PUBLISHER;
708
872
  }
709
873
  /**
710
874
  * Returns true if worker mode is enabled on this queue, false otherwise.
711
- *
712
- * @returns {boolean}
713
875
  */
714
876
  isWorker() {
715
877
  return this.mode === IMQMode.BOTH || this.mode === IMQMode.WORKER;
@@ -718,52 +880,42 @@ let RedisQueue = (() => {
718
880
  * Returns false only when this queue is known to be unable to accept
719
881
  * writes right now — i.e., it has a writer connection currently
720
882
  * in a non-ready (reconnecting/closed) state. A queue that has not yet
721
- * connected is considered available, since a sending lazily connects it.
883
+ * connected is considered available, since sending connects it lazily.
722
884
  * Used for health-aware routing in the clustered queue.
723
885
  *
724
- * @returns {boolean}
886
+ * @remarks
887
+ * The writer connection is shared per `host:port` within the process, so this
888
+ * reflects the health of that server connection rather than of this instance
889
+ * alone — every queue pointing at the same server reports the same value.
725
890
  */
726
891
  get available() {
727
892
  return !this.writer || this.writer.status === 'ready';
728
893
  }
729
894
  /**
730
- * Writer connection associated with this queue instance
731
- *
732
- * @type {IRedisClient}
895
+ * Writer connection associated with this queue instance. Shared by every
896
+ * queue in the process that targets the same `host:port`.
733
897
  */
734
898
  get writer() {
735
899
  return RedisQueue.writers[this.redisKey];
736
900
  }
737
- /**
738
- * Writer connection setter.
739
- *
740
- * @param {IRedisClient} conn
741
- */
742
901
  set writer(conn) {
743
902
  RedisQueue.writers[this.redisKey] = conn;
744
903
  }
745
904
  /**
746
- * Watcher connection instance associated with this queue instance
747
- *
748
- * @type {IRedisClient}
905
+ * Watcher connection associated with this queue instance. Shared by every
906
+ * queue in the process that targets the same `host:port`; at most one queue
907
+ * per prefix is the elected watcher owner.
749
908
  */
750
909
  get watcher() {
751
910
  return RedisQueue.watchers[this.redisKey];
752
911
  }
753
- /**
754
- * Watcher setter sets the watcher connection property for this
755
- * queue instance
756
- *
757
- * @param {IRedisClient} conn
758
- */
759
912
  set watcher(conn) {
760
913
  RedisQueue.watchers[this.redisKey] = conn;
761
914
  }
762
915
  /**
763
916
  * Returns the connection currently bound to the given channel, if any.
764
917
  *
765
- * @param {RedisConnectionChannel} channel
766
- * @returns {IRedisClient | undefined}
918
+ * @param channel -
767
919
  */
768
920
  connectionOf(channel) {
769
921
  switch (channel) {
@@ -780,8 +932,8 @@ let RedisQueue = (() => {
780
932
  /**
781
933
  * Binds the given connection to the given channel.
782
934
  *
783
- * @param {RedisConnectionChannel} channel
784
- * @param {IRedisClient} conn
935
+ * @param channel -
936
+ * @param conn -
785
937
  */
786
938
  bindConnection(channel, conn) {
787
939
  switch (channel) {
@@ -801,23 +953,18 @@ let RedisQueue = (() => {
801
953
  }
802
954
  /**
803
955
  * Logger instance associated with the current queue instance
804
- * @type {ILogger}
805
956
  */
806
957
  get logger() {
807
958
  return this.options.logger || console;
808
959
  }
809
960
  /**
810
961
  * Return a lock key for watcher connection
811
- *
812
- * @returns {string}
813
962
  */
814
963
  get lockKey() {
815
964
  return `${this.options.prefix}:watch:lock`;
816
965
  }
817
966
  /**
818
967
  * Returns current queue key
819
- *
820
- * @returns {string}
821
968
  */
822
969
  get key() {
823
970
  return `${this.options.prefix}:${this.name}`;
@@ -907,9 +1054,8 @@ let RedisQueue = (() => {
907
1054
  /**
908
1055
  * Establishes a given connection channel by its name
909
1056
  *
910
- * @param {RedisConnectionChannel} channel
911
- * @param {IMQOptions} options
912
- * @returns {Promise<IRedisClient>}
1057
+ * @param channel -
1058
+ * @param options -
913
1059
  */
914
1060
  async connect(channel, options) {
915
1061
  this.verbose(`Connecting to ${channel} channel...`);
@@ -968,8 +1114,7 @@ let RedisQueue = (() => {
968
1114
  * Schedules custom reconnection for a given channel with capped
969
1115
  * exponential backoff
970
1116
  *
971
- * @param {RedisConnectionChannel} channel
972
- * @private
1117
+ * @param channel -
973
1118
  */
974
1119
  scheduleReconnect(channel) {
975
1120
  if (this.destroyed || this.reconnecting[channel]) {
@@ -991,8 +1136,7 @@ let RedisQueue = (() => {
991
1136
  * rescheduling itself on failure. Errors are handled internally, so the
992
1137
  * scheduled timer never produces an unhandled rejection.
993
1138
  *
994
- * @param {RedisConnectionChannel} channel
995
- * @returns {Promise<void>}
1139
+ * @param channel -
996
1140
  */
997
1141
  async reconnectNow(channel) {
998
1142
  if (this.destroyed) {
@@ -1036,10 +1180,9 @@ let RedisQueue = (() => {
1036
1180
  /**
1037
1181
  * Generates channel name
1038
1182
  *
1039
- * @param {string} contextName
1040
- * @param {string} prefix
1041
- * @param {RedisConnectionChannel} name
1042
- * @returns {string}
1183
+ * @param contextName -
1184
+ * @param prefix -
1185
+ * @param name -
1043
1186
  */
1044
1187
  getChannelName(contextName, prefix, name) {
1045
1188
  const uniqueSuffix = `pid:${process.pid}:host:${hostname()}`;
@@ -1048,8 +1191,7 @@ let RedisQueue = (() => {
1048
1191
  /**
1049
1192
  * Builds and returns connection error handler
1050
1193
  *
1051
- * @param {RedisConnectionChannel} channel
1052
- * @returns {(err: Error) => void}
1194
+ * @param channel -
1053
1195
  */
1054
1196
  onErrorHandler(channel) {
1055
1197
  return (error) => {
@@ -1068,8 +1210,7 @@ let RedisQueue = (() => {
1068
1210
  /**
1069
1211
  * Builds and returns redis connection close handler
1070
1212
  *
1071
- * @param {RedisConnectionChannel} channel
1072
- * @returns {() => void}
1213
+ * @param channel -
1073
1214
  */
1074
1215
  onCloseHandler(channel) {
1075
1216
  this.verbose(`Redis ${channel} is closing...`);
@@ -1084,8 +1225,7 @@ let RedisQueue = (() => {
1084
1225
  /**
1085
1226
  * Processes given redis-queue message
1086
1227
  *
1087
- * @param {[string, string]} msg
1088
- * @returns {RedisQueue}
1228
+ * @param msg -
1089
1229
  */
1090
1230
  process(msg) {
1091
1231
  const [queue, data] = msg;
@@ -1103,8 +1243,6 @@ let RedisQueue = (() => {
1103
1243
  }
1104
1244
  /**
1105
1245
  * Returns the number of established watcher connections on redis
1106
- *
1107
- * @returns {Promise<number>}
1108
1246
  */
1109
1247
  async watcherCount() {
1110
1248
  if (!this.writer) {
@@ -1120,8 +1258,7 @@ let RedisQueue = (() => {
1120
1258
  /**
1121
1259
  * Processes delayed a message by its given redis key
1122
1260
  *
1123
- * @param {string} key
1124
- * @returns {Promise<void>}
1261
+ * @param key -
1125
1262
  */
1126
1263
  async processDelayed(key) {
1127
1264
  try {
@@ -1149,8 +1286,6 @@ let RedisQueue = (() => {
1149
1286
  }
1150
1287
  /**
1151
1288
  * Watch routine
1152
- *
1153
- * @returns {Promise<void>}
1154
1289
  */
1155
1290
  async processWatch() {
1156
1291
  const now = Date.now();
@@ -1166,7 +1301,13 @@ let RedisQueue = (() => {
1166
1301
  }
1167
1302
  catch (err) {
1168
1303
  this.emitError('OnSafeDelivery', 'safe queue message delivery problem', err);
1169
- this.cleanSafeCheckInterval();
1304
+ // abandon only this sweep — the maintenance interval must keep
1305
+ // running so the next tick retries. Tearing it down here would
1306
+ // be permanent: watch() re-arms the interval only once per
1307
+ // watcher connection, guarded by `__ready__`, so a single
1308
+ // transient SCAN/LMOVE failure would silently disable lease
1309
+ // recovery and cleanup for that connection's whole lifetime.
1310
+ // A genuinely lost writer is handled by runSafeCheck().
1170
1311
  return;
1171
1312
  }
1172
1313
  }
@@ -1174,9 +1315,8 @@ let RedisQueue = (() => {
1174
1315
  /**
1175
1316
  * Process given keys from a message queue
1176
1317
  *
1177
- * @param {string[]} keys
1178
- * @param {number} now
1179
- * @returns {Promise<void>}
1318
+ * @param keys -
1319
+ * @param now -
1180
1320
  */
1181
1321
  async processKeys(keys, now) {
1182
1322
  if (!keys.length) {
@@ -1200,8 +1340,7 @@ let RedisQueue = (() => {
1200
1340
  /**
1201
1341
  * Watch message processor
1202
1342
  *
1203
- * @param {...any[]} args
1204
- * @returns {Promise<void>}
1343
+ * @param args -
1205
1344
  */
1206
1345
  async onWatchMessage(...args) {
1207
1346
  try {
@@ -1227,8 +1366,6 @@ let RedisQueue = (() => {
1227
1366
  }
1228
1367
  /**
1229
1368
  * Setups watch a process on delayed messages
1230
- *
1231
- * @returns {RedisQueue}
1232
1369
  */
1233
1370
  watch() {
1234
1371
  if (!this.writer || !this.watcher || this.watcher.__ready__) {
@@ -1258,8 +1395,6 @@ let RedisQueue = (() => {
1258
1395
  /**
1259
1396
  * A single safe-delivery maintenance tick: recovers messages from dead
1260
1397
  * workers (when safe delivery is on) and prunes orphaned keys.
1261
- *
1262
- * @returns {Promise<void>}
1263
1398
  */
1264
1399
  async runSafeCheck() {
1265
1400
  if (!this.writer) {
@@ -1273,8 +1408,6 @@ let RedisQueue = (() => {
1273
1408
  }
1274
1409
  /**
1275
1410
  * Cleans up orphaned keys from redis
1276
- *
1277
- * @returns {Promise<RedisQueue | undefined>}
1278
1411
  */
1279
1412
  async processCleanup() {
1280
1413
  this.verbose('Cleaning up orphaned keys...');
@@ -1403,8 +1536,6 @@ let RedisQueue = (() => {
1403
1536
  }
1404
1537
  /**
1405
1538
  * Initializes a read process on the redis message queue
1406
- *
1407
- * @returns {RedisQueue}
1408
1539
  */
1409
1540
  read() {
1410
1541
  if (!this.reader) {
@@ -1419,8 +1550,6 @@ let RedisQueue = (() => {
1419
1550
  }
1420
1551
  /**
1421
1552
  * Checks if the watcher connection is locked
1422
- *
1423
- * @returns {Promise<boolean>}
1424
1553
  */
1425
1554
  async isLocked() {
1426
1555
  if (this.writer) {
@@ -1430,8 +1559,6 @@ let RedisQueue = (() => {
1430
1559
  }
1431
1560
  /**
1432
1561
  * Locks watcher connection
1433
- *
1434
- * @returns {Promise<boolean>}
1435
1562
  */
1436
1563
  async lock() {
1437
1564
  if (this.writer) {
@@ -1441,8 +1568,6 @@ let RedisQueue = (() => {
1441
1568
  }
1442
1569
  /**
1443
1570
  * Unlocks watcher connection
1444
- *
1445
- * @returns {Promise<boolean>}
1446
1571
  */
1447
1572
  async unlock() {
1448
1573
  if (this.writer) {
@@ -1453,9 +1578,9 @@ let RedisQueue = (() => {
1453
1578
  /**
1454
1579
  * Emits error
1455
1580
  *
1456
- * @param {string} eventName
1457
- * @param {string} message
1458
- * @param {unknown} err
1581
+ * @param eventName -
1582
+ * @param message -
1583
+ * @param err -
1459
1584
  */
1460
1585
  emitError(eventName, message, err) {
1461
1586
  const error = err instanceof Error ? err : new Error(String(err));
@@ -1470,8 +1595,6 @@ let RedisQueue = (() => {
1470
1595
  }
1471
1596
  /**
1472
1597
  * Acquires an owner for watcher connection to this instance of the queue
1473
- *
1474
- * @returns {Promise<void>}
1475
1598
  */
1476
1599
  async ownWatch() {
1477
1600
  const owned = await this.lock();
@@ -1500,8 +1623,6 @@ let RedisQueue = (() => {
1500
1623
  * Attempts to take over an orphaned watcher lock: if the lock is held
1501
1624
  * but no watcher connection is actually alive, releases and re-acquires
1502
1625
  * ownership. Used to resolve a possible watcher deadlock.
1503
- *
1504
- * @returns {Promise<void>}
1505
1626
  */
1506
1627
  async resolveWatchLock() {
1507
1628
  const noWatcher = !(await this.watcherCount());
@@ -1513,8 +1634,6 @@ let RedisQueue = (() => {
1513
1634
  /**
1514
1635
  * Initializes a single watcher connection across all queues with the same
1515
1636
  * prefix.
1516
- *
1517
- * @returns {Promise<void>}
1518
1637
  */
1519
1638
  async initWatcher() {
1520
1639
  try {