@imqueue/core 3.4.1 → 3.4.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/AGENTS.md CHANGED
@@ -71,12 +71,24 @@ timeout is 15s per test. Run a single spec after a build with
71
71
  - **Two delivery modes**, selected by the `safeDelivery` option: *unreliable*
72
72
  (fast; a message is lost if a consumer grabs it and dies) and *safe/guaranteed*
73
73
  (1.5–2× slower; a grabbed-then-lost message is rescheduled). Safe delivery
74
- relies on Redis `LMOVE`/`BLMOVE` — **Redis 6.2+ is required.** Unreliable
75
- delivery uses `BRPOP` alone and works on 3.2+, so quote 6.2+ as the
76
- requirement unless the sentence is specifically about the unreliable mode.
74
+ covers the **processing**, not only the hand-off: the worker key is held until
75
+ the `message` listener is done, and **a listener says so by what it
76
+ returns** — a returned promise keeps the message checked out until it
77
+ settles, anything else releases it as the listener returns. Listeners are
78
+ therefore invoked through `rawListeners()` rather than `emit()`, which
79
+ discards return values. Safe delivery relies on Redis `LMOVE`/`BLMOVE` —
80
+ **Redis 6.2+ is required.** Unreliable delivery uses `BRPOP` alone and works
81
+ on 3.2+, so quote 6.2+ as the requirement unless the sentence is specifically
82
+ about the unreliable mode.
77
83
  - **No polling / no timers.** Delivery uses blocking Redis ops + keyspace
78
- notification events. If Redis has the `CONFIG` command disabled (e.g. AWS
79
- ElastiCache), keyspace notifications must be enabled out of band:
84
+ notification events. This is why a lease is reclaimed by asking the broker who
85
+ is still connected (`CLIENT LIST`, already read once per maintenance tick for
86
+ the cleanup pass) rather than by renewing a deadline: a per-message heartbeat
87
+ would be a timer, and would prove only that the event loop is free rather than
88
+ that work is progressing. `safeDeliveryTtl` bounds processing on top of that,
89
+ for the handler that wedges inside a process which is otherwise healthy. If
90
+ Redis has the `CONFIG` command disabled (e.g. AWS ElastiCache), keyspace
91
+ notifications must be enabled out of band:
80
92
  `notify-keyspace-events Ex`.
81
93
  - **Keyspace-notification flags are merged, never overwritten.**
82
94
  `notify-keyspace-events` is server-global, so `watch()` reads the current
package/CHANGELOG.md CHANGED
@@ -9,6 +9,114 @@ queue does has an entry.
9
9
 
10
10
  This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
11
11
 
12
+ ## [Unreleased]
13
+
14
+ ### Fixed
15
+
16
+ - **`safeDelivery` lost a message when a worker died mid-handler.** It released
17
+ the message's worker key the instant the message was dispatched to the
18
+ `message` listener, so a worker killed while its handler was still running
19
+ took that message with it and nothing brought it back — the option guaranteed
20
+ the hand-off while its name and documentation promised guaranteed delivery.
21
+ The key is now held until the listener has finished with the message.
22
+
23
+ **A listener says it has finished by what it returns.** Return a promise and
24
+ the message stays checked out until it settles; return anything else and it is
25
+ released as the listener returns. Every registered listener is consulted, and
26
+ the message is released once all the promises they returned have settled —
27
+ settled, not fulfilled, because a handler that threw has still had its turn
28
+ and re-delivering on a rejection would retry a poison message forever.
29
+
30
+ Nothing needs changing to get this: a listener that already returns a promise
31
+ — as `@imqueue/rpc` and `@imqueue/job` both do — is covered as it stands, and
32
+ a synchronous listener behaves exactly as it did.
33
+
34
+ A message that cannot be unpacked releases its lease rather than coming back
35
+ on every sweep.
36
+
37
+ - **A dead worker's message is recovered by asking the broker, not a clock.**
38
+ The worker key now carries the identity of the process that took it, and the
39
+ watcher reclaims it once that process has left `CLIENT LIST` — detected as
40
+ fast as the socket closes, and needing nothing renewed to keep a live lease
41
+ alive. Reconnecting workers get one sweep of grace, mirroring what the cleanup
42
+ pass already gave them, so a reconnect backoff does not cost a duplicate. If
43
+ the client list cannot be read at all, liveness is unknown and a lease is left
44
+ to its budget rather than guessed at.
45
+
46
+ ### Changed
47
+
48
+ - **`safeDeliveryTtl` is now the longest a message may be worked on**, and its
49
+ default moves from `5000` to `300000`. It used to be a hand-off recovery
50
+ deadline, which meant it bounded nothing that mattered: the key was deleted at
51
+ dispatch, so it never covered processing at all. It now bounds processing,
52
+ which is the only thing that recovers a message from a worker that is alive,
53
+ connected and serving other messages while one handler has wedged on this one.
54
+ Liveness cannot see that case, and restarting an otherwise healthy process is
55
+ not a recovery strategy.
56
+
57
+ Set it to the longest a handler in this system can legitimately take, with
58
+ headroom — a slow upstream is the usual reason for a large value, such as a
59
+ data vendor with no job API or screen-scraping behind an HTTP call. Too low
60
+ and a message is reclaimed from a worker still legitimately working on it.
61
+
62
+ The default rose because the meaning changed: 5000 was a sane hand-off
63
+ deadline and is a poor processing budget.
64
+
65
+ - **The maintenance sweep now runs on `watcherCheckDelay`** (5000 ms by
66
+ default) rather than on `safeDeliveryTtl`. How long a message may be worked on
67
+ and how often the watcher looks for abandoned ones are different questions,
68
+ and tying them would make a crashed worker's message wait out a budget meant
69
+ for a live one. `watcherCheckDelay` is therefore the worst-case latency for a
70
+ crashed worker's message coming back; with the watcher check disabled the
71
+ sweep falls back to `safeDeliveryTtl`.
72
+
73
+ - **The reader's blocking pop is half `safeDeliveryTtl` capped at 5000 ms.** A
74
+ lease deadline is stamped before the pop that fills the key, so an uncapped
75
+ wait would hand a message a sizeable part of its budget already spent. At the
76
+ old defaults both of these resolve to exactly what they were.
77
+
78
+ - No option was added or removed.
79
+
80
+ ### Keeping the old behaviour
81
+
82
+ Release-at-dispatch is still available per listener, and exactly: **do not
83
+ return the handler's promise.**
84
+
85
+ ```typescript
86
+ // held until the handler finishes — the fix
87
+ queue.on('message', async message => { await handle(message); });
88
+
89
+ // released at dispatch, bit-for-bit the old behaviour
90
+ queue.on('message', message => { void handle(message); });
91
+ ```
92
+
93
+ Note that `safeDeliveryTtl` is not the lever for this. It never bounded a
94
+ dispatched message's lifetime before — the key was already deleted — and it does
95
+ not bound one now, so no value of it reproduces the old behaviour.
96
+
97
+ ### Notes for upgrading
98
+
99
+ - A synchronous listener needs no change.
100
+ - A listener returning a promise now holds its message for the life of that
101
+ promise, bounded by `safeDeliveryTtl`. Check that budget is above your slowest
102
+ handler, since the default of five minutes is a guess about your workload and
103
+ nothing else.
104
+ - Messages that used to vanish when a worker died now come back, so a handler
105
+ that was quietly getting away with not being idempotent will start seeing
106
+ repeats. Delivery was documented as at-least-once throughout; this makes the
107
+ implementation match.
108
+ - Worker keys written by 3.x carry no owner and are still honoured by their
109
+ deadline, so a rolling upgrade does not strand them. New keys put the owner
110
+ *before* the deadline, so a 3.x watcher still reads the queue off the front
111
+ and a number off the end rather than parsing garbage. While a 3.x watcher is
112
+ the elected one it will still reclaim 4.x leases on that deadline, so expect
113
+ duplicates for the length of the upgrade and finish it promptly.
114
+ - No new redis traffic and no new timers: the maintenance tick already read
115
+ `CLIENT LIST` for the cleanup pass and lease recovery shares that one read.
116
+ Nothing is renewed, polled or scheduled per message — a heartbeat would prove
117
+ only that the event loop is free, not that work is progressing, and so would
118
+ reclaim exactly when a worker is busiest.
119
+
12
120
  ## [3.4.0] - 2026-08-20
13
121
 
14
122
  ### Added
package/README.md CHANGED
@@ -113,6 +113,81 @@ import IMQ, { IMessageQueue, IJson } from '@imqueue/core';
113
113
  })();
114
114
  ```
115
115
 
116
+ # Guaranteed delivery
117
+
118
+ `safeDelivery` moves a message atomically out of the queue into a worker-owned
119
+ key as it is popped, and keeps it there until the message has been handled. A
120
+ worker that dies at any point before then — before it starts, or halfway through
121
+ the handler — leaves the message behind to be re-queued rather than taking it
122
+ down.
123
+
124
+ **How a listener says it has finished is its return value.** Return a promise and
125
+ the message stays checked out until it settles:
126
+
127
+ ```typescript
128
+ const queue = IMQ.create('Orders', { safeDelivery: true });
129
+
130
+ queue.on('message', async (message, id, fromQueue) => {
131
+ await handle(message); // the message is checked out for all of this
132
+ });
133
+ ```
134
+
135
+ Return anything else and the message is released as the listener returns. Every
136
+ registered listener is consulted, and the message is released once all the
137
+ promises they returned have settled — settled, not fulfilled: a handler that
138
+ throws has still had its turn, and re-delivering on a rejection would retry a
139
+ poison message forever.
140
+
141
+ That return value is also the lever for opting out. To have a message released
142
+ at dispatch, as releases before 4.0 did, simply do not return its promise:
143
+
144
+ ```typescript
145
+ queue.on('message', message => {
146
+ void handle(message); // released immediately; a crash loses it
147
+ });
148
+ ```
149
+
150
+ `safeDeliveryTtl` is not that lever and never was — the key used to be deleted
151
+ at dispatch, so no value of it bounded a dispatched message's lifetime then, and
152
+ none bounds one now.
153
+
154
+ | option | default | meaning |
155
+ |---|---|---|
156
+ | `safeDelivery` | `false` | move messages through a worker-owned key, held until handled |
157
+ | `safeDeliveryTtl` | `300000` | the longest a message may be worked on |
158
+
159
+ A message comes back on either of two counts, because there are two ways to lose
160
+ one.
161
+
162
+ The **process dying** is caught by the broker: the worker key names the process
163
+ that took it, and the watcher reclaims the lease once that process leaves
164
+ `CLIENT LIST`. That is a fact the broker holds rather than an inference from a
165
+ clock, so it is noticed as fast as the socket closes, and nothing has to be
166
+ renewed to keep a live lease alive. Workers riding out a reconnect get one sweep
167
+ of grace, and if the client list cannot be read at all, leases are left to their
168
+ budget rather than guessed at.
169
+
170
+ **One handler wedging** is caught by `safeDeliveryTtl`, and only by it. A worker
171
+ can be up, connected and happily serving other messages while one handler is
172
+ stuck forever — liveness cannot see that, and restarting an otherwise healthy
173
+ process is not a recovery strategy. Set the budget to the longest a handler in
174
+ your system can legitimately take, with headroom: a slow upstream is the usual
175
+ reason for a large value — a data vendor with no job API, screen-scraping behind
176
+ an HTTP call, anything that can run for minutes. Set it too low and a message is
177
+ reclaimed from a worker still legitimately working on it.
178
+
179
+ Two internals deliberately do not scale with this value. The maintenance sweep
180
+ runs on `watcherCheckDelay` (5 s by default), so a dead worker is still found
181
+ within seconds however generous the budget — that, not `safeDeliveryTtl`, is the
182
+ latency for a crashed worker's message coming back. And the reader's blocking
183
+ pop is half the budget capped at 5 s, so a message is not born having already
184
+ spent much of it.
185
+
186
+ Delivery is **at-least-once** in every mode. Holding the lease narrows the window
187
+ in which in-flight work is lost — it does not close it, and `SIGKILL` on the
188
+ whole node, an OOM kill or a lost machine still take work with them — so handlers
189
+ must be idempotent.
190
+
116
191
  # Benchmarking
117
192
 
118
193
  First, make sure redis-server is running on localhost. The current version of the
package/index.d.ts CHANGED
@@ -44,6 +44,13 @@
44
44
  * reference-counted, and exactly one queue per key prefix is elected as the
45
45
  * watcher that releases delayed messages and performs maintenance.
46
46
  *
47
+ * Under {@link IMQOptions.safeDelivery} a message stays checked out to its
48
+ * worker until the `message` listener has finished with it, and what a listener
49
+ * **returns** is how it says so: return a promise and the message is held until
50
+ * that promise settles, so a worker that dies mid-handler leaves the message to
51
+ * be re-queued rather than taking it down. Return anything else — as the
52
+ * synchronous example below does — and it is released as the listener returns.
53
+ *
47
54
  * @example
48
55
  * ```typescript
49
56
  * import IMQ, { IMQMode, type IMessageQueue } from '@imqueue/core';
package/index.js CHANGED
@@ -44,6 +44,13 @@
44
44
  * reference-counted, and exactly one queue per key prefix is elected as the
45
45
  * watcher that releases delayed messages and performs maintenance.
46
46
  *
47
+ * Under {@link IMQOptions.safeDelivery} a message stays checked out to its
48
+ * worker until the `message` listener has finished with it, and what a listener
49
+ * **returns** is how it says so: return a promise and the message is held until
50
+ * that promise settles, so a worker that dies mid-handler leaves the message to
51
+ * be re-queued rather than taking it down. Return anything else — as the
52
+ * synchronous example below does — and it is released as the listener returns.
53
+ *
47
54
  * @example
48
55
  * ```typescript
49
56
  * import IMQ, { IMQMode, type IMessageQueue } from '@imqueue/core';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@imqueue/core",
3
- "version": "3.4.1",
3
+ "version": "3.4.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",
@@ -39,7 +39,7 @@
39
39
  },
40
40
  "repository": {
41
41
  "type": "git",
42
- "url": "git://github.com/imqueue/core.git"
42
+ "url": "git+https://github.com/imqueue/core.git"
43
43
  },
44
44
  "bugs": {
45
45
  "url": "https://github.com/imqueue/core/issues"
@@ -51,6 +51,11 @@ export declare abstract class ClusterManager {
51
51
  * Clusters currently registered with this manager.
52
52
  */
53
53
  protected clusters: InitializedCluster[];
54
+ /**
55
+ * Protected so that a manager is only ever obtained through a subclass —
56
+ * this base class holds the registry but implements no transport of its
57
+ * own.
58
+ */
54
59
  protected constructor();
55
60
  /**
56
61
  * Registers a cluster's membership callbacks with this manager and returns
@@ -41,6 +41,11 @@ export class ClusterManager {
41
41
  * Clusters currently registered with this manager.
42
42
  */
43
43
  clusters = [];
44
+ /**
45
+ * Protected so that a manager is only ever obtained through a subclass —
46
+ * this base class holds the registry but implements no transport of its
47
+ * own.
48
+ */
44
49
  constructor() { }
45
50
  /**
46
51
  * Registers a cluster's membership callbacks with this manager and returns
@@ -127,7 +127,21 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
127
127
  * cluster servers
128
128
  */
129
129
  private readonly clusterEmitter;
130
+ /**
131
+ * What has been done to this queue so far, so that a server joining later
132
+ * can be brought to the same point.
133
+ *
134
+ * @remarks
135
+ * Cluster membership changes at runtime, so a per-host queue may be created
136
+ * 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.
139
+ */
130
140
  private state;
141
+ /**
142
+ * Handles for the cluster managers this queue is registered with, kept so
143
+ * that {@link ClusteredRedisQueue.destroy} can deregister from each.
144
+ */
131
145
  private initializedClusters;
132
146
  /**
133
147
  * Creates a clustered queue.
@@ -260,6 +274,11 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
260
274
  * in-flight messages are not counted.
261
275
  */
262
276
  queueLength(): Promise<number>;
277
+ /**
278
+ * Writes a diagnostic line, but only under {@link IMQOptions.verbose}.
279
+ *
280
+ * @param message - the line to write
281
+ */
263
282
  private verbose;
264
283
  /**
265
284
  * Writes an unconditional line through this cluster's logger, in the
@@ -537,9 +556,52 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
537
556
  * sharing an address are removed together.
538
557
  */
539
558
  protected removeServer(server: IServerInput): void;
559
+ /**
560
+ * Adds a server to the cluster, optionally bringing its queue up to the
561
+ * cluster's current state.
562
+ *
563
+ * @param server - the server to add
564
+ * @param initializeQueue - whether to replay `start`/`subscribe` onto the
565
+ * new queue. Passed `false` while the cluster is still being
566
+ * constructed, when there is no state to replay yet
567
+ * @returns the server as registered, which is the existing entry when one
568
+ * already matched
569
+ */
540
570
  private addServerWithQueueInitializing;
571
+ /**
572
+ * Every emitter a listener registered on this cluster must reach.
573
+ *
574
+ * @returns the per-host queues plus the template emitter
575
+ *
576
+ * @remarks
577
+ * The template emitter is included so that listeners registered now are
578
+ * also carried onto queues created later, as servers join.
579
+ */
541
580
  private eventEmitters;
581
+ /**
582
+ * Brings a newly created per-host queue up to the cluster's current state.
583
+ *
584
+ * @param imq - the queue to initialize
585
+ *
586
+ * @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.
590
+ */
542
591
  private initializeQueue;
592
+ /**
593
+ * Finds an already-registered server matching the given one.
594
+ *
595
+ * @param server - the server to look for
596
+ * @returns the registered entry, or `undefined` when it is new
597
+ */
543
598
  private findServer;
599
+ /**
600
+ * Decides whether two server descriptions refer to the same server.
601
+ *
602
+ * @param source - one server description
603
+ * @param target - the other
604
+ * @returns whether they are the same server
605
+ */
544
606
  private static matchServers;
545
607
  }
@@ -112,10 +112,24 @@ export class ClusteredRedisQueue {
112
112
  * cluster servers
113
113
  */
114
114
  clusterEmitter;
115
+ /**
116
+ * What has been done to this queue so far, so that a server joining later
117
+ * can be brought to the same point.
118
+ *
119
+ * @remarks
120
+ * Cluster membership changes at runtime, so a per-host queue may be created
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.
124
+ */
115
125
  state = {
116
126
  started: false,
117
127
  subscription: null,
118
128
  };
129
+ /**
130
+ * Handles for the cluster managers this queue is registered with, kept so
131
+ * that {@link ClusteredRedisQueue.destroy} can deregister from each.
132
+ */
119
133
  initializedClusters = [];
120
134
  /**
121
135
  * Creates a clustered queue.
@@ -341,6 +355,11 @@ export class ClusteredRedisQueue {
341
355
  const lengths = await Promise.all(promises);
342
356
  return lengths.reduce((total, length) => total + length, 0);
343
357
  }
358
+ /**
359
+ * Writes a diagnostic line, but only under {@link IMQOptions.verbose}.
360
+ *
361
+ * @param message - the line to write
362
+ */
344
363
  verbose(message) {
345
364
  if (this.options.verbose) {
346
365
  this.logger.info(`[IMQ-CORE][ClusteredRedisQueue][${this.name}]: ${message}`);
@@ -743,6 +762,17 @@ export class ClusteredRedisQueue {
743
762
  imq: imqToRemove,
744
763
  });
745
764
  }
765
+ /**
766
+ * Adds a server to the cluster, optionally bringing its queue up to the
767
+ * cluster's current state.
768
+ *
769
+ * @param server - the server to add
770
+ * @param initializeQueue - whether to replay `start`/`subscribe` onto the
771
+ * new queue. Passed `false` while the cluster is still being
772
+ * constructed, when there is no state to replay yet
773
+ * @returns the server as registered, which is the existing entry when one
774
+ * already matched
775
+ */
746
776
  addServerWithQueueInitializing(server, initializeQueue = true) {
747
777
  const existingServer = this.findServer(server);
748
778
  if (existingServer) {
@@ -771,9 +801,28 @@ export class ClusteredRedisQueue {
771
801
  this.imqLength = this.imqs.length;
772
802
  return newServer;
773
803
  }
804
+ /**
805
+ * Every emitter a listener registered on this cluster must reach.
806
+ *
807
+ * @returns the per-host queues plus the template emitter
808
+ *
809
+ * @remarks
810
+ * The template emitter is included so that listeners registered now are
811
+ * also carried onto queues created later, as servers join.
812
+ */
774
813
  eventEmitters() {
775
814
  return [...this.imqs, this.templateEmitter];
776
815
  }
816
+ /**
817
+ * Brings a newly created per-host queue up to the cluster's current state.
818
+ *
819
+ * @param imq - the queue to initialize
820
+ *
821
+ * @remarks
822
+ * Replays whatever {@link ClusteredRedisQueue.state} records, so a server
823
+ * that joins after the cluster started is started and subscribed too rather
824
+ * than sitting idle.
825
+ */
777
826
  async initializeQueue(imq) {
778
827
  this.verbose(`Initializing queue with state: ${JSON.stringify(this.state)}`);
779
828
  // both failures are reported here, inside the function, and the
@@ -799,9 +848,22 @@ export class ClusteredRedisQueue {
799
848
  }
800
849
  }
801
850
  }
851
+ /**
852
+ * Finds an already-registered server matching the given one.
853
+ *
854
+ * @param server - the server to look for
855
+ * @returns the registered entry, or `undefined` when it is new
856
+ */
802
857
  findServer(server) {
803
858
  return this.servers.find(existing => ClusteredRedisQueue.matchServers(existing, server));
804
859
  }
860
+ /**
861
+ * Decides whether two server descriptions refer to the same server.
862
+ *
863
+ * @param source - one server description
864
+ * @param target - the other
865
+ * @returns whether they are the same server
866
+ */
805
867
  static matchServers(source, target) {
806
868
  const sameAddress = target.host === source.host && target.port === source.port;
807
869
  if (!target.id && !source.id) {