tricache 0.9.0 → 1.0.1

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 (53) hide show
  1. package/README.md +7 -3
  2. package/dist/{cache-service-DVvroyqA.d.ts → cache-service-CREOp7MM.d.ts} +57 -12
  3. package/dist/{cache-service-KI5ACF3F.js → cache-service-MG7PN6MX.js} +3 -3
  4. package/dist/{chunk-XZL45ABR.js → chunk-2AJKEQMZ.js} +54 -1
  5. package/dist/{chunk-QNU7B43J.js → chunk-3I5L7K6I.js} +17 -0
  6. package/dist/{chunk-PL5J3ZNT.js → chunk-JYQFQJNJ.js} +682 -277
  7. package/dist/{chunk-LJ5QJB5O.js → chunk-UBWLPKTI.js} +127 -11
  8. package/dist/cli.cjs +857 -293
  9. package/dist/cli.js +4 -4
  10. package/dist/dashboard/index.d.ts +2 -2
  11. package/dist/drizzle/index.cjs +865 -294
  12. package/dist/drizzle/index.d.ts +2 -2
  13. package/dist/drizzle/index.js +1 -1
  14. package/dist/edge/index.cjs +115 -36
  15. package/dist/edge/index.d.ts +3 -3
  16. package/dist/edge/index.js +88 -37
  17. package/dist/hono/index.cjs +865 -294
  18. package/dist/hono/index.d.ts +2 -2
  19. package/dist/hono/index.js +1 -1
  20. package/dist/{hono-VA9A1m0I.d.ts → hono-DSV2ve66.d.ts} +11 -4
  21. package/dist/http/index.cjs +917 -315
  22. package/dist/http/index.d.ts +3 -3
  23. package/dist/http/index.js +60 -29
  24. package/dist/index.cjs +885 -294
  25. package/dist/index.d.ts +37 -7
  26. package/dist/index.js +16 -6
  27. package/dist/nestjs/index.cjs +856 -292
  28. package/dist/nestjs/index.d.ts +2 -2
  29. package/dist/nestjs/index.js +4 -4
  30. package/dist/next/index.cjs +858 -300
  31. package/dist/next/index.d.ts +2 -2
  32. package/dist/next/index.js +5 -11
  33. package/dist/prisma/index.d.ts +2 -2
  34. package/dist/serialize-worker.cjs +127 -9
  35. package/dist/serialize-worker.js +8 -4
  36. package/dist/{types-B_QkVwJ7.d.ts → types-Dyip5wAl.d.ts} +53 -7
  37. package/package.json +7 -4
  38. package/src/adapters/node-redis.ts +19 -0
  39. package/src/cache-service.ts +781 -297
  40. package/src/cli.ts +1 -1
  41. package/src/compression.ts +193 -15
  42. package/src/cross-region.ts +1 -1
  43. package/src/edge/cache.ts +94 -42
  44. package/src/env.d.ts +13 -0
  45. package/src/http/express.ts +55 -16
  46. package/src/http/fastify.ts +3 -7
  47. package/src/index.ts +9 -1
  48. package/src/next/cache-handler.ts +1 -4
  49. package/src/next/isr-handler.ts +1 -4
  50. package/src/serialize-worker.ts +6 -2
  51. package/src/smart-memory-cache.ts +3 -2
  52. package/src/types.ts +45 -5
  53. package/src/utils/tag-matcher.ts +90 -0
@@ -49,21 +49,31 @@ import {
49
49
  WTinyLfuStats,
50
50
  CachePresetType,
51
51
  CacheHealthStatus,
52
+ InvalidateTagOptions,
53
+ EvictionReason,
52
54
  } from './types';
53
55
  import { CacheEncryption, EnvelopeEncryption, type EncryptionMode } from './encryption';
54
56
  import { SmartMemoryCache } from './smart-memory-cache';
55
57
  import { DiskTier, resolveDefaultDiskDir } from './disk-tier';
56
58
  import { TierLatencyWatchdog } from './latency-watchdog';
57
- import { resolveAutonomousL1MaxBytes } from './utils/cgroup';
59
+ import { resolveAutonomousL1MaxBytes, readCgroupMemoryLimit } from './utils/cgroup';
58
60
  import { AutoPipeliner } from './adapters/auto-pipeliner';
59
61
  import { IpcTelemetryServer } from './ipc-telemetry.js';
60
62
  import {
61
63
  compressBuffer,
62
64
  decompressBuffer,
65
+ initZstd,
63
66
  PREFIX_COMPRESSED,
64
67
  PREFIX_ENC_COMPRESSED,
65
68
  type CompressionAlgorithm,
69
+ type CustomCompressor,
66
70
  } from './compression';
71
+ import {
72
+ isWildcardTag,
73
+ matchesTagPattern,
74
+ isChildTag,
75
+ expandHierarchicalTags,
76
+ } from './utils/tag-matcher.js';
67
77
 
68
78
  // ─── Lua scripts ─────────────────────────────────────────────────────────────
69
79
 
@@ -501,11 +511,14 @@ export class CacheService {
501
511
  redisProtocol: 2 | 3 | undefined;
502
512
  useShardedPubSub: boolean;
503
513
  compression: CompressionAlgorithm;
514
+ customCompressor?: CustomCompressor;
504
515
  compressionThresholdBytes: number;
505
516
  strictSingleton: boolean;
506
517
  failClosed: boolean;
507
518
  tagStrategy: 'set' | 'generational';
508
519
  tagVersionTtlMs: number;
520
+ hierarchicalTags: boolean;
521
+ tagHierarchyDelimiter: string;
509
522
  cloneStrategy: 'none' | 'structuredClone';
510
523
  backplaneMode: 'pubsub' | 'stream';
511
524
  backplaneStreamMaxLen: number;
@@ -536,6 +549,7 @@ export class CacheService {
536
549
  };
537
550
  /** Pre-computed once — opts.namespace never changes after construction. */
538
551
  private readonly _namespace: string;
552
+ private readonly prefixLen: number;
539
553
  /** Pre-computed once — disableRedis and redisHost never change after construction. */
540
554
  private readonly _redisDisabled: boolean;
541
555
  private readonly watchdog: TierLatencyWatchdog;
@@ -545,6 +559,8 @@ export class CacheService {
545
559
  private readonly _l1Counters = new Map<string, { value: number; expiresAt: number }>();
546
560
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
547
561
  private readonly tagIndex = new Map<string, Set<string>>();
562
+ /** Reverse index of namespaced key → { tags, expiresAt } for bounded cleanup on eviction/delete */
563
+ private readonly keyTags = new Map<string, { tags: string[]; expiresAt: number }>();
548
564
  /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
549
565
  private readonly tagVersions = new Map<string, { version: number; lastSyncedAt: number }>();
550
566
  /**
@@ -552,6 +568,9 @@ export class CacheService {
552
568
  * When an exact-key delete matches a registered pattern, all dependents are cascaded.
553
569
  */
554
570
  private readonly dependencyIndex = new Map<string, Set<string>>();
571
+ /** Reverse index of namespaced dependent key → source glob patterns */
572
+ private readonly keyDependencies = new Map<string, string[]>();
573
+ private readonly _cgroupMemoryLimit: number;
555
574
  private redis: AnyRedisClient | null = null;
556
575
  private redisConnecting: Promise<AnyRedisClient> | null = null;
557
576
  private readonly cb: L2CircuitBreaker;
@@ -626,6 +645,97 @@ export class CacheService {
626
645
  private _getKeyMutationEpoch(namespacedKey: string): number {
627
646
  return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
628
647
  }
648
+
649
+ private _removeKeyTags(namespacedKey: string): void {
650
+ const entry = this.keyTags.get(namespacedKey);
651
+ if (!entry) return;
652
+ for (const tag of entry.tags) {
653
+ const tagKey = this.nk(`_tag_:${tag}`);
654
+ const members = this.tagIndex.get(tagKey);
655
+ if (members) {
656
+ members.delete(namespacedKey);
657
+ if (members.size === 0) this.tagIndex.delete(tagKey);
658
+ }
659
+ }
660
+ this.keyTags.delete(namespacedKey);
661
+ }
662
+
663
+ private _removeKeyDependencies(namespacedKey: string): void {
664
+ const patterns = this.keyDependencies.get(namespacedKey);
665
+ if (patterns) {
666
+ for (const pat of patterns) {
667
+ const deps = this.dependencyIndex.get(pat);
668
+ if (deps) {
669
+ deps.delete(namespacedKey);
670
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
671
+ }
672
+ }
673
+ this.keyDependencies.delete(namespacedKey);
674
+ } else if (this.dependencyIndex.size > 0) {
675
+ for (const [pat, deps] of this.dependencyIndex) {
676
+ deps.delete(namespacedKey);
677
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
678
+ }
679
+ }
680
+ }
681
+
682
+ private _handleL1Eviction(namespacedKey: string, reason: EvictionReason): void {
683
+ const spilledToDisk = !this._diskDisabled && (
684
+ reason === 'capacity' ||
685
+ reason === 'category' ||
686
+ reason === 'rebalance' ||
687
+ reason === 'oom'
688
+ );
689
+ if (!spilledToDisk) {
690
+ this._removeKeyTags(namespacedKey);
691
+ this._removeKeyDependencies(namespacedKey);
692
+ }
693
+ }
694
+
695
+ private _removePrefixFromIndices(prefix: string): void {
696
+ for (const k of Array.from(this.keyTags.keys())) {
697
+ if (k.startsWith(prefix)) this._removeKeyTags(k);
698
+ }
699
+ for (const k of Array.from(this.keyDependencies.keys())) {
700
+ if (k.startsWith(prefix)) this._removeKeyDependencies(k);
701
+ }
702
+ for (const k of Array.from(this._l1Counters.keys())) {
703
+ if (k.startsWith(prefix)) this._l1Counters.delete(k);
704
+ }
705
+ }
706
+
707
+ private _sweepExpiredMetadata(): void {
708
+ const now = Date.now();
709
+ for (const [k, c] of this._l1Counters) {
710
+ if (c.expiresAt <= now) this._l1Counters.delete(k);
711
+ }
712
+ for (const [k, meta] of this.keyTags) {
713
+ if (meta.expiresAt <= now && !this.l1.has(k)) {
714
+ this._removeKeyTags(k);
715
+ this._removeKeyDependencies(k);
716
+ }
717
+ }
718
+ }
719
+
720
+ private _runOomCheck(): void {
721
+ const heap = v8.getHeapStatistics();
722
+ const heapUsed = heap.used_heap_size / heap.heap_size_limit;
723
+ const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0
724
+ ? process.memoryUsage().rss / this._cgroupMemoryLimit
725
+ : 0;
726
+ const used = Math.max(heapUsed, cgroupUsed);
727
+ if (used >= this.opts.oomHeapThreshold) {
728
+ const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
729
+ this.counters.oomEvictions++;
730
+ this.counters.oomLastAt = Date.now();
731
+ this.logger.warn('tricache OOM guard: emergency L1 eviction', {
732
+ heapUsedPct: Math.round(heapUsed * 100),
733
+ cgroupUsedPct: cgroupUsed > 0 ? Math.round(cgroupUsed * 100) : undefined,
734
+ threshold: Math.round(this.opts.oomHeapThreshold * 100),
735
+ evicted,
736
+ });
737
+ }
738
+ }
629
739
  private _ipcServer?: IpcTelemetryServer;
630
740
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
631
741
  private _subDisconnectedAt: number | null = null;
@@ -675,6 +785,7 @@ export class CacheService {
675
785
  constructor(options: CacheOptions = {}) {
676
786
  const logger = options.logger ?? consoleLogger;
677
787
  this.logger = logger;
788
+ this._cgroupMemoryLimit = readCgroupMemoryLimit();
678
789
 
679
790
  // Resolve namespace: trim whitespace, default to empty string
680
791
  const ns = options.namespace?.trim() ?? '';
@@ -765,12 +876,15 @@ export class CacheService {
765
876
  redisSentinel: options.redisSentinel,
766
877
  redisProtocol: options.redisProtocol,
767
878
  useShardedPubSub: options.useShardedPubSub ?? false,
768
- compression: options.compression ?? 'none',
879
+ compression: options.compression ?? 'zstd',
880
+ customCompressor: options.customCompressor,
769
881
  compressionThresholdBytes: options.compressionThresholdBytes ?? 1024,
770
882
  strictSingleton: options.strictSingleton ?? false,
771
883
  failClosed: options.failClosed ?? false,
772
884
  tagStrategy: options.tagStrategy ?? 'set',
773
885
  tagVersionTtlMs: options.tagVersionTtlMs ?? 5_000,
886
+ hierarchicalTags: options.hierarchicalTags ?? false,
887
+ tagHierarchyDelimiter: options.tagHierarchyDelimiter ?? ':',
774
888
  cloneStrategy: options.cloneStrategy ?? 'none',
775
889
  backplaneMode: options.backplaneMode ?? 'pubsub',
776
890
  backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 10_000,
@@ -854,6 +968,7 @@ export class CacheService {
854
968
  });
855
969
 
856
970
  this._namespace = ns;
971
+ this.prefixLen = ns ? ns.length + 1 : 0;
857
972
  // disableRedis takes unconditional precedence; otherwise, L2 is active when
858
973
  // at least one of host / cluster nodes / sentinel is configured.
859
974
  this._redisDisabled = this.opts.disableRedis
@@ -886,7 +1001,10 @@ export class CacheService {
886
1001
  // backplane handler already does for remote invalidations.
887
1002
  setImmediate(() => { void this.disk.save(key, entry as unknown as DiskCacheEntry); });
888
1003
  },
889
- onEviction: options.onEviction,
1004
+ onEviction: (key: string, reason: EvictionReason) => {
1005
+ this._handleL1Eviction(key, reason);
1006
+ options.onEviction?.(key, reason);
1007
+ },
890
1008
  logger,
891
1009
  });
892
1010
 
@@ -935,6 +1053,7 @@ export class CacheService {
935
1053
  // here to avoid a synchronous O(fileCount) event-loop stall at scale.
936
1054
  this.cleanupInterval = setInterval(() => {
937
1055
  const cleaned = this.l1.cleanup();
1056
+ this._sweepExpiredMetadata();
938
1057
  if (cleaned > 0) this.logger.debug('Periodic L1 cleanup', { cleaned });
939
1058
  }, 5 * 60 * 1000);
940
1059
  if (this.cleanupInterval.unref) this.cleanupInterval.unref(); // don't block process exit
@@ -948,21 +1067,10 @@ export class CacheService {
948
1067
  if (this.diskJanitorInterval.unref) this.diskJanitorInterval.unref();
949
1068
  }
950
1069
 
951
- // OOM protection: evict coldest L1 entries when heap pressure rises
1070
+ // OOM protection: evict coldest L1 entries when heap or container RSS pressure rises
952
1071
  if (this.opts.oomProtection) {
953
1072
  this.oomInterval = setInterval(() => {
954
- const heap = v8.getHeapStatistics();
955
- const used = heap.used_heap_size / heap.heap_size_limit;
956
- if (used >= this.opts.oomHeapThreshold) {
957
- const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
958
- this.counters.oomEvictions++;
959
- this.counters.oomLastAt = Date.now();
960
- this.logger.warn('tricache OOM guard: emergency L1 eviction', {
961
- heapUsedPct: Math.round(used * 100),
962
- threshold: Math.round(this.opts.oomHeapThreshold * 100),
963
- evicted,
964
- });
965
- }
1073
+ this._runOomCheck();
966
1074
  }, this.opts.oomCheckIntervalMs);
967
1075
  if (this.oomInterval.unref) this.oomInterval.unref();
968
1076
  }
@@ -991,6 +1099,9 @@ export class CacheService {
991
1099
 
992
1100
  // Auto-warm from remote snapshot or L2 if configured; ready() waits for completion.
993
1101
  const startupPromises: Promise<void>[] = [];
1102
+ if (this.opts.compression === 'zstd') {
1103
+ startupPromises.push(initZstd().then(() => undefined));
1104
+ }
994
1105
  if (this.opts.remoteSnapshot) {
995
1106
  startupPromises.push(this.loadRemoteSnapshot().then(() => undefined));
996
1107
  }
@@ -1472,7 +1583,12 @@ export class CacheService {
1472
1583
  else if (f === 'tagVersion') tagVersionRaw = v;
1473
1584
  }
1474
1585
 
1475
- const validOp = op === 'del' || op === 'del-glob' || op === 'tag_incr';
1586
+ const validOp =
1587
+ op === 'del' ||
1588
+ op === 'del-glob' ||
1589
+ op === 'tag_incr' ||
1590
+ op === 'tag_pattern_incr' ||
1591
+ op === 'tag_pattern_del';
1476
1592
  if (!validOp || typeof key !== 'string' || !key || typeof src !== 'string') {
1477
1593
  this.logger.warn('Backplane: rejected invalid stream entry', {
1478
1594
  op: String(op).slice(0, 40),
@@ -1534,6 +1650,50 @@ export class CacheService {
1534
1650
  const tag = key;
1535
1651
  const ver = typeof tagVersion === 'number' ? tagVersion : ((this.tagVersions.get(tag)?.version ?? 0) + 1);
1536
1652
  this._setLocalTagVersion(tag, ver, performance.now());
1653
+ } else if (op === 'tag_pattern_incr') {
1654
+ const pattern = key;
1655
+ const now = performance.now();
1656
+ for (const [tag, info] of this.tagVersions) {
1657
+ if (matchesTagPattern(pattern, tag)) {
1658
+ this._setLocalTagVersion(tag, info.version + 1, now);
1659
+ }
1660
+ }
1661
+ this.l1.scan((k, entry) => {
1662
+ if (entry.tagVersions) {
1663
+ for (const tag of Object.keys(entry.tagVersions)) {
1664
+ if (matchesTagPattern(pattern, tag)) {
1665
+ this.l1.delete(k);
1666
+ this._bumpKeyMutation(k);
1667
+ break;
1668
+ }
1669
+ }
1670
+ }
1671
+ }, 0);
1672
+ } else if (op === 'tag_pattern_del') {
1673
+ const pattern = key;
1674
+ const matchedTagKeys: string[] = [];
1675
+ const prefix = this.nk('_tag_:');
1676
+ for (const [tagKey, members] of this.tagIndex) {
1677
+ const tag = tagKey.startsWith(prefix) ? tagKey.slice(prefix.length) : tagKey;
1678
+ if (matchesTagPattern(pattern, tag)) {
1679
+ matchedTagKeys.push(tagKey);
1680
+ for (const k of members) {
1681
+ this.l1.delete(k);
1682
+ this._bumpKeyMutation(k);
1683
+ this._pendingDiskDeletes.add(k);
1684
+ setImmediate(() => {
1685
+ try {
1686
+ if (!this._diskDisabled) this.disk.delete(k);
1687
+ } finally {
1688
+ this._pendingDiskDeletes.delete(k);
1689
+ }
1690
+ });
1691
+ }
1692
+ }
1693
+ }
1694
+ for (const tagKey of matchedTagKeys) {
1695
+ this.tagIndex.delete(tagKey);
1696
+ }
1537
1697
  }
1538
1698
  this.logger.debug('Backplane: invalidation applied', { op, key: key.slice(0, 60) });
1539
1699
  }
@@ -1548,7 +1708,7 @@ export class CacheService {
1548
1708
  Array.isArray(msg) ||
1549
1709
  typeof msg.src !== 'string' ||
1550
1710
  typeof msg.key !== 'string' ||
1551
- (msg.op !== 'del' && msg.op !== 'del-glob' && msg.op !== 'tag_incr')
1711
+ (msg.op !== 'del' && msg.op !== 'del-glob' && msg.op !== 'tag_incr' && msg.op !== 'tag_pattern_incr' && msg.op !== 'tag_pattern_del')
1552
1712
  ) {
1553
1713
  this.logger.warn('Backplane: rejected invalid pubsub message format', {
1554
1714
  raw: typeof message === 'string' ? message.slice(0, 100).replace(/[\r\n\t]/g, ' ') : String(message),
@@ -1567,7 +1727,7 @@ export class CacheService {
1567
1727
  }
1568
1728
 
1569
1729
  private async publishInvalidation(
1570
- op: 'del' | 'del-glob' | 'tag_incr',
1730
+ op: 'del' | 'del-glob' | 'tag_incr' | 'tag_pattern_incr' | 'tag_pattern_del',
1571
1731
  key: string,
1572
1732
  tagVersion?: number,
1573
1733
  isCrossRegionRelay = false,
@@ -1640,7 +1800,7 @@ export class CacheService {
1640
1800
  }
1641
1801
 
1642
1802
  private async _broadcastCrossRegion(
1643
- op: 'del' | 'del-glob' | 'tag_incr',
1803
+ op: 'del' | 'del-glob' | 'tag_incr' | 'tag_pattern_incr' | 'tag_pattern_del',
1644
1804
  key: string,
1645
1805
  tagVersion?: number,
1646
1806
  ): Promise<void> {
@@ -1732,6 +1892,84 @@ export class CacheService {
1732
1892
  this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
1733
1893
  }
1734
1894
 
1895
+ private async _isGenerationalEntryStale(tagVersions?: Record<string, number>): Promise<boolean> {
1896
+ if (this.opts.tagStrategy !== 'generational' || !tagVersions) return false;
1897
+ const tags = Object.keys(tagVersions);
1898
+ if (tags.length === 0) return false;
1899
+ const currentVers = await Promise.all(tags.map(tag => this._getTagVersion(tag)));
1900
+ for (let i = 0; i < tags.length; i++) {
1901
+ if (currentVers[i] > tagVersions[tags[i]]) return true;
1902
+ }
1903
+ return false;
1904
+ }
1905
+
1906
+ private async _deleteRedisKeys(client: AnyRedisClient, keys: string[]): Promise<void> {
1907
+ if (keys.length === 0) return;
1908
+ const CHUNK_SIZE = 1_000;
1909
+ if (client instanceof RedisCluster) {
1910
+ for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
1911
+ const chunk = keys.slice(i, i + CHUNK_SIZE);
1912
+ const pl = client.pipeline();
1913
+ for (const k of chunk) pl.del(k);
1914
+ await pl.exec();
1915
+ }
1916
+ return;
1917
+ }
1918
+ for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
1919
+ const chunk = keys.slice(i, i + CHUNK_SIZE);
1920
+ await client.del(...chunk);
1921
+ }
1922
+ }
1923
+
1924
+ private async _parseGenerationalRedisHash<T>(
1925
+ k: string,
1926
+ hashData: Record<string, string>,
1927
+ ): Promise<{ value?: T; tagVersions?: Record<string, number>; stale: boolean } | null> {
1928
+ if (!hashData || !hashData.d) return null;
1929
+ let storedTagVersions: Record<string, number> = {};
1930
+ if (hashData.tv) {
1931
+ try { storedTagVersions = JSON.parse(hashData.tv); } catch { /* ignore */ }
1932
+ }
1933
+ if (await this._isGenerationalEntryStale(storedTagVersions)) {
1934
+ const setAtMs = parseInt(hashData.t, 10) || 0;
1935
+ this._deleteIfStale(k, setAtMs);
1936
+ return { stale: true };
1937
+ }
1938
+ const value = await this._decryptAndDeserialize<T>(hashData.d);
1939
+ return { value, tagVersions: storedTagVersions, stale: false };
1940
+ }
1941
+
1942
+ private async _readRedisEntry<T>(
1943
+ client: AnyRedisClient,
1944
+ k: string,
1945
+ allowAutoPipeline = false,
1946
+ ): Promise<{ value?: T; tagVersions?: Record<string, number>; stale: boolean } | null> {
1947
+ if (this.opts.tagStrategy === 'generational' && typeof (client as any).hgetall === 'function') {
1948
+ try {
1949
+ const hashData = await client.hgetall(k);
1950
+ if (typeof hashData === 'string') {
1951
+ const value = await this._decryptAndDeserialize<T>(hashData);
1952
+ return { value, stale: false };
1953
+ }
1954
+ if (hashData && hashData.d) {
1955
+ return await this._parseGenerationalRedisHash<T>(k, hashData);
1956
+ }
1957
+ return null;
1958
+ } catch (err) {
1959
+ const msg = err instanceof Error ? err.message : String(err);
1960
+ if (!msg.includes('WRONGTYPE')) throw err;
1961
+ // Fall through to GET if key was stored as a plain string without tags
1962
+ }
1963
+ }
1964
+
1965
+ const raw = (allowAutoPipeline && this.opts.autoPipeline && this.pipeliner)
1966
+ ? await this.pipeliner.get(k)
1967
+ : await client.get(k);
1968
+ if (raw == null) return null;
1969
+ const value = await this._decryptAndDeserialize<T>(raw);
1970
+ return { value, stale: false };
1971
+ }
1972
+
1735
1973
  private async _getTagVersion(tag: string): Promise<number> {
1736
1974
  const now = performance.now();
1737
1975
  const local = this.tagVersions.get(tag);
@@ -1767,12 +2005,12 @@ export class CacheService {
1767
2005
  * Offloads to worker thread if pool is active and payload exceeds threshold.
1768
2006
  */
1769
2007
  private async _serializeAndEncrypt(serialized: string): Promise<string> {
1770
- const isCompressed = this.opts.compression && this.opts.compression !== 'none' && serialized.length > this.opts.compressionThresholdBytes;
1771
- if (this._workerPool && (this.enc.isEnabled || isCompressed) && serialized.length > this.opts.workerThresholdBytes) {
2008
+ const isCompressed = (this.opts.customCompressor || (this.opts.compression && this.opts.compression !== 'none')) && serialized.length > this.opts.compressionThresholdBytes;
2009
+ if (this._workerPool && !this.opts.customCompressor && (this.enc.isEnabled || isCompressed) && serialized.length > this.opts.workerThresholdBytes) {
1772
2010
  return this._workerPool.encrypt(serialized);
1773
2011
  }
1774
2012
  if (isCompressed) {
1775
- const compressed = compressBuffer(Buffer.from(serialized, 'utf8'), this.opts.compression);
2013
+ const compressed = compressBuffer(Buffer.from(serialized, 'utf8'), this.opts.compression, this.opts.customCompressor);
1776
2014
  if (this.enc.isEnabled) {
1777
2015
  const encrypted = this.enc.encryptBuffer(compressed);
1778
2016
  return PREFIX_ENC_COMPRESSED + encrypted.toString('base64');
@@ -1788,16 +2026,16 @@ export class CacheService {
1788
2026
  */
1789
2027
  private async _decryptAndDeserialize<T>(raw: string): Promise<T> {
1790
2028
  let plain: string;
1791
- if (this._workerPool && raw.length > this.opts.workerThresholdBytes) {
2029
+ if (this._workerPool && !this.opts.customCompressor && raw.length > this.opts.workerThresholdBytes) {
1792
2030
  plain = await this._workerPool.decrypt(raw);
1793
2031
  } else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
1794
2032
  const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), 'base64');
1795
2033
  const decBuf = this.enc.decryptBuffer(encBuf);
1796
- const decompressed = decompressBuffer(decBuf, this.opts.compression !== 'none' ? this.opts.compression : 'brotli');
2034
+ const decompressed = decompressBuffer(decBuf, this.opts.compression !== 'none' ? this.opts.compression : 'brotli', this.opts.customCompressor);
1797
2035
  plain = decompressed.toString('utf8');
1798
2036
  } else if (raw.startsWith(PREFIX_COMPRESSED)) {
1799
2037
  const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), 'base64');
1800
- const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== 'none' ? this.opts.compression : 'brotli');
2038
+ const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== 'none' ? this.opts.compression : 'brotli', this.opts.customCompressor);
1801
2039
  plain = decompressed.toString('utf8');
1802
2040
  } else if (raw.startsWith('enc:v1:') || this.enc.isEnabled) {
1803
2041
  plain = this.enc.decrypt(raw);
@@ -1884,10 +2122,9 @@ export class CacheService {
1884
2122
  }
1885
2123
 
1886
2124
  this.redisConnecting = (async () => {
2125
+ let client: AnyRedisClient | null = null;
1887
2126
  try {
1888
2127
  // ── Fix 4: Cluster / Sentinel / single-node connection factory ──────
1889
- let client: AnyRedisClient;
1890
-
1891
2128
  if (this.opts.redisClusterNodes?.length) {
1892
2129
  // Redis Cluster — ioredis handles slot routing and multi-node pooling.
1893
2130
  client = new RedisCluster(this.opts.redisClusterNodes, {
@@ -1954,15 +2191,45 @@ export class CacheService {
1954
2191
  client.on('reconnecting', () => this.logger.debug('Redis reconnecting'));
1955
2192
  }
1956
2193
 
2194
+ const pendingClient = client;
1957
2195
  await new Promise<void>((resolve, reject) => {
1958
- client.once('ready', resolve);
1959
- client.once('error', (e: Error) => {
2196
+ let settled = false;
2197
+ const cleanupListeners = () => {
2198
+ pendingClient.removeListener?.('ready', onReady);
2199
+ pendingClient.removeListener?.('error', onError);
2200
+ };
2201
+ const onReady = () => {
2202
+ if (settled) return;
2203
+ settled = true;
2204
+ clearTimeout(timer);
2205
+ cleanupListeners();
2206
+ resolve();
2207
+ };
2208
+ const onError = (e: Error) => {
2209
+ if (settled) return;
2210
+ settled = true;
2211
+ clearTimeout(timer);
2212
+ cleanupListeners();
1960
2213
  this._checkAndLogResp3Hint(e);
1961
2214
  reject(e);
1962
- });
1963
- setTimeout(() => reject(new Error('Redis connection timeout')), 15_000);
2215
+ };
2216
+ const timer = setTimeout(() => {
2217
+ if (settled) return;
2218
+ settled = true;
2219
+ cleanupListeners();
2220
+ reject(new Error('Redis connection timeout'));
2221
+ }, 15_000);
2222
+ if (timer.unref) timer.unref();
2223
+
2224
+ pendingClient.once('ready', onReady);
2225
+ pendingClient.once('error', onError);
1964
2226
  });
1965
2227
 
2228
+ if (this._destroyed) {
2229
+ try { client.disconnect(); } catch { /* ok */ }
2230
+ this._assertActive('getRedis');
2231
+ }
2232
+
1966
2233
  this.cb.onSuccess();
1967
2234
  this.redis = client;
1968
2235
  this.pipeliner = new AutoPipeliner(client, {
@@ -1972,6 +2239,7 @@ export class CacheService {
1972
2239
  this.redisConnecting = null;
1973
2240
  return client;
1974
2241
  } catch (err) {
2242
+ try { client?.disconnect(); } catch { /* ok */ }
1975
2243
  this.cb.onFailure();
1976
2244
  this.redisConnecting = null; // allow retry on next call — fixes the cached-rejection bug
1977
2245
  this._checkAndLogResp3Hint(err as Error);
@@ -2257,22 +2525,14 @@ export class CacheService {
2257
2525
  const optRefreshAhead = opts.refreshAhead;
2258
2526
  const optXfetchBeta = opts.xfetchBeta;
2259
2527
  const optNotFoundTtl = opts.notFoundTtl;
2260
- const optTags = opts.tags;
2528
+ const optTags = opts.tags
2529
+ ? (this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags)
2530
+ : undefined;
2261
2531
 
2262
2532
  // L1: in-memory (fastest path)
2263
2533
  const l1Hit = this.l1.get(k);
2264
2534
  if (l1Hit !== null) {
2265
- let isGenerationalStale = false;
2266
- if (this.opts.tagStrategy === 'generational' && l1Hit.tagVersions) {
2267
- const tags = Object.keys(l1Hit.tagVersions);
2268
- const currentVers = await Promise.all(tags.map(tag => this._getTagVersion(tag)));
2269
- for (let i = 0; i < tags.length; i++) {
2270
- if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
2271
- isGenerationalStale = true;
2272
- break;
2273
- }
2274
- }
2275
- }
2535
+ const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
2276
2536
 
2277
2537
  if (isGenerationalStale) {
2278
2538
  this._deleteIfStale(k, l1Hit.setAt ?? 0);
@@ -2378,17 +2638,7 @@ export class CacheService {
2378
2638
  this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
2379
2639
 
2380
2640
  if (diskHit !== null) {
2381
- let isDiskStale = false;
2382
- if (this.opts.tagStrategy === 'generational' && diskHit.tagVersions) {
2383
- const tags = Object.keys(diskHit.tagVersions);
2384
- const currentVers = await Promise.all(tags.map(tag => this._getTagVersion(tag)));
2385
- for (let i = 0; i < tags.length; i++) {
2386
- if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
2387
- isDiskStale = true;
2388
- break;
2389
- }
2390
- }
2391
- }
2641
+ const isDiskStale = await this._isGenerationalEntryStale(diskHit.tagVersions);
2392
2642
 
2393
2643
  if (isDiskStale) {
2394
2644
  this.disk.delete(k);
@@ -2423,64 +2673,35 @@ export class CacheService {
2423
2673
  try {
2424
2674
  const client = await this.getRedis();
2425
2675
  const redisStart = performance.now();
2426
- if (this.opts.tagStrategy === 'generational') {
2427
- const hashData = await client.hgetall(k);
2428
- const redisElapsed = performance.now() - redisStart;
2429
- this.watchdog.recordRedis(redisElapsed);
2430
- this.cb.onSuccess();
2431
- if (hashData && hashData.d) {
2432
- let isStale = false;
2433
- let storedTagVersions: Record<string, number> = {};
2434
- if (hashData.tv) {
2435
- try { storedTagVersions = JSON.parse(hashData.tv); } catch { /* ignore */ }
2436
- }
2437
- const tags = Object.keys(storedTagVersions);
2438
- const currentVers = await Promise.all(tags.map(tag => this._getTagVersion(tag)));
2439
- for (let i = 0; i < tags.length; i++) {
2440
- if (currentVers[i] > storedTagVersions[tags[i]]) {
2441
- isStale = true;
2442
- break;
2443
- }
2444
- }
2445
- if (isStale) {
2446
- const setAtMs = parseInt(hashData.t, 10) || 0;
2447
- this._deleteIfStale(k, setAtMs);
2448
- } else {
2449
- const parsed = await this._decryptAndDeserialize<T>(hashData.d);
2450
- this.l1.set(k, parsed, ttlMs, priority, undefined, undefined, storedTagVersions);
2451
- this.counters.l2Hits++;
2452
- this.opts.onHit?.(cacheKey, 'l2');
2453
- this.logger.debug('L2 hit (Redis hash)', { cacheKey });
2454
- span.setAttribute('cache.hit', true)
2455
- .setAttribute('cache.item.tier', 'remote')
2456
- .setAttribute('cache.hit_tier', 'l2');
2457
- if (this.opts.frozen) deepFreeze(parsed);
2458
- return (this.opts.cloneStrategy === 'structuredClone' && parsed != null && typeof parsed === 'object')
2459
- ? structuredClone(parsed)
2460
- : parsed;
2461
- }
2462
- }
2463
- } else {
2464
- const raw = (this.opts.autoPipeline && this.pipeliner)
2465
- ? await this.pipeliner.get(k)
2466
- : await client.get(k);
2467
- const redisElapsed = performance.now() - redisStart;
2468
- this.watchdog.recordRedis(redisElapsed);
2469
- this.cb.onSuccess();
2470
- if (raw) {
2471
- const parsed = await this._decryptAndDeserialize<T>(raw);
2472
- this.l1.set(k, parsed, ttlMs, priority);
2473
- this.counters.l2Hits++;
2474
- this.opts.onHit?.(cacheKey, 'l2');
2475
- this.logger.debug('L2 hit (Redis)', { cacheKey });
2476
- span.setAttribute('cache.hit', true)
2477
- .setAttribute('cache.item.tier', 'remote')
2478
- .setAttribute('cache.hit_tier', 'l2');
2479
- if (this.opts.frozen) deepFreeze(parsed);
2480
- return (this.opts.cloneStrategy === 'structuredClone' && parsed != null && typeof parsed === 'object')
2481
- ? structuredClone(parsed)
2676
+ const redisHit = await this._readRedisEntry<T>(client, k, true);
2677
+ const redisElapsed = performance.now() - redisStart;
2678
+ this.watchdog.recordRedis(redisElapsed);
2679
+ this.cb.onSuccess();
2680
+ if (redisHit && !redisHit.stale && redisHit.value !== undefined) {
2681
+ const parsed = redisHit.value;
2682
+ if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
2683
+ this.logger.debug('Aborting L2 promotion — key was mutated or deleted during Redis read', { cacheKey });
2684
+ span.setAttribute('cache.aborted_mutation_race', true);
2685
+ const current = this.l1.get(k);
2686
+ const liveVal = (current && !current.isStale && current.value !== undefined)
2687
+ ? current.value as T
2482
2688
  : parsed;
2689
+ if (this.opts.frozen) deepFreeze(liveVal);
2690
+ return (this.opts.cloneStrategy === 'structuredClone' && liveVal != null && typeof liveVal === 'object')
2691
+ ? structuredClone(liveVal) as T
2692
+ : liveVal;
2483
2693
  }
2694
+ this.l1.set(k, parsed, ttlMs, priority, undefined, undefined, redisHit.tagVersions);
2695
+ this.counters.l2Hits++;
2696
+ this.opts.onHit?.(cacheKey, 'l2');
2697
+ this.logger.debug(redisHit.tagVersions ? 'L2 hit (Redis hash)' : 'L2 hit (Redis)', { cacheKey });
2698
+ span.setAttribute('cache.hit', true)
2699
+ .setAttribute('cache.item.tier', 'remote')
2700
+ .setAttribute('cache.hit_tier', 'l2');
2701
+ if (this.opts.frozen) deepFreeze(parsed);
2702
+ return (this.opts.cloneStrategy === 'structuredClone' && parsed != null && typeof parsed === 'object')
2703
+ ? structuredClone(parsed)
2704
+ : parsed;
2484
2705
  }
2485
2706
  } catch (err) {
2486
2707
  this.cb.onFailure();
@@ -2556,7 +2777,8 @@ export class CacheService {
2556
2777
  : data;
2557
2778
  }
2558
2779
 
2559
- this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
2780
+ const writeTs = Date.now();
2781
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs);
2560
2782
 
2561
2783
  if (!this._redisDisabled) {
2562
2784
  try {
@@ -2564,13 +2786,12 @@ export class CacheService {
2564
2786
  const serialized = JSON.stringify(data);
2565
2787
  const toStore = await this._serializeAndEncrypt(serialized);
2566
2788
  const ttlSec = Math.ceil(effectiveTtl / 1_000);
2567
- if (this.opts.tagStrategy === 'generational' && activeTagVersions) {
2568
- const now = Date.now();
2789
+ if (this.opts.tagStrategy === 'generational' && (activeTagVersions || (!this.opts.autoPipeline && typeof (client as any).hgetall === 'function'))) {
2569
2790
  const tx = client.multi();
2570
2791
  tx.hset(k, {
2571
2792
  d: toStore,
2572
- t: String(now),
2573
- tv: JSON.stringify(activeTagVersions),
2793
+ t: String(writeTs),
2794
+ tv: JSON.stringify(activeTagVersions ?? {}),
2574
2795
  });
2575
2796
  tx.expire(k, ttlSec);
2576
2797
  await tx.exec();
@@ -2734,7 +2955,8 @@ export class CacheService {
2734
2955
  return;
2735
2956
  }
2736
2957
 
2737
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
2958
+ const writeTs = Date.now();
2959
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs);
2738
2960
 
2739
2961
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
2740
2962
  try {
@@ -2742,13 +2964,12 @@ export class CacheService {
2742
2964
  const s = JSON.stringify(data);
2743
2965
  const stored = await this._serializeAndEncrypt(s);
2744
2966
  const ttlSec = Math.ceil(ttlMs / 1_000);
2745
- if (this.opts.tagStrategy === 'generational' && activeTagVersions) {
2746
- const now = Date.now();
2967
+ if (this.opts.tagStrategy === 'generational' && (activeTagVersions || (!this.opts.autoPipeline && typeof (client as any).hgetall === 'function'))) {
2747
2968
  const tx = client.multi();
2748
2969
  tx.hset(cacheKey, {
2749
2970
  d: stored,
2750
- t: String(now),
2751
- tv: JSON.stringify(activeTagVersions),
2971
+ t: String(writeTs),
2972
+ tv: JSON.stringify(activeTagVersions ?? {}),
2752
2973
  });
2753
2974
  tx.expire(cacheKey, ttlSec);
2754
2975
  await tx.exec();
@@ -2797,28 +3018,39 @@ export class CacheService {
2797
3018
  this.counters.sets++;
2798
3019
 
2799
3020
  let activeTagVersions: Record<string, number> | undefined;
2800
- if (opts?.tags?.length) {
3021
+ const tagsToRegister = opts?.tags?.length
3022
+ ? (this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags)
3023
+ : undefined;
3024
+
3025
+ if (tagsToRegister?.length) {
2801
3026
  if (this.opts.tagStrategy === 'generational') {
2802
- const vers = await Promise.all(opts.tags.map(tag => this._getTagVersion(tag)));
3027
+ const vers = await Promise.all(tagsToRegister.map(tag => this._getTagVersion(tag)));
2803
3028
  activeTagVersions = {};
2804
- for (let i = 0; i < opts.tags.length; i++) {
2805
- activeTagVersions[opts.tags[i]] = vers[i];
3029
+ for (let i = 0; i < tagsToRegister.length; i++) {
3030
+ activeTagVersions[tagsToRegister[i]] = vers[i];
2806
3031
  }
2807
3032
  } else {
2808
- await this._registerTags(k, opts.tags, ttlSeconds);
3033
+ await this._registerTags(k, tagsToRegister, ttlSeconds);
2809
3034
  }
2810
3035
  }
2811
3036
 
2812
- this.l1.set(k, data, ttlMs, p, undefined, undefined, activeTagVersions);
3037
+ const writeTs = Date.now();
3038
+ this.l1.set(k, data, ttlMs, p, undefined, undefined, activeTagVersions, writeTs);
2813
3039
 
2814
3040
  // Register dependency patterns: when any key matching a pattern is deleted,
2815
3041
  // this key (k) is automatically cascaded.
2816
- if (opts?.dependsOn?.length) {
2817
- for (const pattern of opts.dependsOn) {
2818
- const nsPattern = this.nk(pattern);
2819
- let deps = this.dependencyIndex.get(nsPattern);
2820
- if (!deps) { deps = new Set(); this.dependencyIndex.set(nsPattern, deps); }
2821
- deps.add(k);
3042
+ if (opts?.dependsOn !== undefined) {
3043
+ this._removeKeyDependencies(k);
3044
+ if (opts.dependsOn.length > 0) {
3045
+ const nsPatterns: string[] = [];
3046
+ for (const pattern of opts.dependsOn) {
3047
+ const nsPattern = this.nk(pattern);
3048
+ nsPatterns.push(nsPattern);
3049
+ let deps = this.dependencyIndex.get(nsPattern);
3050
+ if (!deps) { deps = new Set(); this.dependencyIndex.set(nsPattern, deps); }
3051
+ deps.add(k);
3052
+ }
3053
+ this.keyDependencies.set(k, nsPatterns);
2822
3054
  }
2823
3055
  }
2824
3056
 
@@ -2828,13 +3060,12 @@ export class CacheService {
2828
3060
  const s = JSON.stringify(data);
2829
3061
  const stored = await this._serializeAndEncrypt(s);
2830
3062
  const ttlSec = Math.ceil(ttlMs / 1_000);
2831
- if (this.opts.tagStrategy === 'generational' && activeTagVersions) {
2832
- const now = Date.now();
3063
+ if (this.opts.tagStrategy === 'generational' && (activeTagVersions || (!this.opts.autoPipeline && typeof (client as any).hgetall === 'function'))) {
2833
3064
  const tx = client.multi();
2834
3065
  tx.hset(k, {
2835
3066
  d: stored,
2836
- t: String(now),
2837
- tv: JSON.stringify(activeTagVersions),
3067
+ t: String(writeTs),
3068
+ tv: JSON.stringify(activeTagVersions ?? {}),
2838
3069
  });
2839
3070
  tx.expire(k, ttlSec);
2840
3071
  await tx.exec();
@@ -2871,20 +3102,32 @@ export class CacheService {
2871
3102
  * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
2872
3103
  */
2873
3104
  private async _registerTags(k: string, tags: string[], ttlSeconds: number): Promise<void> {
2874
- for (const tag of tags) {
3105
+ this._removeKeyTags(k);
3106
+ const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
3107
+ const expiresAt = Date.now() + effectiveTtl * 1_000;
3108
+ if (this.keyTags.size >= 100_000 && !this.keyTags.has(k)) {
3109
+ this._sweepExpiredMetadata();
3110
+ if (this.keyTags.size >= 100_000) {
3111
+ const oldestKey = this.keyTags.keys().next().value;
3112
+ if (oldestKey !== undefined) this._removeKeyTags(oldestKey);
3113
+ }
3114
+ }
3115
+ const uniqueTags = Array.from(new Set(tags));
3116
+ for (const tag of uniqueTags) {
2875
3117
  const tagKey = this.nk(`_tag_:${tag}`);
2876
3118
  let members = this.tagIndex.get(tagKey);
2877
3119
  if (!members) { members = new Set(); this.tagIndex.set(tagKey, members); }
2878
3120
  members.add(k);
2879
3121
  }
3122
+ this.keyTags.set(k, { tags: uniqueTags, expiresAt });
2880
3123
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
2881
3124
  try {
2882
3125
  const client = await this.getRedis();
2883
3126
  const pl = client.pipeline();
2884
- for (const tag of tags) {
3127
+ for (const tag of uniqueTags) {
2885
3128
  const tagKey = this.nk(`_tag_:${tag}`);
2886
3129
  pl.sadd(tagKey, k);
2887
- pl.expire(tagKey, ttlSeconds + 3_600);
3130
+ pl.expire(tagKey, effectiveTtl + 3_600);
2888
3131
  }
2889
3132
  await pl.exec();
2890
3133
  this.cb.onSuccess();
@@ -2923,6 +3166,13 @@ export class CacheService {
2923
3166
  }
2924
3167
  this._addPatternTombstone(pfx);
2925
3168
  this.l1.deletePattern(k);
3169
+ this._removePrefixFromIndices(pfx);
3170
+ for (const ktKey of Array.from(this.keyTags.keys())) {
3171
+ if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
3172
+ }
3173
+ for (const kdKey of Array.from(this.keyDependencies.keys())) {
3174
+ if (this._matchesGlob(kdKey, k)) this._removeKeyDependencies(kdKey);
3175
+ }
2926
3176
  } else {
2927
3177
  this._bumpKeyMutation(k);
2928
3178
  this.inflight.delete(k);
@@ -2935,10 +3185,11 @@ export class CacheService {
2935
3185
  this._pendingDiskDeletes.delete(k);
2936
3186
  }
2937
3187
  });
3188
+ this._removeKeyTags(k);
2938
3189
  // Cascade: invalidate any key that declared it depends on this exact key's pattern
2939
3190
  this._cascadeDependencies(k);
2940
3191
  // Clean up: remove k from all dependency registrations (it is gone)
2941
- for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
3192
+ this._removeKeyDependencies(k);
2942
3193
  }
2943
3194
 
2944
3195
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
@@ -2946,7 +3197,7 @@ export class CacheService {
2946
3197
  const client = await this.getRedis();
2947
3198
  if (isPattern) {
2948
3199
  const keys = await this._scanKeys(client, k);
2949
- if (keys.length > 0) await client.del(...keys);
3200
+ await this._deleteRedisKeys(client, keys);
2950
3201
  } else {
2951
3202
  if (this.opts.autoPipeline && this.pipeliner) {
2952
3203
  await this.pipeliner.del(k);
@@ -3012,6 +3263,15 @@ export class CacheService {
3012
3263
  entry.value++;
3013
3264
  return entry.value;
3014
3265
  }
3266
+ if (this._l1Counters.size >= 50_000 && !this._l1Counters.has(k)) {
3267
+ for (const [ck, cv] of this._l1Counters) {
3268
+ if (cv.expiresAt <= now) this._l1Counters.delete(ck);
3269
+ }
3270
+ if (this._l1Counters.size >= 50_000) {
3271
+ const oldest = this._l1Counters.keys().next().value;
3272
+ if (oldest !== undefined) this._l1Counters.delete(oldest);
3273
+ }
3274
+ }
3015
3275
  this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
3016
3276
  return 1;
3017
3277
  }
@@ -3064,6 +3324,7 @@ export class CacheService {
3064
3324
  }
3065
3325
  this._addPatternTombstone(pfx);
3066
3326
  this.l1.deletePattern(k);
3327
+ this._removePrefixFromIndices(pfx);
3067
3328
  } else {
3068
3329
  this._globalEpoch++;
3069
3330
  this.inflight.clear();
@@ -3072,7 +3333,10 @@ export class CacheService {
3072
3333
  if (!this._diskDisabled) this.disk.clear();
3073
3334
  this._l1Counters.clear();
3074
3335
  this.tagIndex.clear();
3336
+ this.keyTags.clear();
3075
3337
  this.tagVersions.clear();
3338
+ this.dependencyIndex.clear();
3339
+ this.keyDependencies.clear();
3076
3340
  this._pendingDiskDeletes.clear();
3077
3341
  this._keyMutationEpochs.clear();
3078
3342
  }
@@ -3082,7 +3346,7 @@ export class CacheService {
3082
3346
  const client = await this.getRedis();
3083
3347
  const pattern = k ?? (this._namespace ? `${this._namespace}:*` : '*');
3084
3348
  const keys = await this._scanKeys(client, pattern);
3085
- if (keys.length > 0) await client.del(...keys);
3349
+ await this._deleteRedisKeys(client, keys);
3086
3350
  } catch (err) {
3087
3351
  this.logger.debug('clear: Redis unavailable', { error: (err as Error).message });
3088
3352
  }
@@ -3227,6 +3491,10 @@ export class CacheService {
3227
3491
  this._assertActive('touch');
3228
3492
  const k = this.nk(cacheKey);
3229
3493
  const hit = this.l1.touch(k, newTtlSeconds * 1_000);
3494
+ if (hit) {
3495
+ const kt = this.keyTags.get(k);
3496
+ if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1_000;
3497
+ }
3230
3498
  if (hit && !this._redisDisabled) {
3231
3499
  try {
3232
3500
  const client = await this.getRedis();
@@ -3255,6 +3523,13 @@ export class CacheService {
3255
3523
  return (entry.value !== undefined ? entry.value : this.codec.decode(entry.data)) as T;
3256
3524
  }
3257
3525
 
3526
+ private _prepareReadValue<T>(val: T): T {
3527
+ if (this.opts.frozen) deepFreeze(val);
3528
+ return (this.opts.cloneStrategy === 'structuredClone' && val != null && typeof val === 'object')
3529
+ ? structuredClone(val)
3530
+ : val;
3531
+ }
3532
+
3258
3533
  /**
3259
3534
  * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
3260
3535
  * Returns the cached value if found and valid, or `null` if absent / expired.
@@ -3270,13 +3545,13 @@ export class CacheService {
3270
3545
  // 1. L1 RAM
3271
3546
  const l1Hit = this.l1.get(k);
3272
3547
  if (l1Hit !== null) {
3273
- this.counters.gets++;
3274
- this.counters.l1Hits++;
3275
- const val = l1Hit.value as T;
3276
- if (this.opts.frozen) deepFreeze(val);
3277
- return (this.opts.cloneStrategy === 'structuredClone' && val != null && typeof val === 'object')
3278
- ? structuredClone(val)
3279
- : val;
3548
+ if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
3549
+ this._deleteIfStale(k, l1Hit.setAt ?? 0);
3550
+ } else {
3551
+ this.counters.gets++;
3552
+ this.counters.l1Hits++;
3553
+ return this._prepareReadValue(l1Hit.value as T);
3554
+ }
3280
3555
  }
3281
3556
 
3282
3557
  // 2. L1.5 Disk
@@ -3284,51 +3559,48 @@ export class CacheService {
3284
3559
  if (this._isTombstonedByPattern(k)) {
3285
3560
  try { this.disk.delete(k); } catch { /* ok */ }
3286
3561
  } else if (this.watchdog.isDiskAllowed()) {
3287
- const diskStart = performance.now();
3288
- const diskHit = this.disk.load(k);
3289
- const diskElapsed = performance.now() - diskStart;
3290
- this.watchdog.recordDisk(diskElapsed);
3291
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
3292
-
3293
- if (diskHit !== null) {
3294
- const promoted = this.l1.importEntries(
3295
- [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
3296
- this.opts.forbiddenSnapshotPrefixes,
3297
- );
3298
- if (promoted > 0) {
3299
- const l1Check = this.l1.get(k);
3300
- if (l1Check !== null) {
3301
- this.counters.gets++;
3302
- this.counters.diskHits++;
3303
- const val = l1Check.value as T;
3304
- if (this.opts.frozen) deepFreeze(val);
3305
- return (this.opts.cloneStrategy === 'structuredClone' && val != null && typeof val === 'object')
3306
- ? structuredClone(val)
3307
- : val;
3562
+ const diskStart = performance.now();
3563
+ const diskHit = this.disk.load(k);
3564
+ const diskElapsed = performance.now() - diskStart;
3565
+ this.watchdog.recordDisk(diskElapsed);
3566
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
3567
+
3568
+ if (diskHit !== null) {
3569
+ if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
3570
+ this.disk.delete(k);
3571
+ } else {
3572
+ const promoted = this.l1.importEntries(
3573
+ [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
3574
+ this.opts.forbiddenSnapshotPrefixes,
3575
+ );
3576
+ if (promoted > 0) {
3577
+ const l1Check = this.l1.get(k);
3578
+ if (l1Check !== null) {
3579
+ this.counters.gets++;
3580
+ this.counters.diskHits++;
3581
+ return this._prepareReadValue(l1Check.value as T);
3582
+ }
3583
+ }
3308
3584
  }
3309
3585
  }
3310
3586
  }
3311
3587
  }
3312
- }
3313
3588
 
3314
3589
  // 3. L2 Redis
3315
3590
  if (!this._redisDisabled && !this.cb.isOpen) {
3316
3591
  try {
3317
3592
  const client = await this.getRedis();
3318
3593
  const redisStart = performance.now();
3319
- const raw = await client.get(k);
3594
+ const redisHit = await this._readRedisEntry<T>(client, k);
3320
3595
  const redisElapsed = performance.now() - redisStart;
3321
3596
  this.watchdog.recordRedis(redisElapsed);
3322
- if (raw !== null) {
3323
- const parsed = await this._decryptAndDeserialize<T>(raw);
3324
- this.l1.set(k, parsed, 60_000, inferPriority(cacheKey));
3597
+ this.cb.onSuccess();
3598
+ if (redisHit && !redisHit.stale && redisHit.value !== undefined) {
3599
+ const parsed = redisHit.value;
3600
+ this.l1.set(k, parsed, 60_000, inferPriority(cacheKey), undefined, undefined, redisHit.tagVersions);
3325
3601
  this.counters.gets++;
3326
3602
  this.counters.l2Hits++;
3327
- this.cb.onSuccess();
3328
- if (this.opts.frozen) deepFreeze(parsed);
3329
- return (this.opts.cloneStrategy === 'structuredClone' && parsed != null && typeof parsed === 'object')
3330
- ? structuredClone(parsed)
3331
- : parsed;
3603
+ return this._prepareReadValue(parsed);
3332
3604
  }
3333
3605
  } catch (err) {
3334
3606
  this.cb.onFailure();
@@ -3350,7 +3622,7 @@ export class CacheService {
3350
3622
  */
3351
3623
  async mget<T>(
3352
3624
  keys: string[],
3353
- fetchFn: (missKeys: string[]) => Promise<Record<string, T>>,
3625
+ fetchFn?: (missKeys: string[]) => Promise<Record<string, T> | Map<string, T>>,
3354
3626
  ttl: number | ((key: string) => number) = 300,
3355
3627
  priority?: CachePriority,
3356
3628
  ): Promise<(T | undefined)[]> {
@@ -3365,12 +3637,20 @@ export class CacheService {
3365
3637
  const missKeys: string[] = [];
3366
3638
 
3367
3639
  // ── Tier 1: L1 (in-memory) ──
3640
+ const now = Date.now();
3368
3641
  for (let i = 0; i < keys.length; i++) {
3369
3642
  const k = this.nk(keys[i]);
3370
3643
  const entry = this.l1.getEntry(k);
3371
- if (entry && entry.expiresAt > Date.now()) {
3372
- result[i] = (entry.value !== undefined ? entry.value : this.codec.decode(entry.data)) as T;
3373
- this.counters.l1Hits++;
3644
+ if (entry && entry.expiresAt > now) {
3645
+ if (await this._isGenerationalEntryStale(entry.tagVersions)) {
3646
+ this._deleteIfStale(k, entry.setAt ?? 0);
3647
+ missIndexes.push(i);
3648
+ missKeys.push(keys[i]);
3649
+ } else {
3650
+ const val = (entry.value !== undefined ? entry.value : this.codec.decode(entry.data)) as T;
3651
+ result[i] = this._prepareReadValue(val);
3652
+ this.counters.l1Hits++;
3653
+ }
3374
3654
  } else {
3375
3655
  missIndexes.push(i);
3376
3656
  missKeys.push(keys[i]);
@@ -3394,23 +3674,61 @@ export class CacheService {
3394
3674
  const client = await this.getRedis();
3395
3675
  const nsKeys = missKeys.map(k => this.nk(k));
3396
3676
  const pipeline = client.multi();
3397
- for (const nk of nsKeys) pipeline.get(nk);
3677
+ const useHashPipeline = this.opts.tagStrategy === 'generational' && typeof (pipeline as any).hgetall === 'function';
3678
+ for (const nk of nsKeys) {
3679
+ if (useHashPipeline) {
3680
+ (pipeline as any).hgetall(nk);
3681
+ } else {
3682
+ pipeline.get(nk);
3683
+ }
3684
+ }
3398
3685
  const redisStart = performance.now();
3399
- const raws = await pipeline.exec() as Array<[Error | null, string | null] | null>;
3686
+ const raws = await pipeline.exec() as Array<[Error | null, any] | null>;
3400
3687
  const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
3401
3688
  this.watchdog.recordRedis(redisElapsed);
3402
3689
  this.cb.onSuccess();
3690
+
3403
3691
  for (let j = 0; j < missKeys.length; j++) {
3404
- const raw = raws[j] ? (raws[j] as [Error | null, string | null])[1] : null;
3692
+ const tuple = raws[j];
3693
+ const err = tuple ? tuple[0] : null;
3694
+ const rawVal = tuple ? tuple[1] : null;
3405
3695
  const idx = missIndexes[j];
3406
- if (raw) {
3407
- const parsed = await this._decryptAndDeserialize<T>(raw);
3408
- const k = nsKeys[j];
3696
+ const k = nsKeys[j];
3697
+
3698
+ let parsed: T | undefined;
3699
+ let tagVersions: Record<string, number> | undefined;
3700
+ let hit = false;
3701
+
3702
+ if (useHashPipeline) {
3703
+ if (err && err.message?.includes('WRONGTYPE')) {
3704
+ const fallbackRaw = await client.get(k);
3705
+ if (fallbackRaw) {
3706
+ parsed = await this._decryptAndDeserialize<T>(fallbackRaw);
3707
+ hit = true;
3708
+ }
3709
+ } else if (!err && typeof rawVal === 'string') {
3710
+ parsed = await this._decryptAndDeserialize<T>(rawVal);
3711
+ hit = true;
3712
+ } else if (!err && rawVal && typeof rawVal === 'object' && rawVal.d) {
3713
+ const hashHit = await this._parseGenerationalRedisHash<T>(k, rawVal);
3714
+ if (hashHit && !hashHit.stale && hashHit.value !== undefined) {
3715
+ parsed = hashHit.value;
3716
+ tagVersions = hashHit.tagVersions;
3717
+ hit = true;
3718
+ }
3719
+ }
3720
+ } else if (!err && rawVal) {
3721
+ parsed = await this._decryptAndDeserialize<T>(rawVal);
3722
+ hit = true;
3723
+ }
3724
+
3725
+ if (hit && parsed !== undefined) {
3409
3726
  const p = priority ?? inferPriority(missKeys[j]);
3410
- this.l1.set(k, parsed, this._jitterTtl((typeof ttl === 'function' ? ttl(missKeys[j]) : ttl) * 1_000), p);
3727
+ const ttlVal = typeof ttl === 'function' ? ttl(missKeys[j]) : ttl;
3728
+ this.l1.set(k, parsed, this._jitterTtl(ttlVal * 1_000), p, undefined, undefined, tagVersions);
3411
3729
  this.counters.l2Hits++;
3412
3730
  l2HitCount++;
3413
- result[idx] = parsed;
3731
+ result[idx] = this._prepareReadValue(parsed);
3414
3732
  missIndexes[j] = -1;
3415
3733
  missKeys[j] = '';
3416
3734
  }
@@ -3443,6 +3761,10 @@ export class CacheService {
3443
3761
  this.watchdog.recordDisk(diskElapsed);
3444
3762
  this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
3445
3763
  if (diskHit !== null) {
3764
+ if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
3765
+ this.disk.delete(k);
3766
+ continue;
3767
+ }
3446
3768
  const promoted = this.l1.importEntries(
3447
3769
  [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
3448
3770
  this.opts.forbiddenSnapshotPrefixes,
@@ -3451,7 +3773,7 @@ export class CacheService {
3451
3773
  const l1Check = this.l1.get(k);
3452
3774
  if (l1Check !== null) {
3453
3775
  this.counters.diskHits++;
3454
- result[missIndexes[j]] = l1Check.value as T;
3776
+ result[missIndexes[j]] = this._prepareReadValue(l1Check.value as T);
3455
3777
  missIndexes.splice(j, 1);
3456
3778
  missKeys.splice(j, 1);
3457
3779
  }
@@ -3461,16 +3783,24 @@ export class CacheService {
3461
3783
  }
3462
3784
 
3463
3785
  // ── Tier 3: fetchFn for whatever still missed ──
3464
- if (missKeys.length > 0) {
3786
+ if (missKeys.length > 0 && fetchFn) {
3465
3787
  this.counters.fetches++;
3466
3788
  const fetched = await fetchFn(missKeys);
3789
+ const isMap = fetched instanceof Map;
3467
3790
  const setPromises: Promise<void>[] = [];
3468
3791
  for (let j = 0; j < missKeys.length; j++) {
3469
- const v = fetched[missKeys[j]];
3792
+ const k = missKeys[j];
3793
+ const v = isMap ? (fetched as Map<string, T>).get(k) : (fetched as Record<string, T>)[k];
3470
3794
  result[missIndexes[j]] = v;
3471
- if (v !== undefined) {
3472
- const resolvedTtl = typeof ttl === 'function' ? ttl(missKeys[j]) : ttl;
3473
- setPromises.push(this.set(missKeys[j], v, resolvedTtl, priority));
3795
+ if (v !== undefined && v !== null) {
3796
+ const resolvedTtl = typeof ttl === 'function' ? ttl(k) : ttl;
3797
+ setPromises.push(this.set(k, v, resolvedTtl, priority));
3798
+ } else if (v == null && this.opts.notFoundTtl > 0) {
3799
+ // Negative caching: cache null/missing records with notFoundTtl to protect origin DB
3800
+ setPromises.push(this.set(k, null as unknown as T, this.opts.notFoundTtl, priority));
3801
+ } else if (v === null) {
3802
+ const resolvedTtl = typeof ttl === 'function' ? ttl(k) : ttl;
3803
+ setPromises.push(this.set(k, null as unknown as T, resolvedTtl, priority));
3474
3804
  }
3475
3805
  }
3476
3806
  if (setPromises.length > 0) {
@@ -3628,102 +3958,163 @@ export class CacheService {
3628
3958
  }
3629
3959
 
3630
3960
  /**
3631
- * Invalidate all keys associated with a tag.
3632
- * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
3633
- *
3634
- * @example
3635
- * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
3636
- * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
3961
+ * Discovers all concrete tag names in the system that match `tag` either via
3962
+ * glob wildcards ('*' or '?') or parent-child hierarchy cascading.
3963
+ * Scans local in-memory indices (tagIndex, tagVersions, L1 entries) and Redis (if connected).
3637
3964
  */
3638
- async invalidateTag(tag: string): Promise<void> {
3639
- this._assertActive('invalidateTag');
3640
- const span = this._startSpan('tricache.invalidate_tag');
3641
- if (this.opts.tracer) {
3642
- span.setAttribute('cache.tag', tag);
3643
- span.setAttribute('cache.tag_strategy', this.opts.tagStrategy);
3965
+ private async _resolveMatchingTags(tag: string, shouldCascade: boolean): Promise<Set<string>> {
3966
+ const isPattern = isWildcardTag(tag);
3967
+ const delim = this.opts.tagHierarchyDelimiter;
3968
+ const matched = new Set<string>();
3969
+
3970
+ const tagMatches = (t: string): boolean => {
3971
+ if (t === tag) return true;
3972
+ if (isPattern && matchesTagPattern(tag, t)) return true;
3973
+ if (shouldCascade && isChildTag(tag, t, delim)) return true;
3974
+ return false;
3975
+ };
3976
+
3977
+ if (shouldCascade && !isPattern) {
3978
+ matched.add(tag);
3644
3979
  }
3645
- try {
3646
- if (this.opts.tagStrategy === 'generational') {
3647
- let newVer = 1;
3648
- if (!this._redisDisabled) {
3649
- try {
3650
- const client = await this.getRedis();
3651
- newVer = await client.incr(this.nk(`tag_ver:${tag}`));
3652
- } catch (err) {
3653
- this.logger.debug('invalidateTag: Redis unavailable', { tag, error: (err as Error).message });
3654
- const current = this.tagVersions.get(tag)?.version ?? 0;
3655
- newVer = current + 1;
3656
- }
3657
- } else {
3658
- const current = this.tagVersions.get(tag)?.version ?? 0;
3659
- newVer = current + 1;
3980
+
3981
+ // 1. Scan in-process tagIndex (set strategy)
3982
+ const tagPrefix = this.nk('_tag_:');
3983
+ for (const tagKey of this.tagIndex.keys()) {
3984
+ const t = tagKey.startsWith(tagPrefix) ? tagKey.slice(tagPrefix.length) : tagKey;
3985
+ if (tagMatches(t)) matched.add(t);
3986
+ }
3987
+
3988
+ // 2. Scan in-process tagVersions (generational strategy)
3989
+ for (const t of this.tagVersions.keys()) {
3990
+ if (tagMatches(t)) matched.add(t);
3991
+ }
3992
+
3993
+ // 3. Scan in-process L1 entries for any active tags
3994
+ this.l1.scan((_k, entry) => {
3995
+ if (entry.tagVersions) {
3996
+ for (const t of Object.keys(entry.tagVersions)) {
3997
+ if (tagMatches(t)) matched.add(t);
3660
3998
  }
3661
- this._setLocalTagVersion(tag, newVer, performance.now());
3662
- if (this.opts.awaitInvalidationBackplane) {
3663
- await this.publishInvalidation('tag_incr', tag, newVer, false, true);
3999
+ }
4000
+ }, 0);
4001
+
4002
+ // 4. Scan Redis if connected
4003
+ if (!this._redisDisabled) {
4004
+ try {
4005
+ const client = await this.getRedis();
4006
+ if (this.opts.tagStrategy === 'generational') {
4007
+ const redisPattern = isPattern
4008
+ ? this.nk(`tag_ver:${tag}`)
4009
+ : this.nk(`tag_ver:${tag}${delim}*`);
4010
+ const scannedKeys = await this._scanKeys(client, redisPattern);
4011
+ const pfx = this.nk('tag_ver:');
4012
+ for (const sk of scannedKeys) {
4013
+ const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
4014
+ if (tagMatches(t)) matched.add(t);
4015
+ }
3664
4016
  } else {
3665
- void this.publishInvalidation('tag_incr', tag, newVer, false, true);
4017
+ const redisPattern = isPattern
4018
+ ? this.nk(`_tag_:${tag}`)
4019
+ : this.nk(`_tag_:${tag}${delim}*`);
4020
+ const scannedKeys = await this._scanKeys(client, redisPattern);
4021
+ const pfx = this.nk('_tag_:');
4022
+ for (const sk of scannedKeys) {
4023
+ const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
4024
+ if (tagMatches(t)) matched.add(t);
4025
+ }
3666
4026
  }
3667
- return;
4027
+ } catch (err) {
4028
+ this.logger.debug('_resolveMatchingTags: Redis scan failed', { tag, error: (err as Error).message });
3668
4029
  }
4030
+ }
3669
4031
 
3670
- const tagKey = this.nk(`_tag_:${tag}`);
3671
- const members = this.tagIndex.get(tagKey) ?? new Set<string>();
4032
+ return matched;
4033
+ }
3672
4034
 
3673
- // Remove from L1 + disk
3674
- for (const k of members) {
3675
- this.l1.delete(k);
3676
- this._bumpKeyMutation(k);
3677
- this._pendingDiskDeletes.add(k);
3678
- setImmediate(() => {
3679
- try {
3680
- if (!this._diskDisabled) this.disk.delete(k);
3681
- } finally {
3682
- this._pendingDiskDeletes.delete(k);
3683
- }
3684
- });
3685
- }
3686
- this.tagIndex.delete(tagKey);
4035
+ private async _publishTagInvalidation(
4036
+ op: 'tag_incr' | 'tag_pattern_incr' | 'tag_pattern_del',
4037
+ key: string,
4038
+ tagVersion?: number,
4039
+ ): Promise<void> {
4040
+ if (this.opts.awaitInvalidationBackplane) {
4041
+ await this.publishInvalidation(op, key, tagVersion, false, true);
4042
+ } else {
4043
+ void this.publishInvalidation(op, key, tagVersion, false, true);
4044
+ }
4045
+ }
4046
+
4047
+ private _removeTagMembersLocal(keys: Iterable<string>): void {
4048
+ const keyList = Array.isArray(keys) ? keys : Array.from(keys);
4049
+ for (const k of keyList) {
4050
+ this.l1.delete(k);
4051
+ this._bumpKeyMutation(k);
4052
+ this._removeKeyTags(k);
4053
+ this._removeKeyDependencies(k);
4054
+ this._pendingDiskDeletes.add(k);
4055
+ setImmediate(() => {
4056
+ try {
4057
+ if (!this._diskDisabled) this.disk.delete(k);
4058
+ } finally {
4059
+ this._pendingDiskDeletes.delete(k);
4060
+ }
4061
+ });
4062
+ }
4063
+ }
3687
4064
 
4065
+ /**
4066
+ * Executes invalidation for a single already-resolved concrete tag without
4067
+ * wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
4068
+ */
4069
+ private async _invalidateConcreteTag(tag: string): Promise<void> {
4070
+ if (this.opts.tagStrategy === 'generational') {
4071
+ let newVer = 1;
3688
4072
  if (!this._redisDisabled) {
3689
4073
  try {
3690
4074
  const client = await this.getRedis();
3691
- const redisMembers: string[] = await client.smembers(tagKey);
3692
- const toDelete = [...new Set([...members, ...redisMembers])];
3693
- if (toDelete.length > 0) {
3694
- await client.del(...toDelete, tagKey);
3695
- } else {
3696
- await client.del(tagKey);
3697
- }
4075
+ newVer = await client.incr(this.nk(`tag_ver:${tag}`));
3698
4076
  } catch (err) {
3699
4077
  this.logger.debug('invalidateTag: Redis unavailable', { tag, error: (err as Error).message });
4078
+ const current = this.tagVersions.get(tag)?.version ?? 0;
4079
+ newVer = current + 1;
3700
4080
  }
4081
+ } else {
4082
+ const current = this.tagVersions.get(tag)?.version ?? 0;
4083
+ newVer = current + 1;
4084
+ }
4085
+ this._setLocalTagVersion(tag, newVer, performance.now());
4086
+ await this._publishTagInvalidation('tag_incr', tag, newVer);
4087
+ return;
4088
+ }
4089
+
4090
+ const tagKey = this.nk(`_tag_:${tag}`);
4091
+ const members = Array.from(this.tagIndex.get(tagKey) ?? []);
4092
+
4093
+ this.tagIndex.delete(tagKey);
4094
+ this._removeTagMembersLocal(members);
4095
+
4096
+ if (!this._redisDisabled) {
4097
+ try {
4098
+ const client = await this.getRedis();
4099
+ const redisMembers: string[] = await client.smembers(tagKey);
4100
+ const toDelete = [...new Set([...members, ...redisMembers, tagKey])];
4101
+ await this._deleteRedisKeys(client, toDelete);
4102
+ } catch (err) {
4103
+ this.logger.debug('invalidateTag: Redis unavailable', { tag, error: (err as Error).message });
3701
4104
  }
3702
- } catch (err) {
3703
- span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
3704
- span.recordException?.(err);
3705
- throw err;
3706
- } finally {
3707
- span.end();
3708
4105
  }
3709
4106
  }
3710
4107
 
3711
4108
  /**
3712
- * Invalidate all keys associated with any of the given tags in a single operation.
3713
- * Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
3714
- * reducing latency when invalidating several related tags together.
3715
- *
3716
- * Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
3717
- * synchronously before the Redis round-trip.
3718
- *
3719
- * @example
3720
- * // Instead of three serial round-trips:
3721
- * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
4109
+ * Executes invalidation for an array of already-resolved concrete tags
4110
+ * without re-entering wildcard/cascade resolution or invalidateTag().
3722
4111
  */
3723
- async invalidateTags(tags: string[]): Promise<void> {
3724
- this._assertActive('invalidateTags');
4112
+ private async _invalidateConcreteTags(tags: string[]): Promise<void> {
3725
4113
  if (tags.length === 0) return;
3726
- if (tags.length === 1) { await this.invalidateTag(tags[0]); return; }
4114
+ if (tags.length === 1) {
4115
+ await this._invalidateConcreteTag(tags[0]);
4116
+ return;
4117
+ }
3727
4118
 
3728
4119
  if (this.opts.tagStrategy === 'generational') {
3729
4120
  const now = performance.now();
@@ -3737,11 +4128,7 @@ export class CacheService {
3737
4128
  const [err, newVer] = results[i] ?? [null, null];
3738
4129
  const ver = (!err && typeof newVer === 'number') ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
3739
4130
  this._setLocalTagVersion(tags[i], ver, now);
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
- }
4131
+ await this._publishTagInvalidation('tag_incr', tags[i], ver);
3745
4132
  }
3746
4133
  return;
3747
4134
  } catch (err) {
@@ -3751,11 +4138,7 @@ export class CacheService {
3751
4138
  for (const tag of tags) {
3752
4139
  const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
3753
4140
  this._setLocalTagVersion(tag, ver, now);
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
- }
4141
+ await this._publishTagInvalidation('tag_incr', tag, ver);
3759
4142
  }
3760
4143
  return;
3761
4144
  }
@@ -3770,18 +4153,7 @@ export class CacheService {
3770
4153
  for (const k of members) allMembers.add(k);
3771
4154
  this.tagIndex.delete(tagKey);
3772
4155
  }
3773
- for (const k of allMembers) {
3774
- this.l1.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
- });
3784
- }
4156
+ this._removeTagMembersLocal(allMembers);
3785
4157
 
3786
4158
  if (!this._redisDisabled) {
3787
4159
  try {
@@ -3798,15 +4170,120 @@ export class CacheService {
3798
4170
  for (const k of redisMembers) { if (!allMembers.has(k)) toDelete.push(k); }
3799
4171
  }
3800
4172
  }
3801
- // Single DEL for all member keys + tag keys
4173
+ // Chunk/cluster-safe DEL for all member keys + tag keys
3802
4174
  const keysToRemove = [...toDelete, ...tagKeys];
3803
- if (keysToRemove.length > 0) await client.del(...keysToRemove);
4175
+ await this._deleteRedisKeys(client, keysToRemove);
3804
4176
  } catch (err) {
3805
4177
  this.logger.debug('invalidateTags: Redis unavailable', { tags, error: (err as Error).message });
3806
4178
  }
3807
4179
  }
3808
4180
  }
3809
4181
 
4182
+ /**
4183
+ * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
4184
+ * Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
4185
+ *
4186
+ * @param tag Tag name or wildcard glob pattern (e.g. `'catalog'`, `'org:123:*'`, `'*:comments'`).
4187
+ * @param opts Optional invalidation options, including `{ cascade: true }` to invalidate child namespaces.
4188
+ *
4189
+ * @example
4190
+ * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
4191
+ * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
4192
+ *
4193
+ * @example
4194
+ * // Wildcard pattern invalidation
4195
+ * await cache.invalidateTag('org:123:*');
4196
+ *
4197
+ * @example
4198
+ * // Hierarchical tag cascading (clears 'org:123' and all child tags like 'org:123:dept:456')
4199
+ * await cache.invalidateTag('org:123', { cascade: true });
4200
+ */
4201
+ async invalidateTag(tag: string, opts?: InvalidateTagOptions): Promise<void> {
4202
+ this._assertActive('invalidateTag');
4203
+ const span = this._startSpan('tricache.invalidate_tag');
4204
+ if (this.opts.tracer) {
4205
+ span.setAttribute('cache.tag', tag);
4206
+ span.setAttribute('cache.tag_strategy', this.opts.tagStrategy);
4207
+ if (opts?.cascade) span.setAttribute('cache.cascade', true);
4208
+ }
4209
+ try {
4210
+ const isPattern = isWildcardTag(tag);
4211
+ const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
4212
+
4213
+ if (isPattern || shouldCascade) {
4214
+ const matchedTags = await this._resolveMatchingTags(tag, shouldCascade);
4215
+ const delim = this.opts.tagHierarchyDelimiter;
4216
+ const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
4217
+
4218
+ if (matchedTags.size > 0) {
4219
+ await this._invalidateConcreteTags(Array.from(matchedTags));
4220
+ }
4221
+
4222
+ // Broadcast wildcard invalidation across backplane and cross-region
4223
+ const op = this.opts.tagStrategy === 'generational' ? 'tag_pattern_incr' : 'tag_pattern_del';
4224
+ await this._publishTagInvalidation(op, broadcastPattern);
4225
+ return;
4226
+ }
4227
+
4228
+ // Fast-path: single discrete tag
4229
+ await this._invalidateConcreteTag(tag);
4230
+ } catch (err) {
4231
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
4232
+ span.recordException?.(err);
4233
+ throw err;
4234
+ } finally {
4235
+ span.end();
4236
+ }
4237
+ }
4238
+
4239
+ /**
4240
+ * Invalidate all keys associated with any of the given tags in a single operation.
4241
+ * Supports discrete tags, wildcard glob patterns, and hierarchical cascading.
4242
+ * Combines multiple tag invalidations into Redis pipeline round-trips.
4243
+ *
4244
+ * @param tags Array of tag names or wildcard patterns (e.g. `['case:acme', 'org:*']`).
4245
+ * @param opts Optional invalidation options, including `{ cascade: true }`.
4246
+ *
4247
+ * @example
4248
+ * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:*']);
4249
+ */
4250
+ async invalidateTags(tags: string[], opts?: InvalidateTagOptions): Promise<void> {
4251
+ this._assertActive('invalidateTags');
4252
+ if (tags.length === 0) return;
4253
+
4254
+ const hasWildcards = tags.some(t => isWildcardTag(t));
4255
+ const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
4256
+
4257
+ if (hasWildcards || shouldCascade) {
4258
+ const allResolvedTags = new Set<string>();
4259
+ const broadcastPatterns = new Set<string>();
4260
+ const delim = this.opts.tagHierarchyDelimiter;
4261
+
4262
+ for (const t of tags) {
4263
+ const tIsPattern = isWildcardTag(t);
4264
+ if (tIsPattern || shouldCascade) {
4265
+ broadcastPatterns.add(tIsPattern ? t : `${t}${delim}*`);
4266
+ const resolved = await this._resolveMatchingTags(t, shouldCascade);
4267
+ for (const rt of resolved) allResolvedTags.add(rt);
4268
+ } else {
4269
+ allResolvedTags.add(t);
4270
+ }
4271
+ }
4272
+
4273
+ if (allResolvedTags.size > 0) {
4274
+ await this._invalidateConcreteTags(Array.from(allResolvedTags));
4275
+ }
4276
+
4277
+ const op = this.opts.tagStrategy === 'generational' ? 'tag_pattern_incr' : 'tag_pattern_del';
4278
+ for (const pattern of broadcastPatterns) {
4279
+ await this._publishTagInvalidation(op, pattern);
4280
+ }
4281
+ return;
4282
+ }
4283
+
4284
+ await this._invalidateConcreteTags(Array.from(new Set(tags)));
4285
+ }
4286
+
3810
4287
  /**
3811
4288
  * Get the current generational tag version for a tag (synced with Redis when due).
3812
4289
  */
@@ -4439,6 +4916,13 @@ export class CacheService {
4439
4916
  this._destroyed = true;
4440
4917
  this._pendingDiskDeletes.clear();
4441
4918
  this._keyMutationEpochs.clear();
4919
+ this.inflight.clear();
4920
+ this.revalidating.clear();
4921
+ this._l1Counters.clear();
4922
+ this.tagIndex.clear();
4923
+ this.keyTags.clear();
4924
+ this.dependencyIndex.clear();
4925
+ this.keyDependencies.clear();
4442
4926
  const g = globalThis as Record<string, unknown>;
4443
4927
  const key = CacheService.globalKey(this.opts);
4444
4928
  if (g[key] === this) {