tricache 0.8.0 → 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 (44) hide show
  1. package/README.md +4 -2
  2. package/dashboards/prometheus-scrape.yml +18 -0
  3. package/dist/{cache-service-CyLdpo77.d.ts → cache-service-DVvroyqA.d.ts} +16 -1
  4. package/dist/{cache-service-5MZXFIGK.js → cache-service-KI5ACF3F.js} +1 -1
  5. package/dist/chunk-BQRURGGD.js +60 -0
  6. package/dist/chunk-IITRFWHY.js +196 -0
  7. package/dist/{chunk-6PQ5MOWR.js → chunk-PL5J3ZNT.js} +370 -81
  8. package/dist/cli.cjs +392 -84
  9. package/dist/cli.js +22 -4
  10. package/dist/dashboard/index.d.ts +2 -2
  11. package/dist/drizzle/index.cjs +350 -81
  12. package/dist/drizzle/index.d.ts +2 -2
  13. package/dist/drizzle/index.js +1 -1
  14. package/dist/edge/index.cjs +99 -38
  15. package/dist/edge/index.d.ts +3 -3
  16. package/dist/edge/index.js +5 -5
  17. package/dist/hono/index.cjs +7760 -0
  18. package/dist/hono/index.d.ts +91 -0
  19. package/dist/hono/index.js +185 -0
  20. package/dist/{hono-DQRS1Xd7.d.ts → hono-VA9A1m0I.d.ts} +3 -2
  21. package/dist/http/index.cjs +449 -119
  22. package/dist/http/index.d.ts +6 -30
  23. package/dist/http/index.js +9 -59
  24. package/dist/index.cjs +370 -81
  25. package/dist/index.d.ts +3 -3
  26. package/dist/index.js +1 -1
  27. package/dist/nestjs/index.cjs +350 -81
  28. package/dist/nestjs/index.d.ts +2 -2
  29. package/dist/nestjs/index.js +1 -1
  30. package/dist/next/index.cjs +350 -81
  31. package/dist/next/index.d.ts +2 -2
  32. package/dist/next/index.js +1 -1
  33. package/dist/prisma/index.d.ts +2 -2
  34. package/dist/{types-B6krw64X.d.ts → types-B_QkVwJ7.d.ts} +23 -0
  35. package/dist/utils-CEsU_Z0s.d.ts +27 -0
  36. package/package.json +16 -6
  37. package/src/cache-service.ts +302 -35
  38. package/src/cli.ts +21 -4
  39. package/src/edge/hono.ts +123 -42
  40. package/src/hono/index.ts +316 -0
  41. package/src/http/index.ts +5 -0
  42. package/src/ipc-telemetry.ts +29 -1
  43. package/src/types.ts +25 -0
  44. package/dist/chunk-ZTSWCFYO.js +0 -135
@@ -469,6 +469,8 @@ export class CacheService {
469
469
  redisHost: string; redisPort: number; redisTls: boolean; disableRedis: boolean;
470
470
  encryptionKey: string | undefined; encryptionMode: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor' | undefined; snapshotPath: string; snapshotMaxAgeMs: number;
471
471
  invalidationBackplane: boolean;
472
+ awaitInvalidationBackplane: boolean;
473
+ lockFailClosed: boolean;
472
474
  oomProtection: boolean; oomHeapThreshold: number;
473
475
  oomCheckIntervalMs: number; oomEvictPercent: number;
474
476
  onMetrics: ((m: CacheMetrics) => void) | undefined;
@@ -573,6 +575,57 @@ export class CacheService {
573
575
  private streamClient: AnyRedisClient | null = null;
574
576
  private _lastStreamId = '$';
575
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
+ }
576
629
  private _ipcServer?: IpcTelemetryServer;
577
630
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
578
631
  private _subDisconnectedAt: number | null = null;
@@ -679,6 +732,8 @@ export class CacheService {
679
732
  os.tmpdir(), ns ? `tricache-snapshot-${ns}.msgpack` : 'tricache-snapshot.msgpack'),
680
733
  snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
681
734
  invalidationBackplane: options.invalidationBackplane ?? true,
735
+ awaitInvalidationBackplane: options.awaitInvalidationBackplane ?? false,
736
+ lockFailClosed: options.lockFailClosed ?? false,
682
737
  oomProtection: options.oomProtection ?? true,
683
738
  oomHeapThreshold: options.oomHeapThreshold ?? 0.85,
684
739
  oomCheckIntervalMs: options.oomCheckIntervalMs ?? 10_000,
@@ -1082,7 +1137,7 @@ export class CacheService {
1082
1137
  'redisHost', 'redisPort', 'redisTls', 'disableRedis',
1083
1138
  'redisClusterNodes', 'redisSentinel', 'encryptionKey', 'encryptionMode',
1084
1139
  'l1MaxBytes', 'l1MaxEntries', 'namespace', 'frozen', 'adaptiveTtl',
1085
- 'l2WriteMode', 'instanceName', 'invalidationBackplane',
1140
+ 'l2WriteMode', 'instanceName', 'invalidationBackplane', 'awaitInvalidationBackplane', 'lockFailClosed',
1086
1141
  ];
1087
1142
 
1088
1143
  /** Returns the names of options that differ between `a` and the live `b`. */
@@ -1129,6 +1184,8 @@ export class CacheService {
1129
1184
  frozen: o.frozen,
1130
1185
  adaptiveTtl: o.adaptiveTtl,
1131
1186
  invalidationBackplane: o.invalidationBackplane,
1187
+ awaitInvalidationBackplane: o.awaitInvalidationBackplane,
1188
+ lockFailClosed: o.lockFailClosed,
1132
1189
  strictSingleton: o.strictSingleton,
1133
1190
  remoteSnapshot: o.remoteSnapshot,
1134
1191
  crossRegion: o.crossRegion,
@@ -1447,14 +1504,36 @@ export class CacheService {
1447
1504
  private _applyInvalidationEvent(op: string, key: string, tagVersion?: number): void {
1448
1505
  if (op === 'del') {
1449
1506
  this.l1.delete(key);
1450
- 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
+ });
1451
1517
  this._cascadeDependencies(key);
1452
1518
  } else if (op === 'del-glob') {
1453
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);
1454
1533
  } else if (op === 'tag_incr') {
1455
1534
  const tag = key;
1456
1535
  const ver = typeof tagVersion === 'number' ? tagVersion : ((this.tagVersions.get(tag)?.version ?? 0) + 1);
1457
- this._setLocalTagVersion(tag, ver, Date.now());
1536
+ this._setLocalTagVersion(tag, ver, performance.now());
1458
1537
  }
1459
1538
  this.logger.debug('Backplane: invalidation applied', { op, key: key.slice(0, 60) });
1460
1539
  }
@@ -1497,7 +1576,11 @@ export class CacheService {
1497
1576
  if (!isCrossRegionRelay && this.opts.crossRegion) {
1498
1577
  const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
1499
1578
  if (shouldBroadcast) {
1500
- void this._broadcastCrossRegion(op, key, tagVersion);
1579
+ if (this.opts.awaitInvalidationBackplane) {
1580
+ await this._broadcastCrossRegion(op, key, tagVersion);
1581
+ } else {
1582
+ void this._broadcastCrossRegion(op, key, tagVersion);
1583
+ }
1501
1584
  }
1502
1585
  }
1503
1586
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
@@ -1535,7 +1618,12 @@ export class CacheService {
1535
1618
  );
1536
1619
  }
1537
1620
  this.counters.invSent++;
1538
- } 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
+ }
1539
1627
  }
1540
1628
 
1541
1629
  private _markCrossRegionEventSeen(id: string): void {
@@ -1776,6 +1864,7 @@ export class CacheService {
1776
1864
  }
1777
1865
 
1778
1866
  private async getRedis(): Promise<AnyRedisClient> {
1867
+ this._assertActive('getRedis');
1779
1868
  if (!this.cb.isAllowed()) throw new Error('tricache: L2 circuit breaker is open');
1780
1869
  if (this.redis) return this.redis;
1781
1870
  if (this.redisConnecting) return this.redisConnecting;
@@ -2152,6 +2241,7 @@ export class CacheService {
2152
2241
  tags?: string[];
2153
2242
  } = {},
2154
2243
  ): Promise<T> {
2244
+ this._assertActive('get');
2155
2245
  const span = this._startSpan('tricache.get');
2156
2246
  if (this.opts.tracer) span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
2157
2247
  const k = this.nk(cacheKey); // namespaced key used for all storage
@@ -2192,7 +2282,14 @@ export class CacheService {
2192
2282
  if (swrGraceMs > 0 && !this.revalidating.has(k)) {
2193
2283
  const priority = optPriority ?? inferPriority(cacheKey);
2194
2284
  this.revalidating.add(k);
2195
- 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
+ );
2196
2293
  this.counters.swrRevalidations++;
2197
2294
  this.logger.debug('SWR: serving stale, revalidating', { cacheKey });
2198
2295
  } else {
@@ -2217,7 +2314,14 @@ export class CacheService {
2217
2314
  if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
2218
2315
  const priority = optPriority ?? inferPriority(cacheKey);
2219
2316
  this.revalidating.add(k);
2220
- 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
+ );
2221
2325
  this.counters.swrRevalidations++;
2222
2326
  this.logger.debug(
2223
2327
  shouldXFetch ? 'XFetch: proactive background recompute' : 'Refresh-ahead: proactive background recompute',
@@ -2257,12 +2361,16 @@ export class CacheService {
2257
2361
  return existing as Promise<T>;
2258
2362
  }
2259
2363
 
2364
+ const mutationEpochAtStart = this._getKeyMutationEpoch(k);
2260
2365
  const executionPromise: Promise<T> = (async () => {
2261
2366
  try {
2262
2367
  // ── Tier 1.5: disk tier (evicted L1 entries) — protected by latency watchdog ──
2263
- if (!this._diskDisabled) {
2264
- const isDiskAllowed = this.watchdog.isDiskAllowed();
2265
- if (isDiskAllowed) {
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) {
2266
2374
  const diskStart = performance.now();
2267
2375
  const diskHit = this.disk.load(k);
2268
2376
  const diskElapsed = performance.now() - diskStart;
@@ -2308,6 +2416,7 @@ export class CacheService {
2308
2416
  }
2309
2417
  }
2310
2418
  }
2419
+ }
2311
2420
 
2312
2421
  // ── Tier 2: Redis (distributed, production-only by default) ──
2313
2422
  if (!this._redisDisabled) {
@@ -2430,6 +2539,23 @@ export class CacheService {
2430
2539
  }
2431
2540
  }
2432
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
+
2433
2559
  this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
2434
2560
 
2435
2561
  if (!this._redisDisabled) {
@@ -2565,25 +2691,47 @@ export class CacheService {
2565
2691
  ttlMs: number,
2566
2692
  swrGraceMs: number,
2567
2693
  priority: CachePriority,
2694
+ knownTagVersions?: Record<string, number>,
2568
2695
  ): Promise<void> {
2696
+ const startEpoch = this._getKeyMutationEpoch(cacheKey);
2569
2697
  try {
2570
2698
  const fetchStart = Date.now();
2571
2699
  const data = await fetchFn();
2572
2700
  const delta = Date.now() - fetchStart;
2573
2701
  const staleAt = Date.now() + ttlMs;
2574
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
+
2575
2709
  // Keep the latency tracker current during SWR background revalidations too
2576
2710
  if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
2577
2711
 
2578
2712
  let activeTagVersions: Record<string, number> | undefined;
2579
2713
  const l1Existing = this.l1.get(cacheKey);
2580
- if (this.opts.tagStrategy === 'generational' && l1Existing?.tagVersions) {
2581
- const tags = Object.keys(l1Existing.tagVersions);
2714
+ const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
2715
+ if (this.opts.tagStrategy === 'generational' && tagVersionsSource) {
2716
+ const tags = Object.keys(tagVersionsSource);
2582
2717
  const vers = await Promise.all(tags.map(tag => this._getTagVersion(tag)));
2583
2718
  activeTagVersions = {};
2584
2719
  for (let i = 0; i < tags.length; i++) {
2585
2720
  activeTagVersions[tags[i]] = vers[i];
2586
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;
2587
2735
  }
2588
2736
 
2589
2737
  this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
@@ -2629,6 +2777,7 @@ export class CacheService {
2629
2777
 
2630
2778
  /** Explicitly write a value into L1 (+ L2 in production). */
2631
2779
  async set<T>(cacheKey: string, data: T, ttlSeconds = 300, priority?: CachePriority, opts?: { tags?: string[]; dependsOn?: string[] }): Promise<void> {
2780
+ this._assertActive('set');
2632
2781
  const span = this._startSpan('tricache.set');
2633
2782
  if (this.opts.tracer) {
2634
2783
  span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
@@ -2642,6 +2791,9 @@ export class CacheService {
2642
2791
  const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1_000);
2643
2792
  const p = priority ?? inferPriority(cacheKey);
2644
2793
  const k = this.nk(cacheKey);
2794
+ this._bumpKeyMutation(k);
2795
+ this.inflight.delete(k);
2796
+ this._pendingDiskDeletes.delete(k);
2645
2797
  this.counters.sets++;
2646
2798
 
2647
2799
  let activeTagVersions: Record<string, number> | undefined;
@@ -2700,7 +2852,11 @@ export class CacheService {
2700
2852
  }
2701
2853
  }
2702
2854
 
2703
- void this.publishInvalidation('del', k);
2855
+ if (this.opts.awaitInvalidationBackplane) {
2856
+ await this.publishInvalidation('del', k);
2857
+ } else {
2858
+ void this.publishInvalidation('del', k);
2859
+ }
2704
2860
  } catch (err) {
2705
2861
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
2706
2862
  span.recordException?.(err);
@@ -2744,6 +2900,7 @@ export class CacheService {
2744
2900
  * await cache.delete('user:abc:*'); // all keys for user abc
2745
2901
  */
2746
2902
  async delete(cacheKey: string): Promise<void> {
2903
+ this._assertActive('delete');
2747
2904
  const span = this._startSpan('tricache.delete');
2748
2905
  if (this.opts.tracer) span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
2749
2906
  try {
@@ -2752,16 +2909,32 @@ export class CacheService {
2752
2909
  this.counters.deletes++;
2753
2910
 
2754
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);
2755
2925
  this.l1.deletePattern(k);
2756
2926
  } else {
2927
+ this._bumpKeyMutation(k);
2928
+ this.inflight.delete(k);
2757
2929
  this.l1.delete(k);
2758
- // Defer the synchronous SHA-256 hash + fs syscalls to the next event-loop tick so
2759
- // the caller's await resolves without blocking. Matches what the backplane handler
2760
- // already does for remote invalidations: setImmediate(() => this.disk.delete(msg.key)).
2761
- // A re-get in the narrow window before the deferred call fires would get an L1 miss
2762
- // and promote the disk entry back — acceptable for a cache (same trade-off the backplane
2763
- // path already accepts).
2764
- setImmediate(() => { if (!this._diskDisabled) this.disk.delete(k); });
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
+ });
2765
2938
  // Cascade: invalidate any key that declared it depends on this exact key's pattern
2766
2939
  this._cascadeDependencies(k);
2767
2940
  // Clean up: remove k from all dependency registrations (it is gone)
@@ -2788,7 +2961,11 @@ export class CacheService {
2788
2961
  }
2789
2962
  }
2790
2963
 
2791
- void this.publishInvalidation(isPattern ? 'del-glob' : 'del', k, undefined, false, true);
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
+ }
2792
2969
  } catch (err) {
2793
2970
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
2794
2971
  span.recordException?.(err);
@@ -2817,6 +2994,7 @@ export class CacheService {
2817
2994
  * fleet-wide.
2818
2995
  */
2819
2996
  async increment(cacheKey: string, ttlSeconds?: number): Promise<number> {
2997
+ this._assertActive('increment');
2820
2998
  const k = this.nk(cacheKey);
2821
2999
 
2822
3000
  if (this._redisDisabled) {
@@ -2862,6 +3040,7 @@ export class CacheService {
2862
3040
  * await cache.clear('user:abc'); // flush all keys for one user
2863
3041
  */
2864
3042
  async clear(prefix?: string): Promise<void> {
3043
+ this._assertActive('clear');
2865
3044
  const span = this._startSpan('tricache.clear');
2866
3045
  if (this.opts.tracer) span.setAttribute('cache.prefix', prefix || '*');
2867
3046
  try {
@@ -2871,15 +3050,31 @@ export class CacheService {
2871
3050
  : undefined;
2872
3051
 
2873
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);
2874
3066
  this.l1.deletePattern(k);
2875
- // Disk-tier pattern delete is not supported (files are keyed by SHA-256 hash);
2876
- // prefix-scoped clears only evict from L1, matching existing delete('glob*') semantics.
2877
3067
  } else {
3068
+ this._globalEpoch++;
3069
+ this.inflight.clear();
3070
+ this._patternTombstones.length = 0;
2878
3071
  this.l1.clear();
2879
3072
  if (!this._diskDisabled) this.disk.clear();
2880
3073
  this._l1Counters.clear();
2881
3074
  this.tagIndex.clear();
2882
3075
  this.tagVersions.clear();
3076
+ this._pendingDiskDeletes.clear();
3077
+ this._keyMutationEpochs.clear();
2883
3078
  }
2884
3079
 
2885
3080
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
@@ -2893,9 +3088,15 @@ export class CacheService {
2893
3088
  }
2894
3089
  }
2895
3090
 
2896
- void this.publishInvalidation('del-glob',
2897
- k ?? (this._namespace ? `${this._namespace}:*` : '*'),
2898
- undefined, false, true);
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
+ }
2899
3100
  } catch (err) {
2900
3101
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
2901
3102
  span.recordException?.(err);
@@ -2911,6 +3112,7 @@ export class CacheService {
2911
3112
  * Returns the number of entries evicted.
2912
3113
  */
2913
3114
  rebalance(): number {
3115
+ this._assertActive('rebalance');
2914
3116
  return this.l1.rebalance();
2915
3117
  }
2916
3118
 
@@ -2920,6 +3122,7 @@ export class CacheService {
2920
3122
  * Only reflects L1 state — does not query Redis or disk.
2921
3123
  */
2922
3124
  ttl(cacheKey: string): number | null {
3125
+ this._assertActive('ttl');
2923
3126
  return this.l1.ttl(this.nk(cacheKey));
2924
3127
  }
2925
3128
 
@@ -2928,6 +3131,7 @@ export class CacheService {
2928
3131
  * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
2929
3132
  */
2930
3133
  has(cacheKey: string): boolean {
3134
+ this._assertActive('has');
2931
3135
  return this.l1.has(this.nk(cacheKey));
2932
3136
  }
2933
3137
 
@@ -2940,6 +3144,7 @@ export class CacheService {
2940
3144
  * for (const key of cache.keys()) console.log(key);
2941
3145
  */
2942
3146
  *keys(): Generator<string> {
3147
+ this._assertActive('keys');
2943
3148
  const prefix = this._namespace ? this._namespace + ':' : '';
2944
3149
  for (const key of this.l1.liveKeys()) {
2945
3150
  if (prefix && !key.startsWith(prefix)) continue;
@@ -2955,6 +3160,7 @@ export class CacheService {
2955
3160
  * for (const val of cache.values<User>()) console.log(val.id);
2956
3161
  */
2957
3162
  *values<T = unknown>(): Generator<T> {
3163
+ this._assertActive('values');
2958
3164
  const prefix = this._namespace ? this._namespace + ':' : '';
2959
3165
  if (!prefix) {
2960
3166
  yield* this.l1.liveValues() as Generator<T>;
@@ -2974,6 +3180,7 @@ export class CacheService {
2974
3180
  * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
2975
3181
  */
2976
3182
  *entries<T = unknown>(): Generator<[string, T]> {
3183
+ this._assertActive('entries');
2977
3184
  const prefix = this._namespace ? this._namespace + ':' : '';
2978
3185
  for (const [key, entry] of this.l1.liveEntries()) {
2979
3186
  if (prefix && !key.startsWith(prefix)) continue;
@@ -3002,6 +3209,7 @@ export class CacheService {
3002
3209
  * `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
3003
3210
  */
3004
3211
  scan<T = unknown>(fn: (rawKey: string, value: T, offset: number) => void): void {
3212
+ this._assertActive('scan');
3005
3213
  const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
3006
3214
  this.l1.scan((key, entry, pfx) => {
3007
3215
  const value = (entry.value !== undefined ? entry.value : entry.data) as T;
@@ -3016,6 +3224,7 @@ export class CacheService {
3016
3224
  * @param newTtlSeconds - The new TTL from now, in seconds.
3017
3225
  */
3018
3226
  async touch(cacheKey: string, newTtlSeconds: number): Promise<boolean> {
3227
+ this._assertActive('touch');
3019
3228
  const k = this.nk(cacheKey);
3020
3229
  const hit = this.l1.touch(k, newTtlSeconds * 1_000);
3021
3230
  if (hit && !this._redisDisabled) {
@@ -3036,6 +3245,7 @@ export class CacheService {
3036
3245
  * if (fresh !== null) return fresh; // serve from L1, no network hop
3037
3246
  */
3038
3247
  getIfFresh<T = unknown>(cacheKey: string): T | null {
3248
+ this._assertActive('getIfFresh');
3039
3249
  const k = this.nk(cacheKey);
3040
3250
  const entry = this.l1.getEntry(k);
3041
3251
  if (!entry) return null;
@@ -3054,6 +3264,7 @@ export class CacheService {
3054
3264
  * const val = await cache.peek<User>('user:123');
3055
3265
  */
3056
3266
  async peek<T = unknown>(cacheKey: string): Promise<T | null> {
3267
+ this._assertActive('peek');
3057
3268
  const k = this.nk(cacheKey);
3058
3269
 
3059
3270
  // 1. L1 RAM
@@ -3069,7 +3280,10 @@ export class CacheService {
3069
3280
  }
3070
3281
 
3071
3282
  // 2. L1.5 Disk
3072
- if (!this._diskDisabled && this.watchdog.isDiskAllowed()) {
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()) {
3073
3287
  const diskStart = performance.now();
3074
3288
  const diskHit = this.disk.load(k);
3075
3289
  const diskElapsed = performance.now() - diskStart;
@@ -3095,6 +3309,7 @@ export class CacheService {
3095
3309
  }
3096
3310
  }
3097
3311
  }
3312
+ }
3098
3313
 
3099
3314
  // 3. L2 Redis
3100
3315
  if (!this._redisDisabled && !this.cb.isOpen) {
@@ -3139,6 +3354,7 @@ export class CacheService {
3139
3354
  ttl: number | ((key: string) => number) = 300,
3140
3355
  priority?: CachePriority,
3141
3356
  ): Promise<(T | undefined)[]> {
3357
+ this._assertActive('mget');
3142
3358
  const span = this._startSpan('tricache.mget');
3143
3359
  if (this.opts.tracer) {
3144
3360
  span.setAttribute('cache.batch.size', keys.length);
@@ -3214,8 +3430,13 @@ export class CacheService {
3214
3430
  // ── Tier 1.5: disk spill (evicted L1 entries) ──
3215
3431
  if (!this._diskDisabled && missKeys.length > 0) {
3216
3432
  for (let j = missKeys.length - 1; j >= 0; j--) {
3217
- if (!this.watchdog.isDiskAllowed()) continue;
3218
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;
3219
3440
  const diskStart = performance.now();
3220
3441
  const diskHit = this.disk.load(k);
3221
3442
  const diskElapsed = performance.now() - diskStart;
@@ -3303,6 +3524,7 @@ export class CacheService {
3303
3524
  async mset<T = unknown>(
3304
3525
  entries: Record<string, { value: T; ttl?: number; priority?: CachePriority; tags?: string[]; dependsOn?: string[] }>,
3305
3526
  ): Promise<void> {
3527
+ this._assertActive('mset');
3306
3528
  const span = this._startSpan('tricache.mset');
3307
3529
  const keys = Object.keys(entries);
3308
3530
  if (this.opts.tracer) {
@@ -3331,6 +3553,7 @@ export class CacheService {
3331
3553
  * await cache.mdel(['user:1', 'user:2', 'user:3']);
3332
3554
  */
3333
3555
  async mdel(keys: string[]): Promise<void> {
3556
+ this._assertActive('mdel');
3334
3557
  const span = this._startSpan('tricache.mdel');
3335
3558
  if (this.opts.tracer) {
3336
3559
  span.setAttribute('cache.batch.size', keys.length);
@@ -3359,6 +3582,7 @@ export class CacheService {
3359
3582
  * console.log(`Warmed ${loaded} keys from Redis`);
3360
3583
  */
3361
3584
  async warmFromL2(pattern: string, opts?: { priority?: CachePriority }): Promise<number> {
3585
+ this._assertActive('warmFromL2');
3362
3586
  if (this._redisDisabled) return 0;
3363
3587
  try {
3364
3588
  const client = await this.getRedis();
@@ -3412,6 +3636,7 @@ export class CacheService {
3412
3636
  * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
3413
3637
  */
3414
3638
  async invalidateTag(tag: string): Promise<void> {
3639
+ this._assertActive('invalidateTag');
3415
3640
  const span = this._startSpan('tricache.invalidate_tag');
3416
3641
  if (this.opts.tracer) {
3417
3642
  span.setAttribute('cache.tag', tag);
@@ -3433,8 +3658,12 @@ export class CacheService {
3433
3658
  const current = this.tagVersions.get(tag)?.version ?? 0;
3434
3659
  newVer = current + 1;
3435
3660
  }
3436
- this._setLocalTagVersion(tag, newVer, Date.now());
3437
- void this.publishInvalidation('tag_incr', tag, newVer, false, true);
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
+ }
3438
3667
  return;
3439
3668
  }
3440
3669
 
@@ -3444,7 +3673,15 @@ export class CacheService {
3444
3673
  // Remove from L1 + disk
3445
3674
  for (const k of members) {
3446
3675
  this.l1.delete(k);
3447
- if (!this._diskDisabled) this.disk.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
+ });
3448
3685
  }
3449
3686
  this.tagIndex.delete(tagKey);
3450
3687
 
@@ -3484,11 +3721,12 @@ export class CacheService {
3484
3721
  * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
3485
3722
  */
3486
3723
  async invalidateTags(tags: string[]): Promise<void> {
3724
+ this._assertActive('invalidateTags');
3487
3725
  if (tags.length === 0) return;
3488
3726
  if (tags.length === 1) { await this.invalidateTag(tags[0]); return; }
3489
3727
 
3490
3728
  if (this.opts.tagStrategy === 'generational') {
3491
- const now = Date.now();
3729
+ const now = performance.now();
3492
3730
  if (!this._redisDisabled) {
3493
3731
  try {
3494
3732
  const client = await this.getRedis();
@@ -3499,7 +3737,11 @@ export class CacheService {
3499
3737
  const [err, newVer] = results[i] ?? [null, null];
3500
3738
  const ver = (!err && typeof newVer === 'number') ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
3501
3739
  this._setLocalTagVersion(tags[i], ver, now);
3502
- void this.publishInvalidation('tag_incr', tags[i], ver, false, true);
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
+ }
3503
3745
  }
3504
3746
  return;
3505
3747
  } catch (err) {
@@ -3509,7 +3751,11 @@ export class CacheService {
3509
3751
  for (const tag of tags) {
3510
3752
  const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
3511
3753
  this._setLocalTagVersion(tag, ver, now);
3512
- void this.publishInvalidation('tag_incr', tag, ver, false, true);
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
+ }
3513
3759
  }
3514
3760
  return;
3515
3761
  }
@@ -3526,7 +3772,15 @@ export class CacheService {
3526
3772
  }
3527
3773
  for (const k of allMembers) {
3528
3774
  this.l1.delete(k);
3529
- 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
+ });
3530
3784
  }
3531
3785
 
3532
3786
  if (!this._redisDisabled) {
@@ -3568,6 +3822,7 @@ export class CacheService {
3568
3822
  * `l2` is `null` when Redis is disabled.
3569
3823
  */
3570
3824
  async ping(): Promise<CachePingResult> {
3825
+ this._assertActive('ping');
3571
3826
  // L1: measure a has() call
3572
3827
  const t0 = Date.now();
3573
3828
  this.l1.has('__ping__');
@@ -3657,6 +3912,7 @@ export class CacheService {
3657
3912
  * Returns the number of keys written.
3658
3913
  */
3659
3914
  async drainToL2(): Promise<number> {
3915
+ this._assertActive('drainToL2');
3660
3916
  if (this._redisDisabled) return 0;
3661
3917
  try {
3662
3918
  const client = await this.getRedis();
@@ -3705,6 +3961,7 @@ export class CacheService {
3705
3961
  * if (!claimed) return res.status(409).json({ error: 'duplicate request' });
3706
3962
  */
3707
3963
  async setIfAbsent<T>(cacheKey: string, value: T, ttlSeconds = 300, priority?: CachePriority): Promise<boolean> {
3964
+ this._assertActive('setIfAbsent');
3708
3965
  const k = this.nk(cacheKey);
3709
3966
 
3710
3967
  // Fast path: L1 check (process-local, no network hop)
@@ -3729,6 +3986,8 @@ export class CacheService {
3729
3986
 
3730
3987
  const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
3731
3988
  const p = priority ?? inferPriority(cacheKey);
3989
+ this._bumpKeyMutation(k);
3990
+ this._pendingDiskDeletes.delete(k);
3732
3991
  this.l1.set(k, value, ttlMs, p);
3733
3992
  this.counters.sets++;
3734
3993
  return true;
@@ -3753,6 +4012,7 @@ export class CacheService {
3753
4012
  fn: () => Promise<T>,
3754
4013
  options?: LockOptions,
3755
4014
  ): Promise<T> {
4015
+ this._assertActive('lock');
3756
4016
  const ttlSeconds = Math.max(1, options?.ttl ?? 30);
3757
4017
  const acquireTimeout = Math.max(0, options?.acquireTimeout ?? 5_000);
3758
4018
  const retryInterval = Math.max(10, options?.retryInterval ?? 100);
@@ -3788,6 +4048,10 @@ export class CacheService {
3788
4048
  }
3789
4049
  } catch (err) {
3790
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
+ }
3791
4055
  this.logger.debug('Distributed lock: Redis error, falling back to in-process mutex', {
3792
4056
  resourceKey, error: (err as Error).message,
3793
4057
  });
@@ -4162,6 +4426,7 @@ export class CacheService {
4162
4426
  * the previous key for seamless fallback decryption of existing cache entries.
4163
4427
  */
4164
4428
  async rotateEncryptionKey(newKeyBase64: string, newMode?: EncryptionMode): Promise<void> {
4429
+ this._assertActive('rotateEncryptionKey');
4165
4430
  this.enc.rotateKey(newKeyBase64, newMode);
4166
4431
  if (this._workerPool) {
4167
4432
  await this._workerPool.drainAndReinit(this.enc.toWorkerInit());
@@ -4172,6 +4437,8 @@ export class CacheService {
4172
4437
  /** Close Redis connections and stop all background timers. */
4173
4438
  async destroy(): Promise<void> {
4174
4439
  this._destroyed = true;
4440
+ this._pendingDiskDeletes.clear();
4441
+ this._keyMutationEpochs.clear();
4175
4442
  const g = globalThis as Record<string, unknown>;
4176
4443
  const key = CacheService.globalKey(this.opts);
4177
4444
  if (g[key] === this) {