tricache 0.7.0 → 0.8.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 (100) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +144 -1428
  3. package/bin/tricache.js +8 -8
  4. package/dashboards/tricache-alerts.yaml +54 -0
  5. package/dashboards/tricache-grafana.json +548 -0
  6. package/dist/cache-service-5MZXFIGK.js +12 -0
  7. package/dist/cache-service-CyLdpo77.d.ts +871 -0
  8. package/dist/{chunk-3XQUQBOZ.js → chunk-6PQ5MOWR.js} +2950 -523
  9. package/dist/chunk-7RV5ZVBB.js +1023 -0
  10. package/dist/{chunk-PFB5FMEY.js → chunk-LJ5QJB5O.js} +116 -20
  11. package/dist/chunk-QNU7B43J.js +687 -0
  12. package/dist/chunk-UGD4VEPD.js +138 -0
  13. package/dist/chunk-XZL45ABR.js +108 -0
  14. package/dist/chunk-ZTSWCFYO.js +135 -0
  15. package/dist/cli.cjs +2894 -518
  16. package/dist/cli.d.ts +1 -0
  17. package/dist/cli.js +103 -5
  18. package/dist/dashboard/index.cjs +1065 -0
  19. package/dist/dashboard/index.d.ts +183 -0
  20. package/dist/dashboard/index.js +22 -0
  21. package/dist/drizzle/index.cjs +2648 -508
  22. package/dist/drizzle/index.d.ts +3 -1
  23. package/dist/drizzle/index.js +1 -1
  24. package/dist/edge/index.cjs +1498 -0
  25. package/dist/edge/index.d.ts +127 -0
  26. package/dist/edge/index.js +1109 -0
  27. package/dist/hono-DQRS1Xd7.d.ts +370 -0
  28. package/dist/http/index.cjs +3038 -589
  29. package/dist/http/index.d.ts +109 -23
  30. package/dist/http/index.js +238 -62
  31. package/dist/index.cjs +6962 -2487
  32. package/dist/index.d.ts +547 -30
  33. package/dist/index.js +104 -5
  34. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  35. package/dist/nestjs/index.cjs +2586 -498
  36. package/dist/nestjs/index.d.ts +3 -1
  37. package/dist/nestjs/index.js +6 -3
  38. package/dist/next/index.cjs +2633 -519
  39. package/dist/next/index.d.ts +13 -7
  40. package/dist/next/index.js +45 -18
  41. package/dist/prisma/index.cjs +2 -1
  42. package/dist/prisma/index.d.ts +3 -1
  43. package/dist/prisma/index.js +2 -1
  44. package/dist/serialize-worker.cjs +31 -19
  45. package/dist/serialize-worker.js +1 -1
  46. package/dist/{cache-service-BblHuF3i.d.ts → types-B6krw64X.d.ts} +605 -646
  47. package/package.json +37 -7
  48. package/src/adapters/auto-pipeliner.ts +206 -0
  49. package/src/adapters/node-redis.ts +370 -0
  50. package/src/cache-service.ts +4231 -3226
  51. package/src/cli.ts +261 -143
  52. package/src/codec.ts +72 -0
  53. package/src/compression.ts +56 -63
  54. package/src/cross-region.ts +245 -0
  55. package/src/dashboard/handler.ts +392 -0
  56. package/src/dashboard/html.ts +594 -0
  57. package/src/dashboard/index.ts +195 -0
  58. package/src/dashboard/types.ts +96 -0
  59. package/src/disk-tier.ts +1223 -821
  60. package/src/drizzle/index.ts +86 -86
  61. package/src/edge/adapters/cloudflare-do.ts +130 -0
  62. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  63. package/src/edge/adapters/upstash.ts +143 -0
  64. package/src/edge/cache.ts +797 -0
  65. package/src/edge/crypto.ts +182 -0
  66. package/src/edge/hono.ts +203 -0
  67. package/src/edge/index.ts +37 -0
  68. package/src/edge/types.ts +230 -0
  69. package/src/edge/utils/base64.ts +63 -0
  70. package/src/edge/utils/murmur3.ts +179 -0
  71. package/src/encryption.ts +635 -493
  72. package/src/http/express.ts +195 -0
  73. package/src/http/fastify.ts +260 -0
  74. package/src/http/index.ts +46 -223
  75. package/src/http/utils.ts +92 -0
  76. package/src/index.ts +149 -47
  77. package/src/ipc-telemetry.ts +481 -0
  78. package/src/latency-watchdog.ts +282 -0
  79. package/src/nestjs/decorators.ts +161 -161
  80. package/src/nestjs/index.ts +23 -23
  81. package/src/nestjs/tricache.module.ts +104 -104
  82. package/src/nestjs/tricache.store.ts +97 -97
  83. package/src/nestjs/types.ts +79 -79
  84. package/src/next/cache-handler.ts +271 -244
  85. package/src/next/index.ts +37 -37
  86. package/src/next/isr-handler.ts +105 -105
  87. package/src/next/types.ts +130 -130
  88. package/src/prisma/index.ts +154 -151
  89. package/src/remote-snapshot.ts +153 -0
  90. package/src/serialize-worker.ts +120 -120
  91. package/src/sigv4-snapshot-adapter.ts +260 -0
  92. package/src/smart-memory-cache.ts +1109 -1024
  93. package/src/types.ts +1199 -902
  94. package/src/utils/cgroup.ts +100 -0
  95. package/src/utils/tracing.ts +54 -0
  96. package/src/wasm/bloom-filter-wasm.ts +109 -102
  97. package/src/worker-pool.ts +299 -299
  98. package/src/wtiny-lfu.ts +624 -0
  99. package/dist/cache-service-AJASH5FX.js +0 -7
  100. package/dist/chunk-UBSR5UYA.js +0 -0
package/src/types.ts CHANGED
@@ -1,902 +1,1199 @@
1
- /**
2
- * tricache — shared types and interfaces
3
- */
4
-
5
- // ─── Logger ─────────────────────────────────────────────────────────────────
6
-
7
- // ─── OpenTelemetry tracer interface ──────────────────────────────────────────
8
-
9
- /**
10
- * Minimal span interface — structurally compatible with `@opentelemetry/api` Span.
11
- * Pass your existing OTEL tracer; no extra package required.
12
- */
13
- export interface ICacheSpan {
14
- setAttribute(key: string, value: string | number | boolean): this;
15
- setStatus(status: { code: 0 | 1 | 2; message?: string }): this;
16
- end(): void;
17
- }
18
-
19
- /**
20
- * Minimal tracer interface — structurally compatible with `@opentelemetry/api` Tracer.
21
- */
22
- export interface ICacheTracer {
23
- startSpan(name: string): ICacheSpan;
24
- }
25
-
26
- /** Minimal logger interface — plug in any logger (pino, winston, console, etc.) */
27
- export interface ILogger {
28
- debug(msg: string, meta?: Record<string, unknown>): void;
29
- info(msg: string, meta?: Record<string, unknown>): void;
30
- warn(msg: string, meta?: Record<string, unknown>): void;
31
- error(msg: string, meta?: Record<string, unknown>, err?: Error): void;
32
- }
33
-
34
- /** Default no-op logger — swap out via CacheService options */
35
- export const consoleLogger: ILogger = {
36
- debug: () => {},
37
- info: (msg, meta) => console.info('[tricache]', msg, meta ?? ''),
38
- warn: (msg, meta) => console.warn('[tricache]', msg, meta ?? ''),
39
- error: (msg, meta, err) => console.error('[tricache]', msg, meta ?? '', err ?? ''),
40
- };
41
-
42
- // ─── Eviction reason ────────────────────────────────────────────────────────
43
-
44
- /**
45
- * Reason passed to the `onEviction` callback.
46
- * - `'capacity'` — L1 over-capacity; evicted during a `set()` call
47
- * - `'category'` — Per-category limit exceeded
48
- * - `'rebalance'` — `cache.rebalance()` was called
49
- * - `'oom'` — OOM guard emergency eviction
50
- * - `'ttl'` — Entry expired during periodic cleanup
51
- * - `'manual'` — Explicit `cache.delete()` call
52
- */
53
- export type EvictionReason = 'capacity' | 'category' | 'rebalance' | 'oom' | 'ttl' | 'manual';
54
-
55
- // ─── Ping result ─────────────────────────────────────────────────────────────
56
-
57
- /** Per-tier latency returned by `cache.ping()`. */
58
- export interface CachePingResult {
59
- /** L1 RAM check latency in milliseconds */
60
- l1: number;
61
- /** L1.5 disk stats access in milliseconds */
62
- disk: number;
63
- /** L2 Redis PING round-trip in milliseconds, or `null` when Redis is disabled */
64
- l2: number | null;
65
- }
66
-
67
- // ─── Cache priorities ────────────────────────────────────────────────────────
68
-
69
- /** Priority levels for L1 eviction — higher = less likely to be evicted */
70
- export enum CachePriority {
71
- LOW = 1, // Easily regenerated (analytics, reports)
72
- NORMAL = 2, // General data
73
- HIGH = 3, // Frequently accessed (profiles, config)
74
- CRITICAL = 4, // Must never be evicted unless expired (auth tokens, active sessions)
75
- }
76
-
77
- // ─── Internal L1 entry shape ─────────────────────────────────────────────────
78
-
79
- /** Internal representation of a single cache entry in the L1 Map */
80
- export interface SmartCacheEntry {
81
- /** msgpackr-packed binary payload — used for disk spill and snapshot serialization */
82
- data: Buffer;
83
- /**
84
- * Deserialized JS value, cached at write time so hot reads skip the unpack step entirely.
85
- * Undefined for entries restored from disk/snapshot (populated lazily on first access).
86
- * NOTE: returned by reference — callers should treat the value as immutable.
87
- */
88
- value?: unknown;
89
- /** always true for entries written by the current code;
90
- * may be false in legacy snapshots/disk files — handled transparently on import */
91
- isCompressed: boolean;
92
- /** Hard expiry — entry is deleted after this timestamp */
93
- expiresAt: number;
94
- /** SWR soft expiry — serve stale + revalidate in background when past this */
95
- staleAt?: number;
96
- /** Exact byte size of the stored value */
97
- size: number;
98
- /** Access count (LFU numerator) */
99
- hits: number;
100
- /** Last access timestamp (LRU comparator) */
101
- lastAccess: number;
102
- /** Eviction priority */
103
- priority: CachePriority;
104
- /** Original TTL in ms at write time — used by refresh-ahead to compute the proactive refresh threshold. */
105
- ttlMs?: number;
106
- /** Milliseconds taken to fetch/compute this value — used by XFetch probabilistic early expiration. */
107
- delta?: number;
108
- /**
109
- * Unix timestamp (ms) when this entry was written.
110
- * Stored explicitly so staleness-fence eviction (`evictSetBefore`) is precise
111
- * instead of approximating via `expiresAt - ttlMs`.
112
- * Optional for backward compatibility with snapshots written by older versions.
113
- */
114
- setAt?: number;
115
- /** Active tag versions at write time (used when tagStrategy === 'generational') */
116
- tagVersions?: Record<string, number>;
117
- }
118
-
119
- /** Returned by SmartMemoryCache.get() — distinguishes "cached null" from a real miss */
120
- export interface CacheHit {
121
- value: unknown;
122
- /** true = past soft TTL (staleAt) but within hard expiry → SWR path */
123
- isStale: boolean;
124
- /** Hard expiry timestamp — lets CacheService.get() do refresh-ahead / XFetch math
125
- * without a second Map lookup (eliminates the duplicate l1.getEntry() call). */
126
- expiresAt: number;
127
- /** Original TTL in ms stored at write time — for refresh-ahead fraction calculation */
128
- ttlMs?: number;
129
- /** Fetch duration in ms stored at write time — for XFetch probabilistic threshold */
130
- delta?: number;
131
- /** Timestamp (Date.now()) recorded inside SmartMemoryCache.get() — lets CacheService
132
- * reuse this value for refresh-ahead/XFetch math instead of making a second syscall. */
133
- fetchedAt?: number;
134
- /** Active tag versions at write time (used when tagStrategy === 'generational') */
135
- tagVersions?: Record<string, number>;
136
- /** Timestamp (ms) when this entry was written into memory */
137
- setAt?: number;
138
- }
139
-
140
- // ─── Disk tier ───────────────────────────────────────────────────────────────
141
-
142
- /** On-disk entry shape (mirrors SmartCacheEntry — Uint8Array accepted for msgpack round-trips;
143
- * legacy disk files written by older versions may have a JSON string in data) */
144
- export interface DiskCacheEntry {
145
- data: string | Buffer | Uint8Array;
146
- isCompressed: boolean;
147
- expiresAt: number;
148
- staleAt?: number;
149
- size: number;
150
- hits: number;
151
- lastAccess: number;
152
- priority: number;
153
- /** Active tag versions at write time (used when tagStrategy === 'generational') */
154
- tagVersions?: Record<string, number>;
155
- }
156
-
157
- // ─── Metrics snapshot ────────────────────────────────────────────────────────
158
-
159
- /**
160
- * Snapshot of runtime metrics for a CacheService instance.
161
- * Returned by `CacheService.metrics()` and passed to the `onMetrics` callback.
162
- * Convert to Prometheus text with `CacheService.toPrometheusText(metrics)`.
163
- */
164
- export interface CacheMetrics {
165
- /** Configured namespace (empty string = no namespace) */
166
- namespace: string;
167
- /** Milliseconds since the CacheService instance was constructed */
168
- uptimeMs: number;
169
-
170
- gets: {
171
- total: number;
172
- l1Hits: number;
173
- /** Fraction of gets served from L1 RAM cache (0–1) */
174
- l1HitRate: number;
175
- diskHits: number;
176
- /** Fraction of gets served from L1.5 disk tier (0–1) */
177
- diskHitRate: number;
178
- l2Hits: number;
179
- /** Fraction of gets served from L2 Redis (0–1) */
180
- l2HitRate: number;
181
- /** fetchFn calls (cache misses that fell through to the DB) */
182
- fetches: number;
183
- /** Fraction of gets that called fetchFn (0–1) */
184
- fetchRate: number;
185
- /** Concurrent get() calls deduplicated by the stampede guard */
186
- stampedePrevented: number;
187
- };
188
-
189
- sets: { total: number };
190
- deletes: { total: number };
191
- revalidations: { total: number };
192
-
193
- /** Rate-limit / singleton diagnostics */
194
- counters: {
195
- /** Times `increment()` hit a Redis error (fail-open by default, or fail-closed re-throw). */
196
- errors: number;
197
- /** Times a later `create(ns)` call passed options diverging from the live singleton. */
198
- singletonDivergences: number;
199
- };
200
-
201
- bloom: {
202
- /** Total bloom-filter checks (get() calls that passed prefix filter) */
203
- checksTotal: number;
204
- /**
205
- * Times the filter said "might contain" but the key was absent in L1.
206
- * A high rate suggests the bloom filter capacity needs increasing.
207
- */
208
- falsePositives: number;
209
- /** falsePositives / checksTotal (0–1; ideal < 0.01) */
210
- falsePositiveRate: number;
211
- };
212
-
213
- compression: {
214
- entriesCompressed: number;
215
- entriesUncompressed: number;
216
- /** Approximate bytes saved by msgpackr vs raw JSON */
217
- bytesSaved: number;
218
- };
219
-
220
- /** Invalidation backplane statistics */
221
- backplane: {
222
- enabled: boolean;
223
- mode: 'pubsub' | 'stream';
224
- /** Invalidation messages published to other instances */
225
- sent: number;
226
- /** Invalidation messages received from other instances */
227
- received: number;
228
- /** Own messages silently skipped (prevents double-eviction) */
229
- skipped: number;
230
- /** Stream entries received (when backplaneMode is 'stream') */
231
- streamEntriesReceived?: number;
232
- /** Replayed invalidations after network reconnect */
233
- streamReplays?: number;
234
- /** Stream trim gaps detected (where consumer fell behind oldest entry) */
235
- streamGaps?: number;
236
- };
237
-
238
- /** L2 Redis circuit breaker state */
239
- l2CircuitBreaker: {
240
- /** `'closed'` = normal; `'open'` = Redis paused; `'half_open'` = probing recovery */
241
- state: 'closed' | 'open' | 'half_open';
242
- };
243
-
244
- /** OOM guard statistics */
245
- oom: {
246
- enabled: boolean;
247
- /** Number of emergency L1 eviction rounds triggered */
248
- evictions: number;
249
- /** Timestamp of the most recent OOM eviction, or null */
250
- lastTriggeredAt: number | null;
251
- };
252
-
253
- l1: { entries: number; sizeBytes: number; maxBytes: number };
254
- disk: { files: number; sizeKB: number; maxKB: number; disabled: boolean };
255
-
256
- /** Adaptive TTL statistics — present only when `adaptiveTtl` is enabled */
257
- adaptiveTtl?: {
258
- enabled: true;
259
- /** Number of unique keys currently tracked in the latency ring buffers */
260
- trackedKeys: number;
261
- /**
262
- * Top-20 slowest keys by p95 fetch latency, sorted descending.
263
- * Keys are shown without the instance namespace prefix.
264
- * Only keys with ≥ 5 recorded samples appear here.
265
- */
266
- slowestKeys: Array<{ key: string; p95Ms: number; adaptedTtlSec: number }>;
267
- };
268
- }
269
-
270
- // ─── Configuration ───────────────────────────────────────────────────────────
271
-
272
- /** Per-category memory limits for L1 */
273
- export interface CategoryLimit {
274
- maxEntries: number;
275
- maxSizeBytes: number;
276
- }
277
-
278
- /**
279
- * Options accepted by CacheService.create()
280
- *
281
- * All fields are optional — sensible defaults are used when omitted.
282
- */
283
- export interface CacheOptions {
284
- /**
285
- * Plug in your own logger (pino, winston, bunyan, …).
286
- * Defaults to a minimal console logger that only prints warn/error.
287
- */
288
- logger?: ILogger;
289
-
290
- // ── L1 (in-memory) ────────────────────────────────────────────────────────
291
- /** Max total bytes held in L1 RAM cache. Default: 200 MB */
292
- l1MaxBytes?: number;
293
- /** Max total entries in L1. Default: 2000 */
294
- l1MaxEntries?: number;
295
- /**
296
- * Fraction of `l1MaxEntries` / `l1MaxBytes` at which proactive eviction fires
297
- * before the hard limit is reached. Range: 0–1. Default: 0.9.
298
- * Lower (e.g. 0.8) reduces GC pressure at the cost of slightly more eviction work.
299
- */
300
- l1EvictionWatermark?: number;
301
- /**
302
- * Per-category limits keyed by the key prefix (e.g. `'org:'`).
303
- * Merged over the built-in defaults.
304
- */
305
- categoryLimits?: Record<string, CategoryLimit>;
306
- /**
307
- * Key prefixes that are never written to disk snapshots or the disk tier.
308
- * Default: ['auth:', 'session:', 'mfa:', 'rate_limit:']
309
- */
310
- forbiddenSnapshotPrefixes?: string[];
311
-
312
- // ── L1.5 (disk tier) ────────────────────────────────────────────────────
313
- /** Directory used for L1.5 disk-spill files. Default: os.tmpdir()/tricache-disk */
314
- diskCacheDir?: string;
315
- /** Max total bytes for the disk tier. Default: 500 MB */
316
- diskMaxBytes?: number;
317
- /** Max bytes for a single disk entry. Default: 10 MB */
318
- diskEntryMaxBytes?: number;
319
-
320
- // ── L2 (Redis) ────────────────────────────────────────────────────────────
321
- /**
322
- * Redis/Valkey hostname (no `redis://` prefix).
323
- * Falls back to the `REDIS_HOST` environment variable.
324
- * When neither is provided, L2 is disabled.
325
- */
326
- redisHost?: string;
327
- /** Redis port. Default: 6379 */
328
- redisPort?: number;
329
- /**
330
- * Whether to enable TLS for the Redis connection. Default: true in production,
331
- * false otherwise.
332
- */
333
- redisTls?: boolean;
334
- /**
335
- * Redis wire protocol version (RESP2 or RESP3).
336
- * Defaults to 3 in ioredis v6+. Set to 2 for legacy proxies or servers without RESP3 support.
337
- */
338
- redisProtocol?: 2 | 3;
339
- /**
340
- * Set to `true` to disable L2 Redis entirely (e.g. when running single-process
341
- * services that don't need distributed caching). Default: false in production,
342
- * true in development.
343
- */
344
- disableRedis?: boolean;
345
-
346
- // ── Encryption ────────────────────────────────────────────────────────────
347
- /**
348
- * Base64-encoded 32-byte AES-256-GCM key for encrypting L2 (Redis) values and
349
- * disk-tier files at rest. Falls back to `CACHE_ENCRYPTION_KEY` env var.
350
- * If not provided in production, a warning is logged and data is stored plaintext.
351
- */
352
- encryptionKey?: string;
353
- /**
354
- * Encryption algorithm used for L2 (Redis) values and disk-tier files.
355
- * - `'aes-256-gcm'` — default. 32-byte key. Authenticated encryption (AEAD).
356
- * - `'aes-128-gcm'` — 16-byte key. ~10% faster on non-AES-NI hardware. AEAD.
357
- * - `'xor'` — XOR obfuscation ONLY. NOT cryptographic security.
358
- * Any key length (minimum 16 bytes recommended).
359
- * Use for dev environments or non-sensitive data only.
360
- * Default: `'aes-256-gcm'`
361
- */
362
- encryptionMode?: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
363
- /**
364
- * Fallback encryption key for zero-downtime key rotation.
365
- * On every read, tricache tries the current `encryptionKey` first.
366
- * If decryption fails (wrong key), it retries with `previousEncryptionKey`.
367
- * All writes always use the current `encryptionKey`.
368
- * Remove this field once you are confident all data has been re-encrypted.
369
- */
370
- previousEncryptionKey?: string;
371
- /** Encryption mode that was used with `previousEncryptionKey`. Defaults to `encryptionMode`. */
372
- previousEncryptionMode?: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
373
-
374
- // ── Compression ──────────────────────────────────────────────────────────
375
- /**
376
- * Optional compression algorithm for L2 (Redis) strings and disk-tier binary blobs.
377
- * - `'brotli'` (default when enabled) — superior compression ratio for JSON / text payloads.
378
- * - `'gzip'` — faster compression / lower CPU overhead.
379
- * - `'none'` — disable compression.
380
- * Default: `'none'` (uncompressed).
381
- */
382
- compression?: 'brotli' | 'gzip' | 'none';
383
- /**
384
- * Minimum payload size in bytes before compression is applied.
385
- * Payloads smaller than this threshold remain uncompressed to avoid compression overhead.
386
- * Default: `1024` (1 KB).
387
- */
388
- compressionThresholdBytes?: number;
389
-
390
- // ── Snapshot ────────────────────────────────────────────────────────────
391
- /**
392
- * Path where the cold-start snapshot is written on SIGTERM/SIGINT and loaded
393
- * on startup. Default: os.tmpdir()/tricache-snapshot.msgpack
394
- */
395
- snapshotPath?: string;
396
- /**
397
- * Max age (ms) of a snapshot file before it is rejected. Default: 2 hours
398
- */
399
- snapshotMaxAgeMs?: number;
400
-
401
- /**
402
- * Optional namespace prefix for all cache keys.
403
- *
404
- * When set, every key is transparently stored as `${namespace}:${key}` in
405
- * L1, L1.5 (disk), and L2 (Redis). This enables:
406
- * - **Multi-tenant isolation**: `CacheService.create({ namespace: 'org_abc' })`
407
- * — tenants sharing the same Redis instance or disk dir are fully isolated.
408
- * - **Environment separation**: `CacheService.create({ namespace: 'staging' })`
409
- * - **Service-level scoping**: microservices sharing one Redis without key collisions.
410
- *
411
- * Consumers never see the prefix — `get('user:1')` behaves identically
412
- * whether namespaced or not. Glob deletes (`delete('user:*')`) automatically
413
- * scope to the namespace.
414
- *
415
- * The process-level singleton, disk cache directory, and cold-start snapshot
416
- * path are all scoped per namespace, so two `CacheService.create()` calls
417
- * with different namespaces return completely independent instances.
418
- *
419
- * Default: `''` (no prefix)
420
- */
421
- namespace?: string;
422
-
423
- /**
424
- * Seconds to extend a stale SWR entry's life when background revalidation fails.
425
- * Without this, a failed revalidation leaves the entry stale until its hard TTL
426
- * expires, after which the next caller blocks. With `staleIfError`, tricache bumps
427
- * the expiry by this many seconds on every failed revalidation, keeping the stale
428
- * value available while the underlying service is degraded.
429
- * Default: `0` (disabled — entry expires normally on revalidation failure).
430
- */
431
- staleIfError?: number;
432
-
433
- /**
434
- * Called after every L1 eviction. Receives the raw (namespaced) key and the reason.
435
- * Useful for diagnosing cache pressure and tuning `categoryLimits`.
436
- */
437
- onEviction?: (key: string, reason: EvictionReason) => void;
438
-
439
- /**
440
- * Human-readable name for this CacheService instance. Added as an `instance` label
441
- * to all Prometheus metrics emitted by `CacheService.toPrometheusText()`.
442
- * Required when multiple CacheService instances share a process — without it,
443
- * metric names from different instances collide.
444
- * Default: `''` (no label).
445
- */
446
- instanceName?: string;
447
-
448
- /**
449
- * Controls whether writes are propagated to L2 (Redis).
450
- * - `'read-write'` (default): read from and write to L2.
451
- * - `'read-only'`: read from L2 but never write, delete, or expire keys in Redis.
452
- * Use for shared read replicas or external Redis clusters you do not own.
453
- */
454
- l2WriteMode?: 'read-write' | 'read-only';
455
-
456
- // ── Invalidation backplane (Redis Pub/Sub) ──────────────────────────────
457
- /**
458
- * Enable Redis Pub/Sub invalidation backplane so every running instance
459
- * evicts a key from its L1 when any peer calls `set()` or `delete()`.
460
- *
461
- * Gives you sub-microsecond in-process cache speed with cluster-wide
462
- * consistency across all your app servers.
463
- *
464
- * Default: `true` (auto-activates when Redis is available).
465
- * Set to `false` for single-process services or eventual-consistency scenarios.
466
- */
467
- invalidationBackplane?: boolean;
468
-
469
- /**
470
- * Enable Redis 7+ Sharded Pub/Sub (`SPUBLISH` / `SSUBSCRIBE`) when connected to
471
- * a Redis Cluster (`redisClusterNodes`). Scopes pub/sub message routing strictly
472
- * to the cluster shard handling the key slot, reducing inter-node cluster bus gossip.
473
- *
474
- * Default: `false` (standard cluster PUBLISH / SUBSCRIBE).
475
- */
476
- useShardedPubSub?: boolean;
477
-
478
- // ── OOM protection ──────────────────────────────────────────────────────
479
- /**
480
- * Enable the GC-aware OOM guard. When heap utilisation crosses
481
- * `oomHeapThreshold`, a fraction of the coldest L1 entries are
482
- * emergency-evicted to L1.5 disk, preventing Node.js OOM crashes inside
483
- * Docker/Kubernetes containers with tight memory limits.
484
- *
485
- * Default: `true`
486
- */
487
- oomProtection?: boolean;
488
- /**
489
- * Heap-used / heap-total ratio that triggers emergency eviction.
490
- * Default: `0.85` (85 %)
491
- */
492
- oomHeapThreshold?: number;
493
- /** Milliseconds between heap-pressure checks. Default: 10 000 ms (10 s) */
494
- oomCheckIntervalMs?: number;
495
- /** Fraction of L1 entries to evict per OOM round. Default: `0.20` (20 %) */
496
- oomEvictPercent?: number;
497
-
498
- // ── Metrics / observability ─────────────────────────────────────────────
499
- /**
500
- * Callback invoked periodically with a `CacheMetrics` snapshot.
501
- * Wire up to OpenTelemetry, Prometheus push gateway, Datadog, etc.
502
- *
503
- * @example
504
- * onMetrics: (m) => statsd.gauge('cache.l1_hit_rate', m.gets.l1HitRate)
505
- */
506
- onMetrics?: (metrics: CacheMetrics) => void;
507
- /** How often the `onMetrics` callback fires (ms). Default: 60 000 ms */
508
- metricsIntervalMs?: number;
509
-
510
- /**
511
- * OpenTelemetry-compatible tracer. When provided, `get()`, `set()`, and
512
- * `delete()` are each wrapped in a span with attributes:
513
- * - `cache.hit` — `'l1' | 'disk' | 'l2' | 'miss'`
514
- * - `cache.key_prefix` — first path segment of the key (e.g. `'user'`)
515
- *
516
- * Pass your existing `@opentelemetry/api` Tracer directly — no extra
517
- * dependency required; the interface is structurally compatible.
518
- *
519
- * @example
520
- * import { trace } from '@opentelemetry/api';
521
- * tracer: trace.getTracer('tricache')
522
- */
523
- tracer?: ICacheTracer;
524
-
525
- // ── TTL jitter ─────────────────────────────────────────────────────────────
526
- /**
527
- * Randomise every stored TTL by ± `ttlJitterFactor × ttl` seconds.
528
- * Prevents thundering-herd cache stampedes when thousands of entries share
529
- * the same TTL and expire simultaneously.
530
- *
531
- * A factor of `0.15` spreads a 300 s TTL uniformly over [255 s, 345 s].
532
- * Default: `0` (disabled — TTLs are stored exactly as given).
533
- */
534
- ttlJitterFactor?: number;
535
-
536
- // ── L2 circuit breaker ─────────────────────────────────────────────────────
537
- /**
538
- * Default TTL in seconds for `null` or `undefined` results from `fetchFn`.
539
- * Caches negative results so a non-existent key (deleted user, bad ID) does not
540
- * hit the DB on every request. Can be overridden per-call via `get(..., { notFoundTtl }).
541
- * Default: `0` (disabled — null/undefined uses the normal TTL).
542
- */
543
- notFoundTtl?: number;
544
-
545
- /**
546
- * Number of consecutive Redis errors before the circuit opens (stops
547
- * attempting Redis until the cooldown elapses).
548
- * Default: `5`.
549
- */
550
- l2CircuitBreakerThreshold?: number;
551
- /**
552
- * Milliseconds the circuit stays open before transitioning to half-open
553
- * (allows a single probe request to test recovery).
554
- * Default: `30 000` ms (30 s).
555
- */
556
- l2CircuitBreakerCooldownMs?: number;
557
- /**
558
- * Redis key pattern to automatically warm L1 from at startup (e.g. `'user:*'`).
559
- * `cache.ready()` returns a Promise that resolves once this warm-up completes.
560
- * No-op when Redis is disabled or unreachable — safe to set unconditionally.
561
- */
562
- warmKeys?: string;
563
-
564
- /**
565
- * Called on every L1, disk, or L2 cache hit. Receives the caller-facing key (no
566
- * namespace prefix) and the tier that served it. Useful for per-route hit-rate
567
- * metrics without waiting for the `onMetrics` interval.
568
- *
569
- * @example
570
- * onHit: (key, tier) => cloudwatch.putMetricData({ key, tier })
571
- */
572
- onHit?: (key: string, tier: 'l1' | 'disk' | 'l2') => void;
573
-
574
- /**
575
- * Called on every cache miss (after L1, disk, and L2 are all exhausted).
576
- * Receives the caller-facing key (no namespace prefix).
577
- *
578
- * @example
579
- * onMiss: (key) => cloudwatch.putMetricData({ key })
580
- */
581
- onMiss?: (key: string) => void;
582
-
583
- /**
584
- * When `true`, every value returned from an L1 cache hit is recursively
585
- * frozen with `Object.freeze()` before being handed to the caller.
586
- * Any attempt to mutate the returned object throws a `TypeError` immediately,
587
- * catching reference-semantic corruption bugs that would otherwise silently
588
- * corrupt the cached entry.
589
- *
590
- * **Do not enable in production** — use `process.env.NODE_ENV !== 'production'`.
591
- * Deep-freezing large objects has measurable overhead per hit.
592
- *
593
- * @example
594
- * frozen: process.env.NODE_ENV !== 'production'
595
- */
596
- frozen?: boolean;
597
-
598
- // ── Adaptive TTL ──────────────────────────────────────────────────────────
599
-
600
- /**
601
- * When `true`, tricache tracks per-key fetch latency in a rolling ring buffer
602
- * and automatically derives an optimal TTL from the p95 fetch duration:
603
- *
604
- * ```
605
- * adaptedTtl = clamp(p95LatencyMs × adaptiveTtlMultiplier, adaptiveTtlMin, adaptiveTtlMax)
606
- * ```
607
- *
608
- * The caller-supplied `ttlSeconds` is used until at least 5 samples are collected
609
- * for a key, then the library takes over TTL management autonomously.
610
- *
611
- * Expensive keys (slow DB queries) get cached longer; cheap keys stay close to
612
- * their base TTL. Callers no longer need to reason about individual TTL values.
613
- *
614
- * Default: `false`.
615
- */
616
- adaptiveTtl?: boolean;
617
-
618
- /**
619
- * Minimum TTL (seconds) the adaptive tuner will ever assign.
620
- * Guards against extremely fast fetches producing near-zero TTLs.
621
- * Default: `10`.
622
- */
623
- adaptiveTtlMin?: number;
624
-
625
- /**
626
- * Maximum TTL (seconds) the adaptive tuner will ever assign.
627
- * Guards against pathologically slow fetches producing indefinite caching.
628
- * Default: `86400` (24 hours).
629
- */
630
- adaptiveTtlMax?: number;
631
-
632
- /**
633
- * `p95FetchLatencyMs × adaptiveTtlMultiplier = adaptedTtlSeconds`.
634
- *
635
- * Intuition: a 200 ms p95 fetch with the default multiplier of 20 yields a
636
- * 4-second TTL. A 2 000 ms fetch yields 40 seconds. Increase the multiplier
637
- * if you want the cache to absorb more upstream pressure.
638
- *
639
- * Default: `20`.
640
- */
641
- adaptiveTtlMultiplier?: number;
642
-
643
- /**
644
- * Number of fetch duration samples kept per key in the ring buffer.
645
- * Larger values smooth out latency spikes but use slightly more memory
646
- * (~8 bytes × samples per tracked key).
647
- * Default: `32`.
648
- */
649
- adaptiveTtlSamples?: number;
650
-
651
- /**
652
- * Maximum number of distinct keys tracked by the adaptive TTL system.
653
- * When the cap is reached, the oldest-tracked key is evicted from the
654
- * ring-buffer store to make room for the new key.
655
- * Default: `5000`.
656
- */
657
- adaptiveTtlMaxKeys?: number;
658
-
659
- // ── Worker-thread serialization offload ────────────────────────────────────
660
- /**
661
- * When `true`, tricache spawns a pool of worker threads and offloads AES-GCM
662
- * encryption and decryption for large payloads to those threads, keeping the
663
- * V8 main event loop free for concurrent HTTP requests.
664
- *
665
- * Only takes effect when `encryptionKey` is set — plaintext payloads are never
666
- * serialized off-thread because `JSON.stringify/parse` is already fast.
667
- *
668
- * Default: `false`. Enable in long-running servers that write multi-megabyte
669
- * encrypted payloads and observe event-loop latency spikes.
670
- */
671
- workerThreads?: boolean;
672
- /**
673
- * Byte threshold above which an L2 payload is offloaded to a worker thread
674
- * for encryption / decryption. Payloads smaller than this are processed
675
- * synchronously (IPC overhead would exceed the savings).
676
- * Default: `131072` (128 KB).
677
- */
678
- workerThresholdBytes?: number;
679
- /**
680
- * Number of worker threads in the pool.
681
- * Default: `Math.min(4, os.availableParallelism())`.
682
- */
683
- workerPoolSize?: number;
684
-
685
- // ── Backplane staleness fence ───────────────────────────────────────────────
686
- /**
687
- * Maximum milliseconds the Redis Pub/Sub subscriber is allowed to be
688
- * disconnected before tricache considers its L1 entries potentially stale.
689
- *
690
- * When the subscriber reconnects after a gap longer than this value, all L1
691
- * entries that were written *before* the disconnect started are evicted.
692
- * This prevents the instance from silently serving data that peers may have
693
- * invalidated while the backplane connection was down.
694
- *
695
- * Set to `0` to disable the fence entirely (accept eventual-consistency drift).
696
- * Default: `5000` (5 seconds).
697
- */
698
- backplaneMaxStalenessMs?: number;
699
-
700
- // ── Disk tier ─────────────────────────────────────────────────────────────
701
- /**
702
- * Explicitly disable the L1.5 disk spill tier and cold-start snapshots.
703
- *
704
- * Tricache auto-detects common serverless / ephemeral-filesystem runtimes
705
- * (AWS Lambda, Google Cloud Run, Google Cloud Functions, Azure Functions,
706
- * Fly.io) and disables the disk tier automatically. Set this to `false` to
707
- * override that detection and force the disk tier on regardless of runtime.
708
- *
709
- * When disabled:
710
- * - L1 evictions are dropped instead of being spilled to disk.
711
- * - Cold-start snapshot persistence is skipped.
712
- * - The `disk` metrics field still appears but shows zeroed counters.
713
- *
714
- * Default: `undefined` (auto-detect).
715
- */
716
- disableDisk?: boolean;
717
-
718
- // ── Redis Cluster / Sentinel ───────────────────────────────────────────────
719
- /**
720
- * Redis Cluster node list. When provided, tricache connects using ioredis
721
- * `Cluster` mode with automatic slot routing and multi-node connection
722
- * pooling — no external proxy required.
723
- *
724
- * Takes precedence over `redisHost`/`redisPort`.
725
- *
726
- * @example
727
- * redisClusterNodes: [
728
- * { host: 'redis-1.internal', port: 6379 },
729
- * { host: 'redis-2.internal', port: 6379 },
730
- * { host: 'redis-3.internal', port: 6379 },
731
- * ]
732
- */
733
- redisClusterNodes?: Array<{ host: string; port: number }>;
734
-
735
- /**
736
- * Redis Sentinel configuration for high-availability setups.
737
- * When provided, tricache connects through Sentinel for automatic
738
- * primary failover — no static `redisHost` / `redisPort` needed.
739
- *
740
- * Takes precedence over `redisHost`/`redisPort` (but not over `redisClusterNodes`).
741
- *
742
- * @example
743
- * redisSentinel: {
744
- * name: 'mymaster',
745
- * sentinels: [
746
- * { host: 'sentinel-1.internal', port: 26379 },
747
- * { host: 'sentinel-2.internal', port: 26379 },
748
- * ],
749
- * }
750
- */
751
- redisSentinel?: {
752
- /** Logical name of the monitored master. Must match the Sentinel `monitor` config. */
753
- name: string;
754
- sentinels: Array<{ host: string; port: number }>;
755
- };
756
-
757
- /**
758
- * When `true`, a second `CacheService.create()` call for an already-existing
759
- * singleton (same namespace) whose options differ from the first call throws
760
- * instead of silently returning the existing instance. Use in codebases where
761
- * multiple init points could pass conflicting configuration (e.g. different
762
- * Redis credentials or TTLs) and you want that class of bug to fail loudly.
763
- *
764
- * Default: `false` (warn once, return existing instance).
765
- */
766
- strictSingleton?: boolean;
767
-
768
- /**
769
- * `cache.increment()` distributed-rate-limit behaviour on a Redis error.
770
- *
771
- * Default: `false` (fail-open — on a Redis error the method returns `0`, so a
772
- * caller's `if (count > LIMIT) reject()` guard never rejects during an outage).
773
- * Set to `true` to instead re-throw the Redis error, letting the caller's limit
774
- * guard enforce the limit even when Redis is unavailable.
775
- */
776
- failClosed?: boolean;
777
-
778
- /**
779
- * Strategy used for tag-based cache invalidation:
780
- * - `'set'` (default): Traditional Redis Set tracking. Members are registered in Redis
781
- * sets and deleted individually on `invalidateTag()`. Best for low-to-medium cardinality tags.
782
- * - `'generational'`: Generational tag versioning ($O(1)$ invalidations). Tag invalidation
783
- * increments an atomic integer version counter in Redis and local memory. Entries store their
784
- * creation tag versions; stale entries are detected on access and pruned with version-gated
785
- * compare-and-delete. Eliminates key scans and Redis bulk deletion stalls on large datasets.
786
- */
787
- tagStrategy?: 'set' | 'generational';
788
-
789
- /**
790
- * Milliseconds before an in-memory generational tag version is re-synced from Redis.
791
- * Bounds maximum partition/missed-broadcast staleness when using `tagStrategy: 'generational'`.
792
- * Default: `5000` ms (5 seconds).
793
- */
794
- tagVersionTtlMs?: number;
795
-
796
- /**
797
- * Read safety strategy for returned cached objects:
798
- * - `'none'` (default): Returns raw in-memory references for sub-microsecond performance (~350 ns).
799
- * - `'structuredClone'`: Clones values via native `structuredClone()` on L1 hits, L2 promotions,
800
- * and fetch returns, preventing caller mutations from polluting the cached reference.
801
- * Supported types: plain objects, arrays, Dates, Maps, Sets, TypedArrays. Functions and class
802
- * prototype chains are not preserved.
803
- */
804
- cloneStrategy?: 'none' | 'structuredClone';
805
-
806
- /**
807
- * Invalidation backplane transport mode:
808
- * - `'pubsub'` (default): Ephemeral Redis Pub/Sub (at-most-once delivery).
809
- * - `'stream'`: Durable Redis Streams (XADD/XREAD) with missed-event replay on reconnect.
810
- */
811
- backplaneMode?: 'pubsub' | 'stream';
812
-
813
- /**
814
- * Maximum retained entries in the Redis invalidation stream (`MAXLEN ~ N`).
815
- * Default: `10000`.
816
- */
817
- backplaneStreamMaxLen?: number;
818
-
819
- /**
820
- * Blocking poll timeout in milliseconds for `XREAD BLOCK`.
821
- * Default: `2000` ms (2 seconds).
822
- */
823
- backplaneStreamBlockMs?: number;
824
-
825
- /**
826
- * Custom Redis Stream key name.
827
- * Default: `tricache:stream:{<namespace>}` (hash-tagged for Redis Cluster single-slot routing).
828
- */
829
- backplaneStreamKey?: string;
830
-
831
- /**
832
- * OpenTelemetry Meter instance for native metrics publishing.
833
- * Compatible with `@opentelemetry/api` Meter.
834
- */
835
- meter?: ICacheMeter;
836
- }
837
-
838
- /**
839
- * Options for the ergonomic `cache.wrap(key, fetchFn, options)` method.
840
- */
841
- export interface WrapOptions {
842
- /** TTL in seconds (default: 300 s). */
843
- ttl?: number;
844
- /** Stale-While-Revalidate grace period in seconds. */
845
- swr?: number;
846
- /** Override the auto-inferred eviction priority. */
847
- priority?: CachePriority;
848
- /** Semantic tags for invalidation. */
849
- tags?: string[];
850
- /** Dependency cascade patterns (e.g. `['user:*']`). */
851
- dependsOn?: string[];
852
- /** 0–1 fraction of TTL elapsed at which a proactive background refresh is scheduled. */
853
- refreshAhead?: number;
854
- /** XFetch probabilistic early expiration factor (0.5–2.0). */
855
- xfetchBeta?: number;
856
- /** Override TTL in seconds for null/undefined fetch results (negative caching). */
857
- notFoundTtl?: number;
858
- }
859
-
860
- /**
861
- * Options for distributed and in-process mutual exclusion locks via `cache.lock()`.
862
- */
863
- export interface LockOptions {
864
- /**
865
- * Lock auto-release TTL in seconds (default: 30 s).
866
- * Prevents deadlocks if the holding node crashes or is terminated.
867
- */
868
- ttl?: number;
869
- /**
870
- * Maximum time to wait to acquire the lock in milliseconds before throwing a timeout error.
871
- * Default: `5000` ms.
872
- */
873
- acquireTimeout?: number;
874
- /**
875
- * Polling retry interval in milliseconds when waiting for lock acquisition.
876
- * Default: `100` ms.
877
- */
878
- retryInterval?: number;
879
- }
880
-
881
- /**
882
- * Structural typing matching OpenTelemetry Metric interfaces (`@opentelemetry/api`).
883
- */
884
- export interface ICacheCounter {
885
- add(value: number, attributes?: Record<string, string | number | boolean>): void;
886
- }
887
-
888
- export interface ICacheObservableGauge {
889
- readonly _isGauge?: true;
890
- }
891
-
892
- export interface ICacheBatchObservableCallback {
893
- (observableResult: {
894
- observe: (metric: ICacheObservableGauge, value: number, attributes?: Record<string, string | number | boolean>) => void;
895
- }): void | Promise<void>;
896
- }
897
-
898
- export interface ICacheMeter {
899
- createCounter(name: string, options?: { description?: string; unit?: string }): ICacheCounter;
900
- createObservableGauge(name: string, options?: { description?: string; unit?: string }): ICacheObservableGauge;
901
- addBatchObservableCallback(callback: ICacheBatchObservableCallback, observables: ICacheObservableGauge[]): void;
902
- }
1
+ import type { RemoteSnapshotOptions } from './remote-snapshot';
2
+ import type { CrossRegionRelayOptions } from './cross-region';
3
+
4
+ /**
5
+ * tricache — shared types and interfaces
6
+ */
7
+
8
+ // ─── Logger ─────────────────────────────────────────────────────────────────
9
+
10
+ // ─── OpenTelemetry tracer interface ──────────────────────────────────────────
11
+
12
+ /**
13
+ * Minimal span interface — structurally compatible with `@opentelemetry/api` Span.
14
+ * Pass your existing OTEL tracer; no extra package required.
15
+ */
16
+ export interface ICacheSpanLink {
17
+ context: {
18
+ traceId: string;
19
+ spanId: string;
20
+ traceFlags?: number;
21
+ };
22
+ }
23
+
24
+ export interface ICacheSpan {
25
+ setAttribute(key: string, value: string | number | boolean): this;
26
+ setStatus(status: { code: 0 | 1 | 2; message?: string }): this;
27
+ recordException?(err: Error | unknown): this;
28
+ end(): void;
29
+ }
30
+
31
+ /**
32
+ * Minimal tracer interface — structurally compatible with `@opentelemetry/api` Tracer.
33
+ */
34
+ export interface ICacheTracer {
35
+ startSpan(name: string, options?: { links?: ICacheSpanLink[] }): ICacheSpan;
36
+ }
37
+
38
+ /** Minimal logger interface — plug in any logger (pino, winston, console, etc.) */
39
+ export interface ILogger {
40
+ debug(msg: string, meta?: Record<string, unknown>): void;
41
+ info(msg: string, meta?: Record<string, unknown>): void;
42
+ warn(msg: string, meta?: Record<string, unknown>): void;
43
+ error(msg: string, meta?: Record<string, unknown>, err?: Error): void;
44
+ }
45
+
46
+ /** Default no-op logger — swap out via CacheService options */
47
+ export const consoleLogger: ILogger = {
48
+ debug: () => {},
49
+ info: (msg, meta) => console.info('[tricache]', msg, meta ?? ''),
50
+ warn: (msg, meta) => console.warn('[tricache]', msg, meta ?? ''),
51
+ error: (msg, meta, err) => console.error('[tricache]', msg, meta ?? '', err ?? ''),
52
+ };
53
+
54
+ // ─── Eviction reason ────────────────────────────────────────────────────────
55
+
56
+ /**
57
+ * Reason passed to the `onEviction` callback.
58
+ * - `'capacity'` — L1 over-capacity; evicted during a `set()` call
59
+ * - `'category'` — Per-category limit exceeded
60
+ * - `'rebalance'` — `cache.rebalance()` was called
61
+ * - `'oom'` — OOM guard emergency eviction
62
+ * - `'ttl'` — Entry expired during periodic cleanup
63
+ * - `'manual'` — Explicit `cache.delete()` call
64
+ */
65
+ export type EvictionReason = 'capacity' | 'category' | 'rebalance' | 'oom' | 'ttl' | 'manual';
66
+
67
+ // ─── Ping result ─────────────────────────────────────────────────────────────
68
+
69
+ /** Per-tier latency returned by `cache.ping()`. */
70
+ export interface CachePingResult {
71
+ /** L1 RAM check latency in milliseconds */
72
+ l1: number;
73
+ /** L1.5 disk stats access in milliseconds */
74
+ disk: number;
75
+ /** L2 Redis PING round-trip in milliseconds, or `null` when Redis is disabled */
76
+ l2: number | null;
77
+ }
78
+
79
+ // ─── Cache priorities ────────────────────────────────────────────────────────
80
+
81
+ /** Priority levels for L1 eviction — higher = less likely to be evicted */
82
+ export enum CachePriority {
83
+ LOW = 1, // Easily regenerated (analytics, reports)
84
+ NORMAL = 2, // General data
85
+ HIGH = 3, // Frequently accessed (profiles, config)
86
+ CRITICAL = 4, // Must never be evicted unless expired (auth tokens, active sessions)
87
+ }
88
+
89
+ // ─── Internal L1 entry shape ─────────────────────────────────────────────────
90
+
91
+ /** Internal representation of a single cache entry in the L1 Map */
92
+ export interface SmartCacheEntry {
93
+ /** msgpackr-packed binary payload — used for disk spill and snapshot serialization */
94
+ data: Buffer;
95
+ /**
96
+ * Deserialized JS value, cached at write time so hot reads skip the unpack step entirely.
97
+ * Undefined for entries restored from disk/snapshot (populated lazily on first access).
98
+ * NOTE: returned by reference — callers should treat the value as immutable.
99
+ */
100
+ value?: unknown;
101
+ /** always true for entries written by the current code;
102
+ * may be false in legacy snapshots/disk files — handled transparently on import */
103
+ isCompressed: boolean;
104
+ /** Hard expiry — entry is deleted after this timestamp */
105
+ expiresAt: number;
106
+ /** SWR soft expiry — serve stale + revalidate in background when past this */
107
+ staleAt?: number;
108
+ /** Exact byte size of the stored value */
109
+ size: number;
110
+ /** Access count (LFU numerator) */
111
+ hits: number;
112
+ /** Last access timestamp (LRU comparator) */
113
+ lastAccess: number;
114
+ /** Eviction priority */
115
+ priority: CachePriority;
116
+ /** Original TTL in ms at write time — used by refresh-ahead to compute the proactive refresh threshold. */
117
+ ttlMs?: number;
118
+ /** Milliseconds taken to fetch/compute this value — used by XFetch probabilistic early expiration. */
119
+ delta?: number;
120
+ /**
121
+ * Unix timestamp (ms) when this entry was written.
122
+ * Stored explicitly so staleness-fence eviction (`evictSetBefore`) is precise
123
+ * instead of approximating via `expiresAt - ttlMs`.
124
+ * Optional for backward compatibility with snapshots written by older versions.
125
+ */
126
+ setAt?: number;
127
+ /** Active tag versions at write time (used when tagStrategy === 'generational') */
128
+ tagVersions?: Record<string, number>;
129
+ }
130
+
131
+ /** Returned by SmartMemoryCache.get() — distinguishes "cached null" from a real miss */
132
+ export interface CacheHit {
133
+ value: unknown;
134
+ /** true = past soft TTL (staleAt) but within hard expiry → SWR path */
135
+ isStale: boolean;
136
+ /** Hard expiry timestamp — lets CacheService.get() do refresh-ahead / XFetch math
137
+ * without a second Map lookup (eliminates the duplicate l1.getEntry() call). */
138
+ expiresAt: number;
139
+ /** Original TTL in ms stored at write time — for refresh-ahead fraction calculation */
140
+ ttlMs?: number;
141
+ /** Fetch duration in ms stored at write time — for XFetch probabilistic threshold */
142
+ delta?: number;
143
+ /** Timestamp (Date.now()) recorded inside SmartMemoryCache.get() — lets CacheService
144
+ * reuse this value for refresh-ahead/XFetch math instead of making a second syscall. */
145
+ fetchedAt?: number;
146
+ /** Active tag versions at write time (used when tagStrategy === 'generational') */
147
+ tagVersions?: Record<string, number>;
148
+ /** Timestamp (ms) when this entry was written into memory */
149
+ setAt?: number;
150
+ }
151
+
152
+ // ─── Disk tier ───────────────────────────────────────────────────────────────
153
+
154
+ /** On-disk entry shape (mirrors SmartCacheEntry — Uint8Array accepted for msgpack round-trips;
155
+ * legacy disk files written by older versions may have a JSON string in data) */
156
+ export interface DiskCacheEntry {
157
+ data: string | Buffer | Uint8Array;
158
+ isCompressed: boolean;
159
+ expiresAt: number;
160
+ staleAt?: number;
161
+ size: number;
162
+ hits: number;
163
+ lastAccess: number;
164
+ priority: number;
165
+ /** Active tag versions at write time (used when tagStrategy === 'generational') */
166
+ tagVersions?: Record<string, number>;
167
+ }
168
+
169
+ // ─── Metrics snapshot ────────────────────────────────────────────────────────
170
+
171
+ /**
172
+ * Snapshot of runtime metrics for a CacheService instance.
173
+ * Returned by `CacheService.metrics()` and passed to the `onMetrics` callback.
174
+ * Convert to Prometheus text with `CacheService.toPrometheusText(metrics)`.
175
+ */
176
+ export interface CacheMetrics {
177
+ /** Configured namespace (empty string = no namespace) */
178
+ namespace: string;
179
+ /** Milliseconds since the CacheService instance was constructed */
180
+ uptimeMs: number;
181
+
182
+ gets: {
183
+ total: number;
184
+ l1Hits: number;
185
+ /** Fraction of gets served from L1 RAM cache (0–1) */
186
+ l1HitRate: number;
187
+ diskHits: number;
188
+ /** Fraction of gets served from L1.5 disk tier (0–1) */
189
+ diskHitRate: number;
190
+ l2Hits: number;
191
+ /** Fraction of gets served from L2 Redis (0–1) */
192
+ l2HitRate: number;
193
+ /** fetchFn calls (cache misses that fell through to the DB) */
194
+ fetches: number;
195
+ /** Fraction of gets that called fetchFn (0–1) */
196
+ fetchRate: number;
197
+ /** Concurrent get() calls deduplicated by the stampede guard */
198
+ stampedePrevented: number;
199
+ };
200
+
201
+ sets: { total: number };
202
+ deletes: { total: number };
203
+ revalidations: { total: number };
204
+
205
+ /** Rate-limit / singleton diagnostics */
206
+ counters: {
207
+ /** Times `increment()` hit a Redis error (fail-open by default, or fail-closed re-throw). */
208
+ errors: number;
209
+ /** Times a later `create(ns)` call passed options diverging from the live singleton. */
210
+ singletonDivergences: number;
211
+ };
212
+
213
+ bloom: {
214
+ /** Total bloom-filter checks (get() calls that passed prefix filter) */
215
+ checksTotal: number;
216
+ /**
217
+ * Times the filter said "might contain" but the key was absent in L1.
218
+ * A high rate suggests the bloom filter capacity needs increasing.
219
+ */
220
+ falsePositives: number;
221
+ /** falsePositives / checksTotal (0–1; ideal < 0.01) */
222
+ falsePositiveRate: number;
223
+ };
224
+
225
+ compression: {
226
+ entriesCompressed: number;
227
+ entriesUncompressed: number;
228
+ /** Approximate bytes saved by msgpackr vs raw JSON */
229
+ bytesSaved: number;
230
+ };
231
+
232
+ /** Invalidation backplane statistics */
233
+ backplane: {
234
+ enabled: boolean;
235
+ mode: 'pubsub' | 'stream';
236
+ /** Invalidation messages published to other instances */
237
+ sent: number;
238
+ /** Invalidation messages received from other instances */
239
+ received: number;
240
+ /** Own messages silently skipped (prevents double-eviction) */
241
+ skipped: number;
242
+ /** Stream entries received (when backplaneMode is 'stream') */
243
+ streamEntriesReceived?: number;
244
+ /** Replayed invalidations after network reconnect */
245
+ streamReplays?: number;
246
+ /** Stream trim gaps detected (where consumer fell behind oldest entry) */
247
+ streamGaps?: number;
248
+ };
249
+
250
+ /** L2 Redis circuit breaker state */
251
+ l2CircuitBreaker: {
252
+ /** `'closed'` = normal; `'open'` = Redis paused; `'half_open'` = probing recovery */
253
+ state: 'closed' | 'open' | 'half_open';
254
+ };
255
+
256
+ /** OOM guard statistics */
257
+ oom: {
258
+ enabled: boolean;
259
+ /** Number of emergency L1 eviction rounds triggered */
260
+ evictions: number;
261
+ /** Timestamp of the most recent OOM eviction, or null */
262
+ lastTriggeredAt: number | null;
263
+ };
264
+
265
+ /** Remote snapshot statistics — present when remoteSnapshot is configured */
266
+ remoteSnapshot?: {
267
+ enabled: boolean;
268
+ uploads: number;
269
+ downloads: number;
270
+ errors: number;
271
+ lastUploadedAt: number | null;
272
+ lastDownloadedAt: number | null;
273
+ };
274
+
275
+ /** Cross-region invalidation relay statistics — present when crossRegion is configured */
276
+ crossRegion?: {
277
+ enabled: boolean;
278
+ currentRegion: string;
279
+ sent: number;
280
+ received: number;
281
+ deduplicated: number;
282
+ errors: number;
283
+ };
284
+
285
+ /** Auto-pipelining statistics — present when autoPipeline is enabled */
286
+ pipelining?: {
287
+ batchesDispatched: number;
288
+ operationsBatched: number;
289
+ pendingQueueSize: number;
290
+ };
291
+
292
+ l1: { entries: number; sizeBytes: number; maxBytes: number };
293
+ disk: {
294
+ files: number;
295
+ sizeKB: number;
296
+ maxKB: number;
297
+ disabled: boolean;
298
+ latencyWatchdog?: {
299
+ bypassActive: boolean;
300
+ bypassStage: 0 | 1 | 2 | 3;
301
+ diskP95Ms: number;
302
+ redisP95Ms: number;
303
+ redisDampened: boolean;
304
+ bypassedTotal: number;
305
+ };
306
+ pruning?: {
307
+ active: boolean;
308
+ pruneRounds: number;
309
+ entriesPruned: number;
310
+ spillsShedTotal: number;
311
+ hostVolumeLowSpacePauses: number;
312
+ };
313
+ };
314
+
315
+ /** Adaptive TTL statistics — present only when `adaptiveTtl` is enabled */
316
+ adaptiveTtl?: {
317
+ enabled: true;
318
+ /** Number of unique keys currently tracked in the latency ring buffers */
319
+ trackedKeys: number;
320
+ /**
321
+ * Top-20 slowest keys by p95 fetch latency, sorted descending.
322
+ * Keys are shown without the instance namespace prefix.
323
+ * Only keys with ≥ 5 recorded samples appear here.
324
+ */
325
+ slowestKeys: Array<{ key: string; p95Ms: number; adaptedTtlSec: number }>;
326
+ };
327
+ }
328
+
329
+ /**
330
+ * Result returned by cache.health()
331
+ *
332
+ * NOTE: Intended strictly for Kubernetes Readiness probes (/ready).
333
+ * Do NOT hook into Liveness probes (/healthz), as degraded caches should shed ingress
334
+ * traffic while keeping the container alive to heal local storage and drain in-flight tasks.
335
+ */
336
+ export interface CacheHealthStatus {
337
+ healthy: boolean;
338
+ degraded: boolean;
339
+ reasons: string[];
340
+ details?: Record<string, unknown>;
341
+ }
342
+
343
+ // ─── Configuration ───────────────────────────────────────────────────────────
344
+
345
+ /** Per-category memory limits for L1 */
346
+ export interface CategoryLimit {
347
+ maxEntries: number;
348
+ maxSizeBytes: number;
349
+ }
350
+
351
+ /**
352
+ * Supported opinionated pre-configurations for CacheService.preset()
353
+ */
354
+ export type CachePresetType = 'nextjs' | 'microservice' | 'serverless' | 'enterprise-hardened';
355
+
356
+ /**
357
+ * Options accepted by CacheService.create()
358
+ *
359
+ * All fields are optional — sensible defaults are used when omitted.
360
+ */
361
+ export interface CacheOptions {
362
+ /**
363
+ * Plug in your own logger (pino, winston, bunyan, …).
364
+ * Defaults to a minimal console logger that only prints warn/error.
365
+ */
366
+ logger?: ILogger;
367
+
368
+ // ── L1 (in-memory) ────────────────────────────────────────────────────────
369
+ /** Max total bytes held in L1 RAM cache. Default: 200 MB */
370
+ l1MaxBytes?: number;
371
+ /** Max total entries in L1. Default: 2000 */
372
+ l1MaxEntries?: number;
373
+ /**
374
+ * Fraction of `l1MaxEntries` / `l1MaxBytes` at which proactive eviction fires
375
+ * before the hard limit is reached. Range: 0–1. Default: 0.9.
376
+ * Lower (e.g. 0.8) reduces GC pressure at the cost of slightly more eviction work.
377
+ */
378
+ l1EvictionWatermark?: number;
379
+ /**
380
+ * Per-category limits keyed by the key prefix (e.g. `'org:'`).
381
+ * Merged over the built-in defaults.
382
+ */
383
+ categoryLimits?: Record<string, CategoryLimit>;
384
+ /**
385
+ * Key prefixes that are never written to disk snapshots or the disk tier.
386
+ * Default: ['auth:', 'session:', 'mfa:', 'rate_limit:']
387
+ */
388
+ forbiddenSnapshotPrefixes?: string[];
389
+ /**
390
+ * L1 cache admission and eviction policy:
391
+ * - `'wtinylfu'`: Window TinyLFU admission policy (popularized by Caffeine) providing
392
+ * mathematical scan resistance and burst recency absorption.
393
+ * - `'adaptive'`: Adaptive LFU x LRU x priority reservoir sampling.
394
+ * Default: `'wtinylfu'`
395
+ */
396
+ l1AdmissionPolicy?: 'wtinylfu' | 'adaptive';
397
+
398
+ // ── L1.5 (disk tier) ────────────────────────────────────────────────────
399
+ /** Directory used for L1.5 disk-spill files. Default: os.tmpdir()/tricache-disk */
400
+ diskCacheDir?: string;
401
+ /** Max total bytes for the disk tier. Default: 500 MB */
402
+ diskMaxBytes?: number;
403
+ /** Max bytes for a single disk entry. Default: 10 MB */
404
+ diskEntryMaxBytes?: number;
405
+ /**
406
+ * Maximum concurrent asynchronous filesystem writes permitted in-flight for disk spills.
407
+ * Protects against libuv threadpool (UV_THREADPOOL_SIZE=4) saturation during cloud I/O throttling.
408
+ * Default: Math.min(4, Math.max(1, Math.floor(os.availableParallelism() / 4)))
409
+ */
410
+ diskMaxConcurrentWrites?: number;
411
+ /**
412
+ * Maximum queued spill writes awaiting execution before shedding kicks in.
413
+ * Once pending writes hit this limit, incoming spills are dropped without touching libuv.
414
+ * Default: 512
415
+ */
416
+ diskMaxPendingWrites?: number;
417
+ /**
418
+ * Maximum time permitted for an individual write before timing out and tripping backpressure.
419
+ * Default: 500 ms
420
+ */
421
+ diskWriteTimeoutMs?: number;
422
+ /**
423
+ * Number of consecutive slow or failed disk writes before tripping the disk circuit breaker to OPEN.
424
+ * Default: 5
425
+ */
426
+ diskCircuitBreakerThreshold?: number;
427
+ /**
428
+ * Cooldown time in ms before transitioning the disk circuit breaker from OPEN to HALF-OPEN for canary probing.
429
+ * Default: 5000 ms
430
+ */
431
+ diskCircuitBreakerCooldownMs?: number;
432
+ /**
433
+ * Enable dynamic tier latency watchdog.
434
+ * Compares disk read latency against Redis and automatically sheds traffic to Redis when disk slows down.
435
+ * Default: true
436
+ */
437
+ diskLatencyWatchdog?: boolean;
438
+ /**
439
+ * Ratio of disk p95 latency to Redis p95 latency required to trip bypass.
440
+ * Default: 1.5
441
+ */
442
+ diskLatencyBypassRatio?: number;
443
+ /**
444
+ * Minimum disk p95 latency floor in ms before bypass can be considered.
445
+ * Default: 10 ms
446
+ */
447
+ diskLatencyBypassMinMs?: number;
448
+ /**
449
+ * Cooldown time in ms before probing canary during Stage 3 bypass.
450
+ * Subject to ±30% anti-synchronicity jitter.
451
+ * Default: 30_000 ms
452
+ */
453
+ diskLatencyBypassCooldownMs?: number;
454
+ /**
455
+ * When true, cache.health().healthy returns false when degraded, causing
456
+ * Kubernetes readiness probes to fail and route traffic away from this pod.
457
+ * Default: false (graceful local degradation without failing readiness)
458
+ */
459
+ failReadinessOnDegraded?: boolean;
460
+
461
+ // ── L2 (Redis) ────────────────────────────────────────────────────────────
462
+ /**
463
+ * Redis/Valkey hostname (no `redis://` prefix).
464
+ * Falls back to the `REDIS_HOST` environment variable.
465
+ * When neither is provided, L2 is disabled.
466
+ */
467
+ redisHost?: string;
468
+ /** Redis port. Default: 6379 */
469
+ redisPort?: number;
470
+ /**
471
+ * Strict per-command timeout for Redis operations.
472
+ * When expired, triggers connection reset / socket destruction to prevent RESP multiplexing desync.
473
+ * Default: 2500 ms
474
+ */
475
+ redisCommandTimeoutMs?: number;
476
+ /**
477
+ * Coalesce Redis operations executed within the identical synchronous tick into a single pipeline round-trip via queueMicrotask.
478
+ * Eliminates syscall and network overhead under heavy concurrent traffic with 0ms event-loop delay.
479
+ * Default: false
480
+ */
481
+ autoPipeline?: boolean;
482
+ /**
483
+ * Maximum batch size for auto-pipelined Redis requests before forcing an immediate dispatch.
484
+ * Default: 100
485
+ */
486
+ maxPipelineBatchSize?: number;
487
+ /**
488
+ * Clock skew tolerance window in milliseconds across cluster nodes / containers.
489
+ * Allows timestamps within this tolerance ahead of the local clock to prevent premature eviction anomalies.
490
+ * Default: 250 ms
491
+ */
492
+ clockSkewToleranceMs?: number;
493
+ /**
494
+ * Whether to enable TLS for the Redis connection. Default: true in production,
495
+ * false otherwise.
496
+ */
497
+ redisTls?: boolean;
498
+ /**
499
+ * Redis wire protocol version (RESP2 or RESP3).
500
+ * Defaults to 3 in ioredis v6+. Set to 2 for legacy proxies or servers without RESP3 support.
501
+ */
502
+ redisProtocol?: 2 | 3;
503
+ /**
504
+ * Set to `true` to disable L2 Redis entirely (e.g. when running single-process
505
+ * services that don't need distributed caching). Default: false in production,
506
+ * true in development.
507
+ */
508
+ disableRedis?: boolean;
509
+
510
+ /**
511
+ * Pre-existing or custom Redis client or driver adapter (e.g. `NodeRedisAdapter` wrapping
512
+ * `@redis/client`, or a pre-configured `ioredis` instance).
513
+ * When supplied, TriCache bypasses internal connection construction and uses this client directly.
514
+ */
515
+ redisClient?: IRedisDriver | any;
516
+
517
+ /**
518
+ * Dedicated subscriber client for Redis Pub/Sub invalidation backplane.
519
+ * If omitted and `redisClient` supports `.duplicate()`, TriCache will duplicate `redisClient`.
520
+ */
521
+ redisSubClient?: IRedisDriver | any;
522
+
523
+ // ── Encryption ────────────────────────────────────────────────────────────
524
+ /**
525
+ * Base64-encoded 32-byte AES-256-GCM key for encrypting L2 (Redis) values and
526
+ * disk-tier files at rest. Falls back to `CACHE_ENCRYPTION_KEY` env var.
527
+ * If not provided in production, a warning is logged and data is stored plaintext.
528
+ */
529
+ encryptionKey?: string;
530
+ /**
531
+ * Encryption algorithm used for L2 (Redis) values and disk-tier files.
532
+ * - `'aes-256-gcm'` — default. 32-byte key. Authenticated encryption (AEAD).
533
+ * - `'aes-128-gcm'` — 16-byte key. ~10% faster on non-AES-NI hardware. AEAD.
534
+ * - `'xor'` — XOR obfuscation ONLY. NOT cryptographic security.
535
+ * Any key length (minimum 16 bytes recommended).
536
+ * Use for dev environments or non-sensitive data only.
537
+ * Default: `'aes-256-gcm'`
538
+ */
539
+ encryptionMode?: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
540
+ /**
541
+ * Fallback encryption key for zero-downtime key rotation.
542
+ * On every read, tricache tries the current `encryptionKey` first.
543
+ * If decryption fails (wrong key), it retries with `previousEncryptionKey`.
544
+ * All writes always use the current `encryptionKey`.
545
+ * Remove this field once you are confident all data has been re-encrypted.
546
+ */
547
+ previousEncryptionKey?: string;
548
+ /** Encryption mode that was used with `previousEncryptionKey`. Defaults to `encryptionMode`. */
549
+ previousEncryptionMode?: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
550
+ /**
551
+ * Fail closed when `encryptionKey` is present but INVALID (wrong length for the
552
+ * selected `encryptionMode`, or empty). Default: `false` — tricache logs an error
553
+ * and continues with at-rest encryption DISABLED (fail-open, backward compatible).
554
+ * Set to `true` for deployments where serving plaintext at rest is unacceptable:
555
+ * the constructor then throws instead of silently downgrading security.
556
+ * Has no effect when no key is configured at all (encryption stays off, by design).
557
+ */
558
+ strictKeyValidation?: boolean;
559
+
560
+ // ── Serialization & Codec (msgpackr) ────────────────────────────────────
561
+ /**
562
+ * Whether to call `.toJSON()` when serializing objects into binary cache buffers.
563
+ * - `true` (default): Honors `.toJSON()`, matching standard JSON serialization conventions.
564
+ * - `false`: Preserves the object's own internal properties (msgpackr 2.1.0+ durable state feature),
565
+ * avoiding accidental API response projections on cached domain entities.
566
+ */
567
+ serializeToJSON?: boolean;
568
+
569
+ // ── Compression ──────────────────────────────────────────────────────────
570
+ /**
571
+ * Optional compression algorithm for L2 (Redis) strings and disk-tier binary blobs.
572
+ * - `'brotli'` (default when enabled) — superior compression ratio for JSON / text payloads.
573
+ * - `'gzip'` — faster compression / lower CPU overhead.
574
+ * - `'none'` — disable compression.
575
+ * Default: `'none'` (uncompressed).
576
+ */
577
+ compression?: 'brotli' | 'gzip' | 'none';
578
+ /**
579
+ * Minimum payload size in bytes before compression is applied.
580
+ * Payloads smaller than this threshold remain uncompressed to avoid compression overhead.
581
+ * Default: `1024` (1 KB).
582
+ */
583
+ compressionThresholdBytes?: number;
584
+
585
+ // ── Snapshot ────────────────────────────────────────────────────────────
586
+ /**
587
+ * Path where the cold-start snapshot is written on SIGTERM/SIGINT and loaded
588
+ * on startup. Default: os.tmpdir()/tricache-snapshot.msgpack
589
+ */
590
+ snapshotPath?: string;
591
+ /**
592
+ * Max age (ms) of a snapshot file before it is rejected. Default: 2 hours
593
+ */
594
+ snapshotMaxAgeMs?: number;
595
+ /**
596
+ * Optional remote blob storage snapshot configuration for stateless containers (S3, GCS, R2, HTTP).
597
+ * Enables persisting and hydrating L1 RAM cache snapshots across Kubernetes / container deployments.
598
+ */
599
+ remoteSnapshot?: RemoteSnapshotOptions;
600
+
601
+ /**
602
+ * Optional namespace prefix for all cache keys.
603
+ *
604
+ * When set, every key is transparently stored as `${namespace}:${key}` in
605
+ * L1, L1.5 (disk), and L2 (Redis). This enables:
606
+ * - **Multi-tenant isolation**: `CacheService.create({ namespace: 'org_abc' })`
607
+ * — tenants sharing the same Redis instance or disk dir are fully isolated.
608
+ * - **Environment separation**: `CacheService.create({ namespace: 'staging' })`
609
+ * - **Service-level scoping**: microservices sharing one Redis without key collisions.
610
+ *
611
+ * Consumers never see the prefix — `get('user:1')` behaves identically
612
+ * whether namespaced or not. Glob deletes (`delete('user:*')`) automatically
613
+ * scope to the namespace.
614
+ *
615
+ * The process-level singleton, disk cache directory, and cold-start snapshot
616
+ * path are all scoped per namespace, so two `CacheService.create()` calls
617
+ * with different namespaces return completely independent instances.
618
+ *
619
+ * Default: `''` (no prefix)
620
+ */
621
+ namespace?: string;
622
+
623
+ /**
624
+ * Seconds to extend a stale SWR entry's life when background revalidation fails.
625
+ * Without this, a failed revalidation leaves the entry stale until its hard TTL
626
+ * expires, after which the next caller blocks. With `staleIfError`, tricache bumps
627
+ * the expiry by this many seconds on every failed revalidation, keeping the stale
628
+ * value available while the underlying service is degraded.
629
+ * Default: `0` (disabled — entry expires normally on revalidation failure).
630
+ */
631
+ staleIfError?: number;
632
+
633
+ /**
634
+ * Called after every L1 eviction. Receives the raw (namespaced) key and the reason.
635
+ * Useful for diagnosing cache pressure and tuning `categoryLimits`.
636
+ */
637
+ onEviction?: (key: string, reason: EvictionReason) => void;
638
+
639
+ /**
640
+ * Human-readable name for this CacheService instance. Added as an `instance` label
641
+ * to all Prometheus metrics emitted by `CacheService.toPrometheusText()`.
642
+ * Required when multiple CacheService instances share a process — without it,
643
+ * metric names from different instances collide.
644
+ * Default: `''` (no label).
645
+ */
646
+ instanceName?: string;
647
+
648
+ /**
649
+ * Controls whether writes are propagated to L2 (Redis).
650
+ * - `'read-write'` (default): read from and write to L2.
651
+ * - `'read-only'`: read from L2 but never write, delete, or expire keys in Redis.
652
+ * Use for shared read replicas or external Redis clusters you do not own.
653
+ */
654
+ l2WriteMode?: 'read-write' | 'read-only';
655
+
656
+ // ── Invalidation backplane (Redis Pub/Sub) ──────────────────────────────
657
+ /**
658
+ * Enable Redis Pub/Sub invalidation backplane so every running instance
659
+ * evicts a key from its L1 when any peer calls `set()` or `delete()`.
660
+ *
661
+ * Gives you sub-microsecond in-process cache speed with cluster-wide
662
+ * consistency across all your app servers.
663
+ *
664
+ * Default: `true` (auto-activates when Redis is available).
665
+ * Set to `false` for single-process services or eventual-consistency scenarios.
666
+ */
667
+ invalidationBackplane?: boolean;
668
+
669
+ /**
670
+ * Enable Redis 7+ Sharded Pub/Sub (`SPUBLISH` / `SSUBSCRIBE`) when connected to
671
+ * a Redis Cluster (`redisClusterNodes`). Scopes pub/sub message routing strictly
672
+ * to the cluster shard handling the key slot, reducing inter-node cluster bus gossip.
673
+ *
674
+ * Default: `false` (standard cluster PUBLISH / SUBSCRIBE).
675
+ */
676
+ useShardedPubSub?: boolean;
677
+
678
+ // ── Multi-Region / Cross-Cluster Invalidation Relay ─────────────────────
679
+ /**
680
+ * Optional cross-region invalidation relay configuration for geo-distributed deployments.
681
+ * Synchronizes `delete()` and `invalidateTag()` events across separate regional Redis clusters
682
+ * (e.g. `us-east-1` and `eu-central-1`) via HTTP mesh or custom message brokers (SNS, SQS, EventBridge)
683
+ * with automatic origin deduplication to prevent invalidation loops.
684
+ */
685
+ crossRegion?: CrossRegionRelayOptions;
686
+
687
+ // ── OOM protection ──────────────────────────────────────────────────────
688
+ /**
689
+ * Enable the GC-aware OOM guard. When heap utilisation crosses
690
+ * `oomHeapThreshold`, a fraction of the coldest L1 entries are
691
+ * emergency-evicted to L1.5 disk, preventing Node.js OOM crashes inside
692
+ * Docker/Kubernetes containers with tight memory limits.
693
+ *
694
+ * Default: `true`
695
+ */
696
+ oomProtection?: boolean;
697
+ /**
698
+ * Heap-used / heap-total ratio that triggers emergency eviction.
699
+ * Default: `0.85` (85 %)
700
+ */
701
+ oomHeapThreshold?: number;
702
+ /** Milliseconds between heap-pressure checks. Default: 10 000 ms (10 s) */
703
+ oomCheckIntervalMs?: number;
704
+ /** Fraction of L1 entries to evict per OOM round. Default: `0.20` (20 %) */
705
+ oomEvictPercent?: number;
706
+
707
+ // ── Metrics / observability ─────────────────────────────────────────────
708
+ /**
709
+ * Callback invoked periodically with a `CacheMetrics` snapshot.
710
+ * Wire up to OpenTelemetry, Prometheus push gateway, Datadog, etc.
711
+ *
712
+ * @example
713
+ * onMetrics: (m) => statsd.gauge('cache.l1_hit_rate', m.gets.l1HitRate)
714
+ */
715
+ onMetrics?: (metrics: CacheMetrics) => void;
716
+ /** How often the `onMetrics` callback fires (ms). Default: 60 000 ms */
717
+ metricsIntervalMs?: number;
718
+
719
+ /**
720
+ * Enable local IPC telemetry server (Unix domain socket on POSIX, Windows Named Pipe on win32)
721
+ * allowing external monitors like `tricache top` to inspect this instance.
722
+ * Default: `false`.
723
+ */
724
+ enableIpc?: boolean;
725
+ /**
726
+ * Custom socket path or Windows named pipe path for the IPC telemetry server.
727
+ * Default: `/tmp/tricache-<pid>.sock` (POSIX) or `\\.\pipe\tricache-<pid>` (Windows).
728
+ */
729
+ ipcSocketPath?: string;
730
+
731
+ /**
732
+ * OpenTelemetry-compatible tracer. When provided, `get()`, `set()`, and
733
+ * `delete()` are each wrapped in a span with attributes:
734
+ * - `cache.hit` — `'l1' | 'disk' | 'l2' | 'miss'`
735
+ * - `cache.key_prefix` — first path segment of the key (e.g. `'user'`)
736
+ *
737
+ * Pass your existing `@opentelemetry/api` Tracer directly — no extra
738
+ * dependency required; the interface is structurally compatible.
739
+ *
740
+ * @example
741
+ * import { trace } from '@opentelemetry/api';
742
+ * tracer: trace.getTracer('tricache')
743
+ */
744
+ tracer?: ICacheTracer;
745
+
746
+ // ── TTL jitter ─────────────────────────────────────────────────────────────
747
+ /**
748
+ * Randomise every stored TTL by ± `ttlJitterFactor × ttl` seconds.
749
+ * Prevents thundering-herd cache stampedes when thousands of entries share
750
+ * the same TTL and expire simultaneously.
751
+ *
752
+ * A factor of `0.15` spreads a 300 s TTL uniformly over [255 s, 345 s].
753
+ * Default: `0` (disabled — TTLs are stored exactly as given).
754
+ */
755
+ ttlJitterFactor?: number;
756
+
757
+ // ── L2 circuit breaker ─────────────────────────────────────────────────────
758
+ /**
759
+ * Default TTL in seconds for `null` or `undefined` results from `fetchFn`.
760
+ * Caches negative results so a non-existent key (deleted user, bad ID) does not
761
+ * hit the DB on every request. Can be overridden per-call via `get(..., { notFoundTtl }).
762
+ * Default: `0` (disabled — null/undefined uses the normal TTL).
763
+ */
764
+ notFoundTtl?: number;
765
+
766
+ /**
767
+ * Number of consecutive Redis errors before the circuit opens (stops
768
+ * attempting Redis until the cooldown elapses).
769
+ * Default: `5`.
770
+ */
771
+ l2CircuitBreakerThreshold?: number;
772
+ /**
773
+ * Milliseconds the circuit stays open before transitioning to half-open
774
+ * (allows a single probe request to test recovery).
775
+ * Default: `30 000` ms (30 s).
776
+ */
777
+ l2CircuitBreakerCooldownMs?: number;
778
+ /**
779
+ * Redis key pattern to automatically warm L1 from at startup (e.g. `'user:*'`).
780
+ * `cache.ready()` returns a Promise that resolves once this warm-up completes.
781
+ * No-op when Redis is disabled or unreachable — safe to set unconditionally.
782
+ */
783
+ warmKeys?: string;
784
+
785
+ /**
786
+ * Called on every L1, disk, or L2 cache hit. Receives the caller-facing key (no
787
+ * namespace prefix) and the tier that served it. Useful for per-route hit-rate
788
+ * metrics without waiting for the `onMetrics` interval.
789
+ *
790
+ * @example
791
+ * onHit: (key, tier) => cloudwatch.putMetricData({ key, tier })
792
+ */
793
+ onHit?: (key: string, tier: 'l1' | 'disk' | 'l2') => void;
794
+
795
+ /**
796
+ * Called on every cache miss (after L1, disk, and L2 are all exhausted).
797
+ * Receives the caller-facing key (no namespace prefix).
798
+ *
799
+ * @example
800
+ * onMiss: (key) => cloudwatch.putMetricData({ key })
801
+ */
802
+ onMiss?: (key: string) => void;
803
+
804
+ /**
805
+ * When `true`, every value returned from an L1 cache hit is recursively
806
+ * frozen with `Object.freeze()` before being handed to the caller.
807
+ * Any attempt to mutate the returned object throws a `TypeError` immediately,
808
+ * catching reference-semantic corruption bugs that would otherwise silently
809
+ * corrupt the cached entry.
810
+ *
811
+ * **Do not enable in production** — use `process.env.NODE_ENV !== 'production'`.
812
+ * Deep-freezing large objects has measurable overhead per hit.
813
+ *
814
+ * @example
815
+ * frozen: process.env.NODE_ENV !== 'production'
816
+ */
817
+ frozen?: boolean;
818
+
819
+ // ── Adaptive TTL ──────────────────────────────────────────────────────────
820
+
821
+ /**
822
+ * When `true`, tricache tracks per-key fetch latency in a rolling ring buffer
823
+ * and automatically derives an optimal TTL from the p95 fetch duration:
824
+ *
825
+ * ```
826
+ * adaptedTtl = clamp(p95LatencyMs × adaptiveTtlMultiplier, adaptiveTtlMin, adaptiveTtlMax)
827
+ * ```
828
+ *
829
+ * The caller-supplied `ttlSeconds` is used until at least 5 samples are collected
830
+ * for a key, then the library takes over TTL management autonomously.
831
+ *
832
+ * Expensive keys (slow DB queries) get cached longer; cheap keys stay close to
833
+ * their base TTL. Callers no longer need to reason about individual TTL values.
834
+ *
835
+ * Default: `false`.
836
+ */
837
+ adaptiveTtl?: boolean;
838
+
839
+ /**
840
+ * Minimum TTL (seconds) the adaptive tuner will ever assign.
841
+ * Guards against extremely fast fetches producing near-zero TTLs.
842
+ * Default: `10`.
843
+ */
844
+ adaptiveTtlMin?: number;
845
+
846
+ /**
847
+ * Maximum TTL (seconds) the adaptive tuner will ever assign.
848
+ * Guards against pathologically slow fetches producing indefinite caching.
849
+ * Default: `86400` (24 hours).
850
+ */
851
+ adaptiveTtlMax?: number;
852
+
853
+ /**
854
+ * `p95FetchLatencyMs × adaptiveTtlMultiplier = adaptedTtlSeconds`.
855
+ *
856
+ * Intuition: a 200 ms p95 fetch with the default multiplier of 20 yields a
857
+ * 4-second TTL. A 2 000 ms fetch yields 40 seconds. Increase the multiplier
858
+ * if you want the cache to absorb more upstream pressure.
859
+ *
860
+ * Default: `20`.
861
+ */
862
+ adaptiveTtlMultiplier?: number;
863
+
864
+ /**
865
+ * Number of fetch duration samples kept per key in the ring buffer.
866
+ * Larger values smooth out latency spikes but use slightly more memory
867
+ * (~8 bytes × samples per tracked key).
868
+ * Default: `32`.
869
+ */
870
+ adaptiveTtlSamples?: number;
871
+
872
+ /**
873
+ * Maximum number of distinct keys tracked by the adaptive TTL system.
874
+ * When the cap is reached, the oldest-tracked key is evicted from the
875
+ * ring-buffer store to make room for the new key.
876
+ * Default: `5000`.
877
+ */
878
+ adaptiveTtlMaxKeys?: number;
879
+
880
+ // ── Worker-thread serialization offload ────────────────────────────────────
881
+ /**
882
+ * When `true`, tricache spawns a pool of worker threads and offloads AES-GCM
883
+ * encryption and decryption for large payloads to those threads, keeping the
884
+ * V8 main event loop free for concurrent HTTP requests.
885
+ *
886
+ * Only takes effect when `encryptionKey` is set — plaintext payloads are never
887
+ * serialized off-thread because `JSON.stringify/parse` is already fast.
888
+ *
889
+ * Default: `false`. Enable in long-running servers that write multi-megabyte
890
+ * encrypted payloads and observe event-loop latency spikes.
891
+ */
892
+ workerThreads?: boolean;
893
+ /**
894
+ * Byte threshold above which an L2 payload is offloaded to a worker thread
895
+ * for encryption / decryption. Payloads smaller than this are processed
896
+ * synchronously (IPC overhead would exceed the savings).
897
+ * Default: `131072` (128 KB).
898
+ */
899
+ workerThresholdBytes?: number;
900
+ /**
901
+ * Number of worker threads in the pool.
902
+ * Default: `Math.min(4, os.availableParallelism())`.
903
+ */
904
+ workerPoolSize?: number;
905
+
906
+ // ── Backplane staleness fence ───────────────────────────────────────────────
907
+ /**
908
+ * Maximum milliseconds the Redis Pub/Sub subscriber is allowed to be
909
+ * disconnected before tricache considers its L1 entries potentially stale.
910
+ *
911
+ * When the subscriber reconnects after a gap longer than this value, all L1
912
+ * entries that were written *before* the disconnect started are evicted.
913
+ * This prevents the instance from silently serving data that peers may have
914
+ * invalidated while the backplane connection was down.
915
+ *
916
+ * Set to `0` to disable the fence entirely (accept eventual-consistency drift).
917
+ * Default: `5000` (5 seconds).
918
+ */
919
+ backplaneMaxStalenessMs?: number;
920
+
921
+ // ── Disk tier ─────────────────────────────────────────────────────────────
922
+ /**
923
+ * Explicitly disable the L1.5 disk spill tier and cold-start snapshots.
924
+ *
925
+ * Tricache auto-detects common serverless / ephemeral-filesystem runtimes
926
+ * (AWS Lambda, Google Cloud Run, Google Cloud Functions, Azure Functions,
927
+ * Fly.io) and disables the disk tier automatically. Set this to `false` to
928
+ * override that detection and force the disk tier on regardless of runtime.
929
+ *
930
+ * When disabled:
931
+ * - L1 evictions are dropped instead of being spilled to disk.
932
+ * - Cold-start snapshot persistence is skipped.
933
+ * - The `disk` metrics field still appears but shows zeroed counters.
934
+ *
935
+ * Default: `undefined` (auto-detect).
936
+ */
937
+ disableDisk?: boolean;
938
+
939
+ // ── Redis Cluster / Sentinel ───────────────────────────────────────────────
940
+ /**
941
+ * Redis Cluster node list. When provided, tricache connects using ioredis
942
+ * `Cluster` mode with automatic slot routing and multi-node connection
943
+ * pooling — no external proxy required.
944
+ *
945
+ * Takes precedence over `redisHost`/`redisPort`.
946
+ *
947
+ * @example
948
+ * redisClusterNodes: [
949
+ * { host: 'redis-1.internal', port: 6379 },
950
+ * { host: 'redis-2.internal', port: 6379 },
951
+ * { host: 'redis-3.internal', port: 6379 },
952
+ * ]
953
+ */
954
+ redisClusterNodes?: Array<{ host: string; port: number }>;
955
+
956
+ /**
957
+ * Redis Sentinel configuration for high-availability setups.
958
+ * When provided, tricache connects through Sentinel for automatic
959
+ * primary failover — no static `redisHost` / `redisPort` needed.
960
+ *
961
+ * Takes precedence over `redisHost`/`redisPort` (but not over `redisClusterNodes`).
962
+ *
963
+ * @example
964
+ * redisSentinel: {
965
+ * name: 'mymaster',
966
+ * sentinels: [
967
+ * { host: 'sentinel-1.internal', port: 26379 },
968
+ * { host: 'sentinel-2.internal', port: 26379 },
969
+ * ],
970
+ * }
971
+ */
972
+ redisSentinel?: {
973
+ /** Logical name of the monitored master. Must match the Sentinel `monitor` config. */
974
+ name: string;
975
+ sentinels: Array<{ host: string; port: number }>;
976
+ };
977
+
978
+ /**
979
+ * When `true`, a second `CacheService.create()` call for an already-existing
980
+ * singleton (same namespace) whose options differ from the first call throws
981
+ * instead of silently returning the existing instance. Use in codebases where
982
+ * multiple init points could pass conflicting configuration (e.g. different
983
+ * Redis credentials or TTLs) and you want that class of bug to fail loudly.
984
+ *
985
+ * Default: `false` (warn once, return existing instance).
986
+ */
987
+ strictSingleton?: boolean;
988
+
989
+ /**
990
+ * `cache.increment()` distributed-rate-limit behaviour on a Redis error.
991
+ *
992
+ * Default: `false` (fail-open — on a Redis error the method returns `0`, so a
993
+ * caller's `if (count > LIMIT) reject()` guard never rejects during an outage).
994
+ * Set to `true` to instead re-throw the Redis error, letting the caller's limit
995
+ * guard enforce the limit even when Redis is unavailable.
996
+ */
997
+ failClosed?: boolean;
998
+
999
+ /**
1000
+ * Strategy used for tag-based cache invalidation:
1001
+ * - `'set'` (default): Traditional Redis Set tracking. Members are registered in Redis
1002
+ * sets and deleted individually on `invalidateTag()`. Best for low-to-medium cardinality tags.
1003
+ * - `'generational'`: Generational tag versioning ($O(1)$ invalidations). Tag invalidation
1004
+ * increments an atomic integer version counter in Redis and local memory. Entries store their
1005
+ * creation tag versions; stale entries are detected on access and pruned with version-gated
1006
+ * compare-and-delete. Eliminates key scans and Redis bulk deletion stalls on large datasets.
1007
+ */
1008
+ tagStrategy?: 'set' | 'generational';
1009
+
1010
+ /**
1011
+ * Milliseconds before an in-memory generational tag version is re-synced from Redis.
1012
+ * Bounds maximum partition/missed-broadcast staleness when using `tagStrategy: 'generational'`.
1013
+ * Default: `5000` ms (5 seconds).
1014
+ */
1015
+ tagVersionTtlMs?: number;
1016
+
1017
+ /**
1018
+ * Read safety strategy for returned cached objects:
1019
+ * - `'none'` (default): Returns raw in-memory references for sub-microsecond performance (~350 ns).
1020
+ * - `'structuredClone'`: Clones values via native `structuredClone()` on L1 hits, L2 promotions,
1021
+ * and fetch returns, preventing caller mutations from polluting the cached reference.
1022
+ * Supported types: plain objects, arrays, Dates, Maps, Sets, TypedArrays. Functions and class
1023
+ * prototype chains are not preserved.
1024
+ */
1025
+ cloneStrategy?: 'none' | 'structuredClone';
1026
+
1027
+ /**
1028
+ * Invalidation backplane transport mode:
1029
+ * - `'pubsub'` (default): Ephemeral Redis Pub/Sub (at-most-once delivery).
1030
+ * - `'stream'`: Durable Redis Streams (XADD/XREAD) with missed-event replay on reconnect.
1031
+ */
1032
+ backplaneMode?: 'pubsub' | 'stream';
1033
+
1034
+ /**
1035
+ * Maximum retained entries in the Redis invalidation stream (`MAXLEN ~ N`).
1036
+ * Default: `10000`.
1037
+ */
1038
+ backplaneStreamMaxLen?: number;
1039
+
1040
+ /**
1041
+ * Blocking poll timeout in milliseconds for `XREAD BLOCK`.
1042
+ * Default: `2000` ms (2 seconds).
1043
+ */
1044
+ backplaneStreamBlockMs?: number;
1045
+
1046
+ /**
1047
+ * Custom Redis Stream key name.
1048
+ * Default: `tricache:stream:{<namespace>}` (hash-tagged for Redis Cluster single-slot routing).
1049
+ */
1050
+ backplaneStreamKey?: string;
1051
+
1052
+ /**
1053
+ * OpenTelemetry Meter instance for native metrics publishing.
1054
+ * Compatible with `@opentelemetry/api` Meter.
1055
+ */
1056
+ meter?: ICacheMeter;
1057
+ }
1058
+
1059
+ /**
1060
+ * Options for the ergonomic `cache.wrap(key, fetchFn, options)` method.
1061
+ */
1062
+ export interface WrapOptions {
1063
+ /** TTL in seconds (default: 300 s). */
1064
+ ttl?: number;
1065
+ /** Stale-While-Revalidate grace period in seconds. */
1066
+ swr?: number;
1067
+ /** Override the auto-inferred eviction priority. */
1068
+ priority?: CachePriority;
1069
+ /** Semantic tags for invalidation. */
1070
+ tags?: string[];
1071
+ /** Dependency cascade patterns (e.g. `['user:*']`). */
1072
+ dependsOn?: string[];
1073
+ /** 0–1 fraction of TTL elapsed at which a proactive background refresh is scheduled. */
1074
+ refreshAhead?: number;
1075
+ /** XFetch probabilistic early expiration factor (0.5–2.0). */
1076
+ xfetchBeta?: number;
1077
+ /** Override TTL in seconds for null/undefined fetch results (negative caching). */
1078
+ notFoundTtl?: number;
1079
+ }
1080
+
1081
+ /**
1082
+ * Options for distributed and in-process mutual exclusion locks via `cache.lock()`.
1083
+ */
1084
+ export interface LockOptions {
1085
+ /**
1086
+ * Lock auto-release TTL in seconds (default: 30 s).
1087
+ * Prevents deadlocks if the holding node crashes or is terminated.
1088
+ */
1089
+ ttl?: number;
1090
+ /**
1091
+ * Maximum time to wait to acquire the lock in milliseconds before throwing a timeout error.
1092
+ * Default: `5000` ms.
1093
+ */
1094
+ acquireTimeout?: number;
1095
+ /**
1096
+ * Polling retry interval in milliseconds when waiting for lock acquisition.
1097
+ * Default: `100` ms.
1098
+ */
1099
+ retryInterval?: number;
1100
+ }
1101
+
1102
+ /**
1103
+ * Structural typing matching OpenTelemetry Metric interfaces (`@opentelemetry/api`).
1104
+ */
1105
+ export interface ICacheCounter {
1106
+ add(value: number, attributes?: Record<string, string | number | boolean>): void;
1107
+ }
1108
+
1109
+ export interface ICacheObservableGauge {
1110
+ readonly _isGauge?: true;
1111
+ }
1112
+
1113
+ export interface ICacheBatchObservableCallback {
1114
+ (observableResult: {
1115
+ observe: (metric: ICacheObservableGauge, value: number, attributes?: Record<string, string | number | boolean>) => void;
1116
+ }): void | Promise<void>;
1117
+ }
1118
+
1119
+ export interface ICacheMeter {
1120
+ createCounter(name: string, options?: { description?: string; unit?: string }): ICacheCounter;
1121
+ createObservableGauge(name: string, options?: { description?: string; unit?: string }): ICacheObservableGauge;
1122
+ addBatchObservableCallback(callback: ICacheBatchObservableCallback, observables: ICacheObservableGauge[]): void;
1123
+ }
1124
+
1125
+ /**
1126
+ * Common pipeline / transaction interface matching ioredis and adapted drivers.
1127
+ */
1128
+ export interface IRedisPipeline {
1129
+ get(key: string): this;
1130
+ set(key: string, value: string, ...args: (string | number)[]): this;
1131
+ setex(key: string, seconds: number, value: string): this;
1132
+ del(...keys: string[]): this;
1133
+ expire(key: string, seconds: number): this;
1134
+ incr(key: string): this;
1135
+ sadd(key: string, ...members: string[]): this;
1136
+ smembers(key: string): this;
1137
+ hset(key: string, value: Record<string, string>): this;
1138
+ exec(): Promise<Array<[Error | null, any]> | null>;
1139
+ }
1140
+
1141
+ /**
1142
+ * Pluggable contract for external Redis drivers (e.g. `@redis/client` / `node-redis`,
1143
+ * custom connection pools, or pre-configured `ioredis` instances).
1144
+ */
1145
+ export interface IRedisDriver {
1146
+ get(key: string): Promise<string | null>;
1147
+ set(key: string, value: string, ...args: (string | number)[]): Promise<unknown>;
1148
+ setex?(key: string, seconds: number, value: string): Promise<unknown>;
1149
+ del(...keys: string[]): Promise<number>;
1150
+ ping(): Promise<string>;
1151
+ expire(key: string, seconds: number): Promise<number | boolean>;
1152
+ incr(key: string): Promise<number>;
1153
+ eval(script: string, numkeys: number, ...args: (string | number)[]): Promise<unknown>;
1154
+ multi(): IRedisPipeline;
1155
+ pipeline?(): IRedisPipeline;
1156
+ smembers?(key: string): Promise<string[]>;
1157
+ sadd?(key: string, ...members: string[]): Promise<number>;
1158
+ scan?(cursor: string, ...args: (string | number)[]): Promise<[string, string[]]>;
1159
+ scanStream?(options?: { match?: string; count?: number }): any;
1160
+ hset?(key: string, value: Record<string, string>): Promise<unknown>;
1161
+ publish?(channel: string, message: string): Promise<number>;
1162
+ subscribe?(...channels: string[]): Promise<unknown>;
1163
+ disconnect(): Promise<void> | void;
1164
+ quit?(): Promise<void> | void;
1165
+ duplicate?(): IRedisDriver;
1166
+ on?(event: string, listener: (...args: any[]) => void): this | unknown;
1167
+ once?(event: string, listener: (...args: any[]) => void): this | unknown;
1168
+ isOpen?: boolean;
1169
+ connect?(): Promise<unknown>;
1170
+ }
1171
+
1172
+ /**
1173
+ * Real-time telemetry and state for the disk tier backpressure queue.
1174
+ */
1175
+ export interface DiskBackpressureStats {
1176
+ activeWrites: number;
1177
+ pendingWrites: number;
1178
+ spillsDropped: number;
1179
+ circuitState: 'closed' | 'open' | 'half-open';
1180
+ lastTripTimestamp: number;
1181
+ }
1182
+
1183
+ /**
1184
+ * Telemetry metrics and counters for Window TinyLFU cache admission.
1185
+ */
1186
+ export interface WTinyLfuStats {
1187
+ capacity: number;
1188
+ size: number;
1189
+ windowSize: number;
1190
+ probationSize: number;
1191
+ protectedSize: number;
1192
+ hits: number;
1193
+ misses: number;
1194
+ hitRate: number;
1195
+ admissions: number;
1196
+ rejections: number;
1197
+ demotions: number;
1198
+ promotions: number;
1199
+ }