@imqueue/core 3.4.2 → 3.5.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.
@@ -71,11 +71,12 @@ export declare const IMQ_CONNECTION_QUIT_TIMEOUT: number;
71
71
  * @remarks
72
72
  * Connection model: the reader is per instance and exists only in
73
73
  * {@link IMQMode.BOTH} or {@link IMQMode.WORKER} mode, while the writer and
74
- * watcher connections are shared per `host:port` across every queue in the
75
- * process and reference-counted. Exactly one queue per key prefix is elected as
76
- * the watcher through a `<prefix>:watch:lock` key, and that owner also releases
77
- * delayed messages, recovers abandoned safe-delivery hand-offs and — when
78
- * {@link IMQOptions.cleanup} is on — prunes orphaned keys.
74
+ * watcher connections are shared per `host:port` — and per TLS configuration —
75
+ * across every queue in the process and reference-counted. Exactly one queue
76
+ * per key prefix is elected as the watcher through a `<prefix>:watch:lock` key,
77
+ * and that owner also releases delayed messages, recovers abandoned
78
+ * safe-delivery hand-offs and — when {@link IMQOptions.cleanup} is on — prunes
79
+ * orphaned keys.
79
80
  *
80
81
  * Lifecycle: {@link RedisQueue.start} is required before consuming or
81
82
  * publishing, while {@link RedisQueue.send} starts the queue lazily.
@@ -107,6 +108,14 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
107
108
  * consuming the key it was started with.
108
109
  */
109
110
  name: string;
111
+ /**
112
+ * Whether this handle publishes, consumes, or both.
113
+ *
114
+ * @remarks
115
+ * Fixed at construction: it decides which connections `start()` opens,
116
+ * so a publisher never opens a reader and cannot consume even by
117
+ * accident.
118
+ */
110
119
  private readonly mode;
111
120
  /**
112
121
  * Writer connections collection
@@ -202,6 +211,8 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
202
211
  * removing their keys.
203
212
  */
204
213
  private lastConnectedKeys;
214
+ /** Lease owners seen connected on the previous sweep (one sweep of grace) */
215
+ private lastOwners;
205
216
  /**
206
217
  * True while this instance holds a reference to the shared writer
207
218
  */
@@ -210,20 +221,51 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
210
221
  * Internal per-channel reconnection state
211
222
  */
212
223
  private reconnectTimers;
224
+ /**
225
+ * Consecutive failed reconnection attempts per channel, which is what the
226
+ * backoff delay is computed from. Reset once a channel connects again.
227
+ */
213
228
  private reconnectAttempts;
229
+ /**
230
+ * Channels with a reconnection already in progress.
231
+ *
232
+ * @remarks
233
+ * A guard, not a status: several `close` events can arrive for one channel,
234
+ * and without this each would start its own reconnection loop.
235
+ */
214
236
  private reconnecting;
215
237
  /**
216
238
  * The `host:port` address of the redis server this queue talks to.
217
239
  *
218
240
  * @remarks
219
241
  * This is not an instance identifier. It is deliberately shared by every
220
- * queue in the process that targets the same server, and is the key under
221
- * which the writer and watcher connections (and the writer reference count)
222
- * are stored. It includes neither the key prefix nor the credentials, so two
223
- * queues differing only in those share the same underlying connections — the
224
- * first one created wins.
242
+ * queue in the process that targets the same server, and it is what
243
+ * identifies that server in logs. It includes neither the key prefix nor
244
+ * the credentials.
245
+ *
246
+ * It is no longer the whole of the connection pool key — see
247
+ * {@link RedisQueue.poolKey} — because connections differing in their
248
+ * transport security must not be shared.
225
249
  */
226
250
  readonly redisKey: string;
251
+ /**
252
+ * Key under which the shared writer and watcher connections, and the writer
253
+ * reference count, are stored.
254
+ *
255
+ * @remarks
256
+ * This is {@link RedisQueue.redisKey} for a plaintext connection, and that
257
+ * address plus a fingerprint of {@link IMQOptions.tls} for an encrypted
258
+ * one. Two queues reaching one server under equal TLS configurations
259
+ * therefore still share a connection, while queues that differ in their
260
+ * trust anchors, client certificate or verification callbacks get separate
261
+ * ones — a queue asking for TLS can never be handed a plaintext socket
262
+ * another queue opened first, nor the reverse.
263
+ *
264
+ * The prefix and the credentials remain outside the key, so queues
265
+ * differing only in those still share a connection and the first one
266
+ * created still wins.
267
+ */
268
+ private readonly poolKey;
227
269
  /**
228
270
  * Lua scripts for redis
229
271
  */
@@ -231,13 +273,18 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
231
273
  /**
232
274
  * Serializes a given data object into string
233
275
  *
234
- * @param data -
276
+ * @param data - the value to serialize; must be JSON-serializable
277
+ * @returns the wire representation, gzipped when
278
+ * {@link IMQOptions.useGzip} is on
235
279
  */
236
280
  private readonly pack;
237
281
  /**
238
282
  * Deserialize string data into an object
239
283
  *
240
- * @param data -
284
+ * @param data - the wire representation, as produced by `pack`
285
+ * @returns the deserialized value
286
+ * @throws when the payload is malformed, or was packed with a different
287
+ * {@link IMQOptions.useGzip} setting
241
288
  */
242
289
  private readonly unpack;
243
290
  /**
@@ -268,7 +315,25 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
268
315
  * Assign it before {@link RedisQueue.start} — a running reader keeps
269
316
  * consuming the key it was started with.
270
317
  */
271
- name: string, options?: Partial<IMQOptions>, mode?: IMQMode);
318
+ name: string, options?: Partial<IMQOptions>,
319
+ /**
320
+ * Whether this handle publishes, consumes, or both.
321
+ *
322
+ * @remarks
323
+ * Fixed at construction: it decides which connections `start()` opens,
324
+ * so a publisher never opens a reader and cannot consume even by
325
+ * accident.
326
+ */
327
+ mode?: IMQMode);
328
+ /**
329
+ * Writes a diagnostic line, but only under {@link IMQOptions.verbose}.
330
+ *
331
+ * @param message - the line to write, tagged with this queue's name
332
+ *
333
+ * @remarks
334
+ * For tracing the queue's own lifecycle. Anything a user must see whether
335
+ * or not verbose is on goes through `logLine` instead.
336
+ */
272
337
  private verbose;
273
338
  /**
274
339
  * Writes an unconditional line through this queue's logger, in the format
@@ -328,8 +393,8 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
328
393
  * Attaches a subscription message handler to a given channel
329
394
  * connection
330
395
  *
331
- * @param chan -
332
- * @param handler -
396
+ * @param chan - the pub/sub channel to deliver messages from
397
+ * @param handler - called with the decoded payload of each message
333
398
  */
334
399
  private attachSubscriptionHandler;
335
400
  /**
@@ -493,9 +558,11 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
493
558
  * and silently discarded.
494
559
  *
495
560
  * With `clearData` set, only the main and delayed keys are removed: messages
496
- * currently leased to a worker key under {@link IMQOptions.safeDelivery} are
497
- * not, and the watcher will re-queue them once their lease expires — so
498
- * messages can reappear after a clearing destroy.
561
+ * currently checked out to a worker key under
562
+ * {@link IMQOptions.safeDelivery} are not, and the watcher returns them to
563
+ * the queue once their worker is gone or their
564
+ * {@link IMQOptions.safeDeliveryTtl} is spent — so messages can reappear
565
+ * after a clearing destroy.
499
566
  *
500
567
  * Never rejects; unlock and clear failures are logged.
501
568
  */
@@ -508,9 +575,10 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
508
575
  * @remarks
509
576
  * A no-op that resolves successfully when the queue has no writer connection.
510
577
  * In-flight messages held in worker keys under
511
- * {@link IMQOptions.safeDelivery} are not removed and may be re-queued by the
512
- * watcher after their lease expires, so this does not guarantee the queue
513
- * stays empty. Errors are logged rather than thrown, so success cannot be
578
+ * {@link IMQOptions.safeDelivery} are not removed, and the watcher returns
579
+ * them to the queue once their worker is gone or their
580
+ * {@link IMQOptions.safeDeliveryTtl} is spent — so this does not guarantee
581
+ * the queue stays empty. Errors are logged rather than thrown, so success cannot be
514
582
  * inferred from a resolved promise.
515
583
  */
516
584
  clear(): Promise<RedisQueue>;
@@ -520,11 +588,14 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
520
588
  * @returns count of messages waiting to be consumed
521
589
  *
522
590
  * @remarks
523
- * Delayed messages that are not yet due, and messages currently leased to a
524
- * worker under {@link IMQOptions.safeDelivery}, are not counted — so this
525
- * is not the amount of outstanding work. Returns `0` when the queue has no
526
- * writer connection, which makes "disconnected" indistinguishable from
527
- * "empty"; it never throws.
591
+ * Delayed messages that are not yet due, and messages currently checked out
592
+ * to a worker under {@link IMQOptions.safeDelivery}, are not counted — so
593
+ * this is not the amount of outstanding work. Under safe delivery a message
594
+ * is checked out for as long as its handler runs, so on a busy queue the
595
+ * shortfall is roughly everything in flight, not a rounding error.
596
+ *
597
+ * Returns `0` when the queue has no writer connection, which makes
598
+ * "disconnected" indistinguishable from "empty"; it never throws.
528
599
  */
529
600
  queueLength(): Promise<number>;
530
601
  /**
@@ -543,35 +614,37 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
543
614
  * Used for health-aware routing in the clustered queue.
544
615
  *
545
616
  * @remarks
546
- * The writer connection is shared per `host:port` within the process, so this
547
- * reflects the health of that server connection rather than of this instance
548
- * alone — every queue pointing at the same server reports the same value.
617
+ * The writer connection is shared per `host:port` and TLS configuration
618
+ * within the process, so this reflects the health of that server connection
619
+ * rather than of this instance alone — every queue pointing at the same
620
+ * server the same way reports the same value.
549
621
  */
550
622
  get available(): boolean;
551
623
  /**
552
624
  * Writer connection associated with this queue instance. Shared by every
553
- * queue in the process that targets the same `host:port`.
625
+ * queue in the process that targets the same {@link RedisQueue.poolKey}.
554
626
  */
555
627
  private get writer();
556
628
  private set writer(value);
557
629
  /**
558
630
  * Watcher connection associated with this queue instance. Shared by every
559
- * queue in the process that targets the same `host:port`; at most one queue
560
- * per prefix is the elected watcher owner.
631
+ * queue in the process that targets the same {@link RedisQueue.poolKey}; at
632
+ * most one queue per prefix is the elected watcher owner.
561
633
  */
562
634
  private get watcher();
563
635
  private set watcher(value);
564
636
  /**
565
637
  * Returns the connection currently bound to the given channel, if any.
566
638
  *
567
- * @param channel -
639
+ * @param channel - which of the queue's connections to look up
640
+ * @returns the connection, or `undefined` when that channel is not open
568
641
  */
569
642
  private connectionOf;
570
643
  /**
571
644
  * Binds the given connection to the given channel.
572
645
  *
573
- * @param channel -
574
- * @param conn -
646
+ * @param channel - which of the queue's connections to bind
647
+ * @param conn - the client to bind, or `undefined` to unbind it
575
648
  */
576
649
  private bindConnection;
577
650
  /**
@@ -594,6 +667,23 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
594
667
  * Destroys writer channel
595
668
  */
596
669
  private destroyWriter;
670
+ /**
671
+ * Installs a durable `error` listener on a connection's socket.
672
+ *
673
+ * @param client - the connection whose socket to guard
674
+ *
675
+ * @remarks
676
+ * The redis client guards the socket with a one-shot listener, which the
677
+ * first failure consumes. A socket that goes on to report a second one -
678
+ * a rejected TLS handshake is answered by an alert that arrives after the
679
+ * failure that caused it - then reaches a socket with nothing attached,
680
+ * and an unhandled `error` takes the process down. Nothing is left to act
681
+ * on it by then, so it is swallowed.
682
+ *
683
+ * Idempotent: connections are marked once guarded, so repeated failures on
684
+ * one socket do not accumulate listeners.
685
+ */
686
+ private guardSocket;
597
687
  /**
598
688
  * Destroys any channel
599
689
  */
@@ -601,15 +691,16 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
601
691
  /**
602
692
  * Establishes a given connection channel by its name
603
693
  *
604
- * @param channel -
605
- * @param options -
694
+ * @param channel - which of the queue's connections to open
695
+ * @param options - connection options; falls back to this queue's own
696
+ * @returns the ready client
606
697
  */
607
698
  private connect;
608
699
  /**
609
700
  * Schedules custom reconnection for a given channel with capped
610
701
  * exponential backoff
611
702
  *
612
- * @param channel -
703
+ * @param channel - which of the queue's connections to reconnect
613
704
  */
614
705
  private scheduleReconnect;
615
706
  /**
@@ -617,33 +708,50 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
617
708
  * rescheduling itself on failure. Errors are handled internally, so the
618
709
  * scheduled timer never produces an unhandled rejection.
619
710
  *
620
- * @param channel -
711
+ * @param channel - which of the queue's connections to reconnect
621
712
  */
622
713
  private reconnectNow;
623
714
  /**
624
715
  * Generates channel name
625
716
  *
626
- * @param contextName -
627
- * @param prefix -
628
- * @param name -
717
+ * @param contextName - the queue name the connection belongs to
718
+ * @param prefix - the key prefix this queue works under
719
+ * @param name - which of the queue's connections this is
720
+ * @returns the name registered with the broker, ending in this process's
721
+ * pid and host — which is what makes a connection, and so a lease
722
+ * owner, identifiable in `CLIENT LIST`
629
723
  */
630
724
  private getChannelName;
631
725
  /**
632
726
  * Builds and returns connection error handler
633
727
  *
634
- * @param channel -
728
+ * @param channel - which of the queue's connections the handler is for
729
+ * @returns the handler to attach to that connection's `error` event
635
730
  */
636
731
  private onErrorHandler;
637
732
  /**
638
733
  * Builds and returns redis connection close handler
639
734
  *
640
- * @param channel -
735
+ * @param channel - which of the queue's connections the handler is for
736
+ * @returns the handler to attach to that connection's `close` event
641
737
  */
642
738
  private onCloseHandler;
643
739
  /**
644
- * Processes given redis-queue message
740
+ * Unpacks one raw queue message and hands it to the `message` listeners.
741
+ *
742
+ * @param msg - the `[queue key, packed message]` pair as read off redis
743
+ * @returns the promises the listeners returned, empty when none did
744
+ *
745
+ * @remarks
746
+ * The return value is how the caller learns when the listeners are actually
747
+ * finished, which is what {@link RedisQueue.readSafe} needs in order to know
748
+ * when a message's lease may be dropped. `emit()` discards what a listener
749
+ * returns, so the listeners are invoked directly; raw listeners are used so
750
+ * a `once` listener still removes itself and still yields its value, exactly
751
+ * as `emit()` would have arranged.
645
752
  *
646
- * @param msg -
753
+ * A listener throwing synchronously propagates, as it does through `emit()`.
754
+ * An unreadable message dispatches nothing and reports nothing pending.
647
755
  */
648
756
  private process;
649
757
  /**
@@ -651,26 +759,63 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
651
759
  */
652
760
  private watcherCount;
653
761
  /**
654
- * Processes delayed a message by its given redis key
762
+ * Moves messages whose delay has elapsed onto their queue.
655
763
  *
656
- * @param key -
764
+ * @param key - the queue key whose `:delayed` companion to drain
657
765
  */
658
766
  private processDelayed;
659
767
  /**
660
- * Watch routine
768
+ * Sweeps for leases whose worker is not coming back and returns their
769
+ * messages to the queue.
770
+ *
771
+ * @param clients - raw `CLIENT LIST` output for this tick, or `undefined`
772
+ * when it could not be read, in which case liveness is unknown and a
773
+ * lease is left to its budget rather than guessed at
661
774
  */
662
775
  private processWatch;
663
776
  /**
664
- * Process given keys from a message queue
777
+ * Decides whether one worker key has been abandoned.
665
778
  *
666
- * @param keys -
667
- * @param now -
779
+ * @param key - the worker key
780
+ * @param now - the timestamp this sweep started at
781
+ * @param owners - processes currently connected, or `undefined` when the
782
+ * client list could not be read
783
+ * @returns whether this key's message should go back on the queue
784
+ *
785
+ * @remarks
786
+ * Which scheme applies is read off the key itself rather than off this
787
+ * queue's options, because the sweeper serves every queue sharing the
788
+ * prefix and they need not be configured alike.
789
+ *
790
+ * A key naming its owner is abandoned on either of two counts, because
791
+ * there are two ways to lose a message. The owner having left the broker's
792
+ * client list catches the process dying — the common case, detected as fast
793
+ * as the socket closes and needing nothing renewed to keep a live lease
794
+ * alive. The deadline catches what liveness cannot see: a worker that is up,
795
+ * connected and serving other messages while one handler has wedged on this
796
+ * one. The budget is honoured even when liveness is unknown, since an
797
+ * exhausted budget is exhausted either way.
798
+ *
799
+ * A key with no owner was written by 3.x, before leases named one. Its
800
+ * deadline is the whole story, exactly as it was then, so a rolling upgrade
801
+ * does not strand it.
802
+ */
803
+ private isAbandoned;
804
+ /**
805
+ * Returns the messages of abandoned leases to their queues.
806
+ *
807
+ * @param keys - worker keys from one page of the sweep's `SCAN`
808
+ * @param now - the timestamp the sweep started at, so every key in a pass
809
+ * is judged against the same instant
810
+ * @param owners - processes currently connected, or `undefined` when the
811
+ * client list could not be read
668
812
  */
669
813
  private processKeys;
670
814
  /**
671
- * Watch message processor
815
+ * Handles one keyspace notification from the watcher subscription.
672
816
  *
673
- * @param args -
817
+ * @param args - the `pmessage` arguments; only the last, the expired key,
818
+ * is used, and only when it is a delayed message's ttl marker
674
819
  */
675
820
  private onWatchMessage;
676
821
  /**
@@ -719,13 +864,60 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
719
864
  */
720
865
  private runSafeCheck;
721
866
  /**
722
- * Cleans up orphaned keys from redis
867
+ * Reads the broker's client list.
868
+ *
869
+ * @returns the raw `CLIENT LIST` output, or `undefined` when it could not
870
+ * be read
871
+ *
872
+ * @remarks
873
+ * A failure must not read as "nobody is connected" — that would reclaim
874
+ * every lease in flight and delete every key in the prefix — so it is
875
+ * reported as unknown rather than as an empty list.
876
+ */
877
+ private readClients;
878
+ /**
879
+ * Extracts the processes currently connected to the broker, as the owner
880
+ * tokens stamped into worker keys.
881
+ *
882
+ * @param clients - raw `CLIENT LIST` output
883
+ * @returns owners seen connected now, plus those seen on the previous sweep
884
+ *
885
+ * @remarks
886
+ * Previous-sweep owners are included deliberately, mirroring the grace the
887
+ * cleanup pass already gives reconnecting clients: a worker riding out a
888
+ * reconnect backoff briefly leaves the client list, and reclaiming its
889
+ * leases then would re-deliver work that is still running. One sweep of
890
+ * grace costs one sweep of recovery latency and removes that whole class of
891
+ * duplicate.
892
+ */
893
+ private connectedOwners;
894
+ /**
895
+ * Removes keys left behind by clients that are no longer connected.
896
+ *
897
+ * @param clients - raw `CLIENT LIST` output for this tick, so the list is
898
+ * read once per sweep. Called on its own, this reads its own; a read
899
+ * that fails throws into the catch below and deletes nothing,
900
+ * because treating an unreadable list as "no client owns anything"
901
+ * would delete every key in the prefix
902
+ * @returns this queue instance, or `undefined` when cleanup is disabled
723
903
  */
724
904
  private processCleanup;
725
905
  /**
726
906
  * Unreliable but fast way of message handling by the queue
727
907
  */
728
908
  private readUnsafe;
909
+ /**
910
+ * Ends one lease, dropping the worker key and with it the message.
911
+ *
912
+ * @param workerKey - the key holding the message
913
+ *
914
+ * @remarks
915
+ * Idempotent, and never throws: an undeleted worker key is re-queued by the
916
+ * watcher later, which is one of the causes a handler can be given for a
917
+ * duplicate. The key itself is never logged, as it carries the queue name
918
+ * and the lease id.
919
+ */
920
+ private releaseLease;
729
921
  /**
730
922
  * Reliable but slow method of message handling by message queue.
731
923
  *
@@ -754,9 +946,10 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
754
946
  /**
755
947
  * Emits error
756
948
  *
757
- * @param eventName -
758
- * @param message -
759
- * @param err -
949
+ * @param eventName - the internal routine that caught it, used as a
950
+ * diagnostic label such as `OnMessage` or `OnReadSafe`
951
+ * @param message - human-readable context for the log line
952
+ * @param err - the caught value, wrapped when it is not an `Error`
760
953
  */
761
954
  private emitError;
762
955
  /**