@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.
@@ -16,7 +16,7 @@
16
16
  import Redis from 'ioredis';
17
17
  import type { RedisOptions } from 'ioredis';
18
18
  import { ILocalStorageProvider } from '@memberjunction/core';
19
- import type { CacheChangedEvent } from '@memberjunction/core';
19
+ import type { CacheChangedEvent, LocalStorageWriteOptions } from '@memberjunction/core';
20
20
  /**
21
21
  * Configuration options for the Redis local storage provider.
22
22
  *
@@ -69,20 +69,47 @@ export interface RedisProviderConfig {
69
69
  keyPrefix?: string;
70
70
  /**
71
71
  * Default time-to-live in seconds applied to every `SetItem` call
72
- * unless overridden by the `ttlSeconds` parameter.
72
+ * unless the call passes its own TTL.
73
73
  *
74
- * Set to `0` or `undefined` to store keys without expiration (persistent).
74
+ * Event-driven invalidation stays the primary freshness mechanism; the TTL bounds how long
75
+ * an entry written by a process that never publishes (a direct SQL change, another
76
+ * application) can be served, and gives a `volatile-*` eviction policy something to evict —
77
+ * Redis never evicts a key without an expiry under those policies.
75
78
  *
76
- * @default undefined (no expiration)
79
+ * Set to `0` to store keys without expiration (persistent).
80
+ *
81
+ * @default 3600 (one hour)
77
82
  */
78
83
  defaultTTLSeconds?: number;
79
84
  /**
80
- * Maximum number of connection retry attempts before giving up.
81
- * Each retry uses exponential backoff (doubling delay up to 30 seconds).
85
+ * Expiry per category, overriding {@link defaultTTLSeconds} (0 = no expiry). **Merged over**
86
+ * the built-in `{ default: 0 }` rather than replacing it, so setting one category never
87
+ * changes another; name `default` here to override even that.
88
+ *
89
+ * The `default` category holds **proxy keys**: entries that vouch for other entries. The
90
+ * metadata snapshot's timestamps key is written after the payload it describes, and a dataset's
91
+ * `_date` key after its blob — so under one blanket TTL the proxy outlives what it vouches for,
92
+ * and a reader finds a freshness claim with nothing behind it. A server booting into that
93
+ * window adopted the timestamps and served empty metadata as current; the dataset check threw.
94
+ */
95
+ categoryTTLSeconds?: Readonly<Record<string, number>>;
96
+ /**
97
+ * Caps reconnection attempts. Past the cap ioredis stops reconnecting for the life of the
98
+ * client, leaving the process cache-blind until it restarts.
82
99
  *
83
- * @default 10
100
+ * Omit it on a long-running process. Set it only for a short-lived script that should fail
101
+ * rather than wait out an outage.
102
+ *
103
+ * @default undefined — retry indefinitely, with each wait capped by {@link maxRetryDelayMs}
84
104
  */
85
105
  maxRetries?: number;
106
+ /**
107
+ * Ceiling on the wait between reconnection attempts, in milliseconds. The backoff doubles from
108
+ * 200ms up to this value and then holds there, so a long outage costs one attempt per ceiling.
109
+ *
110
+ * @default 30000
111
+ */
112
+ maxRetryDelayMs?: number;
86
113
  /**
87
114
  * Whether to log connection events (connect, disconnect, error) via
88
115
  * MemberJunction's `LogStatus` / `LogError` functions.
@@ -103,6 +130,58 @@ export interface RedisProviderConfig {
103
130
  * @default false
104
131
  */
105
132
  enablePubSub?: boolean;
133
+ /**
134
+ * What a `set` or `removed` publishes, per category (the category `default` covers writes
135
+ * without one). `category_cleared` is always published in full.
136
+ *
137
+ * - `'full'` — the event carries the stored value in `Data`, so a subscriber can apply it
138
+ * without reading Redis. Right for categories whose values subscribers adopt (the RunView
139
+ * cache: engines apply the rows).
140
+ * - `'notice'` — the event names the key but carries no value. Right for large values that
141
+ * subscribers only need to know changed (the metadata snapshot: a server that hears about it
142
+ * re-checks its metadata against the database).
143
+ * - `'none'` — nothing is published.
144
+ *
145
+ * Categories not listed use {@link defaultPublishMode}.
146
+ */
147
+ publishModes?: Readonly<Record<string, CachePublishMode>>;
148
+ /**
149
+ * Publish mode for categories not named in {@link publishModes}.
150
+ * @default 'full' (every change carries its value — the behaviour before modes existed)
151
+ */
152
+ defaultPublishMode?: CachePublishMode;
153
+ }
154
+ /** How much a cache write publishes. See {@link RedisProviderConfig.publishModes}. */
155
+ export type CachePublishMode = 'full' | 'notice' | 'none';
156
+ /**
157
+ * Receives a message published on a named channel. May be async; a thrown error or rejected
158
+ * promise is logged and does not stop the other handlers on the channel.
159
+ */
160
+ export type ChannelMessageHandler = (message: string) => void | Promise<void>;
161
+ /**
162
+ * Thrown by {@link RedisLocalStorageProvider.WithKeyLock} when the lock could not be taken in
163
+ * time — distinct from anything `work` itself throws, so a caller can tell "another process is
164
+ * holding this slot" (fall back to invalidating it) from "my own read-modify-write is broken"
165
+ * (a bug, which must not be silently downgraded to an invalidation).
166
+ */
167
+ export declare class KeyLockTimeoutError extends Error {
168
+ readonly LockKey: string;
169
+ /**
170
+ * @param LockKey The lock that could not be taken.
171
+ * @param waitedMs How long the attempt waited.
172
+ * @param reason Why, when it was not contention — e.g. Redis being unreachable. Defaults to the
173
+ * contention message. The class (and so its `name`) is kept either way, because the caller's
174
+ * correct response is the same: do not write, invalidate instead.
175
+ */
176
+ constructor(LockKey: string, waitedMs: number, reason?: string);
177
+ }
178
+ /**
179
+ * Thrown when a held lock expired before its work finished — the work may have raced another
180
+ * writer, so its result must not be trusted.
181
+ */
182
+ export declare class KeyLockLostError extends Error {
183
+ readonly LockKey: string;
184
+ constructor(LockKey: string);
106
185
  }
107
186
  /**
108
187
  * Redis-backed implementation of the MemberJunction {@link ILocalStorageProvider} interface.
@@ -120,8 +199,11 @@ export interface RedisProviderConfig {
120
199
  * - **category** — maps to the MJ cache category (`RunViewCache`, `Metadata`, `DatasetCache`, etc.)
121
200
  * - **key** — the original key from the caller
122
201
  *
123
- * Categories are tracked in a Redis Set at `{prefix}:__categories__:{category}` so that
124
- * `ClearCategory()` and `GetCategoryKeys()` operations are efficient.
202
+ * Keys written with an `IndexGroup` are also recorded in a Redis Set at
203
+ * `{prefix}:__group__:{category}:{group}` (the RunView cache uses the entity name), which
204
+ * `GetIndexGroupKeys()` reads and prunes. `ClearCategory()` and `GetCategoryKeys()` walk the
205
+ * keyspace with `SCAN`; no category-wide set is kept, because expiry never removes set members
206
+ * and such a set grows without bound once keys carry a TTL.
125
207
  *
126
208
  * ### TTL Support
127
209
  *
@@ -156,11 +238,54 @@ export declare class RedisLocalStorageProvider implements ILocalStorageProvider
156
238
  * See {@link ILocalStorageProvider.SharesReferences}.
157
239
  */
158
240
  readonly SharesReferences = false;
241
+ /**
242
+ * `true` — that is the whole point of this provider: every server in the fleet reads what any
243
+ * other wrote. See {@link ILocalStorageProvider.SupportsCrossProcessPersistence}.
244
+ */
245
+ readonly SupportsCrossProcessPersistence = true;
246
+ /**
247
+ * `true` — every process configured with the same URL and key prefix shares this keyspace.
248
+ * See {@link ILocalStorageProvider.SharedAcrossProcesses}.
249
+ */
250
+ readonly SharedAcrossProcesses = true;
159
251
  private _client;
160
252
  private _keyPrefix;
161
253
  private _defaultTTLSeconds;
254
+ private _categoryTTLSeconds;
162
255
  private _enableLogging;
256
+ /** Tokens of the leases this provider holds, so it releases only its own. */
257
+ private readonly _leaseTokens;
163
258
  private _connected;
259
+ /** Ceiling on the reconnect delay. See {@link RedisProviderConfig.maxRetryDelayMs}. */
260
+ private _maxRetryDelayMs;
261
+ /**
262
+ * Whether this client has ever been connected. Distinguishes a startup that has not reached
263
+ * Redis yet, where queueing a command is useful, from a connection that was lost, where
264
+ * {@link shouldFailFast} applies.
265
+ */
266
+ private _hasEverConnected;
267
+ /**
268
+ * The highest shared epoch this process has seen, from its own mutations and from events
269
+ * received. {@link reconcileAfterReconnect} compares it against the value in Redis to decide
270
+ * whether anything was invalidated during a connection gap.
271
+ */
272
+ private _lastSeenEpoch;
273
+ /**
274
+ * Whether this process mutated shared state while disconnected, meaning other servers never
275
+ * received those invalidations. Set so {@link reconcileAfterReconnect} can bump the epoch on
276
+ * recovery and make them flush.
277
+ */
278
+ private _mutatedWhileDisconnected;
279
+ /** Guards against two overlapping reconciliations (client and subscriber both recover). */
280
+ private _reconciling;
281
+ /**
282
+ * Whether the loss of this connection has already been reported to consumers. Reports the loss
283
+ * once per outage — `close` fires on every failed reconnection attempt — and tells the `ready`
284
+ * handler that a recovery, rather than a first connection, is what it is seeing.
285
+ */
286
+ private _connectionLostEmitted;
287
+ /** As {@link _hasEverConnected}, for the subscriber connection. */
288
+ private _subscriberHasEverConnected;
164
289
  private _enablePubSub;
165
290
  private _subscriber;
166
291
  private _pubSubChannel;
@@ -170,6 +295,8 @@ export declare class RedisLocalStorageProvider implements ILocalStorageProvider
170
295
  private _channelHandlers;
171
296
  /** Fully-qualified channel name -> the subscribe still in flight, shared by concurrent callers. */
172
297
  private _pendingChannelSubscribes;
298
+ /** The subscriber start-up in flight or completed, shared by every caller of {@link StartListening}. */
299
+ private _listening;
173
300
  private _config;
174
301
  /**
175
302
  * Creates a new Redis local storage provider and establishes a connection.
@@ -215,12 +342,98 @@ export declare class RedisLocalStorageProvider implements ILocalStorageProvider
215
342
  * @internal
216
343
  */
217
344
  private retryStrategy;
345
+ /**
346
+ * Registers event handlers on the ioredis client for logging connection
347
+ * lifecycle events (connect, ready, close, error, reconnecting).
348
+ * @internal
349
+ */
350
+ private handleClientConnect;
351
+ /**
352
+ * On `ready` the client can serve commands again. A recovery is identified by
353
+ * {@link _connectionLostEmitted} rather than by inspecting `_connected`: ioredis emits `connect`
354
+ * before `ready`, so by this point `_connected` has already been set back to true and cannot
355
+ * distinguish a reconnect from a first connection.
356
+ *
357
+ * @internal
358
+ */
359
+ private handleClientReady;
360
+ /**
361
+ * `close` fires once per failed reconnection attempt, not only on the first drop, so the loss is
362
+ * announced through {@link noteConnectionLost} and reported once per outage.
363
+ *
364
+ * @internal
365
+ */
366
+ private handleClientClose;
218
367
  /**
219
368
  * Registers event handlers on the ioredis client for logging connection
220
369
  * lifecycle events (connect, ready, close, error, reconnecting).
221
370
  * @internal
222
371
  */
223
372
  private setupEventHandlers;
373
+ /**
374
+ * Whether a command should fail immediately instead of being handed to ioredis.
375
+ *
376
+ * True once a connection has been established and then lost. The clients set
377
+ * `maxRetriesPerRequest: null` and leave ioredis's offline queue enabled, so a command issued
378
+ * while disconnected is queued and its promise never settles — over a long outage that is
379
+ * unbounded memory and indefinitely hanging awaits. Callers instead get a miss from a read and
380
+ * a no-op from a write, both of which are correct and only slower.
381
+ *
382
+ * False before the first connection, so a brief queue can still warm the cache at startup.
383
+ * Nothing is stale at that point because nothing is cached.
384
+ *
385
+ * @internal
386
+ */
387
+ private get shouldFailFast();
388
+ /**
389
+ * Records the highest epoch this process has observed, from either direction — a mutation it
390
+ * published, or an event it received. Monotonic: a late-arriving lower value is ignored.
391
+ * @internal
392
+ */
393
+ private noteEpochSeen;
394
+ /**
395
+ * Records that shared state changed while this process could not tell anyone.
396
+ *
397
+ * Reconciliation has to be symmetric. The obvious direction is what this process MISSED, and the
398
+ * epoch comparison covers that. This is the other direction: writes this process made that its
399
+ * siblings never heard, which leave *them* confidently stale. On recovery the epoch is bumped so
400
+ * they flush too.
401
+ * @internal
402
+ */
403
+ private noteMutationWhileDisconnected;
404
+ /**
405
+ * Decides whether this process's caches are still trustworthy after a reconnect, and flushes
406
+ * them if not.
407
+ *
408
+ * ioredis resubscribes on its own, but pub/sub has no replay: invalidations published while this
409
+ * process was disconnected are gone, so the cache may hold entries other servers have already
410
+ * invalidated. One read of the shared epoch counter settles it:
411
+ *
412
+ * - unchanged — nothing was invalidated anywhere during the gap, so the cache is kept
413
+ * - advanced — something changed and this process cannot know what, so everything is dropped
414
+ * - this process mutated while disconnected — the epoch is bumped so siblings flush too, and
415
+ * the cache is dropped here as well
416
+ *
417
+ * An epoch that cannot be read is treated as advanced: without evidence of correctness, flush.
418
+ *
419
+ * @internal
420
+ */
421
+ private reconcileAfterReconnect;
422
+ /**
423
+ * Tells local consumers to drop everything they hold.
424
+ *
425
+ * Expressed as a `category_cleared` event per shared category rather than a new event type,
426
+ * because that action already means "assume nothing in this category is valid" and
427
+ * `LocalCacheManager.DispatchCacheChange` already fans it out to EVERY registered callback. A
428
+ * bespoke event would need every consumer taught about it; this one is understood today.
429
+ *
430
+ * `SourceServerId` is this process deliberately — the flush is local, and a sibling receiving it
431
+ * would filter it out as self-originated anyway since it is never published.
432
+ * @internal
433
+ */
434
+ private requestLocalFlush;
435
+ /** The Redis key holding the fleet-wide invalidation counter. @internal */
436
+ private buildEpochKey;
224
437
  /**
225
438
  * Builds the full Redis key from a category and key name.
226
439
  *
@@ -242,6 +455,32 @@ export declare class RedisLocalStorageProvider implements ILocalStorageProvider
242
455
  * @internal
243
456
  */
244
457
  private buildCategorySetKey;
458
+ /**
459
+ * Builds the Redis Set key that indexes the keys written with one
460
+ * {@link LocalStorageWriteOptions.IndexGroup} in a category.
461
+ *
462
+ * Format: `{prefix}:__group__:{category}:{group}`
463
+ * @internal
464
+ */
465
+ private buildGroupSetKey;
466
+ /**
467
+ * Resolves the TTL for one write: the per-call value when given (a bare number is the legacy
468
+ * `ttlSeconds` argument), then the category's own expiry, then the configured default. `0`
469
+ * means no expiry.
470
+ * @internal
471
+ */
472
+ private resolveWriteOptions;
473
+ /**
474
+ * Lists every Redis key matching a glob pattern with `SCAN`, which never blocks the server
475
+ * the way `KEYS` does. Used only for category-wide operations, not on the per-save path.
476
+ * @internal
477
+ */
478
+ private scanKeys;
479
+ /**
480
+ * Deletes Redis keys in fixed-size batches so one call never sends an unbounded argument list.
481
+ * @internal
482
+ */
483
+ private deleteKeys;
245
484
  /**
246
485
  * Retrieves a value from Redis by key and optional category.
247
486
  *
@@ -285,29 +524,30 @@ export declare class RedisLocalStorageProvider implements ILocalStorageProvider
285
524
  * lose their prototype on retrieval; functions, Maps, Sets, and Dates have JSON's
286
525
  * usual limitations.
287
526
  *
288
- * If a `ttlSeconds` is provided, the key will automatically expire after that
289
- * duration. Otherwise, the configured `defaultTTLSeconds` is used. If neither
290
- * is set, the key persists indefinitely.
527
+ * The key expires after the per-call TTL when one is given, otherwise after the configured
528
+ * `defaultTTLSeconds`. If neither is set (or the value is `0`), the key persists indefinitely.
291
529
  *
292
- * The key is also added to a Redis Set that tracks all keys in the category,
293
- * enabling efficient `ClearCategory()` and `GetCategoryKeys()` operations.
530
+ * When the options carry an `IndexGroup`, the key is also added to that group's Redis Set so
531
+ * {@link GetIndexGroupKeys} can find it. The set is kept alive at least as long as its
532
+ * longest-lived member. There is no category-wide set: one would grow for ever once keys
533
+ * expire, because expiry never removes set members. Category-wide operations use `SCAN`.
294
534
  *
295
535
  * @typeParam T - Type of the value being stored. Caller-controlled.
296
536
  * @param key - The key to store under
297
537
  * @param value - The value to store (will be JSON-serialized internally)
298
538
  * @param category - Optional category for key isolation (defaults to `"default"`)
299
- * @param ttlSeconds - Optional time-to-live in seconds. Overrides `defaultTTLSeconds` from config.
539
+ * @param options - Expiry and index group. A bare number is accepted as the TTL in seconds.
300
540
  *
301
541
  * @example
302
542
  * ```typescript
303
543
  * // Store with default TTL
304
544
  * await provider.SetItem('view:users', { results, maxUpdatedAt }, 'RunViewCache');
305
545
  *
306
- * // Store with explicit 10-minute TTL
307
- * await provider.SetItem('view:users', { results }, 'RunViewCache', 600);
546
+ * // Store with explicit 10-minute TTL, indexed under the entity name
547
+ * await provider.SetItem('Users|…', { results }, 'RunViewCache', { TTLSeconds: 600, IndexGroup: 'Users' });
308
548
  * ```
309
549
  */
310
- SetItem<T>(key: string, value: T, category?: string, ttlSeconds?: number): Promise<void>;
550
+ SetItem<T>(key: string, value: T, category?: string, options?: number | LocalStorageWriteOptions): Promise<void>;
311
551
  /**
312
552
  * Removes a key from Redis and from its category tracking set.
313
553
  *
@@ -321,10 +561,11 @@ export declare class RedisLocalStorageProvider implements ILocalStorageProvider
321
561
  */
322
562
  Remove(key: string, category?: string): Promise<void>;
323
563
  /**
324
- * Clears all keys belonging to a specific category.
564
+ * Clears all keys belonging to a specific category, together with the category's index-group
565
+ * sets and the category set older versions of this provider maintained.
325
566
  *
326
- * Uses the category tracking Set to find all member keys, deletes them
327
- * in a single pipeline call, then removes the tracking Set itself.
567
+ * Keys are found with `SCAN`, so the operation also removes keys a peer wrote and keys whose
568
+ * index entry was lost.
328
569
  *
329
570
  * @param category - The category to clear. If empty, clears the `"default"` category.
330
571
  *
@@ -336,11 +577,27 @@ export declare class RedisLocalStorageProvider implements ILocalStorageProvider
336
577
  */
337
578
  ClearCategory(category: string): Promise<void>;
338
579
  /**
339
- * Returns all keys belonging to a specific category.
580
+ * {@link ClearCategory}, but reporting what happened instead of swallowing it. An administrator
581
+ * running `mj cache clear` needs to know a category did NOT go: the old path logged (with
582
+ * logging off, by default, in the CLI) and returned normally, so the command printed a key
583
+ * count and "servers will reload" for a clear that never happened.
584
+ *
585
+ * While Redis is unreachable the clear is recorded for the reconnect flush and reported as not
586
+ * done — the flush will clear it, but reporting success now would be exactly the lie this
587
+ * method exists to stop.
588
+ *
589
+ * @returns Ok, plus the error when it failed.
590
+ */
591
+ ClearCategoryChecked(category: string): Promise<{
592
+ Ok: boolean;
593
+ Error?: string;
594
+ }>;
595
+ /**
596
+ * Returns all live keys belonging to a specific category.
340
597
  *
341
- * Reads from the category tracking Set, so the result reflects keys
342
- * that were added via `SetItem` (some may have expired via TTL but
343
- * will still appear in the set until cleaned up).
598
+ * Walks the keyspace with `SCAN`, so the cost grows with the whole keyspace. Meant for
599
+ * administration and diagnostics; per-entity lookups on the save path use
600
+ * {@link GetIndexGroupKeys}.
344
601
  *
345
602
  * @param category - The category to list keys from
346
603
  * @returns Array of original key names (without the Redis prefix/category prefix)
@@ -352,6 +609,67 @@ export declare class RedisLocalStorageProvider implements ILocalStorageProvider
352
609
  * ```
353
610
  */
354
611
  GetCategoryKeys(category: string): Promise<string[]>;
612
+ /**
613
+ * Returns the keys written to `category` with `IndexGroup = group` that still exist.
614
+ *
615
+ * Members whose key has expired or been removed are dropped from the group set as a side
616
+ * effect, so the set shrinks back to the live keys whenever it is read. The read and the prune
617
+ * are one Lua script: a peer's `SADD` cannot land between them and be pruned unseen.
618
+ *
619
+ * @param category - The category the keys were written to
620
+ * @param group - The index group (for the RunView cache, the entity name)
621
+ * @returns The live keys, without the Redis prefix/category prefix
622
+ */
623
+ GetIndexGroupKeys(category: string, group: string): Promise<string[]>;
624
+ /**
625
+ * Runs `work` holding an exclusive lock on `key` across every process sharing this keyspace.
626
+ *
627
+ * The lock is `SET {prefix}:__lock__:{category}:{key} <token> NX PX 10000`, retried every 20 ms
628
+ * for up to 5 s, and released only by its holder (compare-and-delete). The 10 s expiry frees a
629
+ * lock whose holder died; `work` is expected to be a short read-modify-write.
630
+ *
631
+ * @throws when the lock is not acquired in time; `work` has not run
632
+ */
633
+ WithKeyLock<T>(key: string, category: string, work: () => Promise<T>): Promise<T>;
634
+ /** Extends this holder's lock. @internal */
635
+ private renewLock;
636
+ /**
637
+ * Whether this holder's token is still the one in the lock.
638
+ *
639
+ * @param confirmedAt when the lock was last known to be ours (acquisition, or the most recent
640
+ * renewal that actually landed)
641
+ *
642
+ * This used to answer `true` when the read failed, on the reasoning that an unreadable check
643
+ * should not fail a write. But the failures are correlated: this read and the renewals share
644
+ * one connection, so a read that throws means the renewals have been throwing too, and the
645
+ * lock is most likely expired — the one case where "still mine" is both unverifiable and
646
+ * probably false. The clock is the evidence that remains: a lock cannot outlive its TTL
647
+ * measured from the last time we know it was ours.
648
+ * @internal
649
+ */
650
+ private stillHoldsLock;
651
+ /**
652
+ * Claims `{prefix}:__lease__:{name}` for `ttlMs` with `SET NX PX`, so one process in the fleet
653
+ * runs a periodic job per period. The lease is not released; it expires.
654
+ */
655
+ TryAcquireLease(name: string, ttlMs: number): Promise<boolean>;
656
+ /**
657
+ * Extends a lease this provider holds, without being able to extend anyone else's: the script
658
+ * only acts when the stored token is this provider's. A lease that has already expired and been
659
+ * taken by another process is NOT stolen back — the caller learns it lost its turn.
660
+ *
661
+ * @returns true when this process still holds the lease afterwards.
662
+ */
663
+ RenewLease(name: string, ttlMs: number): Promise<boolean>;
664
+ /** Ends a lease this provider claimed, if it still holds it (compare-and-delete). */
665
+ ReleaseLease(name: string): Promise<void>;
666
+ private leaseKey;
667
+ /** @internal */
668
+ private acquireLock;
669
+ /** @internal */
670
+ private releaseLock;
671
+ /** Logs any per-command failure a pipeline reported; `exec()` itself does not throw for them. @internal */
672
+ private logPipelineErrors;
355
673
  /**
356
674
  * Whether the Redis client currently has an active connection.
357
675
  *
@@ -367,11 +685,15 @@ export declare class RedisLocalStorageProvider implements ILocalStorageProvider
367
685
  * category tracking. Prefer the `ILocalStorageProvider` methods for
368
686
  * standard operations.
369
687
  *
688
+ * For pub/sub, use {@link PublishMessage}, {@link PublishMessageAndWait} and
689
+ * {@link SubscribeToChannel} instead: they share the provider's subscriber connection and
690
+ * namespace channels with the key prefix.
691
+ *
370
692
  * @example
371
693
  * ```typescript
372
- * // Use for Redis-specific commands like pub/sub, streams, etc.
694
+ * // Use for Redis-specific commands the provider does not wrap, such as streams
373
695
  * const client = provider.Client;
374
- * await client.publish('cache-invalidation', 'entity:Users');
696
+ * await client.xadd('audit-events', '*', 'type', 'login');
375
697
  * ```
376
698
  */
377
699
  get Client(): Redis;
@@ -451,7 +773,8 @@ export declare class RedisLocalStorageProvider implements ILocalStorageProvider
451
773
  * a client in subscribe mode cannot execute other commands).
452
774
  *
453
775
  * Must be called explicitly after construction. No-op if `enablePubSub` is `false`
454
- * in the config, or if already listening.
776
+ * in the config. Concurrent and repeated calls share one start-up; if it fails, the
777
+ * subscriber is discarded and the next call starts a fresh one.
455
778
  *
456
779
  * @example
457
780
  * ```typescript
@@ -468,6 +791,18 @@ export declare class RedisLocalStorageProvider implements ILocalStorageProvider
468
791
  * ```
469
792
  */
470
793
  StartListening(): Promise<void>;
794
+ /**
795
+ * Creates the subscriber connection and subscribes it to the cache-invalidation channel.
796
+ *
797
+ * The message listener is attached before subscribing, so nothing that arrives is missed. On
798
+ * failure the connection is closed and cleared. A retry does not depend on that —
799
+ * {@link StartListening} resets its own in-flight promise and opens a fresh subscriber — but the
800
+ * failed client would otherwise stay open, reconnecting in the background with unlimited retries,
801
+ * and once it got back in it would resubscribe and deliver every invalidation a second time.
802
+ */
803
+ private openSubscriber;
804
+ /** Closes a subscriber that failed to start, and clears it if it is still the current one. */
805
+ private discardSubscriber;
471
806
  /**
472
807
  * Creates the subscriber Redis client, mirroring the main client's connection config.
473
808
  * @internal
@@ -495,27 +830,62 @@ export declare class RedisLocalStorageProvider implements ILocalStorageProvider
495
830
  * @internal
496
831
  */
497
832
  private publishChange;
833
+ /** The configured publish mode for a category. @internal */
834
+ private publishModeFor;
498
835
  /**
499
836
  * Publishes an arbitrary message on a named channel. Fire-and-forget: the promise is not
500
837
  * awaited and a failure is logged rather than raised, so a caller on a hot path is never
501
- * blocked or broken by the message bus.
838
+ * blocked or broken by the message bus. Does nothing when pub/sub is disabled.
839
+ *
840
+ * Use {@link PublishMessageAndWait} when the caller needs to know whether the message went out.
502
841
  *
503
842
  * The channel is namespaced with the provider's key prefix, so several applications can share
504
843
  * one Redis without hearing each other.
505
844
  *
506
845
  * @param channel Logical channel name (unprefixed).
507
846
  * @param payload Message body. Serialize before calling — this layer is shape-agnostic.
847
+ * @throws If `channel` is the name reserved for cache invalidation.
508
848
  */
509
849
  PublishMessage(channel: string, payload: string): void;
850
+ /**
851
+ * Publishes a message on a named channel and waits for Redis to accept it.
852
+ *
853
+ * Use this instead of {@link PublishMessage} when the caller must report honestly whether the
854
+ * message went out — for example, telling a user whether a cancellation reached the server
855
+ * running their request.
856
+ *
857
+ * While the connection is down the publish waits for it to come back rather than failing, so a
858
+ * caller that needs a deadline should race it against a timeout.
859
+ *
860
+ * @param channel Logical channel name (unprefixed), namespaced as in {@link PublishMessage}.
861
+ * @param payload Message body. Serialize before calling — this layer is shape-agnostic.
862
+ * @returns The number of subscribers that received the message, across every process sharing
863
+ * the Redis — including this one, if it subscribes to the same channel. Zero means the
864
+ * message was published but nobody was listening.
865
+ * @throws If pub/sub is disabled, if `channel` is reserved, or if Redis rejects the publish.
866
+ */
867
+ PublishMessageAndWait(channel: string, payload: string): Promise<number>;
510
868
  /**
511
869
  * Registers a handler for messages on a named channel, starting the subscriber if needed.
512
870
  *
871
+ * When pub/sub is disabled this registers nothing and returns an inert unsubscribe; check
872
+ * {@link IsPubSubEnabled} to tell that apart from a live subscription.
873
+ *
513
874
  * No echo suppression happens here — this layer does not know the payload shape. A publisher
514
875
  * that needs it must stamp its own origin on the message and check it in the handler.
515
876
  *
516
- * @returns A function that removes this handler.
877
+ * Redis does not replay messages, so anything published while the subscriber is disconnected
878
+ * is never delivered.
879
+ *
880
+ * @param channel Logical channel name (unprefixed), namespaced as in {@link PublishMessage}.
881
+ * @param handler Called with each message body. May be async.
882
+ * @returns A function that removes this handler. When the last handler on a channel is
883
+ * removed, the provider unsubscribes from it in Redis.
884
+ * @throws If `channel` is reserved, or if Redis rejects the subscribe.
517
885
  */
518
- SubscribeToChannel(channel: string, handler: (message: string) => void): Promise<() => void>;
886
+ SubscribeToChannel(channel: string, handler: ChannelMessageHandler): Promise<() => void>;
887
+ /** Whether the provider was created with `enablePubSub`. When false, the channel methods do nothing. */
888
+ get IsPubSubEnabled(): boolean;
519
889
  /**
520
890
  * The handler set for a channel, subscribing first when no caller has yet.
521
891
  *
@@ -533,9 +903,29 @@ export declare class RedisLocalStorageProvider implements ILocalStorageProvider
533
903
  * with nothing surfaced.
534
904
  */
535
905
  private subscribeChannel;
906
+ /**
907
+ * Removes one handler, and unsubscribes the channel in Redis when it was the last.
908
+ *
909
+ * Safe to call more than once. A handler set that is no longer the channel's current one
910
+ * belongs to a subscription already released, so it never triggers a second unsubscribe. A
911
+ * subscribe that arrives while the unsubscribe is in flight is queued behind it on the same
912
+ * connection, so the channel ends up subscribed.
913
+ */
914
+ private removeChannelHandler;
536
915
  /** Routes an inbound message to the handlers registered for its channel. @internal */
537
916
  private dispatchChannelMessage;
538
- /** Namespaces a channel with the provider's key prefix. @internal */
917
+ /**
918
+ * Runs one handler, containing a throw or a rejected promise so the other handlers still run.
919
+ *
920
+ * Failures are logged even when `enableLogging` is off: that setting quiets connection noise,
921
+ * and a failing handler is a defect in the consumer that would otherwise vanish.
922
+ */
923
+ private invokeChannelHandler;
924
+ /**
925
+ * Namespaces a channel with the provider's key prefix.
926
+ * @throws If the result is the channel reserved for cache invalidation, where a message would
927
+ * be read as a cache change by every server.
928
+ */
539
929
  private qualifyChannel;
540
930
  /**
541
931
  * Registers a callback for cache change events from other servers.
@@ -564,5 +954,94 @@ export declare class RedisLocalStorageProvider implements ILocalStorageProvider
564
954
  * Whether the pub/sub subscriber connection is currently active.
565
955
  */
566
956
  get IsSubscriberConnected(): boolean;
957
+ /**
958
+ * Registers a callback for the loss of the Redis connection.
959
+ *
960
+ * Fires on a transition only — not on the first connect, and not again while a reconnect is
961
+ * being retried. {@link IsConnected} reports the current state but not that it changed, so a
962
+ * consumer wanting to degrade or report health needs this rather than a poll.
963
+ *
964
+ * Use this in preference to reading the log: status-level logging is suppressed when
965
+ * `GetProductionStatus()` is true, so a deployed process says nothing when its cache client
966
+ * dies.
967
+ *
968
+ * @param callback - Invoked with a short human-readable reason for the loss
969
+ * @returns A function that removes this registration
970
+ *
971
+ * @example
972
+ * ```typescript
973
+ * const stop = provider.OnConnectionLost(reason => health.markCacheDown(reason));
974
+ * provider.OnConnectionRestored(() => health.markCacheUp());
975
+ * ```
976
+ */
977
+ OnConnectionLost(callback: (reason: string) => void): () => void;
978
+ /**
979
+ * Registers a callback for the Redis connection being restored after a loss. Not fired for the
980
+ * first connection.
981
+ *
982
+ * Cache correctness after the gap is handled by the provider itself; see
983
+ * {@link OnReconciliationRequired} for the signal that local state had to be dropped.
984
+ *
985
+ * @param callback - Invoked when the connection comes back
986
+ * @returns A function that removes this registration
987
+ */
988
+ OnConnectionRestored(callback: () => void): () => void;
989
+ /**
990
+ * Registers a callback for the provider having concluded, after a connection gap, that local
991
+ * cache state must be dropped.
992
+ *
993
+ * The standard categories are flushed by the provider itself via {@link OnCacheChanged}. Use
994
+ * this for state those categories do not describe — an in-process engine, a derived index, a
995
+ * memoized permission set — which would otherwise survive a reconnect while stale.
996
+ *
997
+ * Does not fire when nothing was invalidated anywhere during the gap.
998
+ *
999
+ * @param callback - Invoked when a flush is required
1000
+ * @returns A function that removes this registration
1001
+ */
1002
+ OnReconciliationRequired(callback: () => void): () => void;
1003
+ /**
1004
+ * The highest fleet-wide epoch this process has observed. Exposed for diagnostics and for tests
1005
+ * that need to assert what reconciliation decided; consumers should not need it.
1006
+ */
1007
+ get LastSeenEpoch(): number;
1008
+ /**
1009
+ * Reports a lost connection once per outage.
1010
+ *
1011
+ * Both routes into this are repeatable: `close` fires on every failed reconnection attempt, and an
1012
+ * exhausted retry ceiling arrives separately after one. Consumers get a single notification, and
1013
+ * the next `ready` clears the latch so the following outage reports again.
1014
+ *
1015
+ * @internal
1016
+ */
1017
+ private noteConnectionLost;
1018
+ /**
1019
+ * Raises the public lost-connection event and logs it.
1020
+ *
1021
+ * Uses the error channel, and is not gated behind `enableLogging`: status-level output is
1022
+ * suppressed in production and that flag is routinely turned off, either of which would leave a
1023
+ * dead cache client silent.
1024
+ *
1025
+ * @internal
1026
+ */
1027
+ private emitConnectionLost;
1028
+ /**
1029
+ * Raises the public restored-connection event and logs it, on the error channel for the same
1030
+ * reason as the loss — otherwise the logs show an outage that never ends.
1031
+ *
1032
+ * @internal
1033
+ */
1034
+ private emitConnectionRestored;
1035
+ /**
1036
+ * Emits to consumer callbacks, containing each listener's errors so that neither the connection
1037
+ * handling that triggered the event nor the other listeners are affected.
1038
+ *
1039
+ * Invokes listeners individually rather than through `EventEmitter.emit`, which calls them
1040
+ * synchronously in turn: one throwing there would stop every listener after it from running at
1041
+ * all.
1042
+ *
1043
+ * @internal
1044
+ */
1045
+ private safeEmit;
567
1046
  }
568
1047
  //# sourceMappingURL=RedisLocalStorageProvider.d.ts.map