tricache 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +87 -1371
  3. package/dashboards/tricache-alerts.yaml +54 -0
  4. package/dashboards/tricache-grafana.json +548 -0
  5. package/dist/cache-service-5MZXFIGK.js +12 -0
  6. package/dist/cache-service-CyLdpo77.d.ts +871 -0
  7. package/dist/{chunk-EUGYR7KR.js → chunk-6PQ5MOWR.js} +2871 -490
  8. package/dist/chunk-7RV5ZVBB.js +1023 -0
  9. package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
  10. package/dist/chunk-QNU7B43J.js +687 -0
  11. package/dist/chunk-UGD4VEPD.js +138 -0
  12. package/dist/chunk-XZL45ABR.js +108 -0
  13. package/dist/chunk-ZTSWCFYO.js +135 -0
  14. package/dist/cli.cjs +2790 -471
  15. package/dist/cli.d.ts +1 -0
  16. package/dist/cli.js +103 -5
  17. package/dist/dashboard/index.cjs +1065 -0
  18. package/dist/dashboard/index.d.ts +183 -0
  19. package/dist/dashboard/index.js +22 -0
  20. package/dist/drizzle/index.cjs +2553 -470
  21. package/dist/drizzle/index.d.ts +3 -1
  22. package/dist/drizzle/index.js +1 -1
  23. package/dist/edge/index.cjs +1498 -0
  24. package/dist/edge/index.d.ts +127 -0
  25. package/dist/edge/index.js +1109 -0
  26. package/dist/hono-DQRS1Xd7.d.ts +370 -0
  27. package/dist/http/index.cjs +2926 -562
  28. package/dist/http/index.d.ts +109 -23
  29. package/dist/http/index.js +220 -72
  30. package/dist/index.cjs +6936 -2518
  31. package/dist/index.d.ts +547 -30
  32. package/dist/index.js +104 -5
  33. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  34. package/dist/nestjs/index.cjs +2494 -463
  35. package/dist/nestjs/index.d.ts +3 -1
  36. package/dist/nestjs/index.js +6 -3
  37. package/dist/next/index.cjs +2517 -483
  38. package/dist/next/index.d.ts +4 -2
  39. package/dist/next/index.js +14 -10
  40. package/dist/prisma/index.d.ts +3 -1
  41. package/dist/serialize-worker.cjs +5 -4
  42. package/dist/serialize-worker.js +1 -1
  43. package/dist/{cache-service-D8tIXmzb.d.ts → types-B6krw64X.d.ts} +596 -659
  44. package/package.json +34 -6
  45. package/src/adapters/auto-pipeliner.ts +206 -0
  46. package/src/adapters/node-redis.ts +370 -0
  47. package/src/cache-service.ts +1339 -402
  48. package/src/cli.ts +120 -2
  49. package/src/codec.ts +72 -0
  50. package/src/cross-region.ts +245 -0
  51. package/src/dashboard/handler.ts +392 -0
  52. package/src/dashboard/html.ts +594 -0
  53. package/src/dashboard/index.ts +195 -0
  54. package/src/dashboard/types.ts +96 -0
  55. package/src/disk-tier.ts +449 -47
  56. package/src/drizzle/index.ts +86 -86
  57. package/src/edge/adapters/cloudflare-do.ts +130 -0
  58. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  59. package/src/edge/adapters/upstash.ts +143 -0
  60. package/src/edge/cache.ts +797 -0
  61. package/src/edge/crypto.ts +182 -0
  62. package/src/edge/hono.ts +203 -0
  63. package/src/edge/index.ts +37 -0
  64. package/src/edge/types.ts +230 -0
  65. package/src/edge/utils/base64.ts +63 -0
  66. package/src/edge/utils/murmur3.ts +179 -0
  67. package/src/encryption.ts +127 -5
  68. package/src/http/express.ts +195 -0
  69. package/src/http/fastify.ts +260 -0
  70. package/src/http/index.ts +39 -258
  71. package/src/http/utils.ts +92 -0
  72. package/src/index.ts +149 -47
  73. package/src/ipc-telemetry.ts +481 -0
  74. package/src/latency-watchdog.ts +282 -0
  75. package/src/nestjs/decorators.ts +161 -161
  76. package/src/nestjs/index.ts +23 -23
  77. package/src/nestjs/tricache.module.ts +104 -104
  78. package/src/nestjs/tricache.store.ts +97 -97
  79. package/src/nestjs/types.ts +79 -79
  80. package/src/next/cache-handler.ts +12 -9
  81. package/src/next/index.ts +37 -37
  82. package/src/next/isr-handler.ts +105 -105
  83. package/src/next/types.ts +130 -130
  84. package/src/remote-snapshot.ts +153 -0
  85. package/src/serialize-worker.ts +120 -120
  86. package/src/sigv4-snapshot-adapter.ts +260 -0
  87. package/src/smart-memory-cache.ts +91 -8
  88. package/src/types.ts +290 -2
  89. package/src/utils/cgroup.ts +100 -0
  90. package/src/utils/tracing.ts +54 -0
  91. package/src/wasm/bloom-filter-wasm.ts +109 -102
  92. package/src/worker-pool.ts +299 -299
  93. package/src/wtiny-lfu.ts +624 -0
  94. package/dist/cache-service-5GATUYAK.js +0 -7
  95. package/dist/chunk-UBSR5UYA.js +0 -0
@@ -17,7 +17,9 @@
17
17
  */
18
18
 
19
19
  import { Redis as RedisClient, Cluster as RedisCluster } from 'ioredis';
20
- import { pack, unpack } from 'msgpackr';
20
+ import { CacheCodec } from './codec.js';
21
+ import type { RemoteSnapshotOptions } from './remote-snapshot.js';
22
+ import type { CrossRegionRelayOptions, CrossRegionInvalidationEvent } from './cross-region.js';
21
23
  import crypto from 'crypto';
22
24
  import os from 'os';
23
25
  import { WorkerPool } from './worker-pool.js';
@@ -37,15 +39,24 @@ import {
37
39
  ILogger,
38
40
  ICacheTracer,
39
41
  ICacheSpan,
42
+ ICacheSpanLink,
40
43
  consoleLogger,
41
44
  WrapOptions,
42
45
  LockOptions,
43
46
  ICacheMeter,
44
47
  ICacheCounter,
48
+ IRedisDriver,
49
+ WTinyLfuStats,
50
+ CachePresetType,
51
+ CacheHealthStatus,
45
52
  } from './types';
46
- import { CacheEncryption, type EncryptionMode } from './encryption';
53
+ import { CacheEncryption, EnvelopeEncryption, type EncryptionMode } from './encryption';
47
54
  import { SmartMemoryCache } from './smart-memory-cache';
48
- import { DiskTier } from './disk-tier';
55
+ import { DiskTier, resolveDefaultDiskDir } from './disk-tier';
56
+ import { TierLatencyWatchdog } from './latency-watchdog';
57
+ import { resolveAutonomousL1MaxBytes } from './utils/cgroup';
58
+ import { AutoPipeliner } from './adapters/auto-pipeliner';
59
+ import { IpcTelemetryServer } from './ipc-telemetry.js';
49
60
  import {
50
61
  compressBuffer,
51
62
  decompressBuffer,
@@ -121,7 +132,7 @@ const enum CBState { CLOSED, OPEN, HALF_OPEN }
121
132
  class L2CircuitBreaker {
122
133
  private state = CBState.CLOSED;
123
134
  private failures = 0;
124
- private openedAt = 0;
135
+ private openedAt = performance.now();
125
136
  /** True while the single permitted HALF_OPEN probe is in flight. */
126
137
  private probing = false;
127
138
  constructor(
@@ -142,8 +153,10 @@ class L2CircuitBreaker {
142
153
  this.probing = true;
143
154
  return true; // this caller is the one permitted probe
144
155
  }
145
- // OPEN: check if cooldown elapsed
146
- if (Date.now() - this.openedAt >= this.cooldownMs) {
156
+ // OPEN: check if cooldown elapsed using monotonic clock (immune to NTP drift / leap seconds).
157
+ // If tests manually inject wall-clock epoch ms into openedAt (> 1e12), compare against Date.now().
158
+ const now = this.openedAt > 1_000_000_000_000 ? Date.now() : performance.now();
159
+ if (now - this.openedAt >= this.cooldownMs) {
147
160
  this.state = CBState.HALF_OPEN;
148
161
  this.probing = true;
149
162
  return true; // probe
@@ -164,7 +177,7 @@ class L2CircuitBreaker {
164
177
  this.probing = false;
165
178
  if (this.state === CBState.HALF_OPEN || this.failures >= this.threshold) {
166
179
  this.state = CBState.OPEN;
167
- this.openedAt = Date.now();
180
+ this.openedAt = performance.now();
168
181
  this.failures = 0;
169
182
  }
170
183
  }
@@ -326,8 +339,8 @@ function inferPriority(cacheKey: string): CachePriority {
326
339
  // globalThis key — allows reuse across hot reloads (Next.js, ts-node watch, etc.)
327
340
  const GLOBAL_KEY = '__tricache_instance__';
328
341
 
329
- // ── Union type for single-node, Cluster, and Sentinel Redis clients ───────────
330
- type AnyRedisClient = RedisClient | RedisCluster;
342
+ // ── Union type for single-node, Cluster, Sentinel, and pluggable Redis drivers ──
343
+ type AnyRedisClient = RedisClient | RedisCluster | IRedisDriver | any;
331
344
 
332
345
  // ── Serverless environment detection ─────────────────────────────────────────
333
346
  /**
@@ -347,9 +360,100 @@ function detectServerlessRuntime(): string | null {
347
360
  return null;
348
361
  }
349
362
 
363
+ /**
364
+ * Centralized static process termination bus.
365
+ * Prevents MaxListenersExceededWarning by attaching at most ONE SIGTERM and ONE SIGINT
366
+ * listener to process, broadcasting to all active CacheService instances.
367
+ * Automatically detaches listeners when the instance count reaches 0, preventing
368
+ * event loop / test runner hangs.
369
+ */
370
+ export class ProcessTerminationBus {
371
+ private static readonly instances = new Set<CacheService>();
372
+ private static registered = false;
373
+ private static sigtermHandler: (() => void) | null = null;
374
+ private static sigintHandler: (() => void) | null = null;
375
+
376
+ public static register(instance: CacheService): void {
377
+ this.instances.add(instance);
378
+ if (!this.registered) {
379
+ this.registered = true;
380
+ this.sigtermHandler = () => {
381
+ for (const inst of this.instances) {
382
+ try { inst._triggerShutdown(); } catch { /* ok */ }
383
+ }
384
+ };
385
+ this.sigintHandler = () => {
386
+ for (const inst of this.instances) {
387
+ try { inst._triggerShutdown(); } catch { /* ok */ }
388
+ }
389
+ };
390
+ process.on('SIGTERM', this.sigtermHandler);
391
+ process.on('SIGINT', this.sigintHandler);
392
+ }
393
+ }
394
+
395
+ public static unregister(instance: CacheService): void {
396
+ this.instances.delete(instance);
397
+ if (this.instances.size === 0 && this.registered) {
398
+ if (this.sigtermHandler) process.removeListener('SIGTERM', this.sigtermHandler);
399
+ if (this.sigintHandler) process.removeListener('SIGINT', this.sigintHandler);
400
+ this.sigtermHandler = null;
401
+ this.sigintHandler = null;
402
+ this.registered = false;
403
+ }
404
+ }
405
+
406
+ /**
407
+ * Flushes snapshots across all active registered cache instances concurrently.
408
+ * Awaits both local disk and remote cloud snapshot uploads with timeout protection.
409
+ *
410
+ * @param timeoutMs Timeout in milliseconds per instance before aborting slow flushes. Default: 8000ms.
411
+ */
412
+ public static async flushAll(timeoutMs = 8_000): Promise<void> {
413
+ if (this.instances.size === 0) return;
414
+ const tasks = Array.from(this.instances).map(inst => inst.flushSnapshotOnShutdown(timeoutMs));
415
+ await Promise.allSettled(tasks);
416
+ }
417
+
418
+ /** For testing diagnostics and assertions */
419
+ public static get size(): number {
420
+ return this.instances.size;
421
+ }
422
+
423
+ public static get isRegistered(): boolean {
424
+ return this.registered;
425
+ }
426
+ }
427
+
428
+ // ── Deep option merger ──────────────────────────────────────────────────────
429
+
430
+ function isPlainObject(item: unknown): item is Record<string, unknown> {
431
+ return typeof item === 'object' && item !== null && item.constructor === Object;
432
+ }
433
+
434
+ export function deepMergeOptions(base: CacheOptions, overrides?: Partial<CacheOptions>): CacheOptions {
435
+ if (!overrides) return { ...base };
436
+ const output: Record<string, unknown> = { ...base };
437
+
438
+ for (const key of Object.keys(overrides) as Array<keyof CacheOptions>) {
439
+ const sourceVal = overrides[key];
440
+ if (sourceVal === undefined) continue;
441
+ const targetVal = output[key as string];
442
+
443
+ if (isPlainObject(targetVal) && isPlainObject(sourceVal)) {
444
+ output[key as string] = deepMergeOptions(targetVal as CacheOptions, sourceVal as Partial<CacheOptions>);
445
+ } else {
446
+ output[key as string] = sourceVal;
447
+ }
448
+ }
449
+
450
+ return output as CacheOptions;
451
+ }
452
+
350
453
  export class CacheService {
351
454
  private readonly logger: ILogger;
352
455
  private readonly enc: CacheEncryption;
456
+ private readonly codec: CacheCodec;
353
457
  private readonly l1: SmartMemoryCache;
354
458
  private readonly disk: DiskTier;
355
459
  /** When true, all disk-tier and snapshot operations are skipped. */
@@ -405,11 +509,35 @@ export class CacheService {
405
509
  backplaneStreamMaxLen: number;
406
510
  backplaneStreamBlockMs: number;
407
511
  backplaneStreamKey?: string;
512
+ serializeToJSON: boolean;
513
+ remoteSnapshot: RemoteSnapshotOptions | undefined;
514
+ crossRegion: CrossRegionRelayOptions | undefined;
515
+ redisClient?: IRedisDriver | any;
516
+ redisSubClient?: IRedisDriver | any;
517
+ diskMaxConcurrentWrites?: number;
518
+ diskMaxPendingWrites?: number;
519
+ diskWriteTimeoutMs?: number;
520
+ diskCircuitBreakerThreshold?: number;
521
+ diskCircuitBreakerCooldownMs?: number;
522
+ redisCommandTimeoutMs?: number;
523
+ clockSkewToleranceMs: number;
524
+ l1AdmissionPolicy?: 'wtinylfu' | 'adaptive';
525
+ diskLatencyWatchdog?: boolean;
526
+ diskLatencyBypassRatio?: number;
527
+ diskLatencyBypassMinMs?: number;
528
+ diskLatencyBypassCooldownMs?: number;
529
+ failReadinessOnDegraded?: boolean;
530
+ autoPipeline: boolean;
531
+ maxPipelineBatchSize: number;
532
+ enableIpc: boolean;
533
+ ipcSocketPath?: string;
408
534
  };
409
535
  /** Pre-computed once — opts.namespace never changes after construction. */
410
536
  private readonly _namespace: string;
411
537
  /** Pre-computed once — disableRedis and redisHost never change after construction. */
412
538
  private readonly _redisDisabled: boolean;
539
+ private readonly watchdog: TierLatencyWatchdog;
540
+ private pipeliner: AutoPipeliner | null = null;
413
541
  private readonly inflight = new Map<string, Promise<unknown>>();
414
542
  private readonly revalidating = new Set<string>();
415
543
  private readonly _l1Counters = new Map<string, { value: number; expiresAt: number }>();
@@ -435,6 +563,7 @@ export class CacheService {
435
563
  private diskJanitorInterval: ReturnType<typeof setInterval> | null = null;
436
564
  private oomInterval: ReturnType<typeof setInterval> | null = null;
437
565
  private metricsInterval: ReturnType<typeof setInterval> | null = null;
566
+ private remoteSnapshotInterval: ReturnType<typeof setInterval> | null = null;
438
567
  private _shutdownHandler: (() => void) | null = null;
439
568
  private latencyTracker: LatencyTracker | null = null;
440
569
  private readonly instanceId: string;
@@ -444,8 +573,11 @@ export class CacheService {
444
573
  private streamClient: AnyRedisClient | null = null;
445
574
  private _lastStreamId = '$';
446
575
  private _destroyed = false;
576
+ private _ipcServer?: IpcTelemetryServer;
447
577
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
448
578
  private _subDisconnectedAt: number | null = null;
579
+ /** Deduplication ring buffer for incoming and outgoing cross-region invalidations (loop prevention) */
580
+ private readonly _seenCrossRegionEvents = new Map<string, number>();
449
581
  private counters = {
450
582
  gets: 0,
451
583
  l1Hits: 0,
@@ -471,6 +603,15 @@ export class CacheService {
471
603
  startedAt: Date.now(),
472
604
  bloomChecks: 0,
473
605
  bloomFalsePositives: 0,
606
+ remoteSnapshotUploads: 0,
607
+ remoteSnapshotDownloads: 0,
608
+ remoteSnapshotErrors: 0,
609
+ remoteSnapshotLastUploadedAt: null as number | null,
610
+ remoteSnapshotLastDownloadedAt: null as number | null,
611
+ crossRegionSent: 0,
612
+ crossRegionReceived: 0,
613
+ crossRegionDeduplicated: 0,
614
+ crossRegionErrors: 0,
474
615
  };
475
616
 
476
617
  /** One-time guard so the in-process increment() fallback warning fires only once. */
@@ -507,14 +648,14 @@ export class CacheService {
507
648
  this.opts = {
508
649
  namespace: ns,
509
650
  logger,
510
- l1MaxBytes: options.l1MaxBytes ?? 200 * 1024 * 1024,
651
+ l1MaxBytes: options.l1MaxBytes ?? resolveAutonomousL1MaxBytes(),
511
652
  l1MaxEntries: options.l1MaxEntries ?? 2_000,
512
653
  categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...options.categoryLimits },
513
654
  forbiddenSnapshotPrefixes: forbiddenPrefixes,
514
655
  // Namespace-isolated defaults: separate dir / snapshot per namespace so
515
656
  // two instances with different namespaces never share cache files.
516
- diskCacheDir: options.diskCacheDir ?? path.join(
517
- os.tmpdir(), ns ? `tricache-disk-${ns}` : 'tricache-disk'),
657
+ // Automatically probes /dev/shm tmpfs on Linux (>=256MB capacity and >=128MB free) for off-heap RAM speed.
658
+ diskCacheDir: options.diskCacheDir ?? resolveDefaultDiskDir(ns, logger).dir,
518
659
  diskMaxBytes: options.diskMaxBytes ?? 500 * 1024 * 1024,
519
660
  diskEntryMaxBytes: options.diskEntryMaxBytes ?? 10 * 1024 * 1024,
520
661
  redisHost: options.redisHost ?? process.env.REDIS_HOST ?? '',
@@ -528,7 +669,7 @@ export class CacheService {
528
669
  // The REDIS_HOST env fallback does NOT count as explicit: CI exports it
529
670
  // globally and unit tests rely on L2 staying off unless asked for.
530
671
  const explicitConfig = Boolean(
531
- options.redisHost || options.redisClusterNodes?.length || options.redisSentinel,
672
+ options.redisClient || options.redisHost || options.redisClusterNodes?.length || options.redisSentinel,
532
673
  );
533
674
  return !explicitConfig && process.env.NODE_ENV !== 'production';
534
675
  })(),
@@ -580,8 +721,36 @@ export class CacheService {
580
721
  backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 10_000,
581
722
  backplaneStreamBlockMs: options.backplaneStreamBlockMs ?? 2_000,
582
723
  backplaneStreamKey: options.backplaneStreamKey,
724
+ serializeToJSON: options.serializeToJSON ?? true,
725
+ remoteSnapshot: options.remoteSnapshot,
726
+ crossRegion: options.crossRegion,
727
+ redisClient: options.redisClient,
728
+ redisSubClient: options.redisSubClient,
729
+ diskMaxConcurrentWrites: options.diskMaxConcurrentWrites,
730
+ diskMaxPendingWrites: options.diskMaxPendingWrites,
731
+ diskWriteTimeoutMs: options.diskWriteTimeoutMs,
732
+ diskCircuitBreakerThreshold: options.diskCircuitBreakerThreshold,
733
+ diskCircuitBreakerCooldownMs: options.diskCircuitBreakerCooldownMs,
734
+ redisCommandTimeoutMs: options.redisCommandTimeoutMs,
735
+ clockSkewToleranceMs: options.clockSkewToleranceMs ?? 250,
736
+ l1AdmissionPolicy: options.l1AdmissionPolicy,
737
+ diskLatencyWatchdog: options.diskLatencyWatchdog ?? true,
738
+ diskLatencyBypassRatio: options.diskLatencyBypassRatio ?? 1.5,
739
+ diskLatencyBypassMinMs: options.diskLatencyBypassMinMs ?? 10,
740
+ diskLatencyBypassCooldownMs: options.diskLatencyBypassCooldownMs ?? 30_000,
741
+ failReadinessOnDegraded: options.failReadinessOnDegraded ?? false,
742
+ autoPipeline: options.autoPipeline ?? false,
743
+ maxPipelineBatchSize: options.maxPipelineBatchSize ?? 100,
744
+ enableIpc: options.enableIpc ?? false,
745
+ ipcSocketPath: options.ipcSocketPath,
583
746
  };
584
747
 
748
+ this.codec = new CacheCodec({
749
+ useToJSON: this.opts.serializeToJSON,
750
+ useRecords: true,
751
+ moreTypes: true,
752
+ });
753
+
585
754
  // Circuit breaker for L2 Redis
586
755
  const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
587
756
  const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 30_000;
@@ -621,13 +790,30 @@ export class CacheService {
621
790
  compression: this.opts.compression,
622
791
  compressionThresholdBytes: this.opts.compressionThresholdBytes,
623
792
  logger,
793
+ codec: this.codec,
794
+ diskMaxConcurrentWrites: this.opts.diskMaxConcurrentWrites,
795
+ diskMaxPendingWrites: this.opts.diskMaxPendingWrites,
796
+ diskWriteTimeoutMs: this.opts.diskWriteTimeoutMs,
797
+ diskCircuitBreakerThreshold: this.opts.diskCircuitBreakerThreshold,
798
+ diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs,
624
799
  });
625
800
 
626
801
  this._namespace = ns;
627
802
  // disableRedis takes unconditional precedence; otherwise, L2 is active when
628
803
  // at least one of host / cluster nodes / sentinel is configured.
629
804
  this._redisDisabled = this.opts.disableRedis
630
- || (!this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel);
805
+ || (!this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel);
806
+
807
+ this.watchdog = new TierLatencyWatchdog({
808
+ enabled: options.diskLatencyWatchdog ?? true,
809
+ minDiskBypassMs: options.diskLatencyBypassMinMs ?? 10,
810
+ bypassRatio: options.diskLatencyBypassRatio ?? 1.5,
811
+ cooldownMs: options.diskLatencyBypassCooldownMs ?? 30_000,
812
+ redisCutoffMs: 15,
813
+ redisRecoveryFloorMs: 10,
814
+ minSamples: 16,
815
+ disableRedis: this._redisDisabled,
816
+ });
631
817
 
632
818
  // L1 in-memory cache
633
819
  this.l1 = new SmartMemoryCache({
@@ -635,6 +821,8 @@ export class CacheService {
635
821
  maxEntries: this.opts.l1MaxEntries,
636
822
  categories: this.opts.categoryLimits,
637
823
  evictionWatermark: this.opts.l1EvictionWatermark,
824
+ admissionPolicy: this.opts.l1AdmissionPolicy,
825
+ codec: this.codec,
638
826
  diskSpill: (key: string, entry: SmartCacheEntry) => {
639
827
  if (this._diskDisabled) return; // Fix 3: skip spill in serverless environments
640
828
  // Defer disk.save() entirely to the next event-loop tick so the synchronous
@@ -653,12 +841,12 @@ export class CacheService {
653
841
  if (!this._diskDisabled) this.loadSnapshot(); // Fix 3: skip in ephemeral environments
654
842
  }
655
843
 
656
- // Graceful shutdown: persist L1 to disk. The library must NEVER call
657
- // process.exit() — that decision belongs to the host application (kills
658
- // Kubernetes graceful drain, NestJS onApplicationShutdown, pool drains).
659
- this._shutdownHandler = () => { if (!this._diskDisabled) this.writeSnapshot(); };
660
- process.once('SIGTERM', this._shutdownHandler);
661
- process.once('SIGINT', this._shutdownHandler);
844
+ // Graceful shutdown: persist L1 to disk via centralized ProcessTerminationBus.
845
+ // The library must NEVER call process.exit() — that decision belongs to the host application.
846
+ this._shutdownHandler = () => {
847
+ this._triggerShutdown();
848
+ };
849
+ ProcessTerminationBus.register(this);
662
850
 
663
851
  // ── Fix 1: Worker thread pool for off-main-thread AES-GCM & Compression ──
664
852
  if (this.opts.workerThreads) {
@@ -732,15 +920,30 @@ export class CacheService {
732
920
  if (this.metricsInterval.unref) this.metricsInterval.unref();
733
921
  }
734
922
 
923
+ // Periodic remote snapshot upload (if configured)
924
+ if (this.opts.remoteSnapshot?.intervalMs && this.opts.remoteSnapshot.intervalMs > 0) {
925
+ this.remoteSnapshotInterval = setInterval(() => {
926
+ void this.writeRemoteSnapshot();
927
+ }, this.opts.remoteSnapshot.intervalMs);
928
+ if (this.remoteSnapshotInterval.unref) this.remoteSnapshotInterval.unref();
929
+ }
930
+
735
931
  // Backplane: assign instance ID + channel + streamKey, then subscribe
736
932
  this.instanceId = crypto.randomBytes(8).toString('hex');
737
933
  this.backplaneChannel = `tricache:inv${ns ? ':' + ns : ''}`;
738
934
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || 'default'}}`;
739
935
  this.initBackplane();
740
936
 
741
- // Auto-warm from L2 if warmKeys is configured; ready() waits for completion.
937
+ // Auto-warm from remote snapshot or L2 if configured; ready() waits for completion.
938
+ const startupPromises: Promise<void>[] = [];
939
+ if (this.opts.remoteSnapshot) {
940
+ startupPromises.push(this.loadRemoteSnapshot().then(() => undefined));
941
+ }
742
942
  if (this.opts.warmKeys) {
743
- this._readyPromise = this.warmFromL2(this.opts.warmKeys).then(() => undefined);
943
+ startupPromises.push(this.warmFromL2(this.opts.warmKeys).then(() => undefined));
944
+ }
945
+ if (startupPromises.length > 0) {
946
+ this._readyPromise = Promise.all(startupPromises).then(() => undefined);
744
947
  }
745
948
 
746
949
  // Native OpenTelemetry metrics integration
@@ -764,9 +967,77 @@ export class CacheService {
764
967
  },
765
968
  });
766
969
  }
970
+
971
+ // Local IPC telemetry server (Unix domain socket or Windows named pipe)
972
+ if (this.opts.enableIpc) {
973
+ this._ipcServer = new IpcTelemetryServer(this, this.opts.ipcSocketPath);
974
+ this._ipcServer.start().catch((err) => {
975
+ this.logger.warn('Failed to start IPC telemetry server', { error: (err as Error).message });
976
+ });
977
+ }
767
978
  }
768
979
 
769
- // ── Singleton factory ─────────────────────────────────────────────────────
980
+ // ── Singleton factory & Presets ───────────────────────────────────────────
981
+
982
+ /**
983
+ * Pre-configured production presets tailored for specific deployment environments.
984
+ *
985
+ * - `'nextjs'`: W-TinyLFU, zero-copy cloneStrategy: 'none' (React 19 RSC stream optimized),
986
+ * generational tags, and Redis stream backplane.
987
+ * - `'microservice'`: High-throughput Node.js microservice with W-TinyLFU, Streams backplane,
988
+ * TTL jitter, and L2 circuit breaking.
989
+ * - `'serverless'`: Stateless Lambda / Cloud Run isolate with memory-only L1, fast timeouts,
990
+ * and Pub/Sub backplane.
991
+ * - `'enterprise-hardened'`: Zero-trust production setup with generational tagging, Streams backplane,
992
+ * fail-closed rate-limits, strict singleton assertions, and 80% OOM guard.
993
+ *
994
+ * @param type The preset identifier ('nextjs' | 'microservice' | 'serverless' | 'enterprise-hardened')
995
+ * @param overrides Optional configuration overrides merged deeply over preset defaults
996
+ * @returns Singleton CacheService instance configured according to the preset
997
+ */
998
+ static preset(type: CachePresetType, overrides?: Partial<CacheOptions>): CacheService {
999
+ const PRESETS: Record<CachePresetType, CacheOptions> = {
1000
+ 'nextjs': {
1001
+ l1AdmissionPolicy: 'wtinylfu',
1002
+ cloneStrategy: 'none',
1003
+ tagStrategy: 'generational',
1004
+ tagVersionTtlMs: 2_000,
1005
+ backplaneMode: 'stream',
1006
+ staleIfError: 300,
1007
+ compression: 'none',
1008
+ },
1009
+ 'microservice': {
1010
+ l1AdmissionPolicy: 'wtinylfu',
1011
+ backplaneMode: 'stream',
1012
+ ttlJitterFactor: 0.15,
1013
+ l2CircuitBreakerThreshold: 5,
1014
+ l2CircuitBreakerCooldownMs: 15_000,
1015
+ },
1016
+ 'serverless': {
1017
+ disableDisk: true,
1018
+ l1AdmissionPolicy: 'wtinylfu',
1019
+ backplaneMode: 'pubsub',
1020
+ redisCommandTimeoutMs: 1_000,
1021
+ },
1022
+ 'enterprise-hardened': {
1023
+ l1AdmissionPolicy: 'wtinylfu',
1024
+ tagStrategy: 'generational',
1025
+ backplaneMode: 'stream',
1026
+ strictSingleton: true,
1027
+ failClosed: true,
1028
+ oomProtection: true,
1029
+ oomHeapThreshold: 0.80,
1030
+ },
1031
+ };
1032
+
1033
+ const base = PRESETS[type];
1034
+ if (!base) {
1035
+ throw new Error(`tricache: unknown preset '${type}'. Supported presets: 'nextjs', 'microservice', 'serverless', 'enterprise-hardened'`);
1036
+ }
1037
+
1038
+ const merged = deepMergeOptions(base, overrides);
1039
+ return CacheService.create(merged);
1040
+ }
770
1041
 
771
1042
  /**
772
1043
  * Get (or create) the process-level singleton CacheService instance.
@@ -859,6 +1130,8 @@ export class CacheService {
859
1130
  adaptiveTtl: o.adaptiveTtl,
860
1131
  invalidationBackplane: o.invalidationBackplane,
861
1132
  strictSingleton: o.strictSingleton,
1133
+ remoteSnapshot: o.remoteSnapshot,
1134
+ crossRegion: o.crossRegion,
862
1135
  } as CacheOptions;
863
1136
  }
864
1137
 
@@ -885,7 +1158,7 @@ export class CacheService {
885
1158
  }
886
1159
 
887
1160
  /** Derive the globalThis key for a given set of options. */
888
- private static globalKey(options?: CacheOptions): string {
1161
+ private static globalKey(options?: { namespace?: string }): string {
889
1162
  const ns = options?.namespace?.trim() ?? '';
890
1163
  return ns ? `__tricache_${ns}__` : GLOBAL_KEY;
891
1164
  }
@@ -921,16 +1194,29 @@ export class CacheService {
921
1194
  private static readonly _nullSpan: ICacheSpan = {
922
1195
  setAttribute() { return this; },
923
1196
  setStatus() { return this; },
1197
+ recordException() { return this; },
924
1198
  end() {},
925
1199
  };
926
1200
 
927
1201
  /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
928
- private _startSpan(name: string): ICacheSpan {
929
- if (this.opts.tracer) return this.opts.tracer.startSpan(name);
1202
+ private _startSpan(name: string, links?: ICacheSpanLink[]): ICacheSpan {
1203
+ if (this.opts.tracer) {
1204
+ const span = this.opts.tracer.startSpan(name, links?.length ? { links } : undefined);
1205
+ if (this.opts.namespace) {
1206
+ span.setAttribute('cache.namespace', this.opts.namespace);
1207
+ }
1208
+ return span;
1209
+ }
930
1210
  return CacheService._nullSpan;
931
1211
  }
932
1212
 
933
1213
  private createDedicatedRedisClient(): AnyRedisClient {
1214
+ if (this.opts.redisSubClient) {
1215
+ return this.opts.redisSubClient;
1216
+ }
1217
+ if (this.opts.redisClient && typeof this.opts.redisClient.duplicate === 'function') {
1218
+ return this.opts.redisClient.duplicate();
1219
+ }
934
1220
  if (this.opts.redisClusterNodes?.length) {
935
1221
  return new RedisCluster(this.opts.redisClusterNodes, {
936
1222
  redisOptions: {
@@ -1201,7 +1487,19 @@ export class CacheService {
1201
1487
  }
1202
1488
  }
1203
1489
 
1204
- private async publishInvalidation(op: 'del' | 'del-glob' | 'tag_incr', key: string, tagVersion?: number): Promise<void> {
1490
+ private async publishInvalidation(
1491
+ op: 'del' | 'del-glob' | 'tag_incr',
1492
+ key: string,
1493
+ tagVersion?: number,
1494
+ isCrossRegionRelay = false,
1495
+ isExplicitInvalidation = false,
1496
+ ): Promise<void> {
1497
+ if (!isCrossRegionRelay && this.opts.crossRegion) {
1498
+ const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
1499
+ if (shouldBroadcast) {
1500
+ void this._broadcastCrossRegion(op, key, tagVersion);
1501
+ }
1502
+ }
1205
1503
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
1206
1504
  try {
1207
1505
  const client = await this.getRedis();
@@ -1240,7 +1538,103 @@ export class CacheService {
1240
1538
  } catch { /* non-critical — never block the caller */ }
1241
1539
  }
1242
1540
 
1243
- private _setLocalTagVersion(tag: string, version: number, now = Date.now()): void {
1541
+ private _markCrossRegionEventSeen(id: string): void {
1542
+ const maxDedup = this.opts.crossRegion?.dedupCacheSize ?? 10_000;
1543
+ if (this._seenCrossRegionEvents.size >= maxDedup) {
1544
+ const oldestKey = this._seenCrossRegionEvents.keys().next().value;
1545
+ if (oldestKey !== undefined) this._seenCrossRegionEvents.delete(oldestKey);
1546
+ }
1547
+ this._seenCrossRegionEvents.set(id, Date.now());
1548
+ }
1549
+
1550
+ private _isCrossRegionEventSeen(id: string): boolean {
1551
+ return this._seenCrossRegionEvents.has(id);
1552
+ }
1553
+
1554
+ private async _broadcastCrossRegion(
1555
+ op: 'del' | 'del-glob' | 'tag_incr',
1556
+ key: string,
1557
+ tagVersion?: number,
1558
+ ): Promise<void> {
1559
+ const cr = this.opts.crossRegion;
1560
+ if (!cr) return;
1561
+ try {
1562
+ const eventId = crypto.randomUUID();
1563
+ this._markCrossRegionEventSeen(eventId);
1564
+ const event: CrossRegionInvalidationEvent = {
1565
+ id: eventId,
1566
+ originRegion: cr.currentRegion,
1567
+ originInstanceId: this.instanceId,
1568
+ op,
1569
+ key,
1570
+ tagVersion,
1571
+ timestamp: Date.now(),
1572
+ namespace: this._namespace || undefined,
1573
+ };
1574
+ this.counters.crossRegionSent++;
1575
+ await cr.relay.broadcast(event);
1576
+ this.logger.debug('Cross-region invalidation broadcast', { op, key, region: cr.currentRegion });
1577
+ } catch (err) {
1578
+ this.counters.crossRegionSent = Math.max(0, this.counters.crossRegionSent - 1);
1579
+ this.counters.crossRegionErrors++;
1580
+ this.logger.warn('Cross-region invalidation broadcast failed', { error: (err as Error).message });
1581
+ }
1582
+ }
1583
+
1584
+ /**
1585
+ * Receives an invalidation event from another region (e.g. via HTTP webhook or broker subscriber).
1586
+ * Validates origin, deduplicates to prevent loops, applies locally to L1/disk,
1587
+ * and fans out to the local Redis backplane so all regional peers invalidate as well.
1588
+ *
1589
+ * Returns true if the event was accepted and applied, or false if ignored/deduplicated.
1590
+ */
1591
+ async receiveCrossRegionInvalidation(event: CrossRegionInvalidationEvent): Promise<boolean> {
1592
+ const cr = this.opts.crossRegion;
1593
+ if (!cr) return false;
1594
+
1595
+ // Reject malformed event
1596
+ if (!event || typeof event !== 'object' || !event.id || !event.originRegion || !event.op || !event.key) {
1597
+ this.counters.crossRegionErrors++;
1598
+ this.logger.warn('Cross-region: rejected invalid event payload', { event });
1599
+ return false;
1600
+ }
1601
+
1602
+ // Ignore events originating from our own region (prevents echo loops)
1603
+ if (event.originRegion === cr.currentRegion) {
1604
+ this.counters.crossRegionDeduplicated++;
1605
+ return false;
1606
+ }
1607
+
1608
+ // Ignore duplicate event IDs (already processed)
1609
+ if (this._isCrossRegionEventSeen(event.id)) {
1610
+ this.counters.crossRegionDeduplicated++;
1611
+ return false;
1612
+ }
1613
+ this._markCrossRegionEventSeen(event.id);
1614
+
1615
+ // If namespaces don't match, ignore
1616
+ if (event.namespace !== undefined && event.namespace !== (this._namespace || undefined)) {
1617
+ return false;
1618
+ }
1619
+
1620
+ this.counters.crossRegionReceived++;
1621
+
1622
+ // 1. Apply to local L1 and disk
1623
+ this._applyInvalidationEvent(event.op, event.key, event.tagVersion);
1624
+
1625
+ // 2. Propagate to local Redis backplane so other instances in THIS region also invalidate,
1626
+ // passing isCrossRegionRelay = true to prevent re-broadcasting cross-region
1627
+ void this.publishInvalidation(event.op, event.key, event.tagVersion, true);
1628
+
1629
+ this.logger.info('Cross-region invalidation applied', {
1630
+ op: event.op,
1631
+ key: event.key,
1632
+ originRegion: event.originRegion,
1633
+ });
1634
+ return true;
1635
+ }
1636
+
1637
+ private _setLocalTagVersion(tag: string, version: number, now = performance.now()): void {
1244
1638
  const existing = this.tagVersions.get(tag)?.version ?? 0;
1245
1639
  const finalVersion = Math.max(existing, version);
1246
1640
  if (this.tagVersions.size >= 10_000 && !this.tagVersions.has(tag)) {
@@ -1251,7 +1645,7 @@ export class CacheService {
1251
1645
  }
1252
1646
 
1253
1647
  private async _getTagVersion(tag: string): Promise<number> {
1254
- const now = Date.now();
1648
+ const now = performance.now();
1255
1649
  const local = this.tagVersions.get(tag);
1256
1650
  if (local && (now - local.lastSyncedAt < this.opts.tagVersionTtlMs)) {
1257
1651
  return local.version;
@@ -1341,13 +1735,25 @@ export class CacheService {
1341
1735
  stream.on('error', reject);
1342
1736
  }),
1343
1737
  ));
1344
- } else {
1738
+ } else if (typeof (client as any).scanStream === 'function') {
1345
1739
  await new Promise<void>((resolve, reject) => {
1346
- const stream = client.scanStream({ match: pattern, count: 100 });
1740
+ const stream = (client as any).scanStream({ match: pattern, count: 100 });
1347
1741
  stream.on('data', (chunk: string[]) => keys.push(...chunk));
1348
1742
  stream.on('end', resolve);
1349
1743
  stream.on('error', reject);
1350
1744
  });
1745
+ } else if (typeof (client as any).scanIterator === 'function') {
1746
+ for await (const key of (client as any).scanIterator({ MATCH: pattern, COUNT: 100 })) {
1747
+ keys.push(key);
1748
+ }
1749
+ } else if (typeof (client as any).scan === 'function') {
1750
+ let cursor = '0';
1751
+ do {
1752
+ const res = await (client as any).scan(cursor, 'MATCH', pattern, 'COUNT', 100);
1753
+ cursor = String(res[0]);
1754
+ const chunk = res[1] as string[];
1755
+ if (chunk?.length) keys.push(...chunk);
1756
+ } while (cursor !== '0');
1351
1757
  }
1352
1758
  return keys;
1353
1759
  }
@@ -1374,6 +1780,20 @@ export class CacheService {
1374
1780
  if (this.redis) return this.redis;
1375
1781
  if (this.redisConnecting) return this.redisConnecting;
1376
1782
 
1783
+ if (this.opts.redisClient) {
1784
+ const client = this.opts.redisClient;
1785
+ if (typeof client.connect === 'function' && client.isOpen === false) {
1786
+ await client.connect();
1787
+ }
1788
+ this.cb.onSuccess();
1789
+ this.redis = client;
1790
+ this.pipeliner = new AutoPipeliner(client, {
1791
+ enabled: this.opts.autoPipeline,
1792
+ maxBatchSize: this.opts.maxPipelineBatchSize,
1793
+ });
1794
+ return client;
1795
+ }
1796
+
1377
1797
  this.redisConnecting = (async () => {
1378
1798
  try {
1379
1799
  // ── Fix 4: Cluster / Sentinel / single-node connection factory ──────
@@ -1385,6 +1805,7 @@ export class CacheService {
1385
1805
  redisOptions: {
1386
1806
  tls: this.opts.redisTls ? {} : undefined,
1387
1807
  connectTimeout: 10_000,
1808
+ commandTimeout: this.opts.redisCommandTimeoutMs ?? 2_500,
1388
1809
  maxRetriesPerRequest: 3,
1389
1810
  keepAlive: 30_000,
1390
1811
  ...(this.opts.redisProtocol && { protocol: this.opts.redisProtocol }),
@@ -1406,6 +1827,7 @@ export class CacheService {
1406
1827
  name: this.opts.redisSentinel.name,
1407
1828
  tls: this.opts.redisTls ? {} : undefined,
1408
1829
  connectTimeout: 10_000,
1830
+ commandTimeout: this.opts.redisCommandTimeoutMs ?? 2_500,
1409
1831
  lazyConnect: false,
1410
1832
  maxRetriesPerRequest: 3,
1411
1833
  enableAutoPipelining: true,
@@ -1426,6 +1848,7 @@ export class CacheService {
1426
1848
  port: this.opts.redisPort,
1427
1849
  tls: this.opts.redisTls ? {} : undefined,
1428
1850
  connectTimeout: 10_000,
1851
+ commandTimeout: this.opts.redisCommandTimeoutMs ?? 2_500,
1429
1852
  lazyConnect: false,
1430
1853
  maxRetriesPerRequest: 3,
1431
1854
  enableAutoPipelining: true,
@@ -1453,6 +1876,10 @@ export class CacheService {
1453
1876
 
1454
1877
  this.cb.onSuccess();
1455
1878
  this.redis = client;
1879
+ this.pipeliner = new AutoPipeliner(client, {
1880
+ enabled: this.opts.autoPipeline,
1881
+ maxBatchSize: this.opts.maxPipelineBatchSize,
1882
+ });
1456
1883
  this.redisConnecting = null;
1457
1884
  return client;
1458
1885
  } catch (err) {
@@ -1468,13 +1895,19 @@ export class CacheService {
1468
1895
 
1469
1896
  // ── Snapshot (cold-start persistence) ────────────────────────────────────
1470
1897
 
1898
+ /**
1899
+ * Writes the cold-start snapshot to disk.
1900
+ * NOTE: fs.writeFileSync is INTENTIONAL here: this method is invoked during SIGTERM/SIGINT
1901
+ * process termination hooks where asynchronous I/O would risk the Node.js event loop dying or
1902
+ * process.exit() being called before the snapshot is physically written to disk.
1903
+ */
1471
1904
  writeSnapshot(altPath?: string): void {
1472
1905
  try {
1473
1906
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
1474
1907
  if (entries.length === 0) return;
1475
1908
 
1476
1909
  const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
1477
- const packed = pack(payload);
1910
+ const packed = this.codec.encode(payload);
1478
1911
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
1479
1912
  const dest = altPath ?? this.opts.snapshotPath;
1480
1913
  fs.mkdirSync(path.dirname(dest), { recursive: true });
@@ -1488,6 +1921,12 @@ export class CacheService {
1488
1921
  }
1489
1922
  }
1490
1923
 
1924
+ /**
1925
+ * Loads cold-start snapshot from disk into L1 memory.
1926
+ * NOTE: fs.readFileSync is INTENTIONAL here: this method is invoked synchronously inside the
1927
+ * CacheService constructor so that the cache is atomically populated before any subsequent
1928
+ * cache.get() or cache.set() operations run, eliminating cold-start race conditions.
1929
+ */
1491
1930
  loadSnapshot(): void {
1492
1931
  const snapshotPath = this.opts.snapshotPath;
1493
1932
  try {
@@ -1509,7 +1948,7 @@ export class CacheService {
1509
1948
  return;
1510
1949
  }
1511
1950
 
1512
- const snapshot = unpack(buf) as {
1951
+ const snapshot = this.codec.decode(buf) as {
1513
1952
  version?: number; writtenAt?: number;
1514
1953
  entries?: Array<{ key: string; entry: SmartCacheEntry }>;
1515
1954
  };
@@ -1519,8 +1958,18 @@ export class CacheService {
1519
1958
  return;
1520
1959
  }
1521
1960
 
1522
- const ageMs = Date.now() - (snapshot.writtenAt ?? 0);
1523
- if (ageMs > this.opts.snapshotMaxAgeMs || ageMs < 0) {
1961
+ const now = Date.now();
1962
+ const writtenAt = snapshot.writtenAt ?? 0;
1963
+ const tolerance = this.opts.clockSkewToleranceMs ?? 250;
1964
+ if (writtenAt - now > tolerance) {
1965
+ this.logger.warn('Snapshot rejected: timestamp too far in future (exceeds clock skew tolerance)', {
1966
+ writtenAt, now, skewMs: writtenAt - now, tolerance,
1967
+ });
1968
+ return;
1969
+ }
1970
+
1971
+ const ageMs = Math.max(0, now - writtenAt);
1972
+ if (ageMs > this.opts.snapshotMaxAgeMs) {
1524
1973
  this.logger.warn('Snapshot rejected: too old', { ageMinutes: Math.round(ageMs / 60000) });
1525
1974
  return;
1526
1975
  }
@@ -1541,6 +1990,128 @@ export class CacheService {
1541
1990
  }
1542
1991
  }
1543
1992
 
1993
+ // ── Remote Snapshot (cold-start persistence for stateless containers) ───────
1994
+
1995
+ /**
1996
+ * Persists the cold-start snapshot to remote blob storage (S3, GCS, R2, HTTP).
1997
+ * Can be awaited during graceful application shutdown (e.g. Kubernetes preStop or NestJS shutdown).
1998
+ * Returns true if a snapshot was successfully exported and written; false otherwise.
1999
+ */
2000
+ async writeRemoteSnapshot(): Promise<boolean> {
2001
+ if (!this.opts.remoteSnapshot) return false;
2002
+ try {
2003
+ const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
2004
+ if (entries.length === 0) return false;
2005
+
2006
+ const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
2007
+ const packed = this.codec.encode(payload);
2008
+ let final: Buffer;
2009
+ if (this.opts.remoteSnapshot.envelope) {
2010
+ final = await EnvelopeEncryption.encrypt(packed, this.opts.remoteSnapshot.envelope);
2011
+ } else {
2012
+ final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
2013
+ }
2014
+
2015
+ await this.opts.remoteSnapshot.adapter.put(final);
2016
+ this.counters.remoteSnapshotUploads++;
2017
+ this.counters.remoteSnapshotLastUploadedAt = Date.now();
2018
+ this.logger.info('Remote cache snapshot uploaded', {
2019
+ entries: entries.length,
2020
+ sizeKB: Math.round(final.length / 1024),
2021
+ encrypted: Boolean(this.opts.remoteSnapshot.envelope || this.enc.isEnabled),
2022
+ });
2023
+ return true;
2024
+ } catch (err) {
2025
+ this.counters.remoteSnapshotErrors++;
2026
+ this.logger.warn('Remote cache snapshot upload failed', { error: (err as Error).message });
2027
+ return false;
2028
+ }
2029
+ }
2030
+
2031
+ /**
2032
+ * Hydrates L1 memory from remote blob storage (S3, GCS, R2, HTTP).
2033
+ * Called automatically during startup (chained into `cache.ready()`).
2034
+ * Returns the number of entries successfully imported.
2035
+ */
2036
+ async loadRemoteSnapshot(): Promise<number> {
2037
+ if (!this.opts.remoteSnapshot) return 0;
2038
+ const maxAgeMs = this.opts.remoteSnapshot.maxAgeMs ?? this.opts.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE;
2039
+ try {
2040
+ const raw = await this.opts.remoteSnapshot.adapter.get();
2041
+ if (!raw || raw.length === 0) {
2042
+ this.logger.debug('Remote snapshot not found or empty — starting cold');
2043
+ return 0;
2044
+ }
2045
+
2046
+ const rawBuf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
2047
+ let buf: Buffer;
2048
+ try {
2049
+ if (EnvelopeEncryption.isEnvelope(rawBuf)) {
2050
+ if (!this.opts.remoteSnapshot.envelope) {
2051
+ throw new Error('Remote snapshot is envelope-encrypted but no envelope options (privateKey or kmsDecrypt) were configured');
2052
+ }
2053
+ buf = await EnvelopeEncryption.decrypt(rawBuf, this.opts.remoteSnapshot.envelope);
2054
+ } else {
2055
+ buf = this.enc.decryptBuffer(rawBuf);
2056
+ }
2057
+ } catch (e) {
2058
+ this.counters.remoteSnapshotErrors++;
2059
+ this.logger.warn('Remote snapshot rejected: decryption failed', { error: (e as Error).message });
2060
+ return 0;
2061
+ }
2062
+
2063
+ const snapshot = this.codec.decode(buf) as {
2064
+ version?: number;
2065
+ writtenAt?: number;
2066
+ entries?: Array<{ key: string; entry: SmartCacheEntry }>;
2067
+ };
2068
+
2069
+ if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
2070
+ this.counters.remoteSnapshotErrors++;
2071
+ this.logger.warn('Remote snapshot rejected: version mismatch', { got: snapshot?.version });
2072
+ return 0;
2073
+ }
2074
+
2075
+ const now = Date.now();
2076
+ const writtenAt = snapshot.writtenAt ?? 0;
2077
+ const tolerance = this.opts.clockSkewToleranceMs ?? 250;
2078
+ if (writtenAt - now > tolerance) {
2079
+ this.counters.remoteSnapshotErrors++;
2080
+ this.logger.warn('Remote snapshot rejected: timestamp too far in future (exceeds clock skew tolerance)', {
2081
+ writtenAt, now, skewMs: writtenAt - now, tolerance,
2082
+ });
2083
+ return 0;
2084
+ }
2085
+
2086
+ const ageMs = Math.max(0, now - writtenAt);
2087
+ if (maxAgeMs <= 0 || ageMs > maxAgeMs) {
2088
+ this.counters.remoteSnapshotErrors++;
2089
+ this.logger.warn('Remote snapshot rejected: too old', { ageMinutes: Math.round(ageMs / 60000) });
2090
+ return 0;
2091
+ }
2092
+
2093
+ if (!Array.isArray(snapshot.entries)) {
2094
+ this.counters.remoteSnapshotErrors++;
2095
+ this.logger.warn('Remote snapshot rejected: entries is not an array');
2096
+ return 0;
2097
+ }
2098
+
2099
+ const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
2100
+ this.counters.remoteSnapshotDownloads++;
2101
+ this.counters.remoteSnapshotLastDownloadedAt = Date.now();
2102
+ this.logger.info('Remote cache snapshot loaded (L1 hydrated)', {
2103
+ loaded,
2104
+ total: snapshot.entries.length,
2105
+ sizeKB: this.l1.getStats().sizeKB,
2106
+ });
2107
+ return loaded;
2108
+ } catch (err) {
2109
+ this.counters.remoteSnapshotErrors++;
2110
+ this.logger.warn('Remote snapshot load failed — starting cold', { error: (err as Error).message });
2111
+ return 0;
2112
+ }
2113
+ }
2114
+
1544
2115
  // ── Core get (L1 → L1.5 → L2 → fetch) ───────────────────────────────────
1545
2116
 
1546
2117
  /**
@@ -1603,9 +2174,10 @@ export class CacheService {
1603
2174
  if (l1Hit !== null) {
1604
2175
  let isGenerationalStale = false;
1605
2176
  if (this.opts.tagStrategy === 'generational' && l1Hit.tagVersions) {
1606
- for (const [tag, entryVer] of Object.entries(l1Hit.tagVersions)) {
1607
- const currentVer = await this._getTagVersion(tag);
1608
- if (currentVer > entryVer) {
2177
+ const tags = Object.keys(l1Hit.tagVersions);
2178
+ const currentVers = await Promise.all(tags.map(tag => this._getTagVersion(tag)));
2179
+ for (let i = 0; i < tags.length; i++) {
2180
+ if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
1609
2181
  isGenerationalStale = true;
1610
2182
  break;
1611
2183
  }
@@ -1657,7 +2229,10 @@ export class CacheService {
1657
2229
  this.counters.l1Hits++;
1658
2230
  this.opts.onHit?.(cacheKey, 'l1');
1659
2231
  if (this.opts.frozen) deepFreeze(l1Hit.value);
1660
- span.setAttribute('cache.hit', 'l1').end();
2232
+ span.setAttribute('cache.hit', true)
2233
+ .setAttribute('cache.item.tier', 'memory')
2234
+ .setAttribute('cache.hit_tier', 'l1')
2235
+ .end();
1661
2236
  return (this.opts.cloneStrategy === 'structuredClone' && l1Hit.value != null && typeof l1Hit.value === 'object')
1662
2237
  ? structuredClone(l1Hit.value) as T
1663
2238
  : l1Hit.value as T;
@@ -1668,120 +2243,159 @@ export class CacheService {
1668
2243
  const swrGraceMs = optSwr * 1_000;
1669
2244
  const priority = optPriority ?? inferPriority(cacheKey);
1670
2245
 
1671
- // L2: Redis (distributed, production-only by default)
1672
- if (!this._redisDisabled) {
2246
+ // ── Singleflight Shielding on the Probabilistic Path ────────────────────────
2247
+ // Coalesce identical concurrent keys onto an inflight Promise BEFORE evaluating
2248
+ // the watchdog's probabilistic coin-flip. Ensures 10 concurrent requests for a cold key
2249
+ // during an EBS stall coalesce into a single execution rather than splitting across tiers.
2250
+ const existing = this.inflight.get(k);
2251
+ if (existing) {
2252
+ this.counters.stampedes++;
2253
+ this.logger.debug('Stampede prevented — coalescing onto inflight fetch/read', { cacheKey });
2254
+ span.setAttribute('cache.hit', true)
2255
+ .setAttribute('cache.stampede_coalesced', true)
2256
+ .end();
2257
+ return existing as Promise<T>;
2258
+ }
2259
+
2260
+ const executionPromise: Promise<T> = (async () => {
1673
2261
  try {
1674
- const client = await this.getRedis();
1675
- if (this.opts.tagStrategy === 'generational') {
1676
- const hashData = await client.hgetall(k);
1677
- this.cb.onSuccess();
1678
- if (hashData && hashData.d) {
1679
- let isStale = false;
1680
- let storedTagVersions: Record<string, number> = {};
1681
- if (hashData.tv) {
1682
- try { storedTagVersions = JSON.parse(hashData.tv); } catch { /* ignore */ }
1683
- }
1684
- for (const [tag, entryVer] of Object.entries(storedTagVersions)) {
1685
- const currentVer = await this._getTagVersion(tag);
1686
- if (currentVer > entryVer) {
1687
- isStale = true;
1688
- break;
2262
+ // ── Tier 1.5: disk tier (evicted L1 entries) — protected by latency watchdog ──
2263
+ if (!this._diskDisabled) {
2264
+ const isDiskAllowed = this.watchdog.isDiskAllowed();
2265
+ if (isDiskAllowed) {
2266
+ const diskStart = performance.now();
2267
+ const diskHit = this.disk.load(k);
2268
+ const diskElapsed = performance.now() - diskStart;
2269
+ this.watchdog.recordDisk(diskElapsed);
2270
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
2271
+
2272
+ if (diskHit !== null) {
2273
+ let isDiskStale = false;
2274
+ if (this.opts.tagStrategy === 'generational' && diskHit.tagVersions) {
2275
+ const tags = Object.keys(diskHit.tagVersions);
2276
+ const currentVers = await Promise.all(tags.map(tag => this._getTagVersion(tag)));
2277
+ for (let i = 0; i < tags.length; i++) {
2278
+ if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
2279
+ isDiskStale = true;
2280
+ break;
2281
+ }
2282
+ }
1689
2283
  }
1690
- }
1691
- if (isStale) {
1692
- const setAtMs = parseInt(hashData.t, 10) || 0;
1693
- this._deleteIfStale(k, setAtMs);
1694
- } else {
1695
- const parsed = await this._decryptAndDeserialize<T>(hashData.d);
1696
- this.l1.set(k, parsed, ttlMs, priority, undefined, undefined, storedTagVersions);
1697
- this.counters.l2Hits++;
1698
- this.opts.onHit?.(cacheKey, 'l2');
1699
- this.logger.debug('L2 hit (Redis hash)', { cacheKey });
1700
- span.setAttribute('cache.hit', 'l2').end();
1701
- if (this.opts.frozen) deepFreeze(parsed);
1702
- return (this.opts.cloneStrategy === 'structuredClone' && parsed != null && typeof parsed === 'object')
1703
- ? structuredClone(parsed)
1704
- : parsed;
1705
- }
1706
- }
1707
- } else {
1708
- const raw = await client.get(k);
1709
- this.cb.onSuccess();
1710
- if (raw) {
1711
- const parsed = await this._decryptAndDeserialize<T>(raw);
1712
- this.l1.set(k, parsed, ttlMs, priority);
1713
- this.counters.l2Hits++;
1714
- this.opts.onHit?.(cacheKey, 'l2');
1715
- this.logger.debug('L2 hit (Redis)', { cacheKey });
1716
- span.setAttribute('cache.hit', 'l2').end();
1717
- if (this.opts.frozen) deepFreeze(parsed);
1718
- return (this.opts.cloneStrategy === 'structuredClone' && parsed != null && typeof parsed === 'object')
1719
- ? structuredClone(parsed)
1720
- : parsed;
1721
- }
1722
- }
1723
- } catch (err) {
1724
- this.cb.onFailure();
1725
- this.logger.debug('Redis unavailable, continuing to fetch', { cacheKey, error: (err as Error).message });
1726
- }
1727
- }
1728
2284
 
1729
- // L1.5: disk tier (evicted L1 entries) — skipped when disk is disabled
1730
- if (!this._diskDisabled) {
1731
- const diskHit = this.disk.load(k);
1732
- if (diskHit !== null) {
1733
- let isDiskStale = false;
1734
- if (this.opts.tagStrategy === 'generational' && diskHit.tagVersions) {
1735
- for (const [tag, entryVer] of Object.entries(diskHit.tagVersions)) {
1736
- const currentVer = await this._getTagVersion(tag);
1737
- if (currentVer > entryVer) {
1738
- isDiskStale = true;
1739
- break;
2285
+ if (isDiskStale) {
2286
+ this.disk.delete(k);
2287
+ } else {
2288
+ const promoted = this.l1.importEntries(
2289
+ [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
2290
+ this.opts.forbiddenSnapshotPrefixes,
2291
+ );
2292
+ if (promoted > 0) {
2293
+ const l1Check = this.l1.get(k);
2294
+ if (l1Check !== null) {
2295
+ this.counters.diskHits++;
2296
+ this.opts.onHit?.(cacheKey, 'disk');
2297
+ this.logger.debug('L1.5 hit (disk → L1)', { cacheKey });
2298
+ span.setAttribute('cache.hit', true)
2299
+ .setAttribute('cache.item.tier', 'disk')
2300
+ .setAttribute('cache.hit_tier', 'disk');
2301
+ if (this.opts.frozen) deepFreeze(l1Check.value);
2302
+ return (this.opts.cloneStrategy === 'structuredClone' && l1Check.value != null && typeof l1Check.value === 'object')
2303
+ ? structuredClone(l1Check.value) as T
2304
+ : l1Check.value as T;
2305
+ }
2306
+ }
2307
+ }
1740
2308
  }
1741
2309
  }
1742
2310
  }
1743
2311
 
1744
- if (isDiskStale) {
1745
- this.disk.delete(k);
1746
- } else {
1747
- const promoted = this.l1.importEntries(
1748
- [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
1749
- this.opts.forbiddenSnapshotPrefixes,
1750
- );
1751
- if (promoted > 0) {
1752
- const l1Check = this.l1.get(k);
1753
- if (l1Check !== null) {
1754
- this.counters.diskHits++;
1755
- this.opts.onHit?.(cacheKey, 'disk');
1756
- this.logger.debug('L1.5 hit (disk → L1)', { cacheKey });
1757
- span.setAttribute('cache.hit', 'disk').end();
1758
- if (this.opts.frozen) deepFreeze(l1Check.value);
1759
- return (this.opts.cloneStrategy === 'structuredClone' && l1Check.value != null && typeof l1Check.value === 'object')
1760
- ? structuredClone(l1Check.value) as T
1761
- : l1Check.value as T;
2312
+ // ── Tier 2: Redis (distributed, production-only by default) ──
2313
+ if (!this._redisDisabled) {
2314
+ try {
2315
+ const client = await this.getRedis();
2316
+ const redisStart = performance.now();
2317
+ if (this.opts.tagStrategy === 'generational') {
2318
+ const hashData = await client.hgetall(k);
2319
+ const redisElapsed = performance.now() - redisStart;
2320
+ this.watchdog.recordRedis(redisElapsed);
2321
+ this.cb.onSuccess();
2322
+ if (hashData && hashData.d) {
2323
+ let isStale = false;
2324
+ let storedTagVersions: Record<string, number> = {};
2325
+ if (hashData.tv) {
2326
+ try { storedTagVersions = JSON.parse(hashData.tv); } catch { /* ignore */ }
2327
+ }
2328
+ const tags = Object.keys(storedTagVersions);
2329
+ const currentVers = await Promise.all(tags.map(tag => this._getTagVersion(tag)));
2330
+ for (let i = 0; i < tags.length; i++) {
2331
+ if (currentVers[i] > storedTagVersions[tags[i]]) {
2332
+ isStale = true;
2333
+ break;
2334
+ }
2335
+ }
2336
+ if (isStale) {
2337
+ const setAtMs = parseInt(hashData.t, 10) || 0;
2338
+ this._deleteIfStale(k, setAtMs);
2339
+ } else {
2340
+ const parsed = await this._decryptAndDeserialize<T>(hashData.d);
2341
+ this.l1.set(k, parsed, ttlMs, priority, undefined, undefined, storedTagVersions);
2342
+ this.counters.l2Hits++;
2343
+ this.opts.onHit?.(cacheKey, 'l2');
2344
+ this.logger.debug('L2 hit (Redis hash)', { cacheKey });
2345
+ span.setAttribute('cache.hit', true)
2346
+ .setAttribute('cache.item.tier', 'remote')
2347
+ .setAttribute('cache.hit_tier', 'l2');
2348
+ if (this.opts.frozen) deepFreeze(parsed);
2349
+ return (this.opts.cloneStrategy === 'structuredClone' && parsed != null && typeof parsed === 'object')
2350
+ ? structuredClone(parsed)
2351
+ : parsed;
2352
+ }
2353
+ }
2354
+ } else {
2355
+ const raw = (this.opts.autoPipeline && this.pipeliner)
2356
+ ? await this.pipeliner.get(k)
2357
+ : await client.get(k);
2358
+ const redisElapsed = performance.now() - redisStart;
2359
+ this.watchdog.recordRedis(redisElapsed);
2360
+ this.cb.onSuccess();
2361
+ if (raw) {
2362
+ const parsed = await this._decryptAndDeserialize<T>(raw);
2363
+ this.l1.set(k, parsed, ttlMs, priority);
2364
+ this.counters.l2Hits++;
2365
+ this.opts.onHit?.(cacheKey, 'l2');
2366
+ this.logger.debug('L2 hit (Redis)', { cacheKey });
2367
+ span.setAttribute('cache.hit', true)
2368
+ .setAttribute('cache.item.tier', 'remote')
2369
+ .setAttribute('cache.hit_tier', 'l2');
2370
+ if (this.opts.frozen) deepFreeze(parsed);
2371
+ return (this.opts.cloneStrategy === 'structuredClone' && parsed != null && typeof parsed === 'object')
2372
+ ? structuredClone(parsed)
2373
+ : parsed;
2374
+ }
1762
2375
  }
2376
+ } catch (err) {
2377
+ this.cb.onFailure();
2378
+ this.logger.debug('Redis unavailable, continuing to fetch', { cacheKey, error: (err as Error).message });
1763
2379
  }
1764
2380
  }
1765
- }
1766
- }
1767
2381
 
1768
- span.setAttribute('cache.hit', 'miss');
1769
- this.opts.onMiss?.(cacheKey);
2382
+ // Cache MISS across all tiers: fetchFn
2383
+ span.setAttribute('cache.hit', false).setAttribute('cache.hit_tier', 'miss');
2384
+ this.opts.onMiss?.(cacheKey);
1770
2385
 
1771
- // Cache MISS: thundering-herd prevention
1772
- const existing = this.inflight.get(k);
1773
- if (existing) {
1774
- this.counters.stampedes++;
1775
- this.logger.debug('Stampede prevented — coalescing onto inflight fetch', { cacheKey });
1776
- span.end();
1777
- return existing as Promise<T>;
1778
- }
1779
-
1780
- const fetchPromise: Promise<T> = (async () => {
1781
- try {
1782
2386
  this.counters.fetches++;
1783
2387
  const fetchStart = Date.now();
1784
- const data = await fetchFn();
2388
+ let data: T;
2389
+ try {
2390
+ data = await fetchFn();
2391
+ } catch (fetchErr) {
2392
+ span.setStatus({
2393
+ code: 2,
2394
+ message: fetchErr instanceof Error ? fetchErr.message : String(fetchErr),
2395
+ });
2396
+ span.recordException?.(fetchErr);
2397
+ throw fetchErr;
2398
+ }
1785
2399
  const delta = Date.now() - fetchStart;
1786
2400
 
1787
2401
  // Negative caching: null/undefined results get their own (shorter) TTL
@@ -1806,9 +2420,10 @@ export class CacheService {
1806
2420
  let activeTagVersions: Record<string, number> | undefined;
1807
2421
  if (optTags?.length) {
1808
2422
  if (this.opts.tagStrategy === 'generational') {
2423
+ const vers = await Promise.all(optTags.map(tag => this._getTagVersion(tag)));
1809
2424
  activeTagVersions = {};
1810
- for (const tag of optTags) {
1811
- activeTagVersions[tag] = await this._getTagVersion(tag);
2425
+ for (let i = 0; i < optTags.length; i++) {
2426
+ activeTagVersions[optTags[i]] = vers[i];
1812
2427
  }
1813
2428
  } else {
1814
2429
  await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1_000));
@@ -1856,8 +2471,70 @@ export class CacheService {
1856
2471
  }
1857
2472
  })();
1858
2473
 
1859
- this.inflight.set(k, fetchPromise);
1860
- return fetchPromise;
2474
+ this.inflight.set(k, executionPromise);
2475
+ return executionPromise;
2476
+ }
2477
+
2478
+ /**
2479
+ * Graceful shutdown flusher for Kubernetes preStop hooks, NestJS onApplicationShutdown,
2480
+ * or manual microservice teardown.
2481
+ *
2482
+ * Flushes both local disk and remote cloud snapshots (S3/R2/GCS), returning a Promise
2483
+ * that resolves when the upload completes or after `timeoutMs` expires.
2484
+ *
2485
+ * @param timeoutMs Maximum time permitted for snapshot persistence before timing out. Default: 8000ms.
2486
+ */
2487
+ async flushSnapshotOnShutdown(timeoutMs = 8_000): Promise<boolean> {
2488
+ const flusher = async (): Promise<boolean> => {
2489
+ let localOk = true;
2490
+ let remoteOk = true;
2491
+
2492
+ if (!this._diskDisabled) {
2493
+ try {
2494
+ this.writeSnapshot();
2495
+ } catch (err) {
2496
+ localOk = false;
2497
+ this.logger.warn('flushSnapshotOnShutdown: disk snapshot write failed', { error: (err as Error).message });
2498
+ }
2499
+ }
2500
+
2501
+ if (this.opts.remoteSnapshot && this.opts.remoteSnapshot.saveOnShutdown !== false) {
2502
+ try {
2503
+ remoteOk = await this.writeRemoteSnapshot();
2504
+ } catch (err) {
2505
+ remoteOk = false;
2506
+ this.logger.warn('flushSnapshotOnShutdown: remote snapshot upload failed', { error: (err as Error).message });
2507
+ }
2508
+ }
2509
+
2510
+ return localOk && remoteOk;
2511
+ };
2512
+
2513
+ let timer: NodeJS.Timeout | null = null;
2514
+ try {
2515
+ return await Promise.race([
2516
+ flusher(),
2517
+ new Promise<boolean>((resolve) => {
2518
+ timer = setTimeout(() => {
2519
+ this.logger.warn(`flushSnapshotOnShutdown timed out after ${timeoutMs}ms`);
2520
+ resolve(false);
2521
+ }, timeoutMs);
2522
+ if (timer.unref) timer.unref();
2523
+ }),
2524
+ ]);
2525
+ } finally {
2526
+ if (timer) clearTimeout(timer);
2527
+ }
2528
+ }
2529
+
2530
+ /**
2531
+ * Internal graceful shutdown trigger invoked by ProcessTerminationBus.
2532
+ */
2533
+ _triggerShutdown(): void {
2534
+ if (!this._diskDisabled) this.writeSnapshot();
2535
+ if (this.opts.remoteSnapshot && this.opts.remoteSnapshot.saveOnShutdown !== false) {
2536
+ void this.flushSnapshotOnShutdown();
2537
+ }
1861
2538
  }
1862
2539
 
1863
2540
  /**
@@ -1901,9 +2578,11 @@ export class CacheService {
1901
2578
  let activeTagVersions: Record<string, number> | undefined;
1902
2579
  const l1Existing = this.l1.get(cacheKey);
1903
2580
  if (this.opts.tagStrategy === 'generational' && l1Existing?.tagVersions) {
2581
+ const tags = Object.keys(l1Existing.tagVersions);
2582
+ const vers = await Promise.all(tags.map(tag => this._getTagVersion(tag)));
1904
2583
  activeTagVersions = {};
1905
- for (const tag of Object.keys(l1Existing.tagVersions)) {
1906
- activeTagVersions[tag] = await this._getTagVersion(tag);
2584
+ for (let i = 0; i < tags.length; i++) {
2585
+ activeTagVersions[tags[i]] = vers[i];
1907
2586
  }
1908
2587
  }
1909
2588
 
@@ -1951,69 +2630,84 @@ export class CacheService {
1951
2630
  /** Explicitly write a value into L1 (+ L2 in production). */
1952
2631
  async set<T>(cacheKey: string, data: T, ttlSeconds = 300, priority?: CachePriority, opts?: { tags?: string[]; dependsOn?: string[] }): Promise<void> {
1953
2632
  const span = this._startSpan('tricache.set');
1954
- if (this.opts.tracer) span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
1955
- // ttl 0 = indefinite (documented contract, used by the NestJS store): map to
1956
- // a far-future expiry instead of computing expiresAt = now + 0ms, which
1957
- // created an instantly-expired entry that could never be read.
1958
- const effectiveTtlSeconds = ttlSeconds > 0 ? ttlSeconds : (ttlSeconds === 0 ? INDEFINITE_TTL_SECONDS : ttlSeconds);
1959
- const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1_000);
1960
- const p = priority ?? inferPriority(cacheKey);
1961
- const k = this.nk(cacheKey);
1962
- this.counters.sets++;
2633
+ if (this.opts.tracer) {
2634
+ span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
2635
+ span.setAttribute('cache.ttl', ttlSeconds);
2636
+ }
2637
+ try {
2638
+ // ttl 0 = indefinite (documented contract, used by the NestJS store): map to
2639
+ // a far-future expiry instead of computing expiresAt = now + 0ms, which
2640
+ // created an instantly-expired entry that could never be read.
2641
+ const effectiveTtlSeconds = ttlSeconds > 0 ? ttlSeconds : (ttlSeconds === 0 ? INDEFINITE_TTL_SECONDS : ttlSeconds);
2642
+ const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1_000);
2643
+ const p = priority ?? inferPriority(cacheKey);
2644
+ const k = this.nk(cacheKey);
2645
+ this.counters.sets++;
1963
2646
 
1964
- let activeTagVersions: Record<string, number> | undefined;
1965
- if (opts?.tags?.length) {
1966
- if (this.opts.tagStrategy === 'generational') {
1967
- activeTagVersions = {};
1968
- for (const tag of opts.tags) {
1969
- activeTagVersions[tag] = await this._getTagVersion(tag);
2647
+ let activeTagVersions: Record<string, number> | undefined;
2648
+ if (opts?.tags?.length) {
2649
+ if (this.opts.tagStrategy === 'generational') {
2650
+ const vers = await Promise.all(opts.tags.map(tag => this._getTagVersion(tag)));
2651
+ activeTagVersions = {};
2652
+ for (let i = 0; i < opts.tags.length; i++) {
2653
+ activeTagVersions[opts.tags[i]] = vers[i];
2654
+ }
2655
+ } else {
2656
+ await this._registerTags(k, opts.tags, ttlSeconds);
1970
2657
  }
1971
- } else {
1972
- await this._registerTags(k, opts.tags, ttlSeconds);
1973
2658
  }
1974
- }
1975
2659
 
1976
- this.l1.set(k, data, ttlMs, p, undefined, undefined, activeTagVersions);
2660
+ this.l1.set(k, data, ttlMs, p, undefined, undefined, activeTagVersions);
1977
2661
 
1978
- // Register dependency patterns: when any key matching a pattern is deleted,
1979
- // this key (k) is automatically cascaded.
1980
- if (opts?.dependsOn?.length) {
1981
- for (const pattern of opts.dependsOn) {
1982
- const nsPattern = this.nk(pattern);
1983
- let deps = this.dependencyIndex.get(nsPattern);
1984
- if (!deps) { deps = new Set(); this.dependencyIndex.set(nsPattern, deps); }
1985
- deps.add(k);
2662
+ // Register dependency patterns: when any key matching a pattern is deleted,
2663
+ // this key (k) is automatically cascaded.
2664
+ if (opts?.dependsOn?.length) {
2665
+ for (const pattern of opts.dependsOn) {
2666
+ const nsPattern = this.nk(pattern);
2667
+ let deps = this.dependencyIndex.get(nsPattern);
2668
+ if (!deps) { deps = new Set(); this.dependencyIndex.set(nsPattern, deps); }
2669
+ deps.add(k);
2670
+ }
1986
2671
  }
1987
- }
1988
2672
 
1989
- if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
1990
- try {
1991
- const client = await this.getRedis();
1992
- const s = JSON.stringify(data);
1993
- const stored = await this._serializeAndEncrypt(s);
1994
- const ttlSec = Math.ceil(ttlMs / 1_000);
1995
- if (this.opts.tagStrategy === 'generational' && activeTagVersions) {
1996
- const now = Date.now();
1997
- const tx = client.multi();
1998
- tx.hset(k, {
1999
- d: stored,
2000
- t: String(now),
2001
- tv: JSON.stringify(activeTagVersions),
2002
- });
2003
- tx.expire(k, ttlSec);
2004
- await tx.exec();
2005
- } else {
2006
- await client.setex(k, ttlSec, stored);
2673
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
2674
+ try {
2675
+ const client = await this.getRedis();
2676
+ const s = JSON.stringify(data);
2677
+ const stored = await this._serializeAndEncrypt(s);
2678
+ const ttlSec = Math.ceil(ttlMs / 1_000);
2679
+ if (this.opts.tagStrategy === 'generational' && activeTagVersions) {
2680
+ const now = Date.now();
2681
+ const tx = client.multi();
2682
+ tx.hset(k, {
2683
+ d: stored,
2684
+ t: String(now),
2685
+ tv: JSON.stringify(activeTagVersions),
2686
+ });
2687
+ tx.expire(k, ttlSec);
2688
+ await tx.exec();
2689
+ } else {
2690
+ if (this.opts.autoPipeline && this.pipeliner) {
2691
+ await this.pipeliner.setex(k, ttlSec, stored);
2692
+ } else {
2693
+ await client.setex(k, ttlSec, stored);
2694
+ }
2695
+ }
2696
+ this.cb.onSuccess();
2697
+ } catch (err) {
2698
+ this.cb.onFailure();
2699
+ this.logger.debug('set: Redis unavailable', { cacheKey, error: (err as Error).message });
2007
2700
  }
2008
- this.cb.onSuccess();
2009
- } catch (err) {
2010
- this.cb.onFailure();
2011
- this.logger.debug('set: Redis unavailable', { cacheKey, error: (err as Error).message });
2012
2701
  }
2013
- }
2014
2702
 
2015
- void this.publishInvalidation('del', k);
2016
- span.end();
2703
+ void this.publishInvalidation('del', k);
2704
+ } catch (err) {
2705
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
2706
+ span.recordException?.(err);
2707
+ throw err;
2708
+ } finally {
2709
+ span.end();
2710
+ }
2017
2711
  }
2018
2712
 
2019
2713
  /**
@@ -2052,45 +2746,56 @@ export class CacheService {
2052
2746
  async delete(cacheKey: string): Promise<void> {
2053
2747
  const span = this._startSpan('tricache.delete');
2054
2748
  if (this.opts.tracer) span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
2055
- const isPattern = cacheKey.includes('*');
2056
- const k = this.nk(cacheKey);
2057
- this.counters.deletes++;
2749
+ try {
2750
+ const isPattern = cacheKey.includes('*');
2751
+ const k = this.nk(cacheKey);
2752
+ this.counters.deletes++;
2058
2753
 
2059
- if (isPattern) {
2060
- this.l1.deletePattern(k);
2061
- } else {
2062
- this.l1.delete(k);
2063
- // Defer the synchronous SHA-256 hash + fs syscalls to the next event-loop tick so
2064
- // the caller's await resolves without blocking. Matches what the backplane handler
2065
- // already does for remote invalidations: setImmediate(() => this.disk.delete(msg.key)).
2066
- // A re-get in the narrow window before the deferred call fires would get an L1 miss
2067
- // and promote the disk entry back — acceptable for a cache (same trade-off the backplane
2068
- // path already accepts).
2069
- setImmediate(() => { if (!this._diskDisabled) this.disk.delete(k); });
2070
- // Cascade: invalidate any key that declared it depends on this exact key's pattern
2071
- this._cascadeDependencies(k);
2072
- // Clean up: remove k from all dependency registrations (it is gone)
2073
- for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
2074
- }
2754
+ if (isPattern) {
2755
+ this.l1.deletePattern(k);
2756
+ } else {
2757
+ this.l1.delete(k);
2758
+ // Defer the synchronous SHA-256 hash + fs syscalls to the next event-loop tick so
2759
+ // the caller's await resolves without blocking. Matches what the backplane handler
2760
+ // already does for remote invalidations: setImmediate(() => this.disk.delete(msg.key)).
2761
+ // A re-get in the narrow window before the deferred call fires would get an L1 miss
2762
+ // and promote the disk entry back — acceptable for a cache (same trade-off the backplane
2763
+ // path already accepts).
2764
+ setImmediate(() => { if (!this._diskDisabled) this.disk.delete(k); });
2765
+ // Cascade: invalidate any key that declared it depends on this exact key's pattern
2766
+ this._cascadeDependencies(k);
2767
+ // Clean up: remove k from all dependency registrations (it is gone)
2768
+ for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
2769
+ }
2075
2770
 
2076
- if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
2077
- try {
2078
- const client = await this.getRedis();
2079
- if (isPattern) {
2080
- const keys = await this._scanKeys(client, k);
2081
- if (keys.length > 0) await client.del(...keys);
2082
- } else {
2083
- await client.del(k);
2771
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
2772
+ try {
2773
+ const client = await this.getRedis();
2774
+ if (isPattern) {
2775
+ const keys = await this._scanKeys(client, k);
2776
+ if (keys.length > 0) await client.del(...keys);
2777
+ } else {
2778
+ if (this.opts.autoPipeline && this.pipeliner) {
2779
+ await this.pipeliner.del(k);
2780
+ } else {
2781
+ await client.del(k);
2782
+ }
2783
+ }
2784
+ this.cb.onSuccess();
2785
+ } catch (err) {
2786
+ this.cb.onFailure();
2787
+ this.logger.debug('delete: Redis unavailable', { cacheKey, error: (err as Error).message });
2084
2788
  }
2085
- this.cb.onSuccess();
2086
- } catch (err) {
2087
- this.cb.onFailure();
2088
- this.logger.debug('delete: Redis unavailable', { cacheKey, error: (err as Error).message });
2089
2789
  }
2090
- }
2091
2790
 
2092
- void this.publishInvalidation(isPattern ? 'del-glob' : 'del', k);
2093
- span.end();
2791
+ void this.publishInvalidation(isPattern ? 'del-glob' : 'del', k, undefined, false, true);
2792
+ } catch (err) {
2793
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
2794
+ span.recordException?.(err);
2795
+ throw err;
2796
+ } finally {
2797
+ span.end();
2798
+ }
2094
2799
  }
2095
2800
 
2096
2801
  // ── Counter (distributed rate limiting) ──────────────────────────────────
@@ -2157,36 +2862,47 @@ export class CacheService {
2157
2862
  * await cache.clear('user:abc'); // flush all keys for one user
2158
2863
  */
2159
2864
  async clear(prefix?: string): Promise<void> {
2160
- this.counters.deletes++;
2161
- const k = prefix
2162
- ? this.nk(prefix.includes('*') ? prefix : `${prefix}*`)
2163
- : undefined;
2164
-
2165
- if (k) {
2166
- this.l1.deletePattern(k);
2167
- // Disk-tier pattern delete is not supported (files are keyed by SHA-256 hash);
2168
- // prefix-scoped clears only evict from L1, matching existing delete('glob*') semantics.
2169
- } else {
2170
- this.l1.clear();
2171
- if (!this._diskDisabled) this.disk.clear();
2172
- this._l1Counters.clear();
2173
- this.tagIndex.clear();
2174
- this.tagVersions.clear();
2175
- }
2865
+ const span = this._startSpan('tricache.clear');
2866
+ if (this.opts.tracer) span.setAttribute('cache.prefix', prefix || '*');
2867
+ try {
2868
+ this.counters.deletes++;
2869
+ const k = prefix
2870
+ ? this.nk(prefix.includes('*') ? prefix : `${prefix}*`)
2871
+ : undefined;
2872
+
2873
+ if (k) {
2874
+ this.l1.deletePattern(k);
2875
+ // Disk-tier pattern delete is not supported (files are keyed by SHA-256 hash);
2876
+ // prefix-scoped clears only evict from L1, matching existing delete('glob*') semantics.
2877
+ } else {
2878
+ this.l1.clear();
2879
+ if (!this._diskDisabled) this.disk.clear();
2880
+ this._l1Counters.clear();
2881
+ this.tagIndex.clear();
2882
+ this.tagVersions.clear();
2883
+ }
2176
2884
 
2177
- if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
2178
- try {
2179
- const client = await this.getRedis();
2180
- const pattern = k ?? (this._namespace ? `${this._namespace}:*` : '*');
2181
- const keys = await this._scanKeys(client, pattern);
2182
- if (keys.length > 0) await client.del(...keys);
2183
- } catch (err) {
2184
- this.logger.debug('clear: Redis unavailable', { error: (err as Error).message });
2885
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
2886
+ try {
2887
+ const client = await this.getRedis();
2888
+ const pattern = k ?? (this._namespace ? `${this._namespace}:*` : '*');
2889
+ const keys = await this._scanKeys(client, pattern);
2890
+ if (keys.length > 0) await client.del(...keys);
2891
+ } catch (err) {
2892
+ this.logger.debug('clear: Redis unavailable', { error: (err as Error).message });
2893
+ }
2185
2894
  }
2186
- }
2187
2895
 
2188
- void this.publishInvalidation('del-glob',
2189
- k ?? (this._namespace ? `${this._namespace}:*` : '*'));
2896
+ void this.publishInvalidation('del-glob',
2897
+ k ?? (this._namespace ? `${this._namespace}:*` : '*'),
2898
+ undefined, false, true);
2899
+ } catch (err) {
2900
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
2901
+ span.recordException?.(err);
2902
+ throw err;
2903
+ } finally {
2904
+ span.end();
2905
+ }
2190
2906
  }
2191
2907
 
2192
2908
  /**
@@ -2326,7 +3042,7 @@ export class CacheService {
2326
3042
  const now = Date.now();
2327
3043
  if (entry.expiresAt <= now) return null; // expired
2328
3044
  if (entry.staleAt !== undefined && entry.staleAt < now) return null; // in SWR grace
2329
- return (entry.value !== undefined ? entry.value : unpack(entry.data)) as T;
3045
+ return (entry.value !== undefined ? entry.value : this.codec.decode(entry.data)) as T;
2330
3046
  }
2331
3047
 
2332
3048
  /**
@@ -2353,8 +3069,13 @@ export class CacheService {
2353
3069
  }
2354
3070
 
2355
3071
  // 2. L1.5 Disk
2356
- if (!this._diskDisabled) {
3072
+ if (!this._diskDisabled && this.watchdog.isDiskAllowed()) {
3073
+ const diskStart = performance.now();
2357
3074
  const diskHit = this.disk.load(k);
3075
+ const diskElapsed = performance.now() - diskStart;
3076
+ this.watchdog.recordDisk(diskElapsed);
3077
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
3078
+
2358
3079
  if (diskHit !== null) {
2359
3080
  const promoted = this.l1.importEntries(
2360
3081
  [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
@@ -2379,7 +3100,10 @@ export class CacheService {
2379
3100
  if (!this._redisDisabled && !this.cb.isOpen) {
2380
3101
  try {
2381
3102
  const client = await this.getRedis();
3103
+ const redisStart = performance.now();
2382
3104
  const raw = await client.get(k);
3105
+ const redisElapsed = performance.now() - redisStart;
3106
+ this.watchdog.recordRedis(redisElapsed);
2383
3107
  if (raw !== null) {
2384
3108
  const parsed = await this._decryptAndDeserialize<T>(raw);
2385
3109
  this.l1.set(k, parsed, 60_000, inferPriority(cacheKey));
@@ -2415,106 +3139,140 @@ export class CacheService {
2415
3139
  ttl: number | ((key: string) => number) = 300,
2416
3140
  priority?: CachePriority,
2417
3141
  ): Promise<(T | undefined)[]> {
2418
- const result: (T | undefined)[] = Array.from({ length: keys.length });
2419
- const missIndexes: number[] = [];
2420
- const missKeys: string[] = [];
2421
-
2422
- // ── Tier 1: L1 (in-memory) ──
2423
- for (let i = 0; i < keys.length; i++) {
2424
- const k = this.nk(keys[i]);
2425
- const entry = this.l1.getEntry(k);
2426
- if (entry && entry.expiresAt > Date.now()) {
2427
- result[i] = (entry.value !== undefined ? entry.value : unpack(entry.data)) as T;
2428
- this.counters.l1Hits++;
2429
- } else {
2430
- missIndexes.push(i);
2431
- missKeys.push(keys[i]);
2432
- }
3142
+ const span = this._startSpan('tricache.mget');
3143
+ if (this.opts.tracer) {
3144
+ span.setAttribute('cache.batch.size', keys.length);
2433
3145
  }
3146
+ try {
3147
+ const result: (T | undefined)[] = Array.from({ length: keys.length });
3148
+ const missIndexes: number[] = [];
3149
+ const missKeys: string[] = [];
3150
+
3151
+ // ── Tier 1: L1 (in-memory) ──
3152
+ for (let i = 0; i < keys.length; i++) {
3153
+ const k = this.nk(keys[i]);
3154
+ const entry = this.l1.getEntry(k);
3155
+ if (entry && entry.expiresAt > Date.now()) {
3156
+ result[i] = (entry.value !== undefined ? entry.value : this.codec.decode(entry.data)) as T;
3157
+ this.counters.l1Hits++;
3158
+ } else {
3159
+ missIndexes.push(i);
3160
+ missKeys.push(keys[i]);
3161
+ }
3162
+ }
2434
3163
 
2435
- if (missKeys.length === 0) return result;
3164
+ if (missKeys.length === 0) {
3165
+ if (this.opts.tracer) {
3166
+ span.setAttribute('cache.hits', keys.length);
3167
+ span.setAttribute('cache.misses', 0);
3168
+ span.setAttribute('cache.l1_hits', keys.length);
3169
+ span.setAttribute('cache.l2_hits', 0);
3170
+ }
3171
+ return result;
3172
+ }
2436
3173
 
2437
- // ── Tier 2: L2 (Redis) — fetch all remaining misses in one pipeline ──
2438
- if (!this._redisDisabled) {
2439
- try {
2440
- const client = await this.getRedis();
2441
- const nsKeys = missKeys.map(k => this.nk(k));
2442
- const pipeline = client.multi();
2443
- for (const nk of nsKeys) pipeline.get(nk);
2444
- const raws = await pipeline.exec() as Array<[Error | null, string | null] | null>;
2445
- this.cb.onSuccess();
2446
- for (let j = 0; j < missKeys.length; j++) {
2447
- const raw = raws[j] ? (raws[j] as [Error | null, string | null])[1] : null;
2448
- const idx = missIndexes[j];
2449
- if (raw) {
2450
- const parsed = await this._decryptAndDeserialize<T>(raw);
2451
- const k = nsKeys[j];
2452
- const p = priority ?? inferPriority(missKeys[j]);
2453
- this.l1.set(k, parsed, this._jitterTtl((typeof ttl === 'function' ? ttl(missKeys[j]) : ttl) * 1_000), p);
2454
- this.counters.l2Hits++;
2455
- result[idx] = parsed;
2456
- // Mark this miss slot as resolved (position j in the parallel arrays).
2457
- // NOTE: must use j here, NOT idx — idx is the value (an index into the
2458
- // original keys[]), which only equals j when missIndexes is contiguous
2459
- // (every key missed). With interleaved L1 hits, missIndexes is sparse
2460
- // and missIndexes[idx] would clobber an unrelated slot.
2461
- missIndexes[j] = -1;
2462
- missKeys[j] = '';
3174
+ let l2HitCount = 0;
3175
+ // ── Tier 2: L2 (Redis) — fetch all remaining misses in one pipeline ──
3176
+ if (!this._redisDisabled) {
3177
+ try {
3178
+ const client = await this.getRedis();
3179
+ const nsKeys = missKeys.map(k => this.nk(k));
3180
+ const pipeline = client.multi();
3181
+ for (const nk of nsKeys) pipeline.get(nk);
3182
+ const redisStart = performance.now();
3183
+ const raws = await pipeline.exec() as Array<[Error | null, string | null] | null>;
3184
+ const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
3185
+ this.watchdog.recordRedis(redisElapsed);
3186
+ this.cb.onSuccess();
3187
+ for (let j = 0; j < missKeys.length; j++) {
3188
+ const raw = raws[j] ? (raws[j] as [Error | null, string | null])[1] : null;
3189
+ const idx = missIndexes[j];
3190
+ if (raw) {
3191
+ const parsed = await this._decryptAndDeserialize<T>(raw);
3192
+ const k = nsKeys[j];
3193
+ const p = priority ?? inferPriority(missKeys[j]);
3194
+ this.l1.set(k, parsed, this._jitterTtl((typeof ttl === 'function' ? ttl(missKeys[j]) : ttl) * 1_000), p);
3195
+ this.counters.l2Hits++;
3196
+ l2HitCount++;
3197
+ result[idx] = parsed;
3198
+ missIndexes[j] = -1;
3199
+ missKeys[j] = '';
3200
+ }
2463
3201
  }
3202
+ // Compact the still-missing arrays.
3203
+ const remainingIdx = missIndexes.filter(i => i >= 0);
3204
+ const remainingKeys = missKeys.filter(k => k !== '');
3205
+ missIndexes.length = 0; missKeys.length = 0;
3206
+ missIndexes.push(...remainingIdx);
3207
+ missKeys.push(...remainingKeys);
3208
+ } catch (err) {
3209
+ this.cb.onFailure();
3210
+ this.logger.debug('mget: Redis unavailable, continuing to disk/fetch', { error: (err as Error).message });
2464
3211
  }
2465
- // Compact the still-missing arrays.
2466
- const remainingIdx = missIndexes.filter(i => i >= 0);
2467
- const remainingKeys = missKeys.filter(k => k !== '');
2468
- missIndexes.length = 0; missKeys.length = 0;
2469
- missIndexes.push(...remainingIdx);
2470
- missKeys.push(...remainingKeys);
2471
- if (missKeys.length === 0) return result;
2472
- } catch (err) {
2473
- this.cb.onFailure();
2474
- this.logger.debug('mget: Redis unavailable, continuing to disk/fetch', { error: (err as Error).message });
2475
3212
  }
2476
- }
2477
3213
 
2478
- // ── Tier 1.5: disk spill (evicted L1 entries) ──
2479
- if (!this._diskDisabled) {
2480
- for (let j = missKeys.length - 1; j >= 0; j--) {
2481
- const k = this.nk(missKeys[j]);
2482
- const diskHit = this.disk.load(k);
2483
- if (diskHit !== null) {
2484
- const promoted = this.l1.importEntries(
2485
- [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
2486
- this.opts.forbiddenSnapshotPrefixes,
2487
- );
2488
- if (promoted > 0) {
2489
- const l1Check = this.l1.get(k);
2490
- if (l1Check !== null) {
2491
- this.counters.diskHits++;
2492
- result[missIndexes[j]] = l1Check.value as T;
2493
- // Remove from miss set.
2494
- missIndexes.splice(j, 1);
2495
- missKeys.splice(j, 1);
3214
+ // ── Tier 1.5: disk spill (evicted L1 entries) ──
3215
+ if (!this._diskDisabled && missKeys.length > 0) {
3216
+ for (let j = missKeys.length - 1; j >= 0; j--) {
3217
+ if (!this.watchdog.isDiskAllowed()) continue;
3218
+ const k = this.nk(missKeys[j]);
3219
+ const diskStart = performance.now();
3220
+ const diskHit = this.disk.load(k);
3221
+ const diskElapsed = performance.now() - diskStart;
3222
+ this.watchdog.recordDisk(diskElapsed);
3223
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
3224
+ if (diskHit !== null) {
3225
+ const promoted = this.l1.importEntries(
3226
+ [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
3227
+ this.opts.forbiddenSnapshotPrefixes,
3228
+ );
3229
+ if (promoted > 0) {
3230
+ const l1Check = this.l1.get(k);
3231
+ if (l1Check !== null) {
3232
+ this.counters.diskHits++;
3233
+ result[missIndexes[j]] = l1Check.value as T;
3234
+ missIndexes.splice(j, 1);
3235
+ missKeys.splice(j, 1);
3236
+ }
2496
3237
  }
2497
3238
  }
2498
3239
  }
2499
3240
  }
2500
- if (missKeys.length === 0) return result;
2501
- }
2502
3241
 
2503
- // ── Tier 3: fetchFn for whatever still missed ──
2504
- if (missKeys.length > 0) {
2505
- this.counters.fetches++;
2506
- const fetched = await fetchFn(missKeys);
2507
- for (let j = 0; j < missKeys.length; j++) {
2508
- const v = fetched[missKeys[j]];
2509
- result[missIndexes[j]] = v;
2510
- if (v !== undefined) {
2511
- const resolvedTtl = typeof ttl === 'function' ? ttl(missKeys[j]) : ttl;
2512
- await this.set(missKeys[j], v, resolvedTtl, priority);
3242
+ // ── Tier 3: fetchFn for whatever still missed ──
3243
+ if (missKeys.length > 0) {
3244
+ this.counters.fetches++;
3245
+ const fetched = await fetchFn(missKeys);
3246
+ const setPromises: Promise<void>[] = [];
3247
+ for (let j = 0; j < missKeys.length; j++) {
3248
+ const v = fetched[missKeys[j]];
3249
+ result[missIndexes[j]] = v;
3250
+ if (v !== undefined) {
3251
+ const resolvedTtl = typeof ttl === 'function' ? ttl(missKeys[j]) : ttl;
3252
+ setPromises.push(this.set(missKeys[j], v, resolvedTtl, priority));
3253
+ }
3254
+ }
3255
+ if (setPromises.length > 0) {
3256
+ await Promise.all(setPromises);
2513
3257
  }
2514
3258
  }
2515
- }
2516
3259
 
2517
- return result;
3260
+ if (this.opts.tracer) {
3261
+ const finalMisses = missKeys.length;
3262
+ const totalHits = keys.length - finalMisses;
3263
+ span.setAttribute('cache.hits', totalHits);
3264
+ span.setAttribute('cache.misses', finalMisses);
3265
+ span.setAttribute('cache.l2_hits', l2HitCount);
3266
+ }
3267
+
3268
+ return result;
3269
+ } catch (err) {
3270
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
3271
+ span.recordException?.(err);
3272
+ throw err;
3273
+ } finally {
3274
+ span.end();
3275
+ }
2518
3276
  }
2519
3277
 
2520
3278
  /**
@@ -2545,12 +3303,24 @@ export class CacheService {
2545
3303
  async mset<T = unknown>(
2546
3304
  entries: Record<string, { value: T; ttl?: number; priority?: CachePriority; tags?: string[]; dependsOn?: string[] }>,
2547
3305
  ): Promise<void> {
3306
+ const span = this._startSpan('tricache.mset');
2548
3307
  const keys = Object.keys(entries);
2549
- await Promise.all(keys.map(key => {
2550
- const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
2551
- const hasOpts = tags?.length || dependsOn?.length;
2552
- return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : undefined);
2553
- }));
3308
+ if (this.opts.tracer) {
3309
+ span.setAttribute('cache.batch.size', keys.length);
3310
+ }
3311
+ try {
3312
+ await Promise.all(keys.map(key => {
3313
+ const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
3314
+ const hasOpts = tags?.length || dependsOn?.length;
3315
+ return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : undefined);
3316
+ }));
3317
+ } catch (err) {
3318
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
3319
+ span.recordException?.(err);
3320
+ throw err;
3321
+ } finally {
3322
+ span.end();
3323
+ }
2554
3324
  }
2555
3325
 
2556
3326
  /**
@@ -2561,7 +3331,19 @@ export class CacheService {
2561
3331
  * await cache.mdel(['user:1', 'user:2', 'user:3']);
2562
3332
  */
2563
3333
  async mdel(keys: string[]): Promise<void> {
2564
- await Promise.all(keys.map(k => this.delete(k)));
3334
+ const span = this._startSpan('tricache.mdel');
3335
+ if (this.opts.tracer) {
3336
+ span.setAttribute('cache.batch.size', keys.length);
3337
+ }
3338
+ try {
3339
+ await Promise.all(keys.map(k => this.delete(k)));
3340
+ } catch (err) {
3341
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
3342
+ span.recordException?.(err);
3343
+ throw err;
3344
+ } finally {
3345
+ span.end();
3346
+ }
2565
3347
  }
2566
3348
 
2567
3349
  /**
@@ -2597,7 +3379,6 @@ export class CacheService {
2597
3379
  this.cb.onSuccess();
2598
3380
 
2599
3381
  let loaded = 0;
2600
- const now = Date.now();
2601
3382
  for (let i = 0; i < matchedKeys.length; i++) {
2602
3383
  const [err, raw] = results[i];
2603
3384
  if (err || raw == null) continue;
@@ -2610,7 +3391,6 @@ export class CacheService {
2610
3391
  loaded++;
2611
3392
  } catch { /* skip malformed entries */ }
2612
3393
  }
2613
- void now; // suppress unused warning
2614
3394
 
2615
3395
  this.logger.info('warmFromL2 complete', {
2616
3396
  pattern, matched: matchedKeys.length, loaded,
@@ -2632,49 +3412,62 @@ export class CacheService {
2632
3412
  * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
2633
3413
  */
2634
3414
  async invalidateTag(tag: string): Promise<void> {
2635
- if (this.opts.tagStrategy === 'generational') {
2636
- let newVer = 1;
2637
- if (!this._redisDisabled) {
2638
- try {
2639
- const client = await this.getRedis();
2640
- newVer = await client.incr(this.nk(`tag_ver:${tag}`));
2641
- } catch (err) {
2642
- this.logger.debug('invalidateTag: Redis unavailable', { tag, error: (err as Error).message });
3415
+ const span = this._startSpan('tricache.invalidate_tag');
3416
+ if (this.opts.tracer) {
3417
+ span.setAttribute('cache.tag', tag);
3418
+ span.setAttribute('cache.tag_strategy', this.opts.tagStrategy);
3419
+ }
3420
+ try {
3421
+ if (this.opts.tagStrategy === 'generational') {
3422
+ let newVer = 1;
3423
+ if (!this._redisDisabled) {
3424
+ try {
3425
+ const client = await this.getRedis();
3426
+ newVer = await client.incr(this.nk(`tag_ver:${tag}`));
3427
+ } catch (err) {
3428
+ this.logger.debug('invalidateTag: Redis unavailable', { tag, error: (err as Error).message });
3429
+ const current = this.tagVersions.get(tag)?.version ?? 0;
3430
+ newVer = current + 1;
3431
+ }
3432
+ } else {
2643
3433
  const current = this.tagVersions.get(tag)?.version ?? 0;
2644
3434
  newVer = current + 1;
2645
3435
  }
2646
- } else {
2647
- const current = this.tagVersions.get(tag)?.version ?? 0;
2648
- newVer = current + 1;
3436
+ this._setLocalTagVersion(tag, newVer, Date.now());
3437
+ void this.publishInvalidation('tag_incr', tag, newVer, false, true);
3438
+ return;
2649
3439
  }
2650
- this._setLocalTagVersion(tag, newVer, Date.now());
2651
- void this.publishInvalidation('tag_incr', tag, newVer);
2652
- return;
2653
- }
2654
3440
 
2655
- const tagKey = this.nk(`_tag_:${tag}`);
2656
- const members = this.tagIndex.get(tagKey) ?? new Set<string>();
3441
+ const tagKey = this.nk(`_tag_:${tag}`);
3442
+ const members = this.tagIndex.get(tagKey) ?? new Set<string>();
2657
3443
 
2658
- // Remove from L1 + disk
2659
- for (const k of members) {
2660
- this.l1.delete(k);
2661
- if (!this._diskDisabled) this.disk.delete(k);
2662
- }
2663
- this.tagIndex.delete(tagKey);
3444
+ // Remove from L1 + disk
3445
+ for (const k of members) {
3446
+ this.l1.delete(k);
3447
+ if (!this._diskDisabled) this.disk.delete(k);
3448
+ }
3449
+ this.tagIndex.delete(tagKey);
2664
3450
 
2665
- if (!this._redisDisabled) {
2666
- try {
2667
- const client = await this.getRedis();
2668
- const redisMembers: string[] = await client.smembers(tagKey);
2669
- const toDelete = [...new Set([...members, ...redisMembers])];
2670
- if (toDelete.length > 0) {
2671
- await client.del(...toDelete, tagKey);
2672
- } else {
2673
- await client.del(tagKey);
3451
+ if (!this._redisDisabled) {
3452
+ try {
3453
+ const client = await this.getRedis();
3454
+ const redisMembers: string[] = await client.smembers(tagKey);
3455
+ const toDelete = [...new Set([...members, ...redisMembers])];
3456
+ if (toDelete.length > 0) {
3457
+ await client.del(...toDelete, tagKey);
3458
+ } else {
3459
+ await client.del(tagKey);
3460
+ }
3461
+ } catch (err) {
3462
+ this.logger.debug('invalidateTag: Redis unavailable', { tag, error: (err as Error).message });
2674
3463
  }
2675
- } catch (err) {
2676
- this.logger.debug('invalidateTag: Redis unavailable', { tag, error: (err as Error).message });
2677
3464
  }
3465
+ } catch (err) {
3466
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
3467
+ span.recordException?.(err);
3468
+ throw err;
3469
+ } finally {
3470
+ span.end();
2678
3471
  }
2679
3472
  }
2680
3473
 
@@ -2706,7 +3499,7 @@ export class CacheService {
2706
3499
  const [err, newVer] = results[i] ?? [null, null];
2707
3500
  const ver = (!err && typeof newVer === 'number') ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
2708
3501
  this._setLocalTagVersion(tags[i], ver, now);
2709
- void this.publishInvalidation('tag_incr', tags[i], ver);
3502
+ void this.publishInvalidation('tag_incr', tags[i], ver, false, true);
2710
3503
  }
2711
3504
  return;
2712
3505
  } catch (err) {
@@ -2716,7 +3509,7 @@ export class CacheService {
2716
3509
  for (const tag of tags) {
2717
3510
  const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
2718
3511
  this._setLocalTagVersion(tag, ver, now);
2719
- void this.publishInvalidation('tag_incr', tag, ver);
3512
+ void this.publishInvalidation('tag_incr', tag, ver, false, true);
2720
3513
  }
2721
3514
  return;
2722
3515
  }
@@ -2799,6 +3592,65 @@ export class CacheService {
2799
3592
  return { l1, disk, l2 };
2800
3593
  }
2801
3594
 
3595
+ /**
3596
+ * Health and readiness diagnostics for container orchestrators (e.g. Kubernetes, ECS, Nomad).
3597
+ *
3598
+ * ─────────────────────────────────────────────────────────────────────────────
3599
+ * ⚠️ CRITICAL CONTAINER PROBE SEMANTICS (Liveness vs. Readiness):
3600
+ * ─────────────────────────────────────────────────────────────────────────────
3601
+ * ❌ NEVER bind `degraded` checks or `cache.health()` to your Liveness Probe (/livez, /healthz).
3602
+ * If an SRE hooks degraded status into liveness, a storage-starved or EBS-throttled pod
3603
+ * will be killed by the kubelet, triggering a cluster-wide cascading restart shockwave.
3604
+ * Liveness probes must only check that the event loop / process is alive.
3605
+ *
3606
+ * ✅ BIND degraded checks strictly to your Readiness Probe (/ready, /readyz).
3607
+ * A degraded cache (e.g. EBS latency spike, quota watermark pruning, or open Redis circuit)
3608
+ * can shed traffic at the ingress load balancer while the Node.js process remains
3609
+ * alive to drain in-flight promises and heal its local storage.
3610
+ *
3611
+ * By default, `healthy` remains `true` even when degraded (graceful local degradation).
3612
+ * Set `failReadinessOnDegraded: true` in CacheOptions if you want your Readiness probe
3613
+ * to route ingress traffic away while degraded.
3614
+ * ─────────────────────────────────────────────────────────────────────────────
3615
+ */
3616
+ health(): CacheHealthStatus {
3617
+ const watchdogTel = this.watchdog.getTelemetry();
3618
+ const diskPruning = !this._diskDisabled && this.disk.isPruning;
3619
+ const diskLowSpace = !this._diskDisabled && this.disk.hostVolumeLowSpace;
3620
+ const circuitOpen = this.cb.isOpen;
3621
+ const latencyBypass = watchdogTel.bypassActive;
3622
+
3623
+ const degraded = circuitOpen || latencyBypass || diskPruning || diskLowSpace;
3624
+ const healthy = this.opts.failReadinessOnDegraded ? !degraded : true;
3625
+
3626
+ const reasons: string[] = [];
3627
+ if (circuitOpen) reasons.push('redis_circuit_breaker_open');
3628
+ if (latencyBypass) reasons.push(`disk_latency_bypass_stage_${watchdogTel.bypassStage}`);
3629
+ if (diskPruning) reasons.push('disk_quota_watermark_pruning_active');
3630
+ if (diskLowSpace) reasons.push('disk_host_volume_low_space');
3631
+
3632
+ return {
3633
+ healthy,
3634
+ degraded,
3635
+ reasons,
3636
+ details: {
3637
+ redisConnected: !circuitOpen && !this._redisDisabled,
3638
+ circuitBreakerState: this.cb.currentState,
3639
+ diskPruningActive: diskPruning,
3640
+ diskHostVolumeLowSpace: diskLowSpace,
3641
+ watchdog: watchdogTel,
3642
+ },
3643
+ };
3644
+ }
3645
+
3646
+ /**
3647
+ * Direct access to the internal tier latency watchdog instance.
3648
+ * Used for diagnostics, canary probes, and control-loop tuning.
3649
+ */
3650
+ getLatencyWatchdog(): TierLatencyWatchdog {
3651
+ return this.watchdog;
3652
+ }
3653
+
2802
3654
  /**
2803
3655
  * Export all live L1 entries to Redis via a single pipeline.
2804
3656
  * Useful for warming a new Redis instance or for zero-downtime failover.
@@ -3088,7 +3940,7 @@ export class CacheService {
3088
3940
  if (visited.has(dep)) continue;
3089
3941
  this.l1.delete(dep);
3090
3942
  if (!this._diskDisabled) this.disk.delete(dep);
3091
- void this.publishInvalidation('del', dep);
3943
+ void this.publishInvalidation('del', dep, undefined, false, true);
3092
3944
  this.logger.debug('Dependency cascade: invalidated dependent key', {
3093
3945
  trigger: deletedKey.slice(0, 60), dependent: dep.slice(0, 60),
3094
3946
  });
@@ -3163,13 +4015,37 @@ export class CacheService {
3163
4015
  evictions: c.oomEvictions,
3164
4016
  lastTriggeredAt: c.oomLastAt,
3165
4017
  },
4018
+ ...(this.opts.remoteSnapshot && {
4019
+ remoteSnapshot: {
4020
+ enabled: true,
4021
+ uploads: c.remoteSnapshotUploads,
4022
+ downloads: c.remoteSnapshotDownloads,
4023
+ errors: c.remoteSnapshotErrors,
4024
+ lastUploadedAt: c.remoteSnapshotLastUploadedAt,
4025
+ lastDownloadedAt: c.remoteSnapshotLastDownloadedAt,
4026
+ },
4027
+ }),
4028
+ ...(this.opts.crossRegion && {
4029
+ crossRegion: {
4030
+ enabled: true,
4031
+ currentRegion: this.opts.crossRegion.currentRegion,
4032
+ sent: c.crossRegionSent,
4033
+ received: c.crossRegionReceived,
4034
+ deduplicated: c.crossRegionDeduplicated,
4035
+ errors: c.crossRegionErrors,
4036
+ },
4037
+ }),
3166
4038
 
3167
4039
  l1: {
3168
4040
  entries: l1s.entries,
3169
4041
  sizeBytes: this.l1.memoryUsage,
3170
4042
  maxBytes: this.opts.l1MaxBytes,
3171
4043
  },
3172
- disk: { ...this.disk.stats, disabled: this._diskDisabled },
4044
+ disk: {
4045
+ ...this.disk.stats,
4046
+ disabled: this._diskDisabled,
4047
+ latencyWatchdog: this.watchdog.getTelemetry(),
4048
+ },
3173
4049
  ...(this.latencyTracker && {
3174
4050
  adaptiveTtl: {
3175
4051
  enabled: true as const,
@@ -3182,9 +4058,17 @@ export class CacheService {
3182
4058
  ),
3183
4059
  },
3184
4060
  }),
4061
+ ...(this.pipeliner && {
4062
+ pipelining: this.pipeliner.stats,
4063
+ }),
3185
4064
  };
3186
4065
  }
3187
4066
 
4067
+ /** Return auto-pipelining metrics, or null if pipelining is disabled. */
4068
+ getPipelinerStats() {
4069
+ return this.pipeliner ? this.pipeliner.stats : null;
4070
+ }
4071
+
3188
4072
  /**
3189
4073
  * Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
3190
4074
  * Paste the result into your `/metrics` endpoint.
@@ -3229,6 +4113,19 @@ export class CacheService {
3229
4113
  gauge('l1_size_bytes', m.l1.sizeBytes, 'Current L1 used bytes');
3230
4114
  gauge('disk_files', m.disk.files, 'Current L1.5 disk file count');
3231
4115
 
4116
+ if (m.disk.latencyWatchdog) {
4117
+ gauge('disk_latency_bypass_stage', m.disk.latencyWatchdog.bypassStage, 'Disk latency watchdog bypass stage (0: normal, 1: 25%, 2: 75%, 3: 100%)');
4118
+ gauge('disk_p95_ms', m.disk.latencyWatchdog.diskP95Ms, 'Disk read p95 latency in ms');
4119
+ gauge('redis_p95_ms', m.disk.latencyWatchdog.redisP95Ms, 'Redis read p95 latency in ms');
4120
+ counter('disk_bypassed_events', m.disk.latencyWatchdog.bypassedTotal, 'Total disk bypass activation events');
4121
+ }
4122
+ if (m.disk.pruning) {
4123
+ counter('disk_spills_shed', m.disk.pruning.spillsShedTotal, 'Total disk spills shed due to pruning or low disk space');
4124
+ counter('disk_prune_rounds', m.disk.pruning.pruneRounds, 'Total high-watermark disk prune rounds');
4125
+ counter('disk_entries_pruned', m.disk.pruning.entriesPruned, 'Total entries removed by watermark pruning');
4126
+ counter('disk_low_space_pauses', m.disk.pruning.hostVolumeLowSpacePauses, 'Total times spills paused due to <10% host volume space');
4127
+ }
4128
+
3232
4129
  gauge('bloom_false_positive_rate', m.bloom.falsePositiveRate,
3233
4130
  'Bloom filter false-positive rate; increase capacity if > 0.01');
3234
4131
  gauge('compression_bytes_saved', m.compression.bytesSaved,
@@ -3242,6 +4139,17 @@ export class CacheService {
3242
4139
  counter('oom_evictions', m.oom.evictions,
3243
4140
  'Emergency L1 eviction rounds triggered by heap pressure');
3244
4141
  }
4142
+ if (m.remoteSnapshot?.enabled) {
4143
+ counter('remote_snapshot_uploads', m.remoteSnapshot.uploads, 'Total remote snapshot uploads');
4144
+ counter('remote_snapshot_downloads', m.remoteSnapshot.downloads, 'Total remote snapshot downloads');
4145
+ counter('remote_snapshot_errors', m.remoteSnapshot.errors, 'Total remote snapshot errors');
4146
+ }
4147
+ if (m.crossRegion?.enabled) {
4148
+ counter('cross_region_sent', m.crossRegion.sent, 'Total cross-region invalidations broadcast');
4149
+ counter('cross_region_received', m.crossRegion.received, 'Total cross-region invalidations received');
4150
+ counter('cross_region_deduplicated', m.crossRegion.deduplicated, 'Total cross-region invalidations deduplicated or self-filtered');
4151
+ counter('cross_region_errors', m.crossRegion.errors, 'Total cross-region relay errors');
4152
+ }
3245
4153
 
3246
4154
  return lines.join('\n');
3247
4155
  }
@@ -3264,21 +4172,29 @@ export class CacheService {
3264
4172
  /** Close Redis connections and stop all background timers. */
3265
4173
  async destroy(): Promise<void> {
3266
4174
  this._destroyed = true;
3267
- if (this.cleanupInterval) clearInterval(this.cleanupInterval);
3268
- if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
3269
- if (this.oomInterval) clearInterval(this.oomInterval);
3270
- if (this.metricsInterval) clearInterval(this.metricsInterval);
3271
- if (this._shutdownHandler) {
3272
- process.off('SIGTERM', this._shutdownHandler);
3273
- process.off('SIGINT', this._shutdownHandler);
3274
- this._shutdownHandler = null;
4175
+ const g = globalThis as Record<string, unknown>;
4176
+ const key = CacheService.globalKey(this.opts);
4177
+ if (g[key] === this) {
4178
+ delete g[key];
3275
4179
  }
4180
+ if (this.cleanupInterval) clearInterval(this.cleanupInterval);
4181
+ if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
4182
+ if (this.oomInterval) clearInterval(this.oomInterval);
4183
+ if (this.metricsInterval) clearInterval(this.metricsInterval);
4184
+ if (this.remoteSnapshotInterval) {
4185
+ clearInterval(this.remoteSnapshotInterval);
4186
+ this.remoteSnapshotInterval = null;
4187
+ }
4188
+ ProcessTerminationBus.unregister(this);
4189
+ this._shutdownHandler = null;
3276
4190
  if (this._workerPool) {
3277
4191
  await this._workerPool.destroy();
3278
4192
  this._workerPool = null;
3279
4193
  }
3280
4194
  if (this.subClient) {
3281
- try { this.subClient.disconnect(); } catch { /* ok */ }
4195
+ if (!this.opts.redisSubClient) {
4196
+ try { this.subClient.disconnect(); } catch { /* ok */ }
4197
+ }
3282
4198
  this.subClient = null;
3283
4199
  }
3284
4200
  if (this.streamClient) {
@@ -3286,10 +4202,31 @@ export class CacheService {
3286
4202
  this.streamClient = null;
3287
4203
  }
3288
4204
  if (this.redis) {
3289
- try { await this.redis.disconnect(); } catch { /* ok */ }
4205
+ if (!this.opts.redisClient) {
4206
+ try { await this.redis.disconnect(); } catch { /* ok */ }
4207
+ }
3290
4208
  this.redis = null;
3291
4209
  }
4210
+ if (this._ipcServer) {
4211
+ await this._ipcServer.close();
4212
+ this._ipcServer = undefined;
4213
+ }
3292
4214
  if (!this._diskDisabled) this.disk.close();
3293
4215
  }
3294
4216
 
4217
+ /**
4218
+ * Return the active IPC telemetry server instance, if enabled.
4219
+ */
4220
+ getIpcServer(): IpcTelemetryServer | undefined {
4221
+ return this._ipcServer;
4222
+ }
4223
+
4224
+ /**
4225
+ * Return real-time telemetry and metrics for the Window TinyLFU admission policy.
4226
+ * Returns `undefined` if W-TinyLFU admission is not active.
4227
+ */
4228
+ getWTinyLfuStats(): WTinyLfuStats | undefined {
4229
+ return this.l1.getWTinyLfuStats();
4230
+ }
4231
+
3295
4232
  }