@imqueue/core 3.7.0 → 3.9.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/CHANGELOG.md CHANGED
@@ -9,6 +9,95 @@ queue does has an entry.
9
9
 
10
10
  This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
11
11
 
12
+ ## [Unreleased]
13
+
14
+ ### Changed
15
+
16
+ - **A clustered `publish()` goes to one broker of the fleet, not to every
17
+ broker.** `subscribe()` already opens the channel on every broker,
18
+ including brokers that join later, so an event published on any one of them
19
+ reaches every subscriber. Publishing on all of them put the whole pub/sub
20
+ stream on every broker — adding brokers took no pub/sub load off the others
21
+ — and ran every subscriber's handler once per broker. Now the broker is
22
+ picked by health-aware round-robin, as for `send()`: publishes spread across
23
+ the fleet, and each subscriber receives an event once. A broker that was
24
+ just discovered is not picked until it has been known for
25
+ `publishSettleTime`, so that subscribers have had time to discover it and
26
+ subscribe on it; when no broker is that old, any ready one is used. A
27
+ publish that fails on its broker is retried once on another ready broker
28
+ before the call rejects, and a broker whose publishes fail is reported once,
29
+ on entering that state. Brokers listed in a static `cluster` are settled from
30
+ the start. An empty cluster still resolves without publishing and logs
31
+ `knownServers=0`.
32
+
33
+ An event now reaches only the subscribers subscribed on the broker it went
34
+ to, so a subscriber that has just started, or whose subscription on that
35
+ broker is still being retried, can miss one that a fan-out would have
36
+ delivered through another broker. A fleet whose subscribers do not each hold
37
+ every broker — a single-host queue, or a cluster manager limited to part of
38
+ the fleet — keeps the old behavior with `publishFanOut: true` on the
39
+ publisher.
40
+
41
+ ### Added
42
+
43
+ - **`IMQOptions.publishSettleTime`**, how long (ms) a clustered queue must
44
+ have known a discovered broker before a publish prefers it. Defaults to
45
+ `IMQ_PUBLISH_SETTLE_TIME`, or 7000: the UDP announcement interval (1 s) plus
46
+ the default `aliveTimeoutCorrection` (5 s), plus one interval for the
47
+ subscription.
48
+ - **`IMQOptions.publishFanOut`**, which makes a clustered `publish()` write
49
+ every event to every broker, as before.
50
+
51
+ ## [3.8.0] - 2026-11-24
52
+
53
+ ### Fixed
54
+
55
+ - **A broker kept after its announcements lapsed was never checked again, so
56
+ one that later hung stayed in routing until the process restarted.** Since
57
+ 3.7.0 a server whose UDP announcements lapse is kept while it answers a
58
+ PING. But the cluster manager reports a lapse once and arms no further
59
+ liveness check, so nothing looked at a kept server again: if its
60
+ announcements never resumed and the broker then stopped answering — its
61
+ connection open and nothing coming back, as with a frozen or partitioned
62
+ host — it kept its share of round-robin and every call routed to it timed
63
+ out. Measured with two brokers at 50 calls/s, one kept and then frozen for
64
+ 25 s: 822 calls timed out, and the broker was never removed. Now a kept
65
+ server is asked again at the interval it announced itself at (one second
66
+ by default, never less), for as long as its announcements stay away, and is
67
+ drained and removed the first time it does not answer within
68
+ `IMQ_LAPSED_ANSWER_TIMEOUT`. The same run lost 93 calls, those already sent
69
+ to the broker before it was removed 3 s after it froze. The check stops when
70
+ the server's announcements resume, when it is removed, and on `destroy()`;
71
+ nothing is scheduled for a server whose announcements never lapsed.
72
+
73
+ A lapse means the announcements did not arrive — lost on the network, or
74
+ not sent by the announcer — not that the receiving process was busy:
75
+ holding a service's event loop for 10 s, and stopping its whole process for
76
+ 10 s, both kept their brokers with no lapse, since announcements are
77
+ received on the UDP worker thread and datagrams already buffered renew the
78
+ server before its expiry is acted on.
79
+
80
+ ### Added
81
+
82
+ - **`IServerInput.timeout`**, how long a server may go unheard, in
83
+ milliseconds, as announced to a discovering cluster manager.
84
+ `UDPClusterManager` sets it from the announcement's interval, static
85
+ `cluster` entries leave it out, and a clustered queue re-checks a server
86
+ kept after its announcements lapsed at that interval (never less than one
87
+ second, and one second where it is missing).
88
+
89
+ ### Changed
90
+
91
+ - **The UDP cluster manager tells a cluster when a server it already has
92
+ announces itself again after a lapse.** Repeat announcements of a known
93
+ server were all withheld from the cluster, so a cluster that kept a lapsed
94
+ server could not learn that its announcements had resumed. With the alive
95
+ check on, the first announcement the manager hears from a server — after a
96
+ lapse, or at all — now reaches the cluster's `add()` even where the cluster
97
+ already has that server; later ones are withheld as before. `add()` is
98
+ idempotent, so a custom cluster sees one extra call per resumption (and one
99
+ at start for a server it was configured with) and nothing else changes.
100
+
12
101
  ## [3.7.0] - 2026-11-22
13
102
 
14
103
  ### Fixed
@@ -16,8 +105,9 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
16
105
  - **A broker whose heartbeats lapsed was dropped while its connections were
17
106
  healthy, and the replies it had already delivered were lost.** The UDP
18
107
  cluster manager removes a server once it misses its heartbeats for the
19
- check's timeout. A busy process misses them without the broker being gone,
20
- and the removal destroyed the server's queue at once: its listeners went
108
+ check's timeout. A lapse means only that the announcements did not arrive —
109
+ lost on the network, or not sent by the announcer — not that the broker is
110
+ gone, and the removal destroyed the server's queue at once: its listeners went
21
111
  before its reader was disconnected, so a reply already read was dropped and
22
112
  its caller waited out its whole timeout. Now a server removed for lapsed
23
113
  heartbeats is asked first; one that answers within
package/README.md CHANGED
@@ -47,7 +47,8 @@ With current implementation on RedisQueue:
47
47
  - **Safe, predictable scaling of queues**. Scaling the number of workers does not
48
48
  increase traffic usage.
49
49
  - **Round-robin message balancing between multiple Redis instances**. This
50
- allows easy horizontal scaling of the messaging queue across Redis instances.
50
+ allows easy horizontal scaling of the messaging queue across Redis instances,
51
+ for queued messages and pub/sub events alike.
51
52
  - **TypeScript included!**
52
53
 
53
54
  # Requirements
@@ -192,6 +193,27 @@ in which in-flight work is lost — it does not close it, and `SIGKILL` on the
192
193
  whole node, an OOM kill or a lost machine still take work with them — so handlers
193
194
  must be idempotent.
194
195
 
196
+ # Pub/sub across several brokers
197
+
198
+ A clustered queue subscribes on every broker it knows, including brokers that
199
+ join later, and publishes each event on **one** of them, picked by the same
200
+ health-aware round-robin that `send()` uses. So every subscriber receives each
201
+ event once, and the event stream splits across the brokers: adding a broker
202
+ takes pub/sub load off the others, as it does for queued messages.
203
+
204
+ A broker that was just discovered is not picked until it has been known for
205
+ `publishSettleTime` (7 s by default, or `IMQ_PUBLISH_SETTLE_TIME`), giving
206
+ every subscriber time to discover it and subscribe on it; when no broker is
207
+ that old, any ready one is used. A publish that fails on its broker is retried
208
+ once on another ready broker before it rejects.
209
+
210
+ An event reaches only the subscribers that are subscribed on the broker it
211
+ went to. Where some subscribers do not hold the whole fleet — a single-host
212
+ queue, or a cluster manager limited to part of it — set `publishFanOut: true`
213
+ on the publisher to write every event to every broker, as releases before
214
+ 3.9.0 did. A clustered subscriber then receives each event once per broker
215
+ and has to deduplicate.
216
+
195
217
  # Transport encryption (TLS)
196
218
 
197
219
  Set `tls` and every connection the queue opens — reader, writer, watcher and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@imqueue/core",
3
- "version": "3.7.0",
3
+ "version": "3.9.0",
4
4
  "description": "Fast JSON message queue over Redis for inter-service communication in Node.js & TypeScript microservices — the transport layer of the @imqueue framework",
5
5
  "keywords": [
6
6
  "message-queue",
@@ -20,13 +20,16 @@ export interface ICluster {
20
20
  /**
21
21
  * Adds a server to the cluster and returns its registration record.
22
22
  * Registration is idempotent — an already-known server is returned
23
- * unchanged.
23
+ * unchanged. A manager calls it again for a known server whose
24
+ * announcements resumed after a lapse, so a cluster still checking that
25
+ * server can stop.
24
26
  */
25
27
  add: (server: IServerInput) => IMessageQueueConnection;
26
28
  /**
27
29
  * Removes a server from the cluster. A no-op when the server is unknown.
28
30
  * With `removal.lapsed`, only the server's announcements stopped arriving,
29
- * and a cluster may keep a server that still answers on its connections.
31
+ * and a cluster may keep a server that still answers on its connections —
32
+ * checking it itself until it stops answering or `add` reports it again.
30
33
  */
31
34
  remove: (server: IServerInput, removal?: ServerRemoval) => void;
32
35
  /**
@@ -57,11 +57,14 @@ export interface ClusterServer extends IMessageQueueConnection {
57
57
  *
58
58
  * @remarks
59
59
  * Distribution is asymmetric, and this is the most important thing to know about
60
- * the class: {@link ClusteredRedisQueue.send} routes each message to exactly
61
- * one server, chosen by health-aware round-robin that skips instances whose
60
+ * the class: {@link ClusteredRedisQueue.send} and
61
+ * {@link ClusteredRedisQueue.publish} route each message to exactly one
62
+ * server, chosen by health-aware round-robin that skips instances whose
62
63
  * writer connection is not ready. Every other operation — `start`, `stop`,
63
- * `clear`, `destroy`, `publish`, `subscribe`, `unsubscribe` and `queueLength` —
64
- * fans out to every server.
64
+ * `clear`, `destroy`, `subscribe`, `unsubscribe` and `queueLength` — fans out
65
+ * to every server. That pairing is what makes pub/sub split across the
66
+ * cluster: every subscriber listens on every server, so an event published on
67
+ * any one of them reaches each subscriber once.
65
68
  *
66
69
  * Fan-out normally uses `Promise.all`, with no rollback on failure. Destroy
67
70
  * attempts every cleanup task and reports failures together in an AggregateError.
@@ -112,6 +115,27 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
112
115
  * Current queue index (round-robin)
113
116
  */
114
117
  private currentQueue;
118
+ /**
119
+ * Round-robin position of the next publish, kept apart from sends so that
120
+ * publishes spread evenly whatever the mix of the two
121
+ */
122
+ private publishCursor;
123
+ /**
124
+ * How long (ms) a discovered server must have been known before a
125
+ * publish prefers it, see {@link IMQOptions.publishSettleTime}
126
+ */
127
+ private readonly publishSettleTime;
128
+ /**
129
+ * When each server's queue joined this cluster (ms since the epoch), or 0
130
+ * for servers listed in the static configuration, which nobody has to
131
+ * discover
132
+ */
133
+ private readonly joinedAt;
134
+ /**
135
+ * Servers whose last publish failed, so that a failing server is reported
136
+ * on entering the state only and not on every publish
137
+ */
138
+ private readonly publishFailing;
115
139
  /**
116
140
  * Time (ms) send() waits for the first server when the cluster is empty
117
141
  */
@@ -165,6 +189,8 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
165
189
  private readonly waitingSends;
166
190
  /** Pending startup shared by batch startup and joining-host initialization. */
167
191
  private readonly starting;
192
+ /** Servers kept after their announcements lapsed, while they stay silent. */
193
+ private readonly lapsedWatches;
168
194
  /** Membership admission stays closed after the first destroy() call. */
169
195
  private closed;
170
196
  /** Failed cleanup tasks remain here for an explicit destroy() retry. */
@@ -512,24 +538,72 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
512
538
  */
513
539
  listenerCount(...args: any[]): number;
514
540
  /**
515
- * Publishes the payload on every redis host in the cluster.
541
+ * Publishes the payload on one redis host of the cluster, chosen by
542
+ * health-aware round-robin among the hosts every subscriber can be
543
+ * expected to know.
516
544
  *
517
545
  * @param data - payload to publish as a channel message
518
546
  * @param toName - optional different pub/sub name to publish to
519
- * @throws TypeError propagated from any host that has no writer connection
547
+ * @throws TypeError propagated from the chosen host when it has no writer
548
+ * connection and no other host is ready to take the publish
520
549
  *
521
550
  * @remarks
522
- * This is the opposite of {@link ClusteredRedisQueue.send}: the same payload
523
- * goes to all hosts. A subscriber connected to several of them therefore
524
- * receives one copy per host.
525
- *
526
- * Publication is not atomic — if any host has no writer connection the call
527
- * rejects even though other hosts may already have published. On an empty
528
- * cluster it resolves without publishing anything — reporting that through
529
- * the logger on entering the state — and unlike `send()` it does not wait
530
- * for a server to appear.
551
+ * Like {@link ClusteredRedisQueue.send}, the payload goes to a single host.
552
+ * One is enough: {@link ClusteredRedisQueue.subscribe} opens the channel on
553
+ * every host, including hosts that join later, so each subscriber receives
554
+ * the event exactly once, and the pub/sub stream splits across the cluster
555
+ * the way queued messages do.
556
+ *
557
+ * The host is picked in this order: a ready host known for at least
558
+ * {@link IMQOptions.publishSettleTime}, so that subscribers have had time
559
+ * to discover it; any ready host, when none has been known that long; and,
560
+ * when no host is ready, the next one in turn, which is known to be down.
561
+ * If publishing on the chosen host fails, the publish is retried once on
562
+ * another ready host, picked the same way, before the call rejects. A
563
+ * publish whose reply was lost after the host accepted it is therefore
564
+ * delivered twice — redis pub/sub is at-most-once per host, not
565
+ * exactly-once.
566
+ *
567
+ * An event reaches only subscribers that have discovered the chosen host
568
+ * and opened the channel on it. A subscriber that has just started, or
569
+ * whose subscription on that host is still being retried, misses it,
570
+ * where fanning out would have reached it through another host. Fleets
571
+ * whose subscribers do not each hold the whole cluster need
572
+ * {@link IMQOptions.publishFanOut}, which writes every event to every
573
+ * host as before — and then rejects if any host has no writer connection,
574
+ * even though other hosts may already have published.
575
+ *
576
+ * On an empty cluster it resolves without publishing anything — reporting
577
+ * that through the logger on entering the state — and unlike `send()` it
578
+ * does not wait for a server to appear.
531
579
  */
532
580
  publish(data: JsonObject, toName?: string): Promise<void>;
581
+ /**
582
+ * Picks the host a publish goes to.
583
+ *
584
+ * @param failed - a host that has just failed this publish, which is
585
+ * excluded; with it, only a ready host is returned
586
+ * @returns the chosen host, or `undefined` when `failed` is given and no
587
+ * other host is ready
588
+ *
589
+ * @remarks
590
+ * Scans in round-robin order from where the previous publish stopped, so
591
+ * publishes spread across the hosts of each tier: ready hosts known for
592
+ * {@link IMQOptions.publishSettleTime} first, then any ready host. Without
593
+ * a host that just failed, and with no host ready at all, the next host in
594
+ * turn is returned anyway, as `send()` does: its publish then reports why.
595
+ */
596
+ private selectPublishQueue;
597
+ /**
598
+ * Publishes on one host, reporting a host whose publishes fail on
599
+ * entering that state and clearing it on its next success.
600
+ *
601
+ * @param imq - the host to publish on
602
+ * @param data - payload to publish
603
+ * @param channel - name the publish goes to, for the report only
604
+ * @param toName - the caller's pub/sub name, passed through
605
+ */
606
+ private publishOn;
533
607
  /**
534
608
  * Subscribes the given handler on every redis host in the cluster, and
535
609
  * remembers the subscription so servers that join later are subscribed
@@ -568,7 +642,10 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
568
642
  * that a host was unreachable when the call was made, not that it stays
569
643
  * unsubscribed.
570
644
  *
571
- * The handler receives one invocation per host that delivers the message.
645
+ * Each event published through a {@link ClusteredRedisQueue} goes to one
646
+ * host, so the handler is invoked once per event — once per host only
647
+ * where the publisher uses {@link IMQOptions.publishFanOut}, or publishes
648
+ * the same event on several hosts by other means.
572
649
  */
573
650
  subscribe(channel: string, handler: (data: JsonObject) => void): Promise<void>;
574
651
  /**
@@ -611,17 +688,78 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
611
688
  * Removes a server from the cluster, matching by `id` or by host and port.
612
689
  *
613
690
  * @param server - address of the server to remove
691
+ * @param removal - why it is removed, where the manager can say
614
692
  *
615
693
  * @remarks
616
694
  * A silent no-op when no server matches. Routing stops using the host
617
695
  * immediately, but teardown of its redis connections is started in the
618
- * background and not awaited: in-flight work on that host is not drained,
619
- * and teardown errors are only logged.
696
+ * background and not awaited: what its reader already took is drained to
697
+ * the listeners first, and teardown errors are only logged.
698
+ *
699
+ * With `removal.lapsed` the server is not removed yet: it is asked a PING
700
+ * and kept while it answers within `IMQ_LAPSED_ANSWER_TIMEOUT`, asked
701
+ * again at the interval it announced itself at for as long as its
702
+ * announcements stay away, and removed the first time it does not answer.
703
+ * An `add` for the same server ends that watch.
620
704
  *
621
705
  * Because the underlying queues are matched by host and port, all entries
622
706
  * sharing an address are removed together.
623
707
  */
624
708
  protected removeServer(server: IServerInput, removal?: ServerRemoval): void;
709
+ /**
710
+ * Starts watching a server whose announcements lapsed: it is kept while
711
+ * it answers a PING, and dropped the first time it does not.
712
+ *
713
+ * @param server - the removal's address, carrying the interval the server
714
+ * announced itself at where the manager knows it
715
+ * @param imq - the queue serving that server
716
+ *
717
+ * @remarks
718
+ * Once a server is kept, nothing else would look at it again: its cluster
719
+ * manager has already reported the lapse and arms no further liveness
720
+ * check. Without this watch a kept broker that later hung - its socket
721
+ * open, nothing answering - stayed in round-robin until the process
722
+ * restarted, and every call routed to it timed out.
723
+ *
724
+ * A repeated lapse for a server already watched is ignored: the watch in
725
+ * progress already decides it.
726
+ */
727
+ private watchLapsed;
728
+ /**
729
+ * Asks a lapsed server whether it answers, keeps it and schedules the
730
+ * next check where it does, and drops it where it does not.
731
+ *
732
+ * @param server - the removal's address
733
+ * @param imq - the queue serving that server
734
+ * @param watch - the watch this check belongs to; a check whose watch has
735
+ * ended meanwhile does nothing
736
+ * @param first - whether this is the check made when the lapse was
737
+ * reported, which is the one that logs the server as kept
738
+ */
739
+ private checkLapsed;
740
+ /**
741
+ * Ends the watch over a lapsed server: its announcements resumed, it is
742
+ * being removed, or the cluster is being destroyed.
743
+ *
744
+ * @param imq - the queue serving that server
745
+ * @returns whether a watch was in progress
746
+ */
747
+ private cancelLapsed;
748
+ /**
749
+ * How long to wait before asking a kept server again.
750
+ *
751
+ * @param server - the removal's address
752
+ * @returns the interval the server announced itself at, where the
753
+ * removal carries it, but never less than
754
+ * {@link LAPSED_RECHECK_INTERVAL}
755
+ *
756
+ * @remarks
757
+ * The interval is {@link IServerInput.timeout}, which
758
+ * {@link UDPClusterManager} sets from the announcement. A manager that
759
+ * does not set it, or sets a value that is not a positive number, gets
760
+ * the default.
761
+ */
762
+ private static recheckInterval;
625
763
  /**
626
764
  * Removes a server known to be gone: out of routing at once, its queue
627
765
  * drained of what it already read and then torn down.
@@ -23,7 +23,7 @@
23
23
  */
24
24
  import { EventEmitter } from 'node:events';
25
25
  import {} from './ClusterManager.js';
26
- import { buildOptions, copyEventEmitter, envInt, errorCode, } from './helpers/index.js';
26
+ import { buildOptions, copyEventEmitter, envInt, errorCode, nextRoundRobin, } from './helpers/index.js';
27
27
  import { DEFAULT_IMQ_OPTIONS, IMQMode, RedisQueue, } from './index.js';
28
28
  /**
29
29
  * Time (ms) send() waits for the first cluster server to become available
@@ -46,6 +46,39 @@ const SYNC_RETRY_MAX_DELAY = 30000;
46
46
  * environment variable, defaults to 2,000.
47
47
  */
48
48
  const LAPSED_ANSWER_TIMEOUT = envInt('IMQ_LAPSED_ANSWER_TIMEOUT', 2000);
49
+ /**
50
+ * Shortest interval (ms) between two checks of a server kept after its
51
+ * announcements lapsed, and the interval used where the removal does not say
52
+ * how often the server announced itself.
53
+ *
54
+ * @remarks
55
+ * A kept server is asked again at the interval it announced itself at - the
56
+ * `timeout` a UDP announcement carries, how long its sender may go unheard,
57
+ * which brokers set to their announcement interval (`REDIS_BROADCAST_INTERVAL`,
58
+ * one second by default). The cluster does not know the manager's
59
+ * `aliveTimeoutCorrection`, and does not need it: that correction is slack
60
+ * for datagrams lost on the way, while a PING travels on the connection the
61
+ * queue already holds and carries its own budget,
62
+ * {@link LAPSED_ANSWER_TIMEOUT}. So a broker kept
63
+ * while silent is watched at the cadence its announcements promised, and one
64
+ * that hangs is out of routing within that interval plus the answer budget.
65
+ * The floor keeps a server announcing a zero or tiny interval from turning
66
+ * the check into a PING loop.
67
+ */
68
+ const LAPSED_RECHECK_INTERVAL = 1000;
69
+ /**
70
+ * Default for {@link IMQOptions.publishSettleTime}: how long (ms) a discovered
71
+ * server must have been known before a publish prefers it. Configurable via
72
+ * the IMQ_PUBLISH_SETTLE_TIME environment variable, defaults to 7,000.
73
+ *
74
+ * @remarks
75
+ * The UDP announcement interval (1 s) plus the manager's default
76
+ * `aliveTimeoutCorrection` (5 s) is the longest a subscriber may go without
77
+ * hearing a broker that the manager still treats as normal, so it is also how
78
+ * late a subscriber may discover a broker the publisher already knows. One
79
+ * more interval covers opening the channel on it once discovered.
80
+ */
81
+ const PUBLISH_SETTLE_TIME = envInt('IMQ_PUBLISH_SETTLE_TIME', 7000);
49
82
  /**
50
83
  * Scales a single logical queue horizontally across several redis instances.
51
84
  * This is what {@link IMQ.create} returns when {@link IMQOptions.cluster} or
@@ -53,11 +86,14 @@ const LAPSED_ANSWER_TIMEOUT = envInt('IMQ_LAPSED_ANSWER_TIMEOUT', 2000);
53
86
  *
54
87
  * @remarks
55
88
  * Distribution is asymmetric, and this is the most important thing to know about
56
- * the class: {@link ClusteredRedisQueue.send} routes each message to exactly
57
- * one server, chosen by health-aware round-robin that skips instances whose
89
+ * the class: {@link ClusteredRedisQueue.send} and
90
+ * {@link ClusteredRedisQueue.publish} route each message to exactly one
91
+ * server, chosen by health-aware round-robin that skips instances whose
58
92
  * writer connection is not ready. Every other operation — `start`, `stop`,
59
- * `clear`, `destroy`, `publish`, `subscribe`, `unsubscribe` and `queueLength` —
60
- * fans out to every server.
93
+ * `clear`, `destroy`, `subscribe`, `unsubscribe` and `queueLength` — fans out
94
+ * to every server. That pairing is what makes pub/sub split across the
95
+ * cluster: every subscriber listens on every server, so an event published on
96
+ * any one of them reaches each subscriber once.
61
97
  *
62
98
  * Fan-out normally uses `Promise.all`, with no rollback on failure. Destroy
63
99
  * attempts every cleanup task and reports failures together in an AggregateError.
@@ -99,6 +135,27 @@ export class ClusteredRedisQueue {
99
135
  * Current queue index (round-robin)
100
136
  */
101
137
  currentQueue = 0;
138
+ /**
139
+ * Round-robin position of the next publish, kept apart from sends so that
140
+ * publishes spread evenly whatever the mix of the two
141
+ */
142
+ publishCursor = 0;
143
+ /**
144
+ * How long (ms) a discovered server must have been known before a
145
+ * publish prefers it, see {@link IMQOptions.publishSettleTime}
146
+ */
147
+ publishSettleTime;
148
+ /**
149
+ * When each server's queue joined this cluster (ms since the epoch), or 0
150
+ * for servers listed in the static configuration, which nobody has to
151
+ * discover
152
+ */
153
+ joinedAt = new WeakMap();
154
+ /**
155
+ * Servers whose last publish failed, so that a failing server is reported
156
+ * on entering the state only and not on every publish
157
+ */
158
+ publishFailing = new WeakSet();
102
159
  /**
103
160
  * Time (ms) send() waits for the first server when the cluster is empty
104
161
  */
@@ -156,6 +213,8 @@ export class ClusteredRedisQueue {
156
213
  waitingSends = new Set();
157
214
  /** Pending startup shared by batch startup and joining-host initialization. */
158
215
  starting = new WeakMap();
216
+ /** Servers kept after their announcements lapsed, while they stay silent. */
217
+ lapsedWatches = new Map();
159
218
  /** Membership admission stays closed after the first destroy() call. */
160
219
  closed = false;
161
220
  /** Failed cleanup tasks remain here for an explicit destroy() retry. */
@@ -207,6 +266,13 @@ export class ClusteredRedisQueue {
207
266
  this.clusterEmitter = new EventEmitter();
208
267
  this.options = buildOptions(DEFAULT_IMQ_OPTIONS, options);
209
268
  this.logger = this.options.logger || console;
269
+ const settleTime = this.options.publishSettleTime;
270
+ this.publishSettleTime =
271
+ settleTime !== undefined &&
272
+ Number.isFinite(settleTime) &&
273
+ settleTime >= 0
274
+ ? settleTime
275
+ : PUBLISH_SETTLE_TIME;
210
276
  if (!this.options.cluster && !this.options.clusterManagers?.length) {
211
277
  throw new TypeError('ClusteredRedisQueue: cluster ' + 'configuration is missing!');
212
278
  }
@@ -305,14 +371,11 @@ export class ClusteredRedisQueue {
305
371
  selectQueue() {
306
372
  const count = this.imqLength;
307
373
  const start = this.currentQueue % count;
308
- for (let offset = 0; offset < count; offset++) {
309
- const index = (start + offset) % count;
310
- const candidate = this.imqs[index];
311
- if (candidate.available) {
312
- this.currentQueue = index + 1;
313
- this.noneAvailable = false;
314
- return candidate;
315
- }
374
+ const index = nextRoundRobin(this.imqs, start, imq => imq.available);
375
+ if (index >= 0) {
376
+ this.currentQueue = index + 1;
377
+ this.noneAvailable = false;
378
+ return this.imqs[index];
316
379
  }
317
380
  // every instance reports its connection as not ready, so the message
318
381
  // goes to a host known to be down. Reported on entering the state
@@ -380,6 +443,7 @@ export class ClusteredRedisQueue {
380
443
  this.state.started = false;
381
444
  for (const imq of this.imqs) {
382
445
  this.cancelSync(imq);
446
+ this.cancelLapsed(imq);
383
447
  this.cleanup.add(() => imq.destroy());
384
448
  }
385
449
  for (const manager of this.options.clusterManagers || []) {
@@ -721,41 +785,114 @@ export class ClusteredRedisQueue {
721
785
  return fn.apply(source, args);
722
786
  }
723
787
  /**
724
- * Publishes the payload on every redis host in the cluster.
788
+ * Publishes the payload on one redis host of the cluster, chosen by
789
+ * health-aware round-robin among the hosts every subscriber can be
790
+ * expected to know.
725
791
  *
726
792
  * @param data - payload to publish as a channel message
727
793
  * @param toName - optional different pub/sub name to publish to
728
- * @throws TypeError propagated from any host that has no writer connection
794
+ * @throws TypeError propagated from the chosen host when it has no writer
795
+ * connection and no other host is ready to take the publish
729
796
  *
730
797
  * @remarks
731
- * This is the opposite of {@link ClusteredRedisQueue.send}: the same payload
732
- * goes to all hosts. A subscriber connected to several of them therefore
733
- * receives one copy per host.
734
- *
735
- * Publication is not atomic — if any host has no writer connection the call
736
- * rejects even though other hosts may already have published. On an empty
737
- * cluster it resolves without publishing anything — reporting that through
738
- * the logger on entering the state — and unlike `send()` it does not wait
739
- * for a server to appear.
798
+ * Like {@link ClusteredRedisQueue.send}, the payload goes to a single host.
799
+ * One is enough: {@link ClusteredRedisQueue.subscribe} opens the channel on
800
+ * every host, including hosts that join later, so each subscriber receives
801
+ * the event exactly once, and the pub/sub stream splits across the cluster
802
+ * the way queued messages do.
803
+ *
804
+ * The host is picked in this order: a ready host known for at least
805
+ * {@link IMQOptions.publishSettleTime}, so that subscribers have had time
806
+ * to discover it; any ready host, when none has been known that long; and,
807
+ * when no host is ready, the next one in turn, which is known to be down.
808
+ * If publishing on the chosen host fails, the publish is retried once on
809
+ * another ready host, picked the same way, before the call rejects. A
810
+ * publish whose reply was lost after the host accepted it is therefore
811
+ * delivered twice — redis pub/sub is at-most-once per host, not
812
+ * exactly-once.
813
+ *
814
+ * An event reaches only subscribers that have discovered the chosen host
815
+ * and opened the channel on it. A subscriber that has just started, or
816
+ * whose subscription on that host is still being retried, misses it,
817
+ * where fanning out would have reached it through another host. Fleets
818
+ * whose subscribers do not each hold the whole cluster need
819
+ * {@link IMQOptions.publishFanOut}, which writes every event to every
820
+ * host as before — and then rejects if any host has no writer connection,
821
+ * even though other hosts may already have published.
822
+ *
823
+ * On an empty cluster it resolves without publishing anything — reporting
824
+ * that through the logger on entering the state — and unlike `send()` it
825
+ * does not wait for a server to appear.
740
826
  */
741
827
  async publish(data, toName) {
742
- const promises = [];
743
- for (const imq of this.imqs) {
744
- promises.push(imq.publish(data, toName));
745
- }
746
- // an empty cluster resolves an empty Promise.all, so the caller is
828
+ const channel = toName || this.name;
829
+ // an empty cluster has nowhere to publish, so the caller would be
747
830
  // told the event went out while nothing was published at all.
748
831
  // Reported on entering the state only
749
- if (!promises.length) {
832
+ if (!this.imqs.length) {
750
833
  if (!this.noPublishTargets) {
751
834
  this.noPublishTargets = true;
752
- this.logLine('error', `nothing published to channel ${toName || this.name}: knownServers=0`);
835
+ this.logLine('error', `nothing published to channel ${channel}: knownServers=0`);
753
836
  }
837
+ return;
754
838
  }
755
- else {
756
- this.noPublishTargets = false;
839
+ this.noPublishTargets = false;
840
+ if (this.options.publishFanOut) {
841
+ await Promise.all(this.imqs.map(imq => imq.publish(data, toName)));
842
+ return;
757
843
  }
758
- await Promise.all(promises);
844
+ const target = this.selectPublishQueue();
845
+ try {
846
+ await this.publishOn(target, data, channel, toName);
847
+ }
848
+ catch (err) {
849
+ const fallback = this.selectPublishQueue(target);
850
+ if (!fallback) {
851
+ throw err;
852
+ }
853
+ await this.publishOn(fallback, data, channel, toName);
854
+ }
855
+ }
856
+ selectPublishQueue(failed) {
857
+ const settledSince = Date.now() - this.publishSettleTime;
858
+ const ready = (imq) => imq !== failed && imq.available;
859
+ const settled = (imq) => ready(imq) && (this.joinedAt.get(imq) ?? 0) <= settledSince;
860
+ for (const accept of [settled, ready]) {
861
+ const index = nextRoundRobin(this.imqs, this.publishCursor, accept);
862
+ if (index >= 0) {
863
+ this.publishCursor = index + 1;
864
+ return this.imqs[index];
865
+ }
866
+ }
867
+ if (failed) {
868
+ return undefined;
869
+ }
870
+ const index = this.publishCursor % this.imqs.length;
871
+ this.publishCursor = index + 1;
872
+ return this.imqs[index];
873
+ }
874
+ /**
875
+ * Publishes on one host, reporting a host whose publishes fail on
876
+ * entering that state and clearing it on its next success.
877
+ *
878
+ * @param imq - the host to publish on
879
+ * @param data - payload to publish
880
+ * @param channel - name the publish goes to, for the report only
881
+ * @param toName - the caller's pub/sub name, passed through
882
+ */
883
+ async publishOn(imq, data, channel, toName) {
884
+ try {
885
+ await imq.publish(data, toName);
886
+ }
887
+ catch (err) {
888
+ if (!this.publishFailing.has(imq)) {
889
+ this.publishFailing.add(imq);
890
+ this.logLine('warn', `failed to publish to channel ${channel} on server ` +
891
+ `${imq.redisKey}, code ${errorCode(err)}`);
892
+ }
893
+ throw err;
894
+ }
895
+ this.publishFailing.delete(imq);
759
896
  }
760
897
  /**
761
898
  * Subscribes the given handler on every redis host in the cluster, and
@@ -795,7 +932,10 @@ export class ClusteredRedisQueue {
795
932
  * that a host was unreachable when the call was made, not that it stays
796
933
  * unsubscribed.
797
934
  *
798
- * The handler receives one invocation per host that delivers the message.
935
+ * Each event published through a {@link ClusteredRedisQueue} goes to one
936
+ * host, so the handler is invoked once per event — once per host only
937
+ * where the publisher uses {@link IMQOptions.publishFanOut}, or publishes
938
+ * the same event on several hosts by other means.
799
939
  */
800
940
  async subscribe(channel, handler) {
801
941
  if (this.closed) {
@@ -876,12 +1016,19 @@ export class ClusteredRedisQueue {
876
1016
  * Removes a server from the cluster, matching by `id` or by host and port.
877
1017
  *
878
1018
  * @param server - address of the server to remove
1019
+ * @param removal - why it is removed, where the manager can say
879
1020
  *
880
1021
  * @remarks
881
1022
  * A silent no-op when no server matches. Routing stops using the host
882
1023
  * immediately, but teardown of its redis connections is started in the
883
- * background and not awaited: in-flight work on that host is not drained,
884
- * and teardown errors are only logged.
1024
+ * background and not awaited: what its reader already took is drained to
1025
+ * the listeners first, and teardown errors are only logged.
1026
+ *
1027
+ * With `removal.lapsed` the server is not removed yet: it is asked a PING
1028
+ * and kept while it answers within `IMQ_LAPSED_ANSWER_TIMEOUT`, asked
1029
+ * again at the interval it announced itself at for as long as its
1030
+ * announcements stay away, and removed the first time it does not answer.
1031
+ * An `add` for the same server ends that watch.
885
1032
  *
886
1033
  * Because the underlying queues are matched by host and port, all entries
887
1034
  * sharing an address are removed together.
@@ -892,24 +1039,123 @@ export class ClusteredRedisQueue {
892
1039
  if (!remove) {
893
1040
  return;
894
1041
  }
895
- // only its announcements lapsed - a busy process misses them as
896
- // easily as a dead broker stops sending them - so the broker is
897
- // asked first, and kept where it still answers
1042
+ // only its announcements lapsed, and a lapse says only that they
1043
+ // stopped arriving - lost on the network, or not sent - not that the
1044
+ // broker is gone. So the broker is asked first, kept where it still
1045
+ // answers, and asked again for as long as it stays silent
898
1046
  if (removal?.lapsed && remove.imq) {
899
- const kept = remove.imq;
900
- void kept.answers(LAPSED_ANSWER_TIMEOUT).then(answers => {
901
- if (answers) {
902
- this.verbose(`Kept the server ${kept.redisKey}: its announcements lapsed, but it answers`);
903
- return;
904
- }
905
- if (this.findServer(server)?.imq === kept) {
906
- this.dropServer(server);
907
- }
908
- });
1047
+ this.watchLapsed(server, remove.imq);
909
1048
  return;
910
1049
  }
911
1050
  this.dropServer(server);
912
1051
  }
1052
+ /**
1053
+ * Starts watching a server whose announcements lapsed: it is kept while
1054
+ * it answers a PING, and dropped the first time it does not.
1055
+ *
1056
+ * @param server - the removal's address, carrying the interval the server
1057
+ * announced itself at where the manager knows it
1058
+ * @param imq - the queue serving that server
1059
+ *
1060
+ * @remarks
1061
+ * Once a server is kept, nothing else would look at it again: its cluster
1062
+ * manager has already reported the lapse and arms no further liveness
1063
+ * check. Without this watch a kept broker that later hung - its socket
1064
+ * open, nothing answering - stayed in round-robin until the process
1065
+ * restarted, and every call routed to it timed out.
1066
+ *
1067
+ * A repeated lapse for a server already watched is ignored: the watch in
1068
+ * progress already decides it.
1069
+ */
1070
+ watchLapsed(server, imq) {
1071
+ if (this.closed || this.lapsedWatches.has(imq)) {
1072
+ return;
1073
+ }
1074
+ const watch = {};
1075
+ this.lapsedWatches.set(imq, watch);
1076
+ this.checkLapsed(server, imq, watch, true);
1077
+ }
1078
+ /**
1079
+ * Asks a lapsed server whether it answers, keeps it and schedules the
1080
+ * next check where it does, and drops it where it does not.
1081
+ *
1082
+ * @param server - the removal's address
1083
+ * @param imq - the queue serving that server
1084
+ * @param watch - the watch this check belongs to; a check whose watch has
1085
+ * ended meanwhile does nothing
1086
+ * @param first - whether this is the check made when the lapse was
1087
+ * reported, which is the one that logs the server as kept
1088
+ */
1089
+ checkLapsed(server, imq, watch, first) {
1090
+ void imq.answers(LAPSED_ANSWER_TIMEOUT).then(answers => {
1091
+ // announcements resumed, the server was removed or the cluster
1092
+ // destroyed while the PING was out: this verdict is no longer
1093
+ // anybody's to act on
1094
+ if (this.closed || this.lapsedWatches.get(imq) !== watch) {
1095
+ return;
1096
+ }
1097
+ if (!answers) {
1098
+ this.lapsedWatches.delete(imq);
1099
+ if (this.findServer(server)?.imq === imq) {
1100
+ if (!first) {
1101
+ this.verbose(`Removing the server ${imq.redisKey}: kept after its announcements lapsed, it no longer answers`);
1102
+ }
1103
+ this.dropServer(server);
1104
+ }
1105
+ return;
1106
+ }
1107
+ if (first) {
1108
+ this.verbose(`Kept the server ${imq.redisKey}: its announcements lapsed, but it answers`);
1109
+ }
1110
+ const timer = setTimeout(() => {
1111
+ watch.timer = undefined;
1112
+ if (!this.closed && this.lapsedWatches.get(imq) === watch) {
1113
+ this.checkLapsed(server, imq, watch, false);
1114
+ }
1115
+ }, ClusteredRedisQueue.recheckInterval(server));
1116
+ // a kept server must not hold the process open on its own
1117
+ timer.unref?.();
1118
+ watch.timer = timer;
1119
+ });
1120
+ }
1121
+ /**
1122
+ * Ends the watch over a lapsed server: its announcements resumed, it is
1123
+ * being removed, or the cluster is being destroyed.
1124
+ *
1125
+ * @param imq - the queue serving that server
1126
+ * @returns whether a watch was in progress
1127
+ */
1128
+ cancelLapsed(imq) {
1129
+ const watch = this.lapsedWatches.get(imq);
1130
+ if (!watch) {
1131
+ return false;
1132
+ }
1133
+ clearTimeout(watch.timer);
1134
+ this.lapsedWatches.delete(imq);
1135
+ return true;
1136
+ }
1137
+ /**
1138
+ * How long to wait before asking a kept server again.
1139
+ *
1140
+ * @param server - the removal's address
1141
+ * @returns the interval the server announced itself at, where the
1142
+ * removal carries it, but never less than
1143
+ * {@link LAPSED_RECHECK_INTERVAL}
1144
+ *
1145
+ * @remarks
1146
+ * The interval is {@link IServerInput.timeout}, which
1147
+ * {@link UDPClusterManager} sets from the announcement. A manager that
1148
+ * does not set it, or sets a value that is not a positive number, gets
1149
+ * the default.
1150
+ */
1151
+ static recheckInterval(server) {
1152
+ const announced = server.timeout;
1153
+ return announced !== undefined &&
1154
+ Number.isFinite(announced) &&
1155
+ announced > 0
1156
+ ? Math.max(LAPSED_RECHECK_INTERVAL, announced)
1157
+ : LAPSED_RECHECK_INTERVAL;
1158
+ }
913
1159
  /**
914
1160
  * Removes a server known to be gone: out of routing at once, its queue
915
1161
  * drained of what it already read and then torn down.
@@ -923,8 +1169,10 @@ export class ClusteredRedisQueue {
923
1169
  }
924
1170
  const imqToRemove = remove.imq;
925
1171
  if (imqToRemove) {
926
- // a retry scheduled for this host must not outlive it
1172
+ // a retry or a lapse check scheduled for this host must not
1173
+ // outlive it
927
1174
  this.cancelSync(imqToRemove);
1175
+ this.cancelLapsed(imqToRemove);
928
1176
  // dropped from routing first: a catch-up run in progress tests
929
1177
  // membership between handlers and stops as soon as it sees this
930
1178
  this.imqs = this.imqs.filter(imq => imqToRemove.redisKey !== imq.redisKey);
@@ -963,6 +1211,12 @@ export class ClusteredRedisQueue {
963
1211
  }
964
1212
  const existingServer = this.findServer(server);
965
1213
  if (existingServer) {
1214
+ // a server kept after its announcements lapsed is announcing
1215
+ // itself again: it is back under its manager's liveness check,
1216
+ // and no longer needs this cluster's
1217
+ if (existingServer.imq && this.cancelLapsed(existingServer.imq)) {
1218
+ this.verbose(`Stopped checking the server ${existingServer.imq.redisKey}: its announcements resumed`);
1219
+ }
966
1220
  return existingServer;
967
1221
  }
968
1222
  const newServer = {
@@ -981,6 +1235,10 @@ export class ClusteredRedisQueue {
981
1235
  const imq = new RedisQueue(this.name, opts);
982
1236
  copyEventEmitter(this.templateEmitter, imq);
983
1237
  newServer.imq = imq;
1238
+ // a server from the static configuration is configured on every
1239
+ // process alike, so nobody has to discover it before it may carry
1240
+ // a publish. A discovered one is new to subscribers too
1241
+ this.joinedAt.set(imq, initializeQueue ? Date.now() : 0);
984
1242
  // registered before the catch-up run starts, so that run can test
985
1243
  // membership against `imqs` and see the host it is working on. Nothing
986
1244
  // can observe the order: there is no await between here and the call
@@ -137,6 +137,18 @@ export interface IServerInput {
137
137
  * TCP port the server listens on.
138
138
  */
139
139
  port: number;
140
+ /**
141
+ * How long this server may go unheard, in milliseconds, as announced to a
142
+ * discovering cluster manager — {@link UDPClusterManager} sets it from the
143
+ * interval carried by the server's announcement. Static `cluster` entries
144
+ * leave it out.
145
+ *
146
+ * @remarks
147
+ * {@link ClusteredRedisQueue} uses it as the interval at which it asks a
148
+ * server kept after its announcements lapsed whether it still answers,
149
+ * never less than one second, and one second where it is missing.
150
+ */
151
+ timeout?: number;
140
152
  }
141
153
  /**
142
154
  * A single queue-host endpoint: where to connect and, optionally, how to
@@ -441,6 +453,48 @@ export interface IMQOptions extends Partial<IMessageQueueConnection> {
441
453
  * {@link ClusterManager} to add your own.
442
454
  */
443
455
  clusterManagers?: ClusterManager[];
456
+ /**
457
+ * How long (ms) a clustered queue must have known a server before
458
+ * {@link ClusteredRedisQueue.publish} prefers it as the one server an
459
+ * event goes to.
460
+ *
461
+ * @defaultValue the `IMQ_PUBLISH_SETTLE_TIME` environment variable, or
462
+ * 7000
463
+ *
464
+ * @remarks
465
+ * A clustered publish goes to one server, and reaches every subscriber
466
+ * only where each of them has already discovered that server and opened
467
+ * the channel on it. Subscribers discover a server at about the time the
468
+ * publisher does, but not at the same moment: a discovered server is
469
+ * therefore not preferred until it has been known this long. The default
470
+ * covers the UDP announcement interval (1 s) plus
471
+ * {@link UDPClusterManagerOptions.aliveTimeoutCorrection} (5 s) — the
472
+ * delay a manager already tolerates between two announcements it hears —
473
+ * plus one more interval for the subscription itself. Set it to match
474
+ * other intervals or corrections where your fleet uses them.
475
+ *
476
+ * Servers listed in {@link IMQOptions.cluster} are settled from the
477
+ * start: every process is configured with them, so nobody has to
478
+ * discover them. When no server has been known long enough — a process
479
+ * that has just started, say — any ready server is used. Ignored with
480
+ * {@link IMQOptions.publishFanOut}.
481
+ */
482
+ publishSettleTime?: number;
483
+ /**
484
+ * Makes {@link ClusteredRedisQueue.publish} write every event to every
485
+ * server of the cluster, as it did before 3.9.0, instead of to one.
486
+ *
487
+ * @defaultValue false
488
+ *
489
+ * @remarks
490
+ * Only for a fleet whose subscribers do not each hold the whole cluster:
491
+ * a subscriber connected to one server alone (a single-host queue, or a
492
+ * cluster manager limited to part of the fleet) receives only what is
493
+ * published on that server. Fan-out costs every server the whole event
494
+ * stream, and delivers each event to a clustered subscriber once per
495
+ * server, so its handlers must deduplicate.
496
+ */
497
+ publishFanOut?: boolean;
444
498
  /**
445
499
  * Enable process signal handling (SIGTERM, SIGINT, SIGABRT) by the queue.
446
500
  * When enabled, the queue releases its watcher lock on these signals and
@@ -307,8 +307,14 @@ export class UDPClusterManager extends ClusterManager {
307
307
  }
308
308
  const action = method;
309
309
  await this.forEachCluster(cluster => {
310
+ // the worker's announcement, its `timeout` already converted from
311
+ // the wire's seconds to the milliseconds IServerInput declares
310
312
  const server = message.server;
311
- if (action === 'add' && cluster.find(server)) {
313
+ // a known server is announced again every interval, and only the
314
+ // first announcement after a lapse tells its cluster anything
315
+ if (action === 'add' &&
316
+ message.resumed !== true &&
317
+ cluster.find(server)) {
312
318
  return;
313
319
  }
314
320
  const handler = cluster[action];
@@ -89,6 +89,13 @@ export declare class UDPWorker {
89
89
  * when {@link UDPWorkerOptions.useAliveCheck} is on.
90
90
  *
91
91
  * @param message - the announcement that named it
92
+ *
93
+ * @remarks
94
+ * With the alive check on, the first announcement of a server this worker
95
+ * is not tracking - first heard, or heard again after its announcements
96
+ * lapsed - is marked `resumed`. The manager hands that one to a cluster
97
+ * even where the cluster already has the server: a cluster that kept a
98
+ * lapsed server learns from it that the server announces itself again.
92
99
  */
93
100
  private addServer;
94
101
  /**
package/src/UDPWorker.js CHANGED
@@ -140,11 +140,21 @@ export class UDPWorker {
140
140
  * when {@link UDPWorkerOptions.useAliveCheck} is on.
141
141
  *
142
142
  * @param message - the announcement that named it
143
+ *
144
+ * @remarks
145
+ * With the alive check on, the first announcement of a server this worker
146
+ * is not tracking - first heard, or heard again after its announcements
147
+ * lapsed - is marked `resumed`. The manager hands that one to a cluster
148
+ * even where the cluster already has the server: a cluster that kept a
149
+ * lapsed server learns from it that the server announces itself again.
143
150
  */
144
151
  addServer(message) {
152
+ const resumed = this.options.useAliveCheck &&
153
+ !this.servers.has(UDPWorker.getServerKey(message));
145
154
  this.messagePort.postMessage({
146
155
  type: 'cluster:add',
147
156
  server: UDPWorker.mapMessage(message),
157
+ ...(resumed ? { resumed } : {}),
148
158
  });
149
159
  if (this.options.useAliveCheck) {
150
160
  this.serverAliveWait(message);
@@ -33,3 +33,4 @@ export * from './envInt.js';
33
33
  export * from './envTls.js';
34
34
  export * from './tlsFingerprint.js';
35
35
  export * from './logging.js';
36
+ export * from './nextRoundRobin.js';
@@ -33,4 +33,5 @@ export * from './envInt.js';
33
33
  export * from './envTls.js';
34
34
  export * from './tlsFingerprint.js';
35
35
  export * from './logging.js';
36
+ export * from './nextRoundRobin.js';
36
37
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,35 @@
1
+ /*!
2
+ * Helper: nextRoundRobin
3
+ *
4
+ * I'm Queue Software Project
5
+ * Copyright (C) 2025 imqueue.com <support@imqueue.com>
6
+ *
7
+ * This program is free software: you can redistribute it and/or modify
8
+ * it under the terms of the GNU General Public License as published by
9
+ * the Free Software Foundation, either version 3 of the License, or
10
+ * (at your option) any later version.
11
+ *
12
+ * This program is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
+ * GNU General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU General Public License
18
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
19
+ *
20
+ * If you want to use this code in a closed source (commercial) project, you can
21
+ * purchase a proprietary commercial license. Please contact us at
22
+ * <support@imqueue.com> to get commercial licensing options.
23
+ */
24
+ /**
25
+ * Finds the next item, in round-robin order, that a predicate accepts.
26
+ *
27
+ * @typeParam T - item type
28
+ * @param items - the items to choose from
29
+ * @param cursor - where the scan starts; taken modulo the number of items,
30
+ * so a cursor that ran past the end of a shrunken list is still valid
31
+ * @param accept - whether an item may be chosen
32
+ * @returns the index of the first accepted item at or after the cursor,
33
+ * wrapping around once, or -1 when none is accepted
34
+ */
35
+ export declare function nextRoundRobin<T>(items: readonly T[], cursor: number, accept: (item: T) => boolean): number;
@@ -0,0 +1,46 @@
1
+ /*!
2
+ * Helper: nextRoundRobin
3
+ *
4
+ * I'm Queue Software Project
5
+ * Copyright (C) 2025 imqueue.com <support@imqueue.com>
6
+ *
7
+ * This program is free software: you can redistribute it and/or modify
8
+ * it under the terms of the GNU General Public License as published by
9
+ * the Free Software Foundation, either version 3 of the License, or
10
+ * (at your option) any later version.
11
+ *
12
+ * This program is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
+ * GNU General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU General Public License
18
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
19
+ *
20
+ * If you want to use this code in a closed source (commercial) project, you can
21
+ * purchase a proprietary commercial license. Please contact us at
22
+ * <support@imqueue.com> to get commercial licensing options.
23
+ */
24
+ /**
25
+ * Finds the next item, in round-robin order, that a predicate accepts.
26
+ *
27
+ * @typeParam T - item type
28
+ * @param items - the items to choose from
29
+ * @param cursor - where the scan starts; taken modulo the number of items,
30
+ * so a cursor that ran past the end of a shrunken list is still valid
31
+ * @param accept - whether an item may be chosen
32
+ * @returns the index of the first accepted item at or after the cursor,
33
+ * wrapping around once, or -1 when none is accepted
34
+ */
35
+ export function nextRoundRobin(items, cursor, accept) {
36
+ const count = items.length;
37
+ const start = count ? cursor % count : 0;
38
+ for (let offset = 0; offset < count; offset++) {
39
+ const index = (start + offset) % count;
40
+ if (accept(items[index])) {
41
+ return index;
42
+ }
43
+ }
44
+ return -1;
45
+ }
46
+ //# sourceMappingURL=nextRoundRobin.js.map