tricache 0.7.1 → 0.9.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 (102) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +89 -1371
  3. package/dashboards/prometheus-scrape.yml +18 -0
  4. package/dashboards/tricache-alerts.yaml +54 -0
  5. package/dashboards/tricache-grafana.json +548 -0
  6. package/dist/cache-service-DVvroyqA.d.ts +886 -0
  7. package/dist/cache-service-KI5ACF3F.js +12 -0
  8. package/dist/chunk-7RV5ZVBB.js +1023 -0
  9. package/dist/chunk-BQRURGGD.js +60 -0
  10. package/dist/chunk-IITRFWHY.js +196 -0
  11. package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
  12. package/dist/{chunk-EUGYR7KR.js → chunk-PL5J3ZNT.js} +3184 -514
  13. package/dist/chunk-QNU7B43J.js +687 -0
  14. package/dist/chunk-UGD4VEPD.js +138 -0
  15. package/dist/chunk-XZL45ABR.js +108 -0
  16. package/dist/cli.cjs +3122 -495
  17. package/dist/cli.d.ts +1 -0
  18. package/dist/cli.js +121 -5
  19. package/dist/dashboard/index.cjs +1065 -0
  20. package/dist/dashboard/index.d.ts +183 -0
  21. package/dist/dashboard/index.js +22 -0
  22. package/dist/drizzle/index.cjs +2846 -494
  23. package/dist/drizzle/index.d.ts +3 -1
  24. package/dist/drizzle/index.js +1 -1
  25. package/dist/edge/index.cjs +1559 -0
  26. package/dist/edge/index.d.ts +127 -0
  27. package/dist/edge/index.js +1109 -0
  28. package/dist/hono/index.cjs +7760 -0
  29. package/dist/hono/index.d.ts +91 -0
  30. package/dist/hono/index.js +185 -0
  31. package/dist/hono-VA9A1m0I.d.ts +371 -0
  32. package/dist/http/index.cjs +3281 -587
  33. package/dist/http/index.d.ts +85 -23
  34. package/dist/http/index.js +176 -78
  35. package/dist/index.cjs +7212 -2505
  36. package/dist/index.d.ts +547 -30
  37. package/dist/index.js +104 -5
  38. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  39. package/dist/nestjs/index.cjs +2787 -487
  40. package/dist/nestjs/index.d.ts +3 -1
  41. package/dist/nestjs/index.js +6 -3
  42. package/dist/next/index.cjs +2804 -501
  43. package/dist/next/index.d.ts +4 -2
  44. package/dist/next/index.js +14 -10
  45. package/dist/prisma/index.d.ts +3 -1
  46. package/dist/serialize-worker.cjs +5 -4
  47. package/dist/serialize-worker.js +1 -1
  48. package/dist/{cache-service-D8tIXmzb.d.ts → types-B_QkVwJ7.d.ts} +622 -662
  49. package/dist/utils-CEsU_Z0s.d.ts +27 -0
  50. package/package.json +48 -10
  51. package/src/adapters/auto-pipeliner.ts +206 -0
  52. package/src/adapters/node-redis.ts +370 -0
  53. package/src/cache-service.ts +1619 -415
  54. package/src/cli.ts +137 -2
  55. package/src/codec.ts +72 -0
  56. package/src/cross-region.ts +245 -0
  57. package/src/dashboard/handler.ts +392 -0
  58. package/src/dashboard/html.ts +594 -0
  59. package/src/dashboard/index.ts +195 -0
  60. package/src/dashboard/types.ts +96 -0
  61. package/src/disk-tier.ts +449 -47
  62. package/src/drizzle/index.ts +86 -86
  63. package/src/edge/adapters/cloudflare-do.ts +130 -0
  64. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  65. package/src/edge/adapters/upstash.ts +143 -0
  66. package/src/edge/cache.ts +797 -0
  67. package/src/edge/crypto.ts +182 -0
  68. package/src/edge/hono.ts +284 -0
  69. package/src/edge/index.ts +37 -0
  70. package/src/edge/types.ts +230 -0
  71. package/src/edge/utils/base64.ts +63 -0
  72. package/src/edge/utils/murmur3.ts +179 -0
  73. package/src/encryption.ts +127 -5
  74. package/src/hono/index.ts +316 -0
  75. package/src/http/express.ts +195 -0
  76. package/src/http/fastify.ts +260 -0
  77. package/src/http/index.ts +44 -258
  78. package/src/http/utils.ts +92 -0
  79. package/src/index.ts +149 -47
  80. package/src/ipc-telemetry.ts +509 -0
  81. package/src/latency-watchdog.ts +282 -0
  82. package/src/nestjs/decorators.ts +161 -161
  83. package/src/nestjs/index.ts +23 -23
  84. package/src/nestjs/tricache.module.ts +104 -104
  85. package/src/nestjs/tricache.store.ts +97 -97
  86. package/src/nestjs/types.ts +79 -79
  87. package/src/next/cache-handler.ts +12 -9
  88. package/src/next/index.ts +37 -37
  89. package/src/next/isr-handler.ts +105 -105
  90. package/src/next/types.ts +130 -130
  91. package/src/remote-snapshot.ts +153 -0
  92. package/src/serialize-worker.ts +120 -120
  93. package/src/sigv4-snapshot-adapter.ts +260 -0
  94. package/src/smart-memory-cache.ts +91 -8
  95. package/src/types.ts +315 -2
  96. package/src/utils/cgroup.ts +100 -0
  97. package/src/utils/tracing.ts +54 -0
  98. package/src/wasm/bloom-filter-wasm.ts +109 -102
  99. package/src/worker-pool.ts +299 -299
  100. package/src/wtiny-lfu.ts +624 -0
  101. package/dist/cache-service-5GATUYAK.js +0 -7
  102. package/dist/chunk-UBSR5UYA.js +0 -0
@@ -12,8 +12,9 @@
12
12
  * - Process-level singleton via globalThis (survives Next.js hot reloads)
13
13
  */
14
14
 
15
- import { pack, unpack } from 'msgpackr';
16
- import type { CacheHit, CachePriority, CategoryLimit, SmartCacheEntry, ILogger, EvictionReason } from './types';
15
+ import { CacheCodec, defaultCodec } from './codec.js';
16
+ import type { CacheHit, CachePriority, CategoryLimit, SmartCacheEntry, ILogger, EvictionReason, WTinyLfuStats } from './types';
17
+ import { WTinyLfuPolicy } from './wtiny-lfu.js';
17
18
 
18
19
  /**
19
20
  * Packed-byte threshold above which the live JS object is NOT stored alongside the
@@ -257,16 +258,27 @@ export interface SmartMemoryCacheOptions {
257
258
  logger: ILogger;
258
259
  /** Fraction of maxEntries / maxBytes at which proactive eviction fires (default 0.9). */
259
260
  evictionWatermark?: number;
261
+ /** Custom binary codec (defaults to defaultCodec with record structures and rich types enabled). */
262
+ codec?: CacheCodec;
263
+ /**
264
+ * Admission policy:
265
+ * - 'wtinylfu': Window TinyLFU segmented admission with mathematical scan resistance.
266
+ * - 'adaptive': Adaptive LFU x LRU x priority reservoir sampling.
267
+ * Default: 'adaptive' (unless explicitly set to 'wtinylfu')
268
+ */
269
+ admissionPolicy?: 'wtinylfu' | 'adaptive';
260
270
  }
261
271
 
262
272
  export class SmartMemoryCache {
263
273
  private readonly cache = new Map<string, SmartCacheEntry>();
264
274
  private readonly opts: SmartMemoryCacheOptions;
275
+ private readonly codec: CacheCodec;
265
276
  private bloom: AnyBloomFilter;
266
277
  /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
267
278
  private readonly categoryPrefixes: string[];
268
279
  /** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
269
280
  private readonly sketch = new CountMinSketch();
281
+ private readonly wtinyPolicy?: WTinyLfuPolicy;
270
282
  private totalSize = 0;
271
283
  private categoryCount = new Map<string, number>();
272
284
  private categorySize = new Map<string, number>();
@@ -294,8 +306,12 @@ export class SmartMemoryCache {
294
306
 
295
307
  constructor(opts: SmartMemoryCacheOptions, existing?: Map<string, SmartCacheEntry>) {
296
308
  this.opts = opts;
309
+ this.codec = opts.codec ?? defaultCodec;
297
310
  this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
298
311
  this.categoryPrefixes = Object.keys(opts.categories).filter(k => k !== 'default');
312
+ if (opts.admissionPolicy === 'wtinylfu') {
313
+ this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch);
314
+ }
299
315
 
300
316
  if (existing) {
301
317
  for (const [k, v] of existing) this.cache.set(k, v);
@@ -311,6 +327,12 @@ export class SmartMemoryCache {
311
327
  this.categoryCount.clear();
312
328
  this.categorySize.clear();
313
329
  this.categoryKeys.clear();
330
+ if (this.wtinyPolicy) {
331
+ this.wtinyPolicy.clear();
332
+ for (const key of this.cache.keys()) {
333
+ this.wtinyPolicy.onSet(key, false);
334
+ }
335
+ }
314
336
  for (const [key, entry] of this.cache) {
315
337
  this.totalSize += entry.size;
316
338
  const cat = this.getCategory(key);
@@ -336,6 +358,7 @@ export class SmartMemoryCache {
336
358
  private _delete(key: string, reason: EvictionReason = 'manual'): boolean {
337
359
  const entry = this.cache.get(key);
338
360
  if (!entry) return false;
361
+ this.wtinyPolicy?.onDelete(key);
339
362
  const cat = this.getCategory(key);
340
363
  this.totalSize -= entry.size;
341
364
  this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
@@ -524,9 +547,10 @@ export class SmartMemoryCache {
524
547
  entry.lastAccess = now;
525
548
  // Sample sketch at 25 % — eviction scoring only needs relative frequency, not exact counts.
526
549
  if ((entry.hits & 3) === 0) this.sketch.increment(key);
550
+ this.wtinyPolicy?.onAccess(key);
527
551
  // value is cached at write time — hot reads return the live object directly,
528
552
  // skipping unpack. Falls back to decode for entries restored from disk/snapshot.
529
- const value = entry.value !== undefined ? entry.value : unpack(entry.data as Buffer);
553
+ const value = entry.value !== undefined ? entry.value : this.codec.decode(entry.data as Buffer);
530
554
  // Fresh object per call — never a shared/reusable one. Callers hold this result
531
555
  // across await boundaries (CacheService.get() awaits tag-version checks between
532
556
  // the L1 hit and the return); a shared object would let a concurrent get()
@@ -555,7 +579,7 @@ export class SmartMemoryCache {
555
579
  ): void {
556
580
  // Single serialization pass — always msgpackr. Eliminates the prior JSON.stringify
557
581
  // "size probe" that was discarded for large payloads (the double-pass).
558
- const packed = pack(data);
582
+ const packed = this.codec.encode(data);
559
583
  const size = packed.byteLength;
560
584
  this.compressions++;
561
585
  this.sketch.increment(key);
@@ -576,7 +600,57 @@ export class SmartMemoryCache {
576
600
  this.categorySize.set(cat, (this.categorySize.get(cat) ?? existingEntry.size) - existingEntry.size);
577
601
  this.cache.delete(key);
578
602
  }
579
- this.ensureCapacity(cat, size);
603
+
604
+ if (this.wtinyPolicy) {
605
+ const decision = this.wtinyPolicy.onSet(key, Boolean(existingEntry));
606
+ if (!decision.admit) {
607
+ if (decision.candidateKey === key) {
608
+ // Candidate itself was rejected by TinyLFU admission gate
609
+ if (this.opts.diskSpill) {
610
+ const now = Date.now();
611
+ const liveValue = size <= LARGE_VALUE_BYTES ? data : undefined;
612
+ this.opts.diskSpill(key, {
613
+ data: packed,
614
+ value: liveValue,
615
+ isCompressed: true,
616
+ expiresAt: now + ttlMs,
617
+ staleAt,
618
+ size,
619
+ hits: 1,
620
+ lastAccess: now,
621
+ priority,
622
+ ttlMs,
623
+ delta,
624
+ setAt: now,
625
+ tagVersions,
626
+ });
627
+ }
628
+ return;
629
+ } else if (decision.candidateKey) {
630
+ // An older window candidate was rejected to make room for key
631
+ const candEntry = this.cache.get(decision.candidateKey);
632
+ if (candEntry && this.opts.diskSpill) {
633
+ this.opts.diskSpill(decision.candidateKey, candEntry);
634
+ }
635
+ this._delete(decision.candidateKey, 'capacity');
636
+ }
637
+ } else if (decision.evictKey) {
638
+ // Main cache victim evicted to admit candidate
639
+ const victimEntry = this.cache.get(decision.evictKey);
640
+ if (victimEntry && this.opts.diskSpill) {
641
+ this.opts.diskSpill(decision.evictKey, victimEntry);
642
+ }
643
+ this._delete(decision.evictKey, 'capacity');
644
+ }
645
+
646
+ // Check category byte limit or total byte limit
647
+ const catSz = this.categorySize.get(cat) ?? 0;
648
+ if (catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
649
+ this.ensureCapacity(cat, size);
650
+ }
651
+ } else {
652
+ this.ensureCapacity(cat, size);
653
+ }
580
654
 
581
655
  const now = Date.now();
582
656
  // Only cache the live object for small entries — large entries would store the packed
@@ -656,6 +730,7 @@ export class SmartMemoryCache {
656
730
  }
657
731
  const count = this.cache.size;
658
732
  this.cache.clear();
733
+ this.wtinyPolicy?.clear();
659
734
  this.totalSize = 0;
660
735
  this.categoryCount.clear();
661
736
  this.categorySize.clear();
@@ -840,12 +915,12 @@ export class SmartMemoryCache {
840
915
  const rawData = entry.data;
841
916
  // Handle both legacy (isCompressed=false, data=JSON string) and current (data=Buffer) formats.
842
917
  const data: Buffer = !entry.isCompressed
843
- ? pack(JSON.parse(rawData as unknown as string)) // legacy: re-encode JSON → msgpackr
918
+ ? this.codec.encode(JSON.parse(rawData as unknown as string)) // legacy: re-encode JSON → msgpackr
844
919
  : rawData instanceof Uint8Array
845
920
  ? Buffer.from(rawData) // msgpackr Uint8Array → Buffer
846
921
  : rawData as Buffer; // already a Buffer
847
922
  // Cache the live object for small entries only — large entries skip double-heap storage.
848
- const value = entry.size <= LARGE_VALUE_BYTES ? unpack(data) : undefined;
923
+ const value = entry.size <= LARGE_VALUE_BYTES ? this.codec.decode(data) : undefined;
849
924
  this.cache.set(key, { ...entry, data, value, isCompressed: true });
850
925
  this.bloom.add(key);
851
926
  loaded++;
@@ -922,7 +997,7 @@ export class SmartMemoryCache {
922
997
  * if the live object was not cached (large-entry optimisation or disk-restored entry).
923
998
  */
924
999
  resolveValue(entry: SmartCacheEntry): unknown {
925
- return entry.value !== undefined ? entry.value : unpack(entry.data as Buffer);
1000
+ return entry.value !== undefined ? entry.value : this.codec.decode(entry.data as Buffer);
926
1001
  }
927
1002
 
928
1003
  // ── Stats ─────────────────────────────────────────────────────────────────
@@ -1023,4 +1098,12 @@ export class SmartMemoryCache {
1023
1098
  out.sort((a, b) => b.hits - a.hits);
1024
1099
  return out.slice(0, n);
1025
1100
  }
1101
+
1102
+ /**
1103
+ * Return real-time metrics and telemetry for the Window TinyLFU admission policy.
1104
+ * Returns `undefined` when running under default adaptive eviction.
1105
+ */
1106
+ getWTinyLfuStats(): WTinyLfuStats | undefined {
1107
+ return this.wtinyPolicy?.getStats();
1108
+ }
1026
1109
  }
package/src/types.ts CHANGED
@@ -1,3 +1,6 @@
1
+ import type { RemoteSnapshotOptions } from './remote-snapshot';
2
+ import type { CrossRegionRelayOptions } from './cross-region';
3
+
1
4
  /**
2
5
  * tricache — shared types and interfaces
3
6
  */
@@ -10,9 +13,18 @@
10
13
  * Minimal span interface — structurally compatible with `@opentelemetry/api` Span.
11
14
  * Pass your existing OTEL tracer; no extra package required.
12
15
  */
16
+ export interface ICacheSpanLink {
17
+ context: {
18
+ traceId: string;
19
+ spanId: string;
20
+ traceFlags?: number;
21
+ };
22
+ }
23
+
13
24
  export interface ICacheSpan {
14
25
  setAttribute(key: string, value: string | number | boolean): this;
15
26
  setStatus(status: { code: 0 | 1 | 2; message?: string }): this;
27
+ recordException?(err: Error | unknown): this;
16
28
  end(): void;
17
29
  }
18
30
 
@@ -20,7 +32,7 @@ export interface ICacheSpan {
20
32
  * Minimal tracer interface — structurally compatible with `@opentelemetry/api` Tracer.
21
33
  */
22
34
  export interface ICacheTracer {
23
- startSpan(name: string): ICacheSpan;
35
+ startSpan(name: string, options?: { links?: ICacheSpanLink[] }): ICacheSpan;
24
36
  }
25
37
 
26
38
  /** Minimal logger interface — plug in any logger (pino, winston, console, etc.) */
@@ -250,8 +262,55 @@ export interface CacheMetrics {
250
262
  lastTriggeredAt: number | null;
251
263
  };
252
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
+
253
292
  l1: { entries: number; sizeBytes: number; maxBytes: number };
254
- disk: { files: number; sizeKB: number; maxKB: number; disabled: boolean };
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
+ };
255
314
 
256
315
  /** Adaptive TTL statistics — present only when `adaptiveTtl` is enabled */
257
316
  adaptiveTtl?: {
@@ -267,6 +326,20 @@ export interface CacheMetrics {
267
326
  };
268
327
  }
269
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
+
270
343
  // ─── Configuration ───────────────────────────────────────────────────────────
271
344
 
272
345
  /** Per-category memory limits for L1 */
@@ -275,6 +348,11 @@ export interface CategoryLimit {
275
348
  maxSizeBytes: number;
276
349
  }
277
350
 
351
+ /**
352
+ * Supported opinionated pre-configurations for CacheService.preset()
353
+ */
354
+ export type CachePresetType = 'nextjs' | 'microservice' | 'serverless' | 'enterprise-hardened';
355
+
278
356
  /**
279
357
  * Options accepted by CacheService.create()
280
358
  *
@@ -308,6 +386,14 @@ export interface CacheOptions {
308
386
  * Default: ['auth:', 'session:', 'mfa:', 'rate_limit:']
309
387
  */
310
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';
311
397
 
312
398
  // ── L1.5 (disk tier) ────────────────────────────────────────────────────
313
399
  /** Directory used for L1.5 disk-spill files. Default: os.tmpdir()/tricache-disk */
@@ -316,6 +402,61 @@ export interface CacheOptions {
316
402
  diskMaxBytes?: number;
317
403
  /** Max bytes for a single disk entry. Default: 10 MB */
318
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;
319
460
 
320
461
  // ── L2 (Redis) ────────────────────────────────────────────────────────────
321
462
  /**
@@ -326,6 +467,29 @@ export interface CacheOptions {
326
467
  redisHost?: string;
327
468
  /** Redis port. Default: 6379 */
328
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;
329
493
  /**
330
494
  * Whether to enable TLS for the Redis connection. Default: true in production,
331
495
  * false otherwise.
@@ -343,6 +507,19 @@ export interface CacheOptions {
343
507
  */
344
508
  disableRedis?: boolean;
345
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
+
346
523
  // ── Encryption ────────────────────────────────────────────────────────────
347
524
  /**
348
525
  * Base64-encoded 32-byte AES-256-GCM key for encrypting L2 (Redis) values and
@@ -380,6 +557,15 @@ export interface CacheOptions {
380
557
  */
381
558
  strictKeyValidation?: boolean;
382
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
+
383
569
  // ── Compression ──────────────────────────────────────────────────────────
384
570
  /**
385
571
  * Optional compression algorithm for L2 (Redis) strings and disk-tier binary blobs.
@@ -406,6 +592,11 @@ export interface CacheOptions {
406
592
  * Max age (ms) of a snapshot file before it is rejected. Default: 2 hours
407
593
  */
408
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;
409
600
 
410
601
  /**
411
602
  * Optional namespace prefix for all cache keys.
@@ -484,6 +675,34 @@ export interface CacheOptions {
484
675
  */
485
676
  useShardedPubSub?: boolean;
486
677
 
678
+ /**
679
+ * If true, await backplane invalidation broadcasts during delete(), set(),
680
+ * clear(), and invalidateTag() operations rather than firing them in the background.
681
+ * Guarantees that remote cluster nodes receive the invalidation before the
682
+ * operation resolves to the caller.
683
+ *
684
+ * Default: `false` (asynchronous fire-and-forget for minimal caller latency).
685
+ */
686
+ awaitInvalidationBackplane?: boolean;
687
+
688
+ /**
689
+ * If `true`, `cache.lock()` operations fail closed (throw an Error) if Redis
690
+ * encounters a connection or runtime error during lock acquisition, preventing
691
+ * split-brain concurrent execution across multiple cluster nodes.
692
+ *
693
+ * Default: `false` (falls back to local in-process mutex with a debug log).
694
+ */
695
+ lockFailClosed?: boolean;
696
+
697
+ // ── Multi-Region / Cross-Cluster Invalidation Relay ─────────────────────
698
+ /**
699
+ * Optional cross-region invalidation relay configuration for geo-distributed deployments.
700
+ * Synchronizes `delete()` and `invalidateTag()` events across separate regional Redis clusters
701
+ * (e.g. `us-east-1` and `eu-central-1`) via HTTP mesh or custom message brokers (SNS, SQS, EventBridge)
702
+ * with automatic origin deduplication to prevent invalidation loops.
703
+ */
704
+ crossRegion?: CrossRegionRelayOptions;
705
+
487
706
  // ── OOM protection ──────────────────────────────────────────────────────
488
707
  /**
489
708
  * Enable the GC-aware OOM guard. When heap utilisation crosses
@@ -516,6 +735,18 @@ export interface CacheOptions {
516
735
  /** How often the `onMetrics` callback fires (ms). Default: 60 000 ms */
517
736
  metricsIntervalMs?: number;
518
737
 
738
+ /**
739
+ * Enable local IPC telemetry server (Unix domain socket on POSIX, Windows Named Pipe on win32)
740
+ * allowing external monitors like `tricache top` to inspect this instance.
741
+ * Default: `false`.
742
+ */
743
+ enableIpc?: boolean;
744
+ /**
745
+ * Custom socket path or Windows named pipe path for the IPC telemetry server.
746
+ * Default: `/tmp/tricache-<pid>.sock` (POSIX) or `\\.\pipe\tricache-<pid>` (Windows).
747
+ */
748
+ ipcSocketPath?: string;
749
+
519
750
  /**
520
751
  * OpenTelemetry-compatible tracer. When provided, `get()`, `set()`, and
521
752
  * `delete()` are each wrapped in a span with attributes:
@@ -885,6 +1116,12 @@ export interface LockOptions {
885
1116
  * Default: `100` ms.
886
1117
  */
887
1118
  retryInterval?: number;
1119
+ /**
1120
+ * If `true`, lock acquisition will throw an error immediately if Redis encounters a
1121
+ * connection or operational error rather than falling back to an in-process mutex.
1122
+ * Overrides `CacheOptions.lockFailClosed`.
1123
+ */
1124
+ failClosedOnRedisError?: boolean;
888
1125
  }
889
1126
 
890
1127
  /**
@@ -909,3 +1146,79 @@ export interface ICacheMeter {
909
1146
  createObservableGauge(name: string, options?: { description?: string; unit?: string }): ICacheObservableGauge;
910
1147
  addBatchObservableCallback(callback: ICacheBatchObservableCallback, observables: ICacheObservableGauge[]): void;
911
1148
  }
1149
+
1150
+ /**
1151
+ * Common pipeline / transaction interface matching ioredis and adapted drivers.
1152
+ */
1153
+ export interface IRedisPipeline {
1154
+ get(key: string): this;
1155
+ set(key: string, value: string, ...args: (string | number)[]): this;
1156
+ setex(key: string, seconds: number, value: string): this;
1157
+ del(...keys: string[]): this;
1158
+ expire(key: string, seconds: number): this;
1159
+ incr(key: string): this;
1160
+ sadd(key: string, ...members: string[]): this;
1161
+ smembers(key: string): this;
1162
+ hset(key: string, value: Record<string, string>): this;
1163
+ exec(): Promise<Array<[Error | null, any]> | null>;
1164
+ }
1165
+
1166
+ /**
1167
+ * Pluggable contract for external Redis drivers (e.g. `@redis/client` / `node-redis`,
1168
+ * custom connection pools, or pre-configured `ioredis` instances).
1169
+ */
1170
+ export interface IRedisDriver {
1171
+ get(key: string): Promise<string | null>;
1172
+ set(key: string, value: string, ...args: (string | number)[]): Promise<unknown>;
1173
+ setex?(key: string, seconds: number, value: string): Promise<unknown>;
1174
+ del(...keys: string[]): Promise<number>;
1175
+ ping(): Promise<string>;
1176
+ expire(key: string, seconds: number): Promise<number | boolean>;
1177
+ incr(key: string): Promise<number>;
1178
+ eval(script: string, numkeys: number, ...args: (string | number)[]): Promise<unknown>;
1179
+ multi(): IRedisPipeline;
1180
+ pipeline?(): IRedisPipeline;
1181
+ smembers?(key: string): Promise<string[]>;
1182
+ sadd?(key: string, ...members: string[]): Promise<number>;
1183
+ scan?(cursor: string, ...args: (string | number)[]): Promise<[string, string[]]>;
1184
+ scanStream?(options?: { match?: string; count?: number }): any;
1185
+ hset?(key: string, value: Record<string, string>): Promise<unknown>;
1186
+ publish?(channel: string, message: string): Promise<number>;
1187
+ subscribe?(...channels: string[]): Promise<unknown>;
1188
+ disconnect(): Promise<void> | void;
1189
+ quit?(): Promise<void> | void;
1190
+ duplicate?(): IRedisDriver;
1191
+ on?(event: string, listener: (...args: any[]) => void): this | unknown;
1192
+ once?(event: string, listener: (...args: any[]) => void): this | unknown;
1193
+ isOpen?: boolean;
1194
+ connect?(): Promise<unknown>;
1195
+ }
1196
+
1197
+ /**
1198
+ * Real-time telemetry and state for the disk tier backpressure queue.
1199
+ */
1200
+ export interface DiskBackpressureStats {
1201
+ activeWrites: number;
1202
+ pendingWrites: number;
1203
+ spillsDropped: number;
1204
+ circuitState: 'closed' | 'open' | 'half-open';
1205
+ lastTripTimestamp: number;
1206
+ }
1207
+
1208
+ /**
1209
+ * Telemetry metrics and counters for Window TinyLFU cache admission.
1210
+ */
1211
+ export interface WTinyLfuStats {
1212
+ capacity: number;
1213
+ size: number;
1214
+ windowSize: number;
1215
+ probationSize: number;
1216
+ protectedSize: number;
1217
+ hits: number;
1218
+ misses: number;
1219
+ hitRate: number;
1220
+ admissions: number;
1221
+ rejections: number;
1222
+ demotions: number;
1223
+ promotions: number;
1224
+ }