@imqueue/core 3.5.4 → 3.6.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,27 @@ 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
- 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.
12
+ ## [3.6.0] - 2026-11-12
18
13
 
19
14
  ### Added
20
15
 
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.
27
-
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.
33
-
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.
55
-
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.
16
+ - **zstd for large messages, `compressAbove`.** A queue message whose JSON is
17
+ longer than `compressAbove` characters (or `IMQ_COMPRESS_ABOVE`, when the
18
+ option is not given) is written zstd-compressed at the fastest level, as
19
+ base64 behind a one-character mark. Smaller messages are written as before.
20
+ Off by default. Measured on a real 4.6 MB message: 293 KB on the wire for
21
+ about 3 ms of extra CPU, where `useGzip` gave 491 KB for about 19 ms, and
22
+ gzip's binary string grows by about half again as it is written as UTF-8.
65
23
 
66
24
  ### Changed
67
25
 
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
-
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.
26
+ - **Every queue reads plain, gzipped and zstd messages, whatever its own
27
+ settings.** The format is told apart by the first character, so producer and
28
+ consumer no longer have to agree on `useGzip`, and a fleet can turn
29
+ compression on one writer at a time once every reader runs this version.
30
+ Writing is unchanged unless `compressAbove` is set.
137
31
 
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.
32
+ ## [3.5.4] - 2026-10-07
157
33
 
158
34
  ### Fixed
159
35
 
@@ -183,6 +59,10 @@ release.
183
59
  `CONFIG SET` only when a flag is missing; where `CONFIG` is not permitted this
184
60
  logs the same `events config error` line as at start-up.
185
61
 
62
+ ## [3.5.3] - 2026-09-18
63
+
64
+ ### Fixed
65
+
186
66
  - **A joining host whose first subscription attempt failed stayed silent for the
187
67
  life of the process.** `RedisQueue.subscribe()` records a handler only after
188
68
  the subscribe resolves, so a first failure left that host's handler list
@@ -231,6 +111,59 @@ release.
231
111
  it was found. `restoreSubscription()` now reconciles the connection's listeners
232
112
  to exactly the remembered handlers instead of appending to them.
233
113
 
114
+ ## [3.5.2] - 2026-09-14
115
+
116
+ The clustered subscription changes below are **patch-level bug fixes**: they
117
+ restore additive subscription replay and close lifecycle races without adding a
118
+ public API.
119
+
120
+ ### Added
121
+
122
+ - **Integration specs covering clustered subscription against a real broker**,
123
+ in `test/integration/clusterSubscription.spec.ts`. Unit mocks verify call
124
+ ordering and simulated delivery; these additionally verify Redis subscription
125
+ acknowledgments and actual deliveries. Unlike the TLS specs they do not stand
126
+ up their own server: they use an ambient one at `REDIS_HOST`/`REDIS_PORT` (default
127
+ `127.0.0.1:6379`) and skip, with a reason, when none answers. `npm test` does
128
+ not run them.
129
+
130
+ ### Changed
131
+
132
+ - **Clustered subscribe()/unsubscribe() now serialise per host.** A call can
133
+ block behind an earlier subscription operation on that host that never
134
+ settles. Different hosts proceed independently. Rejected registrations remain
135
+ remembered and may have succeeded on some hosts; **subscribe() is not
136
+ retryable**. Repeating it adds another registration, including on future
137
+ hosts. To rebuild a known set, await unsubscribe() and register that set again.
138
+ Function-identity deduplication would break deliberate additive registrations;
139
+ rolling back a partial fan-out would require tearing down working subscribers.
140
+
141
+ - **Clustered destroy() clears routing membership and subscription state
142
+ synchronously.** Queued work cannot reopen a destroyed host. Teardown bypasses
143
+ subscription chains so a wedged operation cannot hold it up. Concurrent callers
144
+ await the same teardown (including manager removal) and observe the same
145
+ AggregateError if it fails. Every independent host teardown and manager removal
146
+ is attempted even if others fail. A later destroy() retries only failed tasks;
147
+ successful cleanup is not repeated. Discovery admission closes synchronously
148
+ and stays closed during and after teardown, including retries. A `send()`
149
+ already parked waiting for the first server is rejected as teardown begins,
150
+ rather than waiting out `IMQ_SEND_INIT_TIMEOUT` on a timer that keeps the
151
+ process alive; `send()` and `subscribe()` on a destroyed instance are
152
+ rejected outright instead of stalling or repopulating the cleared state.
153
+ Destroyed instances must not be reused.
154
+
155
+ - **`ClusteredRedisQueue.subscribe()` now rejects a bad channel on an empty
156
+ cluster, where it used to resolve.** Validation lived in the underlying
157
+ queues, so with no servers yet there was nothing to raise it: a second
158
+ channel name, or an empty one, resolved and left the remembered subscription
159
+ naming a channel nothing was subscribed to. The cluster now applies the same
160
+ two checks itself, with the same messages the underlying queue uses, before
161
+ touching any state. An empty cluster is the normal starting point for
162
+ membership discovered at runtime, so a caller that registers before the first
163
+ server arrives will see an error it previously did not.
164
+
165
+ ### Fixed
166
+
234
167
  - **A clustered queue gave a server that joined later only the last-registered
235
168
  subscription handler, silencing every other handler on that host.**
236
169
  `ClusteredRedisQueue` remembered one `{ channel, handler }` pair, so each
@@ -273,6 +206,74 @@ release.
273
206
  they cannot start that host concurrently. Settled startup is released so an
274
207
  explicit later start() can retry.
275
208
 
209
+ ## [3.5.0] - 2026-09-01
210
+
211
+ ### Added
212
+
213
+ - **TLS on connections to the redis broker.** A new `tls` option encrypts every
214
+ connection a queue opens — reader, writer, watcher and subscription alike.
215
+ Pass `true` for Node's defaults, or an object handed to `tls.connect()` as
216
+ given, so a private CA (`ca`) and mutual TLS (`cert`/`key`) both work. The
217
+ option was previously accepted by the type system and dropped on the way to
218
+ the client, which meant the bus could not be encrypted at all.
219
+
220
+ Cluster entries may carry their own `tls`, overriding the cluster-wide one
221
+ for that server alone; an entry that omits it falls back to the top level.
222
+ Per-entry `username` and `password` are still ignored, exactly as before —
223
+ honouring them would change what an existing cluster authenticates with, and
224
+ that has nothing to do with this feature.
225
+
226
+ With `tls` left unset the environment is consulted — `IMQ_REDIS_TLS`,
227
+ `IMQ_REDIS_TLS_CA_FILE`, `IMQ_REDIS_TLS_CERT_FILE`, `IMQ_REDIS_TLS_KEY_FILE`,
228
+ `IMQ_REDIS_TLS_KEY_PASSPHRASE`, `IMQ_REDIS_TLS_SERVERNAME` and
229
+ `IMQ_REDIS_TLS_REJECT_UNAUTHORIZED` — so a deployment can encrypt a fleet
230
+ without a code change. Certificate files are read as the queue is
231
+ constructed, and an unreadable one throws: an unmounted secret stops the
232
+ process rather than leaving it talking to the broker in the clear. Passing
233
+ `tls` explicitly always wins, `tls: false` included, and
234
+ `rejectUnauthorized: false` is warned about because it leaves a connection
235
+ encrypted but unauthenticated.
236
+
237
+ This covers the queue's own connections. `UDPClusterManager` announcements
238
+ remain unauthenticated UDP broadcast and are unaffected.
239
+
240
+ - **Integration specs covering TLS against a real broker**, in
241
+ `test/integration/`, run by `npm run test-integration`. They stand up a
242
+ throwaway TLS-only redis and assert what a mocked `ioredis` cannot: that the
243
+ handshake completes and is verified, that a message crosses it, that the
244
+ connection pool keeps differing TLS configurations apart, and that plaintext,
245
+ an unverifiable certificate and a wrong server name are all refused rather
246
+ than downgraded. They skip themselves, with a reason, wherever
247
+ `redis-server` and `openssl` are not both available, so a checkout without
248
+ redis still passes. `npm test` now globs `test/unit` and does not run them.
249
+
250
+ ### Changed
251
+
252
+ - **Nothing changes for a queue that does not use TLS.** The option is absent
253
+ from `options` unless it was configured, the connection pool key stays the
254
+ plain `host:port`, the redis client is handed no `tls` option, and no new
255
+ warning is emitted. The only added work on that path is one environment
256
+ lookup per queue construction, about a microsecond, and nothing at all per
257
+ message. This is covered by its own group of specs rather than left as a
258
+ claim.
259
+
260
+ - **A connection failure no longer takes the process down during teardown.**
261
+ This is a behaviour change for everyone, not only TLS users: a socket that
262
+ reported a second failure after the one that closed it used to reach an
263
+ `error` with no listener and terminate the process. Such a process now stays
264
+ up, and the failure is still logged and emitted as it always was. Nothing
265
+ that previously succeeded behaves differently; a crash becomes a log line.
266
+
267
+ - **Shared writer and watcher connections are now keyed by TLS configuration as
268
+ well as by `host:port`.** These connections are shared per server within a
269
+ process; queues reaching one server under different TLS configurations now get
270
+ separate connections, so a queue that asked for encryption can never be handed
271
+ a plaintext socket another queue opened first, nor the reverse. Configurations
272
+ equal by value still share, and the public `redisKey` still reports the plain
273
+ `host:port` address.
274
+
275
+ ### Fixed
276
+
276
277
  - **A failed connection could crash the process as it was being torn down.**
277
278
  The redis client guards its socket with a one-shot `error` listener, which
278
279
  the failure that brings the connection down spends. A socket that goes on to
@@ -287,6 +288,46 @@ release.
287
288
  service started against a broker it cannot verify would reject `start()` and
288
289
  then die inside `destroy()` rather than reporting the misconfiguration.
289
290
 
291
+ ## [3.4.3] - 2026-08-30
292
+
293
+ ### Changed
294
+
295
+ - **`safeDeliveryTtl` is now the longest a message may be worked on**, and its
296
+ default moves from `5000` to `300000`. It used to be a hand-off recovery
297
+ deadline, which meant it bounded nothing that mattered: the key was deleted at
298
+ dispatch, so it never covered processing at all. It now bounds processing,
299
+ which is the only thing that recovers a message from a worker that is alive,
300
+ connected and serving other messages while one handler has wedged on this one.
301
+ Liveness cannot see that case, and restarting an otherwise healthy process is
302
+ not a recovery strategy.
303
+
304
+ Set it to the longest a handler in this system can legitimately take, with
305
+ headroom — a slow upstream is the usual reason for a large value, such as a
306
+ data vendor with no job API or screen-scraping behind an HTTP call. Too low
307
+ and a message is reclaimed from a worker still legitimately working on it.
308
+
309
+ The default rose because the meaning changed: 5000 was a sane hand-off
310
+ deadline and is a poor processing budget.
311
+
312
+ - **The maintenance sweep now runs on `watcherCheckDelay`** (5000 ms by
313
+ default) rather than on `safeDeliveryTtl`. How long a message may be worked on
314
+ and how often the watcher looks for abandoned ones are different questions,
315
+ and tying them would make a crashed worker's message wait out a budget meant
316
+ for a live one. `watcherCheckDelay` is therefore the worst-case latency for a
317
+ crashed worker's message coming back; with the watcher check disabled the
318
+ sweep falls back to `safeDeliveryTtl`.
319
+
320
+ - **The reader's blocking pop is half `safeDeliveryTtl` capped at 5000 ms.** A
321
+ lease deadline is stamped before the pop that fills the key, so an uncapped
322
+ wait would hand a message a sizeable part of its budget already spent. At the
323
+ old defaults both of these resolve to exactly what they were.
324
+
325
+ - The safe-delivery changes above alter meanings and defaults only —
326
+ `safeDelivery`, `safeDeliveryTtl` and `watcherCheckDelay` are the same three
327
+ options they were.
328
+
329
+ ### Fixed
330
+
290
331
  - **`safeDelivery` lost a message when a worker died mid-handler.** It released
291
332
  the message's worker key the instant the message was dispatched to the
292
333
  `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.6.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",
@@ -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
@@ -274,8 +274,9 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
274
274
  * Serializes a given data object into string
275
275
  *
276
276
  * @param data - the value to serialize; must be JSON-serializable
277
- * @returns the wire representation, gzipped when
278
- * {@link IMQOptions.useGzip} is on
277
+ * @returns the wire representation: gzipped when
278
+ * {@link IMQOptions.useGzip} is on, zstd-compressed when it is
279
+ * longer than {@link IMQOptions.compressAbove}, JSON otherwise
279
280
  */
280
281
  private readonly pack;
281
282
  /**
@@ -283,8 +284,11 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
283
284
  *
284
285
  * @param data - the wire representation, as produced by `pack`
285
286
  * @returns the deserialized value
286
- * @throws when the payload is malformed, or was packed with a different
287
- * {@link IMQOptions.useGzip} setting
287
+ * @throws when the payload is malformed
288
+ *
289
+ * @remarks
290
+ * Reads plain, gzipped and zstd messages alike, whatever this queue's own
291
+ * settings, so writers can change format one at a time.
288
292
  */
289
293
  private readonly unpack;
290
294
  /**
package/src/RedisQueue.js CHANGED
@@ -59,7 +59,7 @@ import { EventEmitter } from 'node:events';
59
59
  import { randomUUID } from 'node:crypto';
60
60
  import { hostname } from 'node:os';
61
61
  import { IMQMode, profile, } from './index.js';
62
- import { buildOptions, escapeRegExp, randomInt, pack, sha1, unpack, envInt, envTls, tlsFingerprint, errorCode, LOG_MAX_KEYS, } from './helpers/index.js';
62
+ import { buildOptions, escapeRegExp, randomInt, packer, sha1, unpackAny, envInt, envTls, tlsFingerprint, errorCode, LOG_MAX_KEYS, } from './helpers/index.js';
63
63
  import Redis from './redis.js';
64
64
  const RX_CLIENT_NAME = /name=(\S+)/g;
65
65
  const RX_CLIENT_TEST = /:(reader|writer|watcher)/;
@@ -410,8 +410,9 @@ let RedisQueue = (() => {
410
410
  * Serializes a given data object into string
411
411
  *
412
412
  * @param data - the value to serialize; must be JSON-serializable
413
- * @returns the wire representation, gzipped when
414
- * {@link IMQOptions.useGzip} is on
413
+ * @returns the wire representation: gzipped when
414
+ * {@link IMQOptions.useGzip} is on, zstd-compressed when it is
415
+ * longer than {@link IMQOptions.compressAbove}, JSON otherwise
415
416
  */
416
417
  pack;
417
418
  /**
@@ -419,8 +420,11 @@ let RedisQueue = (() => {
419
420
  *
420
421
  * @param data - the wire representation, as produced by `pack`
421
422
  * @returns the deserialized value
422
- * @throws when the payload is malformed, or was packed with a different
423
- * {@link IMQOptions.useGzip} setting
423
+ * @throws when the payload is malformed
424
+ *
425
+ * @remarks
426
+ * Reads plain, gzipped and zstd messages alike, whatever this queue's own
427
+ * settings, so writers can change format one at a time.
424
428
  */
425
429
  unpack;
426
430
  /**
@@ -476,8 +480,11 @@ let RedisQueue = (() => {
476
480
  this.options.tls = fromEnv;
477
481
  }
478
482
  }
479
- this.pack = this.options.useGzip ? pack : JSON.stringify;
480
- this.unpack = this.options.useGzip ? unpack : JSON.parse;
483
+ if (this.options.compressAbove === undefined) {
484
+ this.options.compressAbove = envInt('IMQ_COMPRESS_ABOVE', 0);
485
+ }
486
+ this.pack = packer(!!this.options.useGzip, this.options.compressAbove);
487
+ this.unpack = unpackAny;
481
488
  this.redisKey = `${this.options.host}:${this.options.port}`;
482
489
  this.poolKey = this.options.tls
483
490
  ? `${this.redisKey}#${tlsFingerprint(this.options.tls)}`
@@ -0,0 +1,38 @@
1
+ /**
2
+ * What a zstd-compressed message starts with. A JSON envelope starts with
3
+ * `{` and a gzipped one with `\x1f`, so one character tells the three apart.
4
+ */
5
+ export declare const ZSTD_MARK = "Z";
6
+ /** Whether this Node can write and read zstd at all (22.15 and later). */
7
+ export declare const ZSTD_AVAILABLE: boolean;
8
+ /**
9
+ * Builds the serializer a queue writes with.
10
+ *
11
+ * @param useGzip - gzip every message, as {@link IMQOptions.useGzip} says
12
+ * @param compressAbove - zstd any message whose JSON is longer than this many
13
+ * characters; `0` never does
14
+ * @returns the serializer
15
+ *
16
+ * @remarks
17
+ * zstd at its fastest level shrinks a 4.6 MB description about sixteen times
18
+ * for about 3 ms of CPU, and is skipped below the threshold, where a message
19
+ * is cheaper to send than to compress. The compressed bytes travel as base64,
20
+ * because the queue reads strings and a binary string does not survive the
21
+ * UTF-8 round trip unchanged in size.
22
+ */
23
+ export declare function packer(useGzip: boolean, compressAbove: number): (data: unknown) => string;
24
+ /**
25
+ * Reads a message in whichever of the three formats it was written: plain
26
+ * JSON, gzip, or zstd.
27
+ *
28
+ * @param data - the message as read off the queue
29
+ * @returns the deserialized value
30
+ * @throws when the message is malformed, or is zstd on a Node that cannot
31
+ * read it
32
+ *
33
+ * @remarks
34
+ * A reader taking every format is what lets a fleet turn compression on one
35
+ * writer at a time: every reader is upgraded first, and no writer has to
36
+ * agree with a reader about a setting.
37
+ */
38
+ export declare function unpackAny(data: string): unknown;
@@ -0,0 +1,98 @@
1
+ /*!
2
+ * Helper: compress — zstd for large messages, and a reader for every format
3
+ *
4
+ * I'm Queue Software Project
5
+ * Copyright (C) 2025 imqueue.com <support@imqueue.com>
6
+ *
7
+ * This program is free software: you can redistribute it and/or modify
8
+ * it under the terms of the GNU General Public License as published by
9
+ * the Free Software Foundation, either version 3 of the License, or
10
+ * (at your option) any later version.
11
+ *
12
+ * This program is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
+ * GNU General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU General Public License
18
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
19
+ *
20
+ * If you want to use this code in a closed source (commercial) project, you can
21
+ * purchase a proprietary commercial license. Please contact us at
22
+ * <support@imqueue.com> to get commercial licensing options.
23
+ */
24
+ import zlib from 'node:zlib';
25
+ import { unpack as gunpack } from './unpack.js';
26
+ /**
27
+ * What a zstd-compressed message starts with. A JSON envelope starts with
28
+ * `{` and a gzipped one with `\x1f`, so one character tells the three apart.
29
+ */
30
+ export const ZSTD_MARK = 'Z';
31
+ const GZIP_MARK = 0x1f;
32
+ /** Whether this Node can write and read zstd at all (22.15 and later). */
33
+ export const ZSTD_AVAILABLE = typeof zlib.zstdCompressSync === 'function' &&
34
+ typeof zlib.zstdDecompressSync === 'function';
35
+ /**
36
+ * Builds the serializer a queue writes with.
37
+ *
38
+ * @param useGzip - gzip every message, as {@link IMQOptions.useGzip} says
39
+ * @param compressAbove - zstd any message whose JSON is longer than this many
40
+ * characters; `0` never does
41
+ * @returns the serializer
42
+ *
43
+ * @remarks
44
+ * zstd at its fastest level shrinks a 4.6 MB description about sixteen times
45
+ * for about 3 ms of CPU, and is skipped below the threshold, where a message
46
+ * is cheaper to send than to compress. The compressed bytes travel as base64,
47
+ * because the queue reads strings and a binary string does not survive the
48
+ * UTF-8 round trip unchanged in size.
49
+ */
50
+ export function packer(useGzip, compressAbove) {
51
+ if (useGzip) {
52
+ return data => zlib.gzipSync(JSON.stringify(data)).toString('binary');
53
+ }
54
+ if (!(compressAbove > 0) || !ZSTD_AVAILABLE) {
55
+ return data => JSON.stringify(data);
56
+ }
57
+ return data => {
58
+ const json = JSON.stringify(data);
59
+ if (json.length <= compressAbove) {
60
+ return json;
61
+ }
62
+ return (ZSTD_MARK +
63
+ zlib
64
+ .zstdCompressSync(Buffer.from(json), {
65
+ params: { [zlib.constants.ZSTD_c_compressionLevel]: 1 },
66
+ })
67
+ .toString('base64'));
68
+ };
69
+ }
70
+ /**
71
+ * Reads a message in whichever of the three formats it was written: plain
72
+ * JSON, gzip, or zstd.
73
+ *
74
+ * @param data - the message as read off the queue
75
+ * @returns the deserialized value
76
+ * @throws when the message is malformed, or is zstd on a Node that cannot
77
+ * read it
78
+ *
79
+ * @remarks
80
+ * A reader taking every format is what lets a fleet turn compression on one
81
+ * writer at a time: every reader is upgraded first, and no writer has to
82
+ * agree with a reader about a setting.
83
+ */
84
+ export function unpackAny(data) {
85
+ if (data.charCodeAt(0) === GZIP_MARK) {
86
+ return gunpack(data);
87
+ }
88
+ if (data.startsWith(ZSTD_MARK)) {
89
+ if (!ZSTD_AVAILABLE) {
90
+ throw new TypeError('IMQ: a zstd message arrived, and this Node cannot read zstd');
91
+ }
92
+ return JSON.parse(zlib
93
+ .zstdDecompressSync(Buffer.from(data.slice(1), 'base64'))
94
+ .toString());
95
+ }
96
+ return JSON.parse(data);
97
+ }
98
+ //# sourceMappingURL=compress.js.map
@@ -26,6 +26,7 @@ export * from './sha1.js';
26
26
  export * from './randomInt.js';
27
27
  export * from './pack.js';
28
28
  export * from './unpack.js';
29
+ export * from './compress.js';
29
30
  export * from './escapeRegExp.js';
30
31
  export * from './copyEventEmitter.js';
31
32
  export * from './envInt.js';
@@ -26,6 +26,7 @@ export * from './sha1.js';
26
26
  export * from './randomInt.js';
27
27
  export * from './pack.js';
28
28
  export * from './unpack.js';
29
+ export * from './compress.js';
29
30
  export * from './escapeRegExp.js';
30
31
  export * from './copyEventEmitter.js';
31
32
  export * from './envInt.js';
@@ -1,9 +0,0 @@
1
- {
2
- "permissions": {
3
- "allow": [
4
- "Bash(timeout 25 node benchmark -m 100 -c 2)",
5
- "Bash(timeout 30 node benchmark -m 100 -c 2)",
6
- "Bash(git -C /home/mikhus/projects/imqueue/core diff)"
7
- ]
8
- }
9
- }