@memberjunction/redis-provider 6.2.0-edge.2 → 6.2.0-edge.4

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.
@@ -15,6 +15,7 @@
15
15
  */
16
16
  import Redis from 'ioredis';
17
17
  import { EventEmitter } from 'events';
18
+ import { randomUUID } from 'crypto';
18
19
  import { LogStatus, LogError } from '@memberjunction/core';
19
20
  import { MJGlobal } from '@memberjunction/global';
20
21
  /**
@@ -22,6 +23,162 @@ import { MJGlobal } from '@memberjunction/global';
22
23
  * @internal
23
24
  */
24
25
  const DEFAULT_CATEGORY = 'default';
26
+ /**
27
+ * The categories a reconnect-flush clears.
28
+ *
29
+ * Mirrors `CacheCategory` from `@memberjunction/core` as literals rather than importing it, so the
30
+ * provider takes no value dependency on that module and a category added there cannot change
31
+ * recovery behaviour here without an edit to this list.
32
+ */
33
+ const RECONCILED_CATEGORIES = ['RunViewCache', 'RunQueryCache', 'DatasetCache', 'Metadata', 'default'];
34
+ /**
35
+ * Categories whose expiry differs from the default. The `default` category never expires on its
36
+ * own: it holds keys that vouch for other keys, and a proxy that outlives its subject is worse
37
+ * than one that never expires. See {@link RedisProviderConfig.categoryTTLSeconds}.
38
+ * @internal
39
+ */
40
+ const DEFAULT_CATEGORY_TTL_SECONDS = { default: 0 };
41
+ /** Expiry applied when the configuration does not set `defaultTTLSeconds`. @internal */
42
+ const DEFAULT_TTL_SECONDS = 3600;
43
+ /** Keys requested per `SCAN` step. @internal */
44
+ const SCAN_BATCH = 500;
45
+ /**
46
+ * Prunes one index group and returns its live members, atomically.
47
+ *
48
+ * Every step — reading the set, testing each member, removing the dead ones, dropping a set that
49
+ * ends up empty — has to happen without another process's `SADD` landing in between. Done as
50
+ * separate round trips (SMEMBERS, a pipeline of EXISTS, then SREM/DEL), a peer adding a key after
51
+ * the read was removed by a DEL that had never seen it, and that slot lost its invalidation hook
52
+ * permanently: no later save could find it through the index, so every server served it stale until
53
+ * it expired.
54
+ *
55
+ * KEYS[1] = the group set, ARGV[1] = the `{prefix}:{category}:` prefix of a member's own key.
56
+ * @internal
57
+ */
58
+ const PRUNE_GROUP_SCRIPT = `
59
+ local members = redis.call('SMEMBERS', KEYS[1])
60
+ if #members == 0 then
61
+ return {}
62
+ end
63
+ local alive = {}
64
+ local dead = {}
65
+ for i = 1, #members do
66
+ if redis.call('EXISTS', ARGV[1] .. members[i]) == 1 then
67
+ alive[#alive + 1] = members[i]
68
+ else
69
+ dead[#dead + 1] = members[i]
70
+ end
71
+ end
72
+ if #dead > 0 then
73
+ if #alive == 0 then
74
+ -- Deleting beats emptying: a set made persistent by a member without expiry stays persistent
75
+ -- once that member goes, and a volatile-* maxmemory policy can never evict it.
76
+ redis.call('DEL', KEYS[1])
77
+ else
78
+ redis.call('SREM', KEYS[1], unpack(dead))
79
+ end
80
+ end
81
+ return alive
82
+ `;
83
+ /**
84
+ * Adds a key to an index-group set and keeps the set alive at least as long as its longest-lived
85
+ * member, atomically.
86
+ *
87
+ * KEYS[1] = the group set, ARGV[1] = the member key, ARGV[2] = the member's TTL in seconds (0 = none).
88
+ *
89
+ * - A member stored without expiry makes the set persistent.
90
+ * - A member with a TTL extends the set's expiry when the set would otherwise expire first.
91
+ * - A set that is persistent and already holds other members keeps no expiry: every TTL write
92
+ * gives the set an expiry, so a persistent set with more than one member holds a persistent
93
+ * member.
94
+ *
95
+ * Only `SADD`/`TTL`/`SCARD`/`EXPIRE`/`PERSIST` — no Redis 7-only flags, so it runs on the 6.x
96
+ * tiers that hosted Redis services still offer.
97
+ * @internal
98
+ */
99
+ const ADD_TO_GROUP_SCRIPT = `
100
+ redis.call('SADD', KEYS[1], ARGV[1])
101
+ local ttl = tonumber(ARGV[2])
102
+ if ttl <= 0 then
103
+ redis.call('PERSIST', KEYS[1])
104
+ return 0
105
+ end
106
+ local current = redis.call('TTL', KEYS[1])
107
+ if current == -1 and redis.call('SCARD', KEYS[1]) > 1 then
108
+ return 0
109
+ end
110
+ if current < ttl then
111
+ redis.call('EXPIRE', KEYS[1], ttl)
112
+ end
113
+ return 1
114
+ `;
115
+ /** Deletes a lock key only if it still holds the caller's token. @internal */
116
+ const RELEASE_LOCK_SCRIPT = `
117
+ if redis.call('GET', KEYS[1]) == ARGV[1] then
118
+ return redis.call('DEL', KEYS[1])
119
+ end
120
+ return 0
121
+ `;
122
+ /** How long a key lock lives if its holder dies, and how long a caller waits for one. @internal */
123
+ const KEY_LOCK_TTL_MS = 10000;
124
+ const KEY_LOCK_WAIT_MS = 5000;
125
+ const KEY_LOCK_RETRY_MS = 20;
126
+ /** How often a held lock is extended while its work runs. Must be well under the TTL. @internal */
127
+ const KEY_LOCK_RENEW_MS = 3000;
128
+ /**
129
+ * The longest a lock is renewed for. Renewal keeps a slow read-modify-write safe; without a cap it
130
+ * also keeps a HUNG one holding the key forever, which is worse than the expiry it replaced — no
131
+ * other process could ever take that slot again. Past this, renewal stops and the lock expires on
132
+ * its own TTL, as it did before renewal existed.
133
+ * @internal
134
+ */
135
+ const KEY_LOCK_MAX_HOLD_MS = 60000;
136
+ /** Extends a lock's expiry only if the caller still holds it. @internal */
137
+ const RENEW_LOCK_SCRIPT = `
138
+ if redis.call('GET', KEYS[1]) == ARGV[1] then
139
+ return redis.call('PEXPIRE', KEYS[1], ARGV[2])
140
+ end
141
+ return 0
142
+ `;
143
+ /**
144
+ * Thrown by {@link RedisLocalStorageProvider.WithKeyLock} when the lock could not be taken in
145
+ * time — distinct from anything `work` itself throws, so a caller can tell "another process is
146
+ * holding this slot" (fall back to invalidating it) from "my own read-modify-write is broken"
147
+ * (a bug, which must not be silently downgraded to an invalidation).
148
+ */
149
+ export class KeyLockTimeoutError extends Error {
150
+ /**
151
+ * @param LockKey The lock that could not be taken.
152
+ * @param waitedMs How long the attempt waited.
153
+ * @param reason Why, when it was not contention — e.g. Redis being unreachable. Defaults to the
154
+ * contention message. The class (and so its `name`) is kept either way, because the caller's
155
+ * correct response is the same: do not write, invalidate instead.
156
+ */
157
+ constructor(LockKey, waitedMs, reason) {
158
+ super(reason ?? `timed out after ${waitedMs} ms waiting for another process's lock`);
159
+ this.LockKey = LockKey;
160
+ this.name = 'KeyLockTimeoutError';
161
+ }
162
+ }
163
+ /**
164
+ * Thrown when a held lock expired before its work finished — the work may have raced another
165
+ * writer, so its result must not be trusted.
166
+ */
167
+ export class KeyLockLostError extends Error {
168
+ constructor(LockKey) {
169
+ super(`the lock expired before the work completed; another process may have written the same key`);
170
+ this.LockKey = LockKey;
171
+ this.name = 'KeyLockLostError';
172
+ }
173
+ }
174
+ /**
175
+ * Escapes the glob metacharacters Redis `MATCH` understands, so a literal prefix or category can
176
+ * be embedded in a pattern.
177
+ * @internal
178
+ */
179
+ function escapeGlob(literal) {
180
+ return literal.replace(/[*?[\]\\]/g, ch => `\\${ch}`);
181
+ }
25
182
  /**
26
183
  * Redis-backed implementation of the MemberJunction {@link ILocalStorageProvider} interface.
27
184
  *
@@ -38,8 +195,11 @@ const DEFAULT_CATEGORY = 'default';
38
195
  * - **category** — maps to the MJ cache category (`RunViewCache`, `Metadata`, `DatasetCache`, etc.)
39
196
  * - **key** — the original key from the caller
40
197
  *
41
- * Categories are tracked in a Redis Set at `{prefix}:__categories__:{category}` so that
42
- * `ClearCategory()` and `GetCategoryKeys()` operations are efficient.
198
+ * Keys written with an `IndexGroup` are also recorded in a Redis Set at
199
+ * `{prefix}:__group__:{category}:{group}` (the RunView cache uses the entity name), which
200
+ * `GetIndexGroupKeys()` reads and prunes. `ClearCategory()` and `GetCategoryKeys()` walk the
201
+ * keyspace with `SCAN`; no category-wide set is kept, because expiry never removes set members
202
+ * and such a set grows without bound once keys carry a TTL.
43
203
  *
44
204
  * ### TTL Support
45
205
  *
@@ -107,7 +267,47 @@ export class RedisLocalStorageProvider {
107
267
  * See {@link ILocalStorageProvider.SharesReferences}.
108
268
  */
109
269
  this.SharesReferences = false;
270
+ /**
271
+ * `true` — that is the whole point of this provider: every server in the fleet reads what any
272
+ * other wrote. See {@link ILocalStorageProvider.SupportsCrossProcessPersistence}.
273
+ */
274
+ this.SupportsCrossProcessPersistence = true;
275
+ /**
276
+ * `true` — every process configured with the same URL and key prefix shares this keyspace.
277
+ * See {@link ILocalStorageProvider.SharedAcrossProcesses}.
278
+ */
279
+ this.SharedAcrossProcesses = true;
280
+ /** Tokens of the leases this provider holds, so it releases only its own. */
281
+ this._leaseTokens = new Map();
110
282
  this._connected = false;
283
+ /**
284
+ * Whether this client has ever been connected. Distinguishes a startup that has not reached
285
+ * Redis yet, where queueing a command is useful, from a connection that was lost, where
286
+ * {@link shouldFailFast} applies.
287
+ */
288
+ this._hasEverConnected = false;
289
+ /**
290
+ * The highest shared epoch this process has seen, from its own mutations and from events
291
+ * received. {@link reconcileAfterReconnect} compares it against the value in Redis to decide
292
+ * whether anything was invalidated during a connection gap.
293
+ */
294
+ this._lastSeenEpoch = 0;
295
+ /**
296
+ * Whether this process mutated shared state while disconnected, meaning other servers never
297
+ * received those invalidations. Set so {@link reconcileAfterReconnect} can bump the epoch on
298
+ * recovery and make them flush.
299
+ */
300
+ this._mutatedWhileDisconnected = false;
301
+ /** Guards against two overlapping reconciliations (client and subscriber both recover). */
302
+ this._reconciling = false;
303
+ /**
304
+ * Whether the loss of this connection has already been reported to consumers. Reports the loss
305
+ * once per outage — `close` fires on every failed reconnection attempt — and tells the `ready`
306
+ * handler that a recovery, rather than a first connection, is what it is seeing.
307
+ */
308
+ this._connectionLostEmitted = false;
309
+ /** As {@link _hasEverConnected}, for the subscriber connection. */
310
+ this._subscriberHasEverConnected = false;
111
311
  this._subscriber = null;
112
312
  this._eventEmitter = new EventEmitter();
113
313
  this._subscriberConnected = false;
@@ -115,13 +315,21 @@ export class RedisLocalStorageProvider {
115
315
  this._channelHandlers = new Map();
116
316
  /** Fully-qualified channel name -> the subscribe still in flight, shared by concurrent callers. */
117
317
  this._pendingChannelSubscribes = new Map();
318
+ /** The subscriber start-up in flight or completed, shared by every caller of {@link StartListening}. */
319
+ this._listening = null;
118
320
  this._config = config;
119
321
  this._keyPrefix = config.keyPrefix ?? 'mj';
120
- this._defaultTTLSeconds = config.defaultTTLSeconds;
322
+ this._defaultTTLSeconds = config.defaultTTLSeconds ?? DEFAULT_TTL_SECONDS;
323
+ // Merged over the built-in map, never replacing it: the `default` category's "no expiry"
324
+ // is an invariant of what that category HOLDS (proxy keys), so a host that only wants, say,
325
+ // a dataset TTL must not silently reinstate the bug fixed. Naming `default`
326
+ // explicitly still overrides it, which is the only way that should be possible.
327
+ this._categoryTTLSeconds = { ...DEFAULT_CATEGORY_TTL_SECONDS, ...(config.categoryTTLSeconds ?? {}) };
121
328
  this._enableLogging = config.enableLogging ?? true;
329
+ this._maxRetryDelayMs = config.maxRetryDelayMs ?? 30000;
122
330
  this._enablePubSub = config.enablePubSub ?? false;
123
331
  this._pubSubChannel = `${this._keyPrefix}:__pubsub__`;
124
- const maxRetries = config.maxRetries ?? 10;
332
+ const maxRetries = config.maxRetries; // undefined = retry forever, with a capped delay
125
333
  if (config.url) {
126
334
  this._client = new Redis(config.url, {
127
335
  maxRetriesPerRequest: null,
@@ -152,43 +360,78 @@ export class RedisLocalStorageProvider {
152
360
  * @internal
153
361
  */
154
362
  retryStrategy(times, maxRetries) {
155
- if (times > maxRetries) {
156
- if (this._enableLogging) {
157
- LogError(`Redis: max retries (${maxRetries}) exceeded, giving up`);
158
- }
363
+ // Returning null stops ioredis reconnecting for the life of the client, recoverable only by
364
+ // restarting the process, so only an explicit maxRetries gets that.
365
+ if (maxRetries !== undefined && times > maxRetries) {
366
+ // Error channel: status output is suppressed in production, and this is the one message
367
+ // that must reach a deployed log.
368
+ LogError(`Redis: max retries (${maxRetries}) exceeded after ${times} attempts — giving up permanently. ` +
369
+ `This process is now cache-blind until it restarts. Omit maxRetries to retry forever with a capped delay.`);
370
+ this.noteConnectionLost('retries exhausted');
159
371
  return null;
160
372
  }
161
- // Exponential backoff: 200ms, 400ms, 800ms, ... capped at 30s
162
- const delay = Math.min(times * 200, 30000);
373
+ // 200, 400, 800, 1600 … then held at maxRetryDelayMs.
374
+ const delay = Math.min(200 * Math.pow(2, times - 1), this._maxRetryDelayMs);
163
375
  if (this._enableLogging) {
164
- LogStatus(`Redis: reconnecting in ${delay}ms (attempt ${times}/${maxRetries})`);
376
+ const ceiling = maxRetries === undefined ? 'no limit' : `${maxRetries}`;
377
+ LogStatus(`Redis: reconnecting in ${delay}ms (attempt ${times}, limit ${ceiling})`);
165
378
  }
166
379
  return delay;
167
380
  }
381
+ /**
382
+ * Registers event handlers on the ioredis client for logging connection
383
+ * lifecycle events (connect, ready, close, error, reconnecting).
384
+ * @internal
385
+ */
386
+ handleClientConnect() {
387
+ this._connected = true;
388
+ if (this._enableLogging) {
389
+ LogStatus('Redis: connected');
390
+ }
391
+ }
392
+ /**
393
+ * On `ready` the client can serve commands again. A recovery is identified by
394
+ * {@link _connectionLostEmitted} rather than by inspecting `_connected`: ioredis emits `connect`
395
+ * before `ready`, so by this point `_connected` has already been set back to true and cannot
396
+ * distinguish a reconnect from a first connection.
397
+ *
398
+ * @internal
399
+ */
400
+ handleClientReady() {
401
+ this._connected = true;
402
+ this._hasEverConnected = true;
403
+ if (this._enableLogging) {
404
+ LogStatus('Redis: ready to accept commands');
405
+ }
406
+ if (this._connectionLostEmitted) {
407
+ this._connectionLostEmitted = false;
408
+ this.emitConnectionRestored();
409
+ }
410
+ }
411
+ /**
412
+ * `close` fires once per failed reconnection attempt, not only on the first drop, so the loss is
413
+ * announced through {@link noteConnectionLost} and reported once per outage.
414
+ *
415
+ * @internal
416
+ */
417
+ handleClientClose() {
418
+ this._connected = false;
419
+ if (this._enableLogging) {
420
+ LogStatus('Redis: connection closed');
421
+ }
422
+ if (this._hasEverConnected) {
423
+ this.noteConnectionLost('connection closed');
424
+ }
425
+ }
168
426
  /**
169
427
  * Registers event handlers on the ioredis client for logging connection
170
428
  * lifecycle events (connect, ready, close, error, reconnecting).
171
429
  * @internal
172
430
  */
173
431
  setupEventHandlers() {
174
- this._client.on('connect', () => {
175
- this._connected = true;
176
- if (this._enableLogging) {
177
- LogStatus('Redis: connected');
178
- }
179
- });
180
- this._client.on('ready', () => {
181
- this._connected = true;
182
- if (this._enableLogging) {
183
- LogStatus('Redis: ready to accept commands');
184
- }
185
- });
186
- this._client.on('close', () => {
187
- this._connected = false;
188
- if (this._enableLogging) {
189
- LogStatus('Redis: connection closed');
190
- }
191
- });
432
+ this._client.on('connect', () => this.handleClientConnect());
433
+ this._client.on('ready', () => this.handleClientReady());
434
+ this._client.on('close', () => this.handleClientClose());
192
435
  this._client.on('error', (err) => {
193
436
  if (this._enableLogging) {
194
437
  LogError(`Redis: ${err.message}`);
@@ -200,6 +443,141 @@ export class RedisLocalStorageProvider {
200
443
  }
201
444
  });
202
445
  }
446
+ /**
447
+ * Whether a command should fail immediately instead of being handed to ioredis.
448
+ *
449
+ * True once a connection has been established and then lost. The clients set
450
+ * `maxRetriesPerRequest: null` and leave ioredis's offline queue enabled, so a command issued
451
+ * while disconnected is queued and its promise never settles — over a long outage that is
452
+ * unbounded memory and indefinitely hanging awaits. Callers instead get a miss from a read and
453
+ * a no-op from a write, both of which are correct and only slower.
454
+ *
455
+ * False before the first connection, so a brief queue can still warm the cache at startup.
456
+ * Nothing is stale at that point because nothing is cached.
457
+ *
458
+ * @internal
459
+ */
460
+ get shouldFailFast() {
461
+ return this._hasEverConnected && !this._connected;
462
+ }
463
+ /**
464
+ * Records the highest epoch this process has observed, from either direction — a mutation it
465
+ * published, or an event it received. Monotonic: a late-arriving lower value is ignored.
466
+ * @internal
467
+ */
468
+ noteEpochSeen(epoch) {
469
+ if (typeof epoch === 'number' && epoch > this._lastSeenEpoch) {
470
+ this._lastSeenEpoch = epoch;
471
+ }
472
+ }
473
+ /**
474
+ * Records that shared state changed while this process could not tell anyone.
475
+ *
476
+ * Reconciliation has to be symmetric. The obvious direction is what this process MISSED, and the
477
+ * epoch comparison covers that. This is the other direction: writes this process made that its
478
+ * siblings never heard, which leave *them* confidently stale. On recovery the epoch is bumped so
479
+ * they flush too.
480
+ * @internal
481
+ */
482
+ noteMutationWhileDisconnected() {
483
+ this._mutatedWhileDisconnected = true;
484
+ }
485
+ /**
486
+ * Decides whether this process's caches are still trustworthy after a reconnect, and flushes
487
+ * them if not.
488
+ *
489
+ * ioredis resubscribes on its own, but pub/sub has no replay: invalidations published while this
490
+ * process was disconnected are gone, so the cache may hold entries other servers have already
491
+ * invalidated. One read of the shared epoch counter settles it:
492
+ *
493
+ * - unchanged — nothing was invalidated anywhere during the gap, so the cache is kept
494
+ * - advanced — something changed and this process cannot know what, so everything is dropped
495
+ * - this process mutated while disconnected — the epoch is bumped so siblings flush too, and
496
+ * the cache is dropped here as well
497
+ *
498
+ * An epoch that cannot be read is treated as advanced: without evidence of correctness, flush.
499
+ *
500
+ * @internal
501
+ */
502
+ async reconcileAfterReconnect() {
503
+ if (!this._enablePubSub || this._reconciling) {
504
+ return; // no cross-server invalidation to reconcile, or already in progress
505
+ }
506
+ this._reconciling = true;
507
+ try {
508
+ const dirty = this._mutatedWhileDisconnected;
509
+ this._mutatedWhileDisconnected = false;
510
+ let current;
511
+ if (dirty) {
512
+ // Make siblings flush: our writes never reached them.
513
+ current = await this._client.incr(this.buildEpochKey());
514
+ }
515
+ else {
516
+ const raw = await this._client.get(this.buildEpochKey());
517
+ current = raw === null ? 0 : Number(raw);
518
+ if (!Number.isFinite(current)) {
519
+ throw new Error(`epoch key held a non-numeric value: ${JSON.stringify(raw)}`);
520
+ }
521
+ }
522
+ // Any DIFFERENCE means flush, not only an advance. A lower value is not "no change": the
523
+ // counter is gone — cleared, evicted under maxmemory, or a different instance — and what
524
+ // happened before that is unknowable. Inequality also bounds the damage a peer can do by
525
+ // publishing an absurd epoch, since a later real value differs from it and flushes.
526
+ const suspect = dirty || current !== this._lastSeenEpoch;
527
+ if (!suspect) {
528
+ if (this._enableLogging) {
529
+ // Status, not the error channel: this is the routine outcome and says nothing
530
+ // happened. Only the decisions that DROP a cache are worth an operator's log.
531
+ LogStatus(`[Redis] reconciled after reconnect: epoch unchanged at ${current} — nothing was ` +
532
+ `invalidated while this process was away, so the local cache is kept`);
533
+ }
534
+ return;
535
+ }
536
+ LogError(`[Redis] reconciled after reconnect: epoch ${this._lastSeenEpoch} → ${current}` +
537
+ `${dirty ? ' (this process also mutated while disconnected, so siblings were told to flush)' : ''}` +
538
+ ` — dropping local cache`);
539
+ this._lastSeenEpoch = current;
540
+ this.requestLocalFlush();
541
+ }
542
+ catch (err) {
543
+ // Could not establish correctness; flush rather than trust.
544
+ LogError(`[Redis] reconciliation could not read the epoch (${err.message}) — flushing local cache to be safe`);
545
+ this.requestLocalFlush();
546
+ }
547
+ finally {
548
+ this._reconciling = false;
549
+ }
550
+ }
551
+ /**
552
+ * Tells local consumers to drop everything they hold.
553
+ *
554
+ * Expressed as a `category_cleared` event per shared category rather than a new event type,
555
+ * because that action already means "assume nothing in this category is valid" and
556
+ * `LocalCacheManager.DispatchCacheChange` already fans it out to EVERY registered callback. A
557
+ * bespoke event would need every consumer taught about it; this one is understood today.
558
+ *
559
+ * `SourceServerId` is this process deliberately — the flush is local, and a sibling receiving it
560
+ * would filter it out as self-originated anyway since it is never published.
561
+ * @internal
562
+ */
563
+ requestLocalFlush() {
564
+ for (const category of RECONCILED_CATEGORIES) {
565
+ const event = {
566
+ CacheKey: category,
567
+ Category: category,
568
+ Action: 'category_cleared',
569
+ Timestamp: Date.now(),
570
+ SourceServerId: MJGlobal.Instance.ProcessUUID,
571
+ Epoch: this._lastSeenEpoch,
572
+ };
573
+ this.safeEmit('cacheChanged', event);
574
+ }
575
+ this.safeEmit('reconciliationRequired');
576
+ }
577
+ /** The Redis key holding the fleet-wide invalidation counter. @internal */
578
+ buildEpochKey() {
579
+ return `${this._keyPrefix}:__epoch__`;
580
+ }
203
581
  /**
204
582
  * Builds the full Redis key from a category and key name.
205
583
  *
@@ -225,6 +603,52 @@ export class RedisLocalStorageProvider {
225
603
  buildCategorySetKey(category) {
226
604
  return `${this._keyPrefix}:__categories__:${category}`;
227
605
  }
606
+ /**
607
+ * Builds the Redis Set key that indexes the keys written with one
608
+ * {@link LocalStorageWriteOptions.IndexGroup} in a category.
609
+ *
610
+ * Format: `{prefix}:__group__:{category}:{group}`
611
+ * @internal
612
+ */
613
+ buildGroupSetKey(category, group) {
614
+ return `${this._keyPrefix}:__group__:${category}:${group}`;
615
+ }
616
+ /**
617
+ * Resolves the TTL for one write: the per-call value when given (a bare number is the legacy
618
+ * `ttlSeconds` argument), then the category's own expiry, then the configured default. `0`
619
+ * means no expiry.
620
+ * @internal
621
+ */
622
+ resolveWriteOptions(options, category) {
623
+ const explicit = typeof options === 'number' ? options : options?.TTLSeconds;
624
+ const ttlSeconds = explicit ?? this._categoryTTLSeconds[category] ?? this._defaultTTLSeconds;
625
+ const group = typeof options === 'object' ? options.IndexGroup : undefined;
626
+ return { ttlSeconds: ttlSeconds > 0 ? Math.ceil(ttlSeconds) : 0, group };
627
+ }
628
+ /**
629
+ * Lists every Redis key matching a glob pattern with `SCAN`, which never blocks the server
630
+ * the way `KEYS` does. Used only for category-wide operations, not on the per-save path.
631
+ * @internal
632
+ */
633
+ async scanKeys(pattern) {
634
+ const found = [];
635
+ let cursor = '0';
636
+ do {
637
+ const [next, batch] = await this._client.scan(cursor, 'MATCH', pattern, 'COUNT', SCAN_BATCH);
638
+ found.push(...batch);
639
+ cursor = next;
640
+ } while (cursor !== '0');
641
+ return found;
642
+ }
643
+ /**
644
+ * Deletes Redis keys in fixed-size batches so one call never sends an unbounded argument list.
645
+ * @internal
646
+ */
647
+ async deleteKeys(redisKeys) {
648
+ for (let i = 0; i < redisKeys.length; i += SCAN_BATCH) {
649
+ await this._client.del(...redisKeys.slice(i, i + SCAN_BATCH));
650
+ }
651
+ }
228
652
  /**
229
653
  * Retrieves a value from Redis by key and optional category.
230
654
  *
@@ -246,6 +670,9 @@ export class RedisLocalStorageProvider {
246
670
  * ```
247
671
  */
248
672
  async GetItem(key, category) {
673
+ if (this.shouldFailFast) {
674
+ return null; // a miss: the caller refetches from the source of truth
675
+ }
249
676
  try {
250
677
  const redisKey = this.buildKey(key, category ?? DEFAULT_CATEGORY);
251
678
  const raw = await this._client.get(redisKey);
@@ -286,6 +713,12 @@ export class RedisLocalStorageProvider {
286
713
  const out = new Map();
287
714
  if (keys.length === 0)
288
715
  return out;
716
+ if (this.shouldFailFast) {
717
+ // Every key a miss — same answer MGET would give for absent keys.
718
+ for (const k of keys)
719
+ out.set(k, null);
720
+ return out;
721
+ }
289
722
  try {
290
723
  const cat = category ?? DEFAULT_CATEGORY;
291
724
  const uniqueKeys = Array.from(new Set(keys));
@@ -330,33 +763,37 @@ export class RedisLocalStorageProvider {
330
763
  * lose their prototype on retrieval; functions, Maps, Sets, and Dates have JSON's
331
764
  * usual limitations.
332
765
  *
333
- * If a `ttlSeconds` is provided, the key will automatically expire after that
334
- * duration. Otherwise, the configured `defaultTTLSeconds` is used. If neither
335
- * is set, the key persists indefinitely.
766
+ * The key expires after the per-call TTL when one is given, otherwise after the configured
767
+ * `defaultTTLSeconds`. If neither is set (or the value is `0`), the key persists indefinitely.
336
768
  *
337
- * The key is also added to a Redis Set that tracks all keys in the category,
338
- * enabling efficient `ClearCategory()` and `GetCategoryKeys()` operations.
769
+ * When the options carry an `IndexGroup`, the key is also added to that group's Redis Set so
770
+ * {@link GetIndexGroupKeys} can find it. The set is kept alive at least as long as its
771
+ * longest-lived member. There is no category-wide set: one would grow for ever once keys
772
+ * expire, because expiry never removes set members. Category-wide operations use `SCAN`.
339
773
  *
340
774
  * @typeParam T - Type of the value being stored. Caller-controlled.
341
775
  * @param key - The key to store under
342
776
  * @param value - The value to store (will be JSON-serialized internally)
343
777
  * @param category - Optional category for key isolation (defaults to `"default"`)
344
- * @param ttlSeconds - Optional time-to-live in seconds. Overrides `defaultTTLSeconds` from config.
778
+ * @param options - Expiry and index group. A bare number is accepted as the TTL in seconds.
345
779
  *
346
780
  * @example
347
781
  * ```typescript
348
782
  * // Store with default TTL
349
783
  * await provider.SetItem('view:users', { results, maxUpdatedAt }, 'RunViewCache');
350
784
  *
351
- * // Store with explicit 10-minute TTL
352
- * await provider.SetItem('view:users', { results }, 'RunViewCache', 600);
785
+ * // Store with explicit 10-minute TTL, indexed under the entity name
786
+ * await provider.SetItem('Users|…', { results }, 'RunViewCache', { TTLSeconds: 600, IndexGroup: 'Users' });
353
787
  * ```
354
788
  */
355
- async SetItem(key, value, category, ttlSeconds) {
789
+ async SetItem(key, value, category, options) {
790
+ if (this.shouldFailFast) {
791
+ this.noteMutationWhileDisconnected();
792
+ return;
793
+ }
356
794
  try {
357
795
  const cat = category ?? DEFAULT_CATEGORY;
358
796
  const redisKey = this.buildKey(key, cat);
359
- const categorySetKey = this.buildCategorySetKey(cat);
360
797
  // Serialize once. We need the string for both the Redis SET and (optionally)
361
798
  // the pub/sub publishChange payload, so build it up front.
362
799
  let serialized;
@@ -369,18 +806,18 @@ export class RedisLocalStorageProvider {
369
806
  }
370
807
  return;
371
808
  }
372
- const effectiveTTL = ttlSeconds ?? this._defaultTTLSeconds;
373
- // Use pipeline for atomic set + category tracking
809
+ const { ttlSeconds, group } = this.resolveWriteOptions(options, cat);
374
810
  const pipeline = this._client.pipeline();
375
- if (effectiveTTL && effectiveTTL > 0) {
376
- pipeline.setex(redisKey, effectiveTTL, serialized);
811
+ if (ttlSeconds > 0) {
812
+ pipeline.setex(redisKey, ttlSeconds, serialized);
377
813
  }
378
814
  else {
379
815
  pipeline.set(redisKey, serialized);
380
816
  }
381
- // Track this key in the category set for ClearCategory/GetCategoryKeys
382
- pipeline.sadd(categorySetKey, key);
383
- await pipeline.exec();
817
+ if (group) {
818
+ pipeline.eval(ADD_TO_GROUP_SCRIPT, 1, this.buildGroupSetKey(cat, group), key, ttlSeconds);
819
+ }
820
+ this.logPipelineErrors(await pipeline.exec(), `SetItem "${key}"`);
384
821
  // Publish cache change event for cross-server invalidation
385
822
  this.publishChange(key, cat, 'set', serialized);
386
823
  }
@@ -402,14 +839,15 @@ export class RedisLocalStorageProvider {
402
839
  * ```
403
840
  */
404
841
  async Remove(key, category) {
842
+ if (this.shouldFailFast) {
843
+ this.noteMutationWhileDisconnected();
844
+ return;
845
+ }
405
846
  try {
406
847
  const cat = category ?? DEFAULT_CATEGORY;
407
- const redisKey = this.buildKey(key, cat);
408
- const categorySetKey = this.buildCategorySetKey(cat);
409
- const pipeline = this._client.pipeline();
410
- pipeline.del(redisKey);
411
- pipeline.srem(categorySetKey, key);
412
- await pipeline.exec();
848
+ // Index-group membership is not touched here: the caller does not say which group the
849
+ // key was in, and GetIndexGroupKeys drops members whose key no longer exists.
850
+ await this._client.del(this.buildKey(key, cat));
413
851
  // Publish cache change event for cross-server invalidation
414
852
  this.publishChange(key, cat, 'removed');
415
853
  }
@@ -420,10 +858,11 @@ export class RedisLocalStorageProvider {
420
858
  }
421
859
  }
422
860
  /**
423
- * Clears all keys belonging to a specific category.
861
+ * Clears all keys belonging to a specific category, together with the category's index-group
862
+ * sets and the category set older versions of this provider maintained.
424
863
  *
425
- * Uses the category tracking Set to find all member keys, deletes them
426
- * in a single pipeline call, then removes the tracking Set itself.
864
+ * Keys are found with `SCAN`, so the operation also removes keys a peer wrote and keys whose
865
+ * index entry was lost.
427
866
  *
428
867
  * @param category - The category to clear. If empty, clears the `"default"` category.
429
868
  *
@@ -434,40 +873,58 @@ export class RedisLocalStorageProvider {
434
873
  * ```
435
874
  */
436
875
  async ClearCategory(category) {
876
+ await this.ClearCategoryChecked(category);
877
+ }
878
+ /**
879
+ * {@link ClearCategory}, but reporting what happened instead of swallowing it. An administrator
880
+ * running `mj cache clear` needs to know a category did NOT go: the old path logged (with
881
+ * logging off, by default, in the CLI) and returned normally, so the command printed a key
882
+ * count and "servers will reload" for a clear that never happened.
883
+ *
884
+ * While Redis is unreachable the clear is recorded for the reconnect flush and reported as not
885
+ * done — the flush will clear it, but reporting success now would be exactly the lie this
886
+ * method exists to stop.
887
+ *
888
+ * @returns Ok, plus the error when it failed.
889
+ */
890
+ async ClearCategoryChecked(category) {
891
+ if (this.shouldFailFast) {
892
+ this.noteMutationWhileDisconnected();
893
+ return { Ok: false, Error: 'Redis is unreachable; the clear is deferred to the reconnect flush' };
894
+ }
437
895
  try {
438
896
  const cat = category || DEFAULT_CATEGORY;
439
- const categorySetKey = this.buildCategorySetKey(cat);
440
- // Get all keys in this category
441
- const keys = await this._client.smembers(categorySetKey);
442
- if (keys.length > 0) {
443
- const pipeline = this._client.pipeline();
444
- // Delete each key
445
- for (const key of keys) {
446
- pipeline.del(this.buildKey(key, cat));
447
- }
448
- // Delete the category set itself
449
- pipeline.del(categorySetKey);
450
- await pipeline.exec();
451
- }
452
- else {
453
- // Category set might still exist even if empty
454
- await this._client.del(categorySetKey);
455
- }
897
+ const prefix = escapeGlob(this._keyPrefix);
898
+ const escapedCat = escapeGlob(cat);
899
+ // Index groups go FIRST, entries second. A write can land between the two scans, adding
900
+ // its entry and indexing it in a group. Scanning both and deleting together removed that
901
+ // group while the new entry survived — a live slot no index lists, which a save on another
902
+ // server can no longer find, so it is served stale until it expires. In this order the
903
+ // worst a racing write leaves is a group naming an entry that was then deleted, and a read
904
+ // of the group prunes dead members (GetIndexGroupKeys). A missing member heals itself; a
905
+ // missing index does not.
906
+ const groupKeys = await this.scanKeys(`${prefix}:__group__:${escapedCat}:*`);
907
+ await this.deleteKeys([...groupKeys, this.buildCategorySetKey(cat)]);
908
+ const entryKeys = await this.scanKeys(`${prefix}:${escapedCat}:*`);
909
+ await this.deleteKeys(entryKeys);
456
910
  // Publish category-level change event
457
911
  this.publishChange(cat, cat, 'category_cleared');
912
+ return { Ok: true };
458
913
  }
459
914
  catch (err) {
915
+ const message = err.message;
460
916
  if (this._enableLogging) {
461
- LogError(`Redis ClearCategory failed for "${category}": ${err.message}`);
917
+ LogError(`Redis ClearCategory failed for "${category}": ${message}`);
462
918
  }
919
+ return { Ok: false, Error: message };
463
920
  }
464
921
  }
465
922
  /**
466
- * Returns all keys belonging to a specific category.
923
+ * Returns all live keys belonging to a specific category.
467
924
  *
468
- * Reads from the category tracking Set, so the result reflects keys
469
- * that were added via `SetItem` (some may have expired via TTL but
470
- * will still appear in the set until cleaned up).
925
+ * Walks the keyspace with `SCAN`, so the cost grows with the whole keyspace. Meant for
926
+ * administration and diagnostics; per-entity lookups on the save path use
927
+ * {@link GetIndexGroupKeys}.
471
928
  *
472
929
  * @param category - The category to list keys from
473
930
  * @returns Array of original key names (without the Redis prefix/category prefix)
@@ -479,10 +936,14 @@ export class RedisLocalStorageProvider {
479
936
  * ```
480
937
  */
481
938
  async GetCategoryKeys(category) {
939
+ if (this.shouldFailFast) {
940
+ return []; // unknown rather than wrong: the caller treats it as nothing cached
941
+ }
482
942
  try {
483
943
  const cat = category || DEFAULT_CATEGORY;
484
- const categorySetKey = this.buildCategorySetKey(cat);
485
- return await this._client.smembers(categorySetKey);
944
+ const redisPrefix = this.buildKey('', cat);
945
+ const redisKeys = await this.scanKeys(`${escapeGlob(redisPrefix)}*`);
946
+ return redisKeys.map(k => k.substring(redisPrefix.length));
486
947
  }
487
948
  catch (err) {
488
949
  if (this._enableLogging) {
@@ -491,6 +952,199 @@ export class RedisLocalStorageProvider {
491
952
  return [];
492
953
  }
493
954
  }
955
+ /**
956
+ * Returns the keys written to `category` with `IndexGroup = group` that still exist.
957
+ *
958
+ * Members whose key has expired or been removed are dropped from the group set as a side
959
+ * effect, so the set shrinks back to the live keys whenever it is read. The read and the prune
960
+ * are one Lua script: a peer's `SADD` cannot land between them and be pruned unseen.
961
+ *
962
+ * @param category - The category the keys were written to
963
+ * @param group - The index group (for the RunView cache, the entity name)
964
+ * @returns The live keys, without the Redis prefix/category prefix
965
+ */
966
+ async GetIndexGroupKeys(category, group) {
967
+ if (this.shouldFailFast) {
968
+ // Only the save/delete path asks this — an entity just changed and its peers' slots need
969
+ // maintaining, which cannot happen now. Answering "none" alone would be wrong: the caller
970
+ // would write nothing, so nothing would record the change, the epoch would not move, and
971
+ // peers would keep those slots after the reconnect. Recording it makes reconciliation bump
972
+ // the epoch so they flush.
973
+ this.noteMutationWhileDisconnected();
974
+ return [];
975
+ }
976
+ try {
977
+ const cat = category || DEFAULT_CATEGORY;
978
+ const groupSetKey = this.buildGroupSetKey(cat, group);
979
+ const alive = await this._client.eval(PRUNE_GROUP_SCRIPT, 1, groupSetKey, this.buildKey('', cat));
980
+ return Array.isArray(alive) ? alive.map(m => String(m)) : [];
981
+ }
982
+ catch (err) {
983
+ if (this._enableLogging) {
984
+ LogError(`Redis GetIndexGroupKeys failed for "${category}"/"${group}": ${err.message}`);
985
+ }
986
+ return [];
987
+ }
988
+ }
989
+ /**
990
+ * Runs `work` holding an exclusive lock on `key` across every process sharing this keyspace.
991
+ *
992
+ * The lock is `SET {prefix}:__lock__:{category}:{key} <token> NX PX 10000`, retried every 20 ms
993
+ * for up to 5 s, and released only by its holder (compare-and-delete). The 10 s expiry frees a
994
+ * lock whose holder died; `work` is expected to be a short read-modify-write.
995
+ *
996
+ * @throws when the lock is not acquired in time; `work` has not run
997
+ */
998
+ async WithKeyLock(key, category, work) {
999
+ const lockKey = `${this._keyPrefix}:__lock__:${category || DEFAULT_CATEGORY}:${key}`;
1000
+ if (this.shouldFailFast) {
1001
+ // The SET NX would queue and never settle (see shouldFailFast). The caller's answer to a
1002
+ // lock it cannot take is to invalidate rather than write, which is right here too.
1003
+ throw new KeyLockTimeoutError(lockKey, 0, 'Redis is unreachable, so the lock was not attempted');
1004
+ }
1005
+ const token = randomUUID();
1006
+ await this.acquireLock(lockKey, token);
1007
+ // Work longer than the TTL used to lose the lock silently: it expired, another process took
1008
+ // it, and both wrote — the very lost update this lock exists to prevent. The lock is now
1009
+ // extended while the work runs, and a lock that was lost anyway (a stalled renewal, a
1010
+ // failover) is reported rather than ignored.
1011
+ const renewUntil = Date.now() + KEY_LOCK_MAX_HOLD_MS;
1012
+ // When the lock was last known to be ours. Every successful renewal moves it forward; it is
1013
+ // what the post-work check falls back on when Redis cannot be read at all.
1014
+ let confirmedAt = Date.now();
1015
+ const renewal = setInterval(() => {
1016
+ if (Date.now() >= renewUntil) {
1017
+ clearInterval(renewal);
1018
+ LogError(`Redis key lock "${lockKey}" has been held for ${KEY_LOCK_MAX_HOLD_MS} ms; no longer renewing it, so it expires on its own and other processes can proceed. The work holding it is hung.`);
1019
+ return;
1020
+ }
1021
+ this.renewLock(lockKey, token).then(() => { confirmedAt = Date.now(); }).catch(() => undefined);
1022
+ }, KEY_LOCK_RENEW_MS);
1023
+ if (typeof renewal === 'object' && renewal !== null && 'unref' in renewal) {
1024
+ renewal.unref();
1025
+ }
1026
+ try {
1027
+ const result = await work();
1028
+ if (!(await this.stillHoldsLock(lockKey, token, confirmedAt))) {
1029
+ throw new KeyLockLostError(lockKey);
1030
+ }
1031
+ return result;
1032
+ }
1033
+ finally {
1034
+ clearInterval(renewal);
1035
+ await this.releaseLock(lockKey, token);
1036
+ }
1037
+ }
1038
+ /** Extends this holder's lock. @internal */
1039
+ async renewLock(lockKey, token) {
1040
+ await this._client.eval(RENEW_LOCK_SCRIPT, 1, lockKey, token, String(KEY_LOCK_TTL_MS));
1041
+ }
1042
+ /**
1043
+ * Whether this holder's token is still the one in the lock.
1044
+ *
1045
+ * @param confirmedAt when the lock was last known to be ours (acquisition, or the most recent
1046
+ * renewal that actually landed)
1047
+ *
1048
+ * This used to answer `true` when the read failed, on the reasoning that an unreadable check
1049
+ * should not fail a write. But the failures are correlated: this read and the renewals share
1050
+ * one connection, so a read that throws means the renewals have been throwing too, and the
1051
+ * lock is most likely expired — the one case where "still mine" is both unverifiable and
1052
+ * probably false. The clock is the evidence that remains: a lock cannot outlive its TTL
1053
+ * measured from the last time we know it was ours.
1054
+ * @internal
1055
+ */
1056
+ async stillHoldsLock(lockKey, token, confirmedAt) {
1057
+ try {
1058
+ return (await this._client.get(lockKey)) === token;
1059
+ }
1060
+ catch {
1061
+ return Date.now() - confirmedAt < KEY_LOCK_TTL_MS;
1062
+ }
1063
+ }
1064
+ /**
1065
+ * Claims `{prefix}:__lease__:{name}` for `ttlMs` with `SET NX PX`, so one process in the fleet
1066
+ * runs a periodic job per period. The lease is not released; it expires.
1067
+ */
1068
+ async TryAcquireLease(name, ttlMs) {
1069
+ if (this.shouldFailFast) {
1070
+ return false; // not acquired: this tick's sweep or warm-up simply does not run here
1071
+ }
1072
+ const token = randomUUID();
1073
+ const claimed = (await this._client.set(this.leaseKey(name), token, 'PX', Math.max(1, Math.floor(ttlMs)), 'NX')) === 'OK';
1074
+ if (claimed) {
1075
+ this._leaseTokens.set(name, token);
1076
+ }
1077
+ return claimed;
1078
+ }
1079
+ /**
1080
+ * Extends a lease this provider holds, without being able to extend anyone else's: the script
1081
+ * only acts when the stored token is this provider's. A lease that has already expired and been
1082
+ * taken by another process is NOT stolen back — the caller learns it lost its turn.
1083
+ *
1084
+ * @returns true when this process still holds the lease afterwards.
1085
+ */
1086
+ async RenewLease(name, ttlMs) {
1087
+ const token = this._leaseTokens.get(name);
1088
+ if (!token) {
1089
+ return false;
1090
+ }
1091
+ if (this.shouldFailFast) {
1092
+ return false; // a lease that cannot be renewed must not be assumed held
1093
+ }
1094
+ const extended = await this._client.eval(RENEW_LOCK_SCRIPT, 1, this.leaseKey(name), token, String(Math.max(1, Math.floor(ttlMs))));
1095
+ return Number(extended) === 1;
1096
+ }
1097
+ /** Ends a lease this provider claimed, if it still holds it (compare-and-delete). */
1098
+ async ReleaseLease(name) {
1099
+ const token = this._leaseTokens.get(name);
1100
+ if (!token) {
1101
+ return;
1102
+ }
1103
+ this._leaseTokens.delete(name);
1104
+ if (this.shouldFailFast) {
1105
+ return; // the lease expires on its own TTL; nothing is lost by not deleting it now
1106
+ }
1107
+ await this.releaseLock(this.leaseKey(name), token);
1108
+ }
1109
+ leaseKey(name) {
1110
+ return `${this._keyPrefix}:__lease__:${name}`;
1111
+ }
1112
+ /** @internal */
1113
+ async acquireLock(lockKey, token) {
1114
+ const deadline = Date.now() + KEY_LOCK_WAIT_MS;
1115
+ for (;;) {
1116
+ if ((await this._client.set(lockKey, token, 'PX', KEY_LOCK_TTL_MS, 'NX')) === 'OK') {
1117
+ return;
1118
+ }
1119
+ if (Date.now() >= deadline) {
1120
+ throw new KeyLockTimeoutError(lockKey, KEY_LOCK_WAIT_MS);
1121
+ }
1122
+ await new Promise(resolve => setTimeout(resolve, KEY_LOCK_RETRY_MS));
1123
+ }
1124
+ }
1125
+ /** @internal */
1126
+ async releaseLock(lockKey, token) {
1127
+ try {
1128
+ await this._client.eval(RELEASE_LOCK_SCRIPT, 1, lockKey, token);
1129
+ }
1130
+ catch (err) {
1131
+ // The lock expires on its own; a failed release only delays the next writer.
1132
+ if (this._enableLogging) {
1133
+ LogError(`Redis lock release failed for "${lockKey}": ${err.message}`);
1134
+ }
1135
+ }
1136
+ }
1137
+ /** Logs any per-command failure a pipeline reported; `exec()` itself does not throw for them. @internal */
1138
+ logPipelineErrors(results, context) {
1139
+ if (!this._enableLogging || !results) {
1140
+ return;
1141
+ }
1142
+ for (const [err] of results) {
1143
+ if (err) {
1144
+ LogError(`Redis ${context}: ${err.message}`);
1145
+ }
1146
+ }
1147
+ }
494
1148
  /**
495
1149
  * Whether the Redis client currently has an active connection.
496
1150
  *
@@ -508,11 +1162,15 @@ export class RedisLocalStorageProvider {
508
1162
  * category tracking. Prefer the `ILocalStorageProvider` methods for
509
1163
  * standard operations.
510
1164
  *
1165
+ * For pub/sub, use {@link PublishMessage}, {@link PublishMessageAndWait} and
1166
+ * {@link SubscribeToChannel} instead: they share the provider's subscriber connection and
1167
+ * namespace channels with the key prefix.
1168
+ *
511
1169
  * @example
512
1170
  * ```typescript
513
- * // Use for Redis-specific commands like pub/sub, streams, etc.
1171
+ * // Use for Redis-specific commands the provider does not wrap, such as streams
514
1172
  * const client = provider.Client;
515
- * await client.publish('cache-invalidation', 'entity:Users');
1173
+ * await client.xadd('audit-events', '*', 'type', 'login');
516
1174
  * ```
517
1175
  */
518
1176
  get Client() {
@@ -547,9 +1205,11 @@ export class RedisLocalStorageProvider {
547
1205
  this._subscriber = null;
548
1206
  this._subscriberConnected = false;
549
1207
  }
1208
+ this._listening = null;
550
1209
  // Remove all event listeners
551
1210
  this._eventEmitter.removeAllListeners();
552
1211
  this._channelHandlers.clear();
1212
+ this._pendingChannelSubscribes.clear();
553
1213
  try {
554
1214
  await this._client.quit();
555
1215
  this._connected = false;
@@ -585,6 +1245,9 @@ export class RedisLocalStorageProvider {
585
1245
  * ```
586
1246
  */
587
1247
  async Exists(key, category) {
1248
+ if (this.shouldFailFast) {
1249
+ return false; // nothing is reachable, so nothing is cached as far as the caller is concerned
1250
+ }
588
1251
  try {
589
1252
  const redisKey = this.buildKey(key, category ?? DEFAULT_CATEGORY);
590
1253
  const result = await this._client.exists(redisKey);
@@ -614,6 +1277,9 @@ export class RedisLocalStorageProvider {
614
1277
  * ```
615
1278
  */
616
1279
  async GetTTL(key, category) {
1280
+ if (this.shouldFailFast) {
1281
+ return null; // unknown, which is what the catch below reports for an unreachable server
1282
+ }
617
1283
  try {
618
1284
  const redisKey = this.buildKey(key, category ?? DEFAULT_CATEGORY);
619
1285
  return await this._client.ttl(redisKey);
@@ -658,7 +1324,8 @@ export class RedisLocalStorageProvider {
658
1324
  * a client in subscribe mode cannot execute other commands).
659
1325
  *
660
1326
  * Must be called explicitly after construction. No-op if `enablePubSub` is `false`
661
- * in the config, or if already listening.
1327
+ * in the config. Concurrent and repeated calls share one start-up; if it fails, the
1328
+ * subscriber is discarded and the next call starts a fresh one.
662
1329
  *
663
1330
  * @example
664
1331
  * ```typescript
@@ -681,30 +1348,62 @@ export class RedisLocalStorageProvider {
681
1348
  }
682
1349
  return;
683
1350
  }
684
- if (this._subscriber) {
685
- // Already listening
686
- return;
1351
+ if (!this._listening) {
1352
+ const listening = this.openSubscriber();
1353
+ this._listening = listening;
1354
+ listening.catch(() => {
1355
+ if (this._listening === listening) {
1356
+ this._listening = null;
1357
+ }
1358
+ });
687
1359
  }
688
- this._subscriber = this.createSubscriberClient();
1360
+ return this._listening;
1361
+ }
1362
+ /**
1363
+ * Creates the subscriber connection and subscribes it to the cache-invalidation channel.
1364
+ *
1365
+ * The message listener is attached before subscribing, so nothing that arrives is missed. On
1366
+ * failure the connection is closed and cleared. A retry does not depend on that —
1367
+ * {@link StartListening} resets its own in-flight promise and opens a fresh subscriber — but the
1368
+ * failed client would otherwise stay open, reconnecting in the background with unlimited retries,
1369
+ * and once it got back in it would resubscribe and deliver every invalidation a second time.
1370
+ */
1371
+ async openSubscriber() {
1372
+ const subscriber = this.createSubscriberClient();
1373
+ this._subscriber = subscriber;
689
1374
  this.setupSubscriberEventHandlers();
690
- await this._subscriber.subscribe(this._pubSubChannel);
691
- if (this._enableLogging) {
692
- LogStatus(`Redis pub/sub: subscribed to channel "${this._pubSubChannel}"`);
693
- }
694
- this._subscriber.on('message', (channel, message) => {
1375
+ subscriber.on('message', (channel, message) => {
695
1376
  if (channel === this._pubSubChannel) {
696
1377
  this.handlePubSubMessage(message);
697
1378
  return;
698
1379
  }
699
1380
  this.dispatchChannelMessage(channel, message);
700
1381
  });
1382
+ try {
1383
+ await subscriber.subscribe(this._pubSubChannel);
1384
+ }
1385
+ catch (err) {
1386
+ this.discardSubscriber(subscriber);
1387
+ throw err;
1388
+ }
1389
+ if (this._enableLogging) {
1390
+ LogStatus(`Redis pub/sub: subscribed to channel "${this._pubSubChannel}"`);
1391
+ }
1392
+ }
1393
+ /** Closes a subscriber that failed to start, and clears it if it is still the current one. */
1394
+ discardSubscriber(subscriber) {
1395
+ subscriber.disconnect();
1396
+ if (this._subscriber === subscriber) {
1397
+ this._subscriber = null;
1398
+ this._subscriberConnected = false;
1399
+ }
701
1400
  }
702
1401
  /**
703
1402
  * Creates the subscriber Redis client, mirroring the main client's connection config.
704
1403
  * @internal
705
1404
  */
706
1405
  createSubscriberClient() {
707
- const maxRetries = this._config.maxRetries ?? 10;
1406
+ const maxRetries = this._config.maxRetries; // undefined = retry forever, with a capped delay
708
1407
  if (this._config.url) {
709
1408
  return new Redis(this._config.url, {
710
1409
  maxRetriesPerRequest: null,
@@ -729,13 +1428,24 @@ export class RedisLocalStorageProvider {
729
1428
  if (!this._subscriber)
730
1429
  return;
731
1430
  this._subscriber.on('connect', () => {
1431
+ const wasDown = this._subscriberHasEverConnected && !this._subscriberConnected;
732
1432
  this._subscriberConnected = true;
1433
+ this._subscriberHasEverConnected = true;
733
1434
  if (this._enableLogging) {
734
1435
  LogStatus('Redis pub/sub subscriber: connected');
735
1436
  }
1437
+ // Reconciliation hangs off the subscriber because that is the connection which misses
1438
+ // invalidations. ioredis resubscribes, but cannot replay what it missed.
1439
+ if (wasDown) {
1440
+ void this.reconcileAfterReconnect();
1441
+ }
736
1442
  });
737
1443
  this._subscriber.on('close', () => {
1444
+ const wasUp = this._subscriberConnected;
738
1445
  this._subscriberConnected = false;
1446
+ if (wasUp) {
1447
+ LogError('[Redis] pub/sub subscriber disconnected — invalidations from other servers are not arriving');
1448
+ }
739
1449
  });
740
1450
  this._subscriber.on('error', (err) => {
741
1451
  if (this._enableLogging) {
@@ -751,6 +1461,9 @@ export class RedisLocalStorageProvider {
751
1461
  handlePubSubMessage(message) {
752
1462
  try {
753
1463
  const event = JSON.parse(message);
1464
+ // Before the self-filter below: any event reaching this subscriber shows how far the
1465
+ // shared counter has advanced, regardless of who published it.
1466
+ this.noteEpochSeen(event.Epoch);
754
1467
  // Skip events from this server instance
755
1468
  if (event.SourceServerId === MJGlobal.Instance.ProcessUUID) {
756
1469
  return;
@@ -782,6 +1495,13 @@ export class RedisLocalStorageProvider {
782
1495
  if (!this._enablePubSub) {
783
1496
  return;
784
1497
  }
1498
+ const mode = action === 'category_cleared' ? 'full' : this.publishModeFor(category);
1499
+ if (mode === 'none') {
1500
+ return;
1501
+ }
1502
+ if (mode === 'notice') {
1503
+ data = undefined;
1504
+ }
785
1505
  const event = {
786
1506
  CacheKey: cacheKey,
787
1507
  Category: category,
@@ -790,59 +1510,126 @@ export class RedisLocalStorageProvider {
790
1510
  SourceServerId: MJGlobal.Instance.ProcessUUID,
791
1511
  Data: data,
792
1512
  };
793
- // Publish fire-and-forget — don't await, don't block the caller
794
- const payload = JSON.stringify(event);
795
- this._client.publish(this._pubSubChannel, payload).then(() => {
1513
+ // Bump the shared epoch, then publish carrying its new value. The counter lives here
1514
+ // because every PUBLISHED mutation routes through this method. A category whose publish mode
1515
+ // is 'none' returns above without bumping it, and correctly: the epoch tells a reconnecting
1516
+ // process whether it missed an EVENT, and no process ever receives one for such a category,
1517
+ // so there is nothing to miss. A write made while disconnected is recorded separately, before
1518
+ // this method is reached (see noteMutationWhileDisconnected). INCR has to precede PUBLISH so
1519
+ // the payload can carry the result, which costs a second round trip — off the caller's path,
1520
+ // since this method is fire-and-forget.
1521
+ this._client.incr(this.buildEpochKey()).then((epoch) => {
1522
+ this.noteEpochSeen(epoch);
1523
+ event.Epoch = epoch;
1524
+ return this._client.publish(this._pubSubChannel, JSON.stringify(event));
1525
+ }).then(() => {
796
1526
  if (this._enableLogging) {
797
1527
  LogStatus(`Redis pub/sub: published ${action} event for key "${cacheKey}" on channel "${this._pubSubChannel}"`);
798
1528
  }
799
1529
  }).catch((err) => {
1530
+ // Nobody heard this change, so record it for reconcileAfterReconnect to bump the epoch
1531
+ // on recovery and make the other servers flush.
1532
+ this.noteMutationWhileDisconnected();
800
1533
  if (this._enableLogging) {
801
1534
  LogError(`Redis pub/sub publish failed: ${err.message}`);
802
1535
  }
803
1536
  });
804
1537
  }
1538
+ /** The configured publish mode for a category. @internal */
1539
+ publishModeFor(category) {
1540
+ return this._config.publishModes?.[category] ?? this._config.defaultPublishMode ?? 'full';
1541
+ }
805
1542
  /**
806
1543
  * Publishes an arbitrary message on a named channel. Fire-and-forget: the promise is not
807
1544
  * awaited and a failure is logged rather than raised, so a caller on a hot path is never
808
- * blocked or broken by the message bus.
1545
+ * blocked or broken by the message bus. Does nothing when pub/sub is disabled.
1546
+ *
1547
+ * Use {@link PublishMessageAndWait} when the caller needs to know whether the message went out.
809
1548
  *
810
1549
  * The channel is namespaced with the provider's key prefix, so several applications can share
811
1550
  * one Redis without hearing each other.
812
1551
  *
813
1552
  * @param channel Logical channel name (unprefixed).
814
1553
  * @param payload Message body. Serialize before calling — this layer is shape-agnostic.
1554
+ * @throws If `channel` is the name reserved for cache invalidation.
815
1555
  */
816
1556
  PublishMessage(channel, payload) {
1557
+ const fullChannel = this.qualifyChannel(channel);
817
1558
  if (!this._enablePubSub) {
818
1559
  return;
819
1560
  }
820
- const fullChannel = this.qualifyChannel(channel);
1561
+ if (this.shouldFailFast) {
1562
+ return; // nobody can hear it; fire-and-forget callers already accept a lost message
1563
+ }
821
1564
  this._client.publish(fullChannel, payload).catch((err) => {
822
1565
  if (this._enableLogging) {
823
1566
  LogError(`Redis pub/sub publish failed on "${fullChannel}": ${err.message}`);
824
1567
  }
825
1568
  });
826
1569
  }
1570
+ /**
1571
+ * Publishes a message on a named channel and waits for Redis to accept it.
1572
+ *
1573
+ * Use this instead of {@link PublishMessage} when the caller must report honestly whether the
1574
+ * message went out — for example, telling a user whether a cancellation reached the server
1575
+ * running their request.
1576
+ *
1577
+ * While the connection is down the publish waits for it to come back rather than failing, so a
1578
+ * caller that needs a deadline should race it against a timeout.
1579
+ *
1580
+ * @param channel Logical channel name (unprefixed), namespaced as in {@link PublishMessage}.
1581
+ * @param payload Message body. Serialize before calling — this layer is shape-agnostic.
1582
+ * @returns The number of subscribers that received the message, across every process sharing
1583
+ * the Redis — including this one, if it subscribes to the same channel. Zero means the
1584
+ * message was published but nobody was listening.
1585
+ * @throws If pub/sub is disabled, if `channel` is reserved, or if Redis rejects the publish.
1586
+ */
1587
+ async PublishMessageAndWait(channel, payload) {
1588
+ const fullChannel = this.qualifyChannel(channel);
1589
+ if (!this._enablePubSub) {
1590
+ throw new Error(`Redis pub/sub: cannot publish on "${channel}" — the provider was created without enablePubSub`);
1591
+ }
1592
+ if (this.shouldFailFast) {
1593
+ return 0; // the truthful receiver count while Redis is unreachable
1594
+ }
1595
+ return this._client.publish(fullChannel, payload);
1596
+ }
827
1597
  /**
828
1598
  * Registers a handler for messages on a named channel, starting the subscriber if needed.
829
1599
  *
1600
+ * When pub/sub is disabled this registers nothing and returns an inert unsubscribe; check
1601
+ * {@link IsPubSubEnabled} to tell that apart from a live subscription.
1602
+ *
830
1603
  * No echo suppression happens here — this layer does not know the payload shape. A publisher
831
1604
  * that needs it must stamp its own origin on the message and check it in the handler.
832
1605
  *
833
- * @returns A function that removes this handler.
1606
+ * Redis does not replay messages, so anything published while the subscriber is disconnected
1607
+ * is never delivered.
1608
+ *
1609
+ * @param channel Logical channel name (unprefixed), namespaced as in {@link PublishMessage}.
1610
+ * @param handler Called with each message body. May be async.
1611
+ * @returns A function that removes this handler. When the last handler on a channel is
1612
+ * removed, the provider unsubscribes from it in Redis.
1613
+ * @throws If `channel` is reserved, or if Redis rejects the subscribe.
834
1614
  */
835
1615
  async SubscribeToChannel(channel, handler) {
1616
+ const fullChannel = this.qualifyChannel(channel);
836
1617
  if (!this._enablePubSub) {
837
1618
  return () => undefined;
838
1619
  }
1620
+ if (this.shouldFailFast) {
1621
+ // The SUBSCRIBE would queue and never settle. Fail loudly instead, so the caller can
1622
+ // degrade and say so rather than await forever.
1623
+ throw new Error(`Redis is unreachable; cannot subscribe to "${channel}" until it reconnects`);
1624
+ }
839
1625
  await this.StartListening();
840
- const fullChannel = this.qualifyChannel(channel);
841
1626
  const handlers = await this.channelHandlersFor(fullChannel);
842
1627
  handlers.add(handler);
843
- return () => {
844
- handlers.delete(handler);
845
- };
1628
+ return () => this.removeChannelHandler(fullChannel, handlers, handler);
1629
+ }
1630
+ /** Whether the provider was created with `enablePubSub`. When false, the channel methods do nothing. */
1631
+ get IsPubSubEnabled() {
1632
+ return this._enablePubSub;
846
1633
  }
847
1634
  /**
848
1635
  * The handler set for a channel, subscribing first when no caller has yet.
@@ -875,7 +1662,10 @@ export class RedisLocalStorageProvider {
875
1662
  * with nothing surfaced.
876
1663
  */
877
1664
  async subscribeChannel(fullChannel) {
878
- await this._subscriber?.subscribe(fullChannel);
1665
+ if (!this._subscriber) {
1666
+ throw new Error(`Redis pub/sub: cannot subscribe to "${fullChannel}" — the subscriber is not running`);
1667
+ }
1668
+ await this._subscriber.subscribe(fullChannel);
879
1669
  const handlers = new Set();
880
1670
  this._channelHandlers.set(fullChannel, handlers);
881
1671
  if (this._enableLogging) {
@@ -883,6 +1673,28 @@ export class RedisLocalStorageProvider {
883
1673
  }
884
1674
  return handlers;
885
1675
  }
1676
+ /**
1677
+ * Removes one handler, and unsubscribes the channel in Redis when it was the last.
1678
+ *
1679
+ * Safe to call more than once. A handler set that is no longer the channel's current one
1680
+ * belongs to a subscription already released, so it never triggers a second unsubscribe. A
1681
+ * subscribe that arrives while the unsubscribe is in flight is queued behind it on the same
1682
+ * connection, so the channel ends up subscribed.
1683
+ */
1684
+ removeChannelHandler(fullChannel, handlers, handler) {
1685
+ if (!handlers.delete(handler) || handlers.size > 0) {
1686
+ return;
1687
+ }
1688
+ if (this._channelHandlers.get(fullChannel) !== handlers) {
1689
+ return;
1690
+ }
1691
+ this._channelHandlers.delete(fullChannel);
1692
+ this._subscriber?.unsubscribe(fullChannel).catch((err) => {
1693
+ if (this._enableLogging) {
1694
+ LogError(`Redis pub/sub unsubscribe failed on "${fullChannel}": ${err.message}`);
1695
+ }
1696
+ });
1697
+ }
886
1698
  /** Routes an inbound message to the handlers registered for its channel. @internal */
887
1699
  dispatchChannelMessage(channel, message) {
888
1700
  const handlers = this._channelHandlers.get(channel);
@@ -890,19 +1702,40 @@ export class RedisLocalStorageProvider {
890
1702
  return;
891
1703
  }
892
1704
  for (const handler of handlers) {
893
- try {
894
- handler(message);
895
- }
896
- catch (err) {
897
- if (this._enableLogging) {
898
- LogError(`Redis pub/sub handler for "${channel}" threw: ${err.message}`);
899
- }
1705
+ this.invokeChannelHandler(channel, handler, message);
1706
+ }
1707
+ }
1708
+ /**
1709
+ * Runs one handler, containing a throw or a rejected promise so the other handlers still run.
1710
+ *
1711
+ * Failures are logged even when `enableLogging` is off: that setting quiets connection noise,
1712
+ * and a failing handler is a defect in the consumer that would otherwise vanish.
1713
+ */
1714
+ invokeChannelHandler(channel, handler, message) {
1715
+ const report = (err) => {
1716
+ LogError(`Redis pub/sub handler for "${channel}" failed: ${err instanceof Error ? err.message : String(err)}`);
1717
+ };
1718
+ try {
1719
+ const result = handler(message);
1720
+ if (result instanceof Promise) {
1721
+ result.catch(report);
900
1722
  }
901
1723
  }
1724
+ catch (err) {
1725
+ report(err);
1726
+ }
902
1727
  }
903
- /** Namespaces a channel with the provider's key prefix. @internal */
1728
+ /**
1729
+ * Namespaces a channel with the provider's key prefix.
1730
+ * @throws If the result is the channel reserved for cache invalidation, where a message would
1731
+ * be read as a cache change by every server.
1732
+ */
904
1733
  qualifyChannel(channel) {
905
- return `${this._keyPrefix}:${channel}`;
1734
+ const fullChannel = `${this._keyPrefix}:${channel}`;
1735
+ if (fullChannel === this._pubSubChannel) {
1736
+ throw new Error(`Redis pub/sub: channel "${channel}" is reserved for cache invalidation`);
1737
+ }
1738
+ return fullChannel;
906
1739
  }
907
1740
  /**
908
1741
  * Registers a callback for cache change events from other servers.
@@ -938,5 +1771,132 @@ export class RedisLocalStorageProvider {
938
1771
  get IsSubscriberConnected() {
939
1772
  return this._subscriberConnected;
940
1773
  }
1774
+ /**
1775
+ * Registers a callback for the loss of the Redis connection.
1776
+ *
1777
+ * Fires on a transition only — not on the first connect, and not again while a reconnect is
1778
+ * being retried. {@link IsConnected} reports the current state but not that it changed, so a
1779
+ * consumer wanting to degrade or report health needs this rather than a poll.
1780
+ *
1781
+ * Use this in preference to reading the log: status-level logging is suppressed when
1782
+ * `GetProductionStatus()` is true, so a deployed process says nothing when its cache client
1783
+ * dies.
1784
+ *
1785
+ * @param callback - Invoked with a short human-readable reason for the loss
1786
+ * @returns A function that removes this registration
1787
+ *
1788
+ * @example
1789
+ * ```typescript
1790
+ * const stop = provider.OnConnectionLost(reason => health.markCacheDown(reason));
1791
+ * provider.OnConnectionRestored(() => health.markCacheUp());
1792
+ * ```
1793
+ */
1794
+ OnConnectionLost(callback) {
1795
+ this._eventEmitter.on('connectionLost', callback);
1796
+ return () => {
1797
+ this._eventEmitter.off('connectionLost', callback);
1798
+ };
1799
+ }
1800
+ /**
1801
+ * Registers a callback for the Redis connection being restored after a loss. Not fired for the
1802
+ * first connection.
1803
+ *
1804
+ * Cache correctness after the gap is handled by the provider itself; see
1805
+ * {@link OnReconciliationRequired} for the signal that local state had to be dropped.
1806
+ *
1807
+ * @param callback - Invoked when the connection comes back
1808
+ * @returns A function that removes this registration
1809
+ */
1810
+ OnConnectionRestored(callback) {
1811
+ this._eventEmitter.on('connectionRestored', callback);
1812
+ return () => {
1813
+ this._eventEmitter.off('connectionRestored', callback);
1814
+ };
1815
+ }
1816
+ /**
1817
+ * Registers a callback for the provider having concluded, after a connection gap, that local
1818
+ * cache state must be dropped.
1819
+ *
1820
+ * The standard categories are flushed by the provider itself via {@link OnCacheChanged}. Use
1821
+ * this for state those categories do not describe — an in-process engine, a derived index, a
1822
+ * memoized permission set — which would otherwise survive a reconnect while stale.
1823
+ *
1824
+ * Does not fire when nothing was invalidated anywhere during the gap.
1825
+ *
1826
+ * @param callback - Invoked when a flush is required
1827
+ * @returns A function that removes this registration
1828
+ */
1829
+ OnReconciliationRequired(callback) {
1830
+ this._eventEmitter.on('reconciliationRequired', callback);
1831
+ return () => {
1832
+ this._eventEmitter.off('reconciliationRequired', callback);
1833
+ };
1834
+ }
1835
+ /**
1836
+ * The highest fleet-wide epoch this process has observed. Exposed for diagnostics and for tests
1837
+ * that need to assert what reconciliation decided; consumers should not need it.
1838
+ */
1839
+ get LastSeenEpoch() {
1840
+ return this._lastSeenEpoch;
1841
+ }
1842
+ /**
1843
+ * Reports a lost connection once per outage.
1844
+ *
1845
+ * Both routes into this are repeatable: `close` fires on every failed reconnection attempt, and an
1846
+ * exhausted retry ceiling arrives separately after one. Consumers get a single notification, and
1847
+ * the next `ready` clears the latch so the following outage reports again.
1848
+ *
1849
+ * @internal
1850
+ */
1851
+ noteConnectionLost(reason) {
1852
+ if (this._connectionLostEmitted) {
1853
+ return;
1854
+ }
1855
+ this._connectionLostEmitted = true;
1856
+ this.emitConnectionLost(reason);
1857
+ }
1858
+ /**
1859
+ * Raises the public lost-connection event and logs it.
1860
+ *
1861
+ * Uses the error channel, and is not gated behind `enableLogging`: status-level output is
1862
+ * suppressed in production and that flag is routinely turned off, either of which would leave a
1863
+ * dead cache client silent.
1864
+ *
1865
+ * @internal
1866
+ */
1867
+ emitConnectionLost(reason) {
1868
+ LogError(`[Redis] connection lost (${reason}) — cache reads will miss and writes will no-op until it returns`);
1869
+ this.safeEmit('connectionLost', reason);
1870
+ }
1871
+ /**
1872
+ * Raises the public restored-connection event and logs it, on the error channel for the same
1873
+ * reason as the loss — otherwise the logs show an outage that never ends.
1874
+ *
1875
+ * @internal
1876
+ */
1877
+ emitConnectionRestored() {
1878
+ LogError('[Redis] connection restored');
1879
+ this.safeEmit('connectionRestored');
1880
+ }
1881
+ /**
1882
+ * Emits to consumer callbacks, containing each listener's errors so that neither the connection
1883
+ * handling that triggered the event nor the other listeners are affected.
1884
+ *
1885
+ * Invokes listeners individually rather than through `EventEmitter.emit`, which calls them
1886
+ * synchronously in turn: one throwing there would stop every listener after it from running at
1887
+ * all.
1888
+ *
1889
+ * @internal
1890
+ */
1891
+ safeEmit(event, ...args) {
1892
+ for (const listener of this._eventEmitter.rawListeners(event)) {
1893
+ try {
1894
+ listener(...args);
1895
+ }
1896
+ catch (err) {
1897
+ LogError(`[Redis] a ${event} listener threw: ${err.message}`);
1898
+ }
1899
+ }
1900
+ }
941
1901
  }
942
1902
  //# sourceMappingURL=RedisLocalStorageProvider.js.map