tricache 0.7.0 → 0.7.1

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 (40) hide show
  1. package/README.md +1428 -1428
  2. package/bin/tricache.js +8 -8
  3. package/dist/cache-service-5GATUYAK.js +7 -0
  4. package/dist/{cache-service-BblHuF3i.d.ts → cache-service-D8tIXmzb.d.ts} +23 -1
  5. package/dist/{chunk-3XQUQBOZ.js → chunk-EUGYR7KR.js} +87 -41
  6. package/dist/{chunk-PFB5FMEY.js → chunk-X5AXHPVD.js} +26 -15
  7. package/dist/cli.cjs +113 -56
  8. package/dist/cli.js +3 -3
  9. package/dist/drizzle/index.cjs +114 -57
  10. package/dist/drizzle/index.d.ts +1 -1
  11. package/dist/drizzle/index.js +1 -1
  12. package/dist/http/index.cjs +149 -64
  13. package/dist/http/index.d.ts +1 -1
  14. package/dist/http/index.js +38 -10
  15. package/dist/index.cjs +112 -55
  16. package/dist/index.d.ts +2 -2
  17. package/dist/index.js +2 -2
  18. package/dist/nestjs/index.cjs +112 -55
  19. package/dist/nestjs/index.d.ts +1 -1
  20. package/dist/nestjs/index.js +2 -2
  21. package/dist/next/index.cjs +143 -63
  22. package/dist/next/index.d.ts +10 -6
  23. package/dist/next/index.js +33 -10
  24. package/dist/prisma/index.cjs +2 -1
  25. package/dist/prisma/index.d.ts +1 -1
  26. package/dist/prisma/index.js +2 -1
  27. package/dist/serialize-worker.cjs +26 -15
  28. package/dist/serialize-worker.js +1 -1
  29. package/package.json +4 -2
  30. package/src/cache-service.ts +3294 -3226
  31. package/src/cli.ts +143 -143
  32. package/src/compression.ts +56 -63
  33. package/src/disk-tier.ts +821 -821
  34. package/src/encryption.ts +513 -493
  35. package/src/http/index.ts +265 -223
  36. package/src/next/cache-handler.ts +268 -244
  37. package/src/prisma/index.ts +154 -151
  38. package/src/smart-memory-cache.ts +1026 -1024
  39. package/src/types.ts +911 -902
  40. package/dist/cache-service-AJASH5FX.js +0 -7
package/src/types.ts CHANGED
@@ -1,902 +1,911 @@
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
+ /**
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
+ * Fail closed when `encryptionKey` is present but INVALID (wrong length for the
375
+ * selected `encryptionMode`, or empty). Default: `false` — tricache logs an error
376
+ * and continues with at-rest encryption DISABLED (fail-open, backward compatible).
377
+ * Set to `true` for deployments where serving plaintext at rest is unacceptable:
378
+ * the constructor then throws instead of silently downgrading security.
379
+ * Has no effect when no key is configured at all (encryption stays off, by design).
380
+ */
381
+ strictKeyValidation?: boolean;
382
+
383
+ // ── Compression ──────────────────────────────────────────────────────────
384
+ /**
385
+ * Optional compression algorithm for L2 (Redis) strings and disk-tier binary blobs.
386
+ * - `'brotli'` (default when enabled) — superior compression ratio for JSON / text payloads.
387
+ * - `'gzip'` — faster compression / lower CPU overhead.
388
+ * - `'none'` — disable compression.
389
+ * Default: `'none'` (uncompressed).
390
+ */
391
+ compression?: 'brotli' | 'gzip' | 'none';
392
+ /**
393
+ * Minimum payload size in bytes before compression is applied.
394
+ * Payloads smaller than this threshold remain uncompressed to avoid compression overhead.
395
+ * Default: `1024` (1 KB).
396
+ */
397
+ compressionThresholdBytes?: number;
398
+
399
+ // ── Snapshot ────────────────────────────────────────────────────────────
400
+ /**
401
+ * Path where the cold-start snapshot is written on SIGTERM/SIGINT and loaded
402
+ * on startup. Default: os.tmpdir()/tricache-snapshot.msgpack
403
+ */
404
+ snapshotPath?: string;
405
+ /**
406
+ * Max age (ms) of a snapshot file before it is rejected. Default: 2 hours
407
+ */
408
+ snapshotMaxAgeMs?: number;
409
+
410
+ /**
411
+ * Optional namespace prefix for all cache keys.
412
+ *
413
+ * When set, every key is transparently stored as `${namespace}:${key}` in
414
+ * L1, L1.5 (disk), and L2 (Redis). This enables:
415
+ * - **Multi-tenant isolation**: `CacheService.create({ namespace: 'org_abc' })`
416
+ * — tenants sharing the same Redis instance or disk dir are fully isolated.
417
+ * - **Environment separation**: `CacheService.create({ namespace: 'staging' })`
418
+ * - **Service-level scoping**: microservices sharing one Redis without key collisions.
419
+ *
420
+ * Consumers never see the prefix — `get('user:1')` behaves identically
421
+ * whether namespaced or not. Glob deletes (`delete('user:*')`) automatically
422
+ * scope to the namespace.
423
+ *
424
+ * The process-level singleton, disk cache directory, and cold-start snapshot
425
+ * path are all scoped per namespace, so two `CacheService.create()` calls
426
+ * with different namespaces return completely independent instances.
427
+ *
428
+ * Default: `''` (no prefix)
429
+ */
430
+ namespace?: string;
431
+
432
+ /**
433
+ * Seconds to extend a stale SWR entry's life when background revalidation fails.
434
+ * Without this, a failed revalidation leaves the entry stale until its hard TTL
435
+ * expires, after which the next caller blocks. With `staleIfError`, tricache bumps
436
+ * the expiry by this many seconds on every failed revalidation, keeping the stale
437
+ * value available while the underlying service is degraded.
438
+ * Default: `0` (disabled — entry expires normally on revalidation failure).
439
+ */
440
+ staleIfError?: number;
441
+
442
+ /**
443
+ * Called after every L1 eviction. Receives the raw (namespaced) key and the reason.
444
+ * Useful for diagnosing cache pressure and tuning `categoryLimits`.
445
+ */
446
+ onEviction?: (key: string, reason: EvictionReason) => void;
447
+
448
+ /**
449
+ * Human-readable name for this CacheService instance. Added as an `instance` label
450
+ * to all Prometheus metrics emitted by `CacheService.toPrometheusText()`.
451
+ * Required when multiple CacheService instances share a process — without it,
452
+ * metric names from different instances collide.
453
+ * Default: `''` (no label).
454
+ */
455
+ instanceName?: string;
456
+
457
+ /**
458
+ * Controls whether writes are propagated to L2 (Redis).
459
+ * - `'read-write'` (default): read from and write to L2.
460
+ * - `'read-only'`: read from L2 but never write, delete, or expire keys in Redis.
461
+ * Use for shared read replicas or external Redis clusters you do not own.
462
+ */
463
+ l2WriteMode?: 'read-write' | 'read-only';
464
+
465
+ // ── Invalidation backplane (Redis Pub/Sub) ──────────────────────────────
466
+ /**
467
+ * Enable Redis Pub/Sub invalidation backplane so every running instance
468
+ * evicts a key from its L1 when any peer calls `set()` or `delete()`.
469
+ *
470
+ * Gives you sub-microsecond in-process cache speed with cluster-wide
471
+ * consistency across all your app servers.
472
+ *
473
+ * Default: `true` (auto-activates when Redis is available).
474
+ * Set to `false` for single-process services or eventual-consistency scenarios.
475
+ */
476
+ invalidationBackplane?: boolean;
477
+
478
+ /**
479
+ * Enable Redis 7+ Sharded Pub/Sub (`SPUBLISH` / `SSUBSCRIBE`) when connected to
480
+ * a Redis Cluster (`redisClusterNodes`). Scopes pub/sub message routing strictly
481
+ * to the cluster shard handling the key slot, reducing inter-node cluster bus gossip.
482
+ *
483
+ * Default: `false` (standard cluster PUBLISH / SUBSCRIBE).
484
+ */
485
+ useShardedPubSub?: boolean;
486
+
487
+ // ── OOM protection ──────────────────────────────────────────────────────
488
+ /**
489
+ * Enable the GC-aware OOM guard. When heap utilisation crosses
490
+ * `oomHeapThreshold`, a fraction of the coldest L1 entries are
491
+ * emergency-evicted to L1.5 disk, preventing Node.js OOM crashes inside
492
+ * Docker/Kubernetes containers with tight memory limits.
493
+ *
494
+ * Default: `true`
495
+ */
496
+ oomProtection?: boolean;
497
+ /**
498
+ * Heap-used / heap-total ratio that triggers emergency eviction.
499
+ * Default: `0.85` (85 %)
500
+ */
501
+ oomHeapThreshold?: number;
502
+ /** Milliseconds between heap-pressure checks. Default: 10 000 ms (10 s) */
503
+ oomCheckIntervalMs?: number;
504
+ /** Fraction of L1 entries to evict per OOM round. Default: `0.20` (20 %) */
505
+ oomEvictPercent?: number;
506
+
507
+ // ── Metrics / observability ─────────────────────────────────────────────
508
+ /**
509
+ * Callback invoked periodically with a `CacheMetrics` snapshot.
510
+ * Wire up to OpenTelemetry, Prometheus push gateway, Datadog, etc.
511
+ *
512
+ * @example
513
+ * onMetrics: (m) => statsd.gauge('cache.l1_hit_rate', m.gets.l1HitRate)
514
+ */
515
+ onMetrics?: (metrics: CacheMetrics) => void;
516
+ /** How often the `onMetrics` callback fires (ms). Default: 60 000 ms */
517
+ metricsIntervalMs?: number;
518
+
519
+ /**
520
+ * OpenTelemetry-compatible tracer. When provided, `get()`, `set()`, and
521
+ * `delete()` are each wrapped in a span with attributes:
522
+ * - `cache.hit` — `'l1' | 'disk' | 'l2' | 'miss'`
523
+ * - `cache.key_prefix` — first path segment of the key (e.g. `'user'`)
524
+ *
525
+ * Pass your existing `@opentelemetry/api` Tracer directly — no extra
526
+ * dependency required; the interface is structurally compatible.
527
+ *
528
+ * @example
529
+ * import { trace } from '@opentelemetry/api';
530
+ * tracer: trace.getTracer('tricache')
531
+ */
532
+ tracer?: ICacheTracer;
533
+
534
+ // ── TTL jitter ─────────────────────────────────────────────────────────────
535
+ /**
536
+ * Randomise every stored TTL by ± `ttlJitterFactor × ttl` seconds.
537
+ * Prevents thundering-herd cache stampedes when thousands of entries share
538
+ * the same TTL and expire simultaneously.
539
+ *
540
+ * A factor of `0.15` spreads a 300 s TTL uniformly over [255 s, 345 s].
541
+ * Default: `0` (disabled — TTLs are stored exactly as given).
542
+ */
543
+ ttlJitterFactor?: number;
544
+
545
+ // ── L2 circuit breaker ─────────────────────────────────────────────────────
546
+ /**
547
+ * Default TTL in seconds for `null` or `undefined` results from `fetchFn`.
548
+ * Caches negative results so a non-existent key (deleted user, bad ID) does not
549
+ * hit the DB on every request. Can be overridden per-call via `get(..., { notFoundTtl }).
550
+ * Default: `0` (disabled — null/undefined uses the normal TTL).
551
+ */
552
+ notFoundTtl?: number;
553
+
554
+ /**
555
+ * Number of consecutive Redis errors before the circuit opens (stops
556
+ * attempting Redis until the cooldown elapses).
557
+ * Default: `5`.
558
+ */
559
+ l2CircuitBreakerThreshold?: number;
560
+ /**
561
+ * Milliseconds the circuit stays open before transitioning to half-open
562
+ * (allows a single probe request to test recovery).
563
+ * Default: `30 000` ms (30 s).
564
+ */
565
+ l2CircuitBreakerCooldownMs?: number;
566
+ /**
567
+ * Redis key pattern to automatically warm L1 from at startup (e.g. `'user:*'`).
568
+ * `cache.ready()` returns a Promise that resolves once this warm-up completes.
569
+ * No-op when Redis is disabled or unreachable — safe to set unconditionally.
570
+ */
571
+ warmKeys?: string;
572
+
573
+ /**
574
+ * Called on every L1, disk, or L2 cache hit. Receives the caller-facing key (no
575
+ * namespace prefix) and the tier that served it. Useful for per-route hit-rate
576
+ * metrics without waiting for the `onMetrics` interval.
577
+ *
578
+ * @example
579
+ * onHit: (key, tier) => cloudwatch.putMetricData({ key, tier })
580
+ */
581
+ onHit?: (key: string, tier: 'l1' | 'disk' | 'l2') => void;
582
+
583
+ /**
584
+ * Called on every cache miss (after L1, disk, and L2 are all exhausted).
585
+ * Receives the caller-facing key (no namespace prefix).
586
+ *
587
+ * @example
588
+ * onMiss: (key) => cloudwatch.putMetricData({ key })
589
+ */
590
+ onMiss?: (key: string) => void;
591
+
592
+ /**
593
+ * When `true`, every value returned from an L1 cache hit is recursively
594
+ * frozen with `Object.freeze()` before being handed to the caller.
595
+ * Any attempt to mutate the returned object throws a `TypeError` immediately,
596
+ * catching reference-semantic corruption bugs that would otherwise silently
597
+ * corrupt the cached entry.
598
+ *
599
+ * **Do not enable in production** — use `process.env.NODE_ENV !== 'production'`.
600
+ * Deep-freezing large objects has measurable overhead per hit.
601
+ *
602
+ * @example
603
+ * frozen: process.env.NODE_ENV !== 'production'
604
+ */
605
+ frozen?: boolean;
606
+
607
+ // ── Adaptive TTL ──────────────────────────────────────────────────────────
608
+
609
+ /**
610
+ * When `true`, tricache tracks per-key fetch latency in a rolling ring buffer
611
+ * and automatically derives an optimal TTL from the p95 fetch duration:
612
+ *
613
+ * ```
614
+ * adaptedTtl = clamp(p95LatencyMs × adaptiveTtlMultiplier, adaptiveTtlMin, adaptiveTtlMax)
615
+ * ```
616
+ *
617
+ * The caller-supplied `ttlSeconds` is used until at least 5 samples are collected
618
+ * for a key, then the library takes over TTL management autonomously.
619
+ *
620
+ * Expensive keys (slow DB queries) get cached longer; cheap keys stay close to
621
+ * their base TTL. Callers no longer need to reason about individual TTL values.
622
+ *
623
+ * Default: `false`.
624
+ */
625
+ adaptiveTtl?: boolean;
626
+
627
+ /**
628
+ * Minimum TTL (seconds) the adaptive tuner will ever assign.
629
+ * Guards against extremely fast fetches producing near-zero TTLs.
630
+ * Default: `10`.
631
+ */
632
+ adaptiveTtlMin?: number;
633
+
634
+ /**
635
+ * Maximum TTL (seconds) the adaptive tuner will ever assign.
636
+ * Guards against pathologically slow fetches producing indefinite caching.
637
+ * Default: `86400` (24 hours).
638
+ */
639
+ adaptiveTtlMax?: number;
640
+
641
+ /**
642
+ * `p95FetchLatencyMs × adaptiveTtlMultiplier = adaptedTtlSeconds`.
643
+ *
644
+ * Intuition: a 200 ms p95 fetch with the default multiplier of 20 yields a
645
+ * 4-second TTL. A 2 000 ms fetch yields 40 seconds. Increase the multiplier
646
+ * if you want the cache to absorb more upstream pressure.
647
+ *
648
+ * Default: `20`.
649
+ */
650
+ adaptiveTtlMultiplier?: number;
651
+
652
+ /**
653
+ * Number of fetch duration samples kept per key in the ring buffer.
654
+ * Larger values smooth out latency spikes but use slightly more memory
655
+ * (~8 bytes × samples per tracked key).
656
+ * Default: `32`.
657
+ */
658
+ adaptiveTtlSamples?: number;
659
+
660
+ /**
661
+ * Maximum number of distinct keys tracked by the adaptive TTL system.
662
+ * When the cap is reached, the oldest-tracked key is evicted from the
663
+ * ring-buffer store to make room for the new key.
664
+ * Default: `5000`.
665
+ */
666
+ adaptiveTtlMaxKeys?: number;
667
+
668
+ // ── Worker-thread serialization offload ────────────────────────────────────
669
+ /**
670
+ * When `true`, tricache spawns a pool of worker threads and offloads AES-GCM
671
+ * encryption and decryption for large payloads to those threads, keeping the
672
+ * V8 main event loop free for concurrent HTTP requests.
673
+ *
674
+ * Only takes effect when `encryptionKey` is set — plaintext payloads are never
675
+ * serialized off-thread because `JSON.stringify/parse` is already fast.
676
+ *
677
+ * Default: `false`. Enable in long-running servers that write multi-megabyte
678
+ * encrypted payloads and observe event-loop latency spikes.
679
+ */
680
+ workerThreads?: boolean;
681
+ /**
682
+ * Byte threshold above which an L2 payload is offloaded to a worker thread
683
+ * for encryption / decryption. Payloads smaller than this are processed
684
+ * synchronously (IPC overhead would exceed the savings).
685
+ * Default: `131072` (128 KB).
686
+ */
687
+ workerThresholdBytes?: number;
688
+ /**
689
+ * Number of worker threads in the pool.
690
+ * Default: `Math.min(4, os.availableParallelism())`.
691
+ */
692
+ workerPoolSize?: number;
693
+
694
+ // ── Backplane staleness fence ───────────────────────────────────────────────
695
+ /**
696
+ * Maximum milliseconds the Redis Pub/Sub subscriber is allowed to be
697
+ * disconnected before tricache considers its L1 entries potentially stale.
698
+ *
699
+ * When the subscriber reconnects after a gap longer than this value, all L1
700
+ * entries that were written *before* the disconnect started are evicted.
701
+ * This prevents the instance from silently serving data that peers may have
702
+ * invalidated while the backplane connection was down.
703
+ *
704
+ * Set to `0` to disable the fence entirely (accept eventual-consistency drift).
705
+ * Default: `5000` (5 seconds).
706
+ */
707
+ backplaneMaxStalenessMs?: number;
708
+
709
+ // ── Disk tier ─────────────────────────────────────────────────────────────
710
+ /**
711
+ * Explicitly disable the L1.5 disk spill tier and cold-start snapshots.
712
+ *
713
+ * Tricache auto-detects common serverless / ephemeral-filesystem runtimes
714
+ * (AWS Lambda, Google Cloud Run, Google Cloud Functions, Azure Functions,
715
+ * Fly.io) and disables the disk tier automatically. Set this to `false` to
716
+ * override that detection and force the disk tier on regardless of runtime.
717
+ *
718
+ * When disabled:
719
+ * - L1 evictions are dropped instead of being spilled to disk.
720
+ * - Cold-start snapshot persistence is skipped.
721
+ * - The `disk` metrics field still appears but shows zeroed counters.
722
+ *
723
+ * Default: `undefined` (auto-detect).
724
+ */
725
+ disableDisk?: boolean;
726
+
727
+ // ── Redis Cluster / Sentinel ───────────────────────────────────────────────
728
+ /**
729
+ * Redis Cluster node list. When provided, tricache connects using ioredis
730
+ * `Cluster` mode with automatic slot routing and multi-node connection
731
+ * pooling — no external proxy required.
732
+ *
733
+ * Takes precedence over `redisHost`/`redisPort`.
734
+ *
735
+ * @example
736
+ * redisClusterNodes: [
737
+ * { host: 'redis-1.internal', port: 6379 },
738
+ * { host: 'redis-2.internal', port: 6379 },
739
+ * { host: 'redis-3.internal', port: 6379 },
740
+ * ]
741
+ */
742
+ redisClusterNodes?: Array<{ host: string; port: number }>;
743
+
744
+ /**
745
+ * Redis Sentinel configuration for high-availability setups.
746
+ * When provided, tricache connects through Sentinel for automatic
747
+ * primary failover — no static `redisHost` / `redisPort` needed.
748
+ *
749
+ * Takes precedence over `redisHost`/`redisPort` (but not over `redisClusterNodes`).
750
+ *
751
+ * @example
752
+ * redisSentinel: {
753
+ * name: 'mymaster',
754
+ * sentinels: [
755
+ * { host: 'sentinel-1.internal', port: 26379 },
756
+ * { host: 'sentinel-2.internal', port: 26379 },
757
+ * ],
758
+ * }
759
+ */
760
+ redisSentinel?: {
761
+ /** Logical name of the monitored master. Must match the Sentinel `monitor` config. */
762
+ name: string;
763
+ sentinels: Array<{ host: string; port: number }>;
764
+ };
765
+
766
+ /**
767
+ * When `true`, a second `CacheService.create()` call for an already-existing
768
+ * singleton (same namespace) whose options differ from the first call throws
769
+ * instead of silently returning the existing instance. Use in codebases where
770
+ * multiple init points could pass conflicting configuration (e.g. different
771
+ * Redis credentials or TTLs) and you want that class of bug to fail loudly.
772
+ *
773
+ * Default: `false` (warn once, return existing instance).
774
+ */
775
+ strictSingleton?: boolean;
776
+
777
+ /**
778
+ * `cache.increment()` distributed-rate-limit behaviour on a Redis error.
779
+ *
780
+ * Default: `false` (fail-open — on a Redis error the method returns `0`, so a
781
+ * caller's `if (count > LIMIT) reject()` guard never rejects during an outage).
782
+ * Set to `true` to instead re-throw the Redis error, letting the caller's limit
783
+ * guard enforce the limit even when Redis is unavailable.
784
+ */
785
+ failClosed?: boolean;
786
+
787
+ /**
788
+ * Strategy used for tag-based cache invalidation:
789
+ * - `'set'` (default): Traditional Redis Set tracking. Members are registered in Redis
790
+ * sets and deleted individually on `invalidateTag()`. Best for low-to-medium cardinality tags.
791
+ * - `'generational'`: Generational tag versioning ($O(1)$ invalidations). Tag invalidation
792
+ * increments an atomic integer version counter in Redis and local memory. Entries store their
793
+ * creation tag versions; stale entries are detected on access and pruned with version-gated
794
+ * compare-and-delete. Eliminates key scans and Redis bulk deletion stalls on large datasets.
795
+ */
796
+ tagStrategy?: 'set' | 'generational';
797
+
798
+ /**
799
+ * Milliseconds before an in-memory generational tag version is re-synced from Redis.
800
+ * Bounds maximum partition/missed-broadcast staleness when using `tagStrategy: 'generational'`.
801
+ * Default: `5000` ms (5 seconds).
802
+ */
803
+ tagVersionTtlMs?: number;
804
+
805
+ /**
806
+ * Read safety strategy for returned cached objects:
807
+ * - `'none'` (default): Returns raw in-memory references for sub-microsecond performance (~350 ns).
808
+ * - `'structuredClone'`: Clones values via native `structuredClone()` on L1 hits, L2 promotions,
809
+ * and fetch returns, preventing caller mutations from polluting the cached reference.
810
+ * Supported types: plain objects, arrays, Dates, Maps, Sets, TypedArrays. Functions and class
811
+ * prototype chains are not preserved.
812
+ */
813
+ cloneStrategy?: 'none' | 'structuredClone';
814
+
815
+ /**
816
+ * Invalidation backplane transport mode:
817
+ * - `'pubsub'` (default): Ephemeral Redis Pub/Sub (at-most-once delivery).
818
+ * - `'stream'`: Durable Redis Streams (XADD/XREAD) with missed-event replay on reconnect.
819
+ */
820
+ backplaneMode?: 'pubsub' | 'stream';
821
+
822
+ /**
823
+ * Maximum retained entries in the Redis invalidation stream (`MAXLEN ~ N`).
824
+ * Default: `10000`.
825
+ */
826
+ backplaneStreamMaxLen?: number;
827
+
828
+ /**
829
+ * Blocking poll timeout in milliseconds for `XREAD BLOCK`.
830
+ * Default: `2000` ms (2 seconds).
831
+ */
832
+ backplaneStreamBlockMs?: number;
833
+
834
+ /**
835
+ * Custom Redis Stream key name.
836
+ * Default: `tricache:stream:{<namespace>}` (hash-tagged for Redis Cluster single-slot routing).
837
+ */
838
+ backplaneStreamKey?: string;
839
+
840
+ /**
841
+ * OpenTelemetry Meter instance for native metrics publishing.
842
+ * Compatible with `@opentelemetry/api` Meter.
843
+ */
844
+ meter?: ICacheMeter;
845
+ }
846
+
847
+ /**
848
+ * Options for the ergonomic `cache.wrap(key, fetchFn, options)` method.
849
+ */
850
+ export interface WrapOptions {
851
+ /** TTL in seconds (default: 300 s). */
852
+ ttl?: number;
853
+ /** Stale-While-Revalidate grace period in seconds. */
854
+ swr?: number;
855
+ /** Override the auto-inferred eviction priority. */
856
+ priority?: CachePriority;
857
+ /** Semantic tags for invalidation. */
858
+ tags?: string[];
859
+ /** Dependency cascade patterns (e.g. `['user:*']`). */
860
+ dependsOn?: string[];
861
+ /** 0–1 fraction of TTL elapsed at which a proactive background refresh is scheduled. */
862
+ refreshAhead?: number;
863
+ /** XFetch probabilistic early expiration factor (0.5–2.0). */
864
+ xfetchBeta?: number;
865
+ /** Override TTL in seconds for null/undefined fetch results (negative caching). */
866
+ notFoundTtl?: number;
867
+ }
868
+
869
+ /**
870
+ * Options for distributed and in-process mutual exclusion locks via `cache.lock()`.
871
+ */
872
+ export interface LockOptions {
873
+ /**
874
+ * Lock auto-release TTL in seconds (default: 30 s).
875
+ * Prevents deadlocks if the holding node crashes or is terminated.
876
+ */
877
+ ttl?: number;
878
+ /**
879
+ * Maximum time to wait to acquire the lock in milliseconds before throwing a timeout error.
880
+ * Default: `5000` ms.
881
+ */
882
+ acquireTimeout?: number;
883
+ /**
884
+ * Polling retry interval in milliseconds when waiting for lock acquisition.
885
+ * Default: `100` ms.
886
+ */
887
+ retryInterval?: number;
888
+ }
889
+
890
+ /**
891
+ * Structural typing matching OpenTelemetry Metric interfaces (`@opentelemetry/api`).
892
+ */
893
+ export interface ICacheCounter {
894
+ add(value: number, attributes?: Record<string, string | number | boolean>): void;
895
+ }
896
+
897
+ export interface ICacheObservableGauge {
898
+ readonly _isGauge?: true;
899
+ }
900
+
901
+ export interface ICacheBatchObservableCallback {
902
+ (observableResult: {
903
+ observe: (metric: ICacheObservableGauge, value: number, attributes?: Record<string, string | number | boolean>) => void;
904
+ }): void | Promise<void>;
905
+ }
906
+
907
+ export interface ICacheMeter {
908
+ createCounter(name: string, options?: { description?: string; unit?: string }): ICacheCounter;
909
+ createObservableGauge(name: string, options?: { description?: string; unit?: string }): ICacheObservableGauge;
910
+ addBatchObservableCallback(callback: ICacheBatchObservableCallback, observables: ICacheObservableGauge[]): void;
911
+ }