@imqueue/core 3.3.2 → 3.4.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/AGENTS.md CHANGED
@@ -78,6 +78,12 @@ timeout is 15s per test. Run a single spec after a build with
78
78
  notification events. If Redis has the `CONFIG` command disabled (e.g. AWS
79
79
  ElastiCache), keyspace notifications must be enabled out of band:
80
80
  `notify-keyspace-events Ex`.
81
+ - **Keyspace-notification flags are merged, never overwritten.**
82
+ `notify-keyspace-events` is server-global, so `watch()` reads the current
83
+ value and appends only the missing `E`/`x` flags (`A` counts as covering
84
+ `x`), skipping `CONFIG SET` when the config already suffices. Do not go back
85
+ to setting a literal — that silently breaks other consumers of the same
86
+ Redis.
81
87
  - **Messages must be JSON-serializable** (`IJson`/`JsonObject`). Delayed
82
88
  delivery is supported via the send `delay` argument.
83
89
  - Scaling the number of workers must **not** increase Redis traffic — preserve
package/CHANGELOG.md CHANGED
@@ -5,6 +5,78 @@ behavior changes needed a written record; earlier history is in the git log.
5
5
 
6
6
  This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [Unreleased]
9
+
10
+ ### Added
11
+
12
+ - **Silent failures of the transport are now reported without `verbose`.** Every
13
+ line below is written through the configured logger, carries the queue,
14
+ channel or host it is about and never the message payload, the arguments, a
15
+ redis key or an error text. Nothing is scheduled and no timer is added.
16
+
17
+ - A write to redis rejected inside `send()` — the caller already holds the
18
+ message id and gets no rejection, so this was observable only through the
19
+ optional `errorHandler`, which most callers do not pass. Reported as a
20
+ failure episode per queue instance: the first rejected write is logged
21
+ with its operation, message id and code, further rejections are only
22
+ counted, and the first successful write logs the recovery together with
23
+ that count. A failure a redis client delivers twice — through both its
24
+ command callback and its returned promise — is counted once, while
25
+ `errorHandler` keeps being invoked per delivery, exactly as before.
26
+ - Safe reading of a queue ending on anything other than a planned stop,
27
+ reconnect or destroy. A planned stop stays quiet, as before.
28
+ - A failure of the periodic watcher-existence check itself; the failures of
29
+ delayed-message processing and of watcher initialization were already
30
+ logged and are not duplicated.
31
+ - A subscription being established and being restored after a reconnect, and
32
+ a failed reconnection attempt — the absence of the restore line after a
33
+ reconnect is what makes a lost subscription provable.
34
+ - Safe-delivery maintenance disabling itself for good when the writer
35
+ connection is gone.
36
+ - Messages of expired worker leases being re-queued — aggregated per
37
+ processing pass into one line per destination queue with a count — and a
38
+ worker key that could not be deleted: the two causes of a duplicate
39
+ delivery.
40
+ - Keys removed by the built-in cleanup, with the number of candidates and the
41
+ number actually deleted.
42
+ - A publish whose channel has no subscribers, on entering that state, and, in
43
+ a clustered queue, a publish with no server to publish to at all.
44
+ - In a clustered queue: round-robin having no available instance left, and a
45
+ joining server failing to start or to subscribe, with the host and the
46
+ phase.
47
+
48
+ No control flow, return value, redis round-trip or timer was altered, and no
49
+ new public API was added. One deliberate difference: the line reporting a
50
+ worker key that could not be deleted is now written through a contained
51
+ writer, so a logger which itself throws can no longer surface that throw as
52
+ an unhandled rejection — every line of this change is required to be unable
53
+ to influence queue behaviour.
54
+
55
+ A failure code is never taken from the error as it is: only an allow-listed
56
+ code is printed — an `IMQ_`-prefixed framework code, a system `E…` code, a
57
+ small integer, a known redis reply code (`WRONGTYPE`, `NOSCRIPT`,
58
+ `LOADING`, …) or one of a few known redis-client failure messages mapped to
59
+ codes of our own. Everything else, including the error's message, stack and
60
+ class name, is reported as `unknown`.
61
+
62
+ ## [3.3.3] - 2026-08-18
63
+
64
+ ### Fixed
65
+
66
+ - **Starting a queue overwrote the redis keyspace-notification configuration.**
67
+ `notify-keyspace-events` is a server-global setting, and the watcher owner set
68
+ it to the literal `Ex` on every connection establishment. Any other flag —
69
+ enabled by an operator through a config file or by other code sharing the same
70
+ redis — was silently dropped, breaking every consumer that relied on it, and
71
+ coming back after each reconnect.
72
+
73
+ The current value is now read first, only the missing `E`/`x` flags are
74
+ appended, and `CONFIG SET` is skipped entirely when the configuration already
75
+ suffices. `A` is recognised as covering `x`, so a server on `AK` only gains
76
+ `E`. When `CONFIG` is unavailable (e.g. AWS ElastiCache) the read fails and
77
+ the configuration is left untouched — enable `notify-keyspace-events` out of
78
+ band there, as before.
79
+
8
80
  ## [3.2.4] - 2026-07-26
9
81
 
10
82
  ### Fixed
package/README.md CHANGED
@@ -59,6 +59,12 @@ notification events (particularly when using AWS ElasticCache), like this:
59
59
  notify-keyspace-events Ex
60
60
  ```
61
61
 
62
+ Otherwise the queue configures them itself, and does so without disturbing your
63
+ own setup: it reads `notify-keyspace-events`, appends only the flags it is
64
+ missing (`E` and `x`) and leaves everything else — including flags enabled by
65
+ an operator or by other code sharing the same Redis — in place. Any superset of
66
+ `Ex` is accepted as is, so no `CONFIG SET` is issued at all.
67
+
62
68
  More adapters will be added in the future as needed.
63
69
 
64
70
  # Install
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@imqueue/core",
3
- "version": "3.3.2",
3
+ "version": "3.4.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",
@@ -0,0 +1,12 @@
1
+ {
2
+ "signedContributors": [
3
+ {
4
+ "name": "creomobile",
5
+ "id": 25711804,
6
+ "comment_id": 5346986647,
7
+ "created_at": "2026-08-19T19:27:34Z",
8
+ "repoId": 123814024,
9
+ "pullRequestNo": 27
10
+ }
11
+ ]
12
+ }
@@ -107,6 +107,16 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
107
107
  * Total length of RedisQueue instances
108
108
  */
109
109
  private imqLength;
110
+ /**
111
+ * True while round-robin has no available instance left to pick, so that
112
+ * the condition is reported on entry only and not on every send
113
+ */
114
+ private noneAvailable;
115
+ /**
116
+ * True while a publish had no server to publish to, so that the condition
117
+ * is reported on entry only and not on every publish
118
+ */
119
+ private noPublishTargets;
110
120
  /**
111
121
  * Template EventEmitter instance used to replicate queue EventEmitters when
112
122
  * dynamically modifying the cluster
@@ -251,6 +261,20 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
251
261
  */
252
262
  queueLength(): Promise<number>;
253
263
  private verbose;
264
+ /**
265
+ * Writes an unconditional line through this cluster's logger, in the
266
+ * format `verbose()` uses.
267
+ *
268
+ * @param level - logger method to write the line with
269
+ * @param message - the line, which must never carry message payload,
270
+ * call arguments, raw redis keys or an error text
271
+ *
272
+ * @remarks
273
+ * Never throws: a broken logger must not be able to change what the
274
+ * cluster does. Every call site of this reports a state transition or a
275
+ * lifecycle event, so no rate limiting is needed.
276
+ */
277
+ private logLine;
254
278
  /**
255
279
  * Batch imq action processing on all registered imqs at once
256
280
  *
@@ -444,8 +468,9 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
444
468
  *
445
469
  * Publication is not atomic — if any host has no writer connection the call
446
470
  * rejects even though other hosts may already have published. On an empty
447
- * cluster it resolves without publishing anything, and unlike `send()` it does
448
- * not wait for a server to appear.
471
+ * cluster it resolves without publishing anything — reporting that through
472
+ * the logger on entering the state — and unlike `send()` it does not wait
473
+ * for a server to appear.
449
474
  */
450
475
  publish(data: JsonObject, toName?: string): Promise<void>;
451
476
  /**
@@ -23,7 +23,7 @@
23
23
  */
24
24
  import { EventEmitter } from 'node:events';
25
25
  import {} from './ClusterManager.js';
26
- import { buildOptions, copyEventEmitter } from './helpers/index.js';
26
+ import { buildOptions, copyEventEmitter, 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
@@ -92,6 +92,16 @@ export class ClusteredRedisQueue {
92
92
  * Total length of RedisQueue instances
93
93
  */
94
94
  imqLength = 0;
95
+ /**
96
+ * True while round-robin has no available instance left to pick, so that
97
+ * the condition is reported on entry only and not on every send
98
+ */
99
+ noneAvailable = false;
100
+ /**
101
+ * True while a publish had no server to publish to, so that the condition
102
+ * is reported on entry only and not on every publish
103
+ */
104
+ noPublishTargets = false;
95
105
  /**
96
106
  * Template EventEmitter instance used to replicate queue EventEmitters when
97
107
  * dynamically modifying the cluster
@@ -243,9 +253,19 @@ export class ClusteredRedisQueue {
243
253
  const candidate = this.imqs[index];
244
254
  if (candidate.available) {
245
255
  this.currentQueue = index + 1;
256
+ this.noneAvailable = false;
246
257
  return candidate;
247
258
  }
248
259
  }
260
+ // every instance reports its connection as not ready, so the message
261
+ // goes to a host known to be down. Reported on entering the state
262
+ // only, and the flag is cleared by the first successful pick above,
263
+ // so a second outage after a recovery is visible again
264
+ if (!this.noneAvailable) {
265
+ this.noneAvailable = true;
266
+ this.logLine('warn', `no available instance out of ${count}, sending to an ` +
267
+ 'instance which is known to be down');
268
+ }
249
269
  this.currentQueue = start + 1;
250
270
  return this.imqs[start];
251
271
  }
@@ -326,6 +346,27 @@ export class ClusteredRedisQueue {
326
346
  this.logger.info(`[IMQ-CORE][ClusteredRedisQueue][${this.name}]: ${message}`);
327
347
  }
328
348
  }
349
+ /**
350
+ * Writes an unconditional line through this cluster's logger, in the
351
+ * format `verbose()` uses.
352
+ *
353
+ * @param level - logger method to write the line with
354
+ * @param message - the line, which must never carry message payload,
355
+ * call arguments, raw redis keys or an error text
356
+ *
357
+ * @remarks
358
+ * Never throws: a broken logger must not be able to change what the
359
+ * cluster does. Every call site of this reports a state transition or a
360
+ * lifecycle event, so no rate limiting is needed.
361
+ */
362
+ logLine(level, message) {
363
+ try {
364
+ this.logger[level](`[IMQ-CORE][ClusteredRedisQueue][${this.name}]: ${message}`);
365
+ }
366
+ catch {
367
+ // a failing logger must never influence cluster behaviour
368
+ }
369
+ }
329
370
  /**
330
371
  * Batch imq action processing on all registered imqs at once
331
372
  *
@@ -579,14 +620,27 @@ export class ClusteredRedisQueue {
579
620
  *
580
621
  * Publication is not atomic — if any host has no writer connection the call
581
622
  * rejects even though other hosts may already have published. On an empty
582
- * cluster it resolves without publishing anything, and unlike `send()` it does
583
- * not wait for a server to appear.
623
+ * cluster it resolves without publishing anything — reporting that through
624
+ * the logger on entering the state — and unlike `send()` it does not wait
625
+ * for a server to appear.
584
626
  */
585
627
  async publish(data, toName) {
586
628
  const promises = [];
587
629
  for (const imq of this.imqs) {
588
630
  promises.push(imq.publish(data, toName));
589
631
  }
632
+ // an empty cluster resolves an empty Promise.all, so the caller is
633
+ // told the event went out while nothing was published at all.
634
+ // Reported on entering the state only
635
+ if (!promises.length) {
636
+ if (!this.noPublishTargets) {
637
+ this.noPublishTargets = true;
638
+ this.logLine('error', `nothing published to channel ${toName || this.name}: knownServers=0`);
639
+ }
640
+ }
641
+ else {
642
+ this.noPublishTargets = false;
643
+ }
590
644
  await Promise.all(promises);
591
645
  }
592
646
  /**
@@ -722,11 +776,27 @@ export class ClusteredRedisQueue {
722
776
  }
723
777
  async initializeQueue(imq) {
724
778
  this.verbose(`Initializing queue with state: ${JSON.stringify(this.state)}`);
779
+ // both failures are reported here, inside the function, and the
780
+ // value is re-thrown as it was: the caller starts this without
781
+ // awaiting it, so a new .catch() would either swallow the failure or
782
+ // add a second unhandled rejection
725
783
  if (this.state.started) {
726
- await imq.start();
784
+ try {
785
+ await imq.start();
786
+ }
787
+ catch (err) {
788
+ this.logLine('error', `server ${imq.redisKey} failed to start, code ${errorCode(err)}: the node is not ready to serve queues`);
789
+ throw err;
790
+ }
727
791
  }
728
792
  if (this.state.subscription) {
729
- await imq.subscribe(this.state.subscription.channel, this.state.subscription.handler);
793
+ try {
794
+ await imq.subscribe(this.state.subscription.channel, this.state.subscription.handler);
795
+ }
796
+ catch (err) {
797
+ this.logLine('error', `server ${imq.redisKey} failed to subscribe to channel ${this.state.subscription.channel}, code ${errorCode(err)}: events from this node will never arrive`);
798
+ throw err;
799
+ }
730
800
  }
731
801
  }
732
802
  findServer(server) {
@@ -181,6 +181,21 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
181
181
  * Guards overlapping watcher check runs
182
182
  */
183
183
  private watcherCheckBusy;
184
+ /**
185
+ * Number of rejected writes in the current failure episode of this
186
+ * instance's writer, zero while writes succeed. The first rejection of an
187
+ * episode is logged, the rest only counted, and the first successful
188
+ * write logs the recovery together with this count.
189
+ */
190
+ private rejectedWrites;
191
+ /**
192
+ * Channels a publish currently finds no subscribers on, so that the
193
+ * condition is reported on entry only and not on every publish. Bounded
194
+ * by {@link LOG_MAX_KEYS}: channel names may arrive as unique values, so
195
+ * names above the bound are not remembered and their publishes are
196
+ * reported every time.
197
+ */
198
+ private readonly noSubscribers;
184
199
  /**
185
200
  * Connected client keys seen during the previous cleanup sweep. Used
186
201
  * to give temporarily disconnected clients one sweep of grace before
@@ -255,6 +270,36 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
255
270
  */
256
271
  name: string, options?: Partial<IMQOptions>, mode?: IMQMode);
257
272
  private verbose;
273
+ /**
274
+ * Writes an unconditional line through this queue's logger, in the format
275
+ * `verbose()` uses.
276
+ *
277
+ * @param level - logger method to write the line with
278
+ * @param message - the line, which must never carry message payload,
279
+ * call arguments, raw redis keys or an error text
280
+ *
281
+ * @remarks
282
+ * Never throws: a broken logger must not be able to change what the queue
283
+ * does.
284
+ */
285
+ private logLine;
286
+ /**
287
+ * Records one logical rejected write of this instance's writer: the first
288
+ * rejection of a failure episode writes the given line, every following
289
+ * one only increments the episode counter, and the counter is reported by
290
+ * {@link RedisQueue.recordWriteSuccess} when a write succeeds again.
291
+ *
292
+ * @param message - the line, under the same constraints as
293
+ * {@link RedisQueue.logLine}
294
+ */
295
+ private recordWriteFailure;
296
+ /**
297
+ * Closes the current write-failure episode, if one is open: reports how
298
+ * many writes were rejected in it and resets the counter. The counter is
299
+ * reset before the logger is touched, so a broken logger cannot keep the
300
+ * episode open forever.
301
+ */
302
+ private recordWriteSuccess;
258
303
  /**
259
304
  * Creates a subscription channel over redis and sets up channel
260
305
  * data read handler. The effective Redis channel is `<prefix>:<channel>`.
@@ -324,8 +369,9 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
324
369
  * allowed in any {@link IMQMode}, including `WORKER`.
325
370
  *
326
371
  * The payload is always plain JSON — {@link IMQOptions.useGzip} applies to
327
- * queue messages only. Redis pub/sub drops the message silently when nobody
328
- * is subscribed.
372
+ * queue messages only. Redis pub/sub drops the message when nobody is
373
+ * subscribed; on entering that state the queue writes a warning through
374
+ * its logger, so the drop is no longer silent.
329
375
  */
330
376
  publish(data: JsonObject, toName?: string): Promise<void>;
331
377
  /**
@@ -387,9 +433,12 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
387
433
  * schedule — the message is released by the watcher, so availability
388
434
  * may lag by up to {@link IMQOptions.watcherCheckDelay}. A delay of
389
435
  * `0` or `undefined` sends immediately.
390
- * @param errorHandler - invoked when the write to Redis fails; this is the
391
- * only way to observe such a failure, since the returned promise does
392
- * not reject for it
436
+ * @param errorHandler - invoked when the write to Redis fails; the returned
437
+ * promise does not reject for it, so this is the only programmatic
438
+ * way to observe such a failure. The failure is also reported
439
+ * through the queue's logger: the first rejected write of a failure
440
+ * episode is logged, the rest are counted, and the first successful
441
+ * write logs the recovery with that count
393
442
  * @returns the identifier assigned to the message. It is generated locally
394
443
  * before the write is issued, so it is available even if the write
395
444
  * later fails.
@@ -628,6 +677,38 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
628
677
  * Clears safe check interval
629
678
  */
630
679
  private cleanSafeCheckInterval;
680
+ /**
681
+ * Reads the keyspace-notification flags currently configured on the
682
+ * server.
683
+ *
684
+ * @returns the raw flags string, or an empty string when notifications
685
+ * are disabled
686
+ *
687
+ * @remarks
688
+ * `CONFIG GET` replies as a flat `[name, value]` array over RESP2 and as a
689
+ * map over RESP3, so both shapes are accepted.
690
+ */
691
+ private currentKeyspaceEvents;
692
+ /**
693
+ * Returns the flags from {@link NOTIFY_EVENTS_REQUIRED} that the given
694
+ * configuration does not already provide.
695
+ *
696
+ * @param current - flags string as reported by `CONFIG GET`
697
+ */
698
+ private missingKeyspaceEvents;
699
+ /**
700
+ * Makes sure the server publishes the keyspace events this queue listens
701
+ * for, preserving whatever else is already configured.
702
+ *
703
+ * @remarks
704
+ * Flags configured out of band — by an operator, or by other code sharing
705
+ * the same Redis — are kept: only the missing ones are appended, and
706
+ * `CONFIG SET` is skipped entirely when nothing needs adding. When the
707
+ * `CONFIG` command is unavailable (e.g. AWS ElastiCache) the read fails and
708
+ * the error is reported without touching the configuration; enable
709
+ * `notify-keyspace-events` out of band in that case.
710
+ */
711
+ private ensureKeyspaceEvents;
631
712
  /**
632
713
  * Setups watch a process on delayed messages
633
714
  */
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, } from './helpers/index.js';
62
+ import { buildOptions, escapeRegExp, randomInt, pack, sha1, unpack, envInt, 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)/;
@@ -70,6 +70,20 @@ const RECONNECT_BASE_DELAY = 1000;
70
70
  const RECONNECT_MAX_DELAY = 30000;
71
71
  /** SCAN batch size used while sweeping keys */
72
72
  const SCAN_COUNT = '1000';
73
+ /** Redis config parameter holding the keyspace-notification flags */
74
+ const NOTIFY_EVENTS_PARAM = 'notify-keyspace-events';
75
+ /**
76
+ * Keyspace-notification flags this queue depends on: `E` to receive
77
+ * `__keyevent@<db>__` notifications and `x` for expired-key events. Together
78
+ * they drive delayed-message delivery.
79
+ */
80
+ const NOTIFY_EVENTS_REQUIRED = 'Ex';
81
+ /**
82
+ * Event classes Redis' `A` shortcut expands to — every class except the
83
+ * `K`/`E` delivery selectors and the special `m`/`n` classes. A server
84
+ * configured with `A` therefore already covers `x`.
85
+ */
86
+ const NOTIFY_EVENTS_ALL = 'g$lshzxetd';
73
87
  /**
74
88
  * ioredis retry strategy that disables the built-in reconnection — this
75
89
  * queue performs its own capped-backoff reconnection instead.
@@ -274,6 +288,21 @@ let RedisQueue = (() => {
274
288
  * Guards overlapping watcher check runs
275
289
  */
276
290
  watcherCheckBusy = false;
291
+ /**
292
+ * Number of rejected writes in the current failure episode of this
293
+ * instance's writer, zero while writes succeed. The first rejection of an
294
+ * episode is logged, the rest only counted, and the first successful
295
+ * write logs the recovery together with this count.
296
+ */
297
+ rejectedWrites = 0;
298
+ /**
299
+ * Channels a publish currently finds no subscribers on, so that the
300
+ * condition is reported on entry only and not on every publish. Bounded
301
+ * by {@link LOG_MAX_KEYS}: channel names may arrive as unique values, so
302
+ * names above the bound are not remembered and their publishes are
303
+ * reported every time.
304
+ */
305
+ noSubscribers = new Set();
277
306
  /**
278
307
  * Connected client keys seen during the previous cleanup sweep. Used
279
308
  * to give temporarily disconnected clients one sweep of grace before
@@ -383,6 +412,55 @@ let RedisQueue = (() => {
383
412
  this.logger.info(`[IMQ-CORE][${this.name}]: ${message}`);
384
413
  }
385
414
  }
415
+ /**
416
+ * Writes an unconditional line through this queue's logger, in the format
417
+ * `verbose()` uses.
418
+ *
419
+ * @param level - logger method to write the line with
420
+ * @param message - the line, which must never carry message payload,
421
+ * call arguments, raw redis keys or an error text
422
+ *
423
+ * @remarks
424
+ * Never throws: a broken logger must not be able to change what the queue
425
+ * does.
426
+ */
427
+ logLine(level, message) {
428
+ try {
429
+ this.logger[level](`[IMQ-CORE][${this.name}]: ${message}`);
430
+ }
431
+ catch {
432
+ // a failing logger must never influence queue behaviour
433
+ }
434
+ }
435
+ /**
436
+ * Records one logical rejected write of this instance's writer: the first
437
+ * rejection of a failure episode writes the given line, every following
438
+ * one only increments the episode counter, and the counter is reported by
439
+ * {@link RedisQueue.recordWriteSuccess} when a write succeeds again.
440
+ *
441
+ * @param message - the line, under the same constraints as
442
+ * {@link RedisQueue.logLine}
443
+ */
444
+ recordWriteFailure(message) {
445
+ this.rejectedWrites++;
446
+ if (this.rejectedWrites === 1) {
447
+ this.logLine('error', message);
448
+ }
449
+ }
450
+ /**
451
+ * Closes the current write-failure episode, if one is open: reports how
452
+ * many writes were rejected in it and resets the counter. The counter is
453
+ * reset before the logger is touched, so a broken logger cannot keep the
454
+ * episode open forever.
455
+ */
456
+ recordWriteSuccess() {
457
+ if (this.rejectedWrites === 0) {
458
+ return;
459
+ }
460
+ const rejected = this.rejectedWrites;
461
+ this.rejectedWrites = 0;
462
+ this.logLine('info', `outbound writes resumed after ${rejected} rejected writes`);
463
+ }
386
464
  /**
387
465
  * Creates a subscription channel over redis and sets up channel
388
466
  * data read handler. The effective Redis channel is `<prefix>:<channel>`.
@@ -422,6 +500,9 @@ let RedisQueue = (() => {
422
500
  this.attachSubscriptionHandler(chan, handler);
423
501
  this.subscriptionHandlers.push(handler);
424
502
  this.verbose(`Subscribed to ${channel} channel`);
503
+ // a lifecycle fact, not an alarm: flow continuation hangs on this
504
+ // subscription, so its absence after a reconnect must be provable
505
+ this.logLine('info', `subscribed to channel ${channel}`);
425
506
  }
426
507
  /**
427
508
  * Attaches a subscription message handler to a given channel
@@ -457,6 +538,7 @@ let RedisQueue = (() => {
457
538
  this.attachSubscriptionHandler(chan, handler);
458
539
  }
459
540
  this.verbose(`Restored subscription to ${this.subscriptionName}`);
541
+ this.logLine('info', `restored subscription to channel ${this.subscriptionName}`);
460
542
  }
461
543
  /**
462
544
  * Closes the subscription connection and forgets the channel name together
@@ -510,8 +592,9 @@ let RedisQueue = (() => {
510
592
  * allowed in any {@link IMQMode}, including `WORKER`.
511
593
  *
512
594
  * The payload is always plain JSON — {@link IMQOptions.useGzip} applies to
513
- * queue messages only. Redis pub/sub drops the message silently when nobody
514
- * is subscribed.
595
+ * queue messages only. Redis pub/sub drops the message when nobody is
596
+ * subscribed; on entering that state the queue writes a warning through
597
+ * its logger, so the drop is no longer silent.
515
598
  */
516
599
  async publish(data, toName) {
517
600
  if (!this.writer) {
@@ -519,7 +602,24 @@ let RedisQueue = (() => {
519
602
  }
520
603
  const jsonData = JSON.stringify(data);
521
604
  const name = toName || this.name;
522
- await this.writer.publish(`${this.options.prefix}:${name}`, jsonData);
605
+ const receivers = await this.writer.publish(`${this.options.prefix}:${name}`, jsonData);
606
+ // redis replies with the number of subscribers which received the
607
+ // event: zero means nobody did, and events are how a consumer learns
608
+ // to continue its work. Reported on entering the state only, and only
609
+ // on a strict zero - a client whose reply is not a number is left
610
+ // alone rather than coerced, so reading it can neither throw nor
611
+ // invent a warning
612
+ if (receivers === 0) {
613
+ if (!this.noSubscribers.has(name)) {
614
+ if (this.noSubscribers.size < LOG_MAX_KEYS) {
615
+ this.noSubscribers.add(name);
616
+ }
617
+ this.logLine('warn', `published to channel ${name} on host ${this.redisKey} with no subscribers`);
618
+ }
619
+ }
620
+ else {
621
+ this.noSubscribers.delete(name);
622
+ }
523
623
  this.verbose(`Published message to ${name} channel, data: ${jsonData}
524
624
  `);
525
625
  }
@@ -635,7 +735,22 @@ let RedisQueue = (() => {
635
735
  }
636
736
  this.watcherCheckBusy = true;
637
737
  try {
638
- if (!(await this.watcherCount())) {
738
+ let watchers;
739
+ try {
740
+ watchers = await this.watcherCount();
741
+ }
742
+ catch (err) {
743
+ // the only silent failure of this tick: initWatcher() and
744
+ // processDelayed() log their own errors unconditionally, so
745
+ // wrapping the whole body would just duplicate them. The
746
+ // value is re-thrown, leaving control flow as it was
747
+ // bounded by watcherCheckDelay: this tick runs on an
748
+ // interval, so a persistent failure repeats at that pace
749
+ const code = errorCode(err);
750
+ this.logLine('warn', `watcher check failed, code ${code}`);
751
+ throw err;
752
+ }
753
+ if (!watchers) {
639
754
  await this.initWatcher();
640
755
  }
641
756
  if (this.isWorker()) {
@@ -668,9 +783,12 @@ let RedisQueue = (() => {
668
783
  * schedule — the message is released by the watcher, so availability
669
784
  * may lag by up to {@link IMQOptions.watcherCheckDelay}. A delay of
670
785
  * `0` or `undefined` sends immediately.
671
- * @param errorHandler - invoked when the write to Redis fails; this is the
672
- * only way to observe such a failure, since the returned promise does
673
- * not reject for it
786
+ * @param errorHandler - invoked when the write to Redis fails; the returned
787
+ * promise does not reject for it, so this is the only programmatic
788
+ * way to observe such a failure. The failure is also reported
789
+ * through the queue's logger: the first rejected write of a failure
790
+ * episode is logged, the rest are counted, and the first successful
791
+ * write logs the recovery with that count
674
792
  * @returns the identifier assigned to the message. It is generated locally
675
793
  * before the write is issued, so it is available even if the write
676
794
  * later fails.
@@ -700,9 +818,22 @@ let RedisQueue = (() => {
700
818
  const data = { id, message, from: this.name };
701
819
  const key = `${this.options.prefix}:${toQueue}`;
702
820
  const packet = this.pack(data);
821
+ const countedOps = new Set();
703
822
  const onWriteError = (error, op) => {
704
823
  if (error) {
705
824
  this.verbose(`Writer ${op} error: ${error}`);
825
+ // the caller already holds the message id and gets no
826
+ // rejection, so without this line a rejected write is
827
+ // observable through errorHandler only - and most callers
828
+ // pass none. A client may deliver the same failure through
829
+ // both its callback and its returned promise: the episode
830
+ // counts each logical failure once, while errorHandler keeps
831
+ // being invoked per delivery, exactly as it always was
832
+ if (!countedOps.has(op)) {
833
+ countedOps.add(op);
834
+ this.recordWriteFailure(`write to queue ${toQueue} rejected on ${op}, ` +
835
+ `message ${id}, code ${errorCode(error)}`);
836
+ }
706
837
  if (errorHandler) {
707
838
  errorHandler(error instanceof Error
708
839
  ? error
@@ -722,6 +853,10 @@ let RedisQueue = (() => {
722
853
  onWriteError(err, 'SET');
723
854
  return;
724
855
  }
856
+ // a delayed send is complete only after both
857
+ // ZADD and SET succeeded, so the episode is
858
+ // closed here and not on the ZADD alone
859
+ this.recordWriteSuccess();
725
860
  })
726
861
  .catch((err) => onWriteError(err, 'SET'));
727
862
  });
@@ -731,6 +866,9 @@ let RedisQueue = (() => {
731
866
  if (err) {
732
867
  onWriteError(err, 'LPUSH');
733
868
  }
869
+ else {
870
+ this.recordWriteSuccess();
871
+ }
734
872
  });
735
873
  // guard against unhandled rejections from promise-returning
736
874
  // client implementations in fire-and-forget mode
@@ -1174,6 +1312,9 @@ let RedisQueue = (() => {
1174
1312
  catch (err) {
1175
1313
  this.reconnecting[channel] = false;
1176
1314
  this.verbose(`Reconnect ${channel} failed: ${err}`);
1315
+ // bounded by the exponential reconnection backoff, so a redis
1316
+ // which stays down cannot make this line flood the log
1317
+ this.logLine('warn', `reconnect of the ${channel} channel failed, code ${errorCode(err)}`);
1177
1318
  this.scheduleReconnect(channel);
1178
1319
  }
1179
1320
  }
@@ -1322,19 +1463,52 @@ let RedisQueue = (() => {
1322
1463
  if (!keys.length) {
1323
1464
  return;
1324
1465
  }
1466
+ const requeued = new Map();
1325
1467
  this.verbose(`Watching ${keys.length} keys: ${keys
1326
1468
  .map(key => `"${key}"`)
1327
1469
  .join(', ')}`);
1328
- for (const key of keys) {
1329
- const kp = key.split(':');
1330
- // the last key segment is the worker's lease deadline: only
1331
- // re-queue messages of workers whose lease has expired (the
1332
- // worker died mid-processing); fresh leases belong to live
1333
- // workers and must not be touched
1334
- if (Number(kp.pop()) >= now) {
1335
- continue;
1470
+ try {
1471
+ for (const key of keys) {
1472
+ const kp = key.split(':');
1473
+ // the last key segment is the worker's lease deadline: only
1474
+ // re-queue messages of workers whose lease has expired (the
1475
+ // worker died mid-processing); fresh leases belong to live
1476
+ // workers and must not be touched
1477
+ if (Number(kp.pop()) >= now) {
1478
+ continue;
1479
+ }
1480
+ const target = `${kp.shift()}:${kp.shift()}`;
1481
+ const moved = await this.writer.lmove(key, target, 'RIGHT', 'LEFT');
1482
+ // a non-empty result means a message whose lease expired is being
1483
+ // delivered a second time - either its worker died or it took
1484
+ // longer than the lease ttl. This is one of the two explanations
1485
+ // a handler can be given for a duplicate, the other being a
1486
+ // worker key that could not be deleted. The packed message is
1487
+ // never unpacked here: it carries the payload, and the worker key
1488
+ // is never logged either
1489
+ if (moved) {
1490
+ // the raw target is a redis key and is never printed: when
1491
+ // the exact prefix cannot be stripped off safely (a prefix
1492
+ // carrying ':' breaks the segment arithmetic above), the
1493
+ // queue is reported as unknown rather than leaked
1494
+ const stripped = `${this.options.prefix}:`;
1495
+ const queue = target.startsWith(stripped) &&
1496
+ target.length > stripped.length
1497
+ ? target.slice(stripped.length)
1498
+ : 'unknown';
1499
+ requeued.set(queue, (requeued.get(queue) || 0) + 1);
1500
+ }
1501
+ }
1502
+ }
1503
+ finally {
1504
+ // one line per queue for the whole pass: a backlog of expired
1505
+ // leases is reported as a count instead of a line per message.
1506
+ // Written in a finally so that re-queues which did happen stay
1507
+ // reported even when a later move of the pass throws - the
1508
+ // exception itself keeps escaping exactly as before
1509
+ for (const [queue, count] of requeued) {
1510
+ this.logLine('warn', `re-queued ${count} messages of expired leases to queue ${queue}`);
1336
1511
  }
1337
- await this.writer.lmove(key, `${kp.shift()}:${kp.shift()}`, 'RIGHT', 'LEFT');
1338
1512
  }
1339
1513
  }
1340
1514
  /**
@@ -1364,6 +1538,71 @@ let RedisQueue = (() => {
1364
1538
  delete this.safeCheckInterval;
1365
1539
  }
1366
1540
  }
1541
+ /**
1542
+ * Reads the keyspace-notification flags currently configured on the
1543
+ * server.
1544
+ *
1545
+ * @returns the raw flags string, or an empty string when notifications
1546
+ * are disabled
1547
+ *
1548
+ * @remarks
1549
+ * `CONFIG GET` replies as a flat `[name, value]` array over RESP2 and as a
1550
+ * map over RESP3, so both shapes are accepted.
1551
+ */
1552
+ async currentKeyspaceEvents() {
1553
+ const reply = (await this.writer.config('GET', NOTIFY_EVENTS_PARAM));
1554
+ if (!reply) {
1555
+ return '';
1556
+ }
1557
+ let value;
1558
+ if (Array.isArray(reply)) {
1559
+ const at = reply.indexOf(NOTIFY_EVENTS_PARAM);
1560
+ // an unnamed parameter means the reply is not what was asked for,
1561
+ // and guessing the value out of it could only make things worse
1562
+ value = at < 0 ? undefined : reply[at + 1];
1563
+ }
1564
+ else {
1565
+ value = reply[NOTIFY_EVENTS_PARAM];
1566
+ }
1567
+ return typeof value === 'string' ? value : '';
1568
+ }
1569
+ /**
1570
+ * Returns the flags from {@link NOTIFY_EVENTS_REQUIRED} that the given
1571
+ * configuration does not already provide.
1572
+ *
1573
+ * @param current - flags string as reported by `CONFIG GET`
1574
+ */
1575
+ missingKeyspaceEvents(current) {
1576
+ const covered = current.includes('A')
1577
+ ? current + NOTIFY_EVENTS_ALL
1578
+ : current;
1579
+ return [...NOTIFY_EVENTS_REQUIRED]
1580
+ .filter(flag => !covered.includes(flag))
1581
+ .join('');
1582
+ }
1583
+ /**
1584
+ * Makes sure the server publishes the keyspace events this queue listens
1585
+ * for, preserving whatever else is already configured.
1586
+ *
1587
+ * @remarks
1588
+ * Flags configured out of band — by an operator, or by other code sharing
1589
+ * the same Redis — are kept: only the missing ones are appended, and
1590
+ * `CONFIG SET` is skipped entirely when nothing needs adding. When the
1591
+ * `CONFIG` command is unavailable (e.g. AWS ElastiCache) the read fails and
1592
+ * the error is reported without touching the configuration; enable
1593
+ * `notify-keyspace-events` out of band in that case.
1594
+ */
1595
+ async ensureKeyspaceEvents() {
1596
+ const current = await this.currentKeyspaceEvents();
1597
+ const missing = this.missingKeyspaceEvents(current);
1598
+ if (!missing) {
1599
+ this.verbose(`Keyspace events "${current}" already cover ` +
1600
+ `"${NOTIFY_EVENTS_REQUIRED}", keeping them as is`);
1601
+ return;
1602
+ }
1603
+ this.verbose(`Adding "${missing}" to keyspace events "${current}"`);
1604
+ await this.writer.config('SET', NOTIFY_EVENTS_PARAM, current + missing);
1605
+ }
1367
1606
  /**
1368
1607
  * Setups watch a process on delayed messages
1369
1608
  */
@@ -1371,14 +1610,7 @@ let RedisQueue = (() => {
1371
1610
  if (!this.writer || !this.watcher || this.watcher.__ready__) {
1372
1611
  return this;
1373
1612
  }
1374
- try {
1375
- this.writer
1376
- .config('SET', 'notify-keyspace-events', 'Ex')
1377
- .catch((err) => this.emitError('OnConfig', 'events config error', err));
1378
- }
1379
- catch (err) {
1380
- this.emitError('OnConfig', 'events config error', err);
1381
- }
1613
+ this.ensureKeyspaceEvents().catch((err) => this.emitError('OnConfig', 'events config error', err));
1382
1614
  this.watcher.on('pmessage', this.onWatchMessage.bind(this));
1383
1615
  this.watcher
1384
1616
  .psubscribe('__keyevent@0__:expired', `${this.options.prefix}:delayed:*`)
@@ -1398,6 +1630,14 @@ let RedisQueue = (() => {
1398
1630
  */
1399
1631
  async runSafeCheck() {
1400
1632
  if (!this.writer) {
1633
+ // one line per interval instance, because the interval is
1634
+ // dropped right below and re-armed only by a new watcher
1635
+ // connection: from here on nothing recovers abandoned messages
1636
+ // and nothing prunes orphaned keys
1637
+ const safe = !!this.options.safeDelivery;
1638
+ const cleanup = !!this.options.cleanup;
1639
+ this.logLine('warn', 'safe delivery maintenance stopped: no writer connection, ' +
1640
+ `safeDelivery ${safe}, cleanup ${cleanup}`);
1401
1641
  this.cleanSafeCheckInterval();
1402
1642
  return;
1403
1643
  }
@@ -1445,10 +1685,20 @@ let RedisQueue = (() => {
1445
1685
  }
1446
1686
  }
1447
1687
  if (keysToRemove.length) {
1448
- await this.writer.del(...keysToRemove);
1688
+ const removed = await this.writer.del(...keysToRemove);
1449
1689
  this.verbose(`Keys ${keysToRemove
1450
1690
  .map(k => `"${k}"`)
1451
1691
  .join(', ')} were successfully removed!`);
1692
+ // deleting the keys of a queue considered abandoned is
1693
+ // destructive - a client which was disconnected for two
1694
+ // sweeps loses its queue together with a response it still
1695
+ // waits for. Neither the keys nor the filter are logged:
1696
+ // they carry application names
1697
+ if (typeof removed === 'number' && removed > 0) {
1698
+ // bounded by the maintenance interval: one line per
1699
+ // cleanup pass at most, and it already aggregates counts
1700
+ this.logLine('warn', `cleanup removed ${removed} of ${keysToRemove.length} candidate keys`);
1701
+ }
1452
1702
  }
1453
1703
  }
1454
1704
  catch (err) {
@@ -1514,8 +1764,31 @@ let RedisQueue = (() => {
1514
1764
  try {
1515
1765
  msg = await this.reader.blmove(this.key, workerKey, 'RIGHT', 'LEFT', timeout);
1516
1766
  }
1517
- catch {
1518
- // reader connection ended (stop/reconnect)
1767
+ catch (err) {
1768
+ // a closed or ended reader connection is the planned case -
1769
+ // the queue is stopping, reconnecting or being destroyed,
1770
+ // and stop() drops the reader socket on purpose - so it
1771
+ // stays quiet. Anything else ends safe reading for good,
1772
+ // which must not be silent: the process stays alive and
1773
+ // simply consumes nothing
1774
+ let planned = this.destroyed || !this.reader;
1775
+ if (!planned) {
1776
+ try {
1777
+ planned =
1778
+ err instanceof Error &&
1779
+ /Stream connection ended|Connection is closed/i.test(err.message);
1780
+ }
1781
+ catch {
1782
+ // a message getter which throws is read as an
1783
+ // unexpected failure - before this catch existed,
1784
+ // such a value would have escaped readSafe() as an
1785
+ // unhandled rejection
1786
+ planned = false;
1787
+ }
1788
+ }
1789
+ if (!planned) {
1790
+ this.logLine('warn', `safe reading of queue ${this.name} stopped, code ${errorCode(err)}`);
1791
+ }
1519
1792
  break;
1520
1793
  }
1521
1794
  if (msg === null || msg === undefined) {
@@ -1524,9 +1797,12 @@ let RedisQueue = (() => {
1524
1797
  }
1525
1798
  try {
1526
1799
  this.process([key, msg]);
1527
- this.writer
1528
- .del(workerKey)
1529
- .catch(e => this.logger.warn('OnReadSafe: del error', e));
1800
+ this.writer.del(workerKey).catch((err) =>
1801
+ // an undeleted worker key is re-queued by the watcher
1802
+ // later, which is the other cause of a duplicate. The
1803
+ // key itself is never logged: it carries the client
1804
+ // queue name, the lease uuid and its deadline
1805
+ this.logLine('warn', `OnReadSafe: del error, queue ${this.name}, code ${errorCode(err)}`));
1530
1806
  }
1531
1807
  catch (err) {
1532
1808
  // a single message failure must never kill the read loop
@@ -29,3 +29,4 @@ export * from './unpack.js';
29
29
  export * from './escapeRegExp.js';
30
30
  export * from './copyEventEmitter.js';
31
31
  export * from './envInt.js';
32
+ export * from './logging.js';
@@ -29,4 +29,5 @@ export * from './unpack.js';
29
29
  export * from './escapeRegExp.js';
30
30
  export * from './copyEventEmitter.js';
31
31
  export * from './envInt.js';
32
+ export * from './logging.js';
32
33
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,45 @@
1
+ /*!
2
+ * Helper: logging
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
+ /**
25
+ * Upper bound on the number of channel names the no-subscriber transition
26
+ * state of a queue remembers. Channel names arrive as an unbounded stream of
27
+ * unique client-queue names, so the set must not grow with them: names above
28
+ * the bound are simply not remembered.
29
+ */
30
+ export declare const LOG_MAX_KEYS = 128;
31
+ /**
32
+ * Extracts a loggable failure code from an unknown thrown value.
33
+ *
34
+ * @param err - the caught value, of any shape
35
+ * @returns the code, or `unknown` when none can be told safely
36
+ *
37
+ * @remarks
38
+ * Deliberately conservative: only an allow-listed code can come out of here,
39
+ * because an application error reaches this helper too and anything of its own
40
+ * may carry personal data. Recognised are a framework or system `code`, a
41
+ * small numeric `code`, the leading token of a known Redis error reply and a
42
+ * known redis-client failure message. Everything else — including the error's
43
+ * message, its stack and its class name — yields `unknown`. Never throws.
44
+ */
45
+ export declare function errorCode(err: unknown): string;
@@ -0,0 +1,127 @@
1
+ /*!
2
+ * Helper: logging
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
+ /**
25
+ * Upper bound on the number of channel names the no-subscriber transition
26
+ * state of a queue remembers. Channel names arrive as an unbounded stream of
27
+ * unique client-queue names, so the set must not grow with them: names above
28
+ * the bound are simply not remembered.
29
+ */
30
+ export const LOG_MAX_KEYS = 128;
31
+ /**
32
+ * Redis error replies this helper is allowed to quote. The leading token of a
33
+ * Redis error reply is a protocol constant, never data — but only these are
34
+ * recognised, so an arbitrary upper-case first word of some other error's
35
+ * message can never reach the log.
36
+ */
37
+ const REDIS_REPLY_CODES = new Set([
38
+ 'ASK',
39
+ 'BUSY',
40
+ 'BUSYGROUP',
41
+ 'CLUSTERDOWN',
42
+ 'CROSSSLOT',
43
+ 'ERR',
44
+ 'EXECABORT',
45
+ 'LOADING',
46
+ 'MASTERDOWN',
47
+ 'MISCONF',
48
+ 'MOVED',
49
+ 'NOAUTH',
50
+ 'NOGROUP',
51
+ 'NOPERM',
52
+ 'NOPROTO',
53
+ 'NOREPLICAS',
54
+ 'NOSCRIPT',
55
+ 'NOTBUSY',
56
+ 'OOM',
57
+ 'READONLY',
58
+ 'TRYAGAIN',
59
+ 'UNBLOCKED',
60
+ 'UNKILLABLE',
61
+ 'WRONGPASS',
62
+ 'WRONGTYPE',
63
+ ]);
64
+ /**
65
+ * Transport failures the redis client reports by message only, mapped to a
66
+ * code of our own. The patterns are fixed library strings, so nothing from an
67
+ * application error can match them.
68
+ */
69
+ const CLIENT_MESSAGE_CODES = [
70
+ [/^Connection is closed/i, 'CONNECTION_CLOSED'],
71
+ [/^Stream connection ended/i, 'STREAM_ENDED'],
72
+ [/^Reached the max retries per request limit/i, 'MAX_RETRIES'],
73
+ [/^Command timed out/i, 'COMMAND_TIMEOUT'],
74
+ ];
75
+ /**
76
+ * Shape of an `err.code` this helper accepts: an `IMQ_`-prefixed code of the
77
+ * framework itself, or a system errno such as `ECONNREFUSED`.
78
+ */
79
+ const SAFE_CODE = /^(IMQ_[A-Z0-9_]{1,48}|E[A-Z]{2,15})$/;
80
+ /** Upper bound of a numeric `err.code`, so that no long number can pass */
81
+ const MAX_NUMERIC_CODE = 65535;
82
+ /**
83
+ * Extracts a loggable failure code from an unknown thrown value.
84
+ *
85
+ * @param err - the caught value, of any shape
86
+ * @returns the code, or `unknown` when none can be told safely
87
+ *
88
+ * @remarks
89
+ * Deliberately conservative: only an allow-listed code can come out of here,
90
+ * because an application error reaches this helper too and anything of its own
91
+ * may carry personal data. Recognised are a framework or system `code`, a
92
+ * small numeric `code`, the leading token of a known Redis error reply and a
93
+ * known redis-client failure message. Everything else — including the error's
94
+ * message, its stack and its class name — yields `unknown`. Never throws.
95
+ */
96
+ export function errorCode(err) {
97
+ try {
98
+ const code = err?.code;
99
+ if (typeof code === 'number' &&
100
+ Number.isInteger(code) &&
101
+ code >= 0 &&
102
+ code <= MAX_NUMERIC_CODE) {
103
+ return String(code);
104
+ }
105
+ if (typeof code === 'string' &&
106
+ (SAFE_CODE.test(code) || REDIS_REPLY_CODES.has(code))) {
107
+ return code;
108
+ }
109
+ const message = err?.message;
110
+ if (typeof message === 'string') {
111
+ const reply = message.split(' ', 1)[0];
112
+ if (REDIS_REPLY_CODES.has(reply)) {
113
+ return reply;
114
+ }
115
+ for (const [pattern, mapped] of CLIENT_MESSAGE_CODES) {
116
+ if (pattern.test(message)) {
117
+ return mapped;
118
+ }
119
+ }
120
+ }
121
+ return 'unknown';
122
+ }
123
+ catch {
124
+ return 'unknown';
125
+ }
126
+ }
127
+ //# sourceMappingURL=logging.js.map
@@ -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
- }