@imqueue/core 3.5.4 → 3.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -9,151 +9,51 @@ 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]
12
+ ## [3.7.0] - 2026-11-22
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.
14
+ ### Fixed
15
+
16
+ - **A broker whose heartbeats lapsed was dropped while its connections were
17
+ healthy, and the replies it had already delivered were lost.** The UDP
18
+ cluster manager removes a server once it misses its heartbeats for the
19
+ check's timeout. A busy process misses them without the broker being gone,
20
+ and the removal destroyed the server's queue at once: its listeners went
21
+ before its reader was disconnected, so a reply already read was dropped and
22
+ its caller waited out its whole timeout. Now a server removed for lapsed
23
+ heartbeats is asked first; one that answers within
24
+ `IMQ_LAPSED_ANSWER_TIMEOUT` (2 s) is kept. One that does not is drained
25
+ before it is destroyed: its blocked read is unblocked, and what it already
26
+ read is handed on before its listeners go.
18
27
 
19
28
  ### Added
20
29
 
21
- - **TLS on connections to the redis broker.** A new `tls` option encrypts every
22
- connection a queue opens — reader, writer, watcher and subscription alike.
23
- Pass `true` for Node's defaults, or an object handed to `tls.connect()` as
24
- given, so a private CA (`ca`) and mutual TLS (`cert`/`key`) both work. The
25
- option was previously accepted by the type system and dropped on the way to
26
- the client, which meant the bus could not be encrypted at all.
30
+ - **`IMQ_LAPSED_ANSWER_TIMEOUT`**, how long a server whose heartbeats lapsed
31
+ has to answer before it is removed, in milliseconds (default 2000).
32
+ - **`ServerRemoval`**, the optional second argument of a cluster's
33
+ `remove()`: `{ lapsed: true }` where the removal is for missed heartbeats
34
+ rather than a server that said it was leaving.
27
35
 
28
- Cluster entries may carry their own `tls`, overriding the cluster-wide one
29
- for that server alone; an entry that omits it falls back to the top level.
30
- Per-entry `username` and `password` are still ignored, exactly as before —
31
- honouring them would change what an existing cluster authenticates with, and
32
- that has nothing to do with this feature.
36
+ ## [3.6.0] - 2026-11-12
33
37
 
34
- With `tls` left unset the environment is consulted — `IMQ_REDIS_TLS`,
35
- `IMQ_REDIS_TLS_CA_FILE`, `IMQ_REDIS_TLS_CERT_FILE`, `IMQ_REDIS_TLS_KEY_FILE`,
36
- `IMQ_REDIS_TLS_KEY_PASSPHRASE`, `IMQ_REDIS_TLS_SERVERNAME` and
37
- `IMQ_REDIS_TLS_REJECT_UNAUTHORIZED` — so a deployment can encrypt a fleet
38
- without a code change. Certificate files are read as the queue is
39
- constructed, and an unreadable one throws: an unmounted secret stops the
40
- process rather than leaving it talking to the broker in the clear. Passing
41
- `tls` explicitly always wins, `tls: false` included, and
42
- `rejectUnauthorized: false` is warned about because it leaves a connection
43
- encrypted but unauthenticated.
44
-
45
- This covers the queue's own connections. `UDPClusterManager` announcements
46
- remain unauthenticated UDP broadcast and are unaffected.
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.
38
+ ### Added
55
39
 
56
- - **Integration specs covering TLS against a real broker**, in
57
- `test/integration/`, run by `npm run test-integration`. They stand up a
58
- throwaway TLS-only redis and assert what a mocked `ioredis` cannot: that the
59
- handshake completes and is verified, that a message crosses it, that the
60
- connection pool keeps differing TLS configurations apart, and that plaintext,
61
- an unverifiable certificate and a wrong server name are all refused rather
62
- than downgraded. They skip themselves, with a reason, wherever
63
- `redis-server` and `openssl` are not both available, so a checkout without
64
- redis still passes. `npm test` now globs `test/unit` and does not run them.
40
+ - **zstd for large messages, `compressAbove`.** A queue message whose JSON is
41
+ longer than `compressAbove` characters (or `IMQ_COMPRESS_ABOVE`, when the
42
+ option is not given) is written zstd-compressed at the fastest level, as
43
+ base64 behind a one-character mark. Smaller messages are written as before.
44
+ Off by default. Measured on a real 4.6 MB message: 293 KB on the wire for
45
+ about 3 ms of extra CPU, where `useGzip` gave 491 KB for about 19 ms, and
46
+ gzip's binary string grows by about half again as it is written as UTF-8.
65
47
 
66
48
  ### Changed
67
49
 
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.
50
+ - **Every queue reads plain, gzipped and zstd messages, whatever its own
51
+ settings.** The format is told apart by the first character, so producer and
52
+ consumer no longer have to agree on `useGzip`, and a fleet can turn
53
+ compression on one writer at a time once every reader runs this version.
54
+ Writing is unchanged unless `compressAbove` is set.
76
55
 
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
-
101
- - **Nothing changes for a queue that does not use TLS.** The option is absent
102
- from `options` unless it was configured, the connection pool key stays the
103
- plain `host:port`, the redis client is handed no `tls` option, and no new
104
- warning is emitted. The only added work on that path is one environment
105
- lookup per queue construction, about a microsecond, and nothing at all per
106
- message. This is covered by its own group of specs rather than left as a
107
- claim.
108
-
109
- - **A connection failure no longer takes the process down during teardown.**
110
- This is a behaviour change for everyone, not only TLS users: a socket that
111
- reported a second failure after the one that closed it used to reach an
112
- `error` with no listener and terminate the process. Such a process now stays
113
- up, and the failure is still logged and emitted as it always was. Nothing
114
- that previously succeeded behaves differently; a crash becomes a log line.
115
-
116
- - **Shared writer and watcher connections are now keyed by TLS configuration as
117
- well as by `host:port`.** These connections are shared per server within a
118
- process; queues reaching one server under different TLS configurations now get
119
- separate connections, so a queue that asked for encryption can never be handed
120
- a plaintext socket another queue opened first, nor the reverse. Configurations
121
- equal by value still share, and the public `redisKey` still reports the plain
122
- `host:port` address.
123
-
124
- - **`safeDeliveryTtl` is now the longest a message may be worked on**, and its
125
- default moves from `5000` to `300000`. It used to be a hand-off recovery
126
- deadline, which meant it bounded nothing that mattered: the key was deleted at
127
- dispatch, so it never covered processing at all. It now bounds processing,
128
- which is the only thing that recovers a message from a worker that is alive,
129
- connected and serving other messages while one handler has wedged on this one.
130
- Liveness cannot see that case, and restarting an otherwise healthy process is
131
- not a recovery strategy.
132
-
133
- Set it to the longest a handler in this system can legitimately take, with
134
- headroom — a slow upstream is the usual reason for a large value, such as a
135
- data vendor with no job API or screen-scraping behind an HTTP call. Too low
136
- and a message is reclaimed from a worker still legitimately working on it.
137
-
138
- The default rose because the meaning changed: 5000 was a sane hand-off
139
- deadline and is a poor processing budget.
140
-
141
- - **The maintenance sweep now runs on `watcherCheckDelay`** (5000 ms by
142
- default) rather than on `safeDeliveryTtl`. How long a message may be worked on
143
- and how often the watcher looks for abandoned ones are different questions,
144
- and tying them would make a crashed worker's message wait out a budget meant
145
- for a live one. `watcherCheckDelay` is therefore the worst-case latency for a
146
- crashed worker's message coming back; with the watcher check disabled the
147
- sweep falls back to `safeDeliveryTtl`.
148
-
149
- - **The reader's blocking pop is half `safeDeliveryTtl` capped at 5000 ms.** A
150
- lease deadline is stamped before the pop that fills the key, so an uncapped
151
- wait would hand a message a sizeable part of its budget already spent. At the
152
- old defaults both of these resolve to exactly what they were.
153
-
154
- - The safe-delivery changes above alter meanings and defaults only —
155
- `safeDelivery`, `safeDeliveryTtl` and `watcherCheckDelay` are the same three
156
- options they were.
56
+ ## [3.5.4] - 2026-10-07
157
57
 
158
58
  ### Fixed
159
59
 
@@ -183,6 +83,10 @@ release.
183
83
  `CONFIG SET` only when a flag is missing; where `CONFIG` is not permitted this
184
84
  logs the same `events config error` line as at start-up.
185
85
 
86
+ ## [3.5.3] - 2026-09-18
87
+
88
+ ### Fixed
89
+
186
90
  - **A joining host whose first subscription attempt failed stayed silent for the
187
91
  life of the process.** `RedisQueue.subscribe()` records a handler only after
188
92
  the subscribe resolves, so a first failure left that host's handler list
@@ -231,6 +135,59 @@ release.
231
135
  it was found. `restoreSubscription()` now reconciles the connection's listeners
232
136
  to exactly the remembered handlers instead of appending to them.
233
137
 
138
+ ## [3.5.2] - 2026-09-14
139
+
140
+ The clustered subscription changes below are **patch-level bug fixes**: they
141
+ restore additive subscription replay and close lifecycle races without adding a
142
+ public API.
143
+
144
+ ### Added
145
+
146
+ - **Integration specs covering clustered subscription against a real broker**,
147
+ in `test/integration/clusterSubscription.spec.ts`. Unit mocks verify call
148
+ ordering and simulated delivery; these additionally verify Redis subscription
149
+ acknowledgments and actual deliveries. Unlike the TLS specs they do not stand
150
+ up their own server: they use an ambient one at `REDIS_HOST`/`REDIS_PORT` (default
151
+ `127.0.0.1:6379`) and skip, with a reason, when none answers. `npm test` does
152
+ not run them.
153
+
154
+ ### Changed
155
+
156
+ - **Clustered subscribe()/unsubscribe() now serialise per host.** A call can
157
+ block behind an earlier subscription operation on that host that never
158
+ settles. Different hosts proceed independently. Rejected registrations remain
159
+ remembered and may have succeeded on some hosts; **subscribe() is not
160
+ retryable**. Repeating it adds another registration, including on future
161
+ hosts. To rebuild a known set, await unsubscribe() and register that set again.
162
+ Function-identity deduplication would break deliberate additive registrations;
163
+ rolling back a partial fan-out would require tearing down working subscribers.
164
+
165
+ - **Clustered destroy() clears routing membership and subscription state
166
+ synchronously.** Queued work cannot reopen a destroyed host. Teardown bypasses
167
+ subscription chains so a wedged operation cannot hold it up. Concurrent callers
168
+ await the same teardown (including manager removal) and observe the same
169
+ AggregateError if it fails. Every independent host teardown and manager removal
170
+ is attempted even if others fail. A later destroy() retries only failed tasks;
171
+ successful cleanup is not repeated. Discovery admission closes synchronously
172
+ and stays closed during and after teardown, including retries. A `send()`
173
+ already parked waiting for the first server is rejected as teardown begins,
174
+ rather than waiting out `IMQ_SEND_INIT_TIMEOUT` on a timer that keeps the
175
+ process alive; `send()` and `subscribe()` on a destroyed instance are
176
+ rejected outright instead of stalling or repopulating the cleared state.
177
+ Destroyed instances must not be reused.
178
+
179
+ - **`ClusteredRedisQueue.subscribe()` now rejects a bad channel on an empty
180
+ cluster, where it used to resolve.** Validation lived in the underlying
181
+ queues, so with no servers yet there was nothing to raise it: a second
182
+ channel name, or an empty one, resolved and left the remembered subscription
183
+ naming a channel nothing was subscribed to. The cluster now applies the same
184
+ two checks itself, with the same messages the underlying queue uses, before
185
+ touching any state. An empty cluster is the normal starting point for
186
+ membership discovered at runtime, so a caller that registers before the first
187
+ server arrives will see an error it previously did not.
188
+
189
+ ### Fixed
190
+
234
191
  - **A clustered queue gave a server that joined later only the last-registered
235
192
  subscription handler, silencing every other handler on that host.**
236
193
  `ClusteredRedisQueue` remembered one `{ channel, handler }` pair, so each
@@ -273,6 +230,74 @@ release.
273
230
  they cannot start that host concurrently. Settled startup is released so an
274
231
  explicit later start() can retry.
275
232
 
233
+ ## [3.5.0] - 2026-09-01
234
+
235
+ ### Added
236
+
237
+ - **TLS on connections to the redis broker.** A new `tls` option encrypts every
238
+ connection a queue opens — reader, writer, watcher and subscription alike.
239
+ Pass `true` for Node's defaults, or an object handed to `tls.connect()` as
240
+ given, so a private CA (`ca`) and mutual TLS (`cert`/`key`) both work. The
241
+ option was previously accepted by the type system and dropped on the way to
242
+ the client, which meant the bus could not be encrypted at all.
243
+
244
+ Cluster entries may carry their own `tls`, overriding the cluster-wide one
245
+ for that server alone; an entry that omits it falls back to the top level.
246
+ Per-entry `username` and `password` are still ignored, exactly as before —
247
+ honouring them would change what an existing cluster authenticates with, and
248
+ that has nothing to do with this feature.
249
+
250
+ With `tls` left unset the environment is consulted — `IMQ_REDIS_TLS`,
251
+ `IMQ_REDIS_TLS_CA_FILE`, `IMQ_REDIS_TLS_CERT_FILE`, `IMQ_REDIS_TLS_KEY_FILE`,
252
+ `IMQ_REDIS_TLS_KEY_PASSPHRASE`, `IMQ_REDIS_TLS_SERVERNAME` and
253
+ `IMQ_REDIS_TLS_REJECT_UNAUTHORIZED` — so a deployment can encrypt a fleet
254
+ without a code change. Certificate files are read as the queue is
255
+ constructed, and an unreadable one throws: an unmounted secret stops the
256
+ process rather than leaving it talking to the broker in the clear. Passing
257
+ `tls` explicitly always wins, `tls: false` included, and
258
+ `rejectUnauthorized: false` is warned about because it leaves a connection
259
+ encrypted but unauthenticated.
260
+
261
+ This covers the queue's own connections. `UDPClusterManager` announcements
262
+ remain unauthenticated UDP broadcast and are unaffected.
263
+
264
+ - **Integration specs covering TLS against a real broker**, in
265
+ `test/integration/`, run by `npm run test-integration`. They stand up a
266
+ throwaway TLS-only redis and assert what a mocked `ioredis` cannot: that the
267
+ handshake completes and is verified, that a message crosses it, that the
268
+ connection pool keeps differing TLS configurations apart, and that plaintext,
269
+ an unverifiable certificate and a wrong server name are all refused rather
270
+ than downgraded. They skip themselves, with a reason, wherever
271
+ `redis-server` and `openssl` are not both available, so a checkout without
272
+ redis still passes. `npm test` now globs `test/unit` and does not run them.
273
+
274
+ ### Changed
275
+
276
+ - **Nothing changes for a queue that does not use TLS.** The option is absent
277
+ from `options` unless it was configured, the connection pool key stays the
278
+ plain `host:port`, the redis client is handed no `tls` option, and no new
279
+ warning is emitted. The only added work on that path is one environment
280
+ lookup per queue construction, about a microsecond, and nothing at all per
281
+ message. This is covered by its own group of specs rather than left as a
282
+ claim.
283
+
284
+ - **A connection failure no longer takes the process down during teardown.**
285
+ This is a behaviour change for everyone, not only TLS users: a socket that
286
+ reported a second failure after the one that closed it used to reach an
287
+ `error` with no listener and terminate the process. Such a process now stays
288
+ up, and the failure is still logged and emitted as it always was. Nothing
289
+ that previously succeeded behaves differently; a crash becomes a log line.
290
+
291
+ - **Shared writer and watcher connections are now keyed by TLS configuration as
292
+ well as by `host:port`.** These connections are shared per server within a
293
+ process; queues reaching one server under different TLS configurations now get
294
+ separate connections, so a queue that asked for encryption can never be handed
295
+ a plaintext socket another queue opened first, nor the reverse. Configurations
296
+ equal by value still share, and the public `redisKey` still reports the plain
297
+ `host:port` address.
298
+
299
+ ### Fixed
300
+
276
301
  - **A failed connection could crash the process as it was being torn down.**
277
302
  The redis client guards its socket with a one-shot `error` listener, which
278
303
  the failure that brings the connection down spends. A socket that goes on to
@@ -287,6 +312,46 @@ release.
287
312
  service started against a broker it cannot verify would reject `start()` and
288
313
  then die inside `destroy()` rather than reporting the misconfiguration.
289
314
 
315
+ ## [3.4.3] - 2026-08-30
316
+
317
+ ### Changed
318
+
319
+ - **`safeDeliveryTtl` is now the longest a message may be worked on**, and its
320
+ default moves from `5000` to `300000`. It used to be a hand-off recovery
321
+ deadline, which meant it bounded nothing that mattered: the key was deleted at
322
+ dispatch, so it never covered processing at all. It now bounds processing,
323
+ which is the only thing that recovers a message from a worker that is alive,
324
+ connected and serving other messages while one handler has wedged on this one.
325
+ Liveness cannot see that case, and restarting an otherwise healthy process is
326
+ not a recovery strategy.
327
+
328
+ Set it to the longest a handler in this system can legitimately take, with
329
+ headroom — a slow upstream is the usual reason for a large value, such as a
330
+ data vendor with no job API or screen-scraping behind an HTTP call. Too low
331
+ and a message is reclaimed from a worker still legitimately working on it.
332
+
333
+ The default rose because the meaning changed: 5000 was a sane hand-off
334
+ deadline and is a poor processing budget.
335
+
336
+ - **The maintenance sweep now runs on `watcherCheckDelay`** (5000 ms by
337
+ default) rather than on `safeDeliveryTtl`. How long a message may be worked on
338
+ and how often the watcher looks for abandoned ones are different questions,
339
+ and tying them would make a crashed worker's message wait out a budget meant
340
+ for a live one. `watcherCheckDelay` is therefore the worst-case latency for a
341
+ crashed worker's message coming back; with the watcher check disabled the
342
+ sweep falls back to `safeDeliveryTtl`.
343
+
344
+ - **The reader's blocking pop is half `safeDeliveryTtl` capped at 5000 ms.** A
345
+ lease deadline is stamped before the pop that fills the key, so an uncapped
346
+ wait would hand a message a sizeable part of its budget already spent. At the
347
+ old defaults both of these resolve to exactly what they were.
348
+
349
+ - The safe-delivery changes above alter meanings and defaults only —
350
+ `safeDelivery`, `safeDeliveryTtl` and `watcherCheckDelay` are the same three
351
+ options they were.
352
+
353
+ ### Fixed
354
+
290
355
  - **`safeDelivery` lost a message when a worker died mid-handler.** It released
291
356
  the message's worker key the instant the message was dispatched to the
292
357
  `message` listener, so a worker killed while its handler was still running
package/README.md CHANGED
@@ -69,7 +69,9 @@ Otherwise the queue configures them itself, and does so without disturbing your
69
69
  own setup: it reads `notify-keyspace-events`, appends only the flags it is
70
70
  missing (`E` and `x`) and leaves everything else — including flags enabled by
71
71
  an operator or by other code sharing the same Redis — in place. Any superset of
72
- `Ex` is accepted as is, so no `CONFIG SET` is issued at all.
72
+ `Ex` is accepted as is, so no `CONFIG SET` is issued at all. It checks again
73
+ whenever its watcher reconnects, so a broker restart that drops a value set at
74
+ runtime is repaired without restarting the service.
73
75
 
74
76
  More adapters will be added in the future as needed.
75
77
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@imqueue/core",
3
- "version": "3.5.4",
3
+ "version": "3.7.0",
4
4
  "description": "Fast JSON message queue over Redis for inter-service communication in Node.js & TypeScript microservices — the transport layer of the @imqueue framework",
5
5
  "keywords": [
6
6
  "message-queue",
@@ -1,4 +1,14 @@
1
1
  import { type IMessageQueueConnection, type IServerInput } from './IMessageQueue.js';
2
+ /**
3
+ * Why a {@link ClusterManager} removes a server, where it can say.
4
+ */
5
+ export interface ServerRemoval {
6
+ /**
7
+ * True where the server's announcements stopped arriving and nothing said
8
+ * it went away: a missed heartbeat, not a `down` notice.
9
+ */
10
+ lapsed?: boolean;
11
+ }
2
12
  /**
3
13
  * Membership callbacks a clustered queue hands to a {@link ClusterManager} so
4
14
  * the manager can add and remove servers as it discovers them.
@@ -15,8 +25,10 @@ export interface ICluster {
15
25
  add: (server: IServerInput) => IMessageQueueConnection;
16
26
  /**
17
27
  * Removes a server from the cluster. A no-op when the server is unknown.
28
+ * With `removal.lapsed`, only the server's announcements stopped arriving,
29
+ * and a cluster may keep a server that still answers on its connections.
18
30
  */
19
- remove: (server: IServerInput) => void;
31
+ remove: (server: IServerInput, removal?: ServerRemoval) => void;
20
32
  /**
21
33
  * Looks a server up, matching by `id` when both sides carry one and by host
22
34
  * and port otherwise. Returns `undefined` when it is not registered.
@@ -22,6 +22,7 @@
22
22
  * <support@imqueue.com> to get commercial licensing options.
23
23
  */
24
24
  import { EventEmitter } from 'node:events';
25
+ import { type ServerRemoval } from './ClusterManager.js';
25
26
  import { type EventMap, type ILogger, type IMessageQueue, type IMessageQueueConnection, IMQMode, type IMQOptions, type IServerInput, type JsonObject, RedisQueue } from './index.js';
26
27
  /**
27
28
  * A server registered in a {@link ClusteredRedisQueue}: its address, plus the
@@ -620,7 +621,14 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
620
621
  * Because the underlying queues are matched by host and port, all entries
621
622
  * sharing an address are removed together.
622
623
  */
623
- protected removeServer(server: IServerInput): void;
624
+ protected removeServer(server: IServerInput, removal?: ServerRemoval): void;
625
+ /**
626
+ * Removes a server known to be gone: out of routing at once, its queue
627
+ * drained of what it already read and then torn down.
628
+ *
629
+ * @param server - address of the server to remove
630
+ */
631
+ private dropServer;
624
632
  /**
625
633
  * Adds a server to the cluster, optionally bringing its queue up to the
626
634
  * cluster's current state.
@@ -23,7 +23,7 @@
23
23
  */
24
24
  import { EventEmitter } from 'node:events';
25
25
  import {} from './ClusterManager.js';
26
- import { buildOptions, copyEventEmitter, errorCode } from './helpers/index.js';
26
+ import { buildOptions, copyEventEmitter, envInt, errorCode, } from './helpers/index.js';
27
27
  import { DEFAULT_IMQ_OPTIONS, IMQMode, RedisQueue, } from './index.js';
28
28
  /**
29
29
  * Time (ms) send() waits for the first cluster server to become available
@@ -40,6 +40,12 @@ const SEND_INIT_TIMEOUT = +(process.env.IMQ_SEND_INIT_TIMEOUT || 0) || 30000;
40
40
  const SYNC_RETRY_BASE_DELAY = 1000;
41
41
  /** Longest delay (ms) between subscription catch-up retries. */
42
42
  const SYNC_RETRY_MAX_DELAY = 30000;
43
+ /**
44
+ * Time (ms) a server whose announcements lapsed is given to answer a PING
45
+ * before it is removed. Configurable via the IMQ_LAPSED_ANSWER_TIMEOUT
46
+ * environment variable, defaults to 2,000.
47
+ */
48
+ const LAPSED_ANSWER_TIMEOUT = envInt('IMQ_LAPSED_ANSWER_TIMEOUT', 2000);
43
49
  /**
44
50
  * Scales a single logical queue horizontally across several redis instances.
45
51
  * This is what {@link IMQ.create} returns when {@link IMQOptions.cluster} or
@@ -880,8 +886,37 @@ export class ClusteredRedisQueue {
880
886
  * Because the underlying queues are matched by host and port, all entries
881
887
  * sharing an address are removed together.
882
888
  */
883
- removeServer(server) {
889
+ removeServer(server, removal) {
884
890
  this.verbose(`Removing the server: ${JSON.stringify(server)}`);
891
+ const remove = this.findServer(server);
892
+ if (!remove) {
893
+ return;
894
+ }
895
+ // only its announcements lapsed - a busy process misses them as
896
+ // easily as a dead broker stops sending them - so the broker is
897
+ // asked first, and kept where it still answers
898
+ if (removal?.lapsed && remove.imq) {
899
+ const kept = remove.imq;
900
+ void kept.answers(LAPSED_ANSWER_TIMEOUT).then(answers => {
901
+ if (answers) {
902
+ this.verbose(`Kept the server ${kept.redisKey}: its announcements lapsed, but it answers`);
903
+ return;
904
+ }
905
+ if (this.findServer(server)?.imq === kept) {
906
+ this.dropServer(server);
907
+ }
908
+ });
909
+ return;
910
+ }
911
+ this.dropServer(server);
912
+ }
913
+ /**
914
+ * Removes a server known to be gone: out of routing at once, its queue
915
+ * drained of what it already read and then torn down.
916
+ *
917
+ * @param server - address of the server to remove
918
+ */
919
+ dropServer(server) {
885
920
  const remove = this.findServer(server);
886
921
  if (!remove) {
887
922
  return;
@@ -897,8 +932,11 @@ export class ClusteredRedisQueue {
897
932
  // connection that never answers would then never be torn down at
898
933
  // all, and teardown is the one operation that has to happen
899
934
  // regardless of what the host is doing
935
+ // drained first: a reply its reader already took from the
936
+ // broker reaches its caller rather than going with the socket
900
937
  imqToRemove
901
- .destroy()
938
+ .drain()
939
+ .then(() => imqToRemove.destroy())
902
940
  .catch((err) => this.verbose(`Error destroying removed server: ${err}`));
903
941
  }
904
942
  this.imqLength = this.imqs.length;
@@ -323,17 +323,34 @@ export interface IMQOptions extends Partial<IMessageQueueConnection> {
323
323
  * to `false`.
324
324
  *
325
325
  * @remarks
326
- * Must be set identically on every producer and consumer of a queue: a
327
- * mismatch makes deserialization fail, which emits an `error` event with the
328
- * event name `OnMessage` and drops the message — permanently, even under
329
- * {@link IMQOptions.safeDelivery}: a message that cannot be unpacked reaches
330
- * no listener, so nothing is pending on it and its lease is released at
331
- * once. Re-delivering it would only fail the same way.
326
+ * It decides how this queue writes. Every queue reads plain, gzipped and
327
+ * zstd messages alike, so producers and consumers need not agree on it. A
328
+ * consumer older than that reader still has to agree: there a mismatch
329
+ * fails deserialization, emits an `error` event named `OnMessage` and drops
330
+ * the message permanently, even under {@link IMQOptions.safeDelivery}.
331
+ *
332
+ * Every gzipped byte travels as a character of a UTF-8 string, so about
333
+ * half of them take two bytes on the wire;
334
+ * {@link IMQOptions.compressAbove} is usually the better choice.
332
335
  *
333
336
  * Applies to queue messages only. {@link IMessageQueue.publish} and
334
337
  * {@link IMessageQueue.subscribe} payloads are always plain JSON.
335
338
  */
336
339
  useGzip?: boolean;
340
+ /**
341
+ * Compress a queue message with zstd when its JSON is longer than this
342
+ * many characters. `0`, the default, never does. Read from
343
+ * `IMQ_COMPRESS_ABOVE` when not given.
344
+ *
345
+ * @remarks
346
+ * Unlike {@link IMQOptions.useGzip} it need not agree between producer and
347
+ * consumer: every queue reads plain, gzipped and zstd messages alike. Turn
348
+ * it on only once every consumer runs a version that reads zstd, and on
349
+ * Node 22.15 or later; an older Node writes plain JSON whatever it says.
350
+ * {@link IMQOptions.useGzip} wins where both are set. Applies to queue
351
+ * messages only, not to {@link IMessageQueue.publish}.
352
+ */
353
+ compressAbove?: number;
337
354
  /**
338
355
  * Enable guaranteed message delivery. When enabled, reading a message
339
356
  * moves it atomically out of the queue into a worker-owned key instead of
@@ -152,6 +152,20 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
152
152
  * Reader connection associated with this queue instance
153
153
  */
154
154
  private reader?;
155
+ /**
156
+ * The reader's id on the broker, which {@link RedisQueue.drain} unblocks
157
+ * it by from another connection.
158
+ */
159
+ private readerId?;
160
+ /**
161
+ * The read loop running on the reader, settled once it stops.
162
+ */
163
+ private reading?;
164
+ /**
165
+ * Set while {@link RedisQueue.drain} runs: the read loop hands on what it
166
+ * already read and stops instead of reading again.
167
+ */
168
+ private draining;
155
169
  /**
156
170
  * Channel connection associated with this queue instance
157
171
  * Specially designed for client subscriptions to server-emitted events
@@ -274,8 +288,9 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
274
288
  * Serializes a given data object into string
275
289
  *
276
290
  * @param data - the value to serialize; must be JSON-serializable
277
- * @returns the wire representation, gzipped when
278
- * {@link IMQOptions.useGzip} is on
291
+ * @returns the wire representation: gzipped when
292
+ * {@link IMQOptions.useGzip} is on, zstd-compressed when it is
293
+ * longer than {@link IMQOptions.compressAbove}, JSON otherwise
279
294
  */
280
295
  private readonly pack;
281
296
  /**
@@ -283,8 +298,11 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
283
298
  *
284
299
  * @param data - the wire representation, as produced by `pack`
285
300
  * @returns the deserialized value
286
- * @throws when the payload is malformed, or was packed with a different
287
- * {@link IMQOptions.useGzip} setting
301
+ * @throws when the payload is malformed
302
+ *
303
+ * @remarks
304
+ * Reads plain, gzipped and zstd messages alike, whatever this queue's own
305
+ * settings, so writers can change format one at a time.
288
306
  */
289
307
  private readonly unpack;
290
308
  /**
@@ -620,6 +638,34 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
620
638
  * server the same way reports the same value.
621
639
  */
622
640
  get available(): boolean;
641
+ /**
642
+ * Whether the broker answers this queue's writer within the given time.
643
+ *
644
+ * @param timeoutMs - how long to wait for its answer, in milliseconds
645
+ * @returns true where a PING came back in time, false otherwise
646
+ *
647
+ * @remarks
648
+ * A connection that only reports itself ready may sit on a socket nobody
649
+ * answers; this asks the broker itself. Never rejects.
650
+ */
651
+ answers(timeoutMs: number): Promise<boolean>;
652
+ /**
653
+ * Stops reading and hands on every message the reader already took from
654
+ * the broker, before a teardown that would drop the reader at once.
655
+ *
656
+ * @param timeoutMs - how long to wait for the read loop to stop, in
657
+ * milliseconds
658
+ *
659
+ * @remarks
660
+ * The reader is released from its blocking read by `CLIENT UNBLOCK` sent
661
+ * on the writer. A message the broker already handed it is still in the
662
+ * socket, ahead of the release, so it reaches the `message` listeners
663
+ * before the loop stops; nothing further is taken. Without this, a reply
664
+ * popped but not yet read was lost with the socket, and its caller waited
665
+ * out its whole timeout. Never rejects; a host that does not answer is
666
+ * given up on after `timeoutMs`.
667
+ */
668
+ drain(timeoutMs?: number): Promise<void>;
623
669
  /**
624
670
  * Writer connection associated with this queue instance. Shared by every
625
671
  * queue in the process that targets the same {@link RedisQueue.poolKey}.