@imqueue/core 3.5.1 → 3.5.3
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 +136 -0
- package/package.json +1 -1
- package/src/ClusteredRedisQueue.d.ts +158 -23
- package/src/ClusteredRedisQueue.js +419 -69
- package/src/RedisQueue.js +6 -0
package/CHANGELOG.md
CHANGED
|
@@ -11,6 +11,11 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
|
|
|
11
11
|
|
|
12
12
|
## [Unreleased]
|
|
13
13
|
|
|
14
|
+
The clustered subscription changes below are **patch-level bug fixes**: they
|
|
15
|
+
restore additive subscription replay and close lifecycle races without adding a
|
|
16
|
+
public API. Package versions are updated separately; other unreleased features may require a minor
|
|
17
|
+
release.
|
|
18
|
+
|
|
14
19
|
### Added
|
|
15
20
|
|
|
16
21
|
- **TLS on connections to the redis broker.** A new `tls` option encrypts every
|
|
@@ -40,6 +45,14 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
|
|
|
40
45
|
This covers the queue's own connections. `UDPClusterManager` announcements
|
|
41
46
|
remain unauthenticated UDP broadcast and are unaffected.
|
|
42
47
|
|
|
48
|
+
- **Integration specs covering clustered subscription against a real broker**,
|
|
49
|
+
in `test/integration/clusterSubscription.spec.ts`. Unit mocks verify call
|
|
50
|
+
ordering and simulated delivery; these additionally verify Redis subscription
|
|
51
|
+
acknowledgments and actual deliveries. Unlike the TLS specs they do not stand
|
|
52
|
+
up their own server: they use an ambient one at `REDIS_HOST`/`REDIS_PORT` (default
|
|
53
|
+
`127.0.0.1:6379`) and skip, with a reason, when none answers. `npm test` does
|
|
54
|
+
not run them.
|
|
55
|
+
|
|
43
56
|
- **Integration specs covering TLS against a real broker**, in
|
|
44
57
|
`test/integration/`, run by `npm run test-integration`. They stand up a
|
|
45
58
|
throwaway TLS-only redis and assert what a mocked `ioredis` cannot: that the
|
|
@@ -52,6 +65,39 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
|
|
|
52
65
|
|
|
53
66
|
### Changed
|
|
54
67
|
|
|
68
|
+
- **Clustered subscribe()/unsubscribe() now serialise per host.** A call can
|
|
69
|
+
block behind an earlier subscription operation on that host that never
|
|
70
|
+
settles. Different hosts proceed independently. Rejected registrations remain
|
|
71
|
+
remembered and may have succeeded on some hosts; **subscribe() is not
|
|
72
|
+
retryable**. Repeating it adds another registration, including on future
|
|
73
|
+
hosts. To rebuild a known set, await unsubscribe() and register that set again.
|
|
74
|
+
Function-identity deduplication would break deliberate additive registrations;
|
|
75
|
+
rolling back a partial fan-out would require tearing down working subscribers.
|
|
76
|
+
|
|
77
|
+
- **Clustered destroy() clears routing membership and subscription state
|
|
78
|
+
synchronously.** Queued work cannot reopen a destroyed host. Teardown bypasses
|
|
79
|
+
subscription chains so a wedged operation cannot hold it up. Concurrent callers
|
|
80
|
+
await the same teardown (including manager removal) and observe the same
|
|
81
|
+
AggregateError if it fails. Every independent host teardown and manager removal
|
|
82
|
+
is attempted even if others fail. A later destroy() retries only failed tasks;
|
|
83
|
+
successful cleanup is not repeated. Discovery admission closes synchronously
|
|
84
|
+
and stays closed during and after teardown, including retries. A `send()`
|
|
85
|
+
already parked waiting for the first server is rejected as teardown begins,
|
|
86
|
+
rather than waiting out `IMQ_SEND_INIT_TIMEOUT` on a timer that keeps the
|
|
87
|
+
process alive; `send()` and `subscribe()` on a destroyed instance are
|
|
88
|
+
rejected outright instead of stalling or repopulating the cleared state.
|
|
89
|
+
Destroyed instances must not be reused.
|
|
90
|
+
|
|
91
|
+
- **`ClusteredRedisQueue.subscribe()` now rejects a bad channel on an empty
|
|
92
|
+
cluster, where it used to resolve.** Validation lived in the underlying
|
|
93
|
+
queues, so with no servers yet there was nothing to raise it: a second
|
|
94
|
+
channel name, or an empty one, resolved and left the remembered subscription
|
|
95
|
+
naming a channel nothing was subscribed to. The cluster now applies the same
|
|
96
|
+
two checks itself, with the same messages the underlying queue uses, before
|
|
97
|
+
touching any state. An empty cluster is the normal starting point for
|
|
98
|
+
membership discovered at runtime, so a caller that registers before the first
|
|
99
|
+
server arrives will see an error it previously did not.
|
|
100
|
+
|
|
55
101
|
- **Nothing changes for a queue that does not use TLS.** The option is absent
|
|
56
102
|
from `options` unless it was configured, the connection pool key stays the
|
|
57
103
|
plain `host:port`, the redis client is handed no `tls` option, and no new
|
|
@@ -111,6 +157,96 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
|
|
|
111
157
|
|
|
112
158
|
### Fixed
|
|
113
159
|
|
|
160
|
+
- **A joining host whose first subscription attempt failed stayed silent for the
|
|
161
|
+
life of the process.** `RedisQueue.subscribe()` records a handler only after
|
|
162
|
+
the subscribe resolves, so a first failure left that host's handler list
|
|
163
|
+
empty — and the connection layer's own reconnect replays from that list, so it
|
|
164
|
+
restored a socket that was connected, `ready` and subscribed to nothing.
|
|
165
|
+
Nothing brought the host back: the joining catch-up's rejection was swallowed,
|
|
166
|
+
`start()` fans out startup only, a re-announced address is recognised as a
|
|
167
|
+
known server and skipped, and no event reported the failure. A service that
|
|
168
|
+
subscribes once at start-up never registers again, so the promise of repair
|
|
169
|
+
"on a later registration" never came due. `send()` was unaffected throughout,
|
|
170
|
+
which is what made it hard to see.
|
|
171
|
+
|
|
172
|
+
The join now retries the subscription leg with capped exponential backoff,
|
|
173
|
+
cancelled when the host leaves the cluster or the cluster is destroyed, on an
|
|
174
|
+
unref'd timer so a host that never returns cannot hold the process open. Only
|
|
175
|
+
that leg is retried: a failed `start()` is already retryable through an
|
|
176
|
+
explicit `start()`, and retrying it here would poll a connection object the
|
|
177
|
+
reconnect path owns. Retrying is safe because catch-up reads the cluster-owned
|
|
178
|
+
installed count inside the per-host chain and installs only the missing
|
|
179
|
+
suffix, so it cannot reinstall a handler that already landed.
|
|
180
|
+
|
|
181
|
+
A host that becomes usable only through a retry is announced as `initialized`
|
|
182
|
+
once its startup has also succeeded and while it is still a member. Sends
|
|
183
|
+
parked waiting for a usable server wait on that event, so without it they
|
|
184
|
+
would time out against a cluster that had recovered.
|
|
185
|
+
|
|
186
|
+
- **A cluster member that refused a live registration stayed silent as well.**
|
|
187
|
+
The retry above covered a joining host only. `subscribe()` on a cluster that
|
|
188
|
+
already has members — the only route a statically configured cluster ever
|
|
189
|
+
takes, since its hosts are added without a catch-up — installed the handler on
|
|
190
|
+
each member, and where one refused it recorded nothing and nothing asked
|
|
191
|
+
again. The call rejected, but a rejected `subscribe()` cannot be repeated
|
|
192
|
+
without registering a duplicate, so the application had no repair of its own.
|
|
193
|
+
A member that refuses a registration is now retried by the same
|
|
194
|
+
capped-backoff catch-up as a joining host, under the same cancellation rules.
|
|
195
|
+
The call still rejects, so the caller learns that a host was unreachable when
|
|
196
|
+
it subscribed; it no longer means that host stays unsubscribed.
|
|
197
|
+
|
|
198
|
+
- **A subscription handler could be attached twice to the same connection,
|
|
199
|
+
delivering every message twice.** `connect()` binds a connection before it
|
|
200
|
+
awaits it and returns that same object to any concurrent caller, so a
|
|
201
|
+
`subscribe()` racing a reconnect attached its handler to a connection whose
|
|
202
|
+
restore had not yet run; the restore then re-attached every remembered
|
|
203
|
+
handler, including that one. Reachable before this release by a live
|
|
204
|
+
`subscribe()` during a reconnect; the retry above made it likely, which is how
|
|
205
|
+
it was found. `restoreSubscription()` now reconciles the connection's listeners
|
|
206
|
+
to exactly the remembered handlers instead of appending to them.
|
|
207
|
+
|
|
208
|
+
- **A clustered queue gave a server that joined later only the last-registered
|
|
209
|
+
subscription handler, silencing every other handler on that host.**
|
|
210
|
+
`ClusteredRedisQueue` remembered one `{ channel, handler }` pair, so each
|
|
211
|
+
`subscribe()` overwrote the previous one. Handlers were still forwarded to the
|
|
212
|
+
hosts already known, which is why this stayed invisible while cluster
|
|
213
|
+
membership was stable — but a host added afterwards (a broker replaced, or
|
|
214
|
+
discovery completing after the calls at start-up) was subscribed with the
|
|
215
|
+
**last** handler alone. With one handler carrying business events and another
|
|
216
|
+
carrying cache invalidation, a host could serve the second and silently drop
|
|
217
|
+
the first: the socket stays subscribed, the publisher still sees a subscriber
|
|
218
|
+
and RPC is unaffected, so nothing surfaces the loss.
|
|
219
|
+
|
|
220
|
+
Every registration is now remembered and installed, in registration order,
|
|
221
|
+
including the same function registered twice — `subscribe()` remains additive
|
|
222
|
+
as documented.
|
|
223
|
+
|
|
224
|
+
Live registration and joining-host catch-up share a serialised operation per
|
|
225
|
+
host. Each run reads a cluster-owned per-host installation count and installs
|
|
226
|
+
the remaining registrations, advancing only after success. Direct host
|
|
227
|
+
registrations do not count towards cluster progress. Cluster unsubscribe
|
|
228
|
+
resets that count inside the same chain, including after a rejected teardown.
|
|
229
|
+
Overlapping runs do not duplicate a cluster registration within an
|
|
230
|
+
uninterrupted subscription. This is not an unconditional exactly-once delivery
|
|
231
|
+
guarantee: deliberate repeated registrations still invoke twice, publication
|
|
232
|
+
across hosts can deliver more than once, and unsubscribe/replacement can cause
|
|
233
|
+
a temporary installation that teardown removes before catch-up reinstalls it.
|
|
234
|
+
|
|
235
|
+
A host dropped mid-catch-up receives no further installations and is not
|
|
236
|
+
announced as initialized. Two kinds of `info` line report the ordinal and
|
|
237
|
+
channel of each registration, and how many handlers a catch-up run installed. The verbose
|
|
238
|
+
`Initializing queue with state` line has been removed.
|
|
239
|
+
|
|
240
|
+
- **A server that failed to start while joining could take the process down.**
|
|
241
|
+
Its background initialization now observes rejection, preventing an unhandled
|
|
242
|
+
rejection and process exit. Startup and subscription catch-up run independently:
|
|
243
|
+
a failed or stalled start does not block pub/sub, preserving the documented
|
|
244
|
+
ability to subscribe without start(). Joining hosts still start automatically
|
|
245
|
+
in a started cluster; later subscribe() calls do not retry startup. Deferred
|
|
246
|
+
joining-host startup and cluster start() share pending startup per host, so
|
|
247
|
+
they cannot start that host concurrently. Settled startup is released so an
|
|
248
|
+
explicit later start() can retry.
|
|
249
|
+
|
|
114
250
|
- **A failed connection could crash the process as it was being torn down.**
|
|
115
251
|
The redis client guards its socket with a one-shot `error` listener, which
|
|
116
252
|
the failure that brings the connection down spends. A socket that goes on to
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@imqueue/core",
|
|
3
|
-
"version": "3.5.
|
|
3
|
+
"version": "3.5.3",
|
|
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",
|
|
@@ -34,6 +34,18 @@ export interface ClusterServer extends IMessageQueueConnection {
|
|
|
34
34
|
/**
|
|
35
35
|
* Queue instance created for this host. Present once the server has been
|
|
36
36
|
* registered; the queue may still be starting.
|
|
37
|
+
*
|
|
38
|
+
* @remarks
|
|
39
|
+
* Exposed to inspect or address one specific host. Subscribing through it
|
|
40
|
+
* directly is safe only on the channel the cluster itself uses: a queue
|
|
41
|
+
* accepts one channel, so a direct subscription to another name makes every
|
|
42
|
+
* later cluster registration on that host fail. `unsubscribe()` and
|
|
43
|
+
* `destroy()` on it are not
|
|
44
|
+
* supported: the cluster tracks how many of its own registrations a host
|
|
45
|
+
* has taken, and it cannot see a handler removed behind its back, so a
|
|
46
|
+
* registration made afterwards would be installed while an earlier one
|
|
47
|
+
* stayed missing. Use {@link ClusteredRedisQueue.unsubscribe} and
|
|
48
|
+
* {@link ClusteredRedisQueue.removeServer} instead.
|
|
37
49
|
*/
|
|
38
50
|
imq?: RedisQueue;
|
|
39
51
|
}
|
|
@@ -50,8 +62,8 @@ export interface ClusterServer extends IMessageQueueConnection {
|
|
|
50
62
|
* `clear`, `destroy`, `publish`, `subscribe`, `unsubscribe` and `queueLength` —
|
|
51
63
|
* fans out to every server.
|
|
52
64
|
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
65
|
+
* Fan-out normally uses `Promise.all`, with no rollback on failure. Destroy
|
|
66
|
+
* attempts every cleanup task and reports failures together in an AggregateError.
|
|
55
67
|
*
|
|
56
68
|
* The class only `implements` the `EventEmitter` interface rather than extending
|
|
57
69
|
* it, so `instanceof EventEmitter` is false and every emitter method is a
|
|
@@ -134,10 +146,30 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
|
|
|
134
146
|
* @remarks
|
|
135
147
|
* Cluster membership changes at runtime, so a per-host queue may be created
|
|
136
148
|
* long after `start()` and `subscribe()` were called on the cluster. This
|
|
137
|
-
* records those calls;
|
|
138
|
-
*
|
|
149
|
+
* records those calls; joining hosts replay startup and subscription
|
|
150
|
+
* catch-up independently.
|
|
139
151
|
*/
|
|
140
152
|
private state;
|
|
153
|
+
/**
|
|
154
|
+
* Tracks this cluster's successful installations, independently of handlers
|
|
155
|
+
* registered directly on a host. Teardown resets the installation count.
|
|
156
|
+
*/
|
|
157
|
+
private readonly progress;
|
|
158
|
+
/**
|
|
159
|
+
* Sends parked in {@link ClusteredRedisQueue.sendWhenInitialized}, waiting
|
|
160
|
+
* for a server to appear. Kept so {@link ClusteredRedisQueue.destroy} can
|
|
161
|
+
* settle them at once rather than leaving each to time out against a
|
|
162
|
+
* cluster that can no longer admit a server.
|
|
163
|
+
*/
|
|
164
|
+
private readonly waitingSends;
|
|
165
|
+
/** Pending startup shared by batch startup and joining-host initialization. */
|
|
166
|
+
private readonly starting;
|
|
167
|
+
/** Membership admission stays closed after the first destroy() call. */
|
|
168
|
+
private closed;
|
|
169
|
+
/** Failed cleanup tasks remain here for an explicit destroy() retry. */
|
|
170
|
+
private readonly cleanup;
|
|
171
|
+
/** Teardown shared by concurrent destroy() callers. */
|
|
172
|
+
private destroying?;
|
|
141
173
|
/**
|
|
142
174
|
* Handles for the cluster managers this queue is registered with, kept so
|
|
143
175
|
* that {@link ClusteredRedisQueue.destroy} can deregister from each.
|
|
@@ -243,16 +275,21 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
|
|
|
243
275
|
private sendWhenInitialized;
|
|
244
276
|
/**
|
|
245
277
|
* Destroys every server's queue — closing their connections and removing
|
|
246
|
-
* their event listeners —
|
|
278
|
+
* their event listeners — and unregisters this cluster from all configured
|
|
247
279
|
* cluster managers.
|
|
248
280
|
*
|
|
249
281
|
* @remarks
|
|
250
282
|
* Unregistering shuts a manager down entirely once it has no clusters left,
|
|
251
283
|
* which for {@link UDPClusterManager} also terminates its shared UDP worker.
|
|
252
284
|
*
|
|
253
|
-
*
|
|
254
|
-
*
|
|
255
|
-
*
|
|
285
|
+
* Routing membership and remembered subscriptions are cleared synchronously,
|
|
286
|
+
* so queued subscription work cannot reopen a destroyed host. Teardown does
|
|
287
|
+
* not wait for the subscription chain; concurrent callers await the same
|
|
288
|
+
* teardown, including manager removal. Every independent cleanup is attempted;
|
|
289
|
+
* failures are reported together in an AggregateError. A later destroy()
|
|
290
|
+
* retries only failed tasks; successful tasks are not repeated. Membership
|
|
291
|
+
* admission stays closed, including during retries. The instance must not
|
|
292
|
+
* be reused.
|
|
256
293
|
*/
|
|
257
294
|
destroy(): Promise<void>;
|
|
258
295
|
/**
|
|
@@ -499,26 +536,53 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
|
|
|
499
536
|
*
|
|
500
537
|
* @param channel - channel name within the queue's prefix namespace
|
|
501
538
|
* @param handler - invoked with the parsed payload of each published message
|
|
502
|
-
* @throws TypeError when
|
|
503
|
-
*
|
|
539
|
+
* @throws TypeError when no channel name is given, or when a different
|
|
540
|
+
* channel name is supplied while this instance already remembers
|
|
541
|
+
* one - both are raised here, so they fire on an empty cluster too,
|
|
542
|
+
* where there is no underlying queue to raise them
|
|
504
543
|
*
|
|
505
544
|
* @remarks
|
|
506
545
|
* Only one channel per instance is supported. Calling this again with the
|
|
507
|
-
* same channel registers
|
|
508
|
-
*
|
|
509
|
-
*
|
|
510
|
-
*
|
|
546
|
+
* same channel registers an additional handler — every registration is
|
|
547
|
+
* remembered and all of them are invoked, including the same function
|
|
548
|
+
* registered twice. Calling it with a different channel throws before any
|
|
549
|
+
* state is touched, so the remembered channel keeps naming the channel that
|
|
550
|
+
* is actually subscribed.
|
|
551
|
+
*
|
|
552
|
+
* Servers joining later are given every handler registered before they
|
|
553
|
+
* joined, in registration order.
|
|
554
|
+
*
|
|
555
|
+
* Subscription uses its own connection and does not require start(), even
|
|
556
|
+
* when a host's startup fails or stalls. Subscription changes serialise per
|
|
557
|
+
* host, so a call can wait behind an earlier operation that never settles.
|
|
558
|
+
*
|
|
559
|
+
* A rejected call is not retryable: its registration remains remembered and
|
|
560
|
+
* may already be installed on some hosts. Calling again adds another copy,
|
|
561
|
+
* including for future hosts. To rebuild a known registration set, await
|
|
562
|
+
* unsubscribe() and then register the desired handlers again.
|
|
563
|
+
*
|
|
564
|
+
* A host that refused the registration is not left behind: the cluster
|
|
565
|
+
* retries its catch-up on its own, with capped backoff, until it succeeds,
|
|
566
|
+
* the host leaves or the cluster is destroyed. A rejection therefore reports
|
|
567
|
+
* that a host was unreachable when the call was made, not that it stays
|
|
568
|
+
* unsubscribed.
|
|
511
569
|
*
|
|
512
570
|
* The handler receives one invocation per host that delivers the message.
|
|
513
571
|
*/
|
|
514
572
|
subscribe(channel: string, handler: (data: JsonObject) => void): Promise<void>;
|
|
515
573
|
/**
|
|
516
|
-
* Unsubscribes from the channel on every redis host and forgets
|
|
517
|
-
* remembered
|
|
574
|
+
* Unsubscribes from the channel on every redis host and forgets every
|
|
575
|
+
* remembered handler, so servers joining later are no longer subscribed
|
|
518
576
|
* automatically.
|
|
519
577
|
*
|
|
520
578
|
* @remarks
|
|
521
579
|
* Resolves without effect on an empty cluster.
|
|
580
|
+
*
|
|
581
|
+
* Clears the remembered channel and handlers immediately, then queues each
|
|
582
|
+
* host's teardown behind its current subscription work. A stalled operation
|
|
583
|
+
* on that host therefore also stalls unsubscribe(). Later catch-up reads the
|
|
584
|
+
* cluster's installation count after teardown, even if an earlier run
|
|
585
|
+
* temporarily installed handlers from the replacement list.
|
|
522
586
|
*/
|
|
523
587
|
unsubscribe(): Promise<void>;
|
|
524
588
|
/**
|
|
@@ -538,7 +602,8 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
|
|
|
538
602
|
*
|
|
539
603
|
* For a genuinely new server this returns as soon as the record is created —
|
|
540
604
|
* starting the queue and re-applying any active subscription happen
|
|
541
|
-
* asynchronously afterwards.
|
|
605
|
+
* asynchronously afterwards. Once destroy() begins, discovery is ignored:
|
|
606
|
+
* the returned address has no queue and is not admitted to membership.
|
|
542
607
|
*/
|
|
543
608
|
protected addServer(server: IServerInput): ClusterServer;
|
|
544
609
|
/**
|
|
@@ -579,16 +644,86 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
|
|
|
579
644
|
*/
|
|
580
645
|
private eventEmitters;
|
|
581
646
|
/**
|
|
582
|
-
*
|
|
647
|
+
* Appends one operation to a host's serialised queue.
|
|
648
|
+
*
|
|
649
|
+
* @param imq - the queue the operation belongs to
|
|
650
|
+
* @param operation - the work to run once everything before it has finished
|
|
651
|
+
* @returns a promise for this operation alone, which rejects if it fails
|
|
652
|
+
*
|
|
653
|
+
* @remarks
|
|
654
|
+
* Every `subscribe`, `unsubscribe` and catch-up run for a host goes through
|
|
655
|
+
* here, so operations on one host never overlap, while different hosts stay
|
|
656
|
+
* independent. The tail kept for the next operation is deliberately
|
|
657
|
+
* repaired with a `catch`: chaining onto a rejected tail would make one
|
|
658
|
+
* failed operation reject every operation the host is ever given again,
|
|
659
|
+
* which is precisely the "host that silently stopped working" this class
|
|
660
|
+
* has to avoid. The caller still receives the failure, through the returned
|
|
661
|
+
* promise.
|
|
662
|
+
*/
|
|
663
|
+
private enqueue;
|
|
664
|
+
/**
|
|
665
|
+
* Returns the progress record for a host, creating it on first use.
|
|
666
|
+
*
|
|
667
|
+
* @param imq - the queue to look up
|
|
668
|
+
* @returns that host's progress record
|
|
669
|
+
*/
|
|
670
|
+
private progressOf;
|
|
671
|
+
/**
|
|
672
|
+
* Starts a joining host if it still belongs to a started cluster.
|
|
673
|
+
* Subscription catch-up proceeds independently of this lifecycle operation.
|
|
674
|
+
*/
|
|
675
|
+
private startHost;
|
|
676
|
+
/**
|
|
677
|
+
* Retries a host's subscription catch-up until it succeeds, the host leaves
|
|
678
|
+
* the cluster, or the cluster is destroyed.
|
|
679
|
+
*
|
|
680
|
+
* @param imq - the queue whose catch-up failed
|
|
681
|
+
* @param started - the joining host's startup, which the announcement waits
|
|
682
|
+
* for. A live registration has nothing to announce and omits it
|
|
683
|
+
* @param announce - emits `initialized` for a joining host that only became
|
|
684
|
+
* usable through this retry. Omitted by a live registration, whose
|
|
685
|
+
* host is already a member that sends are routed to
|
|
686
|
+
*
|
|
687
|
+
* @remarks
|
|
688
|
+
* Both routes to a first subscribe end here: a joining host's catch-up, and
|
|
689
|
+
* a live registration on a host that is already a member, which is the only
|
|
690
|
+
* route a statically configured cluster ever takes.
|
|
691
|
+
*
|
|
692
|
+
* A host whose first {@link RedisQueue.subscribe} rejects records
|
|
693
|
+
* nothing: `subscriptionHandlers` stays empty, so the connection layer's
|
|
694
|
+
* own reconnect has nothing to replay and restores a socket subscribed to
|
|
695
|
+
* no channel. Without this, that host never receives another installation —
|
|
696
|
+
* `start()` fans out startup only, a re-announced address is recognised as a
|
|
697
|
+
* known server and skipped, and a service that subscribes once at boot never
|
|
698
|
+
* registers again. The host stays a silent member for the life of the
|
|
699
|
+
* process while every probe it answers reports health.
|
|
700
|
+
*
|
|
701
|
+
* Retrying is safe because catch-up is idempotent: {@link
|
|
702
|
+
* ClusteredRedisQueue.syncHost} reads the cluster-owned installed count
|
|
703
|
+
* inside the per-host chain and installs only the missing suffix, so a retry
|
|
704
|
+
* cannot duplicate a handler that did land. The backoff mirrors the
|
|
705
|
+
* connection layer's, which this has to outlive.
|
|
706
|
+
*/
|
|
707
|
+
private scheduleSync;
|
|
708
|
+
/**
|
|
709
|
+
* Cancels a pending catch-up retry for a host being torn down.
|
|
710
|
+
*
|
|
711
|
+
* @param imq - the queue leaving the cluster
|
|
712
|
+
*/
|
|
713
|
+
private cancelSync;
|
|
714
|
+
/**
|
|
715
|
+
* Installs registrations this cluster has not yet installed on a host.
|
|
583
716
|
*
|
|
584
|
-
* @param imq - the queue to
|
|
717
|
+
* @param imq - the queue to bring up to date
|
|
718
|
+
* @returns this run's completion, rejecting on a failed installation
|
|
585
719
|
*
|
|
586
720
|
* @remarks
|
|
587
|
-
*
|
|
588
|
-
*
|
|
589
|
-
*
|
|
721
|
+
* Both live registrations and joining hosts use the same serialised path.
|
|
722
|
+
* Each run reads the cluster-owned count inside the chain, so repeating it adds
|
|
723
|
+
* nothing. A queued teardown may erase a temporary installation; the run
|
|
724
|
+
* behind that teardown will then see and install the missing suffix again.
|
|
590
725
|
*/
|
|
591
|
-
private
|
|
726
|
+
private syncHost;
|
|
592
727
|
/**
|
|
593
728
|
* Finds an already-registered server matching the given one.
|
|
594
729
|
*
|
|
@@ -31,6 +31,15 @@ import { DEFAULT_IMQ_OPTIONS, IMQMode, RedisQueue, } from './index.js';
|
|
|
31
31
|
* IMQ_SEND_INIT_TIMEOUT environment variable, defaults to 30,000.
|
|
32
32
|
*/
|
|
33
33
|
const SEND_INIT_TIMEOUT = +(process.env.IMQ_SEND_INIT_TIMEOUT || 0) || 30000;
|
|
34
|
+
/**
|
|
35
|
+
* Delay (ms) before the first retry of a joining host's subscription catch-up,
|
|
36
|
+
* doubling up to {@link SYNC_RETRY_MAX_DELAY}. Mirrors the connection layer's
|
|
37
|
+
* own reconnect policy, which this retry has to outlive: the socket may take
|
|
38
|
+
* several attempts to come back, and the handlers have to go on afterwards.
|
|
39
|
+
*/
|
|
40
|
+
const SYNC_RETRY_BASE_DELAY = 1000;
|
|
41
|
+
/** Longest delay (ms) between subscription catch-up retries. */
|
|
42
|
+
const SYNC_RETRY_MAX_DELAY = 30000;
|
|
34
43
|
/**
|
|
35
44
|
* Scales a single logical queue horizontally across several redis instances.
|
|
36
45
|
* This is what {@link IMQ.create} returns when {@link IMQOptions.cluster} or
|
|
@@ -44,8 +53,8 @@ const SEND_INIT_TIMEOUT = +(process.env.IMQ_SEND_INIT_TIMEOUT || 0) || 30000;
|
|
|
44
53
|
* `clear`, `destroy`, `publish`, `subscribe`, `unsubscribe` and `queueLength` —
|
|
45
54
|
* fans out to every server.
|
|
46
55
|
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
56
|
+
* Fan-out normally uses `Promise.all`, with no rollback on failure. Destroy
|
|
57
|
+
* attempts every cleanup task and reports failures together in an AggregateError.
|
|
49
58
|
*
|
|
50
59
|
* The class only `implements` the `EventEmitter` interface rather than extending
|
|
51
60
|
* it, so `instanceof EventEmitter` is false and every emitter method is a
|
|
@@ -119,13 +128,34 @@ export class ClusteredRedisQueue {
|
|
|
119
128
|
* @remarks
|
|
120
129
|
* Cluster membership changes at runtime, so a per-host queue may be created
|
|
121
130
|
* long after `start()` and `subscribe()` were called on the cluster. This
|
|
122
|
-
* records those calls;
|
|
123
|
-
*
|
|
131
|
+
* records those calls; joining hosts replay startup and subscription
|
|
132
|
+
* catch-up independently.
|
|
124
133
|
*/
|
|
125
134
|
state = {
|
|
126
135
|
started: false,
|
|
127
|
-
|
|
136
|
+
channel: null,
|
|
137
|
+
handlers: [],
|
|
128
138
|
};
|
|
139
|
+
/**
|
|
140
|
+
* Tracks this cluster's successful installations, independently of handlers
|
|
141
|
+
* registered directly on a host. Teardown resets the installation count.
|
|
142
|
+
*/
|
|
143
|
+
progress = new WeakMap();
|
|
144
|
+
/**
|
|
145
|
+
* Sends parked in {@link ClusteredRedisQueue.sendWhenInitialized}, waiting
|
|
146
|
+
* for a server to appear. Kept so {@link ClusteredRedisQueue.destroy} can
|
|
147
|
+
* settle them at once rather than leaving each to time out against a
|
|
148
|
+
* cluster that can no longer admit a server.
|
|
149
|
+
*/
|
|
150
|
+
waitingSends = new Set();
|
|
151
|
+
/** Pending startup shared by batch startup and joining-host initialization. */
|
|
152
|
+
starting = new WeakMap();
|
|
153
|
+
/** Membership admission stays closed after the first destroy() call. */
|
|
154
|
+
closed = false;
|
|
155
|
+
/** Failed cleanup tasks remain here for an explicit destroy() retry. */
|
|
156
|
+
cleanup = new Set();
|
|
157
|
+
/** Teardown shared by concurrent destroy() callers. */
|
|
158
|
+
destroying;
|
|
129
159
|
/**
|
|
130
160
|
* Handles for the cluster managers this queue is registered with, kept so
|
|
131
161
|
* that {@link ClusteredRedisQueue.destroy} can deregister from each.
|
|
@@ -247,6 +277,13 @@ export class ClusteredRedisQueue {
|
|
|
247
277
|
* milliseconds).
|
|
248
278
|
*/
|
|
249
279
|
async send(toQueue, message, delay, errorHandler) {
|
|
280
|
+
if (this.closed) {
|
|
281
|
+
// admission is closed, so no server can ever arrive: waiting out
|
|
282
|
+
// the initialisation timeout would stall a shutdown path for
|
|
283
|
+
// IMQ_SEND_INIT_TIMEOUT on a timer that is not unref()'d
|
|
284
|
+
throw new TypeError('ClusteredRedisQueue: the queue was destroyed and cannot be ' +
|
|
285
|
+
'reused, so this message has nowhere to go!');
|
|
286
|
+
}
|
|
250
287
|
if (!this.imqLength) {
|
|
251
288
|
return this.sendWhenInitialized(toQueue, message, delay, errorHandler);
|
|
252
289
|
}
|
|
@@ -292,40 +329,93 @@ export class ClusteredRedisQueue {
|
|
|
292
329
|
return new Promise((resolve, reject) => {
|
|
293
330
|
const onInitialized = ({ imq }) => {
|
|
294
331
|
clearTimeout(timer);
|
|
332
|
+
this.waitingSends.delete(giveUp);
|
|
295
333
|
imq.send(toQueue, message, delay, errorHandler).then(resolve, reject);
|
|
296
334
|
};
|
|
297
|
-
const
|
|
335
|
+
const giveUp = (reason) => {
|
|
336
|
+
clearTimeout(timer);
|
|
298
337
|
this.clusterEmitter.removeListener('initialized', onInitialized);
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
}
|
|
338
|
+
this.waitingSends.delete(giveUp);
|
|
339
|
+
reject(reason);
|
|
340
|
+
};
|
|
341
|
+
const timer = setTimeout(() => giveUp(new Error('ClusteredRedisQueue: no cluster server became ' +
|
|
342
|
+
'available to send the message')), this.sendInitTimeout);
|
|
343
|
+
// registered so destroy() can settle this immediately: once
|
|
344
|
+
// admission is closed no server can ever initialise, and waiting
|
|
345
|
+
// out the timeout would hold the event loop open on a shutdown
|
|
346
|
+
this.waitingSends.add(giveUp);
|
|
302
347
|
this.clusterEmitter.once('initialized', onInitialized);
|
|
303
348
|
});
|
|
304
349
|
}
|
|
305
350
|
/**
|
|
306
351
|
* Destroys every server's queue — closing their connections and removing
|
|
307
|
-
* their event listeners —
|
|
352
|
+
* their event listeners — and unregisters this cluster from all configured
|
|
308
353
|
* cluster managers.
|
|
309
354
|
*
|
|
310
355
|
* @remarks
|
|
311
356
|
* Unregistering shuts a manager down entirely once it has no clusters left,
|
|
312
357
|
* which for {@link UDPClusterManager} also terminates its shared UDP worker.
|
|
313
358
|
*
|
|
314
|
-
*
|
|
315
|
-
*
|
|
316
|
-
*
|
|
359
|
+
* Routing membership and remembered subscriptions are cleared synchronously,
|
|
360
|
+
* so queued subscription work cannot reopen a destroyed host. Teardown does
|
|
361
|
+
* not wait for the subscription chain; concurrent callers await the same
|
|
362
|
+
* teardown, including manager removal. Every independent cleanup is attempted;
|
|
363
|
+
* failures are reported together in an AggregateError. A later destroy()
|
|
364
|
+
* retries only failed tasks; successful tasks are not repeated. Membership
|
|
365
|
+
* admission stays closed, including during retries. The instance must not
|
|
366
|
+
* be reused.
|
|
317
367
|
*/
|
|
318
368
|
async destroy() {
|
|
319
|
-
this.
|
|
320
|
-
|
|
321
|
-
if (!this.options.clusterManagers?.length) {
|
|
322
|
-
return;
|
|
369
|
+
if (this.destroying) {
|
|
370
|
+
return this.destroying;
|
|
323
371
|
}
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
372
|
+
if (!this.closed) {
|
|
373
|
+
this.closed = true;
|
|
374
|
+
this.state.started = false;
|
|
375
|
+
for (const imq of this.imqs) {
|
|
376
|
+
this.cancelSync(imq);
|
|
377
|
+
this.cleanup.add(() => imq.destroy());
|
|
378
|
+
}
|
|
379
|
+
for (const manager of this.options.clusterManagers || []) {
|
|
380
|
+
for (const cluster of this.initializedClusters) {
|
|
381
|
+
this.cleanup.add(() => manager.remove(cluster));
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
// Close routing before queued subscription or startup work can run.
|
|
385
|
+
// Teardown bypasses those chains so a stalled install cannot block it.
|
|
386
|
+
this.imqs = [];
|
|
387
|
+
this.servers = [];
|
|
388
|
+
this.imqLength = 0;
|
|
389
|
+
this.state.channel = null;
|
|
390
|
+
this.state.handlers = [];
|
|
391
|
+
// a send parked waiting for a server can never be satisfied once
|
|
392
|
+
// admission is closed, and its timer is referenced, so leaving it
|
|
393
|
+
// to expire holds the event loop open for the whole timeout
|
|
394
|
+
const parked = Array.from(this.waitingSends);
|
|
395
|
+
this.waitingSends.clear();
|
|
396
|
+
for (const giveUp of parked) {
|
|
397
|
+
giveUp(new Error('ClusteredRedisQueue: the queue was destroyed before ' +
|
|
398
|
+
'a cluster server became available'));
|
|
327
399
|
}
|
|
328
400
|
}
|
|
401
|
+
this.destroying = Promise.resolve()
|
|
402
|
+
.then(async () => {
|
|
403
|
+
this.logLine('info', 'Destroying clustered redis message queue...');
|
|
404
|
+
const results = await Promise.allSettled([...this.cleanup].map(async (operation) => {
|
|
405
|
+
await operation();
|
|
406
|
+
this.cleanup.delete(operation);
|
|
407
|
+
}));
|
|
408
|
+
const errors = results
|
|
409
|
+
.filter(result => result.status === 'rejected')
|
|
410
|
+
.map(result => result.reason);
|
|
411
|
+
if (errors.length) {
|
|
412
|
+
throw new AggregateError(errors, 'Cluster teardown failed');
|
|
413
|
+
}
|
|
414
|
+
})
|
|
415
|
+
.finally(() => {
|
|
416
|
+
this.destroying = undefined;
|
|
417
|
+
});
|
|
418
|
+
return this.destroying;
|
|
329
419
|
}
|
|
330
420
|
/**
|
|
331
421
|
* Deletes this queue's data on every redis host in the cluster,
|
|
@@ -396,8 +486,7 @@ export class ClusteredRedisQueue {
|
|
|
396
486
|
this.logger.info(message);
|
|
397
487
|
const promises = [];
|
|
398
488
|
for (const imq of this.imqs) {
|
|
399
|
-
|
|
400
|
-
promises.push(run.call(imq));
|
|
489
|
+
promises.push(action === 'start' ? this.startHost(imq) : imq[action]());
|
|
401
490
|
}
|
|
402
491
|
await Promise.all(promises);
|
|
403
492
|
return this;
|
|
@@ -669,41 +758,89 @@ export class ClusteredRedisQueue {
|
|
|
669
758
|
*
|
|
670
759
|
* @param channel - channel name within the queue's prefix namespace
|
|
671
760
|
* @param handler - invoked with the parsed payload of each published message
|
|
672
|
-
* @throws TypeError when
|
|
673
|
-
*
|
|
761
|
+
* @throws TypeError when no channel name is given, or when a different
|
|
762
|
+
* channel name is supplied while this instance already remembers
|
|
763
|
+
* one - both are raised here, so they fire on an empty cluster too,
|
|
764
|
+
* where there is no underlying queue to raise them
|
|
674
765
|
*
|
|
675
766
|
* @remarks
|
|
676
767
|
* Only one channel per instance is supported. Calling this again with the
|
|
677
|
-
* same channel registers
|
|
678
|
-
*
|
|
679
|
-
*
|
|
680
|
-
*
|
|
768
|
+
* same channel registers an additional handler — every registration is
|
|
769
|
+
* remembered and all of them are invoked, including the same function
|
|
770
|
+
* registered twice. Calling it with a different channel throws before any
|
|
771
|
+
* state is touched, so the remembered channel keeps naming the channel that
|
|
772
|
+
* is actually subscribed.
|
|
773
|
+
*
|
|
774
|
+
* Servers joining later are given every handler registered before they
|
|
775
|
+
* joined, in registration order.
|
|
776
|
+
*
|
|
777
|
+
* Subscription uses its own connection and does not require start(), even
|
|
778
|
+
* when a host's startup fails or stalls. Subscription changes serialise per
|
|
779
|
+
* host, so a call can wait behind an earlier operation that never settles.
|
|
780
|
+
*
|
|
781
|
+
* A rejected call is not retryable: its registration remains remembered and
|
|
782
|
+
* may already be installed on some hosts. Calling again adds another copy,
|
|
783
|
+
* including for future hosts. To rebuild a known registration set, await
|
|
784
|
+
* unsubscribe() and then register the desired handlers again.
|
|
785
|
+
*
|
|
786
|
+
* A host that refused the registration is not left behind: the cluster
|
|
787
|
+
* retries its catch-up on its own, with capped backoff, until it succeeds,
|
|
788
|
+
* the host leaves or the cluster is destroyed. A rejection therefore reports
|
|
789
|
+
* that a host was unreachable when the call was made, not that it stays
|
|
790
|
+
* unsubscribed.
|
|
681
791
|
*
|
|
682
792
|
* The handler receives one invocation per host that delivers the message.
|
|
683
793
|
*/
|
|
684
794
|
async subscribe(channel, handler) {
|
|
685
|
-
this.
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
promises.push(imq.subscribe(channel, handler));
|
|
795
|
+
if (this.closed) {
|
|
796
|
+
throw new TypeError('ClusteredRedisQueue: the queue was destroyed and cannot be ' +
|
|
797
|
+
'reused, so this subscription would never reach a server!');
|
|
689
798
|
}
|
|
690
|
-
|
|
799
|
+
if (!channel) {
|
|
800
|
+
throw new TypeError(`${channel}: No subscription channel name provided!`);
|
|
801
|
+
}
|
|
802
|
+
if (this.state.channel && this.state.channel !== channel) {
|
|
803
|
+
throw new TypeError(`Invalid channel name provided: expected "${this.state.channel}", but "${channel}" given instead!`);
|
|
804
|
+
}
|
|
805
|
+
this.state.channel = channel;
|
|
806
|
+
this.state.handlers.push(handler);
|
|
807
|
+
this.logLine('info', `registered handler #${this.state.handlers.length} for channel ` +
|
|
808
|
+
`${channel}`);
|
|
809
|
+
await Promise.all(this.imqs.map(imq => this.syncHost(imq).catch(err => {
|
|
810
|
+
// a member that refuses a live registration has no other
|
|
811
|
+
// route back: the caller cannot retry, because calling
|
|
812
|
+
// again registers a second copy, and a service that
|
|
813
|
+
// subscribes once at start-up never registers again. So the
|
|
814
|
+
// cluster retries on its own, exactly as it does for a join
|
|
815
|
+
this.scheduleSync(imq);
|
|
816
|
+
throw err;
|
|
817
|
+
})));
|
|
691
818
|
}
|
|
692
819
|
/**
|
|
693
|
-
* Unsubscribes from the channel on every redis host and forgets
|
|
694
|
-
* remembered
|
|
820
|
+
* Unsubscribes from the channel on every redis host and forgets every
|
|
821
|
+
* remembered handler, so servers joining later are no longer subscribed
|
|
695
822
|
* automatically.
|
|
696
823
|
*
|
|
697
824
|
* @remarks
|
|
698
825
|
* Resolves without effect on an empty cluster.
|
|
826
|
+
*
|
|
827
|
+
* Clears the remembered channel and handlers immediately, then queues each
|
|
828
|
+
* host's teardown behind its current subscription work. A stalled operation
|
|
829
|
+
* on that host therefore also stalls unsubscribe(). Later catch-up reads the
|
|
830
|
+
* cluster's installation count after teardown, even if an earlier run
|
|
831
|
+
* temporarily installed handlers from the replacement list.
|
|
699
832
|
*/
|
|
700
833
|
async unsubscribe() {
|
|
701
|
-
this.state.
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
834
|
+
this.state.channel = null;
|
|
835
|
+
this.state.handlers = [];
|
|
836
|
+
await Promise.all(this.imqs.map(imq => this.enqueue(imq, async () => {
|
|
837
|
+
try {
|
|
838
|
+
await imq.unsubscribe();
|
|
839
|
+
}
|
|
840
|
+
finally {
|
|
841
|
+
this.progressOf(imq).installed = 0;
|
|
842
|
+
}
|
|
843
|
+
})));
|
|
707
844
|
}
|
|
708
845
|
/**
|
|
709
846
|
* Adds a single server to the cluster and returns its registration record.
|
|
@@ -722,7 +859,8 @@ export class ClusteredRedisQueue {
|
|
|
722
859
|
*
|
|
723
860
|
* For a genuinely new server this returns as soon as the record is created —
|
|
724
861
|
* starting the queue and re-applying any active subscription happen
|
|
725
|
-
* asynchronously afterwards.
|
|
862
|
+
* asynchronously afterwards. Once destroy() begins, discovery is ignored:
|
|
863
|
+
* the returned address has no queue and is not admitted to membership.
|
|
726
864
|
*/
|
|
727
865
|
addServer(server) {
|
|
728
866
|
this.verbose(`Adding new server: ${JSON.stringify(server)}`);
|
|
@@ -750,7 +888,15 @@ export class ClusteredRedisQueue {
|
|
|
750
888
|
}
|
|
751
889
|
const imqToRemove = remove.imq;
|
|
752
890
|
if (imqToRemove) {
|
|
891
|
+
// a retry scheduled for this host must not outlive it
|
|
892
|
+
this.cancelSync(imqToRemove);
|
|
893
|
+
// dropped from routing first: a catch-up run in progress tests
|
|
894
|
+
// membership between handlers and stops as soon as it sees this
|
|
753
895
|
this.imqs = this.imqs.filter(imq => imqToRemove.redisKey !== imq.redisKey);
|
|
896
|
+
// not queued behind this host's other work: a queue wedged on a
|
|
897
|
+
// connection that never answers would then never be torn down at
|
|
898
|
+
// all, and teardown is the one operation that has to happen
|
|
899
|
+
// regardless of what the host is doing
|
|
754
900
|
imqToRemove
|
|
755
901
|
.destroy()
|
|
756
902
|
.catch((err) => this.verbose(`Error destroying removed server: ${err}`));
|
|
@@ -774,6 +920,9 @@ export class ClusteredRedisQueue {
|
|
|
774
920
|
* already matched
|
|
775
921
|
*/
|
|
776
922
|
addServerWithQueueInitializing(server, initializeQueue = true) {
|
|
923
|
+
if (this.closed) {
|
|
924
|
+
return { ...server, imq: undefined };
|
|
925
|
+
}
|
|
777
926
|
const existingServer = this.findServer(server);
|
|
778
927
|
if (existingServer) {
|
|
779
928
|
return existingServer;
|
|
@@ -793,17 +942,45 @@ export class ClusteredRedisQueue {
|
|
|
793
942
|
const opts = { ...this.mqOptions, ...newServer };
|
|
794
943
|
const imq = new RedisQueue(this.name, opts);
|
|
795
944
|
copyEventEmitter(this.templateEmitter, imq);
|
|
945
|
+
newServer.imq = imq;
|
|
946
|
+
// registered before the catch-up run starts, so that run can test
|
|
947
|
+
// membership against `imqs` and see the host it is working on. Nothing
|
|
948
|
+
// can observe the order: there is no await between here and the call
|
|
949
|
+
this.imqs.push(imq);
|
|
950
|
+
this.servers.push(newServer);
|
|
796
951
|
if (initializeQueue) {
|
|
797
|
-
|
|
952
|
+
// Lifecycle and subscription use separate connections: a stalled
|
|
953
|
+
// start must not hold up the host's subscription chain.
|
|
954
|
+
const started = this.startHost(imq);
|
|
955
|
+
const synced = this.syncHost(imq);
|
|
956
|
+
// Sends park on this event, so a host that only becomes usable
|
|
957
|
+
// after a retry has to reach it too, or they wait out their whole
|
|
958
|
+
// budget against a cluster that recovered. A host dropped while it
|
|
959
|
+
// was being brought up to date never became a member, and
|
|
960
|
+
// announcing it would release those sends onto a queue that is
|
|
961
|
+
// being destroyed. Exactly one of the two paths below reaches this:
|
|
962
|
+
// a join whose legs both succeeded, or a retry repairing a catch-up
|
|
963
|
+
// whose failure already rejected that join
|
|
964
|
+
const announce = () => {
|
|
965
|
+
if (!this.imqs.includes(imq)) {
|
|
966
|
+
return;
|
|
967
|
+
}
|
|
798
968
|
this.clusterEmitter.emit('initialized', {
|
|
799
969
|
server: newServer,
|
|
800
970
|
imq,
|
|
801
971
|
});
|
|
802
|
-
}
|
|
972
|
+
};
|
|
973
|
+
// only the subscription leg is retried. A failed start is already
|
|
974
|
+
// retryable through an explicit start(), and retrying it here would
|
|
975
|
+
// poll a connection object the reconnect path owns; a failed
|
|
976
|
+
// catch-up has no other route back
|
|
977
|
+
synced.catch(() => this.scheduleSync(imq, started, announce));
|
|
978
|
+
Promise.all([started, synced]).then(announce,
|
|
979
|
+
// reported inside the run; without a handler here a host that
|
|
980
|
+
// simply refuses a connection - routine - becomes an unhandled
|
|
981
|
+
// rejection, which is fatal on current node defaults
|
|
982
|
+
() => undefined);
|
|
803
983
|
}
|
|
804
|
-
newServer.imq = imq;
|
|
805
|
-
this.imqs.push(imq);
|
|
806
|
-
this.servers.push(newServer);
|
|
807
984
|
this.clusterEmitter.emit('add', { server: newServer, imq });
|
|
808
985
|
this.imqLength = this.imqs.length;
|
|
809
986
|
return newServer;
|
|
@@ -821,39 +998,212 @@ export class ClusteredRedisQueue {
|
|
|
821
998
|
return [...this.imqs, this.templateEmitter];
|
|
822
999
|
}
|
|
823
1000
|
/**
|
|
824
|
-
*
|
|
1001
|
+
* Appends one operation to a host's serialised queue.
|
|
825
1002
|
*
|
|
826
|
-
* @param imq - the queue to
|
|
1003
|
+
* @param imq - the queue the operation belongs to
|
|
1004
|
+
* @param operation - the work to run once everything before it has finished
|
|
1005
|
+
* @returns a promise for this operation alone, which rejects if it fails
|
|
827
1006
|
*
|
|
828
1007
|
* @remarks
|
|
829
|
-
*
|
|
830
|
-
*
|
|
831
|
-
*
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
1008
|
+
* Every `subscribe`, `unsubscribe` and catch-up run for a host goes through
|
|
1009
|
+
* here, so operations on one host never overlap, while different hosts stay
|
|
1010
|
+
* independent. The tail kept for the next operation is deliberately
|
|
1011
|
+
* repaired with a `catch`: chaining onto a rejected tail would make one
|
|
1012
|
+
* failed operation reject every operation the host is ever given again,
|
|
1013
|
+
* which is precisely the "host that silently stopped working" this class
|
|
1014
|
+
* has to avoid. The caller still receives the failure, through the returned
|
|
1015
|
+
* promise.
|
|
1016
|
+
*/
|
|
1017
|
+
enqueue(imq, operation) {
|
|
1018
|
+
const progress = this.progressOf(imq);
|
|
1019
|
+
const run = progress.chain.then(operation);
|
|
1020
|
+
progress.chain = run.catch(() => undefined);
|
|
1021
|
+
return run;
|
|
1022
|
+
}
|
|
1023
|
+
/**
|
|
1024
|
+
* Returns the progress record for a host, creating it on first use.
|
|
1025
|
+
*
|
|
1026
|
+
* @param imq - the queue to look up
|
|
1027
|
+
* @returns that host's progress record
|
|
1028
|
+
*/
|
|
1029
|
+
progressOf(imq) {
|
|
1030
|
+
let progress = this.progress.get(imq);
|
|
1031
|
+
if (!progress) {
|
|
1032
|
+
progress = {
|
|
1033
|
+
chain: Promise.resolve(),
|
|
1034
|
+
installed: 0,
|
|
1035
|
+
retryAttempts: 0,
|
|
1036
|
+
};
|
|
1037
|
+
this.progress.set(imq, progress);
|
|
1038
|
+
}
|
|
1039
|
+
return progress;
|
|
1040
|
+
}
|
|
1041
|
+
/**
|
|
1042
|
+
* Starts a joining host if it still belongs to a started cluster.
|
|
1043
|
+
* Subscription catch-up proceeds independently of this lifecycle operation.
|
|
1044
|
+
*/
|
|
1045
|
+
startHost(imq) {
|
|
1046
|
+
// initial eligibility is decided here, synchronously, and rechecked
|
|
1047
|
+
// again before starting: the
|
|
1048
|
+
// promise is cached the moment it is created, so a body that decides
|
|
1049
|
+
// later hands a caller arriving afterwards a settled promise whose
|
|
1050
|
+
// decision was made against state this caller has since changed. That
|
|
1051
|
+
// is how `cluster.start()` could join a run created while the cluster
|
|
1052
|
+
// was still stopped and never start the host at all
|
|
1053
|
+
if (!this.state.started || !this.imqs.includes(imq)) {
|
|
1054
|
+
return Promise.resolve();
|
|
1055
|
+
}
|
|
1056
|
+
const pending = this.starting.get(imq);
|
|
1057
|
+
if (pending) {
|
|
1058
|
+
return pending;
|
|
1059
|
+
}
|
|
1060
|
+
const run = Promise.resolve()
|
|
1061
|
+
.then(async () => {
|
|
1062
|
+
// rechecked here as well as synchronously above: a stop() can
|
|
1063
|
+
// land between creating this run and the microtask that runs
|
|
1064
|
+
// it, and starting a host the cluster has just stopped leaves
|
|
1065
|
+
// the cluster stopped with a host running
|
|
1066
|
+
if (this.state.started && this.imqs.includes(imq)) {
|
|
1067
|
+
try {
|
|
1068
|
+
await imq.start();
|
|
1069
|
+
}
|
|
1070
|
+
catch (err) {
|
|
1071
|
+
this.logLine('error', `server ${imq.redisKey} failed to start, code ` +
|
|
1072
|
+
`${errorCode(err)}: the node is not ready to serve queues`);
|
|
1073
|
+
throw err;
|
|
1074
|
+
}
|
|
842
1075
|
}
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
1076
|
+
})
|
|
1077
|
+
.finally(() => {
|
|
1078
|
+
this.starting.delete(imq);
|
|
1079
|
+
});
|
|
1080
|
+
this.starting.set(imq, run);
|
|
1081
|
+
return run;
|
|
1082
|
+
}
|
|
1083
|
+
/**
|
|
1084
|
+
* Retries a host's subscription catch-up until it succeeds, the host leaves
|
|
1085
|
+
* the cluster, or the cluster is destroyed.
|
|
1086
|
+
*
|
|
1087
|
+
* @param imq - the queue whose catch-up failed
|
|
1088
|
+
* @param started - the joining host's startup, which the announcement waits
|
|
1089
|
+
* for. A live registration has nothing to announce and omits it
|
|
1090
|
+
* @param announce - emits `initialized` for a joining host that only became
|
|
1091
|
+
* usable through this retry. Omitted by a live registration, whose
|
|
1092
|
+
* host is already a member that sends are routed to
|
|
1093
|
+
*
|
|
1094
|
+
* @remarks
|
|
1095
|
+
* Both routes to a first subscribe end here: a joining host's catch-up, and
|
|
1096
|
+
* a live registration on a host that is already a member, which is the only
|
|
1097
|
+
* route a statically configured cluster ever takes.
|
|
1098
|
+
*
|
|
1099
|
+
* A host whose first {@link RedisQueue.subscribe} rejects records
|
|
1100
|
+
* nothing: `subscriptionHandlers` stays empty, so the connection layer's
|
|
1101
|
+
* own reconnect has nothing to replay and restores a socket subscribed to
|
|
1102
|
+
* no channel. Without this, that host never receives another installation —
|
|
1103
|
+
* `start()` fans out startup only, a re-announced address is recognised as a
|
|
1104
|
+
* known server and skipped, and a service that subscribes once at boot never
|
|
1105
|
+
* registers again. The host stays a silent member for the life of the
|
|
1106
|
+
* process while every probe it answers reports health.
|
|
1107
|
+
*
|
|
1108
|
+
* Retrying is safe because catch-up is idempotent: {@link
|
|
1109
|
+
* ClusteredRedisQueue.syncHost} reads the cluster-owned installed count
|
|
1110
|
+
* inside the per-host chain and installs only the missing suffix, so a retry
|
|
1111
|
+
* cannot duplicate a handler that did land. The backoff mirrors the
|
|
1112
|
+
* connection layer's, which this has to outlive.
|
|
1113
|
+
*/
|
|
1114
|
+
scheduleSync(imq, started = Promise.resolve(), announce = () => undefined) {
|
|
1115
|
+
if (this.closed || !this.imqs.includes(imq)) {
|
|
1116
|
+
return;
|
|
1117
|
+
}
|
|
1118
|
+
const progress = this.progressOf(imq);
|
|
1119
|
+
if (progress.retryTimer) {
|
|
1120
|
+
return;
|
|
1121
|
+
}
|
|
1122
|
+
const attempts = progress.retryAttempts + 1;
|
|
1123
|
+
const delay = Math.min(SYNC_RETRY_MAX_DELAY, SYNC_RETRY_BASE_DELAY * 2 ** (attempts - 1));
|
|
1124
|
+
progress.retryAttempts = attempts;
|
|
1125
|
+
const timer = setTimeout(() => {
|
|
1126
|
+
progress.retryTimer = undefined;
|
|
1127
|
+
if (this.closed || !this.imqs.includes(imq)) {
|
|
1128
|
+
return;
|
|
846
1129
|
}
|
|
1130
|
+
this.syncHost(imq).then(() => {
|
|
1131
|
+
progress.retryAttempts = 0;
|
|
1132
|
+
// the host is only usable once its lifecycle came up too
|
|
1133
|
+
started.then(announce, () => undefined);
|
|
1134
|
+
}, () => this.scheduleSync(imq, started, announce));
|
|
1135
|
+
}, delay);
|
|
1136
|
+
// a host that never comes back must not hold the process open
|
|
1137
|
+
timer.unref?.();
|
|
1138
|
+
progress.retryTimer = timer;
|
|
1139
|
+
}
|
|
1140
|
+
/**
|
|
1141
|
+
* Cancels a pending catch-up retry for a host being torn down.
|
|
1142
|
+
*
|
|
1143
|
+
* @param imq - the queue leaving the cluster
|
|
1144
|
+
*/
|
|
1145
|
+
cancelSync(imq) {
|
|
1146
|
+
const progress = this.progress.get(imq);
|
|
1147
|
+
if (progress?.retryTimer) {
|
|
1148
|
+
clearTimeout(progress.retryTimer);
|
|
1149
|
+
progress.retryTimer = undefined;
|
|
847
1150
|
}
|
|
848
|
-
|
|
1151
|
+
}
|
|
1152
|
+
/**
|
|
1153
|
+
* Installs registrations this cluster has not yet installed on a host.
|
|
1154
|
+
*
|
|
1155
|
+
* @param imq - the queue to bring up to date
|
|
1156
|
+
* @returns this run's completion, rejecting on a failed installation
|
|
1157
|
+
*
|
|
1158
|
+
* @remarks
|
|
1159
|
+
* Both live registrations and joining hosts use the same serialised path.
|
|
1160
|
+
* Each run reads the cluster-owned count inside the chain, so repeating it adds
|
|
1161
|
+
* nothing. A queued teardown may erase a temporary installation; the run
|
|
1162
|
+
* behind that teardown will then see and install the missing suffix again.
|
|
1163
|
+
*/
|
|
1164
|
+
syncHost(imq) {
|
|
1165
|
+
return this.enqueue(imq, async () => {
|
|
1166
|
+
const progress = this.progressOf(imq);
|
|
1167
|
+
const channel = this.state.channel;
|
|
1168
|
+
if (!channel) {
|
|
1169
|
+
return;
|
|
1170
|
+
}
|
|
1171
|
+
let installed = 0;
|
|
849
1172
|
try {
|
|
850
|
-
|
|
1173
|
+
for (let i = progress.installed; i < this.state.handlers.length; i++) {
|
|
1174
|
+
if (!this.imqs.includes(imq)) {
|
|
1175
|
+
return;
|
|
1176
|
+
}
|
|
1177
|
+
if (this.state.channel !== channel) {
|
|
1178
|
+
return;
|
|
1179
|
+
}
|
|
1180
|
+
await imq.subscribe(channel, this.state.handlers[i]);
|
|
1181
|
+
// rechecked after the await: teardown bypasses this chain,
|
|
1182
|
+
// so the host can have been removed or destroyed while the
|
|
1183
|
+
// subscribe was in flight. Recording it would leave the
|
|
1184
|
+
// counter claiming an install on a queue that is gone, and
|
|
1185
|
+
// the handler it just attached is torn down with the host
|
|
1186
|
+
if (!this.imqs.includes(imq)) {
|
|
1187
|
+
return;
|
|
1188
|
+
}
|
|
1189
|
+
progress.installed = i + 1;
|
|
1190
|
+
installed++;
|
|
1191
|
+
}
|
|
851
1192
|
}
|
|
852
1193
|
catch (err) {
|
|
853
|
-
this.logLine('error', `server ${imq.redisKey} failed to subscribe to channel
|
|
1194
|
+
this.logLine('error', `server ${imq.redisKey} failed to subscribe to channel ` +
|
|
1195
|
+
`${channel}, code ${errorCode(err)}: some handlers remain ` +
|
|
1196
|
+
'uninstalled until the retry the cluster schedules for ' +
|
|
1197
|
+
'this host succeeds');
|
|
854
1198
|
throw err;
|
|
855
1199
|
}
|
|
856
|
-
|
|
1200
|
+
finally {
|
|
1201
|
+
if (installed) {
|
|
1202
|
+
this.logLine('info', `server ${imq.redisKey} installed ${installed} handler(s) ` +
|
|
1203
|
+
`for channel ${channel}`);
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
});
|
|
857
1207
|
}
|
|
858
1208
|
/**
|
|
859
1209
|
* Finds an already-registered server matching the given one.
|
package/src/RedisQueue.js
CHANGED
|
@@ -630,6 +630,12 @@ let RedisQueue = (() => {
|
|
|
630
630
|
}
|
|
631
631
|
const fcn = `${this.options.prefix}:${this.subscriptionName}`;
|
|
632
632
|
await chan.subscribe(fcn);
|
|
633
|
+
// Reconcile rather than append. connect() binds a connection before it
|
|
634
|
+
// awaits it and hands that same object to any concurrent caller, so a
|
|
635
|
+
// subscribe() racing a reconnect can attach a handler to this very
|
|
636
|
+
// connection before this runs. Appending there would leave the socket
|
|
637
|
+
// carrying the handler twice and deliver every message twice.
|
|
638
|
+
chan.removeAllListeners('message');
|
|
633
639
|
for (const handler of this.subscriptionHandlers) {
|
|
634
640
|
this.attachSubscriptionHandler(chan, handler);
|
|
635
641
|
}
|