tricache 0.7.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +89 -1371
  3. package/dashboards/prometheus-scrape.yml +18 -0
  4. package/dashboards/tricache-alerts.yaml +54 -0
  5. package/dashboards/tricache-grafana.json +548 -0
  6. package/dist/cache-service-DVvroyqA.d.ts +886 -0
  7. package/dist/cache-service-KI5ACF3F.js +12 -0
  8. package/dist/chunk-7RV5ZVBB.js +1023 -0
  9. package/dist/chunk-BQRURGGD.js +60 -0
  10. package/dist/chunk-IITRFWHY.js +196 -0
  11. package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
  12. package/dist/{chunk-EUGYR7KR.js → chunk-PL5J3ZNT.js} +3184 -514
  13. package/dist/chunk-QNU7B43J.js +687 -0
  14. package/dist/chunk-UGD4VEPD.js +138 -0
  15. package/dist/chunk-XZL45ABR.js +108 -0
  16. package/dist/cli.cjs +3122 -495
  17. package/dist/cli.d.ts +1 -0
  18. package/dist/cli.js +121 -5
  19. package/dist/dashboard/index.cjs +1065 -0
  20. package/dist/dashboard/index.d.ts +183 -0
  21. package/dist/dashboard/index.js +22 -0
  22. package/dist/drizzle/index.cjs +2846 -494
  23. package/dist/drizzle/index.d.ts +3 -1
  24. package/dist/drizzle/index.js +1 -1
  25. package/dist/edge/index.cjs +1559 -0
  26. package/dist/edge/index.d.ts +127 -0
  27. package/dist/edge/index.js +1109 -0
  28. package/dist/hono/index.cjs +7760 -0
  29. package/dist/hono/index.d.ts +91 -0
  30. package/dist/hono/index.js +185 -0
  31. package/dist/hono-VA9A1m0I.d.ts +371 -0
  32. package/dist/http/index.cjs +3281 -587
  33. package/dist/http/index.d.ts +85 -23
  34. package/dist/http/index.js +176 -78
  35. package/dist/index.cjs +7212 -2505
  36. package/dist/index.d.ts +547 -30
  37. package/dist/index.js +104 -5
  38. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  39. package/dist/nestjs/index.cjs +2787 -487
  40. package/dist/nestjs/index.d.ts +3 -1
  41. package/dist/nestjs/index.js +6 -3
  42. package/dist/next/index.cjs +2804 -501
  43. package/dist/next/index.d.ts +4 -2
  44. package/dist/next/index.js +14 -10
  45. package/dist/prisma/index.d.ts +3 -1
  46. package/dist/serialize-worker.cjs +5 -4
  47. package/dist/serialize-worker.js +1 -1
  48. package/dist/{cache-service-D8tIXmzb.d.ts → types-B_QkVwJ7.d.ts} +622 -662
  49. package/dist/utils-CEsU_Z0s.d.ts +27 -0
  50. package/package.json +48 -10
  51. package/src/adapters/auto-pipeliner.ts +206 -0
  52. package/src/adapters/node-redis.ts +370 -0
  53. package/src/cache-service.ts +1619 -415
  54. package/src/cli.ts +137 -2
  55. package/src/codec.ts +72 -0
  56. package/src/cross-region.ts +245 -0
  57. package/src/dashboard/handler.ts +392 -0
  58. package/src/dashboard/html.ts +594 -0
  59. package/src/dashboard/index.ts +195 -0
  60. package/src/dashboard/types.ts +96 -0
  61. package/src/disk-tier.ts +449 -47
  62. package/src/drizzle/index.ts +86 -86
  63. package/src/edge/adapters/cloudflare-do.ts +130 -0
  64. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  65. package/src/edge/adapters/upstash.ts +143 -0
  66. package/src/edge/cache.ts +797 -0
  67. package/src/edge/crypto.ts +182 -0
  68. package/src/edge/hono.ts +284 -0
  69. package/src/edge/index.ts +37 -0
  70. package/src/edge/types.ts +230 -0
  71. package/src/edge/utils/base64.ts +63 -0
  72. package/src/edge/utils/murmur3.ts +179 -0
  73. package/src/encryption.ts +127 -5
  74. package/src/hono/index.ts +316 -0
  75. package/src/http/express.ts +195 -0
  76. package/src/http/fastify.ts +260 -0
  77. package/src/http/index.ts +44 -258
  78. package/src/http/utils.ts +92 -0
  79. package/src/index.ts +149 -47
  80. package/src/ipc-telemetry.ts +509 -0
  81. package/src/latency-watchdog.ts +282 -0
  82. package/src/nestjs/decorators.ts +161 -161
  83. package/src/nestjs/index.ts +23 -23
  84. package/src/nestjs/tricache.module.ts +104 -104
  85. package/src/nestjs/tricache.store.ts +97 -97
  86. package/src/nestjs/types.ts +79 -79
  87. package/src/next/cache-handler.ts +12 -9
  88. package/src/next/index.ts +37 -37
  89. package/src/next/isr-handler.ts +105 -105
  90. package/src/next/types.ts +130 -130
  91. package/src/remote-snapshot.ts +153 -0
  92. package/src/serialize-worker.ts +120 -120
  93. package/src/sigv4-snapshot-adapter.ts +260 -0
  94. package/src/smart-memory-cache.ts +91 -8
  95. package/src/types.ts +315 -2
  96. package/src/utils/cgroup.ts +100 -0
  97. package/src/utils/tracing.ts +54 -0
  98. package/src/wasm/bloom-filter-wasm.ts +109 -102
  99. package/src/worker-pool.ts +299 -299
  100. package/src/wtiny-lfu.ts +624 -0
  101. package/dist/cache-service-5GATUYAK.js +0 -7
  102. package/dist/chunk-UBSR5UYA.js +0 -0
@@ -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. */
@@ -365,6 +469,8 @@ export class CacheService {
365
469
  redisHost: string; redisPort: number; redisTls: boolean; disableRedis: boolean;
366
470
  encryptionKey: string | undefined; encryptionMode: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor' | undefined; snapshotPath: string; snapshotMaxAgeMs: number;
367
471
  invalidationBackplane: boolean;
472
+ awaitInvalidationBackplane: boolean;
473
+ lockFailClosed: boolean;
368
474
  oomProtection: boolean; oomHeapThreshold: number;
369
475
  oomCheckIntervalMs: number; oomEvictPercent: number;
370
476
  onMetrics: ((m: CacheMetrics) => void) | undefined;
@@ -405,11 +511,35 @@ export class CacheService {
405
511
  backplaneStreamMaxLen: number;
406
512
  backplaneStreamBlockMs: number;
407
513
  backplaneStreamKey?: string;
514
+ serializeToJSON: boolean;
515
+ remoteSnapshot: RemoteSnapshotOptions | undefined;
516
+ crossRegion: CrossRegionRelayOptions | undefined;
517
+ redisClient?: IRedisDriver | any;
518
+ redisSubClient?: IRedisDriver | any;
519
+ diskMaxConcurrentWrites?: number;
520
+ diskMaxPendingWrites?: number;
521
+ diskWriteTimeoutMs?: number;
522
+ diskCircuitBreakerThreshold?: number;
523
+ diskCircuitBreakerCooldownMs?: number;
524
+ redisCommandTimeoutMs?: number;
525
+ clockSkewToleranceMs: number;
526
+ l1AdmissionPolicy?: 'wtinylfu' | 'adaptive';
527
+ diskLatencyWatchdog?: boolean;
528
+ diskLatencyBypassRatio?: number;
529
+ diskLatencyBypassMinMs?: number;
530
+ diskLatencyBypassCooldownMs?: number;
531
+ failReadinessOnDegraded?: boolean;
532
+ autoPipeline: boolean;
533
+ maxPipelineBatchSize: number;
534
+ enableIpc: boolean;
535
+ ipcSocketPath?: string;
408
536
  };
409
537
  /** Pre-computed once — opts.namespace never changes after construction. */
410
538
  private readonly _namespace: string;
411
539
  /** Pre-computed once — disableRedis and redisHost never change after construction. */
412
540
  private readonly _redisDisabled: boolean;
541
+ private readonly watchdog: TierLatencyWatchdog;
542
+ private pipeliner: AutoPipeliner | null = null;
413
543
  private readonly inflight = new Map<string, Promise<unknown>>();
414
544
  private readonly revalidating = new Set<string>();
415
545
  private readonly _l1Counters = new Map<string, { value: number; expiresAt: number }>();
@@ -435,6 +565,7 @@ export class CacheService {
435
565
  private diskJanitorInterval: ReturnType<typeof setInterval> | null = null;
436
566
  private oomInterval: ReturnType<typeof setInterval> | null = null;
437
567
  private metricsInterval: ReturnType<typeof setInterval> | null = null;
568
+ private remoteSnapshotInterval: ReturnType<typeof setInterval> | null = null;
438
569
  private _shutdownHandler: (() => void) | null = null;
439
570
  private latencyTracker: LatencyTracker | null = null;
440
571
  private readonly instanceId: string;
@@ -444,8 +575,62 @@ export class CacheService {
444
575
  private streamClient: AnyRedisClient | null = null;
445
576
  private _lastStreamId = '$';
446
577
  private _destroyed = false;
578
+ private readonly _pendingDiskDeletes = new Set<string>();
579
+ private _globalEpoch = 0;
580
+ private readonly _keyMutationEpochs = new Map<string, number>();
581
+ /**
582
+ * Pattern tombstones for disk tier.
583
+ * Files in the disk tier are keyed by SHA-256 of namespacedKey.
584
+ * Wildcard pattern deletes cannot scan the filesystem synchronously, so we maintain
585
+ * pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
586
+ */
587
+ private readonly _patternTombstones: Array<{ prefix: string; createdAt: number }> = [];
588
+
589
+ private _addPatternTombstone(prefix: string): void {
590
+ const now = Date.now();
591
+ while (this._patternTombstones.length > 0 && (now - this._patternTombstones[0].createdAt > 3_600_000)) {
592
+ this._patternTombstones.shift();
593
+ }
594
+ if (this._patternTombstones.length >= 2_000) {
595
+ this._patternTombstones.shift();
596
+ }
597
+ this._patternTombstones.push({ prefix, createdAt: now });
598
+ }
599
+
600
+ private _isTombstonedByPattern(namespacedKey: string): boolean {
601
+ if (this._patternTombstones.length === 0) return false;
602
+ for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
603
+ if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
604
+ return true;
605
+ }
606
+ }
607
+ return false;
608
+ }
609
+
610
+ private _assertActive(operation: string): void {
611
+ if (this._destroyed) {
612
+ throw new Error(`TriCacheError: Cannot perform '${operation}' on a destroyed CacheService instance (namespace: '${this._namespace || "(default)"}').`);
613
+ }
614
+ }
615
+
616
+ private _bumpKeyMutation(namespacedKey: string): number {
617
+ const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
618
+ this._keyMutationEpochs.set(namespacedKey, next);
619
+ if (this._keyMutationEpochs.size > 50_000) {
620
+ const oldest = this._keyMutationEpochs.keys().next().value;
621
+ if (oldest !== undefined) this._keyMutationEpochs.delete(oldest);
622
+ }
623
+ return next;
624
+ }
625
+
626
+ private _getKeyMutationEpoch(namespacedKey: string): number {
627
+ return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
628
+ }
629
+ private _ipcServer?: IpcTelemetryServer;
447
630
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
448
631
  private _subDisconnectedAt: number | null = null;
632
+ /** Deduplication ring buffer for incoming and outgoing cross-region invalidations (loop prevention) */
633
+ private readonly _seenCrossRegionEvents = new Map<string, number>();
449
634
  private counters = {
450
635
  gets: 0,
451
636
  l1Hits: 0,
@@ -471,6 +656,15 @@ export class CacheService {
471
656
  startedAt: Date.now(),
472
657
  bloomChecks: 0,
473
658
  bloomFalsePositives: 0,
659
+ remoteSnapshotUploads: 0,
660
+ remoteSnapshotDownloads: 0,
661
+ remoteSnapshotErrors: 0,
662
+ remoteSnapshotLastUploadedAt: null as number | null,
663
+ remoteSnapshotLastDownloadedAt: null as number | null,
664
+ crossRegionSent: 0,
665
+ crossRegionReceived: 0,
666
+ crossRegionDeduplicated: 0,
667
+ crossRegionErrors: 0,
474
668
  };
475
669
 
476
670
  /** One-time guard so the in-process increment() fallback warning fires only once. */
@@ -507,14 +701,14 @@ export class CacheService {
507
701
  this.opts = {
508
702
  namespace: ns,
509
703
  logger,
510
- l1MaxBytes: options.l1MaxBytes ?? 200 * 1024 * 1024,
704
+ l1MaxBytes: options.l1MaxBytes ?? resolveAutonomousL1MaxBytes(),
511
705
  l1MaxEntries: options.l1MaxEntries ?? 2_000,
512
706
  categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...options.categoryLimits },
513
707
  forbiddenSnapshotPrefixes: forbiddenPrefixes,
514
708
  // Namespace-isolated defaults: separate dir / snapshot per namespace so
515
709
  // two instances with different namespaces never share cache files.
516
- diskCacheDir: options.diskCacheDir ?? path.join(
517
- os.tmpdir(), ns ? `tricache-disk-${ns}` : 'tricache-disk'),
710
+ // Automatically probes /dev/shm tmpfs on Linux (>=256MB capacity and >=128MB free) for off-heap RAM speed.
711
+ diskCacheDir: options.diskCacheDir ?? resolveDefaultDiskDir(ns, logger).dir,
518
712
  diskMaxBytes: options.diskMaxBytes ?? 500 * 1024 * 1024,
519
713
  diskEntryMaxBytes: options.diskEntryMaxBytes ?? 10 * 1024 * 1024,
520
714
  redisHost: options.redisHost ?? process.env.REDIS_HOST ?? '',
@@ -528,7 +722,7 @@ export class CacheService {
528
722
  // The REDIS_HOST env fallback does NOT count as explicit: CI exports it
529
723
  // globally and unit tests rely on L2 staying off unless asked for.
530
724
  const explicitConfig = Boolean(
531
- options.redisHost || options.redisClusterNodes?.length || options.redisSentinel,
725
+ options.redisClient || options.redisHost || options.redisClusterNodes?.length || options.redisSentinel,
532
726
  );
533
727
  return !explicitConfig && process.env.NODE_ENV !== 'production';
534
728
  })(),
@@ -538,6 +732,8 @@ export class CacheService {
538
732
  os.tmpdir(), ns ? `tricache-snapshot-${ns}.msgpack` : 'tricache-snapshot.msgpack'),
539
733
  snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
540
734
  invalidationBackplane: options.invalidationBackplane ?? true,
735
+ awaitInvalidationBackplane: options.awaitInvalidationBackplane ?? false,
736
+ lockFailClosed: options.lockFailClosed ?? false,
541
737
  oomProtection: options.oomProtection ?? true,
542
738
  oomHeapThreshold: options.oomHeapThreshold ?? 0.85,
543
739
  oomCheckIntervalMs: options.oomCheckIntervalMs ?? 10_000,
@@ -580,8 +776,36 @@ export class CacheService {
580
776
  backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 10_000,
581
777
  backplaneStreamBlockMs: options.backplaneStreamBlockMs ?? 2_000,
582
778
  backplaneStreamKey: options.backplaneStreamKey,
779
+ serializeToJSON: options.serializeToJSON ?? true,
780
+ remoteSnapshot: options.remoteSnapshot,
781
+ crossRegion: options.crossRegion,
782
+ redisClient: options.redisClient,
783
+ redisSubClient: options.redisSubClient,
784
+ diskMaxConcurrentWrites: options.diskMaxConcurrentWrites,
785
+ diskMaxPendingWrites: options.diskMaxPendingWrites,
786
+ diskWriteTimeoutMs: options.diskWriteTimeoutMs,
787
+ diskCircuitBreakerThreshold: options.diskCircuitBreakerThreshold,
788
+ diskCircuitBreakerCooldownMs: options.diskCircuitBreakerCooldownMs,
789
+ redisCommandTimeoutMs: options.redisCommandTimeoutMs,
790
+ clockSkewToleranceMs: options.clockSkewToleranceMs ?? 250,
791
+ l1AdmissionPolicy: options.l1AdmissionPolicy,
792
+ diskLatencyWatchdog: options.diskLatencyWatchdog ?? true,
793
+ diskLatencyBypassRatio: options.diskLatencyBypassRatio ?? 1.5,
794
+ diskLatencyBypassMinMs: options.diskLatencyBypassMinMs ?? 10,
795
+ diskLatencyBypassCooldownMs: options.diskLatencyBypassCooldownMs ?? 30_000,
796
+ failReadinessOnDegraded: options.failReadinessOnDegraded ?? false,
797
+ autoPipeline: options.autoPipeline ?? false,
798
+ maxPipelineBatchSize: options.maxPipelineBatchSize ?? 100,
799
+ enableIpc: options.enableIpc ?? false,
800
+ ipcSocketPath: options.ipcSocketPath,
583
801
  };
584
802
 
803
+ this.codec = new CacheCodec({
804
+ useToJSON: this.opts.serializeToJSON,
805
+ useRecords: true,
806
+ moreTypes: true,
807
+ });
808
+
585
809
  // Circuit breaker for L2 Redis
586
810
  const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
587
811
  const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 30_000;
@@ -621,13 +845,30 @@ export class CacheService {
621
845
  compression: this.opts.compression,
622
846
  compressionThresholdBytes: this.opts.compressionThresholdBytes,
623
847
  logger,
848
+ codec: this.codec,
849
+ diskMaxConcurrentWrites: this.opts.diskMaxConcurrentWrites,
850
+ diskMaxPendingWrites: this.opts.diskMaxPendingWrites,
851
+ diskWriteTimeoutMs: this.opts.diskWriteTimeoutMs,
852
+ diskCircuitBreakerThreshold: this.opts.diskCircuitBreakerThreshold,
853
+ diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs,
624
854
  });
625
855
 
626
856
  this._namespace = ns;
627
857
  // disableRedis takes unconditional precedence; otherwise, L2 is active when
628
858
  // at least one of host / cluster nodes / sentinel is configured.
629
859
  this._redisDisabled = this.opts.disableRedis
630
- || (!this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel);
860
+ || (!this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel);
861
+
862
+ this.watchdog = new TierLatencyWatchdog({
863
+ enabled: options.diskLatencyWatchdog ?? true,
864
+ minDiskBypassMs: options.diskLatencyBypassMinMs ?? 10,
865
+ bypassRatio: options.diskLatencyBypassRatio ?? 1.5,
866
+ cooldownMs: options.diskLatencyBypassCooldownMs ?? 30_000,
867
+ redisCutoffMs: 15,
868
+ redisRecoveryFloorMs: 10,
869
+ minSamples: 16,
870
+ disableRedis: this._redisDisabled,
871
+ });
631
872
 
632
873
  // L1 in-memory cache
633
874
  this.l1 = new SmartMemoryCache({
@@ -635,6 +876,8 @@ export class CacheService {
635
876
  maxEntries: this.opts.l1MaxEntries,
636
877
  categories: this.opts.categoryLimits,
637
878
  evictionWatermark: this.opts.l1EvictionWatermark,
879
+ admissionPolicy: this.opts.l1AdmissionPolicy,
880
+ codec: this.codec,
638
881
  diskSpill: (key: string, entry: SmartCacheEntry) => {
639
882
  if (this._diskDisabled) return; // Fix 3: skip spill in serverless environments
640
883
  // Defer disk.save() entirely to the next event-loop tick so the synchronous
@@ -653,12 +896,12 @@ export class CacheService {
653
896
  if (!this._diskDisabled) this.loadSnapshot(); // Fix 3: skip in ephemeral environments
654
897
  }
655
898
 
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);
899
+ // Graceful shutdown: persist L1 to disk via centralized ProcessTerminationBus.
900
+ // The library must NEVER call process.exit() — that decision belongs to the host application.
901
+ this._shutdownHandler = () => {
902
+ this._triggerShutdown();
903
+ };
904
+ ProcessTerminationBus.register(this);
662
905
 
663
906
  // ── Fix 1: Worker thread pool for off-main-thread AES-GCM & Compression ──
664
907
  if (this.opts.workerThreads) {
@@ -732,15 +975,30 @@ export class CacheService {
732
975
  if (this.metricsInterval.unref) this.metricsInterval.unref();
733
976
  }
734
977
 
978
+ // Periodic remote snapshot upload (if configured)
979
+ if (this.opts.remoteSnapshot?.intervalMs && this.opts.remoteSnapshot.intervalMs > 0) {
980
+ this.remoteSnapshotInterval = setInterval(() => {
981
+ void this.writeRemoteSnapshot();
982
+ }, this.opts.remoteSnapshot.intervalMs);
983
+ if (this.remoteSnapshotInterval.unref) this.remoteSnapshotInterval.unref();
984
+ }
985
+
735
986
  // Backplane: assign instance ID + channel + streamKey, then subscribe
736
987
  this.instanceId = crypto.randomBytes(8).toString('hex');
737
988
  this.backplaneChannel = `tricache:inv${ns ? ':' + ns : ''}`;
738
989
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || 'default'}}`;
739
990
  this.initBackplane();
740
991
 
741
- // Auto-warm from L2 if warmKeys is configured; ready() waits for completion.
992
+ // Auto-warm from remote snapshot or L2 if configured; ready() waits for completion.
993
+ const startupPromises: Promise<void>[] = [];
994
+ if (this.opts.remoteSnapshot) {
995
+ startupPromises.push(this.loadRemoteSnapshot().then(() => undefined));
996
+ }
742
997
  if (this.opts.warmKeys) {
743
- this._readyPromise = this.warmFromL2(this.opts.warmKeys).then(() => undefined);
998
+ startupPromises.push(this.warmFromL2(this.opts.warmKeys).then(() => undefined));
999
+ }
1000
+ if (startupPromises.length > 0) {
1001
+ this._readyPromise = Promise.all(startupPromises).then(() => undefined);
744
1002
  }
745
1003
 
746
1004
  // Native OpenTelemetry metrics integration
@@ -764,9 +1022,77 @@ export class CacheService {
764
1022
  },
765
1023
  });
766
1024
  }
1025
+
1026
+ // Local IPC telemetry server (Unix domain socket or Windows named pipe)
1027
+ if (this.opts.enableIpc) {
1028
+ this._ipcServer = new IpcTelemetryServer(this, this.opts.ipcSocketPath);
1029
+ this._ipcServer.start().catch((err) => {
1030
+ this.logger.warn('Failed to start IPC telemetry server', { error: (err as Error).message });
1031
+ });
1032
+ }
767
1033
  }
768
1034
 
769
- // ── Singleton factory ─────────────────────────────────────────────────────
1035
+ // ── Singleton factory & Presets ───────────────────────────────────────────
1036
+
1037
+ /**
1038
+ * Pre-configured production presets tailored for specific deployment environments.
1039
+ *
1040
+ * - `'nextjs'`: W-TinyLFU, zero-copy cloneStrategy: 'none' (React 19 RSC stream optimized),
1041
+ * generational tags, and Redis stream backplane.
1042
+ * - `'microservice'`: High-throughput Node.js microservice with W-TinyLFU, Streams backplane,
1043
+ * TTL jitter, and L2 circuit breaking.
1044
+ * - `'serverless'`: Stateless Lambda / Cloud Run isolate with memory-only L1, fast timeouts,
1045
+ * and Pub/Sub backplane.
1046
+ * - `'enterprise-hardened'`: Zero-trust production setup with generational tagging, Streams backplane,
1047
+ * fail-closed rate-limits, strict singleton assertions, and 80% OOM guard.
1048
+ *
1049
+ * @param type The preset identifier ('nextjs' | 'microservice' | 'serverless' | 'enterprise-hardened')
1050
+ * @param overrides Optional configuration overrides merged deeply over preset defaults
1051
+ * @returns Singleton CacheService instance configured according to the preset
1052
+ */
1053
+ static preset(type: CachePresetType, overrides?: Partial<CacheOptions>): CacheService {
1054
+ const PRESETS: Record<CachePresetType, CacheOptions> = {
1055
+ 'nextjs': {
1056
+ l1AdmissionPolicy: 'wtinylfu',
1057
+ cloneStrategy: 'none',
1058
+ tagStrategy: 'generational',
1059
+ tagVersionTtlMs: 2_000,
1060
+ backplaneMode: 'stream',
1061
+ staleIfError: 300,
1062
+ compression: 'none',
1063
+ },
1064
+ 'microservice': {
1065
+ l1AdmissionPolicy: 'wtinylfu',
1066
+ backplaneMode: 'stream',
1067
+ ttlJitterFactor: 0.15,
1068
+ l2CircuitBreakerThreshold: 5,
1069
+ l2CircuitBreakerCooldownMs: 15_000,
1070
+ },
1071
+ 'serverless': {
1072
+ disableDisk: true,
1073
+ l1AdmissionPolicy: 'wtinylfu',
1074
+ backplaneMode: 'pubsub',
1075
+ redisCommandTimeoutMs: 1_000,
1076
+ },
1077
+ 'enterprise-hardened': {
1078
+ l1AdmissionPolicy: 'wtinylfu',
1079
+ tagStrategy: 'generational',
1080
+ backplaneMode: 'stream',
1081
+ strictSingleton: true,
1082
+ failClosed: true,
1083
+ oomProtection: true,
1084
+ oomHeapThreshold: 0.80,
1085
+ },
1086
+ };
1087
+
1088
+ const base = PRESETS[type];
1089
+ if (!base) {
1090
+ throw new Error(`tricache: unknown preset '${type}'. Supported presets: 'nextjs', 'microservice', 'serverless', 'enterprise-hardened'`);
1091
+ }
1092
+
1093
+ const merged = deepMergeOptions(base, overrides);
1094
+ return CacheService.create(merged);
1095
+ }
770
1096
 
771
1097
  /**
772
1098
  * Get (or create) the process-level singleton CacheService instance.
@@ -811,7 +1137,7 @@ export class CacheService {
811
1137
  'redisHost', 'redisPort', 'redisTls', 'disableRedis',
812
1138
  'redisClusterNodes', 'redisSentinel', 'encryptionKey', 'encryptionMode',
813
1139
  'l1MaxBytes', 'l1MaxEntries', 'namespace', 'frozen', 'adaptiveTtl',
814
- 'l2WriteMode', 'instanceName', 'invalidationBackplane',
1140
+ 'l2WriteMode', 'instanceName', 'invalidationBackplane', 'awaitInvalidationBackplane', 'lockFailClosed',
815
1141
  ];
816
1142
 
817
1143
  /** Returns the names of options that differ between `a` and the live `b`. */
@@ -858,7 +1184,11 @@ export class CacheService {
858
1184
  frozen: o.frozen,
859
1185
  adaptiveTtl: o.adaptiveTtl,
860
1186
  invalidationBackplane: o.invalidationBackplane,
1187
+ awaitInvalidationBackplane: o.awaitInvalidationBackplane,
1188
+ lockFailClosed: o.lockFailClosed,
861
1189
  strictSingleton: o.strictSingleton,
1190
+ remoteSnapshot: o.remoteSnapshot,
1191
+ crossRegion: o.crossRegion,
862
1192
  } as CacheOptions;
863
1193
  }
864
1194
 
@@ -885,7 +1215,7 @@ export class CacheService {
885
1215
  }
886
1216
 
887
1217
  /** Derive the globalThis key for a given set of options. */
888
- private static globalKey(options?: CacheOptions): string {
1218
+ private static globalKey(options?: { namespace?: string }): string {
889
1219
  const ns = options?.namespace?.trim() ?? '';
890
1220
  return ns ? `__tricache_${ns}__` : GLOBAL_KEY;
891
1221
  }
@@ -921,16 +1251,29 @@ export class CacheService {
921
1251
  private static readonly _nullSpan: ICacheSpan = {
922
1252
  setAttribute() { return this; },
923
1253
  setStatus() { return this; },
1254
+ recordException() { return this; },
924
1255
  end() {},
925
1256
  };
926
1257
 
927
1258
  /** 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);
1259
+ private _startSpan(name: string, links?: ICacheSpanLink[]): ICacheSpan {
1260
+ if (this.opts.tracer) {
1261
+ const span = this.opts.tracer.startSpan(name, links?.length ? { links } : undefined);
1262
+ if (this.opts.namespace) {
1263
+ span.setAttribute('cache.namespace', this.opts.namespace);
1264
+ }
1265
+ return span;
1266
+ }
930
1267
  return CacheService._nullSpan;
931
1268
  }
932
1269
 
933
1270
  private createDedicatedRedisClient(): AnyRedisClient {
1271
+ if (this.opts.redisSubClient) {
1272
+ return this.opts.redisSubClient;
1273
+ }
1274
+ if (this.opts.redisClient && typeof this.opts.redisClient.duplicate === 'function') {
1275
+ return this.opts.redisClient.duplicate();
1276
+ }
934
1277
  if (this.opts.redisClusterNodes?.length) {
935
1278
  return new RedisCluster(this.opts.redisClusterNodes, {
936
1279
  redisOptions: {
@@ -1161,14 +1504,36 @@ export class CacheService {
1161
1504
  private _applyInvalidationEvent(op: string, key: string, tagVersion?: number): void {
1162
1505
  if (op === 'del') {
1163
1506
  this.l1.delete(key);
1164
- setImmediate(() => { if (!this._diskDisabled) this.disk.delete(key); });
1507
+ this._bumpKeyMutation(key);
1508
+ this.inflight.delete(key);
1509
+ this._pendingDiskDeletes.add(key);
1510
+ setImmediate(() => {
1511
+ try {
1512
+ if (!this._diskDisabled) this.disk.delete(key);
1513
+ } finally {
1514
+ this._pendingDiskDeletes.delete(key);
1515
+ }
1516
+ });
1165
1517
  this._cascadeDependencies(key);
1166
1518
  } else if (op === 'del-glob') {
1167
1519
  this.l1.deletePattern(key);
1520
+ const pfx = key.endsWith('*') ? key.slice(0, -1) : key;
1521
+ for (const liveKey of this.l1.liveKeys()) {
1522
+ if (liveKey.startsWith(pfx)) {
1523
+ this._bumpKeyMutation(liveKey);
1524
+ }
1525
+ }
1526
+ for (const inflightKey of Array.from(this.inflight.keys())) {
1527
+ if (inflightKey.startsWith(pfx)) {
1528
+ this._bumpKeyMutation(inflightKey);
1529
+ this.inflight.delete(inflightKey);
1530
+ }
1531
+ }
1532
+ this._addPatternTombstone(pfx);
1168
1533
  } else if (op === 'tag_incr') {
1169
1534
  const tag = key;
1170
1535
  const ver = typeof tagVersion === 'number' ? tagVersion : ((this.tagVersions.get(tag)?.version ?? 0) + 1);
1171
- this._setLocalTagVersion(tag, ver, Date.now());
1536
+ this._setLocalTagVersion(tag, ver, performance.now());
1172
1537
  }
1173
1538
  this.logger.debug('Backplane: invalidation applied', { op, key: key.slice(0, 60) });
1174
1539
  }
@@ -1201,7 +1566,23 @@ export class CacheService {
1201
1566
  }
1202
1567
  }
1203
1568
 
1204
- private async publishInvalidation(op: 'del' | 'del-glob' | 'tag_incr', key: string, tagVersion?: number): Promise<void> {
1569
+ private async publishInvalidation(
1570
+ op: 'del' | 'del-glob' | 'tag_incr',
1571
+ key: string,
1572
+ tagVersion?: number,
1573
+ isCrossRegionRelay = false,
1574
+ isExplicitInvalidation = false,
1575
+ ): Promise<void> {
1576
+ if (!isCrossRegionRelay && this.opts.crossRegion) {
1577
+ const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
1578
+ if (shouldBroadcast) {
1579
+ if (this.opts.awaitInvalidationBackplane) {
1580
+ await this._broadcastCrossRegion(op, key, tagVersion);
1581
+ } else {
1582
+ void this._broadcastCrossRegion(op, key, tagVersion);
1583
+ }
1584
+ }
1585
+ }
1205
1586
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
1206
1587
  try {
1207
1588
  const client = await this.getRedis();
@@ -1237,10 +1618,111 @@ export class CacheService {
1237
1618
  );
1238
1619
  }
1239
1620
  this.counters.invSent++;
1240
- } catch { /* non-critical — never block the caller */ }
1621
+ } catch (err) {
1622
+ this.logger.warn('Backplane invalidation publish failed', { op, key, error: (err as Error).message });
1623
+ if (this.opts.awaitInvalidationBackplane) {
1624
+ throw err;
1625
+ }
1626
+ }
1627
+ }
1628
+
1629
+ private _markCrossRegionEventSeen(id: string): void {
1630
+ const maxDedup = this.opts.crossRegion?.dedupCacheSize ?? 10_000;
1631
+ if (this._seenCrossRegionEvents.size >= maxDedup) {
1632
+ const oldestKey = this._seenCrossRegionEvents.keys().next().value;
1633
+ if (oldestKey !== undefined) this._seenCrossRegionEvents.delete(oldestKey);
1634
+ }
1635
+ this._seenCrossRegionEvents.set(id, Date.now());
1636
+ }
1637
+
1638
+ private _isCrossRegionEventSeen(id: string): boolean {
1639
+ return this._seenCrossRegionEvents.has(id);
1640
+ }
1641
+
1642
+ private async _broadcastCrossRegion(
1643
+ op: 'del' | 'del-glob' | 'tag_incr',
1644
+ key: string,
1645
+ tagVersion?: number,
1646
+ ): Promise<void> {
1647
+ const cr = this.opts.crossRegion;
1648
+ if (!cr) return;
1649
+ try {
1650
+ const eventId = crypto.randomUUID();
1651
+ this._markCrossRegionEventSeen(eventId);
1652
+ const event: CrossRegionInvalidationEvent = {
1653
+ id: eventId,
1654
+ originRegion: cr.currentRegion,
1655
+ originInstanceId: this.instanceId,
1656
+ op,
1657
+ key,
1658
+ tagVersion,
1659
+ timestamp: Date.now(),
1660
+ namespace: this._namespace || undefined,
1661
+ };
1662
+ this.counters.crossRegionSent++;
1663
+ await cr.relay.broadcast(event);
1664
+ this.logger.debug('Cross-region invalidation broadcast', { op, key, region: cr.currentRegion });
1665
+ } catch (err) {
1666
+ this.counters.crossRegionSent = Math.max(0, this.counters.crossRegionSent - 1);
1667
+ this.counters.crossRegionErrors++;
1668
+ this.logger.warn('Cross-region invalidation broadcast failed', { error: (err as Error).message });
1669
+ }
1670
+ }
1671
+
1672
+ /**
1673
+ * Receives an invalidation event from another region (e.g. via HTTP webhook or broker subscriber).
1674
+ * Validates origin, deduplicates to prevent loops, applies locally to L1/disk,
1675
+ * and fans out to the local Redis backplane so all regional peers invalidate as well.
1676
+ *
1677
+ * Returns true if the event was accepted and applied, or false if ignored/deduplicated.
1678
+ */
1679
+ async receiveCrossRegionInvalidation(event: CrossRegionInvalidationEvent): Promise<boolean> {
1680
+ const cr = this.opts.crossRegion;
1681
+ if (!cr) return false;
1682
+
1683
+ // Reject malformed event
1684
+ if (!event || typeof event !== 'object' || !event.id || !event.originRegion || !event.op || !event.key) {
1685
+ this.counters.crossRegionErrors++;
1686
+ this.logger.warn('Cross-region: rejected invalid event payload', { event });
1687
+ return false;
1688
+ }
1689
+
1690
+ // Ignore events originating from our own region (prevents echo loops)
1691
+ if (event.originRegion === cr.currentRegion) {
1692
+ this.counters.crossRegionDeduplicated++;
1693
+ return false;
1694
+ }
1695
+
1696
+ // Ignore duplicate event IDs (already processed)
1697
+ if (this._isCrossRegionEventSeen(event.id)) {
1698
+ this.counters.crossRegionDeduplicated++;
1699
+ return false;
1700
+ }
1701
+ this._markCrossRegionEventSeen(event.id);
1702
+
1703
+ // If namespaces don't match, ignore
1704
+ if (event.namespace !== undefined && event.namespace !== (this._namespace || undefined)) {
1705
+ return false;
1706
+ }
1707
+
1708
+ this.counters.crossRegionReceived++;
1709
+
1710
+ // 1. Apply to local L1 and disk
1711
+ this._applyInvalidationEvent(event.op, event.key, event.tagVersion);
1712
+
1713
+ // 2. Propagate to local Redis backplane so other instances in THIS region also invalidate,
1714
+ // passing isCrossRegionRelay = true to prevent re-broadcasting cross-region
1715
+ void this.publishInvalidation(event.op, event.key, event.tagVersion, true);
1716
+
1717
+ this.logger.info('Cross-region invalidation applied', {
1718
+ op: event.op,
1719
+ key: event.key,
1720
+ originRegion: event.originRegion,
1721
+ });
1722
+ return true;
1241
1723
  }
1242
1724
 
1243
- private _setLocalTagVersion(tag: string, version: number, now = Date.now()): void {
1725
+ private _setLocalTagVersion(tag: string, version: number, now = performance.now()): void {
1244
1726
  const existing = this.tagVersions.get(tag)?.version ?? 0;
1245
1727
  const finalVersion = Math.max(existing, version);
1246
1728
  if (this.tagVersions.size >= 10_000 && !this.tagVersions.has(tag)) {
@@ -1251,7 +1733,7 @@ export class CacheService {
1251
1733
  }
1252
1734
 
1253
1735
  private async _getTagVersion(tag: string): Promise<number> {
1254
- const now = Date.now();
1736
+ const now = performance.now();
1255
1737
  const local = this.tagVersions.get(tag);
1256
1738
  if (local && (now - local.lastSyncedAt < this.opts.tagVersionTtlMs)) {
1257
1739
  return local.version;
@@ -1341,13 +1823,25 @@ export class CacheService {
1341
1823
  stream.on('error', reject);
1342
1824
  }),
1343
1825
  ));
1344
- } else {
1826
+ } else if (typeof (client as any).scanStream === 'function') {
1345
1827
  await new Promise<void>((resolve, reject) => {
1346
- const stream = client.scanStream({ match: pattern, count: 100 });
1828
+ const stream = (client as any).scanStream({ match: pattern, count: 100 });
1347
1829
  stream.on('data', (chunk: string[]) => keys.push(...chunk));
1348
1830
  stream.on('end', resolve);
1349
1831
  stream.on('error', reject);
1350
1832
  });
1833
+ } else if (typeof (client as any).scanIterator === 'function') {
1834
+ for await (const key of (client as any).scanIterator({ MATCH: pattern, COUNT: 100 })) {
1835
+ keys.push(key);
1836
+ }
1837
+ } else if (typeof (client as any).scan === 'function') {
1838
+ let cursor = '0';
1839
+ do {
1840
+ const res = await (client as any).scan(cursor, 'MATCH', pattern, 'COUNT', 100);
1841
+ cursor = String(res[0]);
1842
+ const chunk = res[1] as string[];
1843
+ if (chunk?.length) keys.push(...chunk);
1844
+ } while (cursor !== '0');
1351
1845
  }
1352
1846
  return keys;
1353
1847
  }
@@ -1370,10 +1864,25 @@ export class CacheService {
1370
1864
  }
1371
1865
 
1372
1866
  private async getRedis(): Promise<AnyRedisClient> {
1867
+ this._assertActive('getRedis');
1373
1868
  if (!this.cb.isAllowed()) throw new Error('tricache: L2 circuit breaker is open');
1374
1869
  if (this.redis) return this.redis;
1375
1870
  if (this.redisConnecting) return this.redisConnecting;
1376
1871
 
1872
+ if (this.opts.redisClient) {
1873
+ const client = this.opts.redisClient;
1874
+ if (typeof client.connect === 'function' && client.isOpen === false) {
1875
+ await client.connect();
1876
+ }
1877
+ this.cb.onSuccess();
1878
+ this.redis = client;
1879
+ this.pipeliner = new AutoPipeliner(client, {
1880
+ enabled: this.opts.autoPipeline,
1881
+ maxBatchSize: this.opts.maxPipelineBatchSize,
1882
+ });
1883
+ return client;
1884
+ }
1885
+
1377
1886
  this.redisConnecting = (async () => {
1378
1887
  try {
1379
1888
  // ── Fix 4: Cluster / Sentinel / single-node connection factory ──────
@@ -1385,6 +1894,7 @@ export class CacheService {
1385
1894
  redisOptions: {
1386
1895
  tls: this.opts.redisTls ? {} : undefined,
1387
1896
  connectTimeout: 10_000,
1897
+ commandTimeout: this.opts.redisCommandTimeoutMs ?? 2_500,
1388
1898
  maxRetriesPerRequest: 3,
1389
1899
  keepAlive: 30_000,
1390
1900
  ...(this.opts.redisProtocol && { protocol: this.opts.redisProtocol }),
@@ -1406,6 +1916,7 @@ export class CacheService {
1406
1916
  name: this.opts.redisSentinel.name,
1407
1917
  tls: this.opts.redisTls ? {} : undefined,
1408
1918
  connectTimeout: 10_000,
1919
+ commandTimeout: this.opts.redisCommandTimeoutMs ?? 2_500,
1409
1920
  lazyConnect: false,
1410
1921
  maxRetriesPerRequest: 3,
1411
1922
  enableAutoPipelining: true,
@@ -1426,6 +1937,7 @@ export class CacheService {
1426
1937
  port: this.opts.redisPort,
1427
1938
  tls: this.opts.redisTls ? {} : undefined,
1428
1939
  connectTimeout: 10_000,
1940
+ commandTimeout: this.opts.redisCommandTimeoutMs ?? 2_500,
1429
1941
  lazyConnect: false,
1430
1942
  maxRetriesPerRequest: 3,
1431
1943
  enableAutoPipelining: true,
@@ -1453,6 +1965,10 @@ export class CacheService {
1453
1965
 
1454
1966
  this.cb.onSuccess();
1455
1967
  this.redis = client;
1968
+ this.pipeliner = new AutoPipeliner(client, {
1969
+ enabled: this.opts.autoPipeline,
1970
+ maxBatchSize: this.opts.maxPipelineBatchSize,
1971
+ });
1456
1972
  this.redisConnecting = null;
1457
1973
  return client;
1458
1974
  } catch (err) {
@@ -1468,13 +1984,19 @@ export class CacheService {
1468
1984
 
1469
1985
  // ── Snapshot (cold-start persistence) ────────────────────────────────────
1470
1986
 
1987
+ /**
1988
+ * Writes the cold-start snapshot to disk.
1989
+ * NOTE: fs.writeFileSync is INTENTIONAL here: this method is invoked during SIGTERM/SIGINT
1990
+ * process termination hooks where asynchronous I/O would risk the Node.js event loop dying or
1991
+ * process.exit() being called before the snapshot is physically written to disk.
1992
+ */
1471
1993
  writeSnapshot(altPath?: string): void {
1472
1994
  try {
1473
1995
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
1474
1996
  if (entries.length === 0) return;
1475
1997
 
1476
1998
  const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
1477
- const packed = pack(payload);
1999
+ const packed = this.codec.encode(payload);
1478
2000
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
1479
2001
  const dest = altPath ?? this.opts.snapshotPath;
1480
2002
  fs.mkdirSync(path.dirname(dest), { recursive: true });
@@ -1488,6 +2010,12 @@ export class CacheService {
1488
2010
  }
1489
2011
  }
1490
2012
 
2013
+ /**
2014
+ * Loads cold-start snapshot from disk into L1 memory.
2015
+ * NOTE: fs.readFileSync is INTENTIONAL here: this method is invoked synchronously inside the
2016
+ * CacheService constructor so that the cache is atomically populated before any subsequent
2017
+ * cache.get() or cache.set() operations run, eliminating cold-start race conditions.
2018
+ */
1491
2019
  loadSnapshot(): void {
1492
2020
  const snapshotPath = this.opts.snapshotPath;
1493
2021
  try {
@@ -1509,7 +2037,7 @@ export class CacheService {
1509
2037
  return;
1510
2038
  }
1511
2039
 
1512
- const snapshot = unpack(buf) as {
2040
+ const snapshot = this.codec.decode(buf) as {
1513
2041
  version?: number; writtenAt?: number;
1514
2042
  entries?: Array<{ key: string; entry: SmartCacheEntry }>;
1515
2043
  };
@@ -1519,8 +2047,18 @@ export class CacheService {
1519
2047
  return;
1520
2048
  }
1521
2049
 
1522
- const ageMs = Date.now() - (snapshot.writtenAt ?? 0);
1523
- if (ageMs > this.opts.snapshotMaxAgeMs || ageMs < 0) {
2050
+ const now = Date.now();
2051
+ const writtenAt = snapshot.writtenAt ?? 0;
2052
+ const tolerance = this.opts.clockSkewToleranceMs ?? 250;
2053
+ if (writtenAt - now > tolerance) {
2054
+ this.logger.warn('Snapshot rejected: timestamp too far in future (exceeds clock skew tolerance)', {
2055
+ writtenAt, now, skewMs: writtenAt - now, tolerance,
2056
+ });
2057
+ return;
2058
+ }
2059
+
2060
+ const ageMs = Math.max(0, now - writtenAt);
2061
+ if (ageMs > this.opts.snapshotMaxAgeMs) {
1524
2062
  this.logger.warn('Snapshot rejected: too old', { ageMinutes: Math.round(ageMs / 60000) });
1525
2063
  return;
1526
2064
  }
@@ -1541,6 +2079,128 @@ export class CacheService {
1541
2079
  }
1542
2080
  }
1543
2081
 
2082
+ // ── Remote Snapshot (cold-start persistence for stateless containers) ───────
2083
+
2084
+ /**
2085
+ * Persists the cold-start snapshot to remote blob storage (S3, GCS, R2, HTTP).
2086
+ * Can be awaited during graceful application shutdown (e.g. Kubernetes preStop or NestJS shutdown).
2087
+ * Returns true if a snapshot was successfully exported and written; false otherwise.
2088
+ */
2089
+ async writeRemoteSnapshot(): Promise<boolean> {
2090
+ if (!this.opts.remoteSnapshot) return false;
2091
+ try {
2092
+ const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
2093
+ if (entries.length === 0) return false;
2094
+
2095
+ const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
2096
+ const packed = this.codec.encode(payload);
2097
+ let final: Buffer;
2098
+ if (this.opts.remoteSnapshot.envelope) {
2099
+ final = await EnvelopeEncryption.encrypt(packed, this.opts.remoteSnapshot.envelope);
2100
+ } else {
2101
+ final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
2102
+ }
2103
+
2104
+ await this.opts.remoteSnapshot.adapter.put(final);
2105
+ this.counters.remoteSnapshotUploads++;
2106
+ this.counters.remoteSnapshotLastUploadedAt = Date.now();
2107
+ this.logger.info('Remote cache snapshot uploaded', {
2108
+ entries: entries.length,
2109
+ sizeKB: Math.round(final.length / 1024),
2110
+ encrypted: Boolean(this.opts.remoteSnapshot.envelope || this.enc.isEnabled),
2111
+ });
2112
+ return true;
2113
+ } catch (err) {
2114
+ this.counters.remoteSnapshotErrors++;
2115
+ this.logger.warn('Remote cache snapshot upload failed', { error: (err as Error).message });
2116
+ return false;
2117
+ }
2118
+ }
2119
+
2120
+ /**
2121
+ * Hydrates L1 memory from remote blob storage (S3, GCS, R2, HTTP).
2122
+ * Called automatically during startup (chained into `cache.ready()`).
2123
+ * Returns the number of entries successfully imported.
2124
+ */
2125
+ async loadRemoteSnapshot(): Promise<number> {
2126
+ if (!this.opts.remoteSnapshot) return 0;
2127
+ const maxAgeMs = this.opts.remoteSnapshot.maxAgeMs ?? this.opts.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE;
2128
+ try {
2129
+ const raw = await this.opts.remoteSnapshot.adapter.get();
2130
+ if (!raw || raw.length === 0) {
2131
+ this.logger.debug('Remote snapshot not found or empty — starting cold');
2132
+ return 0;
2133
+ }
2134
+
2135
+ const rawBuf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
2136
+ let buf: Buffer;
2137
+ try {
2138
+ if (EnvelopeEncryption.isEnvelope(rawBuf)) {
2139
+ if (!this.opts.remoteSnapshot.envelope) {
2140
+ throw new Error('Remote snapshot is envelope-encrypted but no envelope options (privateKey or kmsDecrypt) were configured');
2141
+ }
2142
+ buf = await EnvelopeEncryption.decrypt(rawBuf, this.opts.remoteSnapshot.envelope);
2143
+ } else {
2144
+ buf = this.enc.decryptBuffer(rawBuf);
2145
+ }
2146
+ } catch (e) {
2147
+ this.counters.remoteSnapshotErrors++;
2148
+ this.logger.warn('Remote snapshot rejected: decryption failed', { error: (e as Error).message });
2149
+ return 0;
2150
+ }
2151
+
2152
+ const snapshot = this.codec.decode(buf) as {
2153
+ version?: number;
2154
+ writtenAt?: number;
2155
+ entries?: Array<{ key: string; entry: SmartCacheEntry }>;
2156
+ };
2157
+
2158
+ if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
2159
+ this.counters.remoteSnapshotErrors++;
2160
+ this.logger.warn('Remote snapshot rejected: version mismatch', { got: snapshot?.version });
2161
+ return 0;
2162
+ }
2163
+
2164
+ const now = Date.now();
2165
+ const writtenAt = snapshot.writtenAt ?? 0;
2166
+ const tolerance = this.opts.clockSkewToleranceMs ?? 250;
2167
+ if (writtenAt - now > tolerance) {
2168
+ this.counters.remoteSnapshotErrors++;
2169
+ this.logger.warn('Remote snapshot rejected: timestamp too far in future (exceeds clock skew tolerance)', {
2170
+ writtenAt, now, skewMs: writtenAt - now, tolerance,
2171
+ });
2172
+ return 0;
2173
+ }
2174
+
2175
+ const ageMs = Math.max(0, now - writtenAt);
2176
+ if (maxAgeMs <= 0 || ageMs > maxAgeMs) {
2177
+ this.counters.remoteSnapshotErrors++;
2178
+ this.logger.warn('Remote snapshot rejected: too old', { ageMinutes: Math.round(ageMs / 60000) });
2179
+ return 0;
2180
+ }
2181
+
2182
+ if (!Array.isArray(snapshot.entries)) {
2183
+ this.counters.remoteSnapshotErrors++;
2184
+ this.logger.warn('Remote snapshot rejected: entries is not an array');
2185
+ return 0;
2186
+ }
2187
+
2188
+ const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
2189
+ this.counters.remoteSnapshotDownloads++;
2190
+ this.counters.remoteSnapshotLastDownloadedAt = Date.now();
2191
+ this.logger.info('Remote cache snapshot loaded (L1 hydrated)', {
2192
+ loaded,
2193
+ total: snapshot.entries.length,
2194
+ sizeKB: this.l1.getStats().sizeKB,
2195
+ });
2196
+ return loaded;
2197
+ } catch (err) {
2198
+ this.counters.remoteSnapshotErrors++;
2199
+ this.logger.warn('Remote snapshot load failed — starting cold', { error: (err as Error).message });
2200
+ return 0;
2201
+ }
2202
+ }
2203
+
1544
2204
  // ── Core get (L1 → L1.5 → L2 → fetch) ───────────────────────────────────
1545
2205
 
1546
2206
  /**
@@ -1581,6 +2241,7 @@ export class CacheService {
1581
2241
  tags?: string[];
1582
2242
  } = {},
1583
2243
  ): Promise<T> {
2244
+ this._assertActive('get');
1584
2245
  const span = this._startSpan('tricache.get');
1585
2246
  if (this.opts.tracer) span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
1586
2247
  const k = this.nk(cacheKey); // namespaced key used for all storage
@@ -1603,9 +2264,10 @@ export class CacheService {
1603
2264
  if (l1Hit !== null) {
1604
2265
  let isGenerationalStale = false;
1605
2266
  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) {
2267
+ const tags = Object.keys(l1Hit.tagVersions);
2268
+ const currentVers = await Promise.all(tags.map(tag => this._getTagVersion(tag)));
2269
+ for (let i = 0; i < tags.length; i++) {
2270
+ if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
1609
2271
  isGenerationalStale = true;
1610
2272
  break;
1611
2273
  }
@@ -1620,7 +2282,14 @@ export class CacheService {
1620
2282
  if (swrGraceMs > 0 && !this.revalidating.has(k)) {
1621
2283
  const priority = optPriority ?? inferPriority(cacheKey);
1622
2284
  this.revalidating.add(k);
1623
- void this._revalidate(k, fetchFn, ttlSeconds * 1_000, swrGraceMs, priority);
2285
+ void this._revalidate(
2286
+ k,
2287
+ fetchFn,
2288
+ ttlSeconds * 1_000,
2289
+ swrGraceMs,
2290
+ priority,
2291
+ l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map(t => [t, 0])) : undefined),
2292
+ );
1624
2293
  this.counters.swrRevalidations++;
1625
2294
  this.logger.debug('SWR: serving stale, revalidating', { cacheKey });
1626
2295
  } else {
@@ -1645,7 +2314,14 @@ export class CacheService {
1645
2314
  if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
1646
2315
  const priority = optPriority ?? inferPriority(cacheKey);
1647
2316
  this.revalidating.add(k);
1648
- void this._revalidate(k, fetchFn, entryTtl, optSwr * 1_000, priority);
2317
+ void this._revalidate(
2318
+ k,
2319
+ fetchFn,
2320
+ entryTtl,
2321
+ optSwr * 1_000,
2322
+ priority,
2323
+ l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map(t => [t, 0])) : undefined),
2324
+ );
1649
2325
  this.counters.swrRevalidations++;
1650
2326
  this.logger.debug(
1651
2327
  shouldXFetch ? 'XFetch: proactive background recompute' : 'Refresh-ahead: proactive background recompute',
@@ -1657,7 +2333,10 @@ export class CacheService {
1657
2333
  this.counters.l1Hits++;
1658
2334
  this.opts.onHit?.(cacheKey, 'l1');
1659
2335
  if (this.opts.frozen) deepFreeze(l1Hit.value);
1660
- span.setAttribute('cache.hit', 'l1').end();
2336
+ span.setAttribute('cache.hit', true)
2337
+ .setAttribute('cache.item.tier', 'memory')
2338
+ .setAttribute('cache.hit_tier', 'l1')
2339
+ .end();
1661
2340
  return (this.opts.cloneStrategy === 'structuredClone' && l1Hit.value != null && typeof l1Hit.value === 'object')
1662
2341
  ? structuredClone(l1Hit.value) as T
1663
2342
  : l1Hit.value as T;
@@ -1668,121 +2347,165 @@ export class CacheService {
1668
2347
  const swrGraceMs = optSwr * 1_000;
1669
2348
  const priority = optPriority ?? inferPriority(cacheKey);
1670
2349
 
1671
- // L2: Redis (distributed, production-only by default)
1672
- if (!this._redisDisabled) {
2350
+ // ── Singleflight Shielding on the Probabilistic Path ────────────────────────
2351
+ // Coalesce identical concurrent keys onto an inflight Promise BEFORE evaluating
2352
+ // the watchdog's probabilistic coin-flip. Ensures 10 concurrent requests for a cold key
2353
+ // during an EBS stall coalesce into a single execution rather than splitting across tiers.
2354
+ const existing = this.inflight.get(k);
2355
+ if (existing) {
2356
+ this.counters.stampedes++;
2357
+ this.logger.debug('Stampede prevented — coalescing onto inflight fetch/read', { cacheKey });
2358
+ span.setAttribute('cache.hit', true)
2359
+ .setAttribute('cache.stampede_coalesced', true)
2360
+ .end();
2361
+ return existing as Promise<T>;
2362
+ }
2363
+
2364
+ const mutationEpochAtStart = this._getKeyMutationEpoch(k);
2365
+ const executionPromise: Promise<T> = (async () => {
1673
2366
  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;
2367
+ // ── Tier 1.5: disk tier (evicted L1 entries) — protected by latency watchdog ──
2368
+ if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
2369
+ if (this._isTombstonedByPattern(k)) {
2370
+ try { this.disk.delete(k); } catch { /* ok */ }
2371
+ } else {
2372
+ const isDiskAllowed = this.watchdog.isDiskAllowed();
2373
+ if (isDiskAllowed) {
2374
+ const diskStart = performance.now();
2375
+ const diskHit = this.disk.load(k);
2376
+ const diskElapsed = performance.now() - diskStart;
2377
+ this.watchdog.recordDisk(diskElapsed);
2378
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
2379
+
2380
+ if (diskHit !== null) {
2381
+ let isDiskStale = false;
2382
+ if (this.opts.tagStrategy === 'generational' && diskHit.tagVersions) {
2383
+ const tags = Object.keys(diskHit.tagVersions);
2384
+ const currentVers = await Promise.all(tags.map(tag => this._getTagVersion(tag)));
2385
+ for (let i = 0; i < tags.length; i++) {
2386
+ if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
2387
+ isDiskStale = true;
2388
+ break;
2389
+ }
2390
+ }
2391
+ }
2392
+
2393
+ if (isDiskStale) {
2394
+ this.disk.delete(k);
2395
+ } else {
2396
+ const promoted = this.l1.importEntries(
2397
+ [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
2398
+ this.opts.forbiddenSnapshotPrefixes,
2399
+ );
2400
+ if (promoted > 0) {
2401
+ const l1Check = this.l1.get(k);
2402
+ if (l1Check !== null) {
2403
+ this.counters.diskHits++;
2404
+ this.opts.onHit?.(cacheKey, 'disk');
2405
+ this.logger.debug('L1.5 hit (disk → L1)', { cacheKey });
2406
+ span.setAttribute('cache.hit', true)
2407
+ .setAttribute('cache.item.tier', 'disk')
2408
+ .setAttribute('cache.hit_tier', 'disk');
2409
+ if (this.opts.frozen) deepFreeze(l1Check.value);
2410
+ return (this.opts.cloneStrategy === 'structuredClone' && l1Check.value != null && typeof l1Check.value === 'object')
2411
+ ? structuredClone(l1Check.value) as T
2412
+ : l1Check.value as T;
2413
+ }
2414
+ }
1689
2415
  }
1690
2416
  }
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
2417
  }
1722
2418
  }
1723
- } catch (err) {
1724
- this.cb.onFailure();
1725
- this.logger.debug('Redis unavailable, continuing to fetch', { cacheKey, error: (err as Error).message });
1726
2419
  }
1727
- }
1728
2420
 
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;
2421
+ // ── Tier 2: Redis (distributed, production-only by default) ──
2422
+ if (!this._redisDisabled) {
2423
+ try {
2424
+ const client = await this.getRedis();
2425
+ const redisStart = performance.now();
2426
+ if (this.opts.tagStrategy === 'generational') {
2427
+ const hashData = await client.hgetall(k);
2428
+ const redisElapsed = performance.now() - redisStart;
2429
+ this.watchdog.recordRedis(redisElapsed);
2430
+ this.cb.onSuccess();
2431
+ if (hashData && hashData.d) {
2432
+ let isStale = false;
2433
+ let storedTagVersions: Record<string, number> = {};
2434
+ if (hashData.tv) {
2435
+ try { storedTagVersions = JSON.parse(hashData.tv); } catch { /* ignore */ }
2436
+ }
2437
+ const tags = Object.keys(storedTagVersions);
2438
+ const currentVers = await Promise.all(tags.map(tag => this._getTagVersion(tag)));
2439
+ for (let i = 0; i < tags.length; i++) {
2440
+ if (currentVers[i] > storedTagVersions[tags[i]]) {
2441
+ isStale = true;
2442
+ break;
2443
+ }
2444
+ }
2445
+ if (isStale) {
2446
+ const setAtMs = parseInt(hashData.t, 10) || 0;
2447
+ this._deleteIfStale(k, setAtMs);
2448
+ } else {
2449
+ const parsed = await this._decryptAndDeserialize<T>(hashData.d);
2450
+ this.l1.set(k, parsed, ttlMs, priority, undefined, undefined, storedTagVersions);
2451
+ this.counters.l2Hits++;
2452
+ this.opts.onHit?.(cacheKey, 'l2');
2453
+ this.logger.debug('L2 hit (Redis hash)', { cacheKey });
2454
+ span.setAttribute('cache.hit', true)
2455
+ .setAttribute('cache.item.tier', 'remote')
2456
+ .setAttribute('cache.hit_tier', 'l2');
2457
+ if (this.opts.frozen) deepFreeze(parsed);
2458
+ return (this.opts.cloneStrategy === 'structuredClone' && parsed != null && typeof parsed === 'object')
2459
+ ? structuredClone(parsed)
2460
+ : parsed;
2461
+ }
2462
+ }
2463
+ } else {
2464
+ const raw = (this.opts.autoPipeline && this.pipeliner)
2465
+ ? await this.pipeliner.get(k)
2466
+ : await client.get(k);
2467
+ const redisElapsed = performance.now() - redisStart;
2468
+ this.watchdog.recordRedis(redisElapsed);
2469
+ this.cb.onSuccess();
2470
+ if (raw) {
2471
+ const parsed = await this._decryptAndDeserialize<T>(raw);
2472
+ this.l1.set(k, parsed, ttlMs, priority);
2473
+ this.counters.l2Hits++;
2474
+ this.opts.onHit?.(cacheKey, 'l2');
2475
+ this.logger.debug('L2 hit (Redis)', { cacheKey });
2476
+ span.setAttribute('cache.hit', true)
2477
+ .setAttribute('cache.item.tier', 'remote')
2478
+ .setAttribute('cache.hit_tier', 'l2');
2479
+ if (this.opts.frozen) deepFreeze(parsed);
2480
+ return (this.opts.cloneStrategy === 'structuredClone' && parsed != null && typeof parsed === 'object')
2481
+ ? structuredClone(parsed)
2482
+ : parsed;
2483
+ }
1740
2484
  }
2485
+ } catch (err) {
2486
+ this.cb.onFailure();
2487
+ this.logger.debug('Redis unavailable, continuing to fetch', { cacheKey, error: (err as Error).message });
1741
2488
  }
1742
2489
  }
1743
2490
 
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;
1762
- }
1763
- }
1764
- }
1765
- }
1766
- }
2491
+ // Cache MISS across all tiers: fetchFn
2492
+ span.setAttribute('cache.hit', false).setAttribute('cache.hit_tier', 'miss');
2493
+ this.opts.onMiss?.(cacheKey);
1767
2494
 
1768
- span.setAttribute('cache.hit', 'miss');
1769
- this.opts.onMiss?.(cacheKey);
1770
-
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
- this.counters.fetches++;
1783
- const fetchStart = Date.now();
1784
- const data = await fetchFn();
1785
- const delta = Date.now() - fetchStart;
2495
+ this.counters.fetches++;
2496
+ const fetchStart = Date.now();
2497
+ let data: T;
2498
+ try {
2499
+ data = await fetchFn();
2500
+ } catch (fetchErr) {
2501
+ span.setStatus({
2502
+ code: 2,
2503
+ message: fetchErr instanceof Error ? fetchErr.message : String(fetchErr),
2504
+ });
2505
+ span.recordException?.(fetchErr);
2506
+ throw fetchErr;
2507
+ }
2508
+ const delta = Date.now() - fetchStart;
1786
2509
 
1787
2510
  // Negative caching: null/undefined results get their own (shorter) TTL
1788
2511
  const notFoundTtlMs = (optNotFoundTtl ?? this.opts.notFoundTtl) * 1_000;
@@ -1806,15 +2529,33 @@ export class CacheService {
1806
2529
  let activeTagVersions: Record<string, number> | undefined;
1807
2530
  if (optTags?.length) {
1808
2531
  if (this.opts.tagStrategy === 'generational') {
2532
+ const vers = await Promise.all(optTags.map(tag => this._getTagVersion(tag)));
1809
2533
  activeTagVersions = {};
1810
- for (const tag of optTags) {
1811
- activeTagVersions[tag] = await this._getTagVersion(tag);
2534
+ for (let i = 0; i < optTags.length; i++) {
2535
+ activeTagVersions[optTags[i]] = vers[i];
1812
2536
  }
1813
2537
  } else {
1814
2538
  await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1_000));
1815
2539
  }
1816
2540
  }
1817
2541
 
2542
+ if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
2543
+ this.logger.debug('Aborting in-flight cache commit — key was mutated or deleted during fetch', { cacheKey });
2544
+ span.setAttribute('cache.aborted_mutation_race', true);
2545
+ const current = this.l1.get(k);
2546
+ if (current && !current.isStale && current.value !== undefined) {
2547
+ const freshVal = current.value as T;
2548
+ if (this.opts.frozen) deepFreeze(freshVal);
2549
+ return (this.opts.cloneStrategy === 'structuredClone' && freshVal != null && typeof freshVal === 'object')
2550
+ ? structuredClone(freshVal)
2551
+ : freshVal;
2552
+ }
2553
+ if (this.opts.frozen) deepFreeze(data);
2554
+ return (this.opts.cloneStrategy === 'structuredClone' && data != null && typeof data === 'object')
2555
+ ? structuredClone(data)
2556
+ : data;
2557
+ }
2558
+
1818
2559
  this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
1819
2560
 
1820
2561
  if (!this._redisDisabled) {
@@ -1856,8 +2597,70 @@ export class CacheService {
1856
2597
  }
1857
2598
  })();
1858
2599
 
1859
- this.inflight.set(k, fetchPromise);
1860
- return fetchPromise;
2600
+ this.inflight.set(k, executionPromise);
2601
+ return executionPromise;
2602
+ }
2603
+
2604
+ /**
2605
+ * Graceful shutdown flusher for Kubernetes preStop hooks, NestJS onApplicationShutdown,
2606
+ * or manual microservice teardown.
2607
+ *
2608
+ * Flushes both local disk and remote cloud snapshots (S3/R2/GCS), returning a Promise
2609
+ * that resolves when the upload completes or after `timeoutMs` expires.
2610
+ *
2611
+ * @param timeoutMs Maximum time permitted for snapshot persistence before timing out. Default: 8000ms.
2612
+ */
2613
+ async flushSnapshotOnShutdown(timeoutMs = 8_000): Promise<boolean> {
2614
+ const flusher = async (): Promise<boolean> => {
2615
+ let localOk = true;
2616
+ let remoteOk = true;
2617
+
2618
+ if (!this._diskDisabled) {
2619
+ try {
2620
+ this.writeSnapshot();
2621
+ } catch (err) {
2622
+ localOk = false;
2623
+ this.logger.warn('flushSnapshotOnShutdown: disk snapshot write failed', { error: (err as Error).message });
2624
+ }
2625
+ }
2626
+
2627
+ if (this.opts.remoteSnapshot && this.opts.remoteSnapshot.saveOnShutdown !== false) {
2628
+ try {
2629
+ remoteOk = await this.writeRemoteSnapshot();
2630
+ } catch (err) {
2631
+ remoteOk = false;
2632
+ this.logger.warn('flushSnapshotOnShutdown: remote snapshot upload failed', { error: (err as Error).message });
2633
+ }
2634
+ }
2635
+
2636
+ return localOk && remoteOk;
2637
+ };
2638
+
2639
+ let timer: NodeJS.Timeout | null = null;
2640
+ try {
2641
+ return await Promise.race([
2642
+ flusher(),
2643
+ new Promise<boolean>((resolve) => {
2644
+ timer = setTimeout(() => {
2645
+ this.logger.warn(`flushSnapshotOnShutdown timed out after ${timeoutMs}ms`);
2646
+ resolve(false);
2647
+ }, timeoutMs);
2648
+ if (timer.unref) timer.unref();
2649
+ }),
2650
+ ]);
2651
+ } finally {
2652
+ if (timer) clearTimeout(timer);
2653
+ }
2654
+ }
2655
+
2656
+ /**
2657
+ * Internal graceful shutdown trigger invoked by ProcessTerminationBus.
2658
+ */
2659
+ _triggerShutdown(): void {
2660
+ if (!this._diskDisabled) this.writeSnapshot();
2661
+ if (this.opts.remoteSnapshot && this.opts.remoteSnapshot.saveOnShutdown !== false) {
2662
+ void this.flushSnapshotOnShutdown();
2663
+ }
1861
2664
  }
1862
2665
 
1863
2666
  /**
@@ -1888,23 +2691,47 @@ export class CacheService {
1888
2691
  ttlMs: number,
1889
2692
  swrGraceMs: number,
1890
2693
  priority: CachePriority,
2694
+ knownTagVersions?: Record<string, number>,
1891
2695
  ): Promise<void> {
2696
+ const startEpoch = this._getKeyMutationEpoch(cacheKey);
1892
2697
  try {
1893
2698
  const fetchStart = Date.now();
1894
2699
  const data = await fetchFn();
1895
2700
  const delta = Date.now() - fetchStart;
1896
2701
  const staleAt = Date.now() + ttlMs;
1897
2702
 
2703
+ // Invalidation fence: if the key was deleted or mutated while fetchFn was in-flight, abort commit!
2704
+ if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
2705
+ this.logger.debug('SWR: aborting revalidation commit — key was mutated or deleted during fetch', { cacheKey });
2706
+ return;
2707
+ }
2708
+
1898
2709
  // Keep the latency tracker current during SWR background revalidations too
1899
2710
  if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
1900
2711
 
1901
2712
  let activeTagVersions: Record<string, number> | undefined;
1902
2713
  const l1Existing = this.l1.get(cacheKey);
1903
- if (this.opts.tagStrategy === 'generational' && l1Existing?.tagVersions) {
2714
+ const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
2715
+ if (this.opts.tagStrategy === 'generational' && tagVersionsSource) {
2716
+ const tags = Object.keys(tagVersionsSource);
2717
+ const vers = await Promise.all(tags.map(tag => this._getTagVersion(tag)));
1904
2718
  activeTagVersions = {};
1905
- for (const tag of Object.keys(l1Existing.tagVersions)) {
1906
- activeTagVersions[tag] = await this._getTagVersion(tag);
2719
+ for (let i = 0; i < tags.length; i++) {
2720
+ activeTagVersions[tags[i]] = vers[i];
1907
2721
  }
2722
+ if (knownTagVersions) {
2723
+ for (const t of tags) {
2724
+ if (knownTagVersions[t] !== undefined && activeTagVersions[t] !== knownTagVersions[t]) {
2725
+ this.logger.debug('SWR: aborting revalidation commit — tag version bumped during revalidation', { cacheKey, tag: t });
2726
+ return;
2727
+ }
2728
+ }
2729
+ }
2730
+ }
2731
+
2732
+ if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
2733
+ this.logger.debug('SWR: aborting revalidation commit — key was mutated or deleted during tag resolution', { cacheKey });
2734
+ return;
1908
2735
  }
1909
2736
 
1910
2737
  this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
@@ -1950,70 +2777,93 @@ export class CacheService {
1950
2777
 
1951
2778
  /** Explicitly write a value into L1 (+ L2 in production). */
1952
2779
  async set<T>(cacheKey: string, data: T, ttlSeconds = 300, priority?: CachePriority, opts?: { tags?: string[]; dependsOn?: string[] }): Promise<void> {
2780
+ this._assertActive('set');
1953
2781
  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++;
2782
+ if (this.opts.tracer) {
2783
+ span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
2784
+ span.setAttribute('cache.ttl', ttlSeconds);
2785
+ }
2786
+ try {
2787
+ // ttl 0 = indefinite (documented contract, used by the NestJS store): map to
2788
+ // a far-future expiry instead of computing expiresAt = now + 0ms, which
2789
+ // created an instantly-expired entry that could never be read.
2790
+ const effectiveTtlSeconds = ttlSeconds > 0 ? ttlSeconds : (ttlSeconds === 0 ? INDEFINITE_TTL_SECONDS : ttlSeconds);
2791
+ const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1_000);
2792
+ const p = priority ?? inferPriority(cacheKey);
2793
+ const k = this.nk(cacheKey);
2794
+ this._bumpKeyMutation(k);
2795
+ this.inflight.delete(k);
2796
+ this._pendingDiskDeletes.delete(k);
2797
+ this.counters.sets++;
1963
2798
 
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);
2799
+ let activeTagVersions: Record<string, number> | undefined;
2800
+ if (opts?.tags?.length) {
2801
+ if (this.opts.tagStrategy === 'generational') {
2802
+ const vers = await Promise.all(opts.tags.map(tag => this._getTagVersion(tag)));
2803
+ activeTagVersions = {};
2804
+ for (let i = 0; i < opts.tags.length; i++) {
2805
+ activeTagVersions[opts.tags[i]] = vers[i];
2806
+ }
2807
+ } else {
2808
+ await this._registerTags(k, opts.tags, ttlSeconds);
1970
2809
  }
1971
- } else {
1972
- await this._registerTags(k, opts.tags, ttlSeconds);
1973
2810
  }
1974
- }
1975
2811
 
1976
- this.l1.set(k, data, ttlMs, p, undefined, undefined, activeTagVersions);
2812
+ this.l1.set(k, data, ttlMs, p, undefined, undefined, activeTagVersions);
1977
2813
 
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);
2814
+ // Register dependency patterns: when any key matching a pattern is deleted,
2815
+ // this key (k) is automatically cascaded.
2816
+ if (opts?.dependsOn?.length) {
2817
+ for (const pattern of opts.dependsOn) {
2818
+ const nsPattern = this.nk(pattern);
2819
+ let deps = this.dependencyIndex.get(nsPattern);
2820
+ if (!deps) { deps = new Set(); this.dependencyIndex.set(nsPattern, deps); }
2821
+ deps.add(k);
2822
+ }
1986
2823
  }
1987
- }
1988
2824
 
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);
2825
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
2826
+ try {
2827
+ const client = await this.getRedis();
2828
+ const s = JSON.stringify(data);
2829
+ const stored = await this._serializeAndEncrypt(s);
2830
+ const ttlSec = Math.ceil(ttlMs / 1_000);
2831
+ if (this.opts.tagStrategy === 'generational' && activeTagVersions) {
2832
+ const now = Date.now();
2833
+ const tx = client.multi();
2834
+ tx.hset(k, {
2835
+ d: stored,
2836
+ t: String(now),
2837
+ tv: JSON.stringify(activeTagVersions),
2838
+ });
2839
+ tx.expire(k, ttlSec);
2840
+ await tx.exec();
2841
+ } else {
2842
+ if (this.opts.autoPipeline && this.pipeliner) {
2843
+ await this.pipeliner.setex(k, ttlSec, stored);
2844
+ } else {
2845
+ await client.setex(k, ttlSec, stored);
2846
+ }
2847
+ }
2848
+ this.cb.onSuccess();
2849
+ } catch (err) {
2850
+ this.cb.onFailure();
2851
+ this.logger.debug('set: Redis unavailable', { cacheKey, error: (err as Error).message });
2007
2852
  }
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
2853
  }
2013
- }
2014
2854
 
2015
- void this.publishInvalidation('del', k);
2016
- span.end();
2855
+ if (this.opts.awaitInvalidationBackplane) {
2856
+ await this.publishInvalidation('del', k);
2857
+ } else {
2858
+ void this.publishInvalidation('del', k);
2859
+ }
2860
+ } catch (err) {
2861
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
2862
+ span.recordException?.(err);
2863
+ throw err;
2864
+ } finally {
2865
+ span.end();
2866
+ }
2017
2867
  }
2018
2868
 
2019
2869
  /**
@@ -2050,47 +2900,79 @@ export class CacheService {
2050
2900
  * await cache.delete('user:abc:*'); // all keys for user abc
2051
2901
  */
2052
2902
  async delete(cacheKey: string): Promise<void> {
2903
+ this._assertActive('delete');
2053
2904
  const span = this._startSpan('tricache.delete');
2054
2905
  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++;
2058
-
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
- }
2906
+ try {
2907
+ const isPattern = cacheKey.includes('*');
2908
+ const k = this.nk(cacheKey);
2909
+ this.counters.deletes++;
2910
+
2911
+ if (isPattern) {
2912
+ const pfx = k.endsWith('*') ? k.slice(0, -1) : k;
2913
+ for (const liveKey of this.l1.liveKeys()) {
2914
+ if (liveKey.startsWith(pfx)) {
2915
+ this._bumpKeyMutation(liveKey);
2916
+ }
2917
+ }
2918
+ for (const inflightKey of Array.from(this.inflight.keys())) {
2919
+ if (inflightKey.startsWith(pfx)) {
2920
+ this._bumpKeyMutation(inflightKey);
2921
+ this.inflight.delete(inflightKey);
2922
+ }
2923
+ }
2924
+ this._addPatternTombstone(pfx);
2925
+ this.l1.deletePattern(k);
2926
+ } else {
2927
+ this._bumpKeyMutation(k);
2928
+ this.inflight.delete(k);
2929
+ this.l1.delete(k);
2930
+ this._pendingDiskDeletes.add(k);
2931
+ setImmediate(() => {
2932
+ try {
2933
+ if (!this._diskDisabled) this.disk.delete(k);
2934
+ } finally {
2935
+ this._pendingDiskDeletes.delete(k);
2936
+ }
2937
+ });
2938
+ // Cascade: invalidate any key that declared it depends on this exact key's pattern
2939
+ this._cascadeDependencies(k);
2940
+ // Clean up: remove k from all dependency registrations (it is gone)
2941
+ for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
2942
+ }
2075
2943
 
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);
2944
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
2945
+ try {
2946
+ const client = await this.getRedis();
2947
+ if (isPattern) {
2948
+ const keys = await this._scanKeys(client, k);
2949
+ if (keys.length > 0) await client.del(...keys);
2950
+ } else {
2951
+ if (this.opts.autoPipeline && this.pipeliner) {
2952
+ await this.pipeliner.del(k);
2953
+ } else {
2954
+ await client.del(k);
2955
+ }
2956
+ }
2957
+ this.cb.onSuccess();
2958
+ } catch (err) {
2959
+ this.cb.onFailure();
2960
+ this.logger.debug('delete: Redis unavailable', { cacheKey, error: (err as Error).message });
2084
2961
  }
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
2962
  }
2090
- }
2091
2963
 
2092
- void this.publishInvalidation(isPattern ? 'del-glob' : 'del', k);
2093
- span.end();
2964
+ if (this.opts.awaitInvalidationBackplane) {
2965
+ await this.publishInvalidation(isPattern ? 'del-glob' : 'del', k, undefined, false, true);
2966
+ } else {
2967
+ void this.publishInvalidation(isPattern ? 'del-glob' : 'del', k, undefined, false, true);
2968
+ }
2969
+ } catch (err) {
2970
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
2971
+ span.recordException?.(err);
2972
+ throw err;
2973
+ } finally {
2974
+ span.end();
2975
+ }
2094
2976
  }
2095
2977
 
2096
2978
  // ── Counter (distributed rate limiting) ──────────────────────────────────
@@ -2112,6 +2994,7 @@ export class CacheService {
2112
2994
  * fleet-wide.
2113
2995
  */
2114
2996
  async increment(cacheKey: string, ttlSeconds?: number): Promise<number> {
2997
+ this._assertActive('increment');
2115
2998
  const k = this.nk(cacheKey);
2116
2999
 
2117
3000
  if (this._redisDisabled) {
@@ -2157,36 +3040,70 @@ export class CacheService {
2157
3040
  * await cache.clear('user:abc'); // flush all keys for one user
2158
3041
  */
2159
3042
  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
- }
3043
+ this._assertActive('clear');
3044
+ const span = this._startSpan('tricache.clear');
3045
+ if (this.opts.tracer) span.setAttribute('cache.prefix', prefix || '*');
3046
+ try {
3047
+ this.counters.deletes++;
3048
+ const k = prefix
3049
+ ? this.nk(prefix.includes('*') ? prefix : `${prefix}*`)
3050
+ : undefined;
3051
+
3052
+ if (k) {
3053
+ const pfx = k.endsWith('*') ? k.slice(0, -1) : k;
3054
+ for (const liveKey of this.l1.liveKeys()) {
3055
+ if (liveKey.startsWith(pfx)) {
3056
+ this._bumpKeyMutation(liveKey);
3057
+ }
3058
+ }
3059
+ for (const inflightKey of Array.from(this.inflight.keys())) {
3060
+ if (inflightKey.startsWith(pfx)) {
3061
+ this._bumpKeyMutation(inflightKey);
3062
+ this.inflight.delete(inflightKey);
3063
+ }
3064
+ }
3065
+ this._addPatternTombstone(pfx);
3066
+ this.l1.deletePattern(k);
3067
+ } else {
3068
+ this._globalEpoch++;
3069
+ this.inflight.clear();
3070
+ this._patternTombstones.length = 0;
3071
+ this.l1.clear();
3072
+ if (!this._diskDisabled) this.disk.clear();
3073
+ this._l1Counters.clear();
3074
+ this.tagIndex.clear();
3075
+ this.tagVersions.clear();
3076
+ this._pendingDiskDeletes.clear();
3077
+ this._keyMutationEpochs.clear();
3078
+ }
2176
3079
 
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 });
3080
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
3081
+ try {
3082
+ const client = await this.getRedis();
3083
+ const pattern = k ?? (this._namespace ? `${this._namespace}:*` : '*');
3084
+ const keys = await this._scanKeys(client, pattern);
3085
+ if (keys.length > 0) await client.del(...keys);
3086
+ } catch (err) {
3087
+ this.logger.debug('clear: Redis unavailable', { error: (err as Error).message });
3088
+ }
2185
3089
  }
2186
- }
2187
3090
 
2188
- void this.publishInvalidation('del-glob',
2189
- k ?? (this._namespace ? `${this._namespace}:*` : '*'));
3091
+ if (this.opts.awaitInvalidationBackplane) {
3092
+ await this.publishInvalidation('del-glob',
3093
+ k ?? (this._namespace ? `${this._namespace}:*` : '*'),
3094
+ undefined, false, true);
3095
+ } else {
3096
+ void this.publishInvalidation('del-glob',
3097
+ k ?? (this._namespace ? `${this._namespace}:*` : '*'),
3098
+ undefined, false, true);
3099
+ }
3100
+ } catch (err) {
3101
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
3102
+ span.recordException?.(err);
3103
+ throw err;
3104
+ } finally {
3105
+ span.end();
3106
+ }
2190
3107
  }
2191
3108
 
2192
3109
  /**
@@ -2195,6 +3112,7 @@ export class CacheService {
2195
3112
  * Returns the number of entries evicted.
2196
3113
  */
2197
3114
  rebalance(): number {
3115
+ this._assertActive('rebalance');
2198
3116
  return this.l1.rebalance();
2199
3117
  }
2200
3118
 
@@ -2204,6 +3122,7 @@ export class CacheService {
2204
3122
  * Only reflects L1 state — does not query Redis or disk.
2205
3123
  */
2206
3124
  ttl(cacheKey: string): number | null {
3125
+ this._assertActive('ttl');
2207
3126
  return this.l1.ttl(this.nk(cacheKey));
2208
3127
  }
2209
3128
 
@@ -2212,6 +3131,7 @@ export class CacheService {
2212
3131
  * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
2213
3132
  */
2214
3133
  has(cacheKey: string): boolean {
3134
+ this._assertActive('has');
2215
3135
  return this.l1.has(this.nk(cacheKey));
2216
3136
  }
2217
3137
 
@@ -2224,6 +3144,7 @@ export class CacheService {
2224
3144
  * for (const key of cache.keys()) console.log(key);
2225
3145
  */
2226
3146
  *keys(): Generator<string> {
3147
+ this._assertActive('keys');
2227
3148
  const prefix = this._namespace ? this._namespace + ':' : '';
2228
3149
  for (const key of this.l1.liveKeys()) {
2229
3150
  if (prefix && !key.startsWith(prefix)) continue;
@@ -2239,6 +3160,7 @@ export class CacheService {
2239
3160
  * for (const val of cache.values<User>()) console.log(val.id);
2240
3161
  */
2241
3162
  *values<T = unknown>(): Generator<T> {
3163
+ this._assertActive('values');
2242
3164
  const prefix = this._namespace ? this._namespace + ':' : '';
2243
3165
  if (!prefix) {
2244
3166
  yield* this.l1.liveValues() as Generator<T>;
@@ -2258,6 +3180,7 @@ export class CacheService {
2258
3180
  * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
2259
3181
  */
2260
3182
  *entries<T = unknown>(): Generator<[string, T]> {
3183
+ this._assertActive('entries');
2261
3184
  const prefix = this._namespace ? this._namespace + ':' : '';
2262
3185
  for (const [key, entry] of this.l1.liveEntries()) {
2263
3186
  if (prefix && !key.startsWith(prefix)) continue;
@@ -2286,6 +3209,7 @@ export class CacheService {
2286
3209
  * `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
2287
3210
  */
2288
3211
  scan<T = unknown>(fn: (rawKey: string, value: T, offset: number) => void): void {
3212
+ this._assertActive('scan');
2289
3213
  const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
2290
3214
  this.l1.scan((key, entry, pfx) => {
2291
3215
  const value = (entry.value !== undefined ? entry.value : entry.data) as T;
@@ -2300,6 +3224,7 @@ export class CacheService {
2300
3224
  * @param newTtlSeconds - The new TTL from now, in seconds.
2301
3225
  */
2302
3226
  async touch(cacheKey: string, newTtlSeconds: number): Promise<boolean> {
3227
+ this._assertActive('touch');
2303
3228
  const k = this.nk(cacheKey);
2304
3229
  const hit = this.l1.touch(k, newTtlSeconds * 1_000);
2305
3230
  if (hit && !this._redisDisabled) {
@@ -2320,13 +3245,14 @@ export class CacheService {
2320
3245
  * if (fresh !== null) return fresh; // serve from L1, no network hop
2321
3246
  */
2322
3247
  getIfFresh<T = unknown>(cacheKey: string): T | null {
3248
+ this._assertActive('getIfFresh');
2323
3249
  const k = this.nk(cacheKey);
2324
3250
  const entry = this.l1.getEntry(k);
2325
3251
  if (!entry) return null;
2326
3252
  const now = Date.now();
2327
3253
  if (entry.expiresAt <= now) return null; // expired
2328
3254
  if (entry.staleAt !== undefined && entry.staleAt < now) return null; // in SWR grace
2329
- return (entry.value !== undefined ? entry.value : unpack(entry.data)) as T;
3255
+ return (entry.value !== undefined ? entry.value : this.codec.decode(entry.data)) as T;
2330
3256
  }
2331
3257
 
2332
3258
  /**
@@ -2338,6 +3264,7 @@ export class CacheService {
2338
3264
  * const val = await cache.peek<User>('user:123');
2339
3265
  */
2340
3266
  async peek<T = unknown>(cacheKey: string): Promise<T | null> {
3267
+ this._assertActive('peek');
2341
3268
  const k = this.nk(cacheKey);
2342
3269
 
2343
3270
  // 1. L1 RAM
@@ -2353,8 +3280,16 @@ export class CacheService {
2353
3280
  }
2354
3281
 
2355
3282
  // 2. L1.5 Disk
2356
- if (!this._diskDisabled) {
3283
+ if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
3284
+ if (this._isTombstonedByPattern(k)) {
3285
+ try { this.disk.delete(k); } catch { /* ok */ }
3286
+ } else if (this.watchdog.isDiskAllowed()) {
3287
+ const diskStart = performance.now();
2357
3288
  const diskHit = this.disk.load(k);
3289
+ const diskElapsed = performance.now() - diskStart;
3290
+ this.watchdog.recordDisk(diskElapsed);
3291
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
3292
+
2358
3293
  if (diskHit !== null) {
2359
3294
  const promoted = this.l1.importEntries(
2360
3295
  [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
@@ -2374,12 +3309,16 @@ export class CacheService {
2374
3309
  }
2375
3310
  }
2376
3311
  }
3312
+ }
2377
3313
 
2378
3314
  // 3. L2 Redis
2379
3315
  if (!this._redisDisabled && !this.cb.isOpen) {
2380
3316
  try {
2381
3317
  const client = await this.getRedis();
3318
+ const redisStart = performance.now();
2382
3319
  const raw = await client.get(k);
3320
+ const redisElapsed = performance.now() - redisStart;
3321
+ this.watchdog.recordRedis(redisElapsed);
2383
3322
  if (raw !== null) {
2384
3323
  const parsed = await this._decryptAndDeserialize<T>(raw);
2385
3324
  this.l1.set(k, parsed, 60_000, inferPriority(cacheKey));
@@ -2415,106 +3354,146 @@ export class CacheService {
2415
3354
  ttl: number | ((key: string) => number) = 300,
2416
3355
  priority?: CachePriority,
2417
3356
  ): 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
- }
3357
+ this._assertActive('mget');
3358
+ const span = this._startSpan('tricache.mget');
3359
+ if (this.opts.tracer) {
3360
+ span.setAttribute('cache.batch.size', keys.length);
2433
3361
  }
3362
+ try {
3363
+ const result: (T | undefined)[] = Array.from({ length: keys.length });
3364
+ const missIndexes: number[] = [];
3365
+ const missKeys: string[] = [];
3366
+
3367
+ // ── Tier 1: L1 (in-memory) ──
3368
+ for (let i = 0; i < keys.length; i++) {
3369
+ const k = this.nk(keys[i]);
3370
+ const entry = this.l1.getEntry(k);
3371
+ if (entry && entry.expiresAt > Date.now()) {
3372
+ result[i] = (entry.value !== undefined ? entry.value : this.codec.decode(entry.data)) as T;
3373
+ this.counters.l1Hits++;
3374
+ } else {
3375
+ missIndexes.push(i);
3376
+ missKeys.push(keys[i]);
3377
+ }
3378
+ }
2434
3379
 
2435
- if (missKeys.length === 0) return result;
3380
+ if (missKeys.length === 0) {
3381
+ if (this.opts.tracer) {
3382
+ span.setAttribute('cache.hits', keys.length);
3383
+ span.setAttribute('cache.misses', 0);
3384
+ span.setAttribute('cache.l1_hits', keys.length);
3385
+ span.setAttribute('cache.l2_hits', 0);
3386
+ }
3387
+ return result;
3388
+ }
2436
3389
 
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] = '';
3390
+ let l2HitCount = 0;
3391
+ // ── Tier 2: L2 (Redis) — fetch all remaining misses in one pipeline ──
3392
+ if (!this._redisDisabled) {
3393
+ try {
3394
+ const client = await this.getRedis();
3395
+ const nsKeys = missKeys.map(k => this.nk(k));
3396
+ const pipeline = client.multi();
3397
+ for (const nk of nsKeys) pipeline.get(nk);
3398
+ const redisStart = performance.now();
3399
+ const raws = await pipeline.exec() as Array<[Error | null, string | null] | null>;
3400
+ const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
3401
+ this.watchdog.recordRedis(redisElapsed);
3402
+ this.cb.onSuccess();
3403
+ for (let j = 0; j < missKeys.length; j++) {
3404
+ const raw = raws[j] ? (raws[j] as [Error | null, string | null])[1] : null;
3405
+ const idx = missIndexes[j];
3406
+ if (raw) {
3407
+ const parsed = await this._decryptAndDeserialize<T>(raw);
3408
+ const k = nsKeys[j];
3409
+ const p = priority ?? inferPriority(missKeys[j]);
3410
+ this.l1.set(k, parsed, this._jitterTtl((typeof ttl === 'function' ? ttl(missKeys[j]) : ttl) * 1_000), p);
3411
+ this.counters.l2Hits++;
3412
+ l2HitCount++;
3413
+ result[idx] = parsed;
3414
+ missIndexes[j] = -1;
3415
+ missKeys[j] = '';
3416
+ }
2463
3417
  }
3418
+ // Compact the still-missing arrays.
3419
+ const remainingIdx = missIndexes.filter(i => i >= 0);
3420
+ const remainingKeys = missKeys.filter(k => k !== '');
3421
+ missIndexes.length = 0; missKeys.length = 0;
3422
+ missIndexes.push(...remainingIdx);
3423
+ missKeys.push(...remainingKeys);
3424
+ } catch (err) {
3425
+ this.cb.onFailure();
3426
+ this.logger.debug('mget: Redis unavailable, continuing to disk/fetch', { error: (err as Error).message });
2464
3427
  }
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
3428
  }
2476
- }
2477
3429
 
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);
3430
+ // ── Tier 1.5: disk spill (evicted L1 entries) ──
3431
+ if (!this._diskDisabled && missKeys.length > 0) {
3432
+ for (let j = missKeys.length - 1; j >= 0; j--) {
3433
+ const k = this.nk(missKeys[j]);
3434
+ if (this._pendingDiskDeletes.has(k)) continue;
3435
+ if (this._isTombstonedByPattern(k)) {
3436
+ try { this.disk.delete(k); } catch { /* ok */ }
3437
+ continue;
3438
+ }
3439
+ if (!this.watchdog.isDiskAllowed()) continue;
3440
+ const diskStart = performance.now();
3441
+ const diskHit = this.disk.load(k);
3442
+ const diskElapsed = performance.now() - diskStart;
3443
+ this.watchdog.recordDisk(diskElapsed);
3444
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
3445
+ if (diskHit !== null) {
3446
+ const promoted = this.l1.importEntries(
3447
+ [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
3448
+ this.opts.forbiddenSnapshotPrefixes,
3449
+ );
3450
+ if (promoted > 0) {
3451
+ const l1Check = this.l1.get(k);
3452
+ if (l1Check !== null) {
3453
+ this.counters.diskHits++;
3454
+ result[missIndexes[j]] = l1Check.value as T;
3455
+ missIndexes.splice(j, 1);
3456
+ missKeys.splice(j, 1);
3457
+ }
2496
3458
  }
2497
3459
  }
2498
3460
  }
2499
3461
  }
2500
- if (missKeys.length === 0) return result;
2501
- }
2502
3462
 
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);
3463
+ // ── Tier 3: fetchFn for whatever still missed ──
3464
+ if (missKeys.length > 0) {
3465
+ this.counters.fetches++;
3466
+ const fetched = await fetchFn(missKeys);
3467
+ const setPromises: Promise<void>[] = [];
3468
+ for (let j = 0; j < missKeys.length; j++) {
3469
+ const v = fetched[missKeys[j]];
3470
+ result[missIndexes[j]] = v;
3471
+ if (v !== undefined) {
3472
+ const resolvedTtl = typeof ttl === 'function' ? ttl(missKeys[j]) : ttl;
3473
+ setPromises.push(this.set(missKeys[j], v, resolvedTtl, priority));
3474
+ }
3475
+ }
3476
+ if (setPromises.length > 0) {
3477
+ await Promise.all(setPromises);
2513
3478
  }
2514
3479
  }
2515
- }
2516
3480
 
2517
- return result;
3481
+ if (this.opts.tracer) {
3482
+ const finalMisses = missKeys.length;
3483
+ const totalHits = keys.length - finalMisses;
3484
+ span.setAttribute('cache.hits', totalHits);
3485
+ span.setAttribute('cache.misses', finalMisses);
3486
+ span.setAttribute('cache.l2_hits', l2HitCount);
3487
+ }
3488
+
3489
+ return result;
3490
+ } catch (err) {
3491
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
3492
+ span.recordException?.(err);
3493
+ throw err;
3494
+ } finally {
3495
+ span.end();
3496
+ }
2518
3497
  }
2519
3498
 
2520
3499
  /**
@@ -2545,12 +3524,25 @@ export class CacheService {
2545
3524
  async mset<T = unknown>(
2546
3525
  entries: Record<string, { value: T; ttl?: number; priority?: CachePriority; tags?: string[]; dependsOn?: string[] }>,
2547
3526
  ): Promise<void> {
3527
+ this._assertActive('mset');
3528
+ const span = this._startSpan('tricache.mset');
2548
3529
  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
- }));
3530
+ if (this.opts.tracer) {
3531
+ span.setAttribute('cache.batch.size', keys.length);
3532
+ }
3533
+ try {
3534
+ await Promise.all(keys.map(key => {
3535
+ const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
3536
+ const hasOpts = tags?.length || dependsOn?.length;
3537
+ return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : undefined);
3538
+ }));
3539
+ } catch (err) {
3540
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
3541
+ span.recordException?.(err);
3542
+ throw err;
3543
+ } finally {
3544
+ span.end();
3545
+ }
2554
3546
  }
2555
3547
 
2556
3548
  /**
@@ -2561,7 +3553,20 @@ export class CacheService {
2561
3553
  * await cache.mdel(['user:1', 'user:2', 'user:3']);
2562
3554
  */
2563
3555
  async mdel(keys: string[]): Promise<void> {
2564
- await Promise.all(keys.map(k => this.delete(k)));
3556
+ this._assertActive('mdel');
3557
+ const span = this._startSpan('tricache.mdel');
3558
+ if (this.opts.tracer) {
3559
+ span.setAttribute('cache.batch.size', keys.length);
3560
+ }
3561
+ try {
3562
+ await Promise.all(keys.map(k => this.delete(k)));
3563
+ } catch (err) {
3564
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
3565
+ span.recordException?.(err);
3566
+ throw err;
3567
+ } finally {
3568
+ span.end();
3569
+ }
2565
3570
  }
2566
3571
 
2567
3572
  /**
@@ -2577,6 +3582,7 @@ export class CacheService {
2577
3582
  * console.log(`Warmed ${loaded} keys from Redis`);
2578
3583
  */
2579
3584
  async warmFromL2(pattern: string, opts?: { priority?: CachePriority }): Promise<number> {
3585
+ this._assertActive('warmFromL2');
2580
3586
  if (this._redisDisabled) return 0;
2581
3587
  try {
2582
3588
  const client = await this.getRedis();
@@ -2597,7 +3603,6 @@ export class CacheService {
2597
3603
  this.cb.onSuccess();
2598
3604
 
2599
3605
  let loaded = 0;
2600
- const now = Date.now();
2601
3606
  for (let i = 0; i < matchedKeys.length; i++) {
2602
3607
  const [err, raw] = results[i];
2603
3608
  if (err || raw == null) continue;
@@ -2610,7 +3615,6 @@ export class CacheService {
2610
3615
  loaded++;
2611
3616
  } catch { /* skip malformed entries */ }
2612
3617
  }
2613
- void now; // suppress unused warning
2614
3618
 
2615
3619
  this.logger.info('warmFromL2 complete', {
2616
3620
  pattern, matched: matchedKeys.length, loaded,
@@ -2632,49 +3636,75 @@ export class CacheService {
2632
3636
  * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
2633
3637
  */
2634
3638
  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 });
3639
+ this._assertActive('invalidateTag');
3640
+ const span = this._startSpan('tricache.invalidate_tag');
3641
+ if (this.opts.tracer) {
3642
+ span.setAttribute('cache.tag', tag);
3643
+ span.setAttribute('cache.tag_strategy', this.opts.tagStrategy);
3644
+ }
3645
+ try {
3646
+ if (this.opts.tagStrategy === 'generational') {
3647
+ let newVer = 1;
3648
+ if (!this._redisDisabled) {
3649
+ try {
3650
+ const client = await this.getRedis();
3651
+ newVer = await client.incr(this.nk(`tag_ver:${tag}`));
3652
+ } catch (err) {
3653
+ this.logger.debug('invalidateTag: Redis unavailable', { tag, error: (err as Error).message });
3654
+ const current = this.tagVersions.get(tag)?.version ?? 0;
3655
+ newVer = current + 1;
3656
+ }
3657
+ } else {
2643
3658
  const current = this.tagVersions.get(tag)?.version ?? 0;
2644
3659
  newVer = current + 1;
2645
3660
  }
2646
- } else {
2647
- const current = this.tagVersions.get(tag)?.version ?? 0;
2648
- newVer = current + 1;
3661
+ this._setLocalTagVersion(tag, newVer, performance.now());
3662
+ if (this.opts.awaitInvalidationBackplane) {
3663
+ await this.publishInvalidation('tag_incr', tag, newVer, false, true);
3664
+ } else {
3665
+ void this.publishInvalidation('tag_incr', tag, newVer, false, true);
3666
+ }
3667
+ return;
2649
3668
  }
2650
- this._setLocalTagVersion(tag, newVer, Date.now());
2651
- void this.publishInvalidation('tag_incr', tag, newVer);
2652
- return;
2653
- }
2654
3669
 
2655
- const tagKey = this.nk(`_tag_:${tag}`);
2656
- const members = this.tagIndex.get(tagKey) ?? new Set<string>();
3670
+ const tagKey = this.nk(`_tag_:${tag}`);
3671
+ const members = this.tagIndex.get(tagKey) ?? new Set<string>();
2657
3672
 
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);
3673
+ // Remove from L1 + disk
3674
+ for (const k of members) {
3675
+ this.l1.delete(k);
3676
+ this._bumpKeyMutation(k);
3677
+ this._pendingDiskDeletes.add(k);
3678
+ setImmediate(() => {
3679
+ try {
3680
+ if (!this._diskDisabled) this.disk.delete(k);
3681
+ } finally {
3682
+ this._pendingDiskDeletes.delete(k);
3683
+ }
3684
+ });
3685
+ }
3686
+ this.tagIndex.delete(tagKey);
2664
3687
 
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);
3688
+ if (!this._redisDisabled) {
3689
+ try {
3690
+ const client = await this.getRedis();
3691
+ const redisMembers: string[] = await client.smembers(tagKey);
3692
+ const toDelete = [...new Set([...members, ...redisMembers])];
3693
+ if (toDelete.length > 0) {
3694
+ await client.del(...toDelete, tagKey);
3695
+ } else {
3696
+ await client.del(tagKey);
3697
+ }
3698
+ } catch (err) {
3699
+ this.logger.debug('invalidateTag: Redis unavailable', { tag, error: (err as Error).message });
2674
3700
  }
2675
- } catch (err) {
2676
- this.logger.debug('invalidateTag: Redis unavailable', { tag, error: (err as Error).message });
2677
3701
  }
3702
+ } catch (err) {
3703
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
3704
+ span.recordException?.(err);
3705
+ throw err;
3706
+ } finally {
3707
+ span.end();
2678
3708
  }
2679
3709
  }
2680
3710
 
@@ -2691,11 +3721,12 @@ export class CacheService {
2691
3721
  * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
2692
3722
  */
2693
3723
  async invalidateTags(tags: string[]): Promise<void> {
3724
+ this._assertActive('invalidateTags');
2694
3725
  if (tags.length === 0) return;
2695
3726
  if (tags.length === 1) { await this.invalidateTag(tags[0]); return; }
2696
3727
 
2697
3728
  if (this.opts.tagStrategy === 'generational') {
2698
- const now = Date.now();
3729
+ const now = performance.now();
2699
3730
  if (!this._redisDisabled) {
2700
3731
  try {
2701
3732
  const client = await this.getRedis();
@@ -2706,7 +3737,11 @@ export class CacheService {
2706
3737
  const [err, newVer] = results[i] ?? [null, null];
2707
3738
  const ver = (!err && typeof newVer === 'number') ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
2708
3739
  this._setLocalTagVersion(tags[i], ver, now);
2709
- void this.publishInvalidation('tag_incr', tags[i], ver);
3740
+ if (this.opts.awaitInvalidationBackplane) {
3741
+ await this.publishInvalidation('tag_incr', tags[i], ver, false, true);
3742
+ } else {
3743
+ void this.publishInvalidation('tag_incr', tags[i], ver, false, true);
3744
+ }
2710
3745
  }
2711
3746
  return;
2712
3747
  } catch (err) {
@@ -2716,7 +3751,11 @@ export class CacheService {
2716
3751
  for (const tag of tags) {
2717
3752
  const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
2718
3753
  this._setLocalTagVersion(tag, ver, now);
2719
- void this.publishInvalidation('tag_incr', tag, ver);
3754
+ if (this.opts.awaitInvalidationBackplane) {
3755
+ await this.publishInvalidation('tag_incr', tag, ver, false, true);
3756
+ } else {
3757
+ void this.publishInvalidation('tag_incr', tag, ver, false, true);
3758
+ }
2720
3759
  }
2721
3760
  return;
2722
3761
  }
@@ -2733,7 +3772,15 @@ export class CacheService {
2733
3772
  }
2734
3773
  for (const k of allMembers) {
2735
3774
  this.l1.delete(k);
2736
- this.disk.delete(k);
3775
+ this._bumpKeyMutation(k);
3776
+ this._pendingDiskDeletes.add(k);
3777
+ setImmediate(() => {
3778
+ try {
3779
+ if (!this._diskDisabled) this.disk.delete(k);
3780
+ } finally {
3781
+ this._pendingDiskDeletes.delete(k);
3782
+ }
3783
+ });
2737
3784
  }
2738
3785
 
2739
3786
  if (!this._redisDisabled) {
@@ -2775,6 +3822,7 @@ export class CacheService {
2775
3822
  * `l2` is `null` when Redis is disabled.
2776
3823
  */
2777
3824
  async ping(): Promise<CachePingResult> {
3825
+ this._assertActive('ping');
2778
3826
  // L1: measure a has() call
2779
3827
  const t0 = Date.now();
2780
3828
  this.l1.has('__ping__');
@@ -2799,12 +3847,72 @@ export class CacheService {
2799
3847
  return { l1, disk, l2 };
2800
3848
  }
2801
3849
 
3850
+ /**
3851
+ * Health and readiness diagnostics for container orchestrators (e.g. Kubernetes, ECS, Nomad).
3852
+ *
3853
+ * ─────────────────────────────────────────────────────────────────────────────
3854
+ * ⚠️ CRITICAL CONTAINER PROBE SEMANTICS (Liveness vs. Readiness):
3855
+ * ─────────────────────────────────────────────────────────────────────────────
3856
+ * ❌ NEVER bind `degraded` checks or `cache.health()` to your Liveness Probe (/livez, /healthz).
3857
+ * If an SRE hooks degraded status into liveness, a storage-starved or EBS-throttled pod
3858
+ * will be killed by the kubelet, triggering a cluster-wide cascading restart shockwave.
3859
+ * Liveness probes must only check that the event loop / process is alive.
3860
+ *
3861
+ * ✅ BIND degraded checks strictly to your Readiness Probe (/ready, /readyz).
3862
+ * A degraded cache (e.g. EBS latency spike, quota watermark pruning, or open Redis circuit)
3863
+ * can shed traffic at the ingress load balancer while the Node.js process remains
3864
+ * alive to drain in-flight promises and heal its local storage.
3865
+ *
3866
+ * By default, `healthy` remains `true` even when degraded (graceful local degradation).
3867
+ * Set `failReadinessOnDegraded: true` in CacheOptions if you want your Readiness probe
3868
+ * to route ingress traffic away while degraded.
3869
+ * ─────────────────────────────────────────────────────────────────────────────
3870
+ */
3871
+ health(): CacheHealthStatus {
3872
+ const watchdogTel = this.watchdog.getTelemetry();
3873
+ const diskPruning = !this._diskDisabled && this.disk.isPruning;
3874
+ const diskLowSpace = !this._diskDisabled && this.disk.hostVolumeLowSpace;
3875
+ const circuitOpen = this.cb.isOpen;
3876
+ const latencyBypass = watchdogTel.bypassActive;
3877
+
3878
+ const degraded = circuitOpen || latencyBypass || diskPruning || diskLowSpace;
3879
+ const healthy = this.opts.failReadinessOnDegraded ? !degraded : true;
3880
+
3881
+ const reasons: string[] = [];
3882
+ if (circuitOpen) reasons.push('redis_circuit_breaker_open');
3883
+ if (latencyBypass) reasons.push(`disk_latency_bypass_stage_${watchdogTel.bypassStage}`);
3884
+ if (diskPruning) reasons.push('disk_quota_watermark_pruning_active');
3885
+ if (diskLowSpace) reasons.push('disk_host_volume_low_space');
3886
+
3887
+ return {
3888
+ healthy,
3889
+ degraded,
3890
+ reasons,
3891
+ details: {
3892
+ redisConnected: !circuitOpen && !this._redisDisabled,
3893
+ circuitBreakerState: this.cb.currentState,
3894
+ diskPruningActive: diskPruning,
3895
+ diskHostVolumeLowSpace: diskLowSpace,
3896
+ watchdog: watchdogTel,
3897
+ },
3898
+ };
3899
+ }
3900
+
3901
+ /**
3902
+ * Direct access to the internal tier latency watchdog instance.
3903
+ * Used for diagnostics, canary probes, and control-loop tuning.
3904
+ */
3905
+ getLatencyWatchdog(): TierLatencyWatchdog {
3906
+ return this.watchdog;
3907
+ }
3908
+
2802
3909
  /**
2803
3910
  * Export all live L1 entries to Redis via a single pipeline.
2804
3911
  * Useful for warming a new Redis instance or for zero-downtime failover.
2805
3912
  * Returns the number of keys written.
2806
3913
  */
2807
3914
  async drainToL2(): Promise<number> {
3915
+ this._assertActive('drainToL2');
2808
3916
  if (this._redisDisabled) return 0;
2809
3917
  try {
2810
3918
  const client = await this.getRedis();
@@ -2853,6 +3961,7 @@ export class CacheService {
2853
3961
  * if (!claimed) return res.status(409).json({ error: 'duplicate request' });
2854
3962
  */
2855
3963
  async setIfAbsent<T>(cacheKey: string, value: T, ttlSeconds = 300, priority?: CachePriority): Promise<boolean> {
3964
+ this._assertActive('setIfAbsent');
2856
3965
  const k = this.nk(cacheKey);
2857
3966
 
2858
3967
  // Fast path: L1 check (process-local, no network hop)
@@ -2877,6 +3986,8 @@ export class CacheService {
2877
3986
 
2878
3987
  const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
2879
3988
  const p = priority ?? inferPriority(cacheKey);
3989
+ this._bumpKeyMutation(k);
3990
+ this._pendingDiskDeletes.delete(k);
2880
3991
  this.l1.set(k, value, ttlMs, p);
2881
3992
  this.counters.sets++;
2882
3993
  return true;
@@ -2901,6 +4012,7 @@ export class CacheService {
2901
4012
  fn: () => Promise<T>,
2902
4013
  options?: LockOptions,
2903
4014
  ): Promise<T> {
4015
+ this._assertActive('lock');
2904
4016
  const ttlSeconds = Math.max(1, options?.ttl ?? 30);
2905
4017
  const acquireTimeout = Math.max(0, options?.acquireTimeout ?? 5_000);
2906
4018
  const retryInterval = Math.max(10, options?.retryInterval ?? 100);
@@ -2936,6 +4048,10 @@ export class CacheService {
2936
4048
  }
2937
4049
  } catch (err) {
2938
4050
  if ((err as Error).message.startsWith('Failed to acquire lock')) throw err;
4051
+ const failClosed = options?.failClosedOnRedisError ?? this.opts.lockFailClosed;
4052
+ if (failClosed) {
4053
+ throw new Error(`Distributed lock acquisition failed for resource "${resourceKey}" due to Redis error: ${(err as Error).message}`);
4054
+ }
2939
4055
  this.logger.debug('Distributed lock: Redis error, falling back to in-process mutex', {
2940
4056
  resourceKey, error: (err as Error).message,
2941
4057
  });
@@ -3088,7 +4204,7 @@ export class CacheService {
3088
4204
  if (visited.has(dep)) continue;
3089
4205
  this.l1.delete(dep);
3090
4206
  if (!this._diskDisabled) this.disk.delete(dep);
3091
- void this.publishInvalidation('del', dep);
4207
+ void this.publishInvalidation('del', dep, undefined, false, true);
3092
4208
  this.logger.debug('Dependency cascade: invalidated dependent key', {
3093
4209
  trigger: deletedKey.slice(0, 60), dependent: dep.slice(0, 60),
3094
4210
  });
@@ -3163,13 +4279,37 @@ export class CacheService {
3163
4279
  evictions: c.oomEvictions,
3164
4280
  lastTriggeredAt: c.oomLastAt,
3165
4281
  },
4282
+ ...(this.opts.remoteSnapshot && {
4283
+ remoteSnapshot: {
4284
+ enabled: true,
4285
+ uploads: c.remoteSnapshotUploads,
4286
+ downloads: c.remoteSnapshotDownloads,
4287
+ errors: c.remoteSnapshotErrors,
4288
+ lastUploadedAt: c.remoteSnapshotLastUploadedAt,
4289
+ lastDownloadedAt: c.remoteSnapshotLastDownloadedAt,
4290
+ },
4291
+ }),
4292
+ ...(this.opts.crossRegion && {
4293
+ crossRegion: {
4294
+ enabled: true,
4295
+ currentRegion: this.opts.crossRegion.currentRegion,
4296
+ sent: c.crossRegionSent,
4297
+ received: c.crossRegionReceived,
4298
+ deduplicated: c.crossRegionDeduplicated,
4299
+ errors: c.crossRegionErrors,
4300
+ },
4301
+ }),
3166
4302
 
3167
4303
  l1: {
3168
4304
  entries: l1s.entries,
3169
4305
  sizeBytes: this.l1.memoryUsage,
3170
4306
  maxBytes: this.opts.l1MaxBytes,
3171
4307
  },
3172
- disk: { ...this.disk.stats, disabled: this._diskDisabled },
4308
+ disk: {
4309
+ ...this.disk.stats,
4310
+ disabled: this._diskDisabled,
4311
+ latencyWatchdog: this.watchdog.getTelemetry(),
4312
+ },
3173
4313
  ...(this.latencyTracker && {
3174
4314
  adaptiveTtl: {
3175
4315
  enabled: true as const,
@@ -3182,9 +4322,17 @@ export class CacheService {
3182
4322
  ),
3183
4323
  },
3184
4324
  }),
4325
+ ...(this.pipeliner && {
4326
+ pipelining: this.pipeliner.stats,
4327
+ }),
3185
4328
  };
3186
4329
  }
3187
4330
 
4331
+ /** Return auto-pipelining metrics, or null if pipelining is disabled. */
4332
+ getPipelinerStats() {
4333
+ return this.pipeliner ? this.pipeliner.stats : null;
4334
+ }
4335
+
3188
4336
  /**
3189
4337
  * Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
3190
4338
  * Paste the result into your `/metrics` endpoint.
@@ -3229,6 +4377,19 @@ export class CacheService {
3229
4377
  gauge('l1_size_bytes', m.l1.sizeBytes, 'Current L1 used bytes');
3230
4378
  gauge('disk_files', m.disk.files, 'Current L1.5 disk file count');
3231
4379
 
4380
+ if (m.disk.latencyWatchdog) {
4381
+ gauge('disk_latency_bypass_stage', m.disk.latencyWatchdog.bypassStage, 'Disk latency watchdog bypass stage (0: normal, 1: 25%, 2: 75%, 3: 100%)');
4382
+ gauge('disk_p95_ms', m.disk.latencyWatchdog.diskP95Ms, 'Disk read p95 latency in ms');
4383
+ gauge('redis_p95_ms', m.disk.latencyWatchdog.redisP95Ms, 'Redis read p95 latency in ms');
4384
+ counter('disk_bypassed_events', m.disk.latencyWatchdog.bypassedTotal, 'Total disk bypass activation events');
4385
+ }
4386
+ if (m.disk.pruning) {
4387
+ counter('disk_spills_shed', m.disk.pruning.spillsShedTotal, 'Total disk spills shed due to pruning or low disk space');
4388
+ counter('disk_prune_rounds', m.disk.pruning.pruneRounds, 'Total high-watermark disk prune rounds');
4389
+ counter('disk_entries_pruned', m.disk.pruning.entriesPruned, 'Total entries removed by watermark pruning');
4390
+ counter('disk_low_space_pauses', m.disk.pruning.hostVolumeLowSpacePauses, 'Total times spills paused due to <10% host volume space');
4391
+ }
4392
+
3232
4393
  gauge('bloom_false_positive_rate', m.bloom.falsePositiveRate,
3233
4394
  'Bloom filter false-positive rate; increase capacity if > 0.01');
3234
4395
  gauge('compression_bytes_saved', m.compression.bytesSaved,
@@ -3242,6 +4403,17 @@ export class CacheService {
3242
4403
  counter('oom_evictions', m.oom.evictions,
3243
4404
  'Emergency L1 eviction rounds triggered by heap pressure');
3244
4405
  }
4406
+ if (m.remoteSnapshot?.enabled) {
4407
+ counter('remote_snapshot_uploads', m.remoteSnapshot.uploads, 'Total remote snapshot uploads');
4408
+ counter('remote_snapshot_downloads', m.remoteSnapshot.downloads, 'Total remote snapshot downloads');
4409
+ counter('remote_snapshot_errors', m.remoteSnapshot.errors, 'Total remote snapshot errors');
4410
+ }
4411
+ if (m.crossRegion?.enabled) {
4412
+ counter('cross_region_sent', m.crossRegion.sent, 'Total cross-region invalidations broadcast');
4413
+ counter('cross_region_received', m.crossRegion.received, 'Total cross-region invalidations received');
4414
+ counter('cross_region_deduplicated', m.crossRegion.deduplicated, 'Total cross-region invalidations deduplicated or self-filtered');
4415
+ counter('cross_region_errors', m.crossRegion.errors, 'Total cross-region relay errors');
4416
+ }
3245
4417
 
3246
4418
  return lines.join('\n');
3247
4419
  }
@@ -3254,6 +4426,7 @@ export class CacheService {
3254
4426
  * the previous key for seamless fallback decryption of existing cache entries.
3255
4427
  */
3256
4428
  async rotateEncryptionKey(newKeyBase64: string, newMode?: EncryptionMode): Promise<void> {
4429
+ this._assertActive('rotateEncryptionKey');
3257
4430
  this.enc.rotateKey(newKeyBase64, newMode);
3258
4431
  if (this._workerPool) {
3259
4432
  await this._workerPool.drainAndReinit(this.enc.toWorkerInit());
@@ -3264,21 +4437,31 @@ export class CacheService {
3264
4437
  /** Close Redis connections and stop all background timers. */
3265
4438
  async destroy(): Promise<void> {
3266
4439
  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;
4440
+ this._pendingDiskDeletes.clear();
4441
+ this._keyMutationEpochs.clear();
4442
+ const g = globalThis as Record<string, unknown>;
4443
+ const key = CacheService.globalKey(this.opts);
4444
+ if (g[key] === this) {
4445
+ delete g[key];
4446
+ }
4447
+ if (this.cleanupInterval) clearInterval(this.cleanupInterval);
4448
+ if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
4449
+ if (this.oomInterval) clearInterval(this.oomInterval);
4450
+ if (this.metricsInterval) clearInterval(this.metricsInterval);
4451
+ if (this.remoteSnapshotInterval) {
4452
+ clearInterval(this.remoteSnapshotInterval);
4453
+ this.remoteSnapshotInterval = null;
3275
4454
  }
4455
+ ProcessTerminationBus.unregister(this);
4456
+ this._shutdownHandler = null;
3276
4457
  if (this._workerPool) {
3277
4458
  await this._workerPool.destroy();
3278
4459
  this._workerPool = null;
3279
4460
  }
3280
4461
  if (this.subClient) {
3281
- try { this.subClient.disconnect(); } catch { /* ok */ }
4462
+ if (!this.opts.redisSubClient) {
4463
+ try { this.subClient.disconnect(); } catch { /* ok */ }
4464
+ }
3282
4465
  this.subClient = null;
3283
4466
  }
3284
4467
  if (this.streamClient) {
@@ -3286,10 +4469,31 @@ export class CacheService {
3286
4469
  this.streamClient = null;
3287
4470
  }
3288
4471
  if (this.redis) {
3289
- try { await this.redis.disconnect(); } catch { /* ok */ }
4472
+ if (!this.opts.redisClient) {
4473
+ try { await this.redis.disconnect(); } catch { /* ok */ }
4474
+ }
3290
4475
  this.redis = null;
3291
4476
  }
4477
+ if (this._ipcServer) {
4478
+ await this._ipcServer.close();
4479
+ this._ipcServer = undefined;
4480
+ }
3292
4481
  if (!this._diskDisabled) this.disk.close();
3293
4482
  }
3294
4483
 
4484
+ /**
4485
+ * Return the active IPC telemetry server instance, if enabled.
4486
+ */
4487
+ getIpcServer(): IpcTelemetryServer | undefined {
4488
+ return this._ipcServer;
4489
+ }
4490
+
4491
+ /**
4492
+ * Return real-time telemetry and metrics for the Window TinyLFU admission policy.
4493
+ * Returns `undefined` if W-TinyLFU admission is not active.
4494
+ */
4495
+ getWTinyLfuStats(): WTinyLfuStats | undefined {
4496
+ return this.l1.getWTinyLfuStats();
4497
+ }
4498
+
3295
4499
  }