tricache 0.6.6 → 0.7.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 (55) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +500 -24
  3. package/bin/tricache.js +8 -0
  4. package/dist/cache-service-AJASH5FX.js +7 -0
  5. package/dist/cache-service-BblHuF3i.d.ts +1476 -0
  6. package/dist/chunk-3XQUQBOZ.js +4583 -0
  7. package/dist/{chunk-FKY5R3CE.js → chunk-PFB5FMEY.js} +126 -4
  8. package/dist/chunk-UBSR5UYA.js +0 -0
  9. package/dist/cli.cjs +5181 -0
  10. package/dist/cli.d.ts +11 -0
  11. package/dist/cli.js +130 -0
  12. package/dist/drizzle/index.cjs +5161 -0
  13. package/dist/drizzle/index.d.ts +44 -0
  14. package/dist/drizzle/index.js +46 -0
  15. package/dist/http/index.cjs +5289 -0
  16. package/dist/http/index.d.ts +33 -0
  17. package/dist/http/index.js +172 -0
  18. package/dist/index.cjs +1181 -194
  19. package/dist/index.d.ts +15 -1230
  20. package/dist/index.js +11 -3697
  21. package/dist/nestjs/index.cjs +5305 -0
  22. package/dist/nestjs/index.d.ts +210 -0
  23. package/dist/nestjs/index.js +250 -0
  24. package/dist/next/index.cjs +5327 -0
  25. package/dist/next/index.d.ts +204 -0
  26. package/dist/next/index.js +274 -0
  27. package/dist/prisma/index.cjs +122 -0
  28. package/dist/prisma/index.d.ts +60 -0
  29. package/dist/prisma/index.js +86 -0
  30. package/dist/serialize-worker.cjs +177 -13
  31. package/dist/serialize-worker.js +63 -12
  32. package/package.json +64 -15
  33. package/src/cache-service.ts +1005 -192
  34. package/src/cli.ts +143 -0
  35. package/src/compression.ts +63 -0
  36. package/src/disk-tier.ts +71 -7
  37. package/src/drizzle/index.ts +86 -0
  38. package/src/encryption.ts +56 -5
  39. package/src/http/index.ts +223 -0
  40. package/src/index.ts +7 -0
  41. package/src/nestjs/decorators.ts +161 -0
  42. package/src/nestjs/index.ts +23 -0
  43. package/src/nestjs/tricache.module.ts +104 -0
  44. package/src/nestjs/tricache.store.ts +97 -0
  45. package/src/nestjs/types.ts +79 -0
  46. package/src/next/cache-handler.ts +244 -0
  47. package/src/next/index.ts +37 -0
  48. package/src/next/isr-handler.ts +105 -0
  49. package/src/next/types.ts +130 -0
  50. package/src/prisma/index.ts +151 -0
  51. package/src/serialize-worker.ts +77 -13
  52. package/src/smart-memory-cache.ts +22 -8
  53. package/src/types.ts +172 -2
  54. package/src/wasm/bloom-filter-wasm.ts +3 -2
  55. package/src/worker-pool.ts +156 -42
@@ -0,0 +1,1476 @@
1
+ /**
2
+ * tricache — shared types and interfaces
3
+ */
4
+ /**
5
+ * Minimal span interface — structurally compatible with `@opentelemetry/api` Span.
6
+ * Pass your existing OTEL tracer; no extra package required.
7
+ */
8
+ interface ICacheSpan {
9
+ setAttribute(key: string, value: string | number | boolean): this;
10
+ setStatus(status: {
11
+ code: 0 | 1 | 2;
12
+ message?: string;
13
+ }): this;
14
+ end(): void;
15
+ }
16
+ /**
17
+ * Minimal tracer interface — structurally compatible with `@opentelemetry/api` Tracer.
18
+ */
19
+ interface ICacheTracer {
20
+ startSpan(name: string): ICacheSpan;
21
+ }
22
+ /** Minimal logger interface — plug in any logger (pino, winston, console, etc.) */
23
+ interface ILogger {
24
+ debug(msg: string, meta?: Record<string, unknown>): void;
25
+ info(msg: string, meta?: Record<string, unknown>): void;
26
+ warn(msg: string, meta?: Record<string, unknown>): void;
27
+ error(msg: string, meta?: Record<string, unknown>, err?: Error): void;
28
+ }
29
+ /** Default no-op logger — swap out via CacheService options */
30
+ declare const consoleLogger: ILogger;
31
+ /**
32
+ * Reason passed to the `onEviction` callback.
33
+ * - `'capacity'` — L1 over-capacity; evicted during a `set()` call
34
+ * - `'category'` — Per-category limit exceeded
35
+ * - `'rebalance'` — `cache.rebalance()` was called
36
+ * - `'oom'` — OOM guard emergency eviction
37
+ * - `'ttl'` — Entry expired during periodic cleanup
38
+ * - `'manual'` — Explicit `cache.delete()` call
39
+ */
40
+ type EvictionReason = 'capacity' | 'category' | 'rebalance' | 'oom' | 'ttl' | 'manual';
41
+ /** Per-tier latency returned by `cache.ping()`. */
42
+ interface CachePingResult {
43
+ /** L1 RAM check latency in milliseconds */
44
+ l1: number;
45
+ /** L1.5 disk stats access in milliseconds */
46
+ disk: number;
47
+ /** L2 Redis PING round-trip in milliseconds, or `null` when Redis is disabled */
48
+ l2: number | null;
49
+ }
50
+ /** Priority levels for L1 eviction — higher = less likely to be evicted */
51
+ declare enum CachePriority {
52
+ LOW = 1,// Easily regenerated (analytics, reports)
53
+ NORMAL = 2,// General data
54
+ HIGH = 3,// Frequently accessed (profiles, config)
55
+ CRITICAL = 4
56
+ }
57
+ /** Internal representation of a single cache entry in the L1 Map */
58
+ interface SmartCacheEntry {
59
+ /** msgpackr-packed binary payload — used for disk spill and snapshot serialization */
60
+ data: Buffer;
61
+ /**
62
+ * Deserialized JS value, cached at write time so hot reads skip the unpack step entirely.
63
+ * Undefined for entries restored from disk/snapshot (populated lazily on first access).
64
+ * NOTE: returned by reference — callers should treat the value as immutable.
65
+ */
66
+ value?: unknown;
67
+ /** always true for entries written by the current code;
68
+ * may be false in legacy snapshots/disk files — handled transparently on import */
69
+ isCompressed: boolean;
70
+ /** Hard expiry — entry is deleted after this timestamp */
71
+ expiresAt: number;
72
+ /** SWR soft expiry — serve stale + revalidate in background when past this */
73
+ staleAt?: number;
74
+ /** Exact byte size of the stored value */
75
+ size: number;
76
+ /** Access count (LFU numerator) */
77
+ hits: number;
78
+ /** Last access timestamp (LRU comparator) */
79
+ lastAccess: number;
80
+ /** Eviction priority */
81
+ priority: CachePriority;
82
+ /** Original TTL in ms at write time — used by refresh-ahead to compute the proactive refresh threshold. */
83
+ ttlMs?: number;
84
+ /** Milliseconds taken to fetch/compute this value — used by XFetch probabilistic early expiration. */
85
+ delta?: number;
86
+ /**
87
+ * Unix timestamp (ms) when this entry was written.
88
+ * Stored explicitly so staleness-fence eviction (`evictSetBefore`) is precise
89
+ * instead of approximating via `expiresAt - ttlMs`.
90
+ * Optional for backward compatibility with snapshots written by older versions.
91
+ */
92
+ setAt?: number;
93
+ /** Active tag versions at write time (used when tagStrategy === 'generational') */
94
+ tagVersions?: Record<string, number>;
95
+ }
96
+ /** Returned by SmartMemoryCache.get() — distinguishes "cached null" from a real miss */
97
+ interface CacheHit {
98
+ value: unknown;
99
+ /** true = past soft TTL (staleAt) but within hard expiry → SWR path */
100
+ isStale: boolean;
101
+ /** Hard expiry timestamp — lets CacheService.get() do refresh-ahead / XFetch math
102
+ * without a second Map lookup (eliminates the duplicate l1.getEntry() call). */
103
+ expiresAt: number;
104
+ /** Original TTL in ms stored at write time — for refresh-ahead fraction calculation */
105
+ ttlMs?: number;
106
+ /** Fetch duration in ms stored at write time — for XFetch probabilistic threshold */
107
+ delta?: number;
108
+ /** Timestamp (Date.now()) recorded inside SmartMemoryCache.get() — lets CacheService
109
+ * reuse this value for refresh-ahead/XFetch math instead of making a second syscall. */
110
+ fetchedAt?: number;
111
+ /** Active tag versions at write time (used when tagStrategy === 'generational') */
112
+ tagVersions?: Record<string, number>;
113
+ /** Timestamp (ms) when this entry was written into memory */
114
+ setAt?: number;
115
+ }
116
+ /** On-disk entry shape (mirrors SmartCacheEntry — Uint8Array accepted for msgpack round-trips;
117
+ * legacy disk files written by older versions may have a JSON string in data) */
118
+ interface DiskCacheEntry {
119
+ data: string | Buffer | Uint8Array;
120
+ isCompressed: boolean;
121
+ expiresAt: number;
122
+ staleAt?: number;
123
+ size: number;
124
+ hits: number;
125
+ lastAccess: number;
126
+ priority: number;
127
+ /** Active tag versions at write time (used when tagStrategy === 'generational') */
128
+ tagVersions?: Record<string, number>;
129
+ }
130
+ /**
131
+ * Snapshot of runtime metrics for a CacheService instance.
132
+ * Returned by `CacheService.metrics()` and passed to the `onMetrics` callback.
133
+ * Convert to Prometheus text with `CacheService.toPrometheusText(metrics)`.
134
+ */
135
+ interface CacheMetrics {
136
+ /** Configured namespace (empty string = no namespace) */
137
+ namespace: string;
138
+ /** Milliseconds since the CacheService instance was constructed */
139
+ uptimeMs: number;
140
+ gets: {
141
+ total: number;
142
+ l1Hits: number;
143
+ /** Fraction of gets served from L1 RAM cache (0–1) */
144
+ l1HitRate: number;
145
+ diskHits: number;
146
+ /** Fraction of gets served from L1.5 disk tier (0–1) */
147
+ diskHitRate: number;
148
+ l2Hits: number;
149
+ /** Fraction of gets served from L2 Redis (0–1) */
150
+ l2HitRate: number;
151
+ /** fetchFn calls (cache misses that fell through to the DB) */
152
+ fetches: number;
153
+ /** Fraction of gets that called fetchFn (0–1) */
154
+ fetchRate: number;
155
+ /** Concurrent get() calls deduplicated by the stampede guard */
156
+ stampedePrevented: number;
157
+ };
158
+ sets: {
159
+ total: number;
160
+ };
161
+ deletes: {
162
+ total: number;
163
+ };
164
+ revalidations: {
165
+ total: number;
166
+ };
167
+ /** Rate-limit / singleton diagnostics */
168
+ counters: {
169
+ /** Times `increment()` hit a Redis error (fail-open by default, or fail-closed re-throw). */
170
+ errors: number;
171
+ /** Times a later `create(ns)` call passed options diverging from the live singleton. */
172
+ singletonDivergences: number;
173
+ };
174
+ bloom: {
175
+ /** Total bloom-filter checks (get() calls that passed prefix filter) */
176
+ checksTotal: number;
177
+ /**
178
+ * Times the filter said "might contain" but the key was absent in L1.
179
+ * A high rate suggests the bloom filter capacity needs increasing.
180
+ */
181
+ falsePositives: number;
182
+ /** falsePositives / checksTotal (0–1; ideal < 0.01) */
183
+ falsePositiveRate: number;
184
+ };
185
+ compression: {
186
+ entriesCompressed: number;
187
+ entriesUncompressed: number;
188
+ /** Approximate bytes saved by msgpackr vs raw JSON */
189
+ bytesSaved: number;
190
+ };
191
+ /** Invalidation backplane statistics */
192
+ backplane: {
193
+ enabled: boolean;
194
+ mode: 'pubsub' | 'stream';
195
+ /** Invalidation messages published to other instances */
196
+ sent: number;
197
+ /** Invalidation messages received from other instances */
198
+ received: number;
199
+ /** Own messages silently skipped (prevents double-eviction) */
200
+ skipped: number;
201
+ /** Stream entries received (when backplaneMode is 'stream') */
202
+ streamEntriesReceived?: number;
203
+ /** Replayed invalidations after network reconnect */
204
+ streamReplays?: number;
205
+ /** Stream trim gaps detected (where consumer fell behind oldest entry) */
206
+ streamGaps?: number;
207
+ };
208
+ /** L2 Redis circuit breaker state */
209
+ l2CircuitBreaker: {
210
+ /** `'closed'` = normal; `'open'` = Redis paused; `'half_open'` = probing recovery */
211
+ state: 'closed' | 'open' | 'half_open';
212
+ };
213
+ /** OOM guard statistics */
214
+ oom: {
215
+ enabled: boolean;
216
+ /** Number of emergency L1 eviction rounds triggered */
217
+ evictions: number;
218
+ /** Timestamp of the most recent OOM eviction, or null */
219
+ lastTriggeredAt: number | null;
220
+ };
221
+ l1: {
222
+ entries: number;
223
+ sizeBytes: number;
224
+ maxBytes: number;
225
+ };
226
+ disk: {
227
+ files: number;
228
+ sizeKB: number;
229
+ maxKB: number;
230
+ disabled: boolean;
231
+ };
232
+ /** Adaptive TTL statistics — present only when `adaptiveTtl` is enabled */
233
+ adaptiveTtl?: {
234
+ enabled: true;
235
+ /** Number of unique keys currently tracked in the latency ring buffers */
236
+ trackedKeys: number;
237
+ /**
238
+ * Top-20 slowest keys by p95 fetch latency, sorted descending.
239
+ * Keys are shown without the instance namespace prefix.
240
+ * Only keys with ≥ 5 recorded samples appear here.
241
+ */
242
+ slowestKeys: Array<{
243
+ key: string;
244
+ p95Ms: number;
245
+ adaptedTtlSec: number;
246
+ }>;
247
+ };
248
+ }
249
+ /** Per-category memory limits for L1 */
250
+ interface CategoryLimit {
251
+ maxEntries: number;
252
+ maxSizeBytes: number;
253
+ }
254
+ /**
255
+ * Options accepted by CacheService.create()
256
+ *
257
+ * All fields are optional — sensible defaults are used when omitted.
258
+ */
259
+ interface CacheOptions {
260
+ /**
261
+ * Plug in your own logger (pino, winston, bunyan, …).
262
+ * Defaults to a minimal console logger that only prints warn/error.
263
+ */
264
+ logger?: ILogger;
265
+ /** Max total bytes held in L1 RAM cache. Default: 200 MB */
266
+ l1MaxBytes?: number;
267
+ /** Max total entries in L1. Default: 2000 */
268
+ l1MaxEntries?: number;
269
+ /**
270
+ * Fraction of `l1MaxEntries` / `l1MaxBytes` at which proactive eviction fires
271
+ * before the hard limit is reached. Range: 0–1. Default: 0.9.
272
+ * Lower (e.g. 0.8) reduces GC pressure at the cost of slightly more eviction work.
273
+ */
274
+ l1EvictionWatermark?: number;
275
+ /**
276
+ * Per-category limits keyed by the key prefix (e.g. `'org:'`).
277
+ * Merged over the built-in defaults.
278
+ */
279
+ categoryLimits?: Record<string, CategoryLimit>;
280
+ /**
281
+ * Key prefixes that are never written to disk snapshots or the disk tier.
282
+ * Default: ['auth:', 'session:', 'mfa:', 'rate_limit:']
283
+ */
284
+ forbiddenSnapshotPrefixes?: string[];
285
+ /** Directory used for L1.5 disk-spill files. Default: os.tmpdir()/tricache-disk */
286
+ diskCacheDir?: string;
287
+ /** Max total bytes for the disk tier. Default: 500 MB */
288
+ diskMaxBytes?: number;
289
+ /** Max bytes for a single disk entry. Default: 10 MB */
290
+ diskEntryMaxBytes?: number;
291
+ /**
292
+ * Redis/Valkey hostname (no `redis://` prefix).
293
+ * Falls back to the `REDIS_HOST` environment variable.
294
+ * When neither is provided, L2 is disabled.
295
+ */
296
+ redisHost?: string;
297
+ /** Redis port. Default: 6379 */
298
+ redisPort?: number;
299
+ /**
300
+ * Whether to enable TLS for the Redis connection. Default: true in production,
301
+ * false otherwise.
302
+ */
303
+ redisTls?: boolean;
304
+ /**
305
+ * Redis wire protocol version (RESP2 or RESP3).
306
+ * Defaults to 3 in ioredis v6+. Set to 2 for legacy proxies or servers without RESP3 support.
307
+ */
308
+ redisProtocol?: 2 | 3;
309
+ /**
310
+ * Set to `true` to disable L2 Redis entirely (e.g. when running single-process
311
+ * services that don't need distributed caching). Default: false in production,
312
+ * true in development.
313
+ */
314
+ disableRedis?: boolean;
315
+ /**
316
+ * Base64-encoded 32-byte AES-256-GCM key for encrypting L2 (Redis) values and
317
+ * disk-tier files at rest. Falls back to `CACHE_ENCRYPTION_KEY` env var.
318
+ * If not provided in production, a warning is logged and data is stored plaintext.
319
+ */
320
+ encryptionKey?: string;
321
+ /**
322
+ * Encryption algorithm used for L2 (Redis) values and disk-tier files.
323
+ * - `'aes-256-gcm'` — default. 32-byte key. Authenticated encryption (AEAD).
324
+ * - `'aes-128-gcm'` — 16-byte key. ~10% faster on non-AES-NI hardware. AEAD.
325
+ * - `'xor'` — XOR obfuscation ONLY. NOT cryptographic security.
326
+ * Any key length (minimum 16 bytes recommended).
327
+ * Use for dev environments or non-sensitive data only.
328
+ * Default: `'aes-256-gcm'`
329
+ */
330
+ encryptionMode?: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
331
+ /**
332
+ * Fallback encryption key for zero-downtime key rotation.
333
+ * On every read, tricache tries the current `encryptionKey` first.
334
+ * If decryption fails (wrong key), it retries with `previousEncryptionKey`.
335
+ * All writes always use the current `encryptionKey`.
336
+ * Remove this field once you are confident all data has been re-encrypted.
337
+ */
338
+ previousEncryptionKey?: string;
339
+ /** Encryption mode that was used with `previousEncryptionKey`. Defaults to `encryptionMode`. */
340
+ previousEncryptionMode?: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
341
+ /**
342
+ * Optional compression algorithm for L2 (Redis) strings and disk-tier binary blobs.
343
+ * - `'brotli'` (default when enabled) — superior compression ratio for JSON / text payloads.
344
+ * - `'gzip'` — faster compression / lower CPU overhead.
345
+ * - `'none'` — disable compression.
346
+ * Default: `'none'` (uncompressed).
347
+ */
348
+ compression?: 'brotli' | 'gzip' | 'none';
349
+ /**
350
+ * Minimum payload size in bytes before compression is applied.
351
+ * Payloads smaller than this threshold remain uncompressed to avoid compression overhead.
352
+ * Default: `1024` (1 KB).
353
+ */
354
+ compressionThresholdBytes?: number;
355
+ /**
356
+ * Path where the cold-start snapshot is written on SIGTERM/SIGINT and loaded
357
+ * on startup. Default: os.tmpdir()/tricache-snapshot.msgpack
358
+ */
359
+ snapshotPath?: string;
360
+ /**
361
+ * Max age (ms) of a snapshot file before it is rejected. Default: 2 hours
362
+ */
363
+ snapshotMaxAgeMs?: number;
364
+ /**
365
+ * Optional namespace prefix for all cache keys.
366
+ *
367
+ * When set, every key is transparently stored as `${namespace}:${key}` in
368
+ * L1, L1.5 (disk), and L2 (Redis). This enables:
369
+ * - **Multi-tenant isolation**: `CacheService.create({ namespace: 'org_abc' })`
370
+ * — tenants sharing the same Redis instance or disk dir are fully isolated.
371
+ * - **Environment separation**: `CacheService.create({ namespace: 'staging' })`
372
+ * - **Service-level scoping**: microservices sharing one Redis without key collisions.
373
+ *
374
+ * Consumers never see the prefix — `get('user:1')` behaves identically
375
+ * whether namespaced or not. Glob deletes (`delete('user:*')`) automatically
376
+ * scope to the namespace.
377
+ *
378
+ * The process-level singleton, disk cache directory, and cold-start snapshot
379
+ * path are all scoped per namespace, so two `CacheService.create()` calls
380
+ * with different namespaces return completely independent instances.
381
+ *
382
+ * Default: `''` (no prefix)
383
+ */
384
+ namespace?: string;
385
+ /**
386
+ * Seconds to extend a stale SWR entry's life when background revalidation fails.
387
+ * Without this, a failed revalidation leaves the entry stale until its hard TTL
388
+ * expires, after which the next caller blocks. With `staleIfError`, tricache bumps
389
+ * the expiry by this many seconds on every failed revalidation, keeping the stale
390
+ * value available while the underlying service is degraded.
391
+ * Default: `0` (disabled — entry expires normally on revalidation failure).
392
+ */
393
+ staleIfError?: number;
394
+ /**
395
+ * Called after every L1 eviction. Receives the raw (namespaced) key and the reason.
396
+ * Useful for diagnosing cache pressure and tuning `categoryLimits`.
397
+ */
398
+ onEviction?: (key: string, reason: EvictionReason) => void;
399
+ /**
400
+ * Human-readable name for this CacheService instance. Added as an `instance` label
401
+ * to all Prometheus metrics emitted by `CacheService.toPrometheusText()`.
402
+ * Required when multiple CacheService instances share a process — without it,
403
+ * metric names from different instances collide.
404
+ * Default: `''` (no label).
405
+ */
406
+ instanceName?: string;
407
+ /**
408
+ * Controls whether writes are propagated to L2 (Redis).
409
+ * - `'read-write'` (default): read from and write to L2.
410
+ * - `'read-only'`: read from L2 but never write, delete, or expire keys in Redis.
411
+ * Use for shared read replicas or external Redis clusters you do not own.
412
+ */
413
+ l2WriteMode?: 'read-write' | 'read-only';
414
+ /**
415
+ * Enable Redis Pub/Sub invalidation backplane so every running instance
416
+ * evicts a key from its L1 when any peer calls `set()` or `delete()`.
417
+ *
418
+ * Gives you sub-microsecond in-process cache speed with cluster-wide
419
+ * consistency across all your app servers.
420
+ *
421
+ * Default: `true` (auto-activates when Redis is available).
422
+ * Set to `false` for single-process services or eventual-consistency scenarios.
423
+ */
424
+ invalidationBackplane?: boolean;
425
+ /**
426
+ * Enable Redis 7+ Sharded Pub/Sub (`SPUBLISH` / `SSUBSCRIBE`) when connected to
427
+ * a Redis Cluster (`redisClusterNodes`). Scopes pub/sub message routing strictly
428
+ * to the cluster shard handling the key slot, reducing inter-node cluster bus gossip.
429
+ *
430
+ * Default: `false` (standard cluster PUBLISH / SUBSCRIBE).
431
+ */
432
+ useShardedPubSub?: boolean;
433
+ /**
434
+ * Enable the GC-aware OOM guard. When heap utilisation crosses
435
+ * `oomHeapThreshold`, a fraction of the coldest L1 entries are
436
+ * emergency-evicted to L1.5 disk, preventing Node.js OOM crashes inside
437
+ * Docker/Kubernetes containers with tight memory limits.
438
+ *
439
+ * Default: `true`
440
+ */
441
+ oomProtection?: boolean;
442
+ /**
443
+ * Heap-used / heap-total ratio that triggers emergency eviction.
444
+ * Default: `0.85` (85 %)
445
+ */
446
+ oomHeapThreshold?: number;
447
+ /** Milliseconds between heap-pressure checks. Default: 10 000 ms (10 s) */
448
+ oomCheckIntervalMs?: number;
449
+ /** Fraction of L1 entries to evict per OOM round. Default: `0.20` (20 %) */
450
+ oomEvictPercent?: number;
451
+ /**
452
+ * Callback invoked periodically with a `CacheMetrics` snapshot.
453
+ * Wire up to OpenTelemetry, Prometheus push gateway, Datadog, etc.
454
+ *
455
+ * @example
456
+ * onMetrics: (m) => statsd.gauge('cache.l1_hit_rate', m.gets.l1HitRate)
457
+ */
458
+ onMetrics?: (metrics: CacheMetrics) => void;
459
+ /** How often the `onMetrics` callback fires (ms). Default: 60 000 ms */
460
+ metricsIntervalMs?: number;
461
+ /**
462
+ * OpenTelemetry-compatible tracer. When provided, `get()`, `set()`, and
463
+ * `delete()` are each wrapped in a span with attributes:
464
+ * - `cache.hit` — `'l1' | 'disk' | 'l2' | 'miss'`
465
+ * - `cache.key_prefix` — first path segment of the key (e.g. `'user'`)
466
+ *
467
+ * Pass your existing `@opentelemetry/api` Tracer directly — no extra
468
+ * dependency required; the interface is structurally compatible.
469
+ *
470
+ * @example
471
+ * import { trace } from '@opentelemetry/api';
472
+ * tracer: trace.getTracer('tricache')
473
+ */
474
+ tracer?: ICacheTracer;
475
+ /**
476
+ * Randomise every stored TTL by ± `ttlJitterFactor × ttl` seconds.
477
+ * Prevents thundering-herd cache stampedes when thousands of entries share
478
+ * the same TTL and expire simultaneously.
479
+ *
480
+ * A factor of `0.15` spreads a 300 s TTL uniformly over [255 s, 345 s].
481
+ * Default: `0` (disabled — TTLs are stored exactly as given).
482
+ */
483
+ ttlJitterFactor?: number;
484
+ /**
485
+ * Default TTL in seconds for `null` or `undefined` results from `fetchFn`.
486
+ * Caches negative results so a non-existent key (deleted user, bad ID) does not
487
+ * hit the DB on every request. Can be overridden per-call via `get(..., { notFoundTtl }).
488
+ * Default: `0` (disabled — null/undefined uses the normal TTL).
489
+ */
490
+ notFoundTtl?: number;
491
+ /**
492
+ * Number of consecutive Redis errors before the circuit opens (stops
493
+ * attempting Redis until the cooldown elapses).
494
+ * Default: `5`.
495
+ */
496
+ l2CircuitBreakerThreshold?: number;
497
+ /**
498
+ * Milliseconds the circuit stays open before transitioning to half-open
499
+ * (allows a single probe request to test recovery).
500
+ * Default: `30 000` ms (30 s).
501
+ */
502
+ l2CircuitBreakerCooldownMs?: number;
503
+ /**
504
+ * Redis key pattern to automatically warm L1 from at startup (e.g. `'user:*'`).
505
+ * `cache.ready()` returns a Promise that resolves once this warm-up completes.
506
+ * No-op when Redis is disabled or unreachable — safe to set unconditionally.
507
+ */
508
+ warmKeys?: string;
509
+ /**
510
+ * Called on every L1, disk, or L2 cache hit. Receives the caller-facing key (no
511
+ * namespace prefix) and the tier that served it. Useful for per-route hit-rate
512
+ * metrics without waiting for the `onMetrics` interval.
513
+ *
514
+ * @example
515
+ * onHit: (key, tier) => cloudwatch.putMetricData({ key, tier })
516
+ */
517
+ onHit?: (key: string, tier: 'l1' | 'disk' | 'l2') => void;
518
+ /**
519
+ * Called on every cache miss (after L1, disk, and L2 are all exhausted).
520
+ * Receives the caller-facing key (no namespace prefix).
521
+ *
522
+ * @example
523
+ * onMiss: (key) => cloudwatch.putMetricData({ key })
524
+ */
525
+ onMiss?: (key: string) => void;
526
+ /**
527
+ * When `true`, every value returned from an L1 cache hit is recursively
528
+ * frozen with `Object.freeze()` before being handed to the caller.
529
+ * Any attempt to mutate the returned object throws a `TypeError` immediately,
530
+ * catching reference-semantic corruption bugs that would otherwise silently
531
+ * corrupt the cached entry.
532
+ *
533
+ * **Do not enable in production** — use `process.env.NODE_ENV !== 'production'`.
534
+ * Deep-freezing large objects has measurable overhead per hit.
535
+ *
536
+ * @example
537
+ * frozen: process.env.NODE_ENV !== 'production'
538
+ */
539
+ frozen?: boolean;
540
+ /**
541
+ * When `true`, tricache tracks per-key fetch latency in a rolling ring buffer
542
+ * and automatically derives an optimal TTL from the p95 fetch duration:
543
+ *
544
+ * ```
545
+ * adaptedTtl = clamp(p95LatencyMs × adaptiveTtlMultiplier, adaptiveTtlMin, adaptiveTtlMax)
546
+ * ```
547
+ *
548
+ * The caller-supplied `ttlSeconds` is used until at least 5 samples are collected
549
+ * for a key, then the library takes over TTL management autonomously.
550
+ *
551
+ * Expensive keys (slow DB queries) get cached longer; cheap keys stay close to
552
+ * their base TTL. Callers no longer need to reason about individual TTL values.
553
+ *
554
+ * Default: `false`.
555
+ */
556
+ adaptiveTtl?: boolean;
557
+ /**
558
+ * Minimum TTL (seconds) the adaptive tuner will ever assign.
559
+ * Guards against extremely fast fetches producing near-zero TTLs.
560
+ * Default: `10`.
561
+ */
562
+ adaptiveTtlMin?: number;
563
+ /**
564
+ * Maximum TTL (seconds) the adaptive tuner will ever assign.
565
+ * Guards against pathologically slow fetches producing indefinite caching.
566
+ * Default: `86400` (24 hours).
567
+ */
568
+ adaptiveTtlMax?: number;
569
+ /**
570
+ * `p95FetchLatencyMs × adaptiveTtlMultiplier = adaptedTtlSeconds`.
571
+ *
572
+ * Intuition: a 200 ms p95 fetch with the default multiplier of 20 yields a
573
+ * 4-second TTL. A 2 000 ms fetch yields 40 seconds. Increase the multiplier
574
+ * if you want the cache to absorb more upstream pressure.
575
+ *
576
+ * Default: `20`.
577
+ */
578
+ adaptiveTtlMultiplier?: number;
579
+ /**
580
+ * Number of fetch duration samples kept per key in the ring buffer.
581
+ * Larger values smooth out latency spikes but use slightly more memory
582
+ * (~8 bytes × samples per tracked key).
583
+ * Default: `32`.
584
+ */
585
+ adaptiveTtlSamples?: number;
586
+ /**
587
+ * Maximum number of distinct keys tracked by the adaptive TTL system.
588
+ * When the cap is reached, the oldest-tracked key is evicted from the
589
+ * ring-buffer store to make room for the new key.
590
+ * Default: `5000`.
591
+ */
592
+ adaptiveTtlMaxKeys?: number;
593
+ /**
594
+ * When `true`, tricache spawns a pool of worker threads and offloads AES-GCM
595
+ * encryption and decryption for large payloads to those threads, keeping the
596
+ * V8 main event loop free for concurrent HTTP requests.
597
+ *
598
+ * Only takes effect when `encryptionKey` is set — plaintext payloads are never
599
+ * serialized off-thread because `JSON.stringify/parse` is already fast.
600
+ *
601
+ * Default: `false`. Enable in long-running servers that write multi-megabyte
602
+ * encrypted payloads and observe event-loop latency spikes.
603
+ */
604
+ workerThreads?: boolean;
605
+ /**
606
+ * Byte threshold above which an L2 payload is offloaded to a worker thread
607
+ * for encryption / decryption. Payloads smaller than this are processed
608
+ * synchronously (IPC overhead would exceed the savings).
609
+ * Default: `131072` (128 KB).
610
+ */
611
+ workerThresholdBytes?: number;
612
+ /**
613
+ * Number of worker threads in the pool.
614
+ * Default: `Math.min(4, os.availableParallelism())`.
615
+ */
616
+ workerPoolSize?: number;
617
+ /**
618
+ * Maximum milliseconds the Redis Pub/Sub subscriber is allowed to be
619
+ * disconnected before tricache considers its L1 entries potentially stale.
620
+ *
621
+ * When the subscriber reconnects after a gap longer than this value, all L1
622
+ * entries that were written *before* the disconnect started are evicted.
623
+ * This prevents the instance from silently serving data that peers may have
624
+ * invalidated while the backplane connection was down.
625
+ *
626
+ * Set to `0` to disable the fence entirely (accept eventual-consistency drift).
627
+ * Default: `5000` (5 seconds).
628
+ */
629
+ backplaneMaxStalenessMs?: number;
630
+ /**
631
+ * Explicitly disable the L1.5 disk spill tier and cold-start snapshots.
632
+ *
633
+ * Tricache auto-detects common serverless / ephemeral-filesystem runtimes
634
+ * (AWS Lambda, Google Cloud Run, Google Cloud Functions, Azure Functions,
635
+ * Fly.io) and disables the disk tier automatically. Set this to `false` to
636
+ * override that detection and force the disk tier on regardless of runtime.
637
+ *
638
+ * When disabled:
639
+ * - L1 evictions are dropped instead of being spilled to disk.
640
+ * - Cold-start snapshot persistence is skipped.
641
+ * - The `disk` metrics field still appears but shows zeroed counters.
642
+ *
643
+ * Default: `undefined` (auto-detect).
644
+ */
645
+ disableDisk?: boolean;
646
+ /**
647
+ * Redis Cluster node list. When provided, tricache connects using ioredis
648
+ * `Cluster` mode with automatic slot routing and multi-node connection
649
+ * pooling — no external proxy required.
650
+ *
651
+ * Takes precedence over `redisHost`/`redisPort`.
652
+ *
653
+ * @example
654
+ * redisClusterNodes: [
655
+ * { host: 'redis-1.internal', port: 6379 },
656
+ * { host: 'redis-2.internal', port: 6379 },
657
+ * { host: 'redis-3.internal', port: 6379 },
658
+ * ]
659
+ */
660
+ redisClusterNodes?: Array<{
661
+ host: string;
662
+ port: number;
663
+ }>;
664
+ /**
665
+ * Redis Sentinel configuration for high-availability setups.
666
+ * When provided, tricache connects through Sentinel for automatic
667
+ * primary failover — no static `redisHost` / `redisPort` needed.
668
+ *
669
+ * Takes precedence over `redisHost`/`redisPort` (but not over `redisClusterNodes`).
670
+ *
671
+ * @example
672
+ * redisSentinel: {
673
+ * name: 'mymaster',
674
+ * sentinels: [
675
+ * { host: 'sentinel-1.internal', port: 26379 },
676
+ * { host: 'sentinel-2.internal', port: 26379 },
677
+ * ],
678
+ * }
679
+ */
680
+ redisSentinel?: {
681
+ /** Logical name of the monitored master. Must match the Sentinel `monitor` config. */
682
+ name: string;
683
+ sentinels: Array<{
684
+ host: string;
685
+ port: number;
686
+ }>;
687
+ };
688
+ /**
689
+ * When `true`, a second `CacheService.create()` call for an already-existing
690
+ * singleton (same namespace) whose options differ from the first call throws
691
+ * instead of silently returning the existing instance. Use in codebases where
692
+ * multiple init points could pass conflicting configuration (e.g. different
693
+ * Redis credentials or TTLs) and you want that class of bug to fail loudly.
694
+ *
695
+ * Default: `false` (warn once, return existing instance).
696
+ */
697
+ strictSingleton?: boolean;
698
+ /**
699
+ * `cache.increment()` distributed-rate-limit behaviour on a Redis error.
700
+ *
701
+ * Default: `false` (fail-open — on a Redis error the method returns `0`, so a
702
+ * caller's `if (count > LIMIT) reject()` guard never rejects during an outage).
703
+ * Set to `true` to instead re-throw the Redis error, letting the caller's limit
704
+ * guard enforce the limit even when Redis is unavailable.
705
+ */
706
+ failClosed?: boolean;
707
+ /**
708
+ * Strategy used for tag-based cache invalidation:
709
+ * - `'set'` (default): Traditional Redis Set tracking. Members are registered in Redis
710
+ * sets and deleted individually on `invalidateTag()`. Best for low-to-medium cardinality tags.
711
+ * - `'generational'`: Generational tag versioning ($O(1)$ invalidations). Tag invalidation
712
+ * increments an atomic integer version counter in Redis and local memory. Entries store their
713
+ * creation tag versions; stale entries are detected on access and pruned with version-gated
714
+ * compare-and-delete. Eliminates key scans and Redis bulk deletion stalls on large datasets.
715
+ */
716
+ tagStrategy?: 'set' | 'generational';
717
+ /**
718
+ * Milliseconds before an in-memory generational tag version is re-synced from Redis.
719
+ * Bounds maximum partition/missed-broadcast staleness when using `tagStrategy: 'generational'`.
720
+ * Default: `5000` ms (5 seconds).
721
+ */
722
+ tagVersionTtlMs?: number;
723
+ /**
724
+ * Read safety strategy for returned cached objects:
725
+ * - `'none'` (default): Returns raw in-memory references for sub-microsecond performance (~350 ns).
726
+ * - `'structuredClone'`: Clones values via native `structuredClone()` on L1 hits, L2 promotions,
727
+ * and fetch returns, preventing caller mutations from polluting the cached reference.
728
+ * Supported types: plain objects, arrays, Dates, Maps, Sets, TypedArrays. Functions and class
729
+ * prototype chains are not preserved.
730
+ */
731
+ cloneStrategy?: 'none' | 'structuredClone';
732
+ /**
733
+ * Invalidation backplane transport mode:
734
+ * - `'pubsub'` (default): Ephemeral Redis Pub/Sub (at-most-once delivery).
735
+ * - `'stream'`: Durable Redis Streams (XADD/XREAD) with missed-event replay on reconnect.
736
+ */
737
+ backplaneMode?: 'pubsub' | 'stream';
738
+ /**
739
+ * Maximum retained entries in the Redis invalidation stream (`MAXLEN ~ N`).
740
+ * Default: `10000`.
741
+ */
742
+ backplaneStreamMaxLen?: number;
743
+ /**
744
+ * Blocking poll timeout in milliseconds for `XREAD BLOCK`.
745
+ * Default: `2000` ms (2 seconds).
746
+ */
747
+ backplaneStreamBlockMs?: number;
748
+ /**
749
+ * Custom Redis Stream key name.
750
+ * Default: `tricache:stream:{<namespace>}` (hash-tagged for Redis Cluster single-slot routing).
751
+ */
752
+ backplaneStreamKey?: string;
753
+ /**
754
+ * OpenTelemetry Meter instance for native metrics publishing.
755
+ * Compatible with `@opentelemetry/api` Meter.
756
+ */
757
+ meter?: ICacheMeter;
758
+ }
759
+ /**
760
+ * Options for the ergonomic `cache.wrap(key, fetchFn, options)` method.
761
+ */
762
+ interface WrapOptions {
763
+ /** TTL in seconds (default: 300 s). */
764
+ ttl?: number;
765
+ /** Stale-While-Revalidate grace period in seconds. */
766
+ swr?: number;
767
+ /** Override the auto-inferred eviction priority. */
768
+ priority?: CachePriority;
769
+ /** Semantic tags for invalidation. */
770
+ tags?: string[];
771
+ /** Dependency cascade patterns (e.g. `['user:*']`). */
772
+ dependsOn?: string[];
773
+ /** 0–1 fraction of TTL elapsed at which a proactive background refresh is scheduled. */
774
+ refreshAhead?: number;
775
+ /** XFetch probabilistic early expiration factor (0.5–2.0). */
776
+ xfetchBeta?: number;
777
+ /** Override TTL in seconds for null/undefined fetch results (negative caching). */
778
+ notFoundTtl?: number;
779
+ }
780
+ /**
781
+ * Options for distributed and in-process mutual exclusion locks via `cache.lock()`.
782
+ */
783
+ interface LockOptions {
784
+ /**
785
+ * Lock auto-release TTL in seconds (default: 30 s).
786
+ * Prevents deadlocks if the holding node crashes or is terminated.
787
+ */
788
+ ttl?: number;
789
+ /**
790
+ * Maximum time to wait to acquire the lock in milliseconds before throwing a timeout error.
791
+ * Default: `5000` ms.
792
+ */
793
+ acquireTimeout?: number;
794
+ /**
795
+ * Polling retry interval in milliseconds when waiting for lock acquisition.
796
+ * Default: `100` ms.
797
+ */
798
+ retryInterval?: number;
799
+ }
800
+ /**
801
+ * Structural typing matching OpenTelemetry Metric interfaces (`@opentelemetry/api`).
802
+ */
803
+ interface ICacheCounter {
804
+ add(value: number, attributes?: Record<string, string | number | boolean>): void;
805
+ }
806
+ interface ICacheObservableGauge {
807
+ readonly _isGauge?: true;
808
+ }
809
+ interface ICacheBatchObservableCallback {
810
+ (observableResult: {
811
+ observe: (metric: ICacheObservableGauge, value: number, attributes?: Record<string, string | number | boolean>) => void;
812
+ }): void | Promise<void>;
813
+ }
814
+ interface ICacheMeter {
815
+ createCounter(name: string, options?: {
816
+ description?: string;
817
+ unit?: string;
818
+ }): ICacheCounter;
819
+ createObservableGauge(name: string, options?: {
820
+ description?: string;
821
+ unit?: string;
822
+ }): ICacheObservableGauge;
823
+ addBatchObservableCallback(callback: ICacheBatchObservableCallback, observables: ICacheObservableGauge[]): void;
824
+ }
825
+
826
+ /**
827
+ * Encryption / obfuscation for L2 (Redis) values and disk snapshots at rest.
828
+ *
829
+ * Four modes are supported via the `encryptionMode` CacheOption:
830
+ *
831
+ * ┌──────────────┬────────────┬──────────────────────────────────────────────────────────────┐
832
+ * │ Mode │ Key bytes │ Notes │
833
+ * ├──────────────┼────────────┼──────────────────────────────────────────────────────────────┤
834
+ * │ aes-256-gcm │ 32 │ Default. Authenticated encryption (AEAD). │
835
+ * │ aes-128-gcm │ 16 │ ~15% faster than AES-256. AEAD. │
836
+ * │ aes-128-ctr │ 16 │ Fastest cipher. AES-NI keystream, no auth tag. │
837
+ * │ │ │ Use when integrity is guaranteed elsewhere (TLS, HMAC, etc.). │
838
+ * │ xor │ any (≥ 1) │ XOR obfuscation ONLY — NOT cryptographic. │
839
+ * │ │ │ Use only for dev or non-sensitive data. │
840
+ * └──────────────┴────────────┴──────────────────────────────────────────────────────────────┘
841
+ *
842
+ * Key generation:
843
+ * AES-256 (32 B): node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
844
+ * AES-128 (16 B): node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
845
+ * CTR (16 B): node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
846
+ * XOR (any len): node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
847
+ *
848
+ * Redis envelope formats:
849
+ * enc:v1:<base64(IV[12]|Tag[16]|CT)> ← AES-256-GCM
850
+ * a128:v1:<base64(IV[12]|Tag[16]|CT)> ← AES-128-GCM
851
+ * ctr:v1:<base64(IV[16]|CT)> ← AES-128-CTR (no auth tag)
852
+ * xor:v1:<base64(key⊕data)> ← XOR (self-inverse)
853
+ *
854
+ * Disk envelope formats:
855
+ * TRIC1ENC | IV[12] | Tag[16] | CT[N] ← AES-256-GCM
856
+ * TRIC1128 | IV[12] | Tag[16] | CT[N] ← AES-128-GCM
857
+ * TRIC1CTR | IV[16] | CT[N] ← AES-128-CTR (no auth tag)
858
+ * TRIC1XOR | key⊕data[N] ← XOR
859
+ */
860
+
861
+ /** Encryption algorithm used for L2 (Redis) values and disk-tier files. */
862
+ type EncryptionMode = 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
863
+ declare class CacheEncryption {
864
+ private _key;
865
+ private _keyObj;
866
+ private _mode;
867
+ private _prevKey;
868
+ private _prevKeyObj;
869
+ private _prevMode;
870
+ private readonly _ivPool;
871
+ private _ivOffset;
872
+ /** Return the next unique 12-byte IV slice from the pre-allocated GCM pool. */
873
+ private _nextIV;
874
+ private readonly _ctrIvPool;
875
+ private _ctrIvOffset;
876
+ /** Return the next unique 16-byte IV slice from the pre-allocated CTR pool. */
877
+ private _nextCtrIV;
878
+ /**
879
+ * XOR `data` with the key, cycling through key bytes.
880
+ * Self-inverse: _xorBuffer(_xorBuffer(x)) === x.
881
+ *
882
+ * Fast path: Uint32Array views over the existing Buffer memory — zero copy,
883
+ * no method-call overhead. V8 JITs `out32[i] = data32[i] ^ key32[...]`
884
+ * to a single `XOR r32, r32` instruction. Requires 4-byte-aligned byteOffsets,
885
+ * which Node.js guarantees (pool rounds up to 8 bytes; direct allocs to page).
886
+ *
887
+ * WARNING: XOR is NOT cryptographic. It provides obfuscation only.
888
+ */
889
+ private _xorBuffer;
890
+ constructor(keyBase64: string | undefined, loggerOrMode?: ILogger | EncryptionMode, mode?: EncryptionMode, previousKeyBase64?: string, previousMode?: EncryptionMode);
891
+ get isEnabled(): boolean;
892
+ get mode(): EncryptionMode;
893
+ /**
894
+ * Snapshot the key material needed to spin up an off-main-thread worker pool.
895
+ * Replaces the previously-used `as unknown as { _key, _mode, … }` private-field
896
+ * cast in cache-service.ts — the worker pool reads these via this accessor
897
+ * instead of reaching into underscore-prefixed internals.
898
+ */
899
+ toWorkerInit(): {
900
+ keyBase64: string;
901
+ mode: EncryptionMode;
902
+ prevKeyBase64: string | undefined;
903
+ prevMode: EncryptionMode;
904
+ };
905
+ /**
906
+ * Rotate the active encryption key dynamically at runtime.
907
+ * Promotes the current primary key to previousEncryptionKey for zero-downtime
908
+ * fallback decryption of existing cache entries in L2/Disk, and installs
909
+ * the new key as primary for all subsequent writes.
910
+ */
911
+ rotateKey(newKeyBase64: string, newMode?: EncryptionMode): void;
912
+ /**
913
+ * Encrypt a string for Redis storage.
914
+ * Returns a mode-prefixed base64 string when a key is configured;
915
+ * otherwise returns the original string unchanged (backward-compatible).
916
+ */
917
+ encrypt(plaintext: string): string;
918
+ /**
919
+ * Decrypt a Redis value.
920
+ * Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
921
+ * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
922
+ */
923
+ decrypt(value: string): string;
924
+ private _decryptWithKey;
925
+ /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
926
+ encryptBuffer(data: Buffer): Buffer;
927
+ /**
928
+ * Decrypt a raw Buffer from disk/snapshot.
929
+ * Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
930
+ * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
931
+ */
932
+ decryptBuffer(data: Buffer): Buffer;
933
+ private _decryptBufferWithKey;
934
+ }
935
+
936
+ /**
937
+ * CacheService — three-tier cache with stampede prevention and SWR.
938
+ *
939
+ * Architecture:
940
+ * L1 → SmartMemoryCache (in-process RAM, always active, adaptive eviction)
941
+ * L1.5→ DiskTier (NVMe overflow, evicted L1 entries, 2–100 µs)
942
+ * L2 → Redis / Valkey (distributed, production-only by default, survives restarts)
943
+ * DB → your fetchFunction (cache miss path)
944
+ *
945
+ * Key features:
946
+ * - Thundering-herd / cache-stampede prevention (inflight Promise registry)
947
+ * - Stale-While-Revalidate (serve stale instantly + revalidate in background)
948
+ * - AES-256-GCM encryption for L2 and disk data at rest
949
+ * - Cold-start snapshot: L1 is persisted to disk on SIGTERM and restored on startup
950
+ * - Process-level singleton (globalThis) survives hot reloads in frameworks like Next.js
951
+ * - Periodic cleanup of expired entries every 5 minutes
952
+ */
953
+
954
+ declare class CacheService {
955
+ private readonly logger;
956
+ private readonly enc;
957
+ private readonly l1;
958
+ private readonly disk;
959
+ /** When true, all disk-tier and snapshot operations are skipped. */
960
+ private _diskDisabled;
961
+ /** Worker pool for off-main-thread AES-GCM (null when workerThreads is false or unavailable). */
962
+ private _workerPool;
963
+ private readonly opts;
964
+ /** Pre-computed once — opts.namespace never changes after construction. */
965
+ private readonly _namespace;
966
+ /** Pre-computed once — disableRedis and redisHost never change after construction. */
967
+ private readonly _redisDisabled;
968
+ private readonly inflight;
969
+ private readonly revalidating;
970
+ private readonly _l1Counters;
971
+ /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
972
+ private readonly tagIndex;
973
+ /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
974
+ private readonly tagVersions;
975
+ /**
976
+ * Dependency index: source glob pattern → Set of namespaced dependent keys.
977
+ * When an exact-key delete matches a registered pattern, all dependents are cascaded.
978
+ */
979
+ private readonly dependencyIndex;
980
+ private redis;
981
+ private redisConnecting;
982
+ private readonly cb;
983
+ /** In-process mutex lock map for single-process environments or Redis outages. */
984
+ private _localLocks;
985
+ /** Active OpenTelemetry monotonic counters. */
986
+ private _otelMetrics;
987
+ private snapshotLoaded;
988
+ private _readyPromise;
989
+ private cleanupInterval;
990
+ private diskJanitorInterval;
991
+ private oomInterval;
992
+ private metricsInterval;
993
+ private _shutdownHandler;
994
+ private latencyTracker;
995
+ private readonly instanceId;
996
+ private readonly backplaneChannel;
997
+ private readonly backplaneStreamKey;
998
+ private subClient;
999
+ private streamClient;
1000
+ private _lastStreamId;
1001
+ private _destroyed;
1002
+ /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
1003
+ private _subDisconnectedAt;
1004
+ private counters;
1005
+ /** One-time guard so the in-process increment() fallback warning fires only once. */
1006
+ private _incrementFallbackWarned;
1007
+ constructor(options?: CacheOptions);
1008
+ /**
1009
+ * Get (or create) the process-level singleton CacheService instance.
1010
+ *
1011
+ * Options are only applied on first call — subsequent calls return the
1012
+ * existing instance regardless of options passed. When the new options differ
1013
+ * from what the existing singleton was built with, this is a silent no-op by
1014
+ * default; set `strictSingleton: true` to throw instead, or watch the
1015
+ * `singletonDivergences` metric for detection.
1016
+ *
1017
+ * When `namespace` is set the singleton is keyed by namespace, so two calls
1018
+ * with different namespaces return independent instances.
1019
+ */
1020
+ static create(options?: CacheOptions): CacheService;
1021
+ /**
1022
+ * Keys that, if set differently on a later `create()` call, represent a
1023
+ * meaningful configuration divergence worth flagging (security/correctness
1024
+ * relevant — not cosmetic, e.g. log level).
1025
+ */
1026
+ private static readonly DIVERGENT_KEYS;
1027
+ /** Returns the names of options that differ between `a` and the live `b`. */
1028
+ private static optionsDiff;
1029
+ /** Increment the singleton-divergence counter (surfaced in `metrics()`). */
1030
+ bumpSingletonDivergence(): void;
1031
+ /** Read-only view of the options the singleton was constructed with. */
1032
+ get options(): CacheOptions;
1033
+ /**
1034
+ * Async factory — accepts a Promise that resolves to CacheOptions.
1035
+ * Useful when config is fetched from a secret store at startup.
1036
+ *
1037
+ * @example
1038
+ * const cache = await CacheService.createAsync(fetchSecrets());
1039
+ */
1040
+ static createAsync(options: Promise<CacheOptions> | CacheOptions): Promise<CacheService>;
1041
+ /** Replace the singleton (useful in tests). */
1042
+ static reset(options?: CacheOptions): CacheService;
1043
+ /** Derive the globalThis key for a given set of options. */
1044
+ private static globalKey;
1045
+ /**
1046
+ * Prepend the configured namespace to a raw cache key.
1047
+ * Returns the key unchanged when namespace is empty.
1048
+ *
1049
+ * This is the only place the namespace prefix is applied — callers always
1050
+ * receive and provide un-prefixed keys in the public API.
1051
+ */
1052
+ private nk;
1053
+ /** Strip the instance namespace prefix from a namespaced key (inverse of `nk`). */
1054
+ private unnk;
1055
+ /** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
1056
+ private _jitterTtl;
1057
+ /** Shared no-op span for the common case where no tracer is configured.
1058
+ * Using a singleton avoids allocating a fresh object literal on every get/set/delete call. */
1059
+ private static readonly _nullSpan;
1060
+ /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
1061
+ private _startSpan;
1062
+ private createDedicatedRedisClient;
1063
+ private initBackplane;
1064
+ private _startStreamConsumer;
1065
+ private _applyInvalidationEvent;
1066
+ /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
1067
+ _handleBackplaneMessage(message: string): void;
1068
+ private publishInvalidation;
1069
+ private _setLocalTagVersion;
1070
+ private _getTagVersion;
1071
+ private _deleteIfStale;
1072
+ /**
1073
+ * Serialize payload for L2 Redis storage applying compression and encryption as configured.
1074
+ * Offloads to worker thread if pool is active and payload exceeds threshold.
1075
+ */
1076
+ private _serializeAndEncrypt;
1077
+ /**
1078
+ * Deserialize raw L2 Redis entry applying decryption and decompression as needed.
1079
+ * Offloads to worker thread if pool is active and payload exceeds threshold.
1080
+ */
1081
+ private _decryptAndDeserialize;
1082
+ /**
1083
+ * Scan all keys matching `pattern` across single-node or Cluster clients.
1084
+ * For Cluster, iterates every master node independently (SCAN is node-local).
1085
+ */
1086
+ private _scanKeys;
1087
+ private _checkAndLogResp3Hint;
1088
+ private getRedis;
1089
+ writeSnapshot(altPath?: string): void;
1090
+ loadSnapshot(): void;
1091
+ /**
1092
+ * Get a value from cache, or fetch and cache it.
1093
+ *
1094
+ * @param cacheKey - Unique key identifying this value
1095
+ * @param fetchFn - Called on a cache miss; its return value is cached and returned
1096
+ * @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
1097
+ * @param opts.priority - Override the auto-inferred eviction priority
1098
+ * @param opts.swr - Stale-While-Revalidate grace seconds.
1099
+ * @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
1100
+ * is triggered proactively while the caller still receives the
1101
+ * cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
1102
+ * Requires `fetchFn` to be stable across calls.
1103
+ * @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
1104
+ * recompute more aggressively before expiry. Typical range: 0.5–2.
1105
+ * Complementary to refreshAhead — uses recompute cost (delta) to
1106
+ * decide probabilistically rather than at a fixed threshold.
1107
+ * @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
1108
+ * Caches negative lookups to avoid repeated DB hits for missing keys.
1109
+ */
1110
+ get<T>(cacheKey: string, fetchFn: () => Promise<T>, ttlSeconds?: number, opts?: {
1111
+ priority?: CachePriority;
1112
+ swr?: number;
1113
+ refreshAhead?: number;
1114
+ xfetchBeta?: number;
1115
+ notFoundTtl?: number;
1116
+ /**
1117
+ * Tags to associate with this cache entry when fetchFn populates it on a miss.
1118
+ * Tags are registered in the in-process `tagIndex` and (if Redis is enabled) mirrored
1119
+ * via `SADD` so that `invalidateTag()` covers disk-spill and multi-instance nodes.
1120
+ * On an L1/L2 hit the tags are already registered — this field is a no-op for hits.
1121
+ */
1122
+ tags?: string[];
1123
+ }): Promise<T>;
1124
+ /**
1125
+ * Universal fetch-and-cache wrapper with an ergonomic options object.
1126
+ *
1127
+ * Drop-in ergonomic alternative to `get()` matching developer expectations
1128
+ * from `cache-manager` and `keyv`.
1129
+ *
1130
+ * @param cacheKey - Unique cache key.
1131
+ * @param fetchFn - Executed on a cache miss to retrieve fresh data.
1132
+ * @param options - Optional configuration object (TTL, SWR, tags, priority, etc.).
1133
+ *
1134
+ * @example
1135
+ * const user = await cache.wrap(`user:${id}`, () => db.user.findUnique({ where: { id } }), {
1136
+ * ttl: 300,
1137
+ * swr: 60,
1138
+ * tags: ['users'],
1139
+ * });
1140
+ */
1141
+ wrap<T>(cacheKey: string, fetchFn: () => Promise<T>, options?: WrapOptions): Promise<T>;
1142
+ private _revalidate;
1143
+ /** Explicitly write a value into L1 (+ L2 in production). */
1144
+ set<T>(cacheKey: string, data: T, ttlSeconds?: number, priority?: CachePriority, opts?: {
1145
+ tags?: string[];
1146
+ dependsOn?: string[];
1147
+ }): Promise<void>;
1148
+ /**
1149
+ * Register tags for a cache key in the in-process index and (if Redis is enabled) in
1150
+ * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
1151
+ */
1152
+ private _registerTags;
1153
+ /**
1154
+ * Delete one key or a glob pattern (supports `*` wildcard).
1155
+ *
1156
+ * @example
1157
+ * await cache.delete('user:abc:profile'); // exact key
1158
+ * await cache.delete('user:abc:*'); // all keys for user abc
1159
+ */
1160
+ delete(cacheKey: string): Promise<void>;
1161
+ /**
1162
+ * Distributed counter.
1163
+ *
1164
+ * When Redis is active, atomically increments the key via `INCR` and returns
1165
+ * the new (fleet-wide) value. On a Redis error it increments `counters.errors`
1166
+ * and, by default, fails OPEN — returning `0` so a caller's
1167
+ * `if (count > LIMIT) reject()` guard does NOT reject during an outage. Set
1168
+ * `failClosed: true` to re-throw the error instead, enforcing the limit even
1169
+ * when Redis is unavailable.
1170
+ *
1171
+ * When Redis is disabled (or `disableRedis: true`), this maintains an
1172
+ * IN-PROCESS counter with the same TTL semantics so dev/test rate-limiting
1173
+ * works locally. The returned value is the local count (1, 2, 3, …), NOT 0 —
1174
+ * a one-time warning is logged because rate-limiting is then per-instance, not
1175
+ * fleet-wide.
1176
+ */
1177
+ increment(cacheKey: string, ttlSeconds?: number): Promise<number>;
1178
+ /**
1179
+ * Flush all cached entries, or only those whose key starts with `prefix`.
1180
+ *
1181
+ * @example
1182
+ * await cache.clear(); // flush everything
1183
+ * await cache.clear('user:abc'); // flush all keys for one user
1184
+ */
1185
+ clear(prefix?: string): Promise<void>;
1186
+ /**
1187
+ * Evict L1 entries that violate the current category or global capacity limits.
1188
+ * Useful after a write burst or after adding stricter `categoryLimits`.
1189
+ * Returns the number of entries evicted.
1190
+ */
1191
+ rebalance(): number;
1192
+ /**
1193
+ * Return the remaining TTL in seconds for a key currently in L1.
1194
+ * Returns null if the key is absent from L1 or has already expired.
1195
+ * Only reflects L1 state — does not query Redis or disk.
1196
+ */
1197
+ ttl(cacheKey: string): number | null;
1198
+ /**
1199
+ * Return true if the key exists in L1 and has not expired.
1200
+ * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
1201
+ */
1202
+ has(cacheKey: string): boolean;
1203
+ /**
1204
+ * Lazily yield every non-expired L1 key, stripped of its namespace prefix.
1205
+ *
1206
+ * @example
1207
+ * for (const key of cache.keys()) console.log(key);
1208
+ */
1209
+ keys(): Generator<string>;
1210
+ /**
1211
+ * Lazily yield every non-expired L1 value.
1212
+ * Each value is the cached (pre-deserialized) JS object — no unpack overhead.
1213
+ *
1214
+ * @example
1215
+ * for (const val of cache.values<User>()) console.log(val.id);
1216
+ */
1217
+ values<T = unknown>(): Generator<T>;
1218
+ /**
1219
+ * Lazily yield every non-expired L1 [key, value] pair.
1220
+ * Keys are stripped of their namespace prefix.
1221
+ *
1222
+ * @example
1223
+ * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
1224
+ */
1225
+ entries<T = unknown>(): Generator<[string, T]>;
1226
+ /**
1227
+ * High-throughput bulk scan over all live L1 entries.
1228
+ *
1229
+ * Compared with `entries()` this avoids generator frame overhead, per-entry
1230
+ * `[key, value]` tuple allocation, and the `key.slice()` allocation when the
1231
+ * caller uses the `offset` parameter instead of pre-slicing.
1232
+ *
1233
+ * ```typescript
1234
+ * // Zero extra string allocations — use rawKey + offset directly:
1235
+ * cache.scan((rawKey, value, offset) => {
1236
+ * const key = rawKey.slice(offset); // allocate only if needed
1237
+ * sync(key, value as User);
1238
+ * });
1239
+ * ```
1240
+ *
1241
+ * @param fn Called once per live L1 entry.
1242
+ * `rawKey` — key with namespace prefix still attached.
1243
+ * `value` — deserialized cached value.
1244
+ * `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
1245
+ */
1246
+ scan<T = unknown>(fn: (rawKey: string, value: T, offset: number) => void): void;
1247
+ /**
1248
+ * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
1249
+ * Returns `false` if the key is absent or already expired.
1250
+ *
1251
+ * @param newTtlSeconds - The new TTL from now, in seconds.
1252
+ */
1253
+ touch(cacheKey: string, newTtlSeconds: number): Promise<boolean>;
1254
+ /**
1255
+ * Return the cached value from L1 **only if it is fresh** (not in the SWR grace window).
1256
+ * Returns `null` when the key is absent, expired, or stale — without triggering a fetch.
1257
+ *
1258
+ * @example
1259
+ * const fresh = cache.getIfFresh('user:123');
1260
+ * if (fresh !== null) return fresh; // serve from L1, no network hop
1261
+ */
1262
+ getIfFresh<T = unknown>(cacheKey: string): T | null;
1263
+ /**
1264
+ * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
1265
+ * Returns the cached value if found and valid, or `null` if absent / expired.
1266
+ * Does not write dummy entries on misses or trigger side-effects.
1267
+ *
1268
+ * @example
1269
+ * const val = await cache.peek<User>('user:123');
1270
+ */
1271
+ peek<T = unknown>(cacheKey: string): Promise<T | null>;
1272
+ /**
1273
+ * Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
1274
+ * Preserves input ordering. Uses inflight coalescing per key.
1275
+ *
1276
+ * @param keys - Array of cache keys.
1277
+ * @param fetchFn - Called with only the keys that missed L1.
1278
+ * @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
1279
+ * `(key) => number` so heterogeneous TTLs can be batched in one call.
1280
+ */
1281
+ mget<T>(keys: string[], fetchFn: (missKeys: string[]) => Promise<Record<string, T>>, ttl?: number | ((key: string) => number), priority?: CachePriority): Promise<(T | undefined)[]>;
1282
+ /**
1283
+ * Returns a Promise that resolves once the cache is fully initialised and any
1284
+ * startup warming configured via `warmKeys` has completed.
1285
+ *
1286
+ * Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once
1287
+ * `warmFromL2(warmKeys)` finishes — ideal for k8s readiness probes.
1288
+ *
1289
+ * @example
1290
+ * const cache = CacheService.create({ warmKeys: 'user:*' });
1291
+ * await cache.ready(); // gate traffic until warm
1292
+ */
1293
+ ready(): Promise<void>;
1294
+ /**
1295
+ * Batch write — set multiple entries in a single call.
1296
+ * TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
1297
+ *
1298
+ * @example
1299
+ * await cache.mset({
1300
+ * 'user:1': { value: { name: 'Alice' }, ttl: 300 },
1301
+ * 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
1302
+ * });
1303
+ */
1304
+ mset<T = unknown>(entries: Record<string, {
1305
+ value: T;
1306
+ ttl?: number;
1307
+ priority?: CachePriority;
1308
+ tags?: string[];
1309
+ dependsOn?: string[];
1310
+ }>): Promise<void>;
1311
+ /**
1312
+ * Batch delete — delete multiple exact keys in a single call.
1313
+ * Glob patterns are not supported; use `delete('prefix:*')` for patterns.
1314
+ *
1315
+ * @example
1316
+ * await cache.mdel(['user:1', 'user:2', 'user:3']);
1317
+ */
1318
+ mdel(keys: string[]): Promise<void>;
1319
+ /**
1320
+ * Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
1321
+ * pulling them into L1. Useful on startup to eliminate cold-start penalty when
1322
+ * the local snapshot is unavailable or too stale.
1323
+ *
1324
+ * Returns the number of keys loaded into L1.
1325
+ *
1326
+ * @example
1327
+ * // In your startup hook (e.g. ECS task, k8s readiness probe):
1328
+ * const loaded = await cache.warmFromL2('org:*');
1329
+ * console.log(`Warmed ${loaded} keys from Redis`);
1330
+ */
1331
+ warmFromL2(pattern: string, opts?: {
1332
+ priority?: CachePriority;
1333
+ }): Promise<number>;
1334
+ /**
1335
+ * Invalidate all keys associated with a tag.
1336
+ * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
1337
+ *
1338
+ * @example
1339
+ * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
1340
+ * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
1341
+ */
1342
+ invalidateTag(tag: string): Promise<void>;
1343
+ /**
1344
+ * Invalidate all keys associated with any of the given tags in a single operation.
1345
+ * Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
1346
+ * reducing latency when invalidating several related tags together.
1347
+ *
1348
+ * Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
1349
+ * synchronously before the Redis round-trip.
1350
+ *
1351
+ * @example
1352
+ * // Instead of three serial round-trips:
1353
+ * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
1354
+ */
1355
+ invalidateTags(tags: string[]): Promise<void>;
1356
+ /**
1357
+ * Get the current generational tag version for a tag (synced with Redis when due).
1358
+ */
1359
+ getTagVersion(tag: string): Promise<number>;
1360
+ /**
1361
+ * Measure L1 / disk / Redis latency.
1362
+ * Useful for health checks and dashboards.
1363
+ *
1364
+ * @returns `{ l1, disk, l2 }` latencies in milliseconds.
1365
+ * `l2` is `null` when Redis is disabled.
1366
+ */
1367
+ ping(): Promise<CachePingResult>;
1368
+ /**
1369
+ * Export all live L1 entries to Redis via a single pipeline.
1370
+ * Useful for warming a new Redis instance or for zero-downtime failover.
1371
+ * Returns the number of keys written.
1372
+ */
1373
+ drainToL2(): Promise<number>;
1374
+ stats(): {
1375
+ l1: {
1376
+ entries: number;
1377
+ sizeBytes: number;
1378
+ sizeKB: number;
1379
+ categories: Record<string, {
1380
+ entries: number;
1381
+ hits: number;
1382
+ }>;
1383
+ bloom: {
1384
+ checks: number;
1385
+ falsePositives: number;
1386
+ };
1387
+ compression: {
1388
+ compressed: number;
1389
+ uncompressed: number;
1390
+ bytesSaved: number;
1391
+ };
1392
+ };
1393
+ disk: {
1394
+ files: number;
1395
+ sizeKB: number;
1396
+ maxKB: number;
1397
+ };
1398
+ };
1399
+ /**
1400
+ * Write `value` only if the key is not already cached.
1401
+ * Returns `true` if the write happened, `false` if the key already existed.
1402
+ *
1403
+ * When Redis is available, atomicity is guaranteed via `SET NX EX` so this
1404
+ * is safe to use for idempotency keys and "first writer wins" patterns across
1405
+ * multiple instances. L1 is populated on success.
1406
+ *
1407
+ * @example
1408
+ * const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
1409
+ * if (!claimed) return res.status(409).json({ error: 'duplicate request' });
1410
+ */
1411
+ setIfAbsent<T>(cacheKey: string, value: T, ttlSeconds?: number, priority?: CachePriority): Promise<boolean>;
1412
+ /**
1413
+ * Acquire a distributed (or in-process) mutual exclusion lock on `resourceKey`,
1414
+ * execute `fn`, and automatically release the lock on completion or error.
1415
+ *
1416
+ * When Redis is connected, uses `SET lock:<key> <token> NX EX <ttl>` with
1417
+ * safe Lua token release (`if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end`).
1418
+ * When Redis is disabled, uses an in-process promise-chain mutex to ensure thread-safety.
1419
+ *
1420
+ * @param resourceKey Unique lock name / resource identifier (e.g. `'cron:nightly-sync'`).
1421
+ * @param fn Task to run exclusively while holding the lock.
1422
+ * @param options TTL, acquire timeout, and retry polling intervals.
1423
+ */
1424
+ lock<T>(resourceKey: string, fn: () => Promise<T>, options?: LockOptions): Promise<T>;
1425
+ private _initOtelMetrics;
1426
+ /**
1427
+ * Return the top-N live L1 keys by historical access frequency.
1428
+ * Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
1429
+ * whose historical frequency exceeds their current in-memory hit count.
1430
+ *
1431
+ * Useful for diagnosing what is driving L1 pressure without any extra data
1432
+ * collection overhead.
1433
+ *
1434
+ * @param n - Maximum number of keys to return. Default: 10.
1435
+ *
1436
+ * @example
1437
+ * cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
1438
+ * console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
1439
+ */
1440
+ hotKeys(n?: number): Array<{
1441
+ key: string;
1442
+ hits: number;
1443
+ sizeBytes: number;
1444
+ }>;
1445
+ /**
1446
+ * Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
1447
+ * pattern that may contain `*` wildcards).
1448
+ */
1449
+ private _matchesGlob;
1450
+ /**
1451
+ * When an exact key `deletedKey` is removed, cascade to every dependent key
1452
+ * that was registered via `dependsOn` and whose source pattern matches.
1453
+ * Transitive dependencies are traversed with cycle protection via a visited Set.
1454
+ */
1455
+ private _cascadeDependencies;
1456
+ /** Return a full metrics snapshot. */
1457
+ metrics(): CacheMetrics;
1458
+ /**
1459
+ * Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
1460
+ * Paste the result into your `/metrics` endpoint.
1461
+ *
1462
+ * @param m - Snapshot returned by `cache.metrics()`
1463
+ * @param prefix - Metric name prefix. Default: `"tricache"`
1464
+ */
1465
+ static toPrometheusText(m: CacheMetrics, prefix?: string, instanceName?: string): string;
1466
+ /**
1467
+ * Dynamically rotate the active encryption key at runtime without restarting.
1468
+ * Installs the new key as primary for all subsequent writes, while preserving
1469
+ * the previous key for seamless fallback decryption of existing cache entries.
1470
+ */
1471
+ rotateEncryptionKey(newKeyBase64: string, newMode?: EncryptionMode): Promise<void>;
1472
+ /** Close Redis connections and stop all background timers. */
1473
+ destroy(): Promise<void>;
1474
+ }
1475
+
1476
+ export { CacheService as C, type DiskCacheEntry as D, type EvictionReason as E, type ILogger as I, type LockOptions as L, type SmartCacheEntry as S, type WrapOptions as W, type CategoryLimit as a, type CacheHit as b, CachePriority as c, CacheEncryption as d, type CacheMetrics as e, type CacheOptions as f, type CachePingResult as g, type EncryptionMode as h, type ICacheBatchObservableCallback as i, type ICacheCounter as j, type ICacheMeter as k, type ICacheObservableGauge as l, type ICacheSpan as m, type ICacheTracer as n, consoleLogger as o };