@imqueue/core 3.3.3 → 3.4.1

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.
@@ -0,0 +1,9 @@
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
+ }
package/CHANGELOG.md CHANGED
@@ -3,8 +3,66 @@
3
3
  Notable changes to `@imqueue/core`. Entries start with the first release whose
4
4
  behavior changes needed a written record; earlier history is in the git log.
5
5
 
6
+ A released version absent from this file changed no behavior — it was a
7
+ documentation, CI or packaging-only release. Every release that changed what the
8
+ queue does has an entry.
9
+
6
10
  This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
11
 
12
+ ## [3.4.0] - 2026-08-20
13
+
14
+ ### Added
15
+
16
+ - **Silent failures of the transport are now reported without `verbose`.** Every
17
+ line below is written through the configured logger, carries the queue,
18
+ channel or host it is about and never the message payload, the arguments, a
19
+ redis key or an error text. Nothing is scheduled and no timer is added.
20
+
21
+ - A write to redis rejected inside `send()` — the caller already holds the
22
+ message id and gets no rejection, so this was observable only through the
23
+ optional `errorHandler`, which most callers do not pass. Reported as a
24
+ failure episode per queue instance: the first rejected write is logged
25
+ with its operation, message id and code, further rejections are only
26
+ counted, and the first successful write logs the recovery together with
27
+ that count. A failure a redis client delivers twice — through both its
28
+ command callback and its returned promise — is counted once, while
29
+ `errorHandler` keeps being invoked per delivery, exactly as before.
30
+ - Safe reading of a queue ending on anything other than a planned stop,
31
+ reconnect or destroy. A planned stop stays quiet, as before.
32
+ - A failure of the periodic watcher-existence check itself; the failures of
33
+ delayed-message processing and of watcher initialization were already
34
+ logged and are not duplicated.
35
+ - A subscription being established and being restored after a reconnect, and
36
+ a failed reconnection attempt — the absence of the restore line after a
37
+ reconnect is what makes a lost subscription provable.
38
+ - Safe-delivery maintenance disabling itself for good when the writer
39
+ connection is gone.
40
+ - Messages of expired worker leases being re-queued — aggregated per
41
+ processing pass into one line per destination queue with a count — and a
42
+ worker key that could not be deleted: the two causes of a duplicate
43
+ delivery.
44
+ - Keys removed by the built-in cleanup, with the number of candidates and the
45
+ number actually deleted.
46
+ - A publish whose channel has no subscribers, on entering that state, and, in
47
+ a clustered queue, a publish with no server to publish to at all.
48
+ - In a clustered queue: round-robin having no available instance left, and a
49
+ joining server failing to start or to subscribe, with the host and the
50
+ phase.
51
+
52
+ No control flow, return value, redis round-trip or timer was altered, and no
53
+ new public API was added. One deliberate difference: the line reporting a
54
+ worker key that could not be deleted is now written through a contained
55
+ writer, so a logger which itself throws can no longer surface that throw as
56
+ an unhandled rejection — every line of this change is required to be unable
57
+ to influence queue behaviour.
58
+
59
+ A failure code is never taken from the error as it is: only an allow-listed
60
+ code is printed — an `IMQ_`-prefixed framework code, a system `E…` code, a
61
+ small integer, a known redis reply code (`WRONGTYPE`, `NOSCRIPT`,
62
+ `LOADING`, …) or one of a few known redis-client failure messages mapped to
63
+ codes of our own. Everything else, including the error's message, stack and
64
+ class name, is reported as `unknown`.
65
+
8
66
  ## [3.3.3] - 2026-08-18
9
67
 
10
68
  ### Fixed
@@ -23,6 +81,49 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
23
81
  the configuration is left untouched — enable `notify-keyspace-events` out of
24
82
  band there, as before.
25
83
 
84
+ ## [3.3.0] - 2026-07-28
85
+
86
+ ### Fixed
87
+
88
+ - **One transient sweep failure permanently disabled safe-delivery lease
89
+ recovery and the cleanup sweep.** `processWatch()` cleared `safeCheckInterval`
90
+ in its catch block, while `watch()` re-arms that interval only once per
91
+ watcher connection, guarded by a `__ready__` flag the teardown did not reset.
92
+ A single network blip, `CLUSTERDOWN` or slow failover therefore disabled both
93
+ for that connection's whole lifetime.
94
+
95
+ Nothing looked broken when it happened: the queue kept accepting and
96
+ delivering messages, and only messages abandoned by dead workers quietly
97
+ stopped coming back. Recovery needed the watcher connection replaced, or
98
+ another instance winning the lock.
99
+
100
+ A failed sweep now abandons only that sweep, and the next tick retries. The
101
+ legitimate teardowns are unchanged — `runSafeCheck()` still clears the
102
+ interval when the writer is gone, and `destroy()` clears it on shutdown.
103
+
104
+ - **The `./debug` export subpath could never resolve.** It pointed at
105
+ `./debug.d.ts` and `./debug.js`, neither of which exists in the repository or
106
+ in any published tarball, and nothing in core, rpc or the website imports it.
107
+ Removed. Not a breaking change: resolving it failed before with
108
+ `MODULE_NOT_FOUND` and fails now with `ERR_PACKAGE_PATH_NOT_EXPORTED`, so
109
+ nothing that worked stops working — only the error code differs.
110
+
111
+ ### Deprecated
112
+
113
+ - **`IMessage.delay` and `IMQOptions.verboseExtended` are inert, and now say
114
+ so.** `send()` builds the wire packet as `{ id, message, from }` and
115
+ `process()` reads back the same three, so `IMessage.delay` is never written
116
+ and never read — a delay lives in the delayed sorted set, not in the envelope.
117
+ Nothing anywhere reads `IMQOptions.verboseExtended`, so setting it produces no
118
+ extra output at all, though the published reference claimed it enabled
119
+ extended verbose logging.
120
+
121
+ Deprecated rather than removed because removal is type-level breaking, and
122
+ inconsistently so: an inline object literal at the call site would stop
123
+ compiling while the same option in an inferred config variable would not, so
124
+ two users with identical intent would get different outcomes from one update.
125
+ Both go in the next major.
126
+
26
127
  ## [3.2.4] - 2026-07-26
27
128
 
28
129
  ### Fixed
package/README.md CHANGED
@@ -1,6 +1,8 @@
1
1
  # I Message Queue (@imqueue/core)
2
2
 
3
- [![License](https://img.shields.io/badge/license-GPL-blue.svg)](https://rawgit.com/imqueue/core/master/LICENSE)
3
+ [![Build Status](https://img.shields.io/github/actions/workflow/status/imqueue/core/build.yml)](https://github.com/imqueue/core/actions/workflows/build.yml)
4
+ [![npm version](https://img.shields.io/npm/v/@imqueue/core)](https://www.npmjs.com/package/@imqueue/core)
5
+ [![License](https://img.shields.io/badge/license-GPL-blue.svg)](https://github.com/imqueue/core/blob/master/LICENSE)
4
6
 
5
7
  Simple JSON-based messaging queue for inter-service communication in Node.js &
6
8
  TypeScript back-ends — the Redis-backed transport that powers the @imqueue
@@ -11,7 +13,9 @@ framework. Fast, poll-free delivery with optional guaranteed mode.
11
13
  closed-source products at [imqueue.com](https://imqueue.com/).
12
14
 
13
15
  **Using an AI assistant?** Point it at [imqueue.org/llms.txt](https://imqueue.org/llms.txt)
14
- for a machine-readable index of the docs, or see [AGENTS.md](./AGENTS.md).
16
+ for a machine-readable index of the docs, or see [AGENTS.md](./AGENTS.md). Current
17
+ version, licence and Node floor for every package:
18
+ [imqueue.org/status.json](https://imqueue.org/status.json).
15
19
 
16
20
  **Related packages:**
17
21
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@imqueue/core",
3
- "version": "3.3.3",
3
+ "version": "3.4.1",
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.
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)/;
@@ -288,6 +288,21 @@ let RedisQueue = (() => {
288
288
  * Guards overlapping watcher check runs
289
289
  */
290
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();
291
306
  /**
292
307
  * Connected client keys seen during the previous cleanup sweep. Used
293
308
  * to give temporarily disconnected clients one sweep of grace before
@@ -397,6 +412,55 @@ let RedisQueue = (() => {
397
412
  this.logger.info(`[IMQ-CORE][${this.name}]: ${message}`);
398
413
  }
399
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
+ }
400
464
  /**
401
465
  * Creates a subscription channel over redis and sets up channel
402
466
  * data read handler. The effective Redis channel is `<prefix>:<channel>`.
@@ -436,6 +500,9 @@ let RedisQueue = (() => {
436
500
  this.attachSubscriptionHandler(chan, handler);
437
501
  this.subscriptionHandlers.push(handler);
438
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}`);
439
506
  }
440
507
  /**
441
508
  * Attaches a subscription message handler to a given channel
@@ -471,6 +538,7 @@ let RedisQueue = (() => {
471
538
  this.attachSubscriptionHandler(chan, handler);
472
539
  }
473
540
  this.verbose(`Restored subscription to ${this.subscriptionName}`);
541
+ this.logLine('info', `restored subscription to channel ${this.subscriptionName}`);
474
542
  }
475
543
  /**
476
544
  * Closes the subscription connection and forgets the channel name together
@@ -524,8 +592,9 @@ let RedisQueue = (() => {
524
592
  * allowed in any {@link IMQMode}, including `WORKER`.
525
593
  *
526
594
  * The payload is always plain JSON — {@link IMQOptions.useGzip} applies to
527
- * queue messages only. Redis pub/sub drops the message silently when nobody
528
- * 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.
529
598
  */
530
599
  async publish(data, toName) {
531
600
  if (!this.writer) {
@@ -533,7 +602,24 @@ let RedisQueue = (() => {
533
602
  }
534
603
  const jsonData = JSON.stringify(data);
535
604
  const name = toName || this.name;
536
- 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
+ }
537
623
  this.verbose(`Published message to ${name} channel, data: ${jsonData}
538
624
  `);
539
625
  }
@@ -649,7 +735,22 @@ let RedisQueue = (() => {
649
735
  }
650
736
  this.watcherCheckBusy = true;
651
737
  try {
652
- 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) {
653
754
  await this.initWatcher();
654
755
  }
655
756
  if (this.isWorker()) {
@@ -682,9 +783,12 @@ let RedisQueue = (() => {
682
783
  * schedule — the message is released by the watcher, so availability
683
784
  * may lag by up to {@link IMQOptions.watcherCheckDelay}. A delay of
684
785
  * `0` or `undefined` sends immediately.
685
- * @param errorHandler - invoked when the write to Redis fails; this is the
686
- * only way to observe such a failure, since the returned promise does
687
- * 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
688
792
  * @returns the identifier assigned to the message. It is generated locally
689
793
  * before the write is issued, so it is available even if the write
690
794
  * later fails.
@@ -714,9 +818,22 @@ let RedisQueue = (() => {
714
818
  const data = { id, message, from: this.name };
715
819
  const key = `${this.options.prefix}:${toQueue}`;
716
820
  const packet = this.pack(data);
821
+ const countedOps = new Set();
717
822
  const onWriteError = (error, op) => {
718
823
  if (error) {
719
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
+ }
720
837
  if (errorHandler) {
721
838
  errorHandler(error instanceof Error
722
839
  ? error
@@ -736,6 +853,10 @@ let RedisQueue = (() => {
736
853
  onWriteError(err, 'SET');
737
854
  return;
738
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();
739
860
  })
740
861
  .catch((err) => onWriteError(err, 'SET'));
741
862
  });
@@ -745,6 +866,9 @@ let RedisQueue = (() => {
745
866
  if (err) {
746
867
  onWriteError(err, 'LPUSH');
747
868
  }
869
+ else {
870
+ this.recordWriteSuccess();
871
+ }
748
872
  });
749
873
  // guard against unhandled rejections from promise-returning
750
874
  // client implementations in fire-and-forget mode
@@ -1188,6 +1312,9 @@ let RedisQueue = (() => {
1188
1312
  catch (err) {
1189
1313
  this.reconnecting[channel] = false;
1190
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)}`);
1191
1318
  this.scheduleReconnect(channel);
1192
1319
  }
1193
1320
  }
@@ -1336,19 +1463,52 @@ let RedisQueue = (() => {
1336
1463
  if (!keys.length) {
1337
1464
  return;
1338
1465
  }
1466
+ const requeued = new Map();
1339
1467
  this.verbose(`Watching ${keys.length} keys: ${keys
1340
1468
  .map(key => `"${key}"`)
1341
1469
  .join(', ')}`);
1342
- for (const key of keys) {
1343
- const kp = key.split(':');
1344
- // the last key segment is the worker's lease deadline: only
1345
- // re-queue messages of workers whose lease has expired (the
1346
- // worker died mid-processing); fresh leases belong to live
1347
- // workers and must not be touched
1348
- if (Number(kp.pop()) >= now) {
1349
- 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}`);
1350
1511
  }
1351
- await this.writer.lmove(key, `${kp.shift()}:${kp.shift()}`, 'RIGHT', 'LEFT');
1352
1512
  }
1353
1513
  }
1354
1514
  /**
@@ -1470,6 +1630,14 @@ let RedisQueue = (() => {
1470
1630
  */
1471
1631
  async runSafeCheck() {
1472
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}`);
1473
1641
  this.cleanSafeCheckInterval();
1474
1642
  return;
1475
1643
  }
@@ -1517,10 +1685,20 @@ let RedisQueue = (() => {
1517
1685
  }
1518
1686
  }
1519
1687
  if (keysToRemove.length) {
1520
- await this.writer.del(...keysToRemove);
1688
+ const removed = await this.writer.del(...keysToRemove);
1521
1689
  this.verbose(`Keys ${keysToRemove
1522
1690
  .map(k => `"${k}"`)
1523
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
+ }
1524
1702
  }
1525
1703
  }
1526
1704
  catch (err) {
@@ -1586,8 +1764,31 @@ let RedisQueue = (() => {
1586
1764
  try {
1587
1765
  msg = await this.reader.blmove(this.key, workerKey, 'RIGHT', 'LEFT', timeout);
1588
1766
  }
1589
- catch {
1590
- // 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
+ }
1591
1792
  break;
1592
1793
  }
1593
1794
  if (msg === null || msg === undefined) {
@@ -1596,9 +1797,12 @@ let RedisQueue = (() => {
1596
1797
  }
1597
1798
  try {
1598
1799
  this.process([key, msg]);
1599
- this.writer
1600
- .del(workerKey)
1601
- .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)}`));
1602
1806
  }
1603
1807
  catch (err) {
1604
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