tricache 0.8.0 → 1.0.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 (56) hide show
  1. package/README.md +10 -4
  2. package/dashboards/prometheus-scrape.yml +18 -0
  3. package/dist/{cache-service-5MZXFIGK.js → cache-service-26GCO3UU.js} +3 -3
  4. package/dist/{cache-service-CyLdpo77.d.ts → cache-service-pJ-nFcVj.d.ts} +44 -12
  5. package/dist/{chunk-XZL45ABR.js → chunk-2AJKEQMZ.js} +54 -1
  6. package/dist/{chunk-6PQ5MOWR.js → chunk-7SZSQS55.js} +571 -115
  7. package/dist/chunk-BQRURGGD.js +60 -0
  8. package/dist/chunk-IITRFWHY.js +196 -0
  9. package/dist/{chunk-LJ5QJB5O.js → chunk-UBWLPKTI.js} +127 -11
  10. package/dist/cli.cjs +767 -133
  11. package/dist/cli.js +24 -6
  12. package/dist/dashboard/index.d.ts +2 -2
  13. package/dist/drizzle/index.cjs +734 -132
  14. package/dist/drizzle/index.d.ts +2 -2
  15. package/dist/drizzle/index.js +1 -1
  16. package/dist/edge/index.cjs +163 -46
  17. package/dist/edge/index.d.ts +3 -3
  18. package/dist/edge/index.js +42 -14
  19. package/dist/hono/index.cjs +8093 -0
  20. package/dist/hono/index.d.ts +91 -0
  21. package/dist/hono/index.js +185 -0
  22. package/dist/{hono-DQRS1Xd7.d.ts → hono-DuNvciyq.d.ts} +6 -5
  23. package/dist/http/index.cjs +833 -170
  24. package/dist/http/index.d.ts +6 -30
  25. package/dist/http/index.js +9 -59
  26. package/dist/index.cjs +755 -130
  27. package/dist/index.d.ts +35 -6
  28. package/dist/index.js +16 -6
  29. package/dist/nestjs/index.cjs +725 -130
  30. package/dist/nestjs/index.d.ts +2 -2
  31. package/dist/nestjs/index.js +4 -4
  32. package/dist/next/index.cjs +725 -130
  33. package/dist/next/index.d.ts +2 -2
  34. package/dist/next/index.js +3 -3
  35. package/dist/prisma/index.d.ts +2 -2
  36. package/dist/serialize-worker.cjs +127 -9
  37. package/dist/serialize-worker.js +8 -4
  38. package/dist/{types-B6krw64X.d.ts → types-5HXqBfAf.d.ts} +74 -7
  39. package/dist/utils-CEsU_Z0s.d.ts +27 -0
  40. package/package.json +22 -9
  41. package/src/cache-service.ts +540 -68
  42. package/src/cli.ts +21 -4
  43. package/src/compression.ts +193 -15
  44. package/src/cross-region.ts +1 -1
  45. package/src/edge/cache.ts +38 -11
  46. package/src/edge/hono.ts +123 -42
  47. package/src/env.d.ts +13 -0
  48. package/src/hono/index.ts +316 -0
  49. package/src/http/index.ts +5 -0
  50. package/src/index.ts +9 -1
  51. package/src/ipc-telemetry.ts +29 -1
  52. package/src/serialize-worker.ts +6 -2
  53. package/src/types.ts +68 -5
  54. package/src/utils/tag-matcher.ts +90 -0
  55. package/dist/chunk-ZTSWCFYO.js +0 -135
  56. /package/dist/{chunk-QNU7B43J.js → chunk-VXFTFZ5N.js} +0 -0
@@ -49,6 +49,7 @@ import {
49
49
  WTinyLfuStats,
50
50
  CachePresetType,
51
51
  CacheHealthStatus,
52
+ InvalidateTagOptions,
52
53
  } from './types';
53
54
  import { CacheEncryption, EnvelopeEncryption, type EncryptionMode } from './encryption';
54
55
  import { SmartMemoryCache } from './smart-memory-cache';
@@ -60,10 +61,18 @@ import { IpcTelemetryServer } from './ipc-telemetry.js';
60
61
  import {
61
62
  compressBuffer,
62
63
  decompressBuffer,
64
+ initZstd,
63
65
  PREFIX_COMPRESSED,
64
66
  PREFIX_ENC_COMPRESSED,
65
67
  type CompressionAlgorithm,
68
+ type CustomCompressor,
66
69
  } from './compression';
70
+ import {
71
+ isWildcardTag,
72
+ matchesTagPattern,
73
+ isChildTag,
74
+ expandHierarchicalTags,
75
+ } from './utils/tag-matcher.js';
67
76
 
68
77
  // ─── Lua scripts ─────────────────────────────────────────────────────────────
69
78
 
@@ -469,6 +478,8 @@ export class CacheService {
469
478
  redisHost: string; redisPort: number; redisTls: boolean; disableRedis: boolean;
470
479
  encryptionKey: string | undefined; encryptionMode: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor' | undefined; snapshotPath: string; snapshotMaxAgeMs: number;
471
480
  invalidationBackplane: boolean;
481
+ awaitInvalidationBackplane: boolean;
482
+ lockFailClosed: boolean;
472
483
  oomProtection: boolean; oomHeapThreshold: number;
473
484
  oomCheckIntervalMs: number; oomEvictPercent: number;
474
485
  onMetrics: ((m: CacheMetrics) => void) | undefined;
@@ -499,11 +510,14 @@ export class CacheService {
499
510
  redisProtocol: 2 | 3 | undefined;
500
511
  useShardedPubSub: boolean;
501
512
  compression: CompressionAlgorithm;
513
+ customCompressor?: CustomCompressor;
502
514
  compressionThresholdBytes: number;
503
515
  strictSingleton: boolean;
504
516
  failClosed: boolean;
505
517
  tagStrategy: 'set' | 'generational';
506
518
  tagVersionTtlMs: number;
519
+ hierarchicalTags: boolean;
520
+ tagHierarchyDelimiter: string;
507
521
  cloneStrategy: 'none' | 'structuredClone';
508
522
  backplaneMode: 'pubsub' | 'stream';
509
523
  backplaneStreamMaxLen: number;
@@ -534,6 +548,7 @@ export class CacheService {
534
548
  };
535
549
  /** Pre-computed once — opts.namespace never changes after construction. */
536
550
  private readonly _namespace: string;
551
+ private readonly prefixLen: number;
537
552
  /** Pre-computed once — disableRedis and redisHost never change after construction. */
538
553
  private readonly _redisDisabled: boolean;
539
554
  private readonly watchdog: TierLatencyWatchdog;
@@ -573,6 +588,57 @@ export class CacheService {
573
588
  private streamClient: AnyRedisClient | null = null;
574
589
  private _lastStreamId = '$';
575
590
  private _destroyed = false;
591
+ private readonly _pendingDiskDeletes = new Set<string>();
592
+ private _globalEpoch = 0;
593
+ private readonly _keyMutationEpochs = new Map<string, number>();
594
+ /**
595
+ * Pattern tombstones for disk tier.
596
+ * Files in the disk tier are keyed by SHA-256 of namespacedKey.
597
+ * Wildcard pattern deletes cannot scan the filesystem synchronously, so we maintain
598
+ * pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
599
+ */
600
+ private readonly _patternTombstones: Array<{ prefix: string; createdAt: number }> = [];
601
+
602
+ private _addPatternTombstone(prefix: string): void {
603
+ const now = Date.now();
604
+ while (this._patternTombstones.length > 0 && (now - this._patternTombstones[0].createdAt > 3_600_000)) {
605
+ this._patternTombstones.shift();
606
+ }
607
+ if (this._patternTombstones.length >= 2_000) {
608
+ this._patternTombstones.shift();
609
+ }
610
+ this._patternTombstones.push({ prefix, createdAt: now });
611
+ }
612
+
613
+ private _isTombstonedByPattern(namespacedKey: string): boolean {
614
+ if (this._patternTombstones.length === 0) return false;
615
+ for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
616
+ if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
617
+ return true;
618
+ }
619
+ }
620
+ return false;
621
+ }
622
+
623
+ private _assertActive(operation: string): void {
624
+ if (this._destroyed) {
625
+ throw new Error(`TriCacheError: Cannot perform '${operation}' on a destroyed CacheService instance (namespace: '${this._namespace || "(default)"}').`);
626
+ }
627
+ }
628
+
629
+ private _bumpKeyMutation(namespacedKey: string): number {
630
+ const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
631
+ this._keyMutationEpochs.set(namespacedKey, next);
632
+ if (this._keyMutationEpochs.size > 50_000) {
633
+ const oldest = this._keyMutationEpochs.keys().next().value;
634
+ if (oldest !== undefined) this._keyMutationEpochs.delete(oldest);
635
+ }
636
+ return next;
637
+ }
638
+
639
+ private _getKeyMutationEpoch(namespacedKey: string): number {
640
+ return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
641
+ }
576
642
  private _ipcServer?: IpcTelemetryServer;
577
643
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
578
644
  private _subDisconnectedAt: number | null = null;
@@ -679,6 +745,8 @@ export class CacheService {
679
745
  os.tmpdir(), ns ? `tricache-snapshot-${ns}.msgpack` : 'tricache-snapshot.msgpack'),
680
746
  snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
681
747
  invalidationBackplane: options.invalidationBackplane ?? true,
748
+ awaitInvalidationBackplane: options.awaitInvalidationBackplane ?? false,
749
+ lockFailClosed: options.lockFailClosed ?? false,
682
750
  oomProtection: options.oomProtection ?? true,
683
751
  oomHeapThreshold: options.oomHeapThreshold ?? 0.85,
684
752
  oomCheckIntervalMs: options.oomCheckIntervalMs ?? 10_000,
@@ -710,12 +778,15 @@ export class CacheService {
710
778
  redisSentinel: options.redisSentinel,
711
779
  redisProtocol: options.redisProtocol,
712
780
  useShardedPubSub: options.useShardedPubSub ?? false,
713
- compression: options.compression ?? 'none',
781
+ compression: options.compression ?? 'zstd',
782
+ customCompressor: options.customCompressor,
714
783
  compressionThresholdBytes: options.compressionThresholdBytes ?? 1024,
715
784
  strictSingleton: options.strictSingleton ?? false,
716
785
  failClosed: options.failClosed ?? false,
717
786
  tagStrategy: options.tagStrategy ?? 'set',
718
787
  tagVersionTtlMs: options.tagVersionTtlMs ?? 5_000,
788
+ hierarchicalTags: options.hierarchicalTags ?? false,
789
+ tagHierarchyDelimiter: options.tagHierarchyDelimiter ?? ':',
719
790
  cloneStrategy: options.cloneStrategy ?? 'none',
720
791
  backplaneMode: options.backplaneMode ?? 'pubsub',
721
792
  backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 10_000,
@@ -799,6 +870,7 @@ export class CacheService {
799
870
  });
800
871
 
801
872
  this._namespace = ns;
873
+ this.prefixLen = ns ? ns.length + 1 : 0;
802
874
  // disableRedis takes unconditional precedence; otherwise, L2 is active when
803
875
  // at least one of host / cluster nodes / sentinel is configured.
804
876
  this._redisDisabled = this.opts.disableRedis
@@ -936,6 +1008,9 @@ export class CacheService {
936
1008
 
937
1009
  // Auto-warm from remote snapshot or L2 if configured; ready() waits for completion.
938
1010
  const startupPromises: Promise<void>[] = [];
1011
+ if (this.opts.compression === 'zstd') {
1012
+ startupPromises.push(initZstd().then(() => undefined));
1013
+ }
939
1014
  if (this.opts.remoteSnapshot) {
940
1015
  startupPromises.push(this.loadRemoteSnapshot().then(() => undefined));
941
1016
  }
@@ -1082,7 +1157,7 @@ export class CacheService {
1082
1157
  'redisHost', 'redisPort', 'redisTls', 'disableRedis',
1083
1158
  'redisClusterNodes', 'redisSentinel', 'encryptionKey', 'encryptionMode',
1084
1159
  'l1MaxBytes', 'l1MaxEntries', 'namespace', 'frozen', 'adaptiveTtl',
1085
- 'l2WriteMode', 'instanceName', 'invalidationBackplane',
1160
+ 'l2WriteMode', 'instanceName', 'invalidationBackplane', 'awaitInvalidationBackplane', 'lockFailClosed',
1086
1161
  ];
1087
1162
 
1088
1163
  /** Returns the names of options that differ between `a` and the live `b`. */
@@ -1129,6 +1204,8 @@ export class CacheService {
1129
1204
  frozen: o.frozen,
1130
1205
  adaptiveTtl: o.adaptiveTtl,
1131
1206
  invalidationBackplane: o.invalidationBackplane,
1207
+ awaitInvalidationBackplane: o.awaitInvalidationBackplane,
1208
+ lockFailClosed: o.lockFailClosed,
1132
1209
  strictSingleton: o.strictSingleton,
1133
1210
  remoteSnapshot: o.remoteSnapshot,
1134
1211
  crossRegion: o.crossRegion,
@@ -1447,14 +1524,80 @@ export class CacheService {
1447
1524
  private _applyInvalidationEvent(op: string, key: string, tagVersion?: number): void {
1448
1525
  if (op === 'del') {
1449
1526
  this.l1.delete(key);
1450
- setImmediate(() => { if (!this._diskDisabled) this.disk.delete(key); });
1527
+ this._bumpKeyMutation(key);
1528
+ this.inflight.delete(key);
1529
+ this._pendingDiskDeletes.add(key);
1530
+ setImmediate(() => {
1531
+ try {
1532
+ if (!this._diskDisabled) this.disk.delete(key);
1533
+ } finally {
1534
+ this._pendingDiskDeletes.delete(key);
1535
+ }
1536
+ });
1451
1537
  this._cascadeDependencies(key);
1452
1538
  } else if (op === 'del-glob') {
1453
1539
  this.l1.deletePattern(key);
1540
+ const pfx = key.endsWith('*') ? key.slice(0, -1) : key;
1541
+ for (const liveKey of this.l1.liveKeys()) {
1542
+ if (liveKey.startsWith(pfx)) {
1543
+ this._bumpKeyMutation(liveKey);
1544
+ }
1545
+ }
1546
+ for (const inflightKey of Array.from(this.inflight.keys())) {
1547
+ if (inflightKey.startsWith(pfx)) {
1548
+ this._bumpKeyMutation(inflightKey);
1549
+ this.inflight.delete(inflightKey);
1550
+ }
1551
+ }
1552
+ this._addPatternTombstone(pfx);
1454
1553
  } else if (op === 'tag_incr') {
1455
1554
  const tag = key;
1456
1555
  const ver = typeof tagVersion === 'number' ? tagVersion : ((this.tagVersions.get(tag)?.version ?? 0) + 1);
1457
- this._setLocalTagVersion(tag, ver, Date.now());
1556
+ this._setLocalTagVersion(tag, ver, performance.now());
1557
+ } else if (op === 'tag_pattern_incr') {
1558
+ const pattern = key;
1559
+ const now = performance.now();
1560
+ for (const [tag, info] of this.tagVersions) {
1561
+ if (matchesTagPattern(pattern, tag)) {
1562
+ this._setLocalTagVersion(tag, info.version + 1, now);
1563
+ }
1564
+ }
1565
+ this.l1.scan((k, entry) => {
1566
+ if (entry.tagVersions) {
1567
+ for (const tag of Object.keys(entry.tagVersions)) {
1568
+ if (matchesTagPattern(pattern, tag)) {
1569
+ this.l1.delete(k);
1570
+ this._bumpKeyMutation(k);
1571
+ break;
1572
+ }
1573
+ }
1574
+ }
1575
+ }, 0);
1576
+ } else if (op === 'tag_pattern_del') {
1577
+ const pattern = key;
1578
+ const matchedTagKeys: string[] = [];
1579
+ const prefix = this.nk('_tag_:');
1580
+ for (const [tagKey, members] of this.tagIndex) {
1581
+ const tag = tagKey.startsWith(prefix) ? tagKey.slice(prefix.length) : tagKey;
1582
+ if (matchesTagPattern(pattern, tag)) {
1583
+ matchedTagKeys.push(tagKey);
1584
+ for (const k of members) {
1585
+ this.l1.delete(k);
1586
+ this._bumpKeyMutation(k);
1587
+ this._pendingDiskDeletes.add(k);
1588
+ setImmediate(() => {
1589
+ try {
1590
+ if (!this._diskDisabled) this.disk.delete(k);
1591
+ } finally {
1592
+ this._pendingDiskDeletes.delete(k);
1593
+ }
1594
+ });
1595
+ }
1596
+ }
1597
+ }
1598
+ for (const tagKey of matchedTagKeys) {
1599
+ this.tagIndex.delete(tagKey);
1600
+ }
1458
1601
  }
1459
1602
  this.logger.debug('Backplane: invalidation applied', { op, key: key.slice(0, 60) });
1460
1603
  }
@@ -1469,7 +1612,7 @@ export class CacheService {
1469
1612
  Array.isArray(msg) ||
1470
1613
  typeof msg.src !== 'string' ||
1471
1614
  typeof msg.key !== 'string' ||
1472
- (msg.op !== 'del' && msg.op !== 'del-glob' && msg.op !== 'tag_incr')
1615
+ (msg.op !== 'del' && msg.op !== 'del-glob' && msg.op !== 'tag_incr' && msg.op !== 'tag_pattern_incr' && msg.op !== 'tag_pattern_del')
1473
1616
  ) {
1474
1617
  this.logger.warn('Backplane: rejected invalid pubsub message format', {
1475
1618
  raw: typeof message === 'string' ? message.slice(0, 100).replace(/[\r\n\t]/g, ' ') : String(message),
@@ -1488,7 +1631,7 @@ export class CacheService {
1488
1631
  }
1489
1632
 
1490
1633
  private async publishInvalidation(
1491
- op: 'del' | 'del-glob' | 'tag_incr',
1634
+ op: 'del' | 'del-glob' | 'tag_incr' | 'tag_pattern_incr' | 'tag_pattern_del',
1492
1635
  key: string,
1493
1636
  tagVersion?: number,
1494
1637
  isCrossRegionRelay = false,
@@ -1497,7 +1640,11 @@ export class CacheService {
1497
1640
  if (!isCrossRegionRelay && this.opts.crossRegion) {
1498
1641
  const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
1499
1642
  if (shouldBroadcast) {
1500
- void this._broadcastCrossRegion(op, key, tagVersion);
1643
+ if (this.opts.awaitInvalidationBackplane) {
1644
+ await this._broadcastCrossRegion(op, key, tagVersion);
1645
+ } else {
1646
+ void this._broadcastCrossRegion(op, key, tagVersion);
1647
+ }
1501
1648
  }
1502
1649
  }
1503
1650
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
@@ -1535,7 +1682,12 @@ export class CacheService {
1535
1682
  );
1536
1683
  }
1537
1684
  this.counters.invSent++;
1538
- } catch { /* non-critical — never block the caller */ }
1685
+ } catch (err) {
1686
+ this.logger.warn('Backplane invalidation publish failed', { op, key, error: (err as Error).message });
1687
+ if (this.opts.awaitInvalidationBackplane) {
1688
+ throw err;
1689
+ }
1690
+ }
1539
1691
  }
1540
1692
 
1541
1693
  private _markCrossRegionEventSeen(id: string): void {
@@ -1552,7 +1704,7 @@ export class CacheService {
1552
1704
  }
1553
1705
 
1554
1706
  private async _broadcastCrossRegion(
1555
- op: 'del' | 'del-glob' | 'tag_incr',
1707
+ op: 'del' | 'del-glob' | 'tag_incr' | 'tag_pattern_incr' | 'tag_pattern_del',
1556
1708
  key: string,
1557
1709
  tagVersion?: number,
1558
1710
  ): Promise<void> {
@@ -1679,12 +1831,12 @@ export class CacheService {
1679
1831
  * Offloads to worker thread if pool is active and payload exceeds threshold.
1680
1832
  */
1681
1833
  private async _serializeAndEncrypt(serialized: string): Promise<string> {
1682
- const isCompressed = this.opts.compression && this.opts.compression !== 'none' && serialized.length > this.opts.compressionThresholdBytes;
1683
- if (this._workerPool && (this.enc.isEnabled || isCompressed) && serialized.length > this.opts.workerThresholdBytes) {
1834
+ const isCompressed = (this.opts.customCompressor || (this.opts.compression && this.opts.compression !== 'none')) && serialized.length > this.opts.compressionThresholdBytes;
1835
+ if (this._workerPool && !this.opts.customCompressor && (this.enc.isEnabled || isCompressed) && serialized.length > this.opts.workerThresholdBytes) {
1684
1836
  return this._workerPool.encrypt(serialized);
1685
1837
  }
1686
1838
  if (isCompressed) {
1687
- const compressed = compressBuffer(Buffer.from(serialized, 'utf8'), this.opts.compression);
1839
+ const compressed = compressBuffer(Buffer.from(serialized, 'utf8'), this.opts.compression, this.opts.customCompressor);
1688
1840
  if (this.enc.isEnabled) {
1689
1841
  const encrypted = this.enc.encryptBuffer(compressed);
1690
1842
  return PREFIX_ENC_COMPRESSED + encrypted.toString('base64');
@@ -1700,16 +1852,16 @@ export class CacheService {
1700
1852
  */
1701
1853
  private async _decryptAndDeserialize<T>(raw: string): Promise<T> {
1702
1854
  let plain: string;
1703
- if (this._workerPool && raw.length > this.opts.workerThresholdBytes) {
1855
+ if (this._workerPool && !this.opts.customCompressor && raw.length > this.opts.workerThresholdBytes) {
1704
1856
  plain = await this._workerPool.decrypt(raw);
1705
1857
  } else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
1706
1858
  const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), 'base64');
1707
1859
  const decBuf = this.enc.decryptBuffer(encBuf);
1708
- const decompressed = decompressBuffer(decBuf, this.opts.compression !== 'none' ? this.opts.compression : 'brotli');
1860
+ const decompressed = decompressBuffer(decBuf, this.opts.compression !== 'none' ? this.opts.compression : 'brotli', this.opts.customCompressor);
1709
1861
  plain = decompressed.toString('utf8');
1710
1862
  } else if (raw.startsWith(PREFIX_COMPRESSED)) {
1711
1863
  const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), 'base64');
1712
- const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== 'none' ? this.opts.compression : 'brotli');
1864
+ const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== 'none' ? this.opts.compression : 'brotli', this.opts.customCompressor);
1713
1865
  plain = decompressed.toString('utf8');
1714
1866
  } else if (raw.startsWith('enc:v1:') || this.enc.isEnabled) {
1715
1867
  plain = this.enc.decrypt(raw);
@@ -1776,6 +1928,7 @@ export class CacheService {
1776
1928
  }
1777
1929
 
1778
1930
  private async getRedis(): Promise<AnyRedisClient> {
1931
+ this._assertActive('getRedis');
1779
1932
  if (!this.cb.isAllowed()) throw new Error('tricache: L2 circuit breaker is open');
1780
1933
  if (this.redis) return this.redis;
1781
1934
  if (this.redisConnecting) return this.redisConnecting;
@@ -2152,6 +2305,7 @@ export class CacheService {
2152
2305
  tags?: string[];
2153
2306
  } = {},
2154
2307
  ): Promise<T> {
2308
+ this._assertActive('get');
2155
2309
  const span = this._startSpan('tricache.get');
2156
2310
  if (this.opts.tracer) span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
2157
2311
  const k = this.nk(cacheKey); // namespaced key used for all storage
@@ -2167,7 +2321,9 @@ export class CacheService {
2167
2321
  const optRefreshAhead = opts.refreshAhead;
2168
2322
  const optXfetchBeta = opts.xfetchBeta;
2169
2323
  const optNotFoundTtl = opts.notFoundTtl;
2170
- const optTags = opts.tags;
2324
+ const optTags = opts.tags
2325
+ ? (this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags)
2326
+ : undefined;
2171
2327
 
2172
2328
  // L1: in-memory (fastest path)
2173
2329
  const l1Hit = this.l1.get(k);
@@ -2192,7 +2348,14 @@ export class CacheService {
2192
2348
  if (swrGraceMs > 0 && !this.revalidating.has(k)) {
2193
2349
  const priority = optPriority ?? inferPriority(cacheKey);
2194
2350
  this.revalidating.add(k);
2195
- void this._revalidate(k, fetchFn, ttlSeconds * 1_000, swrGraceMs, priority);
2351
+ void this._revalidate(
2352
+ k,
2353
+ fetchFn,
2354
+ ttlSeconds * 1_000,
2355
+ swrGraceMs,
2356
+ priority,
2357
+ l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map(t => [t, 0])) : undefined),
2358
+ );
2196
2359
  this.counters.swrRevalidations++;
2197
2360
  this.logger.debug('SWR: serving stale, revalidating', { cacheKey });
2198
2361
  } else {
@@ -2217,7 +2380,14 @@ export class CacheService {
2217
2380
  if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
2218
2381
  const priority = optPriority ?? inferPriority(cacheKey);
2219
2382
  this.revalidating.add(k);
2220
- void this._revalidate(k, fetchFn, entryTtl, optSwr * 1_000, priority);
2383
+ void this._revalidate(
2384
+ k,
2385
+ fetchFn,
2386
+ entryTtl,
2387
+ optSwr * 1_000,
2388
+ priority,
2389
+ l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map(t => [t, 0])) : undefined),
2390
+ );
2221
2391
  this.counters.swrRevalidations++;
2222
2392
  this.logger.debug(
2223
2393
  shouldXFetch ? 'XFetch: proactive background recompute' : 'Refresh-ahead: proactive background recompute',
@@ -2257,12 +2427,16 @@ export class CacheService {
2257
2427
  return existing as Promise<T>;
2258
2428
  }
2259
2429
 
2430
+ const mutationEpochAtStart = this._getKeyMutationEpoch(k);
2260
2431
  const executionPromise: Promise<T> = (async () => {
2261
2432
  try {
2262
2433
  // ── 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) {
2434
+ if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
2435
+ if (this._isTombstonedByPattern(k)) {
2436
+ try { this.disk.delete(k); } catch { /* ok */ }
2437
+ } else {
2438
+ const isDiskAllowed = this.watchdog.isDiskAllowed();
2439
+ if (isDiskAllowed) {
2266
2440
  const diskStart = performance.now();
2267
2441
  const diskHit = this.disk.load(k);
2268
2442
  const diskElapsed = performance.now() - diskStart;
@@ -2308,6 +2482,7 @@ export class CacheService {
2308
2482
  }
2309
2483
  }
2310
2484
  }
2485
+ }
2311
2486
 
2312
2487
  // ── Tier 2: Redis (distributed, production-only by default) ──
2313
2488
  if (!this._redisDisabled) {
@@ -2430,6 +2605,23 @@ export class CacheService {
2430
2605
  }
2431
2606
  }
2432
2607
 
2608
+ if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
2609
+ this.logger.debug('Aborting in-flight cache commit — key was mutated or deleted during fetch', { cacheKey });
2610
+ span.setAttribute('cache.aborted_mutation_race', true);
2611
+ const current = this.l1.get(k);
2612
+ if (current && !current.isStale && current.value !== undefined) {
2613
+ const freshVal = current.value as T;
2614
+ if (this.opts.frozen) deepFreeze(freshVal);
2615
+ return (this.opts.cloneStrategy === 'structuredClone' && freshVal != null && typeof freshVal === 'object')
2616
+ ? structuredClone(freshVal)
2617
+ : freshVal;
2618
+ }
2619
+ if (this.opts.frozen) deepFreeze(data);
2620
+ return (this.opts.cloneStrategy === 'structuredClone' && data != null && typeof data === 'object')
2621
+ ? structuredClone(data)
2622
+ : data;
2623
+ }
2624
+
2433
2625
  this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
2434
2626
 
2435
2627
  if (!this._redisDisabled) {
@@ -2565,25 +2757,47 @@ export class CacheService {
2565
2757
  ttlMs: number,
2566
2758
  swrGraceMs: number,
2567
2759
  priority: CachePriority,
2760
+ knownTagVersions?: Record<string, number>,
2568
2761
  ): Promise<void> {
2762
+ const startEpoch = this._getKeyMutationEpoch(cacheKey);
2569
2763
  try {
2570
2764
  const fetchStart = Date.now();
2571
2765
  const data = await fetchFn();
2572
2766
  const delta = Date.now() - fetchStart;
2573
2767
  const staleAt = Date.now() + ttlMs;
2574
2768
 
2769
+ // Invalidation fence: if the key was deleted or mutated while fetchFn was in-flight, abort commit!
2770
+ if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
2771
+ this.logger.debug('SWR: aborting revalidation commit — key was mutated or deleted during fetch', { cacheKey });
2772
+ return;
2773
+ }
2774
+
2575
2775
  // Keep the latency tracker current during SWR background revalidations too
2576
2776
  if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
2577
2777
 
2578
2778
  let activeTagVersions: Record<string, number> | undefined;
2579
2779
  const l1Existing = this.l1.get(cacheKey);
2580
- if (this.opts.tagStrategy === 'generational' && l1Existing?.tagVersions) {
2581
- const tags = Object.keys(l1Existing.tagVersions);
2780
+ const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
2781
+ if (this.opts.tagStrategy === 'generational' && tagVersionsSource) {
2782
+ const tags = Object.keys(tagVersionsSource);
2582
2783
  const vers = await Promise.all(tags.map(tag => this._getTagVersion(tag)));
2583
2784
  activeTagVersions = {};
2584
2785
  for (let i = 0; i < tags.length; i++) {
2585
2786
  activeTagVersions[tags[i]] = vers[i];
2586
2787
  }
2788
+ if (knownTagVersions) {
2789
+ for (const t of tags) {
2790
+ if (knownTagVersions[t] !== undefined && activeTagVersions[t] !== knownTagVersions[t]) {
2791
+ this.logger.debug('SWR: aborting revalidation commit — tag version bumped during revalidation', { cacheKey, tag: t });
2792
+ return;
2793
+ }
2794
+ }
2795
+ }
2796
+ }
2797
+
2798
+ if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
2799
+ this.logger.debug('SWR: aborting revalidation commit — key was mutated or deleted during tag resolution', { cacheKey });
2800
+ return;
2587
2801
  }
2588
2802
 
2589
2803
  this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
@@ -2629,6 +2843,7 @@ export class CacheService {
2629
2843
 
2630
2844
  /** Explicitly write a value into L1 (+ L2 in production). */
2631
2845
  async set<T>(cacheKey: string, data: T, ttlSeconds = 300, priority?: CachePriority, opts?: { tags?: string[]; dependsOn?: string[] }): Promise<void> {
2846
+ this._assertActive('set');
2632
2847
  const span = this._startSpan('tricache.set');
2633
2848
  if (this.opts.tracer) {
2634
2849
  span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
@@ -2642,18 +2857,25 @@ export class CacheService {
2642
2857
  const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1_000);
2643
2858
  const p = priority ?? inferPriority(cacheKey);
2644
2859
  const k = this.nk(cacheKey);
2860
+ this._bumpKeyMutation(k);
2861
+ this.inflight.delete(k);
2862
+ this._pendingDiskDeletes.delete(k);
2645
2863
  this.counters.sets++;
2646
2864
 
2647
2865
  let activeTagVersions: Record<string, number> | undefined;
2648
- if (opts?.tags?.length) {
2866
+ const tagsToRegister = opts?.tags?.length
2867
+ ? (this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags)
2868
+ : undefined;
2869
+
2870
+ if (tagsToRegister?.length) {
2649
2871
  if (this.opts.tagStrategy === 'generational') {
2650
- const vers = await Promise.all(opts.tags.map(tag => this._getTagVersion(tag)));
2872
+ const vers = await Promise.all(tagsToRegister.map(tag => this._getTagVersion(tag)));
2651
2873
  activeTagVersions = {};
2652
- for (let i = 0; i < opts.tags.length; i++) {
2653
- activeTagVersions[opts.tags[i]] = vers[i];
2874
+ for (let i = 0; i < tagsToRegister.length; i++) {
2875
+ activeTagVersions[tagsToRegister[i]] = vers[i];
2654
2876
  }
2655
2877
  } else {
2656
- await this._registerTags(k, opts.tags, ttlSeconds);
2878
+ await this._registerTags(k, tagsToRegister, ttlSeconds);
2657
2879
  }
2658
2880
  }
2659
2881
 
@@ -2700,7 +2922,11 @@ export class CacheService {
2700
2922
  }
2701
2923
  }
2702
2924
 
2703
- void this.publishInvalidation('del', k);
2925
+ if (this.opts.awaitInvalidationBackplane) {
2926
+ await this.publishInvalidation('del', k);
2927
+ } else {
2928
+ void this.publishInvalidation('del', k);
2929
+ }
2704
2930
  } catch (err) {
2705
2931
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
2706
2932
  span.recordException?.(err);
@@ -2744,6 +2970,7 @@ export class CacheService {
2744
2970
  * await cache.delete('user:abc:*'); // all keys for user abc
2745
2971
  */
2746
2972
  async delete(cacheKey: string): Promise<void> {
2973
+ this._assertActive('delete');
2747
2974
  const span = this._startSpan('tricache.delete');
2748
2975
  if (this.opts.tracer) span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
2749
2976
  try {
@@ -2752,16 +2979,32 @@ export class CacheService {
2752
2979
  this.counters.deletes++;
2753
2980
 
2754
2981
  if (isPattern) {
2982
+ const pfx = k.endsWith('*') ? k.slice(0, -1) : k;
2983
+ for (const liveKey of this.l1.liveKeys()) {
2984
+ if (liveKey.startsWith(pfx)) {
2985
+ this._bumpKeyMutation(liveKey);
2986
+ }
2987
+ }
2988
+ for (const inflightKey of Array.from(this.inflight.keys())) {
2989
+ if (inflightKey.startsWith(pfx)) {
2990
+ this._bumpKeyMutation(inflightKey);
2991
+ this.inflight.delete(inflightKey);
2992
+ }
2993
+ }
2994
+ this._addPatternTombstone(pfx);
2755
2995
  this.l1.deletePattern(k);
2756
2996
  } else {
2997
+ this._bumpKeyMutation(k);
2998
+ this.inflight.delete(k);
2757
2999
  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); });
3000
+ this._pendingDiskDeletes.add(k);
3001
+ setImmediate(() => {
3002
+ try {
3003
+ if (!this._diskDisabled) this.disk.delete(k);
3004
+ } finally {
3005
+ this._pendingDiskDeletes.delete(k);
3006
+ }
3007
+ });
2765
3008
  // Cascade: invalidate any key that declared it depends on this exact key's pattern
2766
3009
  this._cascadeDependencies(k);
2767
3010
  // Clean up: remove k from all dependency registrations (it is gone)
@@ -2788,7 +3031,11 @@ export class CacheService {
2788
3031
  }
2789
3032
  }
2790
3033
 
2791
- void this.publishInvalidation(isPattern ? 'del-glob' : 'del', k, undefined, false, true);
3034
+ if (this.opts.awaitInvalidationBackplane) {
3035
+ await this.publishInvalidation(isPattern ? 'del-glob' : 'del', k, undefined, false, true);
3036
+ } else {
3037
+ void this.publishInvalidation(isPattern ? 'del-glob' : 'del', k, undefined, false, true);
3038
+ }
2792
3039
  } catch (err) {
2793
3040
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
2794
3041
  span.recordException?.(err);
@@ -2817,6 +3064,7 @@ export class CacheService {
2817
3064
  * fleet-wide.
2818
3065
  */
2819
3066
  async increment(cacheKey: string, ttlSeconds?: number): Promise<number> {
3067
+ this._assertActive('increment');
2820
3068
  const k = this.nk(cacheKey);
2821
3069
 
2822
3070
  if (this._redisDisabled) {
@@ -2862,6 +3110,7 @@ export class CacheService {
2862
3110
  * await cache.clear('user:abc'); // flush all keys for one user
2863
3111
  */
2864
3112
  async clear(prefix?: string): Promise<void> {
3113
+ this._assertActive('clear');
2865
3114
  const span = this._startSpan('tricache.clear');
2866
3115
  if (this.opts.tracer) span.setAttribute('cache.prefix', prefix || '*');
2867
3116
  try {
@@ -2871,15 +3120,31 @@ export class CacheService {
2871
3120
  : undefined;
2872
3121
 
2873
3122
  if (k) {
3123
+ const pfx = k.endsWith('*') ? k.slice(0, -1) : k;
3124
+ for (const liveKey of this.l1.liveKeys()) {
3125
+ if (liveKey.startsWith(pfx)) {
3126
+ this._bumpKeyMutation(liveKey);
3127
+ }
3128
+ }
3129
+ for (const inflightKey of Array.from(this.inflight.keys())) {
3130
+ if (inflightKey.startsWith(pfx)) {
3131
+ this._bumpKeyMutation(inflightKey);
3132
+ this.inflight.delete(inflightKey);
3133
+ }
3134
+ }
3135
+ this._addPatternTombstone(pfx);
2874
3136
  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
3137
  } else {
3138
+ this._globalEpoch++;
3139
+ this.inflight.clear();
3140
+ this._patternTombstones.length = 0;
2878
3141
  this.l1.clear();
2879
3142
  if (!this._diskDisabled) this.disk.clear();
2880
3143
  this._l1Counters.clear();
2881
3144
  this.tagIndex.clear();
2882
3145
  this.tagVersions.clear();
3146
+ this._pendingDiskDeletes.clear();
3147
+ this._keyMutationEpochs.clear();
2883
3148
  }
2884
3149
 
2885
3150
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
@@ -2893,9 +3158,15 @@ export class CacheService {
2893
3158
  }
2894
3159
  }
2895
3160
 
2896
- void this.publishInvalidation('del-glob',
2897
- k ?? (this._namespace ? `${this._namespace}:*` : '*'),
2898
- undefined, false, true);
3161
+ if (this.opts.awaitInvalidationBackplane) {
3162
+ await this.publishInvalidation('del-glob',
3163
+ k ?? (this._namespace ? `${this._namespace}:*` : '*'),
3164
+ undefined, false, true);
3165
+ } else {
3166
+ void this.publishInvalidation('del-glob',
3167
+ k ?? (this._namespace ? `${this._namespace}:*` : '*'),
3168
+ undefined, false, true);
3169
+ }
2899
3170
  } catch (err) {
2900
3171
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
2901
3172
  span.recordException?.(err);
@@ -2911,6 +3182,7 @@ export class CacheService {
2911
3182
  * Returns the number of entries evicted.
2912
3183
  */
2913
3184
  rebalance(): number {
3185
+ this._assertActive('rebalance');
2914
3186
  return this.l1.rebalance();
2915
3187
  }
2916
3188
 
@@ -2920,6 +3192,7 @@ export class CacheService {
2920
3192
  * Only reflects L1 state — does not query Redis or disk.
2921
3193
  */
2922
3194
  ttl(cacheKey: string): number | null {
3195
+ this._assertActive('ttl');
2923
3196
  return this.l1.ttl(this.nk(cacheKey));
2924
3197
  }
2925
3198
 
@@ -2928,6 +3201,7 @@ export class CacheService {
2928
3201
  * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
2929
3202
  */
2930
3203
  has(cacheKey: string): boolean {
3204
+ this._assertActive('has');
2931
3205
  return this.l1.has(this.nk(cacheKey));
2932
3206
  }
2933
3207
 
@@ -2940,6 +3214,7 @@ export class CacheService {
2940
3214
  * for (const key of cache.keys()) console.log(key);
2941
3215
  */
2942
3216
  *keys(): Generator<string> {
3217
+ this._assertActive('keys');
2943
3218
  const prefix = this._namespace ? this._namespace + ':' : '';
2944
3219
  for (const key of this.l1.liveKeys()) {
2945
3220
  if (prefix && !key.startsWith(prefix)) continue;
@@ -2955,6 +3230,7 @@ export class CacheService {
2955
3230
  * for (const val of cache.values<User>()) console.log(val.id);
2956
3231
  */
2957
3232
  *values<T = unknown>(): Generator<T> {
3233
+ this._assertActive('values');
2958
3234
  const prefix = this._namespace ? this._namespace + ':' : '';
2959
3235
  if (!prefix) {
2960
3236
  yield* this.l1.liveValues() as Generator<T>;
@@ -2974,6 +3250,7 @@ export class CacheService {
2974
3250
  * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
2975
3251
  */
2976
3252
  *entries<T = unknown>(): Generator<[string, T]> {
3253
+ this._assertActive('entries');
2977
3254
  const prefix = this._namespace ? this._namespace + ':' : '';
2978
3255
  for (const [key, entry] of this.l1.liveEntries()) {
2979
3256
  if (prefix && !key.startsWith(prefix)) continue;
@@ -3002,6 +3279,7 @@ export class CacheService {
3002
3279
  * `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
3003
3280
  */
3004
3281
  scan<T = unknown>(fn: (rawKey: string, value: T, offset: number) => void): void {
3282
+ this._assertActive('scan');
3005
3283
  const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
3006
3284
  this.l1.scan((key, entry, pfx) => {
3007
3285
  const value = (entry.value !== undefined ? entry.value : entry.data) as T;
@@ -3016,6 +3294,7 @@ export class CacheService {
3016
3294
  * @param newTtlSeconds - The new TTL from now, in seconds.
3017
3295
  */
3018
3296
  async touch(cacheKey: string, newTtlSeconds: number): Promise<boolean> {
3297
+ this._assertActive('touch');
3019
3298
  const k = this.nk(cacheKey);
3020
3299
  const hit = this.l1.touch(k, newTtlSeconds * 1_000);
3021
3300
  if (hit && !this._redisDisabled) {
@@ -3036,6 +3315,7 @@ export class CacheService {
3036
3315
  * if (fresh !== null) return fresh; // serve from L1, no network hop
3037
3316
  */
3038
3317
  getIfFresh<T = unknown>(cacheKey: string): T | null {
3318
+ this._assertActive('getIfFresh');
3039
3319
  const k = this.nk(cacheKey);
3040
3320
  const entry = this.l1.getEntry(k);
3041
3321
  if (!entry) return null;
@@ -3054,6 +3334,7 @@ export class CacheService {
3054
3334
  * const val = await cache.peek<User>('user:123');
3055
3335
  */
3056
3336
  async peek<T = unknown>(cacheKey: string): Promise<T | null> {
3337
+ this._assertActive('peek');
3057
3338
  const k = this.nk(cacheKey);
3058
3339
 
3059
3340
  // 1. L1 RAM
@@ -3069,7 +3350,10 @@ export class CacheService {
3069
3350
  }
3070
3351
 
3071
3352
  // 2. L1.5 Disk
3072
- if (!this._diskDisabled && this.watchdog.isDiskAllowed()) {
3353
+ if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
3354
+ if (this._isTombstonedByPattern(k)) {
3355
+ try { this.disk.delete(k); } catch { /* ok */ }
3356
+ } else if (this.watchdog.isDiskAllowed()) {
3073
3357
  const diskStart = performance.now();
3074
3358
  const diskHit = this.disk.load(k);
3075
3359
  const diskElapsed = performance.now() - diskStart;
@@ -3095,6 +3379,7 @@ export class CacheService {
3095
3379
  }
3096
3380
  }
3097
3381
  }
3382
+ }
3098
3383
 
3099
3384
  // 3. L2 Redis
3100
3385
  if (!this._redisDisabled && !this.cb.isOpen) {
@@ -3135,10 +3420,11 @@ export class CacheService {
3135
3420
  */
3136
3421
  async mget<T>(
3137
3422
  keys: string[],
3138
- fetchFn: (missKeys: string[]) => Promise<Record<string, T>>,
3423
+ fetchFn?: (missKeys: string[]) => Promise<Record<string, T> | Map<string, T>>,
3139
3424
  ttl: number | ((key: string) => number) = 300,
3140
3425
  priority?: CachePriority,
3141
3426
  ): Promise<(T | undefined)[]> {
3427
+ this._assertActive('mget');
3142
3428
  const span = this._startSpan('tricache.mget');
3143
3429
  if (this.opts.tracer) {
3144
3430
  span.setAttribute('cache.batch.size', keys.length);
@@ -3214,8 +3500,13 @@ export class CacheService {
3214
3500
  // ── Tier 1.5: disk spill (evicted L1 entries) ──
3215
3501
  if (!this._diskDisabled && missKeys.length > 0) {
3216
3502
  for (let j = missKeys.length - 1; j >= 0; j--) {
3217
- if (!this.watchdog.isDiskAllowed()) continue;
3218
3503
  const k = this.nk(missKeys[j]);
3504
+ if (this._pendingDiskDeletes.has(k)) continue;
3505
+ if (this._isTombstonedByPattern(k)) {
3506
+ try { this.disk.delete(k); } catch { /* ok */ }
3507
+ continue;
3508
+ }
3509
+ if (!this.watchdog.isDiskAllowed()) continue;
3219
3510
  const diskStart = performance.now();
3220
3511
  const diskHit = this.disk.load(k);
3221
3512
  const diskElapsed = performance.now() - diskStart;
@@ -3240,16 +3531,24 @@ export class CacheService {
3240
3531
  }
3241
3532
 
3242
3533
  // ── Tier 3: fetchFn for whatever still missed ──
3243
- if (missKeys.length > 0) {
3534
+ if (missKeys.length > 0 && fetchFn) {
3244
3535
  this.counters.fetches++;
3245
3536
  const fetched = await fetchFn(missKeys);
3537
+ const isMap = fetched instanceof Map;
3246
3538
  const setPromises: Promise<void>[] = [];
3247
3539
  for (let j = 0; j < missKeys.length; j++) {
3248
- const v = fetched[missKeys[j]];
3540
+ const k = missKeys[j];
3541
+ const v = isMap ? (fetched as Map<string, T>).get(k) : (fetched as Record<string, T>)[k];
3249
3542
  result[missIndexes[j]] = v;
3250
- if (v !== undefined) {
3251
- const resolvedTtl = typeof ttl === 'function' ? ttl(missKeys[j]) : ttl;
3252
- setPromises.push(this.set(missKeys[j], v, resolvedTtl, priority));
3543
+ if (v !== undefined && v !== null) {
3544
+ const resolvedTtl = typeof ttl === 'function' ? ttl(k) : ttl;
3545
+ setPromises.push(this.set(k, v, resolvedTtl, priority));
3546
+ } else if (v == null && this.opts.notFoundTtl > 0) {
3547
+ // Negative caching: cache null/missing records with notFoundTtl to protect origin DB
3548
+ setPromises.push(this.set(k, null as unknown as T, this.opts.notFoundTtl, priority));
3549
+ } else if (v === null) {
3550
+ const resolvedTtl = typeof ttl === 'function' ? ttl(k) : ttl;
3551
+ setPromises.push(this.set(k, null as unknown as T, resolvedTtl, priority));
3253
3552
  }
3254
3553
  }
3255
3554
  if (setPromises.length > 0) {
@@ -3303,6 +3602,7 @@ export class CacheService {
3303
3602
  async mset<T = unknown>(
3304
3603
  entries: Record<string, { value: T; ttl?: number; priority?: CachePriority; tags?: string[]; dependsOn?: string[] }>,
3305
3604
  ): Promise<void> {
3605
+ this._assertActive('mset');
3306
3606
  const span = this._startSpan('tricache.mset');
3307
3607
  const keys = Object.keys(entries);
3308
3608
  if (this.opts.tracer) {
@@ -3331,6 +3631,7 @@ export class CacheService {
3331
3631
  * await cache.mdel(['user:1', 'user:2', 'user:3']);
3332
3632
  */
3333
3633
  async mdel(keys: string[]): Promise<void> {
3634
+ this._assertActive('mdel');
3334
3635
  const span = this._startSpan('tricache.mdel');
3335
3636
  if (this.opts.tracer) {
3336
3637
  span.setAttribute('cache.batch.size', keys.length);
@@ -3359,6 +3660,7 @@ export class CacheService {
3359
3660
  * console.log(`Warmed ${loaded} keys from Redis`);
3360
3661
  */
3361
3662
  async warmFromL2(pattern: string, opts?: { priority?: CachePriority }): Promise<number> {
3663
+ this._assertActive('warmFromL2');
3362
3664
  if (this._redisDisabled) return 0;
3363
3665
  try {
3364
3666
  const client = await this.getRedis();
@@ -3404,20 +3706,131 @@ export class CacheService {
3404
3706
  }
3405
3707
 
3406
3708
  /**
3407
- * Invalidate all keys associated with a tag.
3408
- * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
3709
+ * Discovers all concrete tag names in the system that match `tag` either via
3710
+ * glob wildcards ('*' or '?') or parent-child hierarchy cascading.
3711
+ * Scans local in-memory indices (tagIndex, tagVersions, L1 entries) and Redis (if connected).
3712
+ */
3713
+ private async _resolveMatchingTags(tag: string, shouldCascade: boolean): Promise<Set<string>> {
3714
+ const isPattern = isWildcardTag(tag);
3715
+ const delim = this.opts.tagHierarchyDelimiter;
3716
+ const matched = new Set<string>();
3717
+
3718
+ const tagMatches = (t: string): boolean => {
3719
+ if (t === tag) return true;
3720
+ if (isPattern && matchesTagPattern(tag, t)) return true;
3721
+ if (shouldCascade && isChildTag(tag, t, delim)) return true;
3722
+ return false;
3723
+ };
3724
+
3725
+ if (shouldCascade && !isPattern) {
3726
+ matched.add(tag);
3727
+ }
3728
+
3729
+ // 1. Scan in-process tagIndex (set strategy)
3730
+ const tagPrefix = this.nk('_tag_:');
3731
+ for (const tagKey of this.tagIndex.keys()) {
3732
+ const t = tagKey.startsWith(tagPrefix) ? tagKey.slice(tagPrefix.length) : tagKey;
3733
+ if (tagMatches(t)) matched.add(t);
3734
+ }
3735
+
3736
+ // 2. Scan in-process tagVersions (generational strategy)
3737
+ for (const t of this.tagVersions.keys()) {
3738
+ if (tagMatches(t)) matched.add(t);
3739
+ }
3740
+
3741
+ // 3. Scan in-process L1 entries for any active tags
3742
+ this.l1.scan((_k, entry) => {
3743
+ if (entry.tagVersions) {
3744
+ for (const t of Object.keys(entry.tagVersions)) {
3745
+ if (tagMatches(t)) matched.add(t);
3746
+ }
3747
+ }
3748
+ }, 0);
3749
+
3750
+ // 4. Scan Redis if connected
3751
+ if (!this._redisDisabled) {
3752
+ try {
3753
+ const client = await this.getRedis();
3754
+ if (this.opts.tagStrategy === 'generational') {
3755
+ const redisPattern = isPattern
3756
+ ? this.nk(`tag_ver:${tag}`)
3757
+ : this.nk(`tag_ver:${tag}${delim}*`);
3758
+ const scannedKeys = await this._scanKeys(client, redisPattern);
3759
+ const pfx = this.nk('tag_ver:');
3760
+ for (const sk of scannedKeys) {
3761
+ const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
3762
+ if (tagMatches(t)) matched.add(t);
3763
+ }
3764
+ } else {
3765
+ const redisPattern = isPattern
3766
+ ? this.nk(`_tag_:${tag}`)
3767
+ : this.nk(`_tag_:${tag}${delim}*`);
3768
+ const scannedKeys = await this._scanKeys(client, redisPattern);
3769
+ const pfx = this.nk('_tag_:');
3770
+ for (const sk of scannedKeys) {
3771
+ const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
3772
+ if (tagMatches(t)) matched.add(t);
3773
+ }
3774
+ }
3775
+ } catch (err) {
3776
+ this.logger.debug('_resolveMatchingTags: Redis scan failed', { tag, error: (err as Error).message });
3777
+ }
3778
+ }
3779
+
3780
+ return matched;
3781
+ }
3782
+
3783
+ /**
3784
+ * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
3785
+ * Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
3786
+ *
3787
+ * @param tag Tag name or wildcard glob pattern (e.g. `'catalog'`, `'org:123:*'`, `'*:comments'`).
3788
+ * @param opts Optional invalidation options, including `{ cascade: true }` to invalidate child namespaces.
3409
3789
  *
3410
3790
  * @example
3411
3791
  * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
3412
3792
  * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
3793
+ *
3794
+ * @example
3795
+ * // Wildcard pattern invalidation
3796
+ * await cache.invalidateTag('org:123:*');
3797
+ *
3798
+ * @example
3799
+ * // Hierarchical tag cascading (clears 'org:123' and all child tags like 'org:123:dept:456')
3800
+ * await cache.invalidateTag('org:123', { cascade: true });
3413
3801
  */
3414
- async invalidateTag(tag: string): Promise<void> {
3802
+ async invalidateTag(tag: string, opts?: InvalidateTagOptions): Promise<void> {
3803
+ this._assertActive('invalidateTag');
3415
3804
  const span = this._startSpan('tricache.invalidate_tag');
3416
3805
  if (this.opts.tracer) {
3417
3806
  span.setAttribute('cache.tag', tag);
3418
3807
  span.setAttribute('cache.tag_strategy', this.opts.tagStrategy);
3808
+ if (opts?.cascade) span.setAttribute('cache.cascade', true);
3419
3809
  }
3420
3810
  try {
3811
+ const isPattern = isWildcardTag(tag);
3812
+ const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
3813
+
3814
+ if (isPattern || shouldCascade) {
3815
+ const matchedTags = await this._resolveMatchingTags(tag, shouldCascade);
3816
+ const delim = this.opts.tagHierarchyDelimiter;
3817
+ const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
3818
+
3819
+ if (matchedTags.size > 0) {
3820
+ await this.invalidateTags(Array.from(matchedTags));
3821
+ }
3822
+
3823
+ // Broadcast wildcard invalidation across backplane and cross-region
3824
+ const op = this.opts.tagStrategy === 'generational' ? 'tag_pattern_incr' : 'tag_pattern_del';
3825
+ if (this.opts.awaitInvalidationBackplane) {
3826
+ await this.publishInvalidation(op, broadcastPattern, undefined, false, true);
3827
+ } else {
3828
+ void this.publishInvalidation(op, broadcastPattern, undefined, false, true);
3829
+ }
3830
+ return;
3831
+ }
3832
+
3833
+ // Fast-path: single discrete tag
3421
3834
  if (this.opts.tagStrategy === 'generational') {
3422
3835
  let newVer = 1;
3423
3836
  if (!this._redisDisabled) {
@@ -3433,8 +3846,12 @@ export class CacheService {
3433
3846
  const current = this.tagVersions.get(tag)?.version ?? 0;
3434
3847
  newVer = current + 1;
3435
3848
  }
3436
- this._setLocalTagVersion(tag, newVer, Date.now());
3437
- void this.publishInvalidation('tag_incr', tag, newVer, false, true);
3849
+ this._setLocalTagVersion(tag, newVer, performance.now());
3850
+ if (this.opts.awaitInvalidationBackplane) {
3851
+ await this.publishInvalidation('tag_incr', tag, newVer, false, true);
3852
+ } else {
3853
+ void this.publishInvalidation('tag_incr', tag, newVer, false, true);
3854
+ }
3438
3855
  return;
3439
3856
  }
3440
3857
 
@@ -3444,7 +3861,15 @@ export class CacheService {
3444
3861
  // Remove from L1 + disk
3445
3862
  for (const k of members) {
3446
3863
  this.l1.delete(k);
3447
- if (!this._diskDisabled) this.disk.delete(k);
3864
+ this._bumpKeyMutation(k);
3865
+ this._pendingDiskDeletes.add(k);
3866
+ setImmediate(() => {
3867
+ try {
3868
+ if (!this._diskDisabled) this.disk.delete(k);
3869
+ } finally {
3870
+ this._pendingDiskDeletes.delete(k);
3871
+ }
3872
+ });
3448
3873
  }
3449
3874
  this.tagIndex.delete(tagKey);
3450
3875
 
@@ -3473,22 +3898,40 @@ export class CacheService {
3473
3898
 
3474
3899
  /**
3475
3900
  * Invalidate all keys associated with any of the given tags in a single operation.
3476
- * Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
3477
- * reducing latency when invalidating several related tags together.
3901
+ * Supports discrete tags, wildcard glob patterns, and hierarchical cascading.
3902
+ * Combines multiple tag invalidations into Redis pipeline round-trips.
3478
3903
  *
3479
- * Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
3480
- * synchronously before the Redis round-trip.
3904
+ * @param tags Array of tag names or wildcard patterns (e.g. `['case:acme', 'org:*']`).
3905
+ * @param opts Optional invalidation options, including `{ cascade: true }`.
3481
3906
  *
3482
3907
  * @example
3483
- * // Instead of three serial round-trips:
3484
- * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
3908
+ * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:*']);
3485
3909
  */
3486
- async invalidateTags(tags: string[]): Promise<void> {
3910
+ async invalidateTags(tags: string[], opts?: InvalidateTagOptions): Promise<void> {
3911
+ this._assertActive('invalidateTags');
3487
3912
  if (tags.length === 0) return;
3488
- if (tags.length === 1) { await this.invalidateTag(tags[0]); return; }
3913
+
3914
+ const hasWildcards = tags.some(t => isWildcardTag(t));
3915
+ const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
3916
+
3917
+ if (hasWildcards || shouldCascade) {
3918
+ const allResolvedTags = new Set<string>();
3919
+ for (const t of tags) {
3920
+ if (isWildcardTag(t) || shouldCascade) {
3921
+ const resolved = await this._resolveMatchingTags(t, shouldCascade);
3922
+ for (const rt of resolved) allResolvedTags.add(rt);
3923
+ } else {
3924
+ allResolvedTags.add(t);
3925
+ }
3926
+ }
3927
+ if (allResolvedTags.size === 0) return;
3928
+ tags = Array.from(allResolvedTags);
3929
+ }
3930
+
3931
+ if (tags.length === 1) { await this.invalidateTag(tags[0], opts); return; }
3489
3932
 
3490
3933
  if (this.opts.tagStrategy === 'generational') {
3491
- const now = Date.now();
3934
+ const now = performance.now();
3492
3935
  if (!this._redisDisabled) {
3493
3936
  try {
3494
3937
  const client = await this.getRedis();
@@ -3499,7 +3942,11 @@ export class CacheService {
3499
3942
  const [err, newVer] = results[i] ?? [null, null];
3500
3943
  const ver = (!err && typeof newVer === 'number') ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
3501
3944
  this._setLocalTagVersion(tags[i], ver, now);
3502
- void this.publishInvalidation('tag_incr', tags[i], ver, false, true);
3945
+ if (this.opts.awaitInvalidationBackplane) {
3946
+ await this.publishInvalidation('tag_incr', tags[i], ver, false, true);
3947
+ } else {
3948
+ void this.publishInvalidation('tag_incr', tags[i], ver, false, true);
3949
+ }
3503
3950
  }
3504
3951
  return;
3505
3952
  } catch (err) {
@@ -3509,7 +3956,11 @@ export class CacheService {
3509
3956
  for (const tag of tags) {
3510
3957
  const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
3511
3958
  this._setLocalTagVersion(tag, ver, now);
3512
- void this.publishInvalidation('tag_incr', tag, ver, false, true);
3959
+ if (this.opts.awaitInvalidationBackplane) {
3960
+ await this.publishInvalidation('tag_incr', tag, ver, false, true);
3961
+ } else {
3962
+ void this.publishInvalidation('tag_incr', tag, ver, false, true);
3963
+ }
3513
3964
  }
3514
3965
  return;
3515
3966
  }
@@ -3526,7 +3977,15 @@ export class CacheService {
3526
3977
  }
3527
3978
  for (const k of allMembers) {
3528
3979
  this.l1.delete(k);
3529
- this.disk.delete(k);
3980
+ this._bumpKeyMutation(k);
3981
+ this._pendingDiskDeletes.add(k);
3982
+ setImmediate(() => {
3983
+ try {
3984
+ if (!this._diskDisabled) this.disk.delete(k);
3985
+ } finally {
3986
+ this._pendingDiskDeletes.delete(k);
3987
+ }
3988
+ });
3530
3989
  }
3531
3990
 
3532
3991
  if (!this._redisDisabled) {
@@ -3568,6 +4027,7 @@ export class CacheService {
3568
4027
  * `l2` is `null` when Redis is disabled.
3569
4028
  */
3570
4029
  async ping(): Promise<CachePingResult> {
4030
+ this._assertActive('ping');
3571
4031
  // L1: measure a has() call
3572
4032
  const t0 = Date.now();
3573
4033
  this.l1.has('__ping__');
@@ -3657,6 +4117,7 @@ export class CacheService {
3657
4117
  * Returns the number of keys written.
3658
4118
  */
3659
4119
  async drainToL2(): Promise<number> {
4120
+ this._assertActive('drainToL2');
3660
4121
  if (this._redisDisabled) return 0;
3661
4122
  try {
3662
4123
  const client = await this.getRedis();
@@ -3705,6 +4166,7 @@ export class CacheService {
3705
4166
  * if (!claimed) return res.status(409).json({ error: 'duplicate request' });
3706
4167
  */
3707
4168
  async setIfAbsent<T>(cacheKey: string, value: T, ttlSeconds = 300, priority?: CachePriority): Promise<boolean> {
4169
+ this._assertActive('setIfAbsent');
3708
4170
  const k = this.nk(cacheKey);
3709
4171
 
3710
4172
  // Fast path: L1 check (process-local, no network hop)
@@ -3729,6 +4191,8 @@ export class CacheService {
3729
4191
 
3730
4192
  const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
3731
4193
  const p = priority ?? inferPriority(cacheKey);
4194
+ this._bumpKeyMutation(k);
4195
+ this._pendingDiskDeletes.delete(k);
3732
4196
  this.l1.set(k, value, ttlMs, p);
3733
4197
  this.counters.sets++;
3734
4198
  return true;
@@ -3753,6 +4217,7 @@ export class CacheService {
3753
4217
  fn: () => Promise<T>,
3754
4218
  options?: LockOptions,
3755
4219
  ): Promise<T> {
4220
+ this._assertActive('lock');
3756
4221
  const ttlSeconds = Math.max(1, options?.ttl ?? 30);
3757
4222
  const acquireTimeout = Math.max(0, options?.acquireTimeout ?? 5_000);
3758
4223
  const retryInterval = Math.max(10, options?.retryInterval ?? 100);
@@ -3788,6 +4253,10 @@ export class CacheService {
3788
4253
  }
3789
4254
  } catch (err) {
3790
4255
  if ((err as Error).message.startsWith('Failed to acquire lock')) throw err;
4256
+ const failClosed = options?.failClosedOnRedisError ?? this.opts.lockFailClosed;
4257
+ if (failClosed) {
4258
+ throw new Error(`Distributed lock acquisition failed for resource "${resourceKey}" due to Redis error: ${(err as Error).message}`);
4259
+ }
3791
4260
  this.logger.debug('Distributed lock: Redis error, falling back to in-process mutex', {
3792
4261
  resourceKey, error: (err as Error).message,
3793
4262
  });
@@ -4162,6 +4631,7 @@ export class CacheService {
4162
4631
  * the previous key for seamless fallback decryption of existing cache entries.
4163
4632
  */
4164
4633
  async rotateEncryptionKey(newKeyBase64: string, newMode?: EncryptionMode): Promise<void> {
4634
+ this._assertActive('rotateEncryptionKey');
4165
4635
  this.enc.rotateKey(newKeyBase64, newMode);
4166
4636
  if (this._workerPool) {
4167
4637
  await this._workerPool.drainAndReinit(this.enc.toWorkerInit());
@@ -4172,6 +4642,8 @@ export class CacheService {
4172
4642
  /** Close Redis connections and stop all background timers. */
4173
4643
  async destroy(): Promise<void> {
4174
4644
  this._destroyed = true;
4645
+ this._pendingDiskDeletes.clear();
4646
+ this._keyMutationEpochs.clear();
4175
4647
  const g = globalThis as Record<string, unknown>;
4176
4648
  const key = CacheService.globalKey(this.opts);
4177
4649
  if (g[key] === this) {