tricache 1.0.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +89 -93
  2. package/dashboards/tricache-alerts.yaml +80 -4
  3. package/dashboards/tricache-grafana.json +54 -1
  4. package/dashboards/tricache-inventory.rules.yml +21 -0
  5. package/dist/cache-service-BV5T8-20.d.cts +1064 -0
  6. package/dist/cache-service-UZXOQGEY.js +14 -0
  7. package/dist/{cache-service-CREOp7MM.d.ts → cache-service-tpyrXvlH.d.ts} +157 -24
  8. package/dist/{chunk-UBWLPKTI.js → chunk-EJXG7WO6.js} +152 -32
  9. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  10. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  11. package/dist/{chunk-2AJKEQMZ.js → chunk-KV7KISK2.js} +54 -5
  12. package/dist/{chunk-JYQFQJNJ.js → chunk-MB3DMVWN.js} +3424 -1022
  13. package/dist/chunk-RBJRTGFK.js +94 -0
  14. package/dist/chunk-S5N65I45.js +17 -0
  15. package/dist/cli.cjs +3694 -1070
  16. package/dist/cli.d.cts +12 -0
  17. package/dist/cli.js +210 -14
  18. package/dist/dashboard/index.cjs +111 -29
  19. package/dist/dashboard/index.d.cts +185 -0
  20. package/dist/dashboard/index.d.ts +5 -3
  21. package/dist/dashboard/index.js +1 -1
  22. package/dist/drizzle/index.cjs +3578 -1068
  23. package/dist/drizzle/index.d.cts +46 -0
  24. package/dist/drizzle/index.d.ts +2 -2
  25. package/dist/drizzle/index.js +6 -2
  26. package/dist/edge/index.cjs +368 -162
  27. package/dist/edge/index.d.cts +134 -0
  28. package/dist/edge/index.d.ts +11 -4
  29. package/dist/edge/index.js +314 -155
  30. package/dist/hono/index.cjs +3614 -1087
  31. package/dist/hono/index.d.cts +93 -0
  32. package/dist/hono/index.d.ts +7 -5
  33. package/dist/hono/index.js +16 -9
  34. package/dist/hono-CMv2VdQ6.d.cts +404 -0
  35. package/dist/{hono-DSV2ve66.d.ts → hono-Dvq04kX9.d.ts} +33 -7
  36. package/dist/http/index.cjs +3712 -1124
  37. package/dist/http/index.d.cts +103 -0
  38. package/dist/http/index.d.ts +13 -5
  39. package/dist/http/index.js +92 -43
  40. package/dist/index.cjs +4067 -1252
  41. package/dist/index.d.cts +1071 -0
  42. package/dist/index.d.ts +123 -27
  43. package/dist/index.js +878 -21
  44. package/dist/{murmur3-CMGw9PbV.d.ts → murmur3-DF8BFRnu.d.cts} +1 -0
  45. package/dist/murmur3-DF8BFRnu.d.ts +99 -0
  46. package/dist/nestjs/index.cjs +3635 -1112
  47. package/dist/nestjs/index.d.cts +299 -0
  48. package/dist/nestjs/index.d.ts +120 -33
  49. package/dist/nestjs/index.js +132 -43
  50. package/dist/next/index.cjs +3704 -1175
  51. package/dist/next/index.d.cts +238 -0
  52. package/dist/next/index.d.ts +39 -11
  53. package/dist/next/index.js +202 -102
  54. package/dist/prisma/index.cjs +29 -18
  55. package/dist/prisma/index.d.cts +62 -0
  56. package/dist/prisma/index.d.ts +2 -2
  57. package/dist/prisma/index.js +17 -18
  58. package/dist/serialize-worker.cjs +162 -39
  59. package/dist/serialize-worker.d.cts +2 -0
  60. package/dist/serialize-worker.js +9 -7
  61. package/dist/{types-Dyip5wAl.d.ts → types-F8vRWMrE.d.cts} +186 -54
  62. package/dist/types-F8vRWMrE.d.ts +1636 -0
  63. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  64. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  65. package/package.json +116 -37
  66. package/src/adapters/auto-pipeliner.ts +150 -26
  67. package/src/adapters/node-redis.ts +106 -27
  68. package/src/cache-service.ts +2215 -793
  69. package/src/cli.ts +25 -14
  70. package/src/codec.ts +3 -3
  71. package/src/compression.ts +39 -16
  72. package/src/cross-region.ts +22 -4
  73. package/src/dashboard/handler.ts +26 -6
  74. package/src/dashboard/html.ts +35 -10
  75. package/src/dashboard/index.ts +35 -13
  76. package/src/dashboard/types.ts +3 -1
  77. package/src/disk-tier.ts +448 -102
  78. package/src/drizzle/index.ts +2 -1
  79. package/src/edge/adapters/cloudflare-do.ts +25 -10
  80. package/src/edge/adapters/cloudflare-kv.ts +12 -9
  81. package/src/edge/adapters/upstash.ts +27 -11
  82. package/src/edge/cache.ts +200 -110
  83. package/src/edge/hono.ts +23 -6
  84. package/src/edge/types.ts +17 -5
  85. package/src/encryption.ts +50 -18
  86. package/src/env.d.ts +1 -1
  87. package/src/errors.ts +12 -0
  88. package/src/hono/index.ts +19 -9
  89. package/src/http/express.ts +62 -17
  90. package/src/http/fastify.ts +35 -21
  91. package/src/http/utils.ts +60 -20
  92. package/src/index.ts +6 -0
  93. package/src/ipc-telemetry.ts +35 -9
  94. package/src/latency-watchdog.ts +5 -1
  95. package/src/nestjs/decorators.ts +11 -6
  96. package/src/nestjs/index.ts +2 -0
  97. package/src/nestjs/keyv-adapter.ts +68 -0
  98. package/src/nestjs/tricache.module.ts +15 -12
  99. package/src/nestjs/tricache.store.ts +69 -26
  100. package/src/nestjs/types.ts +30 -16
  101. package/src/next/cache-handler.ts +151 -53
  102. package/src/next/index.ts +1 -0
  103. package/src/next/types.ts +25 -0
  104. package/src/origin-capacity.ts +134 -0
  105. package/src/prisma/index.ts +17 -24
  106. package/src/remote-snapshot.ts +37 -27
  107. package/src/serialize-worker.ts +8 -5
  108. package/src/sigv4-snapshot-adapter.ts +37 -27
  109. package/src/smart-memory-cache.ts +121 -44
  110. package/src/types.ts +117 -37
  111. package/src/utils/cgroup.ts +12 -0
  112. package/src/utils/config-comparison.ts +29 -0
  113. package/src/utils/deadline.ts +14 -0
  114. package/src/utils/diagnostics.ts +27 -0
  115. package/src/utils/lz4-size.ts +74 -0
  116. package/src/utils/namespace-key.ts +48 -0
  117. package/src/utils/query-key.ts +13 -0
  118. package/src/utils/redis-slot.ts +13 -0
  119. package/src/utils/snapshot-transfer.ts +83 -0
  120. package/src/utils/work-limits.ts +73 -0
  121. package/src/utils/write-revision.ts +4 -0
  122. package/src/wasm/bloom-filter-wasm.ts +25 -5
  123. package/src/worker-pool.ts +44 -15
  124. package/src/wtiny-lfu.ts +82 -20
  125. package/dist/cache-service-MG7PN6MX.js +0 -12
  126. package/dist/chunk-3I5L7K6I.js +0 -704
  127. package/dist/chunk-BQRURGGD.js +0 -60
@@ -0,0 +1,1064 @@
1
+ import { C as CacheOptions, b as CacheMetrics, c as CacheHealthStatus, d as CachePresetType, e as CrossRegionInvalidationEvent, f as CachePriority, W as WrapOptions, a as InvalidateTagOptions, g as CachePingResult, D as DiskBackpressureStats, L as LockOptions, E as EncryptionMode, h as WTinyLfuStats } from './types-F8vRWMrE.cjs';
2
+
3
+ /**
4
+ * TierLatencyWatchdog — Graduated, self-healing tier latency watchdog.
5
+ *
6
+ * Prevents EBS/cloud NVMe latency degradation from impacting application p95 response times.
7
+ * Incorporates control-theory safeguards:
8
+ * - Amortized zero-allocation p95 calculation (fires every 32 samples on pre-allocated typed arrays).
9
+ * - Graduated probabilistic shedding (Stage 0: 0% -> Stage 1: 25% -> Stage 2: 75% -> Stage 3: 100%).
10
+ * - Asymmetric hysteresis on Redis circuit (cuts diversion at 15ms, requires recovery below 10ms).
11
+ * - Anti-synchronicity cooldown jitter (±30%) to eliminate fleet-wide failover shockwaves.
12
+ * - Single-canary half-open recovery probing.
13
+ */
14
+ interface LatencyWatchdogOptions {
15
+ enabled?: boolean;
16
+ minDiskBypassMs?: number;
17
+ bypassRatio?: number;
18
+ cooldownMs?: number;
19
+ redisCutoffMs?: number;
20
+ redisRecoveryFloorMs?: number;
21
+ minSamples?: number;
22
+ disableRedis?: boolean;
23
+ }
24
+ interface LatencyWatchdogTelemetry {
25
+ bypassActive: boolean;
26
+ bypassStage: 0 | 1 | 2 | 3;
27
+ diskP95Ms: number;
28
+ redisP95Ms: number;
29
+ redisDampened: boolean;
30
+ bypassedTotal: number;
31
+ }
32
+ declare class TierLatencyWatchdog {
33
+ private readonly enabled;
34
+ private readonly minDiskBypassMs;
35
+ private readonly bypassRatio;
36
+ private readonly cooldownMs;
37
+ private readonly redisCutoffMs;
38
+ private readonly redisRecoveryFloorMs;
39
+ private readonly minSamples;
40
+ private disableRedis;
41
+ private readonly diskRing;
42
+ private readonly redisRing;
43
+ private readonly scratch;
44
+ private diskIdx;
45
+ private redisIdx;
46
+ private diskCount;
47
+ private redisCount;
48
+ private cachedDiskP95;
49
+ private cachedRedisP95;
50
+ private stage;
51
+ private redisDampened;
52
+ private redisRecoveryConsecutiveSamples;
53
+ private bypassedUntilMonotonic;
54
+ private canaryInFlight;
55
+ private bypassedTotal;
56
+ constructor(options?: LatencyWatchdogOptions);
57
+ setDisableRedis(disabled: boolean): void;
58
+ /**
59
+ * Record disk read duration in milliseconds (zero-allocation hot path).
60
+ */
61
+ recordDisk(ms: number): void;
62
+ /**
63
+ * Record Redis read duration in milliseconds (zero-allocation hot path).
64
+ */
65
+ recordRedis(ms: number): void;
66
+ private recalculateP95;
67
+ private computeP95;
68
+ /**
69
+ * Core Control Loop:
70
+ * - Evaluates asymmetric hysteresis on Redis circuit.
71
+ * - Assigns graduated stage (0, 1, 2, 3) with anti-synchronicity jitter.
72
+ */
73
+ private evaluateControlLoop;
74
+ private calculateJitteredCooldown;
75
+ /**
76
+ * Determine whether a read is permitted to check the disk tier.
77
+ *
78
+ * In Stage 1 and 2, sheds traffic probabilistically.
79
+ * In Stage 3, blocks all reads except for a single canary probe once cooldown expires.
80
+ *
81
+ * @param randomOverride Optional seeded random number [0, 1) for deterministic unit testing.
82
+ */
83
+ isDiskAllowed(randomOverride?: number): boolean;
84
+ /**
85
+ * Callback invoked when the single canary read probe completes.
86
+ */
87
+ onCanaryResult(success: boolean, elapsedMs: number): void;
88
+ getTelemetry(): LatencyWatchdogTelemetry;
89
+ }
90
+
91
+ /**
92
+ * Platform-agnostic IPC socket / named pipe path resolver.
93
+ * - POSIX: `/tmp/tricache-<id>.sock` (or `$TMPDIR/tricache-<id>.sock`)
94
+ * - Windows: `\\.\pipe\tricache-<id>`
95
+ */
96
+ declare function resolveIpcSocketPath(id?: string | number): string;
97
+ /**
98
+ * Cache provider interface required by the IPC telemetry server.
99
+ */
100
+ interface IIpcCacheProvider {
101
+ options?: CacheOptions;
102
+ metrics(): CacheMetrics;
103
+ stats?(): {
104
+ l1: Record<string, unknown>;
105
+ disk: Record<string, unknown>;
106
+ };
107
+ hotKeys?(n?: number): Array<{
108
+ key: string;
109
+ hits: number;
110
+ sizeBytes: number;
111
+ }>;
112
+ health?(): CacheHealthStatus;
113
+ }
114
+ /**
115
+ * Serialized telemetry payload transferred across the IPC bridge.
116
+ */
117
+ interface IpcMetricsPayload {
118
+ pid: number;
119
+ uptimeMs: number;
120
+ timestamp: number;
121
+ namespace?: string;
122
+ l1MaxBytes?: number;
123
+ metrics: CacheMetrics;
124
+ stats?: {
125
+ l1: Record<string, unknown>;
126
+ disk: Record<string, unknown>;
127
+ };
128
+ hotKeys?: Array<{
129
+ key: string;
130
+ hits: number;
131
+ sizeBytes: number;
132
+ }>;
133
+ health?: CacheHealthStatus;
134
+ }
135
+ /**
136
+ * Lightweight, non-blocking IPC Telemetry Server.
137
+ * Exposes real-time cache metrics over Unix domain sockets (POSIX) or Named Pipes (Windows).
138
+ */
139
+ declare class IpcTelemetryServer {
140
+ private readonly cache;
141
+ private server;
142
+ readonly socketPath: string;
143
+ private _closed;
144
+ private _starting;
145
+ private readonly sockets;
146
+ private _exitHandler;
147
+ private _sigintHandler;
148
+ private _sigtermHandler;
149
+ constructor(cache: IIpcCacheProvider, customSocketPath?: string);
150
+ /**
151
+ * Start listening on the IPC socket / pipe.
152
+ */
153
+ start(): Promise<void>;
154
+ private startInternal;
155
+ /**
156
+ * Build a complete telemetry snapshot from the underlying cache provider.
157
+ */
158
+ getSnapshot(): IpcMetricsPayload;
159
+ private _unlinkSocket;
160
+ /**
161
+ * Gracefully close the IPC telemetry server and clean up handlers and sockets.
162
+ */
163
+ close(): Promise<void>;
164
+ get isListening(): boolean;
165
+ }
166
+ /**
167
+ * IPC Telemetry Client for connecting to and querying a running TriCache instance.
168
+ */
169
+ declare class IpcTelemetryClient {
170
+ readonly socketPath: string;
171
+ constructor(socketPath?: string);
172
+ /**
173
+ * Fetch a live metrics snapshot from the IPC server.
174
+ */
175
+ getMetrics(timeoutMs?: number): Promise<IpcMetricsPayload>;
176
+ /**
177
+ * Send a ping over the IPC bridge and measure round-trip latency.
178
+ */
179
+ ping(timeoutMs?: number): Promise<number>;
180
+ }
181
+ /**
182
+ * Probe local system for active TriCache IPC sockets.
183
+ */
184
+ declare function findActiveSockets(): Promise<string[]>;
185
+ declare function renderProgressBar(ratio: number, width?: number): string;
186
+ declare function formatBytes(bytes: number): string;
187
+ declare function formatNumber(n: number): string;
188
+ declare function formatDuration(ms: number): string;
189
+ /**
190
+ * Render an ANSI/ASCII dashboard representation of the cache metrics.
191
+ */
192
+ declare function renderTopDashboard(payload: IpcMetricsPayload): string;
193
+
194
+ /**
195
+ * Centralized static process termination bus.
196
+ * Prevents MaxListenersExceededWarning by attaching at most ONE SIGTERM and ONE SIGINT
197
+ * listener to process, broadcasting to all active CacheService instances.
198
+ * Automatically detaches listeners when the instance count reaches 0, preventing
199
+ * event loop / test runner hangs.
200
+ */
201
+ declare class ProcessTerminationBus {
202
+ private static readonly instances;
203
+ private static registered;
204
+ private static sigtermHandler;
205
+ private static sigintHandler;
206
+ static register(instance: CacheService): void;
207
+ static unregister(instance: CacheService): void;
208
+ /**
209
+ * Flushes snapshots across all active registered cache instances concurrently.
210
+ * Awaits both local disk and remote cloud snapshot uploads with timeout protection.
211
+ *
212
+ * @param timeoutMs Timeout in milliseconds per instance before aborting slow flushes. Default: 8000ms.
213
+ */
214
+ static flushAll(timeoutMs?: number): Promise<void>;
215
+ /** For testing diagnostics and assertions */
216
+ static get size(): number;
217
+ static get isRegistered(): boolean;
218
+ }
219
+ declare function deepMergeOptions(base: CacheOptions, overrides?: Partial<CacheOptions>): CacheOptions;
220
+ declare class CacheService {
221
+ private readonly _originWork;
222
+ private readonly _backgroundWork;
223
+ private readonly _originCapacityLimiter;
224
+ private readonly _dependencyBudget;
225
+ private readonly _dependencyReleases;
226
+ private readonly _dependencyExpirations;
227
+ private readonly _lifecycle;
228
+ private readonly _singletonConfig;
229
+ private readonly logger;
230
+ private readonly enc;
231
+ private readonly codec;
232
+ private readonly l1;
233
+ private readonly disk;
234
+ /** When true, all disk-tier and snapshot operations are skipped. */
235
+ private _diskDisabled;
236
+ /** Worker pool for off-main-thread AES-GCM (null when workerThreads is false or unavailable). */
237
+ private _workerPool;
238
+ private readonly opts;
239
+ /** Pre-computed once — opts.namespace never changes after construction. */
240
+ private readonly _namespace;
241
+ private readonly _namespacePrefix;
242
+ private readonly _dataPrefix;
243
+ private readonly _tagSetPrefix;
244
+ private readonly _tagVersionPrefix;
245
+ private readonly _lockPrefix;
246
+ private readonly prefixLen;
247
+ /** Pre-computed once — disableRedis and redisHost never change after construction. */
248
+ private readonly _redisDisabled;
249
+ private readonly watchdog;
250
+ private pipeliner;
251
+ private readonly inflight;
252
+ private readonly revalidating;
253
+ private readonly _l1Counters;
254
+ /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
255
+ private readonly tagIndex;
256
+ /** Reverse index of namespaced key → { tags, expiresAt } for bounded cleanup on eviction/delete */
257
+ private readonly keyTags;
258
+ /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
259
+ private readonly tagVersions;
260
+ /** Share active generation reads only; retain at most the tag-cache ceiling. */
261
+ private readonly _tagVersionRefreshes;
262
+ private _tagRefreshEpoch;
263
+ /**
264
+ * Dependency index: source glob pattern → Set of namespaced dependent keys.
265
+ * When an exact-key delete matches a registered pattern, all dependents are cascaded.
266
+ */
267
+ private readonly dependencyIndex;
268
+ /** Reverse index of namespaced dependent key → source glob patterns */
269
+ private readonly keyDependencies;
270
+ /** Active writers retain their dependency edges even before admission or after eviction. */
271
+ private readonly _pendingDependencies;
272
+ private readonly _cgroupMemoryLimit;
273
+ private redis;
274
+ private redisConnecting;
275
+ private readonly cb;
276
+ /** In-process mutex lock map for single-process environments or Redis outages. */
277
+ private _localLocks;
278
+ /** Active OpenTelemetry monotonic counters. */
279
+ private _otelMetrics;
280
+ private snapshotLoaded;
281
+ private _readyPromise;
282
+ private cleanupInterval;
283
+ private diskJanitorInterval;
284
+ private oomInterval;
285
+ private metricsInterval;
286
+ private remoteSnapshotInterval;
287
+ private _shutdownHandler;
288
+ private latencyTracker;
289
+ private readonly instanceId;
290
+ private readonly backplaneChannel;
291
+ private readonly backplaneStreamKey;
292
+ private subClient;
293
+ private streamClient;
294
+ private _lastStreamId;
295
+ private _restoredSnapshot;
296
+ private _backplaneAvailable;
297
+ private _backplaneUnavailableReason;
298
+ private _backplaneUnavailableSince;
299
+ private _backplaneStateSince;
300
+ private _lastBackplaneHeartbeatAt;
301
+ private _backplaneHeartbeatInterval;
302
+ private _backplaneHeartbeat;
303
+ private _heartbeatPublishInFlight;
304
+ private _backplaneSubscriptionReady;
305
+ private _backplaneTransportEpoch;
306
+ private _retryBackplaneSubscription;
307
+ private _preparedBackplaneClient;
308
+ private _invalidationReadEpoch;
309
+ private _otelCleanup;
310
+ private _streamRecovering;
311
+ private readonly _backplaneDisposers;
312
+ private _destroyed;
313
+ private readonly _pendingDiskDeletes;
314
+ /** Active invalidations fence cold Redis reads until their asynchronous deletion settles. */
315
+ private readonly _pendingRedisInvalidations;
316
+ private _globalEpoch;
317
+ private _pendingSpillCount;
318
+ private readonly _pendingSpills;
319
+ /** Strict reads trust only revisions spilled in this consumer epoch; bounded independently of disk size. */
320
+ private readonly _protectedSpillRevisions;
321
+ private _suppressSpills;
322
+ private _diskCleanupScheduled;
323
+ private readonly _keyMutationEpochs;
324
+ /**
325
+ * Pattern tombstones for disk tier.
326
+ * Files in the disk tier are keyed by SHA-256 of namespacedKey.
327
+ * Wildcard pattern deletes cannot scan the filesystem synchronously, so we maintain
328
+ * pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
329
+ */
330
+ private readonly _patternTombstones;
331
+ private _diskInvalidatedBefore;
332
+ private _addPatternTombstone;
333
+ private _isTombstonedByPattern;
334
+ private _assertActive;
335
+ private _beginRedisInvalidation;
336
+ private _isRedisReadInvalidated;
337
+ private _bumpKeyMutation;
338
+ private _getKeyMutationEpoch;
339
+ /** Capture a commit fence before asynchronous computation outside the cache. */
340
+ captureMutationFence(cacheKey: string): () => boolean;
341
+ /** Force tag re-sync without forgetting locally observed monotonic generations. */
342
+ refreshTagVersions(): void;
343
+ private _fenceInvalidation;
344
+ private _invalidateDiskKey;
345
+ private _scheduleDiskCleanup;
346
+ private _reserveDependencies;
347
+ private _registerDependencies;
348
+ private _trackPendingDependencies;
349
+ private _rememberTags;
350
+ private _restoreEntryMetadata;
351
+ private _removeKeyTags;
352
+ private _removeKeyDependencies;
353
+ private _clearDependencyMetadata;
354
+ private _notifyReadObserver;
355
+ private _runOrigin;
356
+ private _handleL1Eviction;
357
+ private _removePatternFromIndices;
358
+ private _sweepExpiredMetadata;
359
+ private _runOomCheck;
360
+ private _ipcServer?;
361
+ /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
362
+ private _subDisconnectedAt;
363
+ /** Deduplication ring buffer for incoming and outgoing cross-region invalidations (loop prevention) */
364
+ private readonly _seenCrossRegionEvents;
365
+ private counters;
366
+ /** One-time guard so the in-process increment() fallback warning fires only once. */
367
+ private _incrementFallbackWarned;
368
+ constructor(options?: CacheOptions);
369
+ /**
370
+ * Pre-configured production presets tailored for specific deployment environments.
371
+ *
372
+ * - `'nextjs'`: W-TinyLFU, zero-copy cloneStrategy: 'none' (React 19 RSC stream optimized),
373
+ * generational tags, and Redis stream backplane.
374
+ * - `'microservice'`: High-throughput Node.js microservice with W-TinyLFU, Streams backplane,
375
+ * TTL jitter, and L2 circuit breaking.
376
+ * - `'serverless'`: Stateless Lambda / Cloud Run isolate with memory-only L1, fast timeouts,
377
+ * and Pub/Sub backplane.
378
+ * - `'enterprise-hardened'`: Zero-trust production setup with generational tagging, Streams backplane,
379
+ * fail-closed rate-limits, strict singleton assertions, and 80% OOM guard.
380
+ *
381
+ * @param type The preset identifier ('nextjs' | 'microservice' | 'serverless' | 'enterprise-hardened')
382
+ * @param overrides Optional configuration overrides merged deeply over preset defaults
383
+ * @returns Singleton CacheService instance configured according to the preset
384
+ */
385
+ static preset(type: CachePresetType, overrides?: Partial<CacheOptions>): CacheService;
386
+ /**
387
+ * Get (or create) the process-level singleton CacheService instance.
388
+ *
389
+ * Options are only applied on first call — subsequent calls return the
390
+ * existing instance regardless of options passed. When the new options differ
391
+ * from what the existing singleton was built with, this is a silent no-op by
392
+ * default; set `strictSingleton: true` to throw instead, or watch the
393
+ * `singletonDivergences` metric for detection.
394
+ *
395
+ * When `namespace` is set the singleton is keyed by namespace, so two calls
396
+ * with different namespaces return independent instances.
397
+ */
398
+ static create(options?: CacheOptions): CacheService;
399
+ /**
400
+ * Keys that, if set differently on a later `create()` call, represent a
401
+ * meaningful configuration divergence worth flagging (security/correctness
402
+ * relevant — not cosmetic, e.g. log level).
403
+ */
404
+ /** Returns the names of options that differ between `a` and the live `b`. */
405
+ private static optionsDiff;
406
+ /** Increment the singleton-divergence counter (surfaced in `metrics()`). */
407
+ bumpSingletonDivergence(): void;
408
+ /** Sanitized diagnostic view; retain the original options/adapters to reuse configuration. */
409
+ get options(): CacheOptions;
410
+ /**
411
+ * Async factory — accepts a Promise that resolves to CacheOptions.
412
+ * Useful when config is fetched from a secret store at startup.
413
+ *
414
+ * @example
415
+ * const cache = await CacheService.createAsync(fetchSecrets());
416
+ */
417
+ static createAsync(options: Promise<CacheOptions> | CacheOptions): Promise<CacheService>;
418
+ /** Replace the singleton (useful in tests). */
419
+ static reset(options?: CacheOptions): CacheService;
420
+ /** Derive the globalThis key for a given set of options. */
421
+ private static globalKey;
422
+ /**
423
+ * Encode the namespace, data domain, and raw key as an unambiguous v3 key.
424
+ *
425
+ * Callers always receive and provide logical keys in the public API.
426
+ */
427
+ private nk;
428
+ private tagIndexKey;
429
+ private tagIndexPrefix;
430
+ private tagVersionKey;
431
+ private tagVersionPrefix;
432
+ private lockKey;
433
+ private undk;
434
+ /**
435
+ * Validate a snapshot write timestamp before age/skew arithmetic.
436
+ *
437
+ * NaN and non-numeric values previously made every comparison false, so a
438
+ * malformed timestamp skipped both the future-skew and maximum-age gates.
439
+ * Missing or invalid values are rejected outright rather than treated as 0.
440
+ */
441
+ private _snapshotWrittenAt;
442
+ /** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
443
+ private _jitterTtl;
444
+ /** Shared no-op span for the common case where no tracer is configured.
445
+ * Using a singleton avoids allocating a fresh object literal on every get/set/delete call. */
446
+ private static readonly _nullSpan;
447
+ /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
448
+ private _startSpan;
449
+ private createDedicatedRedisClient;
450
+ private _listenBackplane;
451
+ private _strictInvalidationReadProtectionEnabled;
452
+ private _setBackplaneUnavailable;
453
+ private _flushLocalCacheAfterInvalidationRecovery;
454
+ private _setBackplaneAvailable;
455
+ private _rejectCachedRead;
456
+ private _ensureCachedReadAllowed;
457
+ /** Shared admission/commit/response fence. Health checks must also evaluate elapsed deadlines. */
458
+ private _cachedReadAllowed;
459
+ private _checkBackplaneDeadline;
460
+ private _startBackplaneHeartbeat;
461
+ private _publishBackplaneHeartbeat;
462
+ private _acceptBackplaneHeartbeat;
463
+ private _protectedConsumerDisconnected;
464
+ private _initProtectedPubSub;
465
+ private initBackplane;
466
+ private _resetAfterStreamGap;
467
+ private _startStreamConsumer;
468
+ /**
469
+ * Validate + apply one XREAD stream entry. `fields` is the flat ioredis
470
+ * shape [name, value, name, value, …]. Mirrors the schema rules of the
471
+ * pubsub path (`_handleBackplaneMessage`): op must be a known operation,
472
+ * key/src must be non-empty strings, tagVersion must parse to a finite
473
+ * number. Invalid entries are logged and dropped — never applied.
474
+ */
475
+ /** @internal Exposed for testing. */
476
+ _processStreamEntry(fields: string[], deferHeartbeat?: (src: unknown, nonce: unknown) => void): void;
477
+ private _applyInvalidationEvent;
478
+ /**
479
+ * Parse an optional tag version from either transport.
480
+ *
481
+ * Pub/Sub previously forwarded any numeric value (including `1.5`) while
482
+ * Streams rejected non-integers, so the two transports disagreed on the same
483
+ * logical payload. Both now share this validation: absent means "no version",
484
+ * and anything present must be a non-negative safe integer.
485
+ */
486
+ private _parseTagVersion;
487
+ /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
488
+ _handleBackplaneMessage(message: string): void;
489
+ private publishInvalidation;
490
+ private _markCrossRegionEventSeen;
491
+ private _isCrossRegionEventSeen;
492
+ private _broadcastCrossRegion;
493
+ /**
494
+ * Receives an invalidation event from another region (e.g. via HTTP webhook or broker subscriber).
495
+ * Validates origin, deduplicates to prevent loops, applies locally to L1/disk,
496
+ * and fans out to the local Redis backplane so all regional peers invalidate as well.
497
+ *
498
+ * Returns true if the event was accepted and applied, or false if ignored/deduplicated.
499
+ */
500
+ receiveCrossRegionInvalidation(event: CrossRegionInvalidationEvent): Promise<boolean>;
501
+ private _setLocalTagVersion;
502
+ private _isGenerationalEntryStale;
503
+ private _deleteRedisKeys;
504
+ private _parseRedisHash;
505
+ private _readRedisEntry;
506
+ private _getTagVersion;
507
+ private _refreshTagVersion;
508
+ private _readRedisBatch;
509
+ private _promoteRedisEntry;
510
+ private _readDiskEntry;
511
+ /** Common write policy and metadata across get/set/revalidation/draining. */
512
+ private _writeRedisEntry;
513
+ private _deleteIfStale;
514
+ /**
515
+ * Serialize payload for L2 Redis storage applying compression and encryption as configured.
516
+ * Offloads to worker thread if pool is active and payload exceeds threshold.
517
+ */
518
+ private _redisContext;
519
+ private _serializeAndEncrypt;
520
+ /**
521
+ * Deserialize raw L2 Redis entry applying decryption and decompression as needed.
522
+ * Offloads to worker thread if pool is active and payload exceeds threshold.
523
+ */
524
+ private _decryptAndDeserialize;
525
+ /**
526
+ * Scan all keys matching `pattern` across single-node or Cluster clients.
527
+ * For Cluster, iterates every master node independently (SCAN is node-local).
528
+ */
529
+ private _scanKeys;
530
+ private _checkAndLogResp3Hint;
531
+ private getRedis;
532
+ /**
533
+ * Writes the cold-start snapshot to disk.
534
+ * NOTE: fs.writeFileSync is INTENTIONAL here: this method is invoked during SIGTERM/SIGINT
535
+ * process termination hooks where asynchronous I/O would risk the Node.js event loop dying or
536
+ * process.exit() being called before the snapshot is physically written to disk.
537
+ *
538
+ * @returns `true` when a snapshot was written (or when there was nothing to write),
539
+ * `false` when the write failed. Callers that report shutdown success must
540
+ * check this value.
541
+ */
542
+ writeSnapshot(altPath?: string): boolean;
543
+ /**
544
+ * Loads cold-start snapshot from disk into L1 memory.
545
+ * NOTE: fs.readFileSync is INTENTIONAL here: this method is invoked synchronously inside the
546
+ * CacheService constructor so that the cache is atomically populated before any subsequent
547
+ * cache.get() or cache.set() operations run, eliminating cold-start race conditions.
548
+ */
549
+ loadSnapshot(): void;
550
+ /**
551
+ * Persists the cold-start snapshot to remote blob storage (S3, GCS, R2, HTTP).
552
+ * Can be awaited during graceful application shutdown (e.g. Kubernetes preStop or NestJS shutdown).
553
+ * Returns true if a snapshot was successfully exported and written; false otherwise.
554
+ */
555
+ writeRemoteSnapshot(): Promise<boolean>;
556
+ /**
557
+ * Hydrates L1 memory from remote blob storage (S3, GCS, R2, HTTP).
558
+ * Called automatically during startup (chained into `cache.ready()`).
559
+ * Returns the number of entries successfully imported.
560
+ */
561
+ loadRemoteSnapshot(): Promise<number>;
562
+ /**
563
+ * Get a value from cache, or fetch and cache it.
564
+ *
565
+ * @param cacheKey - Unique key identifying this value
566
+ * @param fetchFn - Called on a cache miss; its return value is cached and returned
567
+ * @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
568
+ * @param opts.priority - Override the auto-inferred eviction priority
569
+ * @param opts.swr - Stale-While-Revalidate grace seconds.
570
+ * @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
571
+ * is triggered proactively while the caller still receives the
572
+ * cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
573
+ * Requires `fetchFn` to be stable across calls.
574
+ * @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
575
+ * recompute more aggressively before expiry. Typical range: 0.5–2.
576
+ * Complementary to refreshAhead — uses recompute cost (delta) to
577
+ * decide probabilistically rather than at a fixed threshold.
578
+ * @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
579
+ * Caches negative lookups to avoid repeated DB hits for missing keys.
580
+ */
581
+ get<T>(cacheKey: string, fetchFn: (signal?: AbortSignal) => Promise<T>, ttlSeconds?: number, opts?: {
582
+ priority?: CachePriority;
583
+ swr?: number;
584
+ refreshAhead?: number;
585
+ xfetchBeta?: number;
586
+ notFoundTtl?: number;
587
+ /**
588
+ * Tags to associate with this cache entry when fetchFn populates it on a miss.
589
+ * Tags are registered in the in-process `tagIndex` and (if Redis is enabled) mirrored
590
+ * via `SADD` so that `invalidateTag()` covers disk-spill and multi-instance nodes.
591
+ * On an L1/L2 hit the tags are already registered — this field is a no-op for hits.
592
+ */
593
+ tags?: string[];
594
+ /** Dependency patterns registered when a miss populates the entry. */
595
+ dependsOn?: string[];
596
+ }): Promise<T>;
597
+ /**
598
+ * Graceful shutdown flusher for Kubernetes preStop hooks, NestJS onApplicationShutdown,
599
+ * or manual microservice teardown.
600
+ *
601
+ * Flushes both local disk and remote cloud snapshots (S3/R2/GCS), returning a Promise
602
+ * that resolves when the upload completes or after `timeoutMs` expires.
603
+ *
604
+ * @param timeoutMs Maximum time permitted for snapshot persistence before timing out. Default: 8000ms.
605
+ */
606
+ flushSnapshotOnShutdown(timeoutMs?: number): Promise<boolean>;
607
+ private _drainPendingDiskWork;
608
+ /**
609
+ * Internal graceful shutdown trigger invoked by ProcessTerminationBus.
610
+ */
611
+ _triggerShutdown(): void;
612
+ /**
613
+ * Universal fetch-and-cache wrapper with an ergonomic options object.
614
+ *
615
+ * Drop-in ergonomic alternative to `get()` matching developer expectations
616
+ * from `cache-manager` and `keyv`.
617
+ *
618
+ * @param cacheKey - Unique cache key.
619
+ * @param fetchFn - Executed on a cache miss to retrieve fresh data.
620
+ * @param options - Optional configuration object (TTL, SWR, tags, priority, etc.).
621
+ *
622
+ * @example
623
+ * const user = await cache.wrap(`user:${id}`, () => db.user.findUnique({ where: { id } }), {
624
+ * ttl: 300,
625
+ * swr: 60,
626
+ * tags: ['users'],
627
+ * });
628
+ */
629
+ wrap<T>(cacheKey: string, fetchFn: (signal?: AbortSignal) => Promise<T>, options?: WrapOptions): Promise<T>;
630
+ private _revalidate;
631
+ /** Explicitly write a value into L1 (+ L2 in production). */
632
+ set<T>(cacheKey: string, data: T, ttlSeconds?: number, priority?: CachePriority, opts?: {
633
+ tags?: string[];
634
+ dependsOn?: string[];
635
+ }): Promise<void>;
636
+ private _set;
637
+ /**
638
+ * Retain remote discovery through the entry's hard deadline plus cleanup grace.
639
+ * Each atomic registration initializes new sets and only extends expiring sets;
640
+ * existing persistent sets retain their unknown member lifetimes. Local metadata
641
+ * is maintained at admission/retention changes. Redis failure remains best effort.
642
+ */
643
+ private _registerTags;
644
+ /**
645
+ * Delete one key or a glob pattern (supports `*` wildcard).
646
+ *
647
+ * @example
648
+ * await cache.delete('user:abc:profile'); // exact key
649
+ * await cache.delete('user:abc:*'); // all keys for user abc
650
+ */
651
+ delete(cacheKey: string): Promise<void>;
652
+ /**
653
+ * Distributed counter.
654
+ *
655
+ * When Redis is active, one single-key script increments and applies missing
656
+ * expiry, returning the new fleet-wide value. A positive TTL starts a fixed
657
+ * window only when no expiry exists; subsequent increments do not extend it.
658
+ * Omitted/zero TTL creates a permanent counter and preserves existing expiry.
659
+ * Positive fractional seconds round up to milliseconds. Invalid TTLs reject
660
+ * before mutation. On a Redis error it increments `counters.errors`
661
+ * and, by default, fails OPEN — returning `0` so a caller's
662
+ * `if (count > LIMIT) reject()` guard does NOT reject during an outage. Set
663
+ * `failClosed: true` to re-throw the error instead, enforcing the limit even
664
+ * when Redis is unavailable.
665
+ *
666
+ * When Redis is disabled (or `disableRedis: true`), this maintains an
667
+ * IN-PROCESS counter with the same TTL semantics so dev/test rate-limiting
668
+ * works locally. The returned value is the local count (1, 2, 3, …), NOT 0 —
669
+ * a one-time warning is logged because rate-limiting is then per-instance, not
670
+ * fleet-wide.
671
+ */
672
+ increment(cacheKey: string, ttlSeconds?: number): Promise<number>;
673
+ /**
674
+ * Flush all cached entries, or only those whose key starts with `prefix`.
675
+ *
676
+ * @example
677
+ * await cache.clear(); // flush everything
678
+ * await cache.clear('user:abc'); // flush all keys for one user
679
+ */
680
+ clear(prefix?: string): Promise<void>;
681
+ /**
682
+ * Evict L1 entries that violate the current category or global capacity limits.
683
+ * Useful after a write burst or after adding stricter `categoryLimits`.
684
+ * Returns the number of entries evicted.
685
+ */
686
+ rebalance(): number;
687
+ /**
688
+ * Return the remaining TTL in seconds for a key currently in L1.
689
+ * Returns null if the key is absent from L1 or has already expired.
690
+ * Only reflects L1 state — does not query Redis or disk.
691
+ */
692
+ ttl(cacheKey: string): number | null;
693
+ /**
694
+ * Return true if the key exists in L1 and has not expired.
695
+ * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
696
+ */
697
+ has(cacheKey: string): boolean;
698
+ /**
699
+ * Lazily yield every non-expired L1 key, stripped of its namespace prefix.
700
+ *
701
+ * @example
702
+ * for (const key of cache.keys()) console.log(key);
703
+ */
704
+ keys(): Generator<string>;
705
+ /**
706
+ * Lazily yield every non-expired L1 value.
707
+ * Each value is the cached (pre-deserialized) JS object — no unpack overhead.
708
+ *
709
+ * @example
710
+ * for (const val of cache.values<User>()) console.log(val.id);
711
+ */
712
+ values<T = unknown>(): Generator<T>;
713
+ /**
714
+ * Lazily yield every non-expired L1 [key, value] pair.
715
+ * Keys are stripped of their namespace prefix.
716
+ *
717
+ * @example
718
+ * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
719
+ */
720
+ entries<T = unknown>(): Generator<[string, T]>;
721
+ /**
722
+ * High-throughput bulk scan over all live L1 entries.
723
+ *
724
+ * Compared with `entries()` this avoids generator frame overhead, per-entry
725
+ * `[key, value]` tuple allocation, and the `key.slice()` allocation when the
726
+ * caller uses the `offset` parameter instead of pre-slicing.
727
+ *
728
+ * ```typescript
729
+ * // Zero extra string allocations — use rawKey + offset directly:
730
+ * cache.scan((rawKey, value, offset) => {
731
+ * const key = rawKey.slice(offset); // allocate only if needed
732
+ * sync(key, value as User);
733
+ * });
734
+ * ```
735
+ *
736
+ * @param fn Called once per live L1 entry.
737
+ * `rawKey` — key with namespace prefix still attached.
738
+ * `value` — deserialized cached value.
739
+ * `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
740
+ */
741
+ scan<T = unknown>(fn: (rawKey: string, value: T, offset: number) => void): void;
742
+ /**
743
+ * Extend the TTL of a key in L1 and Redis without fetching.
744
+ * Returns `false` if the key is absent or already expired.
745
+ *
746
+ * @param newTtlSeconds - The new TTL from now, in seconds.
747
+ */
748
+ touch(cacheKey: string, newTtlSeconds: number): Promise<boolean>;
749
+ /**
750
+ * Return the cached value from L1 **only if it is fresh** (not in the SWR grace window).
751
+ * Returns `null` when the key is absent, expired, or stale — without triggering a fetch.
752
+ *
753
+ * @example
754
+ * const fresh = cache.getIfFresh('user:123');
755
+ * if (fresh !== null) return fresh; // serve from L1, no network hop
756
+ */
757
+ private _isLocallyInvalidated;
758
+ getIfFresh<T = unknown>(cacheKey: string): T | null;
759
+ private _prepareWriteValue;
760
+ private _prepareReadValue;
761
+ /**
762
+ * Origin-free read across L1, optional disk, and Redis without invoking a fetcher.
763
+ * Returns the cached value if found and valid, or `null` if absent / expired.
764
+ * Promotes hits and updates metrics/access policy; it can perform stale cleanup.
765
+ *
766
+ * @example
767
+ * const val = await cache.peek<User>('user:123');
768
+ */
769
+ peek<T = unknown>(cacheKey: string): Promise<T | null>;
770
+ /**
771
+ * Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
772
+ * Preserves input ordering. Uses inflight coalescing per key.
773
+ *
774
+ * @param keys - Array of cache keys.
775
+ * @param fetchFn - Called with only the keys that missed L1.
776
+ * @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
777
+ * `(key) => number` so heterogeneous TTLs can be batched in one call.
778
+ */
779
+ mget<T>(keys: string[], fetchFn?: (missKeys: string[], signal?: AbortSignal) => Promise<Record<string, T> | Map<string, T>>, ttl?: number | ((key: string) => number), priority?: CachePriority): Promise<(T | undefined)[]>;
780
+ /**
781
+ * Returns a Promise that resolves once the cache is fully initialised and any
782
+ * startup warming configured via `warmKeys` has completed.
783
+ *
784
+ * Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once
785
+ * `warmFromL2(warmKeys)` finishes — ideal for k8s readiness probes.
786
+ *
787
+ * @example
788
+ * const cache = CacheService.create({ warmKeys: 'user:*' });
789
+ * await cache.ready(); // gate traffic until warm
790
+ */
791
+ ready(): Promise<void>;
792
+ /**
793
+ * Batch write — set multiple entries in a single call.
794
+ * TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
795
+ *
796
+ * @example
797
+ * await cache.mset({
798
+ * 'user:1': { value: { name: 'Alice' }, ttl: 300 },
799
+ * 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
800
+ * });
801
+ */
802
+ mset<T = unknown>(entries: Record<string, {
803
+ value: T;
804
+ ttl?: number;
805
+ priority?: CachePriority;
806
+ tags?: string[];
807
+ dependsOn?: string[];
808
+ }>): Promise<void>;
809
+ /**
810
+ * Batch delete — delete multiple exact keys in a single call.
811
+ * Glob patterns are not supported; use `delete('prefix:*')` for patterns.
812
+ *
813
+ * @example
814
+ * await cache.mdel(['user:1', 'user:2', 'user:3']);
815
+ */
816
+ mdel(keys: string[]): Promise<void>;
817
+ /**
818
+ * Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
819
+ * pulling them into L1. Useful on startup to eliminate cold-start penalty when
820
+ * the local snapshot is unavailable or too stale.
821
+ *
822
+ * Returns the number of keys loaded into L1.
823
+ *
824
+ * @example
825
+ * // In your startup hook (e.g. ECS task, k8s readiness probe):
826
+ * const loaded = await cache.warmFromL2('org:*');
827
+ * console.log(`Warmed ${loaded} keys from Redis`);
828
+ */
829
+ warmFromL2(pattern: string, opts?: {
830
+ priority?: CachePriority;
831
+ }): Promise<number>;
832
+ /**
833
+ * Discovers all concrete tag names in the system that match `tag` either via
834
+ * glob wildcards ('*' or '?') or parent-child hierarchy cascading.
835
+ * Scans local in-memory indices (tagIndex, tagVersions, L1 entries) and Redis (if connected).
836
+ */
837
+ private _resolveMatchingTags;
838
+ private _publishTagInvalidation;
839
+ private _removeTagMembersLocal;
840
+ /**
841
+ * Executes invalidation for a single already-resolved concrete tag without
842
+ * wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
843
+ */
844
+ private _invalidateConcreteTag;
845
+ /**
846
+ * Executes invalidation for an array of already-resolved concrete tags
847
+ * without re-entering wildcard/cascade resolution or invalidateTag().
848
+ */
849
+ private _invalidateConcreteTags;
850
+ /**
851
+ * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
852
+ * Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
853
+ *
854
+ * @param tag Tag name or wildcard glob pattern (e.g. `'catalog'`, `'org:123:*'`, `'*:comments'`).
855
+ * @param opts Optional invalidation options, including `{ cascade: true }` to invalidate child namespaces.
856
+ *
857
+ * @example
858
+ * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
859
+ * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
860
+ *
861
+ * @example
862
+ * // Wildcard pattern invalidation
863
+ * await cache.invalidateTag('org:123:*');
864
+ *
865
+ * @example
866
+ * // Hierarchical tag cascading (clears 'org:123' and all child tags like 'org:123:dept:456')
867
+ * await cache.invalidateTag('org:123', { cascade: true });
868
+ */
869
+ invalidateTag(tag: string, opts?: InvalidateTagOptions): Promise<void>;
870
+ /**
871
+ * Invalidate all keys associated with any of the given tags in a single operation.
872
+ * Supports discrete tags, wildcard glob patterns, and hierarchical cascading.
873
+ * Combines multiple tag invalidations into Redis pipeline round-trips.
874
+ *
875
+ * @param tags Array of tag names or wildcard patterns (e.g. `['case:acme', 'org:*']`).
876
+ * @param opts Optional invalidation options, including `{ cascade: true }`.
877
+ *
878
+ * @example
879
+ * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:*']);
880
+ */
881
+ invalidateTags(tags: string[], opts?: InvalidateTagOptions): Promise<void>;
882
+ /**
883
+ * Get the current generational tag version for a tag (synced with Redis when due).
884
+ */
885
+ getTagVersion(tag: string): Promise<number>;
886
+ /**
887
+ * Measure L1 / disk / Redis latency.
888
+ * Useful for health checks and dashboards.
889
+ *
890
+ * @returns `{ l1, disk, l2 }` latencies in milliseconds.
891
+ * `l2` is `null` when Redis is disabled.
892
+ */
893
+ ping(): Promise<CachePingResult>;
894
+ /**
895
+ * Health and readiness diagnostics for container orchestrators (e.g. Kubernetes, ECS, Nomad).
896
+ *
897
+ * ─────────────────────────────────────────────────────────────────────────────
898
+ * ⚠️ CRITICAL CONTAINER PROBE SEMANTICS (Liveness vs. Readiness):
899
+ * ─────────────────────────────────────────────────────────────────────────────
900
+ * ❌ NEVER bind `degraded` checks or `cache.health()` to your Liveness Probe (/livez, /healthz).
901
+ * If an SRE hooks degraded status into liveness, a storage-starved or EBS-throttled pod
902
+ * will be killed by the kubelet, triggering a cluster-wide cascading restart shockwave.
903
+ * Liveness probes must only check that the event loop / process is alive.
904
+ *
905
+ * ✅ BIND degraded checks strictly to your Readiness Probe (/ready, /readyz).
906
+ * A degraded cache (e.g. EBS latency spike, quota watermark pruning, or open Redis circuit)
907
+ * can shed traffic at the ingress load balancer while the Node.js process remains
908
+ * alive to drain in-flight promises and heal its local storage.
909
+ *
910
+ * By default, `healthy` remains `true` even when degraded (graceful local degradation).
911
+ * Set `failReadinessOnDegraded: true` in CacheOptions if you want your Readiness probe
912
+ * to route ingress traffic away while degraded.
913
+ * ─────────────────────────────────────────────────────────────────────────────
914
+ */
915
+ health(): CacheHealthStatus;
916
+ /**
917
+ * Direct access to the internal tier latency watchdog instance.
918
+ * Used for diagnostics, canary probes, and control-loop tuning.
919
+ */
920
+ getLatencyWatchdog(): TierLatencyWatchdog;
921
+ /**
922
+ * Export all live L1 entries to Redis via a single pipeline.
923
+ * Useful for warming a new Redis instance or for zero-downtime failover.
924
+ * Returns the number of keys written.
925
+ */
926
+ drainToL2(): Promise<number>;
927
+ stats(): {
928
+ l1: {
929
+ entries: number;
930
+ sizeBytes: number;
931
+ sizeKB: number;
932
+ categories: Record<string, {
933
+ entries: number;
934
+ hits: number;
935
+ }>;
936
+ bloom: {
937
+ checks: number;
938
+ falsePositives: number;
939
+ absentChecks: number;
940
+ };
941
+ compression: {
942
+ compressed: number;
943
+ uncompressed: number;
944
+ bytesSaved: number;
945
+ };
946
+ };
947
+ disk: {
948
+ files: number;
949
+ sizeKB: number;
950
+ maxKB: number;
951
+ backpressure?: DiskBackpressureStats;
952
+ pruning?: {
953
+ active: boolean;
954
+ pruneRounds: number;
955
+ entriesPruned: number;
956
+ spillsShedTotal: number;
957
+ hostVolumeLowSpacePauses: number;
958
+ };
959
+ };
960
+ };
961
+ /**
962
+ * Write `value` only if the key is not already cached.
963
+ * Returns `true` if the write happened, `false` if the key already existed.
964
+ *
965
+ * When Redis is available, atomicity is guaranteed via `SET NX EX` so this
966
+ * is safe to use for idempotency keys and "first writer wins" patterns across
967
+ * multiple instances. L1 is populated on success.
968
+ *
969
+ * @example
970
+ * const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
971
+ * if (!claimed) return res.status(409).json({ error: 'duplicate request' });
972
+ */
973
+ setIfAbsent<T>(cacheKey: string, value: T, ttlSeconds?: number, priority?: CachePriority): Promise<boolean>;
974
+ /**
975
+ * Acquire a distributed (or in-process) mutual exclusion lock on `resourceKey`,
976
+ * execute `fn`, and automatically release the lock on completion or error.
977
+ *
978
+ * When Redis is connected, uses `SET lock:<key> <token> NX EX <ttl>` with
979
+ * safe Lua token release (`if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end`).
980
+ * When Redis is disabled, uses an in-process promise-chain mutex to ensure thread-safety.
981
+ *
982
+ * @param resourceKey Unique lock name / resource identifier (e.g. `'cron:nightly-sync'`).
983
+ * @param fn Task to run exclusively while holding the lock.
984
+ * @param options TTL, acquire timeout, and retry polling intervals.
985
+ */
986
+ lock<T>(resourceKey: string, fn: () => Promise<T>, options?: LockOptions): Promise<T>;
987
+ private _initOtelMetrics;
988
+ /**
989
+ * Return the top-N live L1 keys by historical access frequency.
990
+ * Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
991
+ * whose historical frequency exceeds their current in-memory hit count.
992
+ *
993
+ * Useful for diagnosing what is driving L1 pressure without any extra data
994
+ * collection overhead.
995
+ *
996
+ * @param n - Maximum number of keys to return. Default: 10.
997
+ *
998
+ * @example
999
+ * cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
1000
+ * console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
1001
+ */
1002
+ hotKeys(n?: number): Array<{
1003
+ key: string;
1004
+ hits: number;
1005
+ sizeBytes: number;
1006
+ }>;
1007
+ /**
1008
+ * Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
1009
+ * pattern that may contain `*` wildcards).
1010
+ */
1011
+ private _matchesGlob;
1012
+ /**
1013
+ * When an exact key `deletedKey` is removed, cascade to every dependent key
1014
+ * that was registered via `dependsOn` and whose source pattern matches.
1015
+ * Collect the complete closure before mutating indices, including current pending
1016
+ * writers. Fence all affected work synchronously; callers release Redis read
1017
+ * fences only after remote deletion has settled.
1018
+ */
1019
+ private _cascadeDependencies;
1020
+ private _cascadeDependenciesForPattern;
1021
+ private _cascadeDependencyClosure;
1022
+ /** Whether two `*`-only globs can match at least one common string. */
1023
+ private _globPatternsIntersect;
1024
+ private _publishPatternAndKeyInvalidations;
1025
+ /** Attempt every publication even when an awaited transport rejects one key. */
1026
+ private _publishKeyInvalidations;
1027
+ /** A peer's 'del' can accompany a set: remove dependent Redis values, never the source. */
1028
+ private _completeBackplaneCascade;
1029
+ /** Return a full metrics snapshot. */
1030
+ metrics(): CacheMetrics;
1031
+ /** Return auto-pipelining metrics, or null if pipelining is disabled. */
1032
+ getPipelinerStats(): {
1033
+ batchesDispatched: number;
1034
+ operationsBatched: number;
1035
+ pendingQueueSize: number;
1036
+ } | null;
1037
+ /**
1038
+ * Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
1039
+ * Paste the result into your `/metrics` endpoint.
1040
+ *
1041
+ * @param m - Snapshot returned by `cache.metrics()`
1042
+ * @param prefix - Metric name prefix. Default: `"tricache"`
1043
+ */
1044
+ static toPrometheusText(m: CacheMetrics, prefix?: string, instanceName?: string): string;
1045
+ /**
1046
+ * Dynamically rotate the active encryption key at runtime without restarting.
1047
+ * Installs the new key as primary for all subsequent writes, while preserving
1048
+ * the previous key for seamless fallback decryption of existing cache entries.
1049
+ */
1050
+ rotateEncryptionKey(newKeyBase64: string, newMode?: EncryptionMode): Promise<void>;
1051
+ /** Close Redis connections and stop all background timers. */
1052
+ destroy(): Promise<void>;
1053
+ /**
1054
+ * Return the active IPC telemetry server instance, if enabled.
1055
+ */
1056
+ getIpcServer(): IpcTelemetryServer | undefined;
1057
+ /**
1058
+ * Return real-time telemetry and metrics for the Window TinyLFU admission policy.
1059
+ * Returns `undefined` if W-TinyLFU admission is not active.
1060
+ */
1061
+ getWTinyLfuStats(): WTinyLfuStats | undefined;
1062
+ }
1063
+
1064
+ export { CacheService as C, type IIpcCacheProvider as I, type LatencyWatchdogOptions as L, ProcessTerminationBus as P, TierLatencyWatchdog as T, type IpcMetricsPayload as a, IpcTelemetryClient as b, IpcTelemetryServer as c, type LatencyWatchdogTelemetry as d, deepMergeOptions as e, findActiveSockets as f, formatBytes as g, formatDuration as h, formatNumber as i, renderTopDashboard as j, resolveIpcSocketPath as k, renderProgressBar as r };