@imqueue/core 3.5.1 → 3.5.2

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
@@ -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,48 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
111
157
 
112
158
  ### Fixed
113
159
 
160
+ - **A clustered queue gave a server that joined later only the last-registered
161
+ subscription handler, silencing every other handler on that host.**
162
+ `ClusteredRedisQueue` remembered one `{ channel, handler }` pair, so each
163
+ `subscribe()` overwrote the previous one. Handlers were still forwarded to the
164
+ hosts already known, which is why this stayed invisible while cluster
165
+ membership was stable — but a host added afterwards (a broker replaced, or
166
+ discovery completing after the calls at start-up) was subscribed with the
167
+ **last** handler alone. With one handler carrying business events and another
168
+ carrying cache invalidation, a host could serve the second and silently drop
169
+ the first: the socket stays subscribed, the publisher still sees a subscriber
170
+ and RPC is unaffected, so nothing surfaces the loss.
171
+
172
+ Every registration is now remembered and installed, in registration order,
173
+ including the same function registered twice — `subscribe()` remains additive
174
+ as documented.
175
+
176
+ Live registration and joining-host catch-up share a serialised operation per
177
+ host. Each run reads a cluster-owned per-host installation count and installs
178
+ the remaining registrations, advancing only after success. Direct host
179
+ registrations do not count towards cluster progress. Cluster unsubscribe
180
+ resets that count inside the same chain, including after a rejected teardown.
181
+ Overlapping runs do not duplicate a cluster registration within an
182
+ uninterrupted subscription. This is not an unconditional exactly-once delivery
183
+ guarantee: deliberate repeated registrations still invoke twice, publication
184
+ across hosts can deliver more than once, and unsubscribe/replacement can cause
185
+ a temporary installation that teardown removes before catch-up reinstalls it.
186
+
187
+ A host dropped mid-catch-up receives no further installations and is not
188
+ announced as initialized. Two kinds of `info` line report the ordinal and
189
+ channel of each registration, and how many handlers a catch-up run installed. The verbose
190
+ `Initializing queue with state` line has been removed.
191
+
192
+ - **A server that failed to start while joining could take the process down.**
193
+ Its background initialization now observes rejection, preventing an unhandled
194
+ rejection and process exit. Startup and subscription catch-up run independently:
195
+ a failed or stalled start does not block pub/sub, preserving the documented
196
+ ability to subscribe without start(). Joining hosts still start automatically
197
+ in a started cluster; later subscribe() calls do not retry startup. Deferred
198
+ joining-host startup and cluster start() share pending startup per host, so
199
+ they cannot start that host concurrently. Settled startup is released so an
200
+ explicit later start() can retry.
201
+
114
202
  - **A failed connection could crash the process as it was being torn down.**
115
203
  The redis client guards its socket with a one-shot `error` listener, which
116
204
  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.1",
3
+ "version": "3.5.2",
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
- * Every fan-out uses `Promise.all`, so one failing host fails the whole call with
54
- * no partial-failure reporting and no rollback.
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; {@link ClusteredRedisQueue.initializeQueue} replays
138
- * them onto each new queue.
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 — then unregisters this cluster from all configured
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
- * The instance must not be reused afterwards: internal routing state is not
254
- * cleared, so a subsequent {@link ClusteredRedisQueue.send} would silently
255
- * re-open a connection.
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,47 @@ 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 a different channel name is supplied while a
503
- * subscription is already open on the underlying queues
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 the handler a second time; calling it with a
508
- * different channel rejects — and the remembered subscription is left
509
- * pointing at the rejected name, which is what newly joining servers would
510
- * then use.
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.
511
563
  *
512
564
  * The handler receives one invocation per host that delivers the message.
513
565
  */
514
566
  subscribe(channel: string, handler: (data: JsonObject) => void): Promise<void>;
515
567
  /**
516
- * Unsubscribes from the channel on every redis host and forgets the
517
- * remembered subscription, so servers joining later are no longer subscribed
568
+ * Unsubscribes from the channel on every redis host and forgets every
569
+ * remembered handler, so servers joining later are no longer subscribed
518
570
  * automatically.
519
571
  *
520
572
  * @remarks
521
573
  * Resolves without effect on an empty cluster.
574
+ *
575
+ * Clears the remembered channel and handlers immediately, then queues each
576
+ * host's teardown behind its current subscription work. A stalled operation
577
+ * on that host therefore also stalls unsubscribe(). Later catch-up reads the
578
+ * cluster's installation count after teardown, even if an earlier run
579
+ * temporarily installed handlers from the replacement list.
522
580
  */
523
581
  unsubscribe(): Promise<void>;
524
582
  /**
@@ -538,7 +596,8 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
538
596
  *
539
597
  * For a genuinely new server this returns as soon as the record is created —
540
598
  * starting the queue and re-applying any active subscription happen
541
- * asynchronously afterwards.
599
+ * asynchronously afterwards. Once destroy() begins, discovery is ignored:
600
+ * the returned address has no queue and is not admitted to membership.
542
601
  */
543
602
  protected addServer(server: IServerInput): ClusterServer;
544
603
  /**
@@ -579,16 +638,48 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
579
638
  */
580
639
  private eventEmitters;
581
640
  /**
582
- * Brings a newly created per-host queue up to the cluster's current state.
641
+ * Appends one operation to a host's serialised queue.
642
+ *
643
+ * @param imq - the queue the operation belongs to
644
+ * @param operation - the work to run once everything before it has finished
645
+ * @returns a promise for this operation alone, which rejects if it fails
646
+ *
647
+ * @remarks
648
+ * Every `subscribe`, `unsubscribe` and catch-up run for a host goes through
649
+ * here, so operations on one host never overlap, while different hosts stay
650
+ * independent. The tail kept for the next operation is deliberately
651
+ * repaired with a `catch`: chaining onto a rejected tail would make one
652
+ * failed operation reject every operation the host is ever given again,
653
+ * which is precisely the "host that silently stopped working" this class
654
+ * has to avoid. The caller still receives the failure, through the returned
655
+ * promise.
656
+ */
657
+ private enqueue;
658
+ /**
659
+ * Returns the progress record for a host, creating it on first use.
660
+ *
661
+ * @param imq - the queue to look up
662
+ * @returns that host's progress record
663
+ */
664
+ private progressOf;
665
+ /**
666
+ * Starts a joining host if it still belongs to a started cluster.
667
+ * Subscription catch-up proceeds independently of this lifecycle operation.
668
+ */
669
+ private startHost;
670
+ /**
671
+ * Installs registrations this cluster has not yet installed on a host.
583
672
  *
584
- * @param imq - the queue to initialize
673
+ * @param imq - the queue to bring up to date
674
+ * @returns this run's completion, rejecting on a failed installation
585
675
  *
586
676
  * @remarks
587
- * Replays whatever {@link ClusteredRedisQueue.state} records, so a server
588
- * that joins after the cluster started is started and subscribed too rather
589
- * than sitting idle.
677
+ * Both live registrations and joining hosts use the same serialised path.
678
+ * Each run reads the cluster-owned count inside the chain, so repeating it adds
679
+ * nothing. A queued teardown may erase a temporary installation; the run
680
+ * behind that teardown will then see and install the missing suffix again.
590
681
  */
591
- private initializeQueue;
682
+ private syncHost;
592
683
  /**
593
684
  * Finds an already-registered server matching the given one.
594
685
  *
@@ -44,8 +44,8 @@ const SEND_INIT_TIMEOUT = +(process.env.IMQ_SEND_INIT_TIMEOUT || 0) || 30000;
44
44
  * `clear`, `destroy`, `publish`, `subscribe`, `unsubscribe` and `queueLength` —
45
45
  * fans out to every server.
46
46
  *
47
- * Every fan-out uses `Promise.all`, so one failing host fails the whole call with
48
- * no partial-failure reporting and no rollback.
47
+ * Fan-out normally uses `Promise.all`, with no rollback on failure. Destroy
48
+ * attempts every cleanup task and reports failures together in an AggregateError.
49
49
  *
50
50
  * The class only `implements` the `EventEmitter` interface rather than extending
51
51
  * it, so `instanceof EventEmitter` is false and every emitter method is a
@@ -119,13 +119,34 @@ export class ClusteredRedisQueue {
119
119
  * @remarks
120
120
  * Cluster membership changes at runtime, so a per-host queue may be created
121
121
  * long after `start()` and `subscribe()` were called on the cluster. This
122
- * records those calls; {@link ClusteredRedisQueue.initializeQueue} replays
123
- * them onto each new queue.
122
+ * records those calls; joining hosts replay startup and subscription
123
+ * catch-up independently.
124
124
  */
125
125
  state = {
126
126
  started: false,
127
- subscription: null,
127
+ channel: null,
128
+ handlers: [],
128
129
  };
130
+ /**
131
+ * Tracks this cluster's successful installations, independently of handlers
132
+ * registered directly on a host. Teardown resets the installation count.
133
+ */
134
+ progress = new WeakMap();
135
+ /**
136
+ * Sends parked in {@link ClusteredRedisQueue.sendWhenInitialized}, waiting
137
+ * for a server to appear. Kept so {@link ClusteredRedisQueue.destroy} can
138
+ * settle them at once rather than leaving each to time out against a
139
+ * cluster that can no longer admit a server.
140
+ */
141
+ waitingSends = new Set();
142
+ /** Pending startup shared by batch startup and joining-host initialization. */
143
+ starting = new WeakMap();
144
+ /** Membership admission stays closed after the first destroy() call. */
145
+ closed = false;
146
+ /** Failed cleanup tasks remain here for an explicit destroy() retry. */
147
+ cleanup = new Set();
148
+ /** Teardown shared by concurrent destroy() callers. */
149
+ destroying;
129
150
  /**
130
151
  * Handles for the cluster managers this queue is registered with, kept so
131
152
  * that {@link ClusteredRedisQueue.destroy} can deregister from each.
@@ -247,6 +268,13 @@ export class ClusteredRedisQueue {
247
268
  * milliseconds).
248
269
  */
249
270
  async send(toQueue, message, delay, errorHandler) {
271
+ if (this.closed) {
272
+ // admission is closed, so no server can ever arrive: waiting out
273
+ // the initialisation timeout would stall a shutdown path for
274
+ // IMQ_SEND_INIT_TIMEOUT on a timer that is not unref()'d
275
+ throw new TypeError('ClusteredRedisQueue: the queue was destroyed and cannot be ' +
276
+ 'reused, so this message has nowhere to go!');
277
+ }
250
278
  if (!this.imqLength) {
251
279
  return this.sendWhenInitialized(toQueue, message, delay, errorHandler);
252
280
  }
@@ -292,40 +320,92 @@ export class ClusteredRedisQueue {
292
320
  return new Promise((resolve, reject) => {
293
321
  const onInitialized = ({ imq }) => {
294
322
  clearTimeout(timer);
323
+ this.waitingSends.delete(giveUp);
295
324
  imq.send(toQueue, message, delay, errorHandler).then(resolve, reject);
296
325
  };
297
- const timer = setTimeout(() => {
326
+ const giveUp = (reason) => {
327
+ clearTimeout(timer);
298
328
  this.clusterEmitter.removeListener('initialized', onInitialized);
299
- reject(new Error('ClusteredRedisQueue: no cluster server became ' +
300
- 'available to send the message'));
301
- }, this.sendInitTimeout);
329
+ this.waitingSends.delete(giveUp);
330
+ reject(reason);
331
+ };
332
+ const timer = setTimeout(() => giveUp(new Error('ClusteredRedisQueue: no cluster server became ' +
333
+ 'available to send the message')), this.sendInitTimeout);
334
+ // registered so destroy() can settle this immediately: once
335
+ // admission is closed no server can ever initialise, and waiting
336
+ // out the timeout would hold the event loop open on a shutdown
337
+ this.waitingSends.add(giveUp);
302
338
  this.clusterEmitter.once('initialized', onInitialized);
303
339
  });
304
340
  }
305
341
  /**
306
342
  * Destroys every server's queue — closing their connections and removing
307
- * their event listeners — then unregisters this cluster from all configured
343
+ * their event listeners — and unregisters this cluster from all configured
308
344
  * cluster managers.
309
345
  *
310
346
  * @remarks
311
347
  * Unregistering shuts a manager down entirely once it has no clusters left,
312
348
  * which for {@link UDPClusterManager} also terminates its shared UDP worker.
313
349
  *
314
- * The instance must not be reused afterwards: internal routing state is not
315
- * cleared, so a subsequent {@link ClusteredRedisQueue.send} would silently
316
- * re-open a connection.
350
+ * Routing membership and remembered subscriptions are cleared synchronously,
351
+ * so queued subscription work cannot reopen a destroyed host. Teardown does
352
+ * not wait for the subscription chain; concurrent callers await the same
353
+ * teardown, including manager removal. Every independent cleanup is attempted;
354
+ * failures are reported together in an AggregateError. A later destroy()
355
+ * retries only failed tasks; successful tasks are not repeated. Membership
356
+ * admission stays closed, including during retries. The instance must not
357
+ * be reused.
317
358
  */
318
359
  async destroy() {
319
- this.state.started = false;
320
- await this.batch('destroy', 'Destroying clustered redis message queue...');
321
- if (!this.options.clusterManagers?.length) {
322
- return;
360
+ if (this.destroying) {
361
+ return this.destroying;
323
362
  }
324
- for (const manager of this.options.clusterManagers) {
325
- for (const cluster of this.initializedClusters) {
326
- await manager.remove(cluster);
363
+ if (!this.closed) {
364
+ this.closed = true;
365
+ this.state.started = false;
366
+ for (const imq of this.imqs) {
367
+ this.cleanup.add(() => imq.destroy());
368
+ }
369
+ for (const manager of this.options.clusterManagers || []) {
370
+ for (const cluster of this.initializedClusters) {
371
+ this.cleanup.add(() => manager.remove(cluster));
372
+ }
373
+ }
374
+ // Close routing before queued subscription or startup work can run.
375
+ // Teardown bypasses those chains so a stalled install cannot block it.
376
+ this.imqs = [];
377
+ this.servers = [];
378
+ this.imqLength = 0;
379
+ this.state.channel = null;
380
+ this.state.handlers = [];
381
+ // a send parked waiting for a server can never be satisfied once
382
+ // admission is closed, and its timer is referenced, so leaving it
383
+ // to expire holds the event loop open for the whole timeout
384
+ const parked = Array.from(this.waitingSends);
385
+ this.waitingSends.clear();
386
+ for (const giveUp of parked) {
387
+ giveUp(new Error('ClusteredRedisQueue: the queue was destroyed before ' +
388
+ 'a cluster server became available'));
327
389
  }
328
390
  }
391
+ this.destroying = Promise.resolve()
392
+ .then(async () => {
393
+ this.logLine('info', 'Destroying clustered redis message queue...');
394
+ const results = await Promise.allSettled([...this.cleanup].map(async (operation) => {
395
+ await operation();
396
+ this.cleanup.delete(operation);
397
+ }));
398
+ const errors = results
399
+ .filter(result => result.status === 'rejected')
400
+ .map(result => result.reason);
401
+ if (errors.length) {
402
+ throw new AggregateError(errors, 'Cluster teardown failed');
403
+ }
404
+ })
405
+ .finally(() => {
406
+ this.destroying = undefined;
407
+ });
408
+ return this.destroying;
329
409
  }
330
410
  /**
331
411
  * Deletes this queue's data on every redis host in the cluster,
@@ -396,8 +476,7 @@ export class ClusteredRedisQueue {
396
476
  this.logger.info(message);
397
477
  const promises = [];
398
478
  for (const imq of this.imqs) {
399
- const run = imq[action];
400
- promises.push(run.call(imq));
479
+ promises.push(action === 'start' ? this.startHost(imq) : imq[action]());
401
480
  }
402
481
  await Promise.all(promises);
403
482
  return this;
@@ -669,41 +748,75 @@ export class ClusteredRedisQueue {
669
748
  *
670
749
  * @param channel - channel name within the queue's prefix namespace
671
750
  * @param handler - invoked with the parsed payload of each published message
672
- * @throws TypeError when a different channel name is supplied while a
673
- * subscription is already open on the underlying queues
751
+ * @throws TypeError when no channel name is given, or when a different
752
+ * channel name is supplied while this instance already remembers
753
+ * one - both are raised here, so they fire on an empty cluster too,
754
+ * where there is no underlying queue to raise them
674
755
  *
675
756
  * @remarks
676
757
  * Only one channel per instance is supported. Calling this again with the
677
- * same channel registers the handler a second time; calling it with a
678
- * different channel rejects — and the remembered subscription is left
679
- * pointing at the rejected name, which is what newly joining servers would
680
- * then use.
758
+ * same channel registers an additional handler — every registration is
759
+ * remembered and all of them are invoked, including the same function
760
+ * registered twice. Calling it with a different channel throws before any
761
+ * state is touched, so the remembered channel keeps naming the channel that
762
+ * is actually subscribed.
763
+ *
764
+ * Servers joining later are given every handler registered before they
765
+ * joined, in registration order.
766
+ *
767
+ * Subscription uses its own connection and does not require start(), even
768
+ * when a host's startup fails or stalls. Subscription changes serialise per
769
+ * host, so a call can wait behind an earlier operation that never settles.
770
+ *
771
+ * A rejected call is not retryable: its registration remains remembered and
772
+ * may already be installed on some hosts. Calling again adds another copy,
773
+ * including for future hosts. To rebuild a known registration set, await
774
+ * unsubscribe() and then register the desired handlers again.
681
775
  *
682
776
  * The handler receives one invocation per host that delivers the message.
683
777
  */
684
778
  async subscribe(channel, handler) {
685
- this.state.subscription = { channel, handler };
686
- const promises = [];
687
- for (const imq of this.imqs) {
688
- promises.push(imq.subscribe(channel, handler));
779
+ if (this.closed) {
780
+ throw new TypeError('ClusteredRedisQueue: the queue was destroyed and cannot be ' +
781
+ 'reused, so this subscription would never reach a server!');
689
782
  }
690
- await Promise.all(promises);
783
+ if (!channel) {
784
+ throw new TypeError(`${channel}: No subscription channel name provided!`);
785
+ }
786
+ if (this.state.channel && this.state.channel !== channel) {
787
+ throw new TypeError(`Invalid channel name provided: expected "${this.state.channel}", but "${channel}" given instead!`);
788
+ }
789
+ this.state.channel = channel;
790
+ this.state.handlers.push(handler);
791
+ this.logLine('info', `registered handler #${this.state.handlers.length} for channel ` +
792
+ `${channel}`);
793
+ await Promise.all(this.imqs.map(imq => this.syncHost(imq)));
691
794
  }
692
795
  /**
693
- * Unsubscribes from the channel on every redis host and forgets the
694
- * remembered subscription, so servers joining later are no longer subscribed
796
+ * Unsubscribes from the channel on every redis host and forgets every
797
+ * remembered handler, so servers joining later are no longer subscribed
695
798
  * automatically.
696
799
  *
697
800
  * @remarks
698
801
  * Resolves without effect on an empty cluster.
802
+ *
803
+ * Clears the remembered channel and handlers immediately, then queues each
804
+ * host's teardown behind its current subscription work. A stalled operation
805
+ * on that host therefore also stalls unsubscribe(). Later catch-up reads the
806
+ * cluster's installation count after teardown, even if an earlier run
807
+ * temporarily installed handlers from the replacement list.
699
808
  */
700
809
  async unsubscribe() {
701
- this.state.subscription = null;
702
- const promises = [];
703
- for (const imq of this.imqs) {
704
- promises.push(imq.unsubscribe());
705
- }
706
- await Promise.all(promises);
810
+ this.state.channel = null;
811
+ this.state.handlers = [];
812
+ await Promise.all(this.imqs.map(imq => this.enqueue(imq, async () => {
813
+ try {
814
+ await imq.unsubscribe();
815
+ }
816
+ finally {
817
+ this.progressOf(imq).installed = 0;
818
+ }
819
+ })));
707
820
  }
708
821
  /**
709
822
  * Adds a single server to the cluster and returns its registration record.
@@ -722,7 +835,8 @@ export class ClusteredRedisQueue {
722
835
  *
723
836
  * For a genuinely new server this returns as soon as the record is created —
724
837
  * starting the queue and re-applying any active subscription happen
725
- * asynchronously afterwards.
838
+ * asynchronously afterwards. Once destroy() begins, discovery is ignored:
839
+ * the returned address has no queue and is not admitted to membership.
726
840
  */
727
841
  addServer(server) {
728
842
  this.verbose(`Adding new server: ${JSON.stringify(server)}`);
@@ -750,7 +864,13 @@ export class ClusteredRedisQueue {
750
864
  }
751
865
  const imqToRemove = remove.imq;
752
866
  if (imqToRemove) {
867
+ // dropped from routing first: a catch-up run in progress tests
868
+ // membership between handlers and stops as soon as it sees this
753
869
  this.imqs = this.imqs.filter(imq => imqToRemove.redisKey !== imq.redisKey);
870
+ // not queued behind this host's other work: a queue wedged on a
871
+ // connection that never answers would then never be torn down at
872
+ // all, and teardown is the one operation that has to happen
873
+ // regardless of what the host is doing
754
874
  imqToRemove
755
875
  .destroy()
756
876
  .catch((err) => this.verbose(`Error destroying removed server: ${err}`));
@@ -774,6 +894,9 @@ export class ClusteredRedisQueue {
774
894
  * already matched
775
895
  */
776
896
  addServerWithQueueInitializing(server, initializeQueue = true) {
897
+ if (this.closed) {
898
+ return { ...server, imq: undefined };
899
+ }
777
900
  const existingServer = this.findServer(server);
778
901
  if (existingServer) {
779
902
  return existingServer;
@@ -793,17 +916,33 @@ export class ClusteredRedisQueue {
793
916
  const opts = { ...this.mqOptions, ...newServer };
794
917
  const imq = new RedisQueue(this.name, opts);
795
918
  copyEventEmitter(this.templateEmitter, imq);
919
+ newServer.imq = imq;
920
+ // registered before the catch-up run starts, so that run can test
921
+ // membership against `imqs` and see the host it is working on. Nothing
922
+ // can observe the order: there is no await between here and the call
923
+ this.imqs.push(imq);
924
+ this.servers.push(newServer);
796
925
  if (initializeQueue) {
797
- this.initializeQueue(imq).then(() => {
926
+ // Lifecycle and subscription use separate connections: a stalled
927
+ // start must not hold up the host's subscription chain.
928
+ Promise.all([this.startHost(imq), this.syncHost(imq)]).then(() => {
929
+ // a host dropped while it was being brought up to date
930
+ // never became a member, and announcing it would release a
931
+ // send that is waiting for a usable server onto a queue
932
+ // that is being destroyed
933
+ if (!this.imqs.includes(imq)) {
934
+ return;
935
+ }
798
936
  this.clusterEmitter.emit('initialized', {
799
937
  server: newServer,
800
938
  imq,
801
939
  });
802
- });
940
+ },
941
+ // reported inside the run; without a handler here a host that
942
+ // simply refuses a connection - routine - becomes an unhandled
943
+ // rejection, which is fatal on current node defaults
944
+ () => undefined);
803
945
  }
804
- newServer.imq = imq;
805
- this.imqs.push(imq);
806
- this.servers.push(newServer);
807
946
  this.clusterEmitter.emit('add', { server: newServer, imq });
808
947
  this.imqLength = this.imqs.length;
809
948
  return newServer;
@@ -821,39 +960,141 @@ export class ClusteredRedisQueue {
821
960
  return [...this.imqs, this.templateEmitter];
822
961
  }
823
962
  /**
824
- * Brings a newly created per-host queue up to the cluster's current state.
963
+ * Appends one operation to a host's serialised queue.
825
964
  *
826
- * @param imq - the queue to initialize
965
+ * @param imq - the queue the operation belongs to
966
+ * @param operation - the work to run once everything before it has finished
967
+ * @returns a promise for this operation alone, which rejects if it fails
827
968
  *
828
969
  * @remarks
829
- * Replays whatever {@link ClusteredRedisQueue.state} records, so a server
830
- * that joins after the cluster started is started and subscribed too rather
831
- * than sitting idle.
832
- */
833
- async initializeQueue(imq) {
834
- this.verbose(`Initializing queue with state: ${JSON.stringify(this.state)}`);
835
- // both failures are reported here, inside the function, and the
836
- // value is re-thrown as it was: the caller starts this without
837
- // awaiting it, so a new .catch() would either swallow the failure or
838
- // add a second unhandled rejection
839
- if (this.state.started) {
840
- try {
841
- await imq.start();
970
+ * Every `subscribe`, `unsubscribe` and catch-up run for a host goes through
971
+ * here, so operations on one host never overlap, while different hosts stay
972
+ * independent. The tail kept for the next operation is deliberately
973
+ * repaired with a `catch`: chaining onto a rejected tail would make one
974
+ * failed operation reject every operation the host is ever given again,
975
+ * which is precisely the "host that silently stopped working" this class
976
+ * has to avoid. The caller still receives the failure, through the returned
977
+ * promise.
978
+ */
979
+ enqueue(imq, operation) {
980
+ const progress = this.progressOf(imq);
981
+ const run = progress.chain.then(operation);
982
+ progress.chain = run.catch(() => undefined);
983
+ return run;
984
+ }
985
+ /**
986
+ * Returns the progress record for a host, creating it on first use.
987
+ *
988
+ * @param imq - the queue to look up
989
+ * @returns that host's progress record
990
+ */
991
+ progressOf(imq) {
992
+ let progress = this.progress.get(imq);
993
+ if (!progress) {
994
+ progress = {
995
+ chain: Promise.resolve(),
996
+ installed: 0,
997
+ };
998
+ this.progress.set(imq, progress);
999
+ }
1000
+ return progress;
1001
+ }
1002
+ /**
1003
+ * Starts a joining host if it still belongs to a started cluster.
1004
+ * Subscription catch-up proceeds independently of this lifecycle operation.
1005
+ */
1006
+ startHost(imq) {
1007
+ // initial eligibility is decided here, synchronously, and rechecked
1008
+ // again before starting: the
1009
+ // promise is cached the moment it is created, so a body that decides
1010
+ // later hands a caller arriving afterwards a settled promise whose
1011
+ // decision was made against state this caller has since changed. That
1012
+ // is how `cluster.start()` could join a run created while the cluster
1013
+ // was still stopped and never start the host at all
1014
+ if (!this.state.started || !this.imqs.includes(imq)) {
1015
+ return Promise.resolve();
1016
+ }
1017
+ const pending = this.starting.get(imq);
1018
+ if (pending) {
1019
+ return pending;
1020
+ }
1021
+ const run = Promise.resolve()
1022
+ .then(async () => {
1023
+ // rechecked here as well as synchronously above: a stop() can
1024
+ // land between creating this run and the microtask that runs
1025
+ // it, and starting a host the cluster has just stopped leaves
1026
+ // the cluster stopped with a host running
1027
+ if (this.state.started && this.imqs.includes(imq)) {
1028
+ try {
1029
+ await imq.start();
1030
+ }
1031
+ catch (err) {
1032
+ this.logLine('error', `server ${imq.redisKey} failed to start, code ` +
1033
+ `${errorCode(err)}: the node is not ready to serve queues`);
1034
+ throw err;
1035
+ }
842
1036
  }
843
- catch (err) {
844
- this.logLine('error', `server ${imq.redisKey} failed to start, code ${errorCode(err)}: the node is not ready to serve queues`);
845
- throw err;
1037
+ })
1038
+ .finally(() => {
1039
+ this.starting.delete(imq);
1040
+ });
1041
+ this.starting.set(imq, run);
1042
+ return run;
1043
+ }
1044
+ /**
1045
+ * Installs registrations this cluster has not yet installed on a host.
1046
+ *
1047
+ * @param imq - the queue to bring up to date
1048
+ * @returns this run's completion, rejecting on a failed installation
1049
+ *
1050
+ * @remarks
1051
+ * Both live registrations and joining hosts use the same serialised path.
1052
+ * Each run reads the cluster-owned count inside the chain, so repeating it adds
1053
+ * nothing. A queued teardown may erase a temporary installation; the run
1054
+ * behind that teardown will then see and install the missing suffix again.
1055
+ */
1056
+ syncHost(imq) {
1057
+ return this.enqueue(imq, async () => {
1058
+ const progress = this.progressOf(imq);
1059
+ const channel = this.state.channel;
1060
+ if (!channel) {
1061
+ return;
846
1062
  }
847
- }
848
- if (this.state.subscription) {
1063
+ let installed = 0;
849
1064
  try {
850
- await imq.subscribe(this.state.subscription.channel, this.state.subscription.handler);
1065
+ for (let i = progress.installed; i < this.state.handlers.length; i++) {
1066
+ if (!this.imqs.includes(imq)) {
1067
+ return;
1068
+ }
1069
+ if (this.state.channel !== channel) {
1070
+ return;
1071
+ }
1072
+ await imq.subscribe(channel, this.state.handlers[i]);
1073
+ // rechecked after the await: teardown bypasses this chain,
1074
+ // so the host can have been removed or destroyed while the
1075
+ // subscribe was in flight. Recording it would leave the
1076
+ // counter claiming an install on a queue that is gone, and
1077
+ // the handler it just attached is torn down with the host
1078
+ if (!this.imqs.includes(imq)) {
1079
+ return;
1080
+ }
1081
+ progress.installed = i + 1;
1082
+ installed++;
1083
+ }
851
1084
  }
852
1085
  catch (err) {
853
- this.logLine('error', `server ${imq.redisKey} failed to subscribe to channel ${this.state.subscription.channel}, code ${errorCode(err)}: events from this node will never arrive`);
1086
+ this.logLine('error', `server ${imq.redisKey} failed to subscribe to channel ` +
1087
+ `${channel}, code ${errorCode(err)}: some handlers remain ` +
1088
+ 'uninstalled until a later registration triggers another catch-up');
854
1089
  throw err;
855
1090
  }
856
- }
1091
+ finally {
1092
+ if (installed) {
1093
+ this.logLine('info', `server ${imq.redisKey} installed ${installed} handler(s) ` +
1094
+ `for channel ${channel}`);
1095
+ }
1096
+ }
1097
+ });
857
1098
  }
858
1099
  /**
859
1100
  * Finds an already-registered server matching the given one.