@imqueue/core 3.5.2 → 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 CHANGED
@@ -157,6 +157,54 @@ release.
157
157
 
158
158
  ### Fixed
159
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
+
160
208
  - **A clustered queue gave a server that joined later only the last-registered
161
209
  subscription handler, silencing every other handler on that host.**
162
210
  `ClusteredRedisQueue` remembered one `{ channel, handler }` pair, so each
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@imqueue/core",
3
- "version": "3.5.2",
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",
@@ -561,6 +561,12 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
561
561
  * including for future hosts. To rebuild a known registration set, await
562
562
  * unsubscribe() and then register the desired handlers again.
563
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.
569
+ *
564
570
  * The handler receives one invocation per host that delivers the message.
565
571
  */
566
572
  subscribe(channel: string, handler: (data: JsonObject) => void): Promise<void>;
@@ -667,6 +673,44 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
667
673
  * Subscription catch-up proceeds independently of this lifecycle operation.
668
674
  */
669
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;
670
714
  /**
671
715
  * Installs registrations this cluster has not yet installed on a host.
672
716
  *
@@ -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
@@ -364,6 +373,7 @@ export class ClusteredRedisQueue {
364
373
  this.closed = true;
365
374
  this.state.started = false;
366
375
  for (const imq of this.imqs) {
376
+ this.cancelSync(imq);
367
377
  this.cleanup.add(() => imq.destroy());
368
378
  }
369
379
  for (const manager of this.options.clusterManagers || []) {
@@ -773,6 +783,12 @@ export class ClusteredRedisQueue {
773
783
  * including for future hosts. To rebuild a known registration set, await
774
784
  * unsubscribe() and then register the desired handlers again.
775
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.
791
+ *
776
792
  * The handler receives one invocation per host that delivers the message.
777
793
  */
778
794
  async subscribe(channel, handler) {
@@ -790,7 +806,15 @@ export class ClusteredRedisQueue {
790
806
  this.state.handlers.push(handler);
791
807
  this.logLine('info', `registered handler #${this.state.handlers.length} for channel ` +
792
808
  `${channel}`);
793
- await Promise.all(this.imqs.map(imq => this.syncHost(imq)));
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
+ })));
794
818
  }
795
819
  /**
796
820
  * Unsubscribes from the channel on every redis host and forgets every
@@ -864,6 +888,8 @@ export class ClusteredRedisQueue {
864
888
  }
865
889
  const imqToRemove = remove.imq;
866
890
  if (imqToRemove) {
891
+ // a retry scheduled for this host must not outlive it
892
+ this.cancelSync(imqToRemove);
867
893
  // dropped from routing first: a catch-up run in progress tests
868
894
  // membership between handlers and stops as soon as it sees this
869
895
  this.imqs = this.imqs.filter(imq => imqToRemove.redisKey !== imq.redisKey);
@@ -925,11 +951,17 @@ export class ClusteredRedisQueue {
925
951
  if (initializeQueue) {
926
952
  // Lifecycle and subscription use separate connections: a stalled
927
953
  // 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
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 = () => {
933
965
  if (!this.imqs.includes(imq)) {
934
966
  return;
935
967
  }
@@ -937,7 +969,13 @@ export class ClusteredRedisQueue {
937
969
  server: newServer,
938
970
  imq,
939
971
  });
940
- },
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,
941
979
  // reported inside the run; without a handler here a host that
942
980
  // simply refuses a connection - routine - becomes an unhandled
943
981
  // rejection, which is fatal on current node defaults
@@ -994,6 +1032,7 @@ export class ClusteredRedisQueue {
994
1032
  progress = {
995
1033
  chain: Promise.resolve(),
996
1034
  installed: 0,
1035
+ retryAttempts: 0,
997
1036
  };
998
1037
  this.progress.set(imq, progress);
999
1038
  }
@@ -1041,6 +1080,75 @@ export class ClusteredRedisQueue {
1041
1080
  this.starting.set(imq, run);
1042
1081
  return run;
1043
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;
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;
1150
+ }
1151
+ }
1044
1152
  /**
1045
1153
  * Installs registrations this cluster has not yet installed on a host.
1046
1154
  *
@@ -1085,7 +1193,8 @@ export class ClusteredRedisQueue {
1085
1193
  catch (err) {
1086
1194
  this.logLine('error', `server ${imq.redisKey} failed to subscribe to channel ` +
1087
1195
  `${channel}, code ${errorCode(err)}: some handlers remain ` +
1088
- 'uninstalled until a later registration triggers another catch-up');
1196
+ 'uninstalled until the retry the cluster schedules for ' +
1197
+ 'this host succeeds');
1089
1198
  throw err;
1090
1199
  }
1091
1200
  finally {
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
  }