tricache 1.0.0 → 1.0.2

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 (97) hide show
  1. package/README.md +36 -28
  2. package/dist/{cache-service-pJ-nFcVj.d.ts → cache-service-B108FzER.d.ts} +63 -3
  3. package/dist/cache-service-CWI4jkS7.d.cts +963 -0
  4. package/dist/{cache-service-26GCO3UU.js → cache-service-GYPZFB7O.js} +2 -2
  5. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  6. package/dist/{chunk-2AJKEQMZ.js → chunk-H4GFLQ26.js} +7 -4
  7. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  8. package/dist/chunk-OYDU3SMI.js +89 -0
  9. package/dist/{chunk-VXFTFZ5N.js → chunk-VNRDL5RA.js} +117 -138
  10. package/dist/{chunk-7SZSQS55.js → chunk-WYF7NOAT.js} +1831 -759
  11. package/dist/cli.cjs +1757 -777
  12. package/dist/cli.d.cts +12 -0
  13. package/dist/cli.js +27 -6
  14. package/dist/dashboard/index.cjs +111 -29
  15. package/dist/dashboard/index.d.cts +185 -0
  16. package/dist/dashboard/index.d.ts +5 -3
  17. package/dist/dashboard/index.js +1 -1
  18. package/dist/drizzle/index.cjs +1757 -773
  19. package/dist/drizzle/index.d.cts +46 -0
  20. package/dist/drizzle/index.d.ts +2 -2
  21. package/dist/drizzle/index.js +1 -1
  22. package/dist/edge/index.cjs +280 -153
  23. package/dist/edge/index.d.cts +127 -0
  24. package/dist/edge/index.d.ts +3 -3
  25. package/dist/edge/index.js +254 -147
  26. package/dist/hono/index.cjs +1805 -793
  27. package/dist/hono/index.d.cts +93 -0
  28. package/dist/hono/index.d.ts +7 -5
  29. package/dist/hono/index.js +16 -9
  30. package/dist/{hono-DuNvciyq.d.ts → hono-3rDMYVtY.d.ts} +23 -3
  31. package/dist/hono-C886ok3X.d.cts +391 -0
  32. package/dist/http/index.cjs +1946 -842
  33. package/dist/http/index.d.cts +103 -0
  34. package/dist/http/index.d.ts +13 -5
  35. package/dist/http/index.js +137 -57
  36. package/dist/index.cjs +2073 -937
  37. package/dist/index.d.cts +1006 -0
  38. package/dist/index.d.ts +40 -8
  39. package/dist/index.js +8 -8
  40. package/dist/murmur3-CMGw9PbV.d.cts +98 -0
  41. package/dist/nestjs/index.cjs +1849 -806
  42. package/dist/nestjs/index.d.cts +285 -0
  43. package/dist/nestjs/index.d.ts +103 -30
  44. package/dist/nestjs/index.js +115 -32
  45. package/dist/next/index.cjs +1913 -887
  46. package/dist/next/index.d.cts +232 -0
  47. package/dist/next/index.d.ts +33 -11
  48. package/dist/next/index.js +174 -107
  49. package/dist/prisma/index.cjs +11 -1
  50. package/dist/prisma/index.d.cts +62 -0
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +11 -1
  53. package/dist/serialize-worker.d.cts +2 -0
  54. package/dist/{types-5HXqBfAf.d.ts → types-BA4pz1A0.d.cts} +26 -9
  55. package/dist/types-BA4pz1A0.d.ts +1519 -0
  56. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  57. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  58. package/package.json +96 -36
  59. package/src/adapters/auto-pipeliner.ts +107 -24
  60. package/src/adapters/node-redis.ts +123 -25
  61. package/src/cache-service.ts +1238 -659
  62. package/src/cli.ts +24 -6
  63. package/src/cross-region.ts +21 -3
  64. package/src/dashboard/handler.ts +26 -6
  65. package/src/dashboard/html.ts +35 -10
  66. package/src/dashboard/index.ts +35 -13
  67. package/src/dashboard/types.ts +3 -1
  68. package/src/disk-tier.ts +171 -65
  69. package/src/edge/cache.ts +202 -129
  70. package/src/edge/hono.ts +23 -6
  71. package/src/edge/types.ts +2 -0
  72. package/src/hono/index.ts +19 -9
  73. package/src/http/express.ts +110 -26
  74. package/src/http/fastify.ts +38 -28
  75. package/src/http/utils.ts +54 -20
  76. package/src/ipc-telemetry.ts +35 -9
  77. package/src/nestjs/decorators.ts +1 -1
  78. package/src/nestjs/index.ts +2 -0
  79. package/src/nestjs/keyv-adapter.ts +68 -0
  80. package/src/nestjs/tricache.module.ts +13 -11
  81. package/src/nestjs/tricache.store.ts +51 -20
  82. package/src/nestjs/types.ts +29 -15
  83. package/src/next/cache-handler.ts +132 -57
  84. package/src/next/index.ts +1 -0
  85. package/src/next/isr-handler.ts +1 -4
  86. package/src/next/types.ts +21 -0
  87. package/src/prisma/index.ts +12 -1
  88. package/src/smart-memory-cache.ts +65 -27
  89. package/src/types.ts +27 -2
  90. package/src/utils/cgroup.ts +12 -0
  91. package/src/utils/deadline.ts +14 -0
  92. package/src/utils/diagnostics.ts +27 -0
  93. package/src/utils/redis-slot.ts +13 -0
  94. package/src/wasm/bloom-filter-wasm.ts +9 -4
  95. package/src/worker-pool.ts +17 -8
  96. package/src/wtiny-lfu.ts +20 -6
  97. package/dist/chunk-BQRURGGD.js +0 -60
@@ -0,0 +1,963 @@
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-BA4pz1A0.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 logger;
222
+ private readonly enc;
223
+ private readonly codec;
224
+ private readonly l1;
225
+ private readonly disk;
226
+ /** When true, all disk-tier and snapshot operations are skipped. */
227
+ private _diskDisabled;
228
+ /** Worker pool for off-main-thread AES-GCM (null when workerThreads is false or unavailable). */
229
+ private _workerPool;
230
+ private readonly opts;
231
+ /** Pre-computed once — opts.namespace never changes after construction. */
232
+ private readonly _namespace;
233
+ private readonly prefixLen;
234
+ /** Pre-computed once — disableRedis and redisHost never change after construction. */
235
+ private readonly _redisDisabled;
236
+ private readonly watchdog;
237
+ private pipeliner;
238
+ private readonly inflight;
239
+ private readonly revalidating;
240
+ private readonly _l1Counters;
241
+ /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
242
+ private readonly tagIndex;
243
+ /** Reverse index of namespaced key → { tags, expiresAt } for bounded cleanup on eviction/delete */
244
+ private readonly keyTags;
245
+ /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
246
+ private readonly tagVersions;
247
+ private _tagRefreshEpoch;
248
+ /**
249
+ * Dependency index: source glob pattern → Set of namespaced dependent keys.
250
+ * When an exact-key delete matches a registered pattern, all dependents are cascaded.
251
+ */
252
+ private readonly dependencyIndex;
253
+ /** Reverse index of namespaced dependent key → source glob patterns */
254
+ private readonly keyDependencies;
255
+ private readonly _cgroupMemoryLimit;
256
+ private redis;
257
+ private redisConnecting;
258
+ private readonly cb;
259
+ /** In-process mutex lock map for single-process environments or Redis outages. */
260
+ private _localLocks;
261
+ /** Active OpenTelemetry monotonic counters. */
262
+ private _otelMetrics;
263
+ private snapshotLoaded;
264
+ private _readyPromise;
265
+ private cleanupInterval;
266
+ private diskJanitorInterval;
267
+ private oomInterval;
268
+ private metricsInterval;
269
+ private remoteSnapshotInterval;
270
+ private _shutdownHandler;
271
+ private latencyTracker;
272
+ private readonly instanceId;
273
+ private readonly backplaneChannel;
274
+ private readonly backplaneStreamKey;
275
+ private subClient;
276
+ private streamClient;
277
+ private _lastStreamId;
278
+ private _restoredSnapshot;
279
+ private _backplaneAvailable;
280
+ private _otelCleanup;
281
+ private _streamRecovering;
282
+ private readonly _backplaneDisposers;
283
+ private _destroyed;
284
+ private readonly _pendingDiskDeletes;
285
+ private _globalEpoch;
286
+ private _pendingSpillCount;
287
+ private _suppressSpills;
288
+ private _diskCleanupScheduled;
289
+ private readonly _keyMutationEpochs;
290
+ /**
291
+ * Pattern tombstones for disk tier.
292
+ * Files in the disk tier are keyed by SHA-256 of namespacedKey.
293
+ * Wildcard pattern deletes cannot scan the filesystem synchronously, so we maintain
294
+ * pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
295
+ */
296
+ private readonly _patternTombstones;
297
+ private _diskInvalidatedBefore;
298
+ private _addPatternTombstone;
299
+ private _isTombstonedByPattern;
300
+ private _assertActive;
301
+ private _bumpKeyMutation;
302
+ private _getKeyMutationEpoch;
303
+ /** Capture a commit fence before asynchronous computation outside the cache. */
304
+ captureMutationFence(cacheKey: string): () => boolean;
305
+ /** Force tag re-sync without forgetting locally observed monotonic generations. */
306
+ refreshTagVersions(): void;
307
+ private _fenceInvalidation;
308
+ private _invalidateDiskKey;
309
+ private _scheduleDiskCleanup;
310
+ private _registerDependencies;
311
+ private _rememberTags;
312
+ private _restoreEntryMetadata;
313
+ private _removeKeyTags;
314
+ private _removeKeyDependencies;
315
+ private _handleL1Eviction;
316
+ private _removePatternFromIndices;
317
+ private _sweepExpiredMetadata;
318
+ private _runOomCheck;
319
+ private _ipcServer?;
320
+ /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
321
+ private _subDisconnectedAt;
322
+ /** Deduplication ring buffer for incoming and outgoing cross-region invalidations (loop prevention) */
323
+ private readonly _seenCrossRegionEvents;
324
+ private counters;
325
+ /** One-time guard so the in-process increment() fallback warning fires only once. */
326
+ private _incrementFallbackWarned;
327
+ constructor(options?: CacheOptions);
328
+ /**
329
+ * Pre-configured production presets tailored for specific deployment environments.
330
+ *
331
+ * - `'nextjs'`: W-TinyLFU, zero-copy cloneStrategy: 'none' (React 19 RSC stream optimized),
332
+ * generational tags, and Redis stream backplane.
333
+ * - `'microservice'`: High-throughput Node.js microservice with W-TinyLFU, Streams backplane,
334
+ * TTL jitter, and L2 circuit breaking.
335
+ * - `'serverless'`: Stateless Lambda / Cloud Run isolate with memory-only L1, fast timeouts,
336
+ * and Pub/Sub backplane.
337
+ * - `'enterprise-hardened'`: Zero-trust production setup with generational tagging, Streams backplane,
338
+ * fail-closed rate-limits, strict singleton assertions, and 80% OOM guard.
339
+ *
340
+ * @param type The preset identifier ('nextjs' | 'microservice' | 'serverless' | 'enterprise-hardened')
341
+ * @param overrides Optional configuration overrides merged deeply over preset defaults
342
+ * @returns Singleton CacheService instance configured according to the preset
343
+ */
344
+ static preset(type: CachePresetType, overrides?: Partial<CacheOptions>): CacheService;
345
+ /**
346
+ * Get (or create) the process-level singleton CacheService instance.
347
+ *
348
+ * Options are only applied on first call — subsequent calls return the
349
+ * existing instance regardless of options passed. When the new options differ
350
+ * from what the existing singleton was built with, this is a silent no-op by
351
+ * default; set `strictSingleton: true` to throw instead, or watch the
352
+ * `singletonDivergences` metric for detection.
353
+ *
354
+ * When `namespace` is set the singleton is keyed by namespace, so two calls
355
+ * with different namespaces return independent instances.
356
+ */
357
+ static create(options?: CacheOptions): CacheService;
358
+ /**
359
+ * Keys that, if set differently on a later `create()` call, represent a
360
+ * meaningful configuration divergence worth flagging (security/correctness
361
+ * relevant — not cosmetic, e.g. log level).
362
+ */
363
+ private static readonly DIVERGENT_KEYS;
364
+ /** Returns the names of options that differ between `a` and the live `b`. */
365
+ private static optionsDiff;
366
+ /** Increment the singleton-divergence counter (surfaced in `metrics()`). */
367
+ bumpSingletonDivergence(): void;
368
+ /** Sanitized diagnostic view; retain the original options/adapters to reuse configuration. */
369
+ get options(): CacheOptions;
370
+ /**
371
+ * Async factory — accepts a Promise that resolves to CacheOptions.
372
+ * Useful when config is fetched from a secret store at startup.
373
+ *
374
+ * @example
375
+ * const cache = await CacheService.createAsync(fetchSecrets());
376
+ */
377
+ static createAsync(options: Promise<CacheOptions> | CacheOptions): Promise<CacheService>;
378
+ /** Replace the singleton (useful in tests). */
379
+ static reset(options?: CacheOptions): CacheService;
380
+ /** Derive the globalThis key for a given set of options. */
381
+ private static globalKey;
382
+ /**
383
+ * Prepend the configured namespace to a raw cache key.
384
+ * Returns the key unchanged when namespace is empty.
385
+ *
386
+ * This is the only place the namespace prefix is applied — callers always
387
+ * receive and provide un-prefixed keys in the public API.
388
+ */
389
+ private nk;
390
+ /** Strip the instance namespace prefix from a namespaced key (inverse of `nk`). */
391
+ private unnk;
392
+ /** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
393
+ private _jitterTtl;
394
+ /** Shared no-op span for the common case where no tracer is configured.
395
+ * Using a singleton avoids allocating a fresh object literal on every get/set/delete call. */
396
+ private static readonly _nullSpan;
397
+ /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
398
+ private _startSpan;
399
+ private createDedicatedRedisClient;
400
+ private _listenBackplane;
401
+ private initBackplane;
402
+ private _resetAfterStreamGap;
403
+ private _startStreamConsumer;
404
+ /**
405
+ * Validate + apply one XREAD stream entry. `fields` is the flat ioredis
406
+ * shape [name, value, name, value, …]. Mirrors the schema rules of the
407
+ * pubsub path (`_handleBackplaneMessage`): op must be a known operation,
408
+ * key/src must be non-empty strings, tagVersion must parse to a finite
409
+ * number. Invalid entries are logged and dropped — never applied.
410
+ */
411
+ /** @internal Exposed for testing. */
412
+ _processStreamEntry(fields: string[]): void;
413
+ private _applyInvalidationEvent;
414
+ /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
415
+ _handleBackplaneMessage(message: string): void;
416
+ private publishInvalidation;
417
+ private _markCrossRegionEventSeen;
418
+ private _isCrossRegionEventSeen;
419
+ private _broadcastCrossRegion;
420
+ /**
421
+ * Receives an invalidation event from another region (e.g. via HTTP webhook or broker subscriber).
422
+ * Validates origin, deduplicates to prevent loops, applies locally to L1/disk,
423
+ * and fans out to the local Redis backplane so all regional peers invalidate as well.
424
+ *
425
+ * Returns true if the event was accepted and applied, or false if ignored/deduplicated.
426
+ */
427
+ receiveCrossRegionInvalidation(event: CrossRegionInvalidationEvent): Promise<boolean>;
428
+ private _setLocalTagVersion;
429
+ private _isGenerationalEntryStale;
430
+ private _deleteRedisKeys;
431
+ private _parseGenerationalRedisHash;
432
+ private _readRedisEntry;
433
+ private _getTagVersion;
434
+ private _readRedisBatch;
435
+ private _promoteRedisEntry;
436
+ private _readDiskEntry;
437
+ /** Common write policy and metadata across get/set/revalidation/draining. */
438
+ private _writeRedisEntry;
439
+ private _deleteIfStale;
440
+ /**
441
+ * Serialize payload for L2 Redis storage applying compression and encryption as configured.
442
+ * Offloads to worker thread if pool is active and payload exceeds threshold.
443
+ */
444
+ private _serializeAndEncrypt;
445
+ /**
446
+ * Deserialize raw L2 Redis entry applying decryption and decompression as needed.
447
+ * Offloads to worker thread if pool is active and payload exceeds threshold.
448
+ */
449
+ private _decryptAndDeserialize;
450
+ /**
451
+ * Scan all keys matching `pattern` across single-node or Cluster clients.
452
+ * For Cluster, iterates every master node independently (SCAN is node-local).
453
+ */
454
+ private _scanKeys;
455
+ private _checkAndLogResp3Hint;
456
+ private getRedis;
457
+ /**
458
+ * Writes the cold-start snapshot to disk.
459
+ * NOTE: fs.writeFileSync is INTENTIONAL here: this method is invoked during SIGTERM/SIGINT
460
+ * process termination hooks where asynchronous I/O would risk the Node.js event loop dying or
461
+ * process.exit() being called before the snapshot is physically written to disk.
462
+ */
463
+ writeSnapshot(altPath?: string): void;
464
+ /**
465
+ * Loads cold-start snapshot from disk into L1 memory.
466
+ * NOTE: fs.readFileSync is INTENTIONAL here: this method is invoked synchronously inside the
467
+ * CacheService constructor so that the cache is atomically populated before any subsequent
468
+ * cache.get() or cache.set() operations run, eliminating cold-start race conditions.
469
+ */
470
+ loadSnapshot(): void;
471
+ /**
472
+ * Persists the cold-start snapshot to remote blob storage (S3, GCS, R2, HTTP).
473
+ * Can be awaited during graceful application shutdown (e.g. Kubernetes preStop or NestJS shutdown).
474
+ * Returns true if a snapshot was successfully exported and written; false otherwise.
475
+ */
476
+ writeRemoteSnapshot(): Promise<boolean>;
477
+ /**
478
+ * Hydrates L1 memory from remote blob storage (S3, GCS, R2, HTTP).
479
+ * Called automatically during startup (chained into `cache.ready()`).
480
+ * Returns the number of entries successfully imported.
481
+ */
482
+ loadRemoteSnapshot(): Promise<number>;
483
+ /**
484
+ * Get a value from cache, or fetch and cache it.
485
+ *
486
+ * @param cacheKey - Unique key identifying this value
487
+ * @param fetchFn - Called on a cache miss; its return value is cached and returned
488
+ * @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
489
+ * @param opts.priority - Override the auto-inferred eviction priority
490
+ * @param opts.swr - Stale-While-Revalidate grace seconds.
491
+ * @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
492
+ * is triggered proactively while the caller still receives the
493
+ * cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
494
+ * Requires `fetchFn` to be stable across calls.
495
+ * @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
496
+ * recompute more aggressively before expiry. Typical range: 0.5–2.
497
+ * Complementary to refreshAhead — uses recompute cost (delta) to
498
+ * decide probabilistically rather than at a fixed threshold.
499
+ * @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
500
+ * Caches negative lookups to avoid repeated DB hits for missing keys.
501
+ */
502
+ get<T>(cacheKey: string, fetchFn: () => Promise<T>, ttlSeconds?: number, opts?: {
503
+ priority?: CachePriority;
504
+ swr?: number;
505
+ refreshAhead?: number;
506
+ xfetchBeta?: number;
507
+ notFoundTtl?: number;
508
+ /**
509
+ * Tags to associate with this cache entry when fetchFn populates it on a miss.
510
+ * Tags are registered in the in-process `tagIndex` and (if Redis is enabled) mirrored
511
+ * via `SADD` so that `invalidateTag()` covers disk-spill and multi-instance nodes.
512
+ * On an L1/L2 hit the tags are already registered — this field is a no-op for hits.
513
+ */
514
+ tags?: string[];
515
+ /** Dependency patterns registered when a miss populates the entry. */
516
+ dependsOn?: string[];
517
+ }): Promise<T>;
518
+ /**
519
+ * Graceful shutdown flusher for Kubernetes preStop hooks, NestJS onApplicationShutdown,
520
+ * or manual microservice teardown.
521
+ *
522
+ * Flushes both local disk and remote cloud snapshots (S3/R2/GCS), returning a Promise
523
+ * that resolves when the upload completes or after `timeoutMs` expires.
524
+ *
525
+ * @param timeoutMs Maximum time permitted for snapshot persistence before timing out. Default: 8000ms.
526
+ */
527
+ flushSnapshotOnShutdown(timeoutMs?: number): Promise<boolean>;
528
+ /**
529
+ * Internal graceful shutdown trigger invoked by ProcessTerminationBus.
530
+ */
531
+ _triggerShutdown(): void;
532
+ /**
533
+ * Universal fetch-and-cache wrapper with an ergonomic options object.
534
+ *
535
+ * Drop-in ergonomic alternative to `get()` matching developer expectations
536
+ * from `cache-manager` and `keyv`.
537
+ *
538
+ * @param cacheKey - Unique cache key.
539
+ * @param fetchFn - Executed on a cache miss to retrieve fresh data.
540
+ * @param options - Optional configuration object (TTL, SWR, tags, priority, etc.).
541
+ *
542
+ * @example
543
+ * const user = await cache.wrap(`user:${id}`, () => db.user.findUnique({ where: { id } }), {
544
+ * ttl: 300,
545
+ * swr: 60,
546
+ * tags: ['users'],
547
+ * });
548
+ */
549
+ wrap<T>(cacheKey: string, fetchFn: () => Promise<T>, options?: WrapOptions): Promise<T>;
550
+ private _revalidate;
551
+ /** Explicitly write a value into L1 (+ L2 in production). */
552
+ set<T>(cacheKey: string, data: T, ttlSeconds?: number, priority?: CachePriority, opts?: {
553
+ tags?: string[];
554
+ dependsOn?: string[];
555
+ }): Promise<void>;
556
+ /**
557
+ * Register tags for a cache key in the in-process index and (if Redis is enabled) in
558
+ * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
559
+ */
560
+ private _registerTags;
561
+ /**
562
+ * Delete one key or a glob pattern (supports `*` wildcard).
563
+ *
564
+ * @example
565
+ * await cache.delete('user:abc:profile'); // exact key
566
+ * await cache.delete('user:abc:*'); // all keys for user abc
567
+ */
568
+ delete(cacheKey: string): Promise<void>;
569
+ /**
570
+ * Distributed counter.
571
+ *
572
+ * When Redis is active, atomically increments the key via `INCR` and returns
573
+ * the new (fleet-wide) value. On a Redis error it increments `counters.errors`
574
+ * and, by default, fails OPEN — returning `0` so a caller's
575
+ * `if (count > LIMIT) reject()` guard does NOT reject during an outage. Set
576
+ * `failClosed: true` to re-throw the error instead, enforcing the limit even
577
+ * when Redis is unavailable.
578
+ *
579
+ * When Redis is disabled (or `disableRedis: true`), this maintains an
580
+ * IN-PROCESS counter with the same TTL semantics so dev/test rate-limiting
581
+ * works locally. The returned value is the local count (1, 2, 3, …), NOT 0 —
582
+ * a one-time warning is logged because rate-limiting is then per-instance, not
583
+ * fleet-wide.
584
+ */
585
+ increment(cacheKey: string, ttlSeconds?: number): Promise<number>;
586
+ /**
587
+ * Flush all cached entries, or only those whose key starts with `prefix`.
588
+ *
589
+ * @example
590
+ * await cache.clear(); // flush everything
591
+ * await cache.clear('user:abc'); // flush all keys for one user
592
+ */
593
+ clear(prefix?: string): Promise<void>;
594
+ /**
595
+ * Evict L1 entries that violate the current category or global capacity limits.
596
+ * Useful after a write burst or after adding stricter `categoryLimits`.
597
+ * Returns the number of entries evicted.
598
+ */
599
+ rebalance(): number;
600
+ /**
601
+ * Return the remaining TTL in seconds for a key currently in L1.
602
+ * Returns null if the key is absent from L1 or has already expired.
603
+ * Only reflects L1 state — does not query Redis or disk.
604
+ */
605
+ ttl(cacheKey: string): number | null;
606
+ /**
607
+ * Return true if the key exists in L1 and has not expired.
608
+ * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
609
+ */
610
+ has(cacheKey: string): boolean;
611
+ /**
612
+ * Lazily yield every non-expired L1 key, stripped of its namespace prefix.
613
+ *
614
+ * @example
615
+ * for (const key of cache.keys()) console.log(key);
616
+ */
617
+ keys(): Generator<string>;
618
+ /**
619
+ * Lazily yield every non-expired L1 value.
620
+ * Each value is the cached (pre-deserialized) JS object — no unpack overhead.
621
+ *
622
+ * @example
623
+ * for (const val of cache.values<User>()) console.log(val.id);
624
+ */
625
+ values<T = unknown>(): Generator<T>;
626
+ /**
627
+ * Lazily yield every non-expired L1 [key, value] pair.
628
+ * Keys are stripped of their namespace prefix.
629
+ *
630
+ * @example
631
+ * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
632
+ */
633
+ entries<T = unknown>(): Generator<[string, T]>;
634
+ /**
635
+ * High-throughput bulk scan over all live L1 entries.
636
+ *
637
+ * Compared with `entries()` this avoids generator frame overhead, per-entry
638
+ * `[key, value]` tuple allocation, and the `key.slice()` allocation when the
639
+ * caller uses the `offset` parameter instead of pre-slicing.
640
+ *
641
+ * ```typescript
642
+ * // Zero extra string allocations — use rawKey + offset directly:
643
+ * cache.scan((rawKey, value, offset) => {
644
+ * const key = rawKey.slice(offset); // allocate only if needed
645
+ * sync(key, value as User);
646
+ * });
647
+ * ```
648
+ *
649
+ * @param fn Called once per live L1 entry.
650
+ * `rawKey` — key with namespace prefix still attached.
651
+ * `value` — deserialized cached value.
652
+ * `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
653
+ */
654
+ scan<T = unknown>(fn: (rawKey: string, value: T, offset: number) => void): void;
655
+ /**
656
+ * Extend the TTL of a key in L1 and Redis without fetching.
657
+ * Returns `false` if the key is absent or already expired.
658
+ *
659
+ * @param newTtlSeconds - The new TTL from now, in seconds.
660
+ */
661
+ touch(cacheKey: string, newTtlSeconds: number): Promise<boolean>;
662
+ /**
663
+ * Return the cached value from L1 **only if it is fresh** (not in the SWR grace window).
664
+ * Returns `null` when the key is absent, expired, or stale — without triggering a fetch.
665
+ *
666
+ * @example
667
+ * const fresh = cache.getIfFresh('user:123');
668
+ * if (fresh !== null) return fresh; // serve from L1, no network hop
669
+ */
670
+ getIfFresh<T = unknown>(cacheKey: string): T | null;
671
+ private _prepareReadValue;
672
+ /**
673
+ * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
674
+ * Returns the cached value if found and valid, or `null` if absent / expired.
675
+ * Does not write dummy entries on misses or trigger side-effects.
676
+ *
677
+ * @example
678
+ * const val = await cache.peek<User>('user:123');
679
+ */
680
+ peek<T = unknown>(cacheKey: string): Promise<T | null>;
681
+ /**
682
+ * Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
683
+ * Preserves input ordering. Uses inflight coalescing per key.
684
+ *
685
+ * @param keys - Array of cache keys.
686
+ * @param fetchFn - Called with only the keys that missed L1.
687
+ * @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
688
+ * `(key) => number` so heterogeneous TTLs can be batched in one call.
689
+ */
690
+ mget<T>(keys: string[], fetchFn?: (missKeys: string[]) => Promise<Record<string, T> | Map<string, T>>, ttl?: number | ((key: string) => number), priority?: CachePriority): Promise<(T | undefined)[]>;
691
+ /**
692
+ * Returns a Promise that resolves once the cache is fully initialised and any
693
+ * startup warming configured via `warmKeys` has completed.
694
+ *
695
+ * Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once
696
+ * `warmFromL2(warmKeys)` finishes — ideal for k8s readiness probes.
697
+ *
698
+ * @example
699
+ * const cache = CacheService.create({ warmKeys: 'user:*' });
700
+ * await cache.ready(); // gate traffic until warm
701
+ */
702
+ ready(): Promise<void>;
703
+ /**
704
+ * Batch write — set multiple entries in a single call.
705
+ * TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
706
+ *
707
+ * @example
708
+ * await cache.mset({
709
+ * 'user:1': { value: { name: 'Alice' }, ttl: 300 },
710
+ * 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
711
+ * });
712
+ */
713
+ mset<T = unknown>(entries: Record<string, {
714
+ value: T;
715
+ ttl?: number;
716
+ priority?: CachePriority;
717
+ tags?: string[];
718
+ dependsOn?: string[];
719
+ }>): Promise<void>;
720
+ /**
721
+ * Batch delete — delete multiple exact keys in a single call.
722
+ * Glob patterns are not supported; use `delete('prefix:*')` for patterns.
723
+ *
724
+ * @example
725
+ * await cache.mdel(['user:1', 'user:2', 'user:3']);
726
+ */
727
+ mdel(keys: string[]): Promise<void>;
728
+ /**
729
+ * Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
730
+ * pulling them into L1. Useful on startup to eliminate cold-start penalty when
731
+ * the local snapshot is unavailable or too stale.
732
+ *
733
+ * Returns the number of keys loaded into L1.
734
+ *
735
+ * @example
736
+ * // In your startup hook (e.g. ECS task, k8s readiness probe):
737
+ * const loaded = await cache.warmFromL2('org:*');
738
+ * console.log(`Warmed ${loaded} keys from Redis`);
739
+ */
740
+ warmFromL2(pattern: string, opts?: {
741
+ priority?: CachePriority;
742
+ }): Promise<number>;
743
+ /**
744
+ * Discovers all concrete tag names in the system that match `tag` either via
745
+ * glob wildcards ('*' or '?') or parent-child hierarchy cascading.
746
+ * Scans local in-memory indices (tagIndex, tagVersions, L1 entries) and Redis (if connected).
747
+ */
748
+ private _resolveMatchingTags;
749
+ private _publishTagInvalidation;
750
+ private _removeTagMembersLocal;
751
+ /**
752
+ * Executes invalidation for a single already-resolved concrete tag without
753
+ * wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
754
+ */
755
+ private _invalidateConcreteTag;
756
+ /**
757
+ * Executes invalidation for an array of already-resolved concrete tags
758
+ * without re-entering wildcard/cascade resolution or invalidateTag().
759
+ */
760
+ private _invalidateConcreteTags;
761
+ /**
762
+ * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
763
+ * Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
764
+ *
765
+ * @param tag Tag name or wildcard glob pattern (e.g. `'catalog'`, `'org:123:*'`, `'*:comments'`).
766
+ * @param opts Optional invalidation options, including `{ cascade: true }` to invalidate child namespaces.
767
+ *
768
+ * @example
769
+ * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
770
+ * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
771
+ *
772
+ * @example
773
+ * // Wildcard pattern invalidation
774
+ * await cache.invalidateTag('org:123:*');
775
+ *
776
+ * @example
777
+ * // Hierarchical tag cascading (clears 'org:123' and all child tags like 'org:123:dept:456')
778
+ * await cache.invalidateTag('org:123', { cascade: true });
779
+ */
780
+ invalidateTag(tag: string, opts?: InvalidateTagOptions): Promise<void>;
781
+ /**
782
+ * Invalidate all keys associated with any of the given tags in a single operation.
783
+ * Supports discrete tags, wildcard glob patterns, and hierarchical cascading.
784
+ * Combines multiple tag invalidations into Redis pipeline round-trips.
785
+ *
786
+ * @param tags Array of tag names or wildcard patterns (e.g. `['case:acme', 'org:*']`).
787
+ * @param opts Optional invalidation options, including `{ cascade: true }`.
788
+ *
789
+ * @example
790
+ * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:*']);
791
+ */
792
+ invalidateTags(tags: string[], opts?: InvalidateTagOptions): Promise<void>;
793
+ /**
794
+ * Get the current generational tag version for a tag (synced with Redis when due).
795
+ */
796
+ getTagVersion(tag: string): Promise<number>;
797
+ /**
798
+ * Measure L1 / disk / Redis latency.
799
+ * Useful for health checks and dashboards.
800
+ *
801
+ * @returns `{ l1, disk, l2 }` latencies in milliseconds.
802
+ * `l2` is `null` when Redis is disabled.
803
+ */
804
+ ping(): Promise<CachePingResult>;
805
+ /**
806
+ * Health and readiness diagnostics for container orchestrators (e.g. Kubernetes, ECS, Nomad).
807
+ *
808
+ * ─────────────────────────────────────────────────────────────────────────────
809
+ * ⚠️ CRITICAL CONTAINER PROBE SEMANTICS (Liveness vs. Readiness):
810
+ * ─────────────────────────────────────────────────────────────────────────────
811
+ * ❌ NEVER bind `degraded` checks or `cache.health()` to your Liveness Probe (/livez, /healthz).
812
+ * If an SRE hooks degraded status into liveness, a storage-starved or EBS-throttled pod
813
+ * will be killed by the kubelet, triggering a cluster-wide cascading restart shockwave.
814
+ * Liveness probes must only check that the event loop / process is alive.
815
+ *
816
+ * ✅ BIND degraded checks strictly to your Readiness Probe (/ready, /readyz).
817
+ * A degraded cache (e.g. EBS latency spike, quota watermark pruning, or open Redis circuit)
818
+ * can shed traffic at the ingress load balancer while the Node.js process remains
819
+ * alive to drain in-flight promises and heal its local storage.
820
+ *
821
+ * By default, `healthy` remains `true` even when degraded (graceful local degradation).
822
+ * Set `failReadinessOnDegraded: true` in CacheOptions if you want your Readiness probe
823
+ * to route ingress traffic away while degraded.
824
+ * ─────────────────────────────────────────────────────────────────────────────
825
+ */
826
+ health(): CacheHealthStatus;
827
+ /**
828
+ * Direct access to the internal tier latency watchdog instance.
829
+ * Used for diagnostics, canary probes, and control-loop tuning.
830
+ */
831
+ getLatencyWatchdog(): TierLatencyWatchdog;
832
+ /**
833
+ * Export all live L1 entries to Redis via a single pipeline.
834
+ * Useful for warming a new Redis instance or for zero-downtime failover.
835
+ * Returns the number of keys written.
836
+ */
837
+ drainToL2(): Promise<number>;
838
+ stats(): {
839
+ l1: {
840
+ entries: number;
841
+ sizeBytes: number;
842
+ sizeKB: number;
843
+ categories: Record<string, {
844
+ entries: number;
845
+ hits: number;
846
+ }>;
847
+ bloom: {
848
+ checks: number;
849
+ falsePositives: number;
850
+ };
851
+ compression: {
852
+ compressed: number;
853
+ uncompressed: number;
854
+ bytesSaved: number;
855
+ };
856
+ };
857
+ disk: {
858
+ files: number;
859
+ sizeKB: number;
860
+ maxKB: number;
861
+ backpressure?: DiskBackpressureStats;
862
+ pruning?: {
863
+ active: boolean;
864
+ pruneRounds: number;
865
+ entriesPruned: number;
866
+ spillsShedTotal: number;
867
+ hostVolumeLowSpacePauses: number;
868
+ };
869
+ };
870
+ };
871
+ /**
872
+ * Write `value` only if the key is not already cached.
873
+ * Returns `true` if the write happened, `false` if the key already existed.
874
+ *
875
+ * When Redis is available, atomicity is guaranteed via `SET NX EX` so this
876
+ * is safe to use for idempotency keys and "first writer wins" patterns across
877
+ * multiple instances. L1 is populated on success.
878
+ *
879
+ * @example
880
+ * const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
881
+ * if (!claimed) return res.status(409).json({ error: 'duplicate request' });
882
+ */
883
+ setIfAbsent<T>(cacheKey: string, value: T, ttlSeconds?: number, priority?: CachePriority): Promise<boolean>;
884
+ /**
885
+ * Acquire a distributed (or in-process) mutual exclusion lock on `resourceKey`,
886
+ * execute `fn`, and automatically release the lock on completion or error.
887
+ *
888
+ * When Redis is connected, uses `SET lock:<key> <token> NX EX <ttl>` with
889
+ * safe Lua token release (`if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end`).
890
+ * When Redis is disabled, uses an in-process promise-chain mutex to ensure thread-safety.
891
+ *
892
+ * @param resourceKey Unique lock name / resource identifier (e.g. `'cron:nightly-sync'`).
893
+ * @param fn Task to run exclusively while holding the lock.
894
+ * @param options TTL, acquire timeout, and retry polling intervals.
895
+ */
896
+ lock<T>(resourceKey: string, fn: () => Promise<T>, options?: LockOptions): Promise<T>;
897
+ private _initOtelMetrics;
898
+ /**
899
+ * Return the top-N live L1 keys by historical access frequency.
900
+ * Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
901
+ * whose historical frequency exceeds their current in-memory hit count.
902
+ *
903
+ * Useful for diagnosing what is driving L1 pressure without any extra data
904
+ * collection overhead.
905
+ *
906
+ * @param n - Maximum number of keys to return. Default: 10.
907
+ *
908
+ * @example
909
+ * cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
910
+ * console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
911
+ */
912
+ hotKeys(n?: number): Array<{
913
+ key: string;
914
+ hits: number;
915
+ sizeBytes: number;
916
+ }>;
917
+ /**
918
+ * Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
919
+ * pattern that may contain `*` wildcards).
920
+ */
921
+ private _matchesGlob;
922
+ /**
923
+ * When an exact key `deletedKey` is removed, cascade to every dependent key
924
+ * that was registered via `dependsOn` and whose source pattern matches.
925
+ * Transitive dependencies are traversed with cycle protection via a visited Set.
926
+ */
927
+ private _cascadeDependencies;
928
+ /** Return a full metrics snapshot. */
929
+ metrics(): CacheMetrics;
930
+ /** Return auto-pipelining metrics, or null if pipelining is disabled. */
931
+ getPipelinerStats(): {
932
+ batchesDispatched: number;
933
+ operationsBatched: number;
934
+ pendingQueueSize: number;
935
+ } | null;
936
+ /**
937
+ * Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
938
+ * Paste the result into your `/metrics` endpoint.
939
+ *
940
+ * @param m - Snapshot returned by `cache.metrics()`
941
+ * @param prefix - Metric name prefix. Default: `"tricache"`
942
+ */
943
+ static toPrometheusText(m: CacheMetrics, prefix?: string, instanceName?: string): string;
944
+ /**
945
+ * Dynamically rotate the active encryption key at runtime without restarting.
946
+ * Installs the new key as primary for all subsequent writes, while preserving
947
+ * the previous key for seamless fallback decryption of existing cache entries.
948
+ */
949
+ rotateEncryptionKey(newKeyBase64: string, newMode?: EncryptionMode): Promise<void>;
950
+ /** Close Redis connections and stop all background timers. */
951
+ destroy(): Promise<void>;
952
+ /**
953
+ * Return the active IPC telemetry server instance, if enabled.
954
+ */
955
+ getIpcServer(): IpcTelemetryServer | undefined;
956
+ /**
957
+ * Return real-time telemetry and metrics for the Window TinyLFU admission policy.
958
+ * Returns `undefined` if W-TinyLFU admission is not active.
959
+ */
960
+ getWTinyLfuStats(): WTinyLfuStats | undefined;
961
+ }
962
+
963
+ 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 };