@imqueue/core 3.3.1 → 3.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -71,11 +71,19 @@ timeout is 15s per test. Run a single spec after a build with
71
71
  - **Two delivery modes**, selected by the `safeDelivery` option: *unreliable*
72
72
  (fast; a message is lost if a consumer grabs it and dies) and *safe/guaranteed*
73
73
  (1.5–2× slower; a grabbed-then-lost message is rescheduled). Safe delivery
74
- relies on Redis `LMOVE`/`BLMOVE` — **Redis 6.2+ is required.**
74
+ relies on Redis `LMOVE`/`BLMOVE` — **Redis 6.2+ is required.** Unreliable
75
+ delivery uses `BRPOP` alone and works on 3.2+, so quote 6.2+ as the
76
+ requirement unless the sentence is specifically about the unreliable mode.
75
77
  - **No polling / no timers.** Delivery uses blocking Redis ops + keyspace
76
78
  notification events. If Redis has the `CONFIG` command disabled (e.g. AWS
77
79
  ElastiCache), keyspace notifications must be enabled out of band:
78
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.
79
87
  - **Messages must be JSON-serializable** (`IJson`/`JsonObject`). Delayed
80
88
  delivery is supported via the send `delay` argument.
81
89
  - Scaling the number of workers must **not** increase Redis traffic — preserve
package/CHANGELOG.md CHANGED
@@ -5,6 +5,24 @@ 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
+ ## [3.3.3] - 2026-08-18
9
+
10
+ ### Fixed
11
+
12
+ - **Starting a queue overwrote the redis keyspace-notification configuration.**
13
+ `notify-keyspace-events` is a server-global setting, and the watcher owner set
14
+ it to the literal `Ex` on every connection establishment. Any other flag —
15
+ enabled by an operator through a config file or by other code sharing the same
16
+ redis — was silently dropped, breaking every consumer that relied on it, and
17
+ coming back after each reconnect.
18
+
19
+ The current value is now read first, only the missing `E`/`x` flags are
20
+ appended, and `CONFIG SET` is skipped entirely when the configuration already
21
+ suffices. `A` is recognised as covering `x`, so a server on `AK` only gains
22
+ `E`. When `CONFIG` is unavailable (e.g. AWS ElastiCache) the read fails and
23
+ the configuration is left untouched — enable `notify-keyspace-events` out of
24
+ band there, as before.
25
+
8
26
  ## [3.2.4] - 2026-07-26
9
27
 
10
28
  ### Fixed
package/README.md CHANGED
@@ -47,8 +47,10 @@ With current implementation on RedisQueue:
47
47
  # Requirements
48
48
 
49
49
  Currently this module has only one available adapter, which is Redis. Redis server
50
- 6.2+ is required (the queue relies on `LMOVE`/`BLMOVE` commands for safe message
51
- delivery).
50
+ 6.2+ is required, because safe (guaranteed) delivery moves each message with the
51
+ `LMOVE`/`BLMOVE` commands, which arrived in 6.2. Unreliable delivery uses `BRPOP`
52
+ alone and runs on 3.2+, so an older server is only enough if `safeDelivery` stays
53
+ off — which is not what most deployments want.
52
54
 
53
55
  If the config command is disabled on Redis, you must manually enable keyspace
54
56
  notification events (particularly when using AWS ElasticCache), like this:
@@ -57,6 +59,12 @@ notification events (particularly when using AWS ElasticCache), like this:
57
59
  notify-keyspace-events Ex
58
60
  ```
59
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
+
60
68
  More adapters will be added in the future as needed.
61
69
 
62
70
  # Install
package/context7.json CHANGED
@@ -2,13 +2,43 @@
2
2
  "$schema": "https://context7.com/schema/context7.json",
3
3
  "projectTitle": "@imqueue/core",
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
- "excludeFolders": ["src", "lib", "node_modules", "test", "tests", "coverage", "docs/api"],
6
- "excludeFiles": ["CHANGELOG.md", "LICENSE"],
5
+ "branch": "master",
6
+ "excludeFolders": ["src", "test", "tests", "lib", "dist", "coverage", "node_modules", "scripts", "benchmark", ".github"],
7
+ "excludeFiles": ["CHANGELOG.md", "LICENSE", "CLAUDE.md", "CONTRIBUTING.md", "CONTRIBUTION-TERMS.md", "SECURITY.md"],
7
8
  "rules": [
8
- "Use ClusteredRedisQueue as the reliable queue implementation for production; it owns delivery, blocking reads and reconnection.",
9
- "The queue serializes rich types correctly — do not hand-roll JSON.stringify, which drops Date, Map, Set, BigInt and undefined.",
10
- "Delivery is at-least-once, so message handlers should be idempotent.",
11
- "@imqueue/core is the transport under @imqueue/rpc; most apps consume it through @imqueue/rpc rather than directly.",
12
- "@imqueue is GPL-3.0; a commercial license is available for closed-source use (see imqueue.com/license)."
13
- ]
9
+ "@imqueue/core is a JSON message queue over Redis for inter-service communication in Node.js and TypeScript. It is the transport @imqueue/rpc builds typed RPC on. Install with `npm i @imqueue/core`.",
10
+ "Prefer @imqueue/rpc for typed service-to-service calls. Reach for @imqueue/core directly only when you want raw queue semantics.",
11
+ "IMQ is the default export and a factory. Create queues with `IMQ.create(name, options)` — do not instantiate RedisQueue or ClusteredRedisQueue yourself.",
12
+ "IMQ.create() returns a RedisQueue for a single server, and a ClusteredRedisQueue when IMQOptions.cluster or IMQOptions.clusterManagers is supplied. Clustering is horizontal spread across Redis instances, not a reliability setting.",
13
+ "Minimal use: `const q = IMQ.create('MyQueue'); await q.start(); q.on('message', (msg, id, from) => {}); await q.send('OtherQueue', { hello: 'world' });`",
14
+ "A queue is an EventEmitter that emits exactly two events: 'message' with (message, id, fromQueue), and 'error'.",
15
+ "Delay a message with send's third argument, in milliseconds: `await q.send('MyQueue', { later: true }, 1000)`.",
16
+ "Messages must be JSON-serializable (IJson / JsonObject).",
17
+ "Serialization is plain JSON — JSON.stringify, or gzip over it when useGzip is on. A Date therefore arrives as an ISO string, a Map or Set arrives as {}, undefined properties vanish and a BigInt throws. Convert rich types yourself at both ends.",
18
+ "Two delivery modes, chosen by the safeDelivery option: unreliable (the default, fastest — a message is lost if a consumer grabs it and dies) and guaranteed (1.5-2x slower — a grabbed-then-lost message is re-queued).",
19
+ "safeDelivery guarantees the HAND-OFF, not the processing. The worker key is released once the message reaches the 'message' listener, so a worker killed while its handler still runs loses that message exactly as with safe delivery off.",
20
+ "Delivery is at-least-once in BOTH modes, so handlers must be idempotent. Nothing in @imqueue/core offers exactly-once delivery; do not describe it as if it did.",
21
+ "safeDeliveryTtl (default 5000 ms) is the recovery deadline for an abandoned hand-off, not a processing deadline. A slow handler is neither interrupted nor re-queued, so raising it extends no protection over long-running work.",
22
+ "Draining in-flight work before exit is the application's job, in either delivery mode.",
23
+ "Omitted options fall back to DEFAULT_IMQ_OPTIONS: localhost:6379, prefix 'imq', cleanup off, safeDelivery off, gzip off, a 5000 ms watcher check and safe-delivery TTL, and signal handling on.",
24
+ "handleSignals is ON by default: on SIGTERM, SIGINT or SIGABRT the queue releases its watcher lock and then exits the process, without waiting for in-flight 'message' handlers. Disable it when the host application manages shutdown.",
25
+ "Only cleanup and cleanupFilter are required by the IMQOptions type, while every constructor and IMQ.create() accept a Partial<IMQOptions> — declare option literals as Partial<IMQOptions>.",
26
+ "cleanupFilter is a Redis glob appended to the prefix as `<prefix>:<cleanupFilter>` and defaults to '*', i.e. every key in the namespace. It only matters when cleanup is on, which it is not by default.",
27
+ "useGzip trades worker CPU for network traffic and is off by default. vendor defaults to 'Redis' and is the only supported value.",
28
+ "ClusteredRedisQueue distributes asymmetrically: send() routes each message to exactly ONE server, by health-aware round-robin that skips instances whose writer is not ready.",
29
+ "Every other ClusteredRedisQueue operation — start, stop, clear, destroy, publish, subscribe, unsubscribe, queueLength — fans out to every server.",
30
+ "Those fan-outs use Promise.all, so one failing host fails the whole call with no partial-failure reporting and no rollback.",
31
+ "ClusteredRedisQueue only implements the EventEmitter interface rather than extending it, so `instanceof EventEmitter` is false, and emit and once are per-server — a once() listener runs once per server, not once in total.",
32
+ "Requires Redis 6.2+, because safe delivery moves messages with LMOVE/BLMOVE. Unreliable delivery uses BRPOP alone and runs on 3.2+, so quote 6.2+ unless safeDelivery is known to be off.",
33
+ "Requires Node.js 22.12+. The package is ESM-only, so consumers must use `import`, not `require()`.",
34
+ "Delivery uses blocking Redis operations plus keyspace notification events — no timers and no polling — so an idle queue consumes no resources and delivery has no scheduling delay.",
35
+ "Delayed delivery depends on Redis key-expiry events. Where the CONFIG command is disabled, notably AWS ElastiCache, enable them out of band with `notify-keyspace-events Ex`.",
36
+ "Scaling the number of workers does not increase Redis traffic; the same queue can have many concurrent consumers.",
37
+ "Measured throughput for 1 KB messages on one i7 core: ~35-40k/sec unreliable, ~20-25k guaranteed, ~10k delayed (~200k and ~120k on a 24-core box). Treat these as a shape and measure your own: `node benchmark -c 4 -m 10000`.",
38
+ "ioredis is the only runtime dependency, and Redis is currently the only queue adapter.",
39
+ "@imqueue/core is GPL-3.0-only. Commercial licensing for closed-source products: https://imqueue.com/license/.",
40
+ "Guides and the generated API reference are at https://imqueue.org/; a machine-readable index at https://imqueue.org/llms.txt; a hosted MCP server for agents at https://mcp.imqueue.org/mcp."
41
+ ],
42
+ "url": "https://context7.com/imqueue/core",
43
+ "public_key": "pk_fjNtG1ue4XLAYwKYgyOMq"
14
44
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@imqueue/core",
3
- "version": "3.3.1",
3
+ "version": "3.3.3",
4
4
  "description": "Fast JSON message queue over Redis for inter-service communication in Node.js & TypeScript microservices — the transport layer of the @imqueue framework",
5
5
  "keywords": [
6
6
  "message-queue",
@@ -628,6 +628,38 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
628
628
  * Clears safe check interval
629
629
  */
630
630
  private cleanSafeCheckInterval;
631
+ /**
632
+ * Reads the keyspace-notification flags currently configured on the
633
+ * server.
634
+ *
635
+ * @returns the raw flags string, or an empty string when notifications
636
+ * are disabled
637
+ *
638
+ * @remarks
639
+ * `CONFIG GET` replies as a flat `[name, value]` array over RESP2 and as a
640
+ * map over RESP3, so both shapes are accepted.
641
+ */
642
+ private currentKeyspaceEvents;
643
+ /**
644
+ * Returns the flags from {@link NOTIFY_EVENTS_REQUIRED} that the given
645
+ * configuration does not already provide.
646
+ *
647
+ * @param current - flags string as reported by `CONFIG GET`
648
+ */
649
+ private missingKeyspaceEvents;
650
+ /**
651
+ * Makes sure the server publishes the keyspace events this queue listens
652
+ * for, preserving whatever else is already configured.
653
+ *
654
+ * @remarks
655
+ * Flags configured out of band — by an operator, or by other code sharing
656
+ * the same Redis — are kept: only the missing ones are appended, and
657
+ * `CONFIG SET` is skipped entirely when nothing needs adding. When the
658
+ * `CONFIG` command is unavailable (e.g. AWS ElastiCache) the read fails and
659
+ * the error is reported without touching the configuration; enable
660
+ * `notify-keyspace-events` out of band in that case.
661
+ */
662
+ private ensureKeyspaceEvents;
631
663
  /**
632
664
  * Setups watch a process on delayed messages
633
665
  */
package/src/RedisQueue.js CHANGED
@@ -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.
@@ -1364,6 +1378,71 @@ let RedisQueue = (() => {
1364
1378
  delete this.safeCheckInterval;
1365
1379
  }
1366
1380
  }
1381
+ /**
1382
+ * Reads the keyspace-notification flags currently configured on the
1383
+ * server.
1384
+ *
1385
+ * @returns the raw flags string, or an empty string when notifications
1386
+ * are disabled
1387
+ *
1388
+ * @remarks
1389
+ * `CONFIG GET` replies as a flat `[name, value]` array over RESP2 and as a
1390
+ * map over RESP3, so both shapes are accepted.
1391
+ */
1392
+ async currentKeyspaceEvents() {
1393
+ const reply = (await this.writer.config('GET', NOTIFY_EVENTS_PARAM));
1394
+ if (!reply) {
1395
+ return '';
1396
+ }
1397
+ let value;
1398
+ if (Array.isArray(reply)) {
1399
+ const at = reply.indexOf(NOTIFY_EVENTS_PARAM);
1400
+ // an unnamed parameter means the reply is not what was asked for,
1401
+ // and guessing the value out of it could only make things worse
1402
+ value = at < 0 ? undefined : reply[at + 1];
1403
+ }
1404
+ else {
1405
+ value = reply[NOTIFY_EVENTS_PARAM];
1406
+ }
1407
+ return typeof value === 'string' ? value : '';
1408
+ }
1409
+ /**
1410
+ * Returns the flags from {@link NOTIFY_EVENTS_REQUIRED} that the given
1411
+ * configuration does not already provide.
1412
+ *
1413
+ * @param current - flags string as reported by `CONFIG GET`
1414
+ */
1415
+ missingKeyspaceEvents(current) {
1416
+ const covered = current.includes('A')
1417
+ ? current + NOTIFY_EVENTS_ALL
1418
+ : current;
1419
+ return [...NOTIFY_EVENTS_REQUIRED]
1420
+ .filter(flag => !covered.includes(flag))
1421
+ .join('');
1422
+ }
1423
+ /**
1424
+ * Makes sure the server publishes the keyspace events this queue listens
1425
+ * for, preserving whatever else is already configured.
1426
+ *
1427
+ * @remarks
1428
+ * Flags configured out of band — by an operator, or by other code sharing
1429
+ * the same Redis — are kept: only the missing ones are appended, and
1430
+ * `CONFIG SET` is skipped entirely when nothing needs adding. When the
1431
+ * `CONFIG` command is unavailable (e.g. AWS ElastiCache) the read fails and
1432
+ * the error is reported without touching the configuration; enable
1433
+ * `notify-keyspace-events` out of band in that case.
1434
+ */
1435
+ async ensureKeyspaceEvents() {
1436
+ const current = await this.currentKeyspaceEvents();
1437
+ const missing = this.missingKeyspaceEvents(current);
1438
+ if (!missing) {
1439
+ this.verbose(`Keyspace events "${current}" already cover ` +
1440
+ `"${NOTIFY_EVENTS_REQUIRED}", keeping them as is`);
1441
+ return;
1442
+ }
1443
+ this.verbose(`Adding "${missing}" to keyspace events "${current}"`);
1444
+ await this.writer.config('SET', NOTIFY_EVENTS_PARAM, current + missing);
1445
+ }
1367
1446
  /**
1368
1447
  * Setups watch a process on delayed messages
1369
1448
  */
@@ -1371,14 +1450,7 @@ let RedisQueue = (() => {
1371
1450
  if (!this.writer || !this.watcher || this.watcher.__ready__) {
1372
1451
  return this;
1373
1452
  }
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
- }
1453
+ this.ensureKeyspaceEvents().catch((err) => this.emitError('OnConfig', 'events config error', err));
1382
1454
  this.watcher.on('pmessage', this.onWatchMessage.bind(this));
1383
1455
  this.watcher
1384
1456
  .psubscribe('__keyevent@0__:expired', `${this.options.prefix}:delayed:*`)
@@ -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
- }