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
@@ -1914,13 +1914,38 @@ var import_os2 = __toESM(require("os"), 1);
1914
1914
 
1915
1915
  // src/compression.ts
1916
1916
  var import_zlib = __toESM(require("zlib"), 1);
1917
+ var import_lz4js = __toESM(require("lz4js"), 1);
1918
+ var import_zstd_codec = require("zstd-codec");
1917
1919
  var PREFIX_COMPRESSED = "cmp:v1:";
1918
1920
  var PREFIX_ENC_COMPRESSED = "ecp:v1:";
1919
1921
  var COMPRESSION_MAGIC = Buffer.from([84, 82, 67, 1]);
1922
+ var zstdSimple = null;
1923
+ var zstdInitPromise = null;
1924
+ function initZstd() {
1925
+ if (zstdSimple) return Promise.resolve(zstdSimple);
1926
+ if (!zstdInitPromise) {
1927
+ zstdInitPromise = new Promise((resolve) => {
1928
+ try {
1929
+ import_zstd_codec.ZstdCodec.run((zstd) => {
1930
+ zstdSimple = new zstd.Simple();
1931
+ resolve(zstdSimple);
1932
+ });
1933
+ } catch {
1934
+ resolve(null);
1935
+ }
1936
+ });
1937
+ }
1938
+ return zstdInitPromise;
1939
+ }
1940
+ initZstd().catch(() => {
1941
+ });
1920
1942
  function isCompressed(buf) {
1921
1943
  return buf.length >= 4 && buf[0] === 84 && buf[1] === 82 && buf[2] === 67 && buf[3] === 1;
1922
1944
  }
1923
- function compressBuffer(buf, algorithm) {
1945
+ function compressBuffer(buf, algorithm, custom) {
1946
+ if (custom) {
1947
+ return custom.compress(buf);
1948
+ }
1924
1949
  if (algorithm === "brotli") {
1925
1950
  return import_zlib.default.brotliCompressSync(buf, {
1926
1951
  params: {
@@ -1932,37 +1957,127 @@ function compressBuffer(buf, algorithm) {
1932
1957
  if (algorithm === "gzip") {
1933
1958
  return import_zlib.default.gzipSync(buf, { level: 6 });
1934
1959
  }
1960
+ if (algorithm === "lz4") {
1961
+ return Buffer.from(import_lz4js.default.compress(buf));
1962
+ }
1963
+ if (algorithm === "zstd") {
1964
+ if (!zstdSimple) {
1965
+ return import_zlib.default.brotliCompressSync(buf, {
1966
+ params: { [import_zlib.default.constants.BROTLI_PARAM_QUALITY]: 4 }
1967
+ });
1968
+ }
1969
+ return Buffer.from(zstdSimple.compress(buf));
1970
+ }
1935
1971
  return buf;
1936
1972
  }
1937
- function decompressBuffer(buf, algorithm = "brotli") {
1973
+ var MAX_DECOMPRESS_BYTES = 25 * 1024 * 1024;
1974
+ function decompressBuffer(buf, algorithm = "zstd", custom) {
1975
+ if (custom) {
1976
+ const res = custom.decompress(buf);
1977
+ if (res.length > MAX_DECOMPRESS_BYTES) {
1978
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
1979
+ }
1980
+ return res;
1981
+ }
1982
+ const checkSafety = (decomp) => {
1983
+ if (decomp.length > MAX_DECOMPRESS_BYTES) {
1984
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
1985
+ }
1986
+ return decomp;
1987
+ };
1988
+ if (buf.length >= 4 && buf[0] === 40 && buf[1] === 181 && buf[2] === 47 && buf[3] === 253) {
1989
+ if (zstdSimple) {
1990
+ try {
1991
+ return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
1992
+ } catch (err) {
1993
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
1994
+ }
1995
+ }
1996
+ }
1997
+ if (buf.length >= 4 && buf[0] === 4 && buf[1] === 34 && buf[2] === 77 && buf[3] === 24) {
1998
+ try {
1999
+ return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
2000
+ } catch (err) {
2001
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
2002
+ }
2003
+ }
2004
+ if (buf.length >= 2 && buf[0] === 31 && buf[1] === 139) {
2005
+ try {
2006
+ return import_zlib.default.gunzipSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
2007
+ } catch (err) {
2008
+ if (err?.code === "ERR_BUFFER_TOO_LARGE") {
2009
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
2010
+ }
2011
+ }
2012
+ }
2013
+ if (algorithm === "none") {
2014
+ return buf;
2015
+ }
2016
+ if (algorithm === "lz4") {
2017
+ try {
2018
+ return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
2019
+ } catch (err) {
2020
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
2021
+ }
2022
+ }
2023
+ if (algorithm === "zstd" && zstdSimple) {
2024
+ try {
2025
+ return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
2026
+ } catch (err) {
2027
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
2028
+ }
2029
+ }
1938
2030
  const tryBrotli = () => {
1939
2031
  try {
1940
- return import_zlib.default.brotliDecompressSync(buf);
1941
- } catch {
2032
+ return import_zlib.default.brotliDecompressSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
2033
+ } catch (err) {
2034
+ if (err?.code === "ERR_BUFFER_TOO_LARGE") {
2035
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
2036
+ }
1942
2037
  return null;
1943
2038
  }
1944
2039
  };
1945
2040
  const tryGzip = () => {
1946
2041
  try {
1947
- return import_zlib.default.gunzipSync(buf);
1948
- } catch {
2042
+ return import_zlib.default.gunzipSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
2043
+ } catch (err) {
2044
+ if (err?.code === "ERR_BUFFER_TOO_LARGE") {
2045
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
2046
+ }
2047
+ return null;
2048
+ }
2049
+ };
2050
+ const tryLz4 = () => {
2051
+ try {
2052
+ return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
2053
+ } catch (err) {
2054
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
2055
+ return null;
2056
+ }
2057
+ };
2058
+ const tryZstd = () => {
2059
+ if (!zstdSimple) return null;
2060
+ try {
2061
+ return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
2062
+ } catch (err) {
2063
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
1949
2064
  return null;
1950
2065
  }
1951
2066
  };
1952
- const result = algorithm === "gzip" ? tryGzip() ?? tryBrotli() : tryBrotli() ?? tryGzip();
2067
+ const result = (algorithm === "gzip" ? tryGzip() : null) ?? (algorithm === "lz4" ? tryLz4() : null) ?? (algorithm === "zstd" ? tryZstd() : null) ?? tryBrotli() ?? tryGzip() ?? tryLz4() ?? tryZstd();
1953
2068
  if (result === null) {
1954
2069
  throw new Error(`tricache: corrupt compressed payload (${buf.length} bytes, algorithm=${algorithm})`);
1955
2070
  }
1956
2071
  return result;
1957
2072
  }
1958
- function compressWithHeader(buf, algorithm) {
2073
+ function compressWithHeader(buf, algorithm, custom) {
1959
2074
  if (algorithm === "none") return buf;
1960
- const compressed = compressBuffer(buf, algorithm);
2075
+ const compressed = compressBuffer(buf, algorithm, custom);
1961
2076
  return Buffer.concat([COMPRESSION_MAGIC, compressed]);
1962
2077
  }
1963
- function decompressWithHeader(buf, algorithm = "brotli") {
2078
+ function decompressWithHeader(buf, algorithm = "zstd", custom) {
1964
2079
  if (isCompressed(buf)) {
1965
- return decompressBuffer(buf.subarray(4), algorithm);
2080
+ return decompressBuffer(buf.subarray(4), algorithm, custom);
1966
2081
  }
1967
2082
  return buf;
1968
2083
  }
@@ -3577,6 +3692,55 @@ var IpcTelemetryServer = class {
3577
3692
  }
3578
3693
  };
3579
3694
 
3695
+ // src/utils/tag-matcher.ts
3696
+ var globRegexCache = /* @__PURE__ */ new Map();
3697
+ function isWildcardTag(tag) {
3698
+ return tag.includes("*") || tag.includes("?");
3699
+ }
3700
+ function matchesTagPattern(pattern, tag) {
3701
+ if (pattern === "*" || pattern === tag) return true;
3702
+ if (!pattern.includes("*") && !pattern.includes("?")) return pattern === tag;
3703
+ if (pattern.endsWith("*") && !pattern.slice(0, -1).includes("*") && !pattern.includes("?")) {
3704
+ const prefix = pattern.slice(0, -1);
3705
+ return tag.startsWith(prefix);
3706
+ }
3707
+ if (pattern.startsWith("*") && !pattern.slice(1).includes("*") && !pattern.includes("?")) {
3708
+ const suffix = pattern.slice(1);
3709
+ return tag.endsWith(suffix);
3710
+ }
3711
+ let re = globRegexCache.get(pattern);
3712
+ if (!re) {
3713
+ if (globRegexCache.size >= 1e3) globRegexCache.clear();
3714
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
3715
+ re = new RegExp(`^${escaped}$`);
3716
+ globRegexCache.set(pattern, re);
3717
+ }
3718
+ return re.test(tag);
3719
+ }
3720
+ function isChildTag(parentTag, candidateTag, delimiter = ":") {
3721
+ if (candidateTag === parentTag) return true;
3722
+ const prefix = parentTag.endsWith(delimiter) ? parentTag : `${parentTag}${delimiter}`;
3723
+ return candidateTag.startsWith(prefix);
3724
+ }
3725
+ function expandHierarchicalTags(tags, delimiter = ":") {
3726
+ if (!tags.length) return [];
3727
+ const result = /* @__PURE__ */ new Set();
3728
+ for (const tag of tags) {
3729
+ if (!tag) continue;
3730
+ const parts = tag.split(delimiter).filter((p) => p.length > 0);
3731
+ if (parts.length <= 1) {
3732
+ result.add(tag);
3733
+ continue;
3734
+ }
3735
+ let accumulated = "";
3736
+ for (let i = 0; i < parts.length; i++) {
3737
+ accumulated = i === 0 ? parts[i] : `${accumulated}${delimiter}${parts[i]}`;
3738
+ result.add(accumulated);
3739
+ }
3740
+ }
3741
+ return Array.from(result);
3742
+ }
3743
+
3580
3744
  // src/cache-service.ts
3581
3745
  var LUA_COMPARE_AND_DELETE = `
3582
3746
  local currentTs = redis.call('HGET', KEYS[1], 't')
@@ -3595,21 +3759,21 @@ var DEFAULT_CATEGORY_LIMITS = {
3595
3759
  var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
3596
3760
  var DEFAULT_COUNTER_TTL_SECONDS = 60;
3597
3761
  var GLOB_REGEX_CACHE_MAX = 256;
3598
- var globRegexCache = /* @__PURE__ */ new Map();
3762
+ var globRegexCache2 = /* @__PURE__ */ new Map();
3599
3763
  function getGlobRegex(pattern) {
3600
- let re = globRegexCache.get(pattern);
3764
+ let re = globRegexCache2.get(pattern);
3601
3765
  if (re) {
3602
- globRegexCache.delete(pattern);
3603
- globRegexCache.set(pattern, re);
3766
+ globRegexCache2.delete(pattern);
3767
+ globRegexCache2.set(pattern, re);
3604
3768
  return re;
3605
3769
  }
3606
3770
  const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*+/g, ".*");
3607
3771
  re = new RegExp("^" + escaped + "$");
3608
- if (globRegexCache.size >= GLOB_REGEX_CACHE_MAX) {
3609
- const oldestKey = globRegexCache.keys().next().value;
3610
- if (oldestKey !== void 0) globRegexCache.delete(oldestKey);
3772
+ if (globRegexCache2.size >= GLOB_REGEX_CACHE_MAX) {
3773
+ const oldestKey = globRegexCache2.keys().next().value;
3774
+ if (oldestKey !== void 0) globRegexCache2.delete(oldestKey);
3611
3775
  }
3612
- globRegexCache.set(pattern, re);
3776
+ globRegexCache2.set(pattern, re);
3613
3777
  return re;
3614
3778
  }
3615
3779
  var L2CircuitBreaker = class {
@@ -3863,6 +4027,7 @@ var CacheService = class _CacheService {
3863
4027
  opts;
3864
4028
  /** Pre-computed once — opts.namespace never changes after construction. */
3865
4029
  _namespace;
4030
+ prefixLen;
3866
4031
  /** Pre-computed once — disableRedis and redisHost never change after construction. */
3867
4032
  _redisDisabled;
3868
4033
  watchdog;
@@ -3902,6 +4067,52 @@ var CacheService = class _CacheService {
3902
4067
  streamClient = null;
3903
4068
  _lastStreamId = "$";
3904
4069
  _destroyed = false;
4070
+ _pendingDiskDeletes = /* @__PURE__ */ new Set();
4071
+ _globalEpoch = 0;
4072
+ _keyMutationEpochs = /* @__PURE__ */ new Map();
4073
+ /**
4074
+ * Pattern tombstones for disk tier.
4075
+ * Files in the disk tier are keyed by SHA-256 of namespacedKey.
4076
+ * Wildcard pattern deletes cannot scan the filesystem synchronously, so we maintain
4077
+ * pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
4078
+ */
4079
+ _patternTombstones = [];
4080
+ _addPatternTombstone(prefix) {
4081
+ const now = Date.now();
4082
+ while (this._patternTombstones.length > 0 && now - this._patternTombstones[0].createdAt > 36e5) {
4083
+ this._patternTombstones.shift();
4084
+ }
4085
+ if (this._patternTombstones.length >= 2e3) {
4086
+ this._patternTombstones.shift();
4087
+ }
4088
+ this._patternTombstones.push({ prefix, createdAt: now });
4089
+ }
4090
+ _isTombstonedByPattern(namespacedKey) {
4091
+ if (this._patternTombstones.length === 0) return false;
4092
+ for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
4093
+ if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
4094
+ return true;
4095
+ }
4096
+ }
4097
+ return false;
4098
+ }
4099
+ _assertActive(operation) {
4100
+ if (this._destroyed) {
4101
+ throw new Error(`TriCacheError: Cannot perform '${operation}' on a destroyed CacheService instance (namespace: '${this._namespace || "(default)"}').`);
4102
+ }
4103
+ }
4104
+ _bumpKeyMutation(namespacedKey) {
4105
+ const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
4106
+ this._keyMutationEpochs.set(namespacedKey, next);
4107
+ if (this._keyMutationEpochs.size > 5e4) {
4108
+ const oldest = this._keyMutationEpochs.keys().next().value;
4109
+ if (oldest !== void 0) this._keyMutationEpochs.delete(oldest);
4110
+ }
4111
+ return next;
4112
+ }
4113
+ _getKeyMutationEpoch(namespacedKey) {
4114
+ return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
4115
+ }
3905
4116
  _ipcServer;
3906
4117
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
3907
4118
  _subDisconnectedAt = null;
@@ -3990,6 +4201,8 @@ var CacheService = class _CacheService {
3990
4201
  ),
3991
4202
  snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
3992
4203
  invalidationBackplane: options.invalidationBackplane ?? true,
4204
+ awaitInvalidationBackplane: options.awaitInvalidationBackplane ?? false,
4205
+ lockFailClosed: options.lockFailClosed ?? false,
3993
4206
  oomProtection: options.oomProtection ?? true,
3994
4207
  oomHeapThreshold: options.oomHeapThreshold ?? 0.85,
3995
4208
  oomCheckIntervalMs: options.oomCheckIntervalMs ?? 1e4,
@@ -4023,12 +4236,15 @@ var CacheService = class _CacheService {
4023
4236
  redisSentinel: options.redisSentinel,
4024
4237
  redisProtocol: options.redisProtocol,
4025
4238
  useShardedPubSub: options.useShardedPubSub ?? false,
4026
- compression: options.compression ?? "none",
4239
+ compression: options.compression ?? "zstd",
4240
+ customCompressor: options.customCompressor,
4027
4241
  compressionThresholdBytes: options.compressionThresholdBytes ?? 1024,
4028
4242
  strictSingleton: options.strictSingleton ?? false,
4029
4243
  failClosed: options.failClosed ?? false,
4030
4244
  tagStrategy: options.tagStrategy ?? "set",
4031
4245
  tagVersionTtlMs: options.tagVersionTtlMs ?? 5e3,
4246
+ hierarchicalTags: options.hierarchicalTags ?? false,
4247
+ tagHierarchyDelimiter: options.tagHierarchyDelimiter ?? ":",
4032
4248
  cloneStrategy: options.cloneStrategy ?? "none",
4033
4249
  backplaneMode: options.backplaneMode ?? "pubsub",
4034
4250
  backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
@@ -4101,6 +4317,7 @@ var CacheService = class _CacheService {
4101
4317
  diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs
4102
4318
  });
4103
4319
  this._namespace = ns;
4320
+ this.prefixLen = ns ? ns.length + 1 : 0;
4104
4321
  this._redisDisabled = this.opts.disableRedis || !this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
4105
4322
  this.watchdog = new TierLatencyWatchdog({
4106
4323
  enabled: options.diskLatencyWatchdog ?? true,
@@ -4210,6 +4427,9 @@ var CacheService = class _CacheService {
4210
4427
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
4211
4428
  this.initBackplane();
4212
4429
  const startupPromises = [];
4430
+ if (this.opts.compression === "zstd") {
4431
+ startupPromises.push(initZstd().then(() => void 0));
4432
+ }
4213
4433
  if (this.opts.remoteSnapshot) {
4214
4434
  startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
4215
4435
  }
@@ -4355,7 +4575,9 @@ var CacheService = class _CacheService {
4355
4575
  "adaptiveTtl",
4356
4576
  "l2WriteMode",
4357
4577
  "instanceName",
4358
- "invalidationBackplane"
4578
+ "invalidationBackplane",
4579
+ "awaitInvalidationBackplane",
4580
+ "lockFailClosed"
4359
4581
  ];
4360
4582
  /** Returns the names of options that differ between `a` and the live `b`. */
4361
4583
  static optionsDiff(a, b) {
@@ -4396,6 +4618,8 @@ var CacheService = class _CacheService {
4396
4618
  frozen: o.frozen,
4397
4619
  adaptiveTtl: o.adaptiveTtl,
4398
4620
  invalidationBackplane: o.invalidationBackplane,
4621
+ awaitInvalidationBackplane: o.awaitInvalidationBackplane,
4622
+ lockFailClosed: o.lockFailClosed,
4399
4623
  strictSingleton: o.strictSingleton,
4400
4624
  remoteSnapshot: o.remoteSnapshot,
4401
4625
  crossRegion: o.crossRegion
@@ -4681,16 +4905,80 @@ var CacheService = class _CacheService {
4681
4905
  _applyInvalidationEvent(op, key, tagVersion) {
4682
4906
  if (op === "del") {
4683
4907
  this.l1.delete(key);
4908
+ this._bumpKeyMutation(key);
4909
+ this.inflight.delete(key);
4910
+ this._pendingDiskDeletes.add(key);
4684
4911
  setImmediate(() => {
4685
- if (!this._diskDisabled) this.disk.delete(key);
4912
+ try {
4913
+ if (!this._diskDisabled) this.disk.delete(key);
4914
+ } finally {
4915
+ this._pendingDiskDeletes.delete(key);
4916
+ }
4686
4917
  });
4687
4918
  this._cascadeDependencies(key);
4688
4919
  } else if (op === "del-glob") {
4689
4920
  this.l1.deletePattern(key);
4921
+ const pfx = key.endsWith("*") ? key.slice(0, -1) : key;
4922
+ for (const liveKey of this.l1.liveKeys()) {
4923
+ if (liveKey.startsWith(pfx)) {
4924
+ this._bumpKeyMutation(liveKey);
4925
+ }
4926
+ }
4927
+ for (const inflightKey of Array.from(this.inflight.keys())) {
4928
+ if (inflightKey.startsWith(pfx)) {
4929
+ this._bumpKeyMutation(inflightKey);
4930
+ this.inflight.delete(inflightKey);
4931
+ }
4932
+ }
4933
+ this._addPatternTombstone(pfx);
4690
4934
  } else if (op === "tag_incr") {
4691
4935
  const tag = key;
4692
4936
  const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
4693
- this._setLocalTagVersion(tag, ver, Date.now());
4937
+ this._setLocalTagVersion(tag, ver, performance.now());
4938
+ } else if (op === "tag_pattern_incr") {
4939
+ const pattern = key;
4940
+ const now = performance.now();
4941
+ for (const [tag, info] of this.tagVersions) {
4942
+ if (matchesTagPattern(pattern, tag)) {
4943
+ this._setLocalTagVersion(tag, info.version + 1, now);
4944
+ }
4945
+ }
4946
+ this.l1.scan((k, entry) => {
4947
+ if (entry.tagVersions) {
4948
+ for (const tag of Object.keys(entry.tagVersions)) {
4949
+ if (matchesTagPattern(pattern, tag)) {
4950
+ this.l1.delete(k);
4951
+ this._bumpKeyMutation(k);
4952
+ break;
4953
+ }
4954
+ }
4955
+ }
4956
+ }, 0);
4957
+ } else if (op === "tag_pattern_del") {
4958
+ const pattern = key;
4959
+ const matchedTagKeys = [];
4960
+ const prefix = this.nk("_tag_:");
4961
+ for (const [tagKey, members] of this.tagIndex) {
4962
+ const tag = tagKey.startsWith(prefix) ? tagKey.slice(prefix.length) : tagKey;
4963
+ if (matchesTagPattern(pattern, tag)) {
4964
+ matchedTagKeys.push(tagKey);
4965
+ for (const k of members) {
4966
+ this.l1.delete(k);
4967
+ this._bumpKeyMutation(k);
4968
+ this._pendingDiskDeletes.add(k);
4969
+ setImmediate(() => {
4970
+ try {
4971
+ if (!this._diskDisabled) this.disk.delete(k);
4972
+ } finally {
4973
+ this._pendingDiskDeletes.delete(k);
4974
+ }
4975
+ });
4976
+ }
4977
+ }
4978
+ }
4979
+ for (const tagKey of matchedTagKeys) {
4980
+ this.tagIndex.delete(tagKey);
4981
+ }
4694
4982
  }
4695
4983
  this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
4696
4984
  }
@@ -4698,7 +4986,7 @@ var CacheService = class _CacheService {
4698
4986
  _handleBackplaneMessage(message) {
4699
4987
  try {
4700
4988
  const msg = JSON.parse(message);
4701
- if (!msg || typeof msg !== "object" || Array.isArray(msg) || typeof msg.src !== "string" || typeof msg.key !== "string" || msg.op !== "del" && msg.op !== "del-glob" && msg.op !== "tag_incr") {
4989
+ if (!msg || typeof msg !== "object" || Array.isArray(msg) || typeof msg.src !== "string" || typeof msg.key !== "string" || msg.op !== "del" && msg.op !== "del-glob" && msg.op !== "tag_incr" && msg.op !== "tag_pattern_incr" && msg.op !== "tag_pattern_del") {
4702
4990
  this.logger.warn("Backplane: rejected invalid pubsub message format", {
4703
4991
  raw: typeof message === "string" ? message.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(message)
4704
4992
  });
@@ -4718,7 +5006,11 @@ var CacheService = class _CacheService {
4718
5006
  if (!isCrossRegionRelay && this.opts.crossRegion) {
4719
5007
  const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
4720
5008
  if (shouldBroadcast) {
4721
- void this._broadcastCrossRegion(op, key, tagVersion);
5009
+ if (this.opts.awaitInvalidationBackplane) {
5010
+ await this._broadcastCrossRegion(op, key, tagVersion);
5011
+ } else {
5012
+ void this._broadcastCrossRegion(op, key, tagVersion);
5013
+ }
4722
5014
  }
4723
5015
  }
4724
5016
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
@@ -4759,7 +5051,11 @@ var CacheService = class _CacheService {
4759
5051
  );
4760
5052
  }
4761
5053
  this.counters.invSent++;
4762
- } catch {
5054
+ } catch (err) {
5055
+ this.logger.warn("Backplane invalidation publish failed", { op, key, error: err.message });
5056
+ if (this.opts.awaitInvalidationBackplane) {
5057
+ throw err;
5058
+ }
4763
5059
  }
4764
5060
  }
4765
5061
  _markCrossRegionEventSeen(id) {
@@ -4877,12 +5173,12 @@ var CacheService = class _CacheService {
4877
5173
  * Offloads to worker thread if pool is active and payload exceeds threshold.
4878
5174
  */
4879
5175
  async _serializeAndEncrypt(serialized) {
4880
- const isCompressed2 = this.opts.compression && this.opts.compression !== "none" && serialized.length > this.opts.compressionThresholdBytes;
4881
- if (this._workerPool && (this.enc.isEnabled || isCompressed2) && serialized.length > this.opts.workerThresholdBytes) {
5176
+ const isCompressed2 = (this.opts.customCompressor || this.opts.compression && this.opts.compression !== "none") && serialized.length > this.opts.compressionThresholdBytes;
5177
+ if (this._workerPool && !this.opts.customCompressor && (this.enc.isEnabled || isCompressed2) && serialized.length > this.opts.workerThresholdBytes) {
4882
5178
  return this._workerPool.encrypt(serialized);
4883
5179
  }
4884
5180
  if (isCompressed2) {
4885
- const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression);
5181
+ const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression, this.opts.customCompressor);
4886
5182
  if (this.enc.isEnabled) {
4887
5183
  const encrypted = this.enc.encryptBuffer(compressed);
4888
5184
  return PREFIX_ENC_COMPRESSED + encrypted.toString("base64");
@@ -4897,16 +5193,16 @@ var CacheService = class _CacheService {
4897
5193
  */
4898
5194
  async _decryptAndDeserialize(raw) {
4899
5195
  let plain;
4900
- if (this._workerPool && raw.length > this.opts.workerThresholdBytes) {
5196
+ if (this._workerPool && !this.opts.customCompressor && raw.length > this.opts.workerThresholdBytes) {
4901
5197
  plain = await this._workerPool.decrypt(raw);
4902
5198
  } else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
4903
5199
  const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), "base64");
4904
5200
  const decBuf = this.enc.decryptBuffer(encBuf);
4905
- const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
5201
+ const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
4906
5202
  plain = decompressed.toString("utf8");
4907
5203
  } else if (raw.startsWith(PREFIX_COMPRESSED)) {
4908
5204
  const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), "base64");
4909
- const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
5205
+ const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
4910
5206
  plain = decompressed.toString("utf8");
4911
5207
  } else if (raw.startsWith("enc:v1:") || this.enc.isEnabled) {
4912
5208
  plain = this.enc.decrypt(raw);
@@ -4963,6 +5259,7 @@ var CacheService = class _CacheService {
4963
5259
  }
4964
5260
  }
4965
5261
  async getRedis() {
5262
+ this._assertActive("getRedis");
4966
5263
  if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
4967
5264
  if (this.redis) return this.redis;
4968
5265
  if (this.redisConnecting) return this.redisConnecting;
@@ -5291,6 +5588,7 @@ var CacheService = class _CacheService {
5291
5588
  * Caches negative lookups to avoid repeated DB hits for missing keys.
5292
5589
  */
5293
5590
  async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
5591
+ this._assertActive("get");
5294
5592
  const span = this._startSpan("tricache.get");
5295
5593
  if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
5296
5594
  const k = this.nk(cacheKey);
@@ -5300,7 +5598,7 @@ var CacheService = class _CacheService {
5300
5598
  const optRefreshAhead = opts.refreshAhead;
5301
5599
  const optXfetchBeta = opts.xfetchBeta;
5302
5600
  const optNotFoundTtl = opts.notFoundTtl;
5303
- const optTags = opts.tags;
5601
+ const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
5304
5602
  const l1Hit = this.l1.get(k);
5305
5603
  if (l1Hit !== null) {
5306
5604
  let isGenerationalStale = false;
@@ -5322,7 +5620,14 @@ var CacheService = class _CacheService {
5322
5620
  if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
5323
5621
  const priority2 = optPriority ?? inferPriority(cacheKey);
5324
5622
  this.revalidating.add(k);
5325
- void this._revalidate(k, fetchFn, ttlSeconds * 1e3, swrGraceMs2, priority2);
5623
+ void this._revalidate(
5624
+ k,
5625
+ fetchFn,
5626
+ ttlSeconds * 1e3,
5627
+ swrGraceMs2,
5628
+ priority2,
5629
+ l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
5630
+ );
5326
5631
  this.counters.swrRevalidations++;
5327
5632
  this.logger.debug("SWR: serving stale, revalidating", { cacheKey });
5328
5633
  } else {
@@ -5341,7 +5646,14 @@ var CacheService = class _CacheService {
5341
5646
  if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
5342
5647
  const priority2 = optPriority ?? inferPriority(cacheKey);
5343
5648
  this.revalidating.add(k);
5344
- void this._revalidate(k, fetchFn, entryTtl, optSwr * 1e3, priority2);
5649
+ void this._revalidate(
5650
+ k,
5651
+ fetchFn,
5652
+ entryTtl,
5653
+ optSwr * 1e3,
5654
+ priority2,
5655
+ l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
5656
+ );
5345
5657
  this.counters.swrRevalidations++;
5346
5658
  this.logger.debug(
5347
5659
  shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
@@ -5367,44 +5679,52 @@ var CacheService = class _CacheService {
5367
5679
  span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
5368
5680
  return existing;
5369
5681
  }
5682
+ const mutationEpochAtStart = this._getKeyMutationEpoch(k);
5370
5683
  const executionPromise = (async () => {
5371
5684
  try {
5372
- if (!this._diskDisabled) {
5373
- const isDiskAllowed = this.watchdog.isDiskAllowed();
5374
- if (isDiskAllowed) {
5375
- const diskStart = performance.now();
5376
- const diskHit = this.disk.load(k);
5377
- const diskElapsed = performance.now() - diskStart;
5378
- this.watchdog.recordDisk(diskElapsed);
5379
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
5380
- if (diskHit !== null) {
5381
- let isDiskStale = false;
5382
- if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
5383
- const tags = Object.keys(diskHit.tagVersions);
5384
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5385
- for (let i = 0; i < tags.length; i++) {
5386
- if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
5387
- isDiskStale = true;
5388
- break;
5685
+ if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
5686
+ if (this._isTombstonedByPattern(k)) {
5687
+ try {
5688
+ this.disk.delete(k);
5689
+ } catch {
5690
+ }
5691
+ } else {
5692
+ const isDiskAllowed = this.watchdog.isDiskAllowed();
5693
+ if (isDiskAllowed) {
5694
+ const diskStart = performance.now();
5695
+ const diskHit = this.disk.load(k);
5696
+ const diskElapsed = performance.now() - diskStart;
5697
+ this.watchdog.recordDisk(diskElapsed);
5698
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
5699
+ if (diskHit !== null) {
5700
+ let isDiskStale = false;
5701
+ if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
5702
+ const tags = Object.keys(diskHit.tagVersions);
5703
+ const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5704
+ for (let i = 0; i < tags.length; i++) {
5705
+ if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
5706
+ isDiskStale = true;
5707
+ break;
5708
+ }
5389
5709
  }
5390
5710
  }
5391
- }
5392
- if (isDiskStale) {
5393
- this.disk.delete(k);
5394
- } else {
5395
- const promoted = this.l1.importEntries(
5396
- [{ key: k, entry: diskHit }],
5397
- this.opts.forbiddenSnapshotPrefixes
5398
- );
5399
- if (promoted > 0) {
5400
- const l1Check = this.l1.get(k);
5401
- if (l1Check !== null) {
5402
- this.counters.diskHits++;
5403
- this.opts.onHit?.(cacheKey, "disk");
5404
- this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
5405
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
5406
- if (this.opts.frozen) deepFreeze(l1Check.value);
5407
- return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
5711
+ if (isDiskStale) {
5712
+ this.disk.delete(k);
5713
+ } else {
5714
+ const promoted = this.l1.importEntries(
5715
+ [{ key: k, entry: diskHit }],
5716
+ this.opts.forbiddenSnapshotPrefixes
5717
+ );
5718
+ if (promoted > 0) {
5719
+ const l1Check = this.l1.get(k);
5720
+ if (l1Check !== null) {
5721
+ this.counters.diskHits++;
5722
+ this.opts.onHit?.(cacheKey, "disk");
5723
+ this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
5724
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
5725
+ if (this.opts.frozen) deepFreeze(l1Check.value);
5726
+ return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
5727
+ }
5408
5728
  }
5409
5729
  }
5410
5730
  }
@@ -5515,6 +5835,18 @@ var CacheService = class _CacheService {
5515
5835
  await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
5516
5836
  }
5517
5837
  }
5838
+ if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
5839
+ this.logger.debug("Aborting in-flight cache commit \u2014 key was mutated or deleted during fetch", { cacheKey });
5840
+ span.setAttribute("cache.aborted_mutation_race", true);
5841
+ const current = this.l1.get(k);
5842
+ if (current && !current.isStale && current.value !== void 0) {
5843
+ const freshVal = current.value;
5844
+ if (this.opts.frozen) deepFreeze(freshVal);
5845
+ return this.opts.cloneStrategy === "structuredClone" && freshVal != null && typeof freshVal === "object" ? structuredClone(freshVal) : freshVal;
5846
+ }
5847
+ if (this.opts.frozen) deepFreeze(data);
5848
+ return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
5849
+ }
5518
5850
  this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
5519
5851
  if (!this._redisDisabled) {
5520
5852
  try {
@@ -5631,22 +5963,40 @@ var CacheService = class _CacheService {
5631
5963
  const ttl = options?.ttl ?? 300;
5632
5964
  return this.get(cacheKey, fetchFn, ttl, options);
5633
5965
  }
5634
- async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
5966
+ async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority, knownTagVersions) {
5967
+ const startEpoch = this._getKeyMutationEpoch(cacheKey);
5635
5968
  try {
5636
5969
  const fetchStart = Date.now();
5637
5970
  const data = await fetchFn();
5638
5971
  const delta = Date.now() - fetchStart;
5639
5972
  const staleAt = Date.now() + ttlMs;
5973
+ if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
5974
+ this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during fetch", { cacheKey });
5975
+ return;
5976
+ }
5640
5977
  if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
5641
5978
  let activeTagVersions;
5642
5979
  const l1Existing = this.l1.get(cacheKey);
5643
- if (this.opts.tagStrategy === "generational" && l1Existing?.tagVersions) {
5644
- const tags = Object.keys(l1Existing.tagVersions);
5980
+ const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
5981
+ if (this.opts.tagStrategy === "generational" && tagVersionsSource) {
5982
+ const tags = Object.keys(tagVersionsSource);
5645
5983
  const vers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5646
5984
  activeTagVersions = {};
5647
5985
  for (let i = 0; i < tags.length; i++) {
5648
5986
  activeTagVersions[tags[i]] = vers[i];
5649
5987
  }
5988
+ if (knownTagVersions) {
5989
+ for (const t of tags) {
5990
+ if (knownTagVersions[t] !== void 0 && activeTagVersions[t] !== knownTagVersions[t]) {
5991
+ this.logger.debug("SWR: aborting revalidation commit \u2014 tag version bumped during revalidation", { cacheKey, tag: t });
5992
+ return;
5993
+ }
5994
+ }
5995
+ }
5996
+ }
5997
+ if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
5998
+ this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
5999
+ return;
5650
6000
  }
5651
6001
  this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
5652
6002
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
@@ -5690,6 +6040,7 @@ var CacheService = class _CacheService {
5690
6040
  // ── Explicit set / delete ─────────────────────────────────────────────────
5691
6041
  /** Explicitly write a value into L1 (+ L2 in production). */
5692
6042
  async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
6043
+ this._assertActive("set");
5693
6044
  const span = this._startSpan("tricache.set");
5694
6045
  if (this.opts.tracer) {
5695
6046
  span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
@@ -5700,17 +6051,21 @@ var CacheService = class _CacheService {
5700
6051
  const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
5701
6052
  const p = priority ?? inferPriority(cacheKey);
5702
6053
  const k = this.nk(cacheKey);
6054
+ this._bumpKeyMutation(k);
6055
+ this.inflight.delete(k);
6056
+ this._pendingDiskDeletes.delete(k);
5703
6057
  this.counters.sets++;
5704
6058
  let activeTagVersions;
5705
- if (opts?.tags?.length) {
6059
+ const tagsToRegister = opts?.tags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
6060
+ if (tagsToRegister?.length) {
5706
6061
  if (this.opts.tagStrategy === "generational") {
5707
- const vers = await Promise.all(opts.tags.map((tag) => this._getTagVersion(tag)));
6062
+ const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
5708
6063
  activeTagVersions = {};
5709
- for (let i = 0; i < opts.tags.length; i++) {
5710
- activeTagVersions[opts.tags[i]] = vers[i];
6064
+ for (let i = 0; i < tagsToRegister.length; i++) {
6065
+ activeTagVersions[tagsToRegister[i]] = vers[i];
5711
6066
  }
5712
6067
  } else {
5713
- await this._registerTags(k, opts.tags, ttlSeconds);
6068
+ await this._registerTags(k, tagsToRegister, ttlSeconds);
5714
6069
  }
5715
6070
  }
5716
6071
  this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
@@ -5754,7 +6109,11 @@ var CacheService = class _CacheService {
5754
6109
  this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
5755
6110
  }
5756
6111
  }
5757
- void this.publishInvalidation("del", k);
6112
+ if (this.opts.awaitInvalidationBackplane) {
6113
+ await this.publishInvalidation("del", k);
6114
+ } else {
6115
+ void this.publishInvalidation("del", k);
6116
+ }
5758
6117
  } catch (err) {
5759
6118
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
5760
6119
  span.recordException?.(err);
@@ -5801,6 +6160,7 @@ var CacheService = class _CacheService {
5801
6160
  * await cache.delete('user:abc:*'); // all keys for user abc
5802
6161
  */
5803
6162
  async delete(cacheKey) {
6163
+ this._assertActive("delete");
5804
6164
  const span = this._startSpan("tricache.delete");
5805
6165
  if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
5806
6166
  try {
@@ -5808,11 +6168,31 @@ var CacheService = class _CacheService {
5808
6168
  const k = this.nk(cacheKey);
5809
6169
  this.counters.deletes++;
5810
6170
  if (isPattern) {
6171
+ const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6172
+ for (const liveKey of this.l1.liveKeys()) {
6173
+ if (liveKey.startsWith(pfx)) {
6174
+ this._bumpKeyMutation(liveKey);
6175
+ }
6176
+ }
6177
+ for (const inflightKey of Array.from(this.inflight.keys())) {
6178
+ if (inflightKey.startsWith(pfx)) {
6179
+ this._bumpKeyMutation(inflightKey);
6180
+ this.inflight.delete(inflightKey);
6181
+ }
6182
+ }
6183
+ this._addPatternTombstone(pfx);
5811
6184
  this.l1.deletePattern(k);
5812
6185
  } else {
6186
+ this._bumpKeyMutation(k);
6187
+ this.inflight.delete(k);
5813
6188
  this.l1.delete(k);
6189
+ this._pendingDiskDeletes.add(k);
5814
6190
  setImmediate(() => {
5815
- if (!this._diskDisabled) this.disk.delete(k);
6191
+ try {
6192
+ if (!this._diskDisabled) this.disk.delete(k);
6193
+ } finally {
6194
+ this._pendingDiskDeletes.delete(k);
6195
+ }
5816
6196
  });
5817
6197
  this._cascadeDependencies(k);
5818
6198
  for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
@@ -5836,7 +6216,11 @@ var CacheService = class _CacheService {
5836
6216
  this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
5837
6217
  }
5838
6218
  }
5839
- void this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
6219
+ if (this.opts.awaitInvalidationBackplane) {
6220
+ await this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
6221
+ } else {
6222
+ void this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
6223
+ }
5840
6224
  } catch (err) {
5841
6225
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
5842
6226
  span.recordException?.(err);
@@ -5863,6 +6247,7 @@ var CacheService = class _CacheService {
5863
6247
  * fleet-wide.
5864
6248
  */
5865
6249
  async increment(cacheKey, ttlSeconds) {
6250
+ this._assertActive("increment");
5866
6251
  const k = this.nk(cacheKey);
5867
6252
  if (this._redisDisabled) {
5868
6253
  if (!this._incrementFallbackWarned) {
@@ -5904,19 +6289,38 @@ var CacheService = class _CacheService {
5904
6289
  * await cache.clear('user:abc'); // flush all keys for one user
5905
6290
  */
5906
6291
  async clear(prefix) {
6292
+ this._assertActive("clear");
5907
6293
  const span = this._startSpan("tricache.clear");
5908
6294
  if (this.opts.tracer) span.setAttribute("cache.prefix", prefix || "*");
5909
6295
  try {
5910
6296
  this.counters.deletes++;
5911
6297
  const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
5912
6298
  if (k) {
6299
+ const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6300
+ for (const liveKey of this.l1.liveKeys()) {
6301
+ if (liveKey.startsWith(pfx)) {
6302
+ this._bumpKeyMutation(liveKey);
6303
+ }
6304
+ }
6305
+ for (const inflightKey of Array.from(this.inflight.keys())) {
6306
+ if (inflightKey.startsWith(pfx)) {
6307
+ this._bumpKeyMutation(inflightKey);
6308
+ this.inflight.delete(inflightKey);
6309
+ }
6310
+ }
6311
+ this._addPatternTombstone(pfx);
5913
6312
  this.l1.deletePattern(k);
5914
6313
  } else {
6314
+ this._globalEpoch++;
6315
+ this.inflight.clear();
6316
+ this._patternTombstones.length = 0;
5915
6317
  this.l1.clear();
5916
6318
  if (!this._diskDisabled) this.disk.clear();
5917
6319
  this._l1Counters.clear();
5918
6320
  this.tagIndex.clear();
5919
6321
  this.tagVersions.clear();
6322
+ this._pendingDiskDeletes.clear();
6323
+ this._keyMutationEpochs.clear();
5920
6324
  }
5921
6325
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
5922
6326
  try {
@@ -5928,13 +6332,23 @@ var CacheService = class _CacheService {
5928
6332
  this.logger.debug("clear: Redis unavailable", { error: err.message });
5929
6333
  }
5930
6334
  }
5931
- void this.publishInvalidation(
5932
- "del-glob",
5933
- k ?? (this._namespace ? `${this._namespace}:*` : "*"),
5934
- void 0,
5935
- false,
5936
- true
5937
- );
6335
+ if (this.opts.awaitInvalidationBackplane) {
6336
+ await this.publishInvalidation(
6337
+ "del-glob",
6338
+ k ?? (this._namespace ? `${this._namespace}:*` : "*"),
6339
+ void 0,
6340
+ false,
6341
+ true
6342
+ );
6343
+ } else {
6344
+ void this.publishInvalidation(
6345
+ "del-glob",
6346
+ k ?? (this._namespace ? `${this._namespace}:*` : "*"),
6347
+ void 0,
6348
+ false,
6349
+ true
6350
+ );
6351
+ }
5938
6352
  } catch (err) {
5939
6353
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
5940
6354
  span.recordException?.(err);
@@ -5949,6 +6363,7 @@ var CacheService = class _CacheService {
5949
6363
  * Returns the number of entries evicted.
5950
6364
  */
5951
6365
  rebalance() {
6366
+ this._assertActive("rebalance");
5952
6367
  return this.l1.rebalance();
5953
6368
  }
5954
6369
  /**
@@ -5957,6 +6372,7 @@ var CacheService = class _CacheService {
5957
6372
  * Only reflects L1 state — does not query Redis or disk.
5958
6373
  */
5959
6374
  ttl(cacheKey) {
6375
+ this._assertActive("ttl");
5960
6376
  return this.l1.ttl(this.nk(cacheKey));
5961
6377
  }
5962
6378
  /**
@@ -5964,6 +6380,7 @@ var CacheService = class _CacheService {
5964
6380
  * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
5965
6381
  */
5966
6382
  has(cacheKey) {
6383
+ this._assertActive("has");
5967
6384
  return this.l1.has(this.nk(cacheKey));
5968
6385
  }
5969
6386
  // ── Iteration ─────────────────────────────────────────────────────────────
@@ -5974,6 +6391,7 @@ var CacheService = class _CacheService {
5974
6391
  * for (const key of cache.keys()) console.log(key);
5975
6392
  */
5976
6393
  *keys() {
6394
+ this._assertActive("keys");
5977
6395
  const prefix = this._namespace ? this._namespace + ":" : "";
5978
6396
  for (const key of this.l1.liveKeys()) {
5979
6397
  if (prefix && !key.startsWith(prefix)) continue;
@@ -5988,6 +6406,7 @@ var CacheService = class _CacheService {
5988
6406
  * for (const val of cache.values<User>()) console.log(val.id);
5989
6407
  */
5990
6408
  *values() {
6409
+ this._assertActive("values");
5991
6410
  const prefix = this._namespace ? this._namespace + ":" : "";
5992
6411
  if (!prefix) {
5993
6412
  yield* this.l1.liveValues();
@@ -6006,6 +6425,7 @@ var CacheService = class _CacheService {
6006
6425
  * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
6007
6426
  */
6008
6427
  *entries() {
6428
+ this._assertActive("entries");
6009
6429
  const prefix = this._namespace ? this._namespace + ":" : "";
6010
6430
  for (const [key, entry] of this.l1.liveEntries()) {
6011
6431
  if (prefix && !key.startsWith(prefix)) continue;
@@ -6033,6 +6453,7 @@ var CacheService = class _CacheService {
6033
6453
  * `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
6034
6454
  */
6035
6455
  scan(fn) {
6456
+ this._assertActive("scan");
6036
6457
  const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
6037
6458
  this.l1.scan((key, entry, pfx) => {
6038
6459
  const value = entry.value !== void 0 ? entry.value : entry.data;
@@ -6046,6 +6467,7 @@ var CacheService = class _CacheService {
6046
6467
  * @param newTtlSeconds - The new TTL from now, in seconds.
6047
6468
  */
6048
6469
  async touch(cacheKey, newTtlSeconds) {
6470
+ this._assertActive("touch");
6049
6471
  const k = this.nk(cacheKey);
6050
6472
  const hit = this.l1.touch(k, newTtlSeconds * 1e3);
6051
6473
  if (hit && !this._redisDisabled) {
@@ -6066,6 +6488,7 @@ var CacheService = class _CacheService {
6066
6488
  * if (fresh !== null) return fresh; // serve from L1, no network hop
6067
6489
  */
6068
6490
  getIfFresh(cacheKey) {
6491
+ this._assertActive("getIfFresh");
6069
6492
  const k = this.nk(cacheKey);
6070
6493
  const entry = this.l1.getEntry(k);
6071
6494
  if (!entry) return null;
@@ -6083,6 +6506,7 @@ var CacheService = class _CacheService {
6083
6506
  * const val = await cache.peek<User>('user:123');
6084
6507
  */
6085
6508
  async peek(cacheKey) {
6509
+ this._assertActive("peek");
6086
6510
  const k = this.nk(cacheKey);
6087
6511
  const l1Hit = this.l1.get(k);
6088
6512
  if (l1Hit !== null) {
@@ -6092,25 +6516,32 @@ var CacheService = class _CacheService {
6092
6516
  if (this.opts.frozen) deepFreeze(val);
6093
6517
  return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6094
6518
  }
6095
- if (!this._diskDisabled && this.watchdog.isDiskAllowed()) {
6096
- const diskStart = performance.now();
6097
- const diskHit = this.disk.load(k);
6098
- const diskElapsed = performance.now() - diskStart;
6099
- this.watchdog.recordDisk(diskElapsed);
6100
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6101
- if (diskHit !== null) {
6102
- const promoted = this.l1.importEntries(
6103
- [{ key: k, entry: diskHit }],
6104
- this.opts.forbiddenSnapshotPrefixes
6105
- );
6106
- if (promoted > 0) {
6107
- const l1Check = this.l1.get(k);
6108
- if (l1Check !== null) {
6109
- this.counters.gets++;
6110
- this.counters.diskHits++;
6111
- const val = l1Check.value;
6112
- if (this.opts.frozen) deepFreeze(val);
6113
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6519
+ if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
6520
+ if (this._isTombstonedByPattern(k)) {
6521
+ try {
6522
+ this.disk.delete(k);
6523
+ } catch {
6524
+ }
6525
+ } else if (this.watchdog.isDiskAllowed()) {
6526
+ const diskStart = performance.now();
6527
+ const diskHit = this.disk.load(k);
6528
+ const diskElapsed = performance.now() - diskStart;
6529
+ this.watchdog.recordDisk(diskElapsed);
6530
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6531
+ if (diskHit !== null) {
6532
+ const promoted = this.l1.importEntries(
6533
+ [{ key: k, entry: diskHit }],
6534
+ this.opts.forbiddenSnapshotPrefixes
6535
+ );
6536
+ if (promoted > 0) {
6537
+ const l1Check = this.l1.get(k);
6538
+ if (l1Check !== null) {
6539
+ this.counters.gets++;
6540
+ this.counters.diskHits++;
6541
+ const val = l1Check.value;
6542
+ if (this.opts.frozen) deepFreeze(val);
6543
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6544
+ }
6114
6545
  }
6115
6546
  }
6116
6547
  }
@@ -6148,6 +6579,7 @@ var CacheService = class _CacheService {
6148
6579
  * `(key) => number` so heterogeneous TTLs can be batched in one call.
6149
6580
  */
6150
6581
  async mget(keys, fetchFn, ttl = 300, priority) {
6582
+ this._assertActive("mget");
6151
6583
  const span = this._startSpan("tricache.mget");
6152
6584
  if (this.opts.tracer) {
6153
6585
  span.setAttribute("cache.batch.size", keys.length);
@@ -6216,8 +6648,16 @@ var CacheService = class _CacheService {
6216
6648
  }
6217
6649
  if (!this._diskDisabled && missKeys.length > 0) {
6218
6650
  for (let j = missKeys.length - 1; j >= 0; j--) {
6219
- if (!this.watchdog.isDiskAllowed()) continue;
6220
6651
  const k = this.nk(missKeys[j]);
6652
+ if (this._pendingDiskDeletes.has(k)) continue;
6653
+ if (this._isTombstonedByPattern(k)) {
6654
+ try {
6655
+ this.disk.delete(k);
6656
+ } catch {
6657
+ }
6658
+ continue;
6659
+ }
6660
+ if (!this.watchdog.isDiskAllowed()) continue;
6221
6661
  const diskStart = performance.now();
6222
6662
  const diskHit = this.disk.load(k);
6223
6663
  const diskElapsed = performance.now() - diskStart;
@@ -6240,16 +6680,23 @@ var CacheService = class _CacheService {
6240
6680
  }
6241
6681
  }
6242
6682
  }
6243
- if (missKeys.length > 0) {
6683
+ if (missKeys.length > 0 && fetchFn) {
6244
6684
  this.counters.fetches++;
6245
6685
  const fetched = await fetchFn(missKeys);
6686
+ const isMap = fetched instanceof Map;
6246
6687
  const setPromises = [];
6247
6688
  for (let j = 0; j < missKeys.length; j++) {
6248
- const v = fetched[missKeys[j]];
6689
+ const k = missKeys[j];
6690
+ const v = isMap ? fetched.get(k) : fetched[k];
6249
6691
  result[missIndexes[j]] = v;
6250
- if (v !== void 0) {
6251
- const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
6252
- setPromises.push(this.set(missKeys[j], v, resolvedTtl, priority));
6692
+ if (v !== void 0 && v !== null) {
6693
+ const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
6694
+ setPromises.push(this.set(k, v, resolvedTtl, priority));
6695
+ } else if (v == null && this.opts.notFoundTtl > 0) {
6696
+ setPromises.push(this.set(k, null, this.opts.notFoundTtl, priority));
6697
+ } else if (v === null) {
6698
+ const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
6699
+ setPromises.push(this.set(k, null, resolvedTtl, priority));
6253
6700
  }
6254
6701
  }
6255
6702
  if (setPromises.length > 0) {
@@ -6297,6 +6744,7 @@ var CacheService = class _CacheService {
6297
6744
  * });
6298
6745
  */
6299
6746
  async mset(entries) {
6747
+ this._assertActive("mset");
6300
6748
  const span = this._startSpan("tricache.mset");
6301
6749
  const keys = Object.keys(entries);
6302
6750
  if (this.opts.tracer) {
@@ -6324,6 +6772,7 @@ var CacheService = class _CacheService {
6324
6772
  * await cache.mdel(['user:1', 'user:2', 'user:3']);
6325
6773
  */
6326
6774
  async mdel(keys) {
6775
+ this._assertActive("mdel");
6327
6776
  const span = this._startSpan("tricache.mdel");
6328
6777
  if (this.opts.tracer) {
6329
6778
  span.setAttribute("cache.batch.size", keys.length);
@@ -6351,6 +6800,7 @@ var CacheService = class _CacheService {
6351
6800
  * console.log(`Warmed ${loaded} keys from Redis`);
6352
6801
  */
6353
6802
  async warmFromL2(pattern, opts) {
6803
+ this._assertActive("warmFromL2");
6354
6804
  if (this._redisDisabled) return 0;
6355
6805
  try {
6356
6806
  const client = await this.getRedis();
@@ -6389,20 +6839,109 @@ var CacheService = class _CacheService {
6389
6839
  }
6390
6840
  }
6391
6841
  /**
6392
- * Invalidate all keys associated with a tag.
6393
- * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
6842
+ * Discovers all concrete tag names in the system that match `tag` either via
6843
+ * glob wildcards ('*' or '?') or parent-child hierarchy cascading.
6844
+ * Scans local in-memory indices (tagIndex, tagVersions, L1 entries) and Redis (if connected).
6845
+ */
6846
+ async _resolveMatchingTags(tag, shouldCascade) {
6847
+ const isPattern = isWildcardTag(tag);
6848
+ const delim = this.opts.tagHierarchyDelimiter;
6849
+ const matched = /* @__PURE__ */ new Set();
6850
+ const tagMatches = (t) => {
6851
+ if (t === tag) return true;
6852
+ if (isPattern && matchesTagPattern(tag, t)) return true;
6853
+ if (shouldCascade && isChildTag(tag, t, delim)) return true;
6854
+ return false;
6855
+ };
6856
+ if (shouldCascade && !isPattern) {
6857
+ matched.add(tag);
6858
+ }
6859
+ const tagPrefix = this.nk("_tag_:");
6860
+ for (const tagKey of this.tagIndex.keys()) {
6861
+ const t = tagKey.startsWith(tagPrefix) ? tagKey.slice(tagPrefix.length) : tagKey;
6862
+ if (tagMatches(t)) matched.add(t);
6863
+ }
6864
+ for (const t of this.tagVersions.keys()) {
6865
+ if (tagMatches(t)) matched.add(t);
6866
+ }
6867
+ this.l1.scan((_k, entry) => {
6868
+ if (entry.tagVersions) {
6869
+ for (const t of Object.keys(entry.tagVersions)) {
6870
+ if (tagMatches(t)) matched.add(t);
6871
+ }
6872
+ }
6873
+ }, 0);
6874
+ if (!this._redisDisabled) {
6875
+ try {
6876
+ const client = await this.getRedis();
6877
+ if (this.opts.tagStrategy === "generational") {
6878
+ const redisPattern = isPattern ? this.nk(`tag_ver:${tag}`) : this.nk(`tag_ver:${tag}${delim}*`);
6879
+ const scannedKeys = await this._scanKeys(client, redisPattern);
6880
+ const pfx = this.nk("tag_ver:");
6881
+ for (const sk of scannedKeys) {
6882
+ const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
6883
+ if (tagMatches(t)) matched.add(t);
6884
+ }
6885
+ } else {
6886
+ const redisPattern = isPattern ? this.nk(`_tag_:${tag}`) : this.nk(`_tag_:${tag}${delim}*`);
6887
+ const scannedKeys = await this._scanKeys(client, redisPattern);
6888
+ const pfx = this.nk("_tag_:");
6889
+ for (const sk of scannedKeys) {
6890
+ const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
6891
+ if (tagMatches(t)) matched.add(t);
6892
+ }
6893
+ }
6894
+ } catch (err) {
6895
+ this.logger.debug("_resolveMatchingTags: Redis scan failed", { tag, error: err.message });
6896
+ }
6897
+ }
6898
+ return matched;
6899
+ }
6900
+ /**
6901
+ * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
6902
+ * Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
6903
+ *
6904
+ * @param tag Tag name or wildcard glob pattern (e.g. `'catalog'`, `'org:123:*'`, `'*:comments'`).
6905
+ * @param opts Optional invalidation options, including `{ cascade: true }` to invalidate child namespaces.
6394
6906
  *
6395
6907
  * @example
6396
6908
  * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
6397
6909
  * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
6910
+ *
6911
+ * @example
6912
+ * // Wildcard pattern invalidation
6913
+ * await cache.invalidateTag('org:123:*');
6914
+ *
6915
+ * @example
6916
+ * // Hierarchical tag cascading (clears 'org:123' and all child tags like 'org:123:dept:456')
6917
+ * await cache.invalidateTag('org:123', { cascade: true });
6398
6918
  */
6399
- async invalidateTag(tag) {
6919
+ async invalidateTag(tag, opts) {
6920
+ this._assertActive("invalidateTag");
6400
6921
  const span = this._startSpan("tricache.invalidate_tag");
6401
6922
  if (this.opts.tracer) {
6402
6923
  span.setAttribute("cache.tag", tag);
6403
6924
  span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
6925
+ if (opts?.cascade) span.setAttribute("cache.cascade", true);
6404
6926
  }
6405
6927
  try {
6928
+ const isPattern = isWildcardTag(tag);
6929
+ const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
6930
+ if (isPattern || shouldCascade) {
6931
+ const matchedTags = await this._resolveMatchingTags(tag, shouldCascade);
6932
+ const delim = this.opts.tagHierarchyDelimiter;
6933
+ const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
6934
+ if (matchedTags.size > 0) {
6935
+ await this.invalidateTags(Array.from(matchedTags));
6936
+ }
6937
+ const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
6938
+ if (this.opts.awaitInvalidationBackplane) {
6939
+ await this.publishInvalidation(op, broadcastPattern, void 0, false, true);
6940
+ } else {
6941
+ void this.publishInvalidation(op, broadcastPattern, void 0, false, true);
6942
+ }
6943
+ return;
6944
+ }
6406
6945
  if (this.opts.tagStrategy === "generational") {
6407
6946
  let newVer = 1;
6408
6947
  if (!this._redisDisabled) {
@@ -6418,15 +6957,27 @@ var CacheService = class _CacheService {
6418
6957
  const current = this.tagVersions.get(tag)?.version ?? 0;
6419
6958
  newVer = current + 1;
6420
6959
  }
6421
- this._setLocalTagVersion(tag, newVer, Date.now());
6422
- void this.publishInvalidation("tag_incr", tag, newVer, false, true);
6960
+ this._setLocalTagVersion(tag, newVer, performance.now());
6961
+ if (this.opts.awaitInvalidationBackplane) {
6962
+ await this.publishInvalidation("tag_incr", tag, newVer, false, true);
6963
+ } else {
6964
+ void this.publishInvalidation("tag_incr", tag, newVer, false, true);
6965
+ }
6423
6966
  return;
6424
6967
  }
6425
6968
  const tagKey = this.nk(`_tag_:${tag}`);
6426
6969
  const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
6427
6970
  for (const k of members) {
6428
6971
  this.l1.delete(k);
6429
- if (!this._diskDisabled) this.disk.delete(k);
6972
+ this._bumpKeyMutation(k);
6973
+ this._pendingDiskDeletes.add(k);
6974
+ setImmediate(() => {
6975
+ try {
6976
+ if (!this._diskDisabled) this.disk.delete(k);
6977
+ } finally {
6978
+ this._pendingDiskDeletes.delete(k);
6979
+ }
6980
+ });
6430
6981
  }
6431
6982
  this.tagIndex.delete(tagKey);
6432
6983
  if (!this._redisDisabled) {
@@ -6453,24 +7004,39 @@ var CacheService = class _CacheService {
6453
7004
  }
6454
7005
  /**
6455
7006
  * Invalidate all keys associated with any of the given tags in a single operation.
6456
- * Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
6457
- * reducing latency when invalidating several related tags together.
7007
+ * Supports discrete tags, wildcard glob patterns, and hierarchical cascading.
7008
+ * Combines multiple tag invalidations into Redis pipeline round-trips.
6458
7009
  *
6459
- * Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
6460
- * synchronously before the Redis round-trip.
7010
+ * @param tags Array of tag names or wildcard patterns (e.g. `['case:acme', 'org:*']`).
7011
+ * @param opts Optional invalidation options, including `{ cascade: true }`.
6461
7012
  *
6462
7013
  * @example
6463
- * // Instead of three serial round-trips:
6464
- * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
7014
+ * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:*']);
6465
7015
  */
6466
- async invalidateTags(tags) {
7016
+ async invalidateTags(tags, opts) {
7017
+ this._assertActive("invalidateTags");
6467
7018
  if (tags.length === 0) return;
7019
+ const hasWildcards = tags.some((t) => isWildcardTag(t));
7020
+ const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
7021
+ if (hasWildcards || shouldCascade) {
7022
+ const allResolvedTags = /* @__PURE__ */ new Set();
7023
+ for (const t of tags) {
7024
+ if (isWildcardTag(t) || shouldCascade) {
7025
+ const resolved = await this._resolveMatchingTags(t, shouldCascade);
7026
+ for (const rt of resolved) allResolvedTags.add(rt);
7027
+ } else {
7028
+ allResolvedTags.add(t);
7029
+ }
7030
+ }
7031
+ if (allResolvedTags.size === 0) return;
7032
+ tags = Array.from(allResolvedTags);
7033
+ }
6468
7034
  if (tags.length === 1) {
6469
- await this.invalidateTag(tags[0]);
7035
+ await this.invalidateTag(tags[0], opts);
6470
7036
  return;
6471
7037
  }
6472
7038
  if (this.opts.tagStrategy === "generational") {
6473
- const now = Date.now();
7039
+ const now = performance.now();
6474
7040
  if (!this._redisDisabled) {
6475
7041
  try {
6476
7042
  const client = await this.getRedis();
@@ -6481,7 +7047,11 @@ var CacheService = class _CacheService {
6481
7047
  const [err, newVer] = results[i] ?? [null, null];
6482
7048
  const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
6483
7049
  this._setLocalTagVersion(tags[i], ver, now);
6484
- void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7050
+ if (this.opts.awaitInvalidationBackplane) {
7051
+ await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7052
+ } else {
7053
+ void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7054
+ }
6485
7055
  }
6486
7056
  return;
6487
7057
  } catch (err) {
@@ -6491,7 +7061,11 @@ var CacheService = class _CacheService {
6491
7061
  for (const tag of tags) {
6492
7062
  const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
6493
7063
  this._setLocalTagVersion(tag, ver, now);
6494
- void this.publishInvalidation("tag_incr", tag, ver, false, true);
7064
+ if (this.opts.awaitInvalidationBackplane) {
7065
+ await this.publishInvalidation("tag_incr", tag, ver, false, true);
7066
+ } else {
7067
+ void this.publishInvalidation("tag_incr", tag, ver, false, true);
7068
+ }
6495
7069
  }
6496
7070
  return;
6497
7071
  }
@@ -6506,7 +7080,15 @@ var CacheService = class _CacheService {
6506
7080
  }
6507
7081
  for (const k of allMembers) {
6508
7082
  this.l1.delete(k);
6509
- this.disk.delete(k);
7083
+ this._bumpKeyMutation(k);
7084
+ this._pendingDiskDeletes.add(k);
7085
+ setImmediate(() => {
7086
+ try {
7087
+ if (!this._diskDisabled) this.disk.delete(k);
7088
+ } finally {
7089
+ this._pendingDiskDeletes.delete(k);
7090
+ }
7091
+ });
6510
7092
  }
6511
7093
  if (!this._redisDisabled) {
6512
7094
  try {
@@ -6543,6 +7125,7 @@ var CacheService = class _CacheService {
6543
7125
  * `l2` is `null` when Redis is disabled.
6544
7126
  */
6545
7127
  async ping() {
7128
+ this._assertActive("ping");
6546
7129
  const t0 = Date.now();
6547
7130
  this.l1.has("__ping__");
6548
7131
  const l1 = Date.now() - t0;
@@ -6622,6 +7205,7 @@ var CacheService = class _CacheService {
6622
7205
  * Returns the number of keys written.
6623
7206
  */
6624
7207
  async drainToL2() {
7208
+ this._assertActive("drainToL2");
6625
7209
  if (this._redisDisabled) return 0;
6626
7210
  try {
6627
7211
  const client = await this.getRedis();
@@ -6665,6 +7249,7 @@ var CacheService = class _CacheService {
6665
7249
  * if (!claimed) return res.status(409).json({ error: 'duplicate request' });
6666
7250
  */
6667
7251
  async setIfAbsent(cacheKey, value, ttlSeconds = 300, priority) {
7252
+ this._assertActive("setIfAbsent");
6668
7253
  const k = this.nk(cacheKey);
6669
7254
  if (this.l1.has(k)) return false;
6670
7255
  if (!this._redisDisabled) {
@@ -6683,6 +7268,8 @@ var CacheService = class _CacheService {
6683
7268
  }
6684
7269
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
6685
7270
  const p = priority ?? inferPriority(cacheKey);
7271
+ this._bumpKeyMutation(k);
7272
+ this._pendingDiskDeletes.delete(k);
6686
7273
  this.l1.set(k, value, ttlMs, p);
6687
7274
  this.counters.sets++;
6688
7275
  return true;
@@ -6701,6 +7288,7 @@ var CacheService = class _CacheService {
6701
7288
  * @param options TTL, acquire timeout, and retry polling intervals.
6702
7289
  */
6703
7290
  async lock(resourceKey, fn, options) {
7291
+ this._assertActive("lock");
6704
7292
  const ttlSeconds = Math.max(1, options?.ttl ?? 30);
6705
7293
  const acquireTimeout = Math.max(0, options?.acquireTimeout ?? 5e3);
6706
7294
  const retryInterval = Math.max(10, options?.retryInterval ?? 100);
@@ -6727,6 +7315,10 @@ var CacheService = class _CacheService {
6727
7315
  }
6728
7316
  } catch (err) {
6729
7317
  if (err.message.startsWith("Failed to acquire lock")) throw err;
7318
+ const failClosed = options?.failClosedOnRedisError ?? this.opts.lockFailClosed;
7319
+ if (failClosed) {
7320
+ throw new Error(`Distributed lock acquisition failed for resource "${resourceKey}" due to Redis error: ${err.message}`);
7321
+ }
6730
7322
  this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
6731
7323
  resourceKey,
6732
7324
  error: err.message
@@ -7072,6 +7664,7 @@ var CacheService = class _CacheService {
7072
7664
  * the previous key for seamless fallback decryption of existing cache entries.
7073
7665
  */
7074
7666
  async rotateEncryptionKey(newKeyBase64, newMode) {
7667
+ this._assertActive("rotateEncryptionKey");
7075
7668
  this.enc.rotateKey(newKeyBase64, newMode);
7076
7669
  if (this._workerPool) {
7077
7670
  await this._workerPool.drainAndReinit(this.enc.toWorkerInit());
@@ -7081,6 +7674,8 @@ var CacheService = class _CacheService {
7081
7674
  /** Close Redis connections and stop all background timers. */
7082
7675
  async destroy() {
7083
7676
  this._destroyed = true;
7677
+ this._pendingDiskDeletes.clear();
7678
+ this._keyMutationEpochs.clear();
7084
7679
  const g = globalThis;
7085
7680
  const key = _CacheService.globalKey(this.opts);
7086
7681
  if (g[key] === this) {