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
@@ -1942,10 +1942,29 @@ var init_smart_memory_cache = __esm({
1942
1942
  });
1943
1943
 
1944
1944
  // src/compression.ts
1945
+ function initZstd() {
1946
+ if (zstdSimple) return Promise.resolve(zstdSimple);
1947
+ if (!zstdInitPromise) {
1948
+ zstdInitPromise = new Promise((resolve) => {
1949
+ try {
1950
+ import_zstd_codec.ZstdCodec.run((zstd) => {
1951
+ zstdSimple = new zstd.Simple();
1952
+ resolve(zstdSimple);
1953
+ });
1954
+ } catch {
1955
+ resolve(null);
1956
+ }
1957
+ });
1958
+ }
1959
+ return zstdInitPromise;
1960
+ }
1945
1961
  function isCompressed(buf) {
1946
1962
  return buf.length >= 4 && buf[0] === 84 && buf[1] === 82 && buf[2] === 67 && buf[3] === 1;
1947
1963
  }
1948
- function compressBuffer(buf, algorithm) {
1964
+ function compressBuffer(buf, algorithm, custom) {
1965
+ if (custom) {
1966
+ return custom.compress(buf);
1967
+ }
1949
1968
  if (algorithm === "brotli") {
1950
1969
  return import_zlib.default.brotliCompressSync(buf, {
1951
1970
  params: {
@@ -1957,48 +1976,144 @@ function compressBuffer(buf, algorithm) {
1957
1976
  if (algorithm === "gzip") {
1958
1977
  return import_zlib.default.gzipSync(buf, { level: 6 });
1959
1978
  }
1979
+ if (algorithm === "lz4") {
1980
+ return Buffer.from(import_lz4js.default.compress(buf));
1981
+ }
1982
+ if (algorithm === "zstd") {
1983
+ if (!zstdSimple) {
1984
+ return import_zlib.default.brotliCompressSync(buf, {
1985
+ params: { [import_zlib.default.constants.BROTLI_PARAM_QUALITY]: 4 }
1986
+ });
1987
+ }
1988
+ return Buffer.from(zstdSimple.compress(buf));
1989
+ }
1960
1990
  return buf;
1961
1991
  }
1962
- function decompressBuffer(buf, algorithm = "brotli") {
1992
+ function decompressBuffer(buf, algorithm = "zstd", custom) {
1993
+ if (custom) {
1994
+ const res = custom.decompress(buf);
1995
+ if (res.length > MAX_DECOMPRESS_BYTES) {
1996
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
1997
+ }
1998
+ return res;
1999
+ }
2000
+ const checkSafety = (decomp) => {
2001
+ if (decomp.length > MAX_DECOMPRESS_BYTES) {
2002
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
2003
+ }
2004
+ return decomp;
2005
+ };
2006
+ if (buf.length >= 4 && buf[0] === 40 && buf[1] === 181 && buf[2] === 47 && buf[3] === 253) {
2007
+ if (zstdSimple) {
2008
+ try {
2009
+ return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
2010
+ } catch (err) {
2011
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
2012
+ }
2013
+ }
2014
+ }
2015
+ if (buf.length >= 4 && buf[0] === 4 && buf[1] === 34 && buf[2] === 77 && buf[3] === 24) {
2016
+ try {
2017
+ return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
2018
+ } catch (err) {
2019
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
2020
+ }
2021
+ }
2022
+ if (buf.length >= 2 && buf[0] === 31 && buf[1] === 139) {
2023
+ try {
2024
+ return import_zlib.default.gunzipSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
2025
+ } catch (err) {
2026
+ if (err?.code === "ERR_BUFFER_TOO_LARGE") {
2027
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
2028
+ }
2029
+ }
2030
+ }
2031
+ if (algorithm === "none") {
2032
+ return buf;
2033
+ }
2034
+ if (algorithm === "lz4") {
2035
+ try {
2036
+ return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
2037
+ } catch (err) {
2038
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
2039
+ }
2040
+ }
2041
+ if (algorithm === "zstd" && zstdSimple) {
2042
+ try {
2043
+ return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
2044
+ } catch (err) {
2045
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
2046
+ }
2047
+ }
1963
2048
  const tryBrotli = () => {
1964
2049
  try {
1965
- return import_zlib.default.brotliDecompressSync(buf);
1966
- } catch {
2050
+ return import_zlib.default.brotliDecompressSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
2051
+ } catch (err) {
2052
+ if (err?.code === "ERR_BUFFER_TOO_LARGE") {
2053
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
2054
+ }
1967
2055
  return null;
1968
2056
  }
1969
2057
  };
1970
2058
  const tryGzip = () => {
1971
2059
  try {
1972
- return import_zlib.default.gunzipSync(buf);
1973
- } catch {
2060
+ return import_zlib.default.gunzipSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
2061
+ } catch (err) {
2062
+ if (err?.code === "ERR_BUFFER_TOO_LARGE") {
2063
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
2064
+ }
1974
2065
  return null;
1975
2066
  }
1976
2067
  };
1977
- const result = algorithm === "gzip" ? tryGzip() ?? tryBrotli() : tryBrotli() ?? tryGzip();
2068
+ const tryLz4 = () => {
2069
+ try {
2070
+ return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
2071
+ } catch (err) {
2072
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
2073
+ return null;
2074
+ }
2075
+ };
2076
+ const tryZstd = () => {
2077
+ if (!zstdSimple) return null;
2078
+ try {
2079
+ return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
2080
+ } catch (err) {
2081
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
2082
+ return null;
2083
+ }
2084
+ };
2085
+ const result = (algorithm === "gzip" ? tryGzip() : null) ?? (algorithm === "lz4" ? tryLz4() : null) ?? (algorithm === "zstd" ? tryZstd() : null) ?? tryBrotli() ?? tryGzip() ?? tryLz4() ?? tryZstd();
1978
2086
  if (result === null) {
1979
2087
  throw new Error(`tricache: corrupt compressed payload (${buf.length} bytes, algorithm=${algorithm})`);
1980
2088
  }
1981
2089
  return result;
1982
2090
  }
1983
- function compressWithHeader(buf, algorithm) {
2091
+ function compressWithHeader(buf, algorithm, custom) {
1984
2092
  if (algorithm === "none") return buf;
1985
- const compressed = compressBuffer(buf, algorithm);
2093
+ const compressed = compressBuffer(buf, algorithm, custom);
1986
2094
  return Buffer.concat([COMPRESSION_MAGIC, compressed]);
1987
2095
  }
1988
- function decompressWithHeader(buf, algorithm = "brotli") {
2096
+ function decompressWithHeader(buf, algorithm = "zstd", custom) {
1989
2097
  if (isCompressed(buf)) {
1990
- return decompressBuffer(buf.subarray(4), algorithm);
2098
+ return decompressBuffer(buf.subarray(4), algorithm, custom);
1991
2099
  }
1992
2100
  return buf;
1993
2101
  }
1994
- var import_zlib, PREFIX_COMPRESSED, PREFIX_ENC_COMPRESSED, COMPRESSION_MAGIC;
2102
+ var import_zlib, import_lz4js, import_zstd_codec, PREFIX_COMPRESSED, PREFIX_ENC_COMPRESSED, COMPRESSION_MAGIC, zstdSimple, zstdInitPromise, MAX_DECOMPRESS_BYTES;
1995
2103
  var init_compression = __esm({
1996
2104
  "src/compression.ts"() {
1997
2105
  "use strict";
1998
2106
  import_zlib = __toESM(require("zlib"), 1);
2107
+ import_lz4js = __toESM(require("lz4js"), 1);
2108
+ import_zstd_codec = require("zstd-codec");
1999
2109
  PREFIX_COMPRESSED = "cmp:v1:";
2000
2110
  PREFIX_ENC_COMPRESSED = "ecp:v1:";
2001
2111
  COMPRESSION_MAGIC = Buffer.from([84, 82, 67, 1]);
2112
+ zstdSimple = null;
2113
+ zstdInitPromise = null;
2114
+ initZstd().catch(() => {
2115
+ });
2116
+ MAX_DECOMPRESS_BYTES = 25 * 1024 * 1024;
2002
2117
  }
2003
2118
  });
2004
2119
 
@@ -3648,6 +3763,61 @@ var init_ipc_telemetry = __esm({
3648
3763
  }
3649
3764
  });
3650
3765
 
3766
+ // src/utils/tag-matcher.ts
3767
+ function isWildcardTag(tag) {
3768
+ return tag.includes("*") || tag.includes("?");
3769
+ }
3770
+ function matchesTagPattern(pattern, tag) {
3771
+ if (pattern === "*" || pattern === tag) return true;
3772
+ if (!pattern.includes("*") && !pattern.includes("?")) return pattern === tag;
3773
+ if (pattern.endsWith("*") && !pattern.slice(0, -1).includes("*") && !pattern.includes("?")) {
3774
+ const prefix = pattern.slice(0, -1);
3775
+ return tag.startsWith(prefix);
3776
+ }
3777
+ if (pattern.startsWith("*") && !pattern.slice(1).includes("*") && !pattern.includes("?")) {
3778
+ const suffix = pattern.slice(1);
3779
+ return tag.endsWith(suffix);
3780
+ }
3781
+ let re = globRegexCache.get(pattern);
3782
+ if (!re) {
3783
+ if (globRegexCache.size >= 1e3) globRegexCache.clear();
3784
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
3785
+ re = new RegExp(`^${escaped}$`);
3786
+ globRegexCache.set(pattern, re);
3787
+ }
3788
+ return re.test(tag);
3789
+ }
3790
+ function isChildTag(parentTag, candidateTag, delimiter = ":") {
3791
+ if (candidateTag === parentTag) return true;
3792
+ const prefix = parentTag.endsWith(delimiter) ? parentTag : `${parentTag}${delimiter}`;
3793
+ return candidateTag.startsWith(prefix);
3794
+ }
3795
+ function expandHierarchicalTags(tags, delimiter = ":") {
3796
+ if (!tags.length) return [];
3797
+ const result = /* @__PURE__ */ new Set();
3798
+ for (const tag of tags) {
3799
+ if (!tag) continue;
3800
+ const parts = tag.split(delimiter).filter((p) => p.length > 0);
3801
+ if (parts.length <= 1) {
3802
+ result.add(tag);
3803
+ continue;
3804
+ }
3805
+ let accumulated = "";
3806
+ for (let i = 0; i < parts.length; i++) {
3807
+ accumulated = i === 0 ? parts[i] : `${accumulated}${delimiter}${parts[i]}`;
3808
+ result.add(accumulated);
3809
+ }
3810
+ }
3811
+ return Array.from(result);
3812
+ }
3813
+ var globRegexCache;
3814
+ var init_tag_matcher = __esm({
3815
+ "src/utils/tag-matcher.ts"() {
3816
+ "use strict";
3817
+ globRegexCache = /* @__PURE__ */ new Map();
3818
+ }
3819
+ });
3820
+
3651
3821
  // src/cache-service.ts
3652
3822
  var cache_service_exports = {};
3653
3823
  __export(cache_service_exports, {
@@ -3656,19 +3826,19 @@ __export(cache_service_exports, {
3656
3826
  deepMergeOptions: () => deepMergeOptions
3657
3827
  });
3658
3828
  function getGlobRegex(pattern) {
3659
- let re = globRegexCache.get(pattern);
3829
+ let re = globRegexCache2.get(pattern);
3660
3830
  if (re) {
3661
- globRegexCache.delete(pattern);
3662
- globRegexCache.set(pattern, re);
3831
+ globRegexCache2.delete(pattern);
3832
+ globRegexCache2.set(pattern, re);
3663
3833
  return re;
3664
3834
  }
3665
3835
  const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*+/g, ".*");
3666
3836
  re = new RegExp("^" + escaped + "$");
3667
- if (globRegexCache.size >= GLOB_REGEX_CACHE_MAX) {
3668
- const oldestKey = globRegexCache.keys().next().value;
3669
- if (oldestKey !== void 0) globRegexCache.delete(oldestKey);
3837
+ if (globRegexCache2.size >= GLOB_REGEX_CACHE_MAX) {
3838
+ const oldestKey = globRegexCache2.keys().next().value;
3839
+ if (oldestKey !== void 0) globRegexCache2.delete(oldestKey);
3670
3840
  }
3671
- globRegexCache.set(pattern, re);
3841
+ globRegexCache2.set(pattern, re);
3672
3842
  return re;
3673
3843
  }
3674
3844
  function deepFreeze(obj) {
@@ -3711,7 +3881,7 @@ function deepMergeOptions(base, overrides) {
3711
3881
  }
3712
3882
  return output;
3713
3883
  }
3714
- var import_ioredis, import_crypto3, import_os3, import_node_v82, import_fs3, import_path3, LUA_COMPARE_AND_DELETE, SNAPSHOT_VERSION, DEFAULT_SNAPSHOT_MAX_AGE, INDEFINITE_TTL_SECONDS, SNAPSHOT_MAX_FILE_BYTES, DEFAULT_CATEGORY_LIMITS, DEFAULT_FORBIDDEN_PREFIXES, DEFAULT_COUNTER_TTL_SECONDS, GLOB_REGEX_CACHE_MAX, globRegexCache, L2CircuitBreaker, LatencyTracker, GLOBAL_KEY, ProcessTerminationBus, CacheService;
3884
+ var import_ioredis, import_crypto3, import_os3, import_node_v82, import_fs3, import_path3, LUA_COMPARE_AND_DELETE, SNAPSHOT_VERSION, DEFAULT_SNAPSHOT_MAX_AGE, INDEFINITE_TTL_SECONDS, SNAPSHOT_MAX_FILE_BYTES, DEFAULT_CATEGORY_LIMITS, DEFAULT_FORBIDDEN_PREFIXES, DEFAULT_COUNTER_TTL_SECONDS, GLOB_REGEX_CACHE_MAX, globRegexCache2, L2CircuitBreaker, LatencyTracker, GLOBAL_KEY, ProcessTerminationBus, CacheService;
3715
3885
  var init_cache_service = __esm({
3716
3886
  "src/cache-service.ts"() {
3717
3887
  "use strict";
@@ -3732,6 +3902,7 @@ var init_cache_service = __esm({
3732
3902
  init_auto_pipeliner();
3733
3903
  init_ipc_telemetry();
3734
3904
  init_compression();
3905
+ init_tag_matcher();
3735
3906
  LUA_COMPARE_AND_DELETE = `
3736
3907
  local currentTs = redis.call('HGET', KEYS[1], 't')
3737
3908
  if currentTs and currentTs == ARGV[1] then
@@ -3749,7 +3920,7 @@ return 0
3749
3920
  DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
3750
3921
  DEFAULT_COUNTER_TTL_SECONDS = 60;
3751
3922
  GLOB_REGEX_CACHE_MAX = 256;
3752
- globRegexCache = /* @__PURE__ */ new Map();
3923
+ globRegexCache2 = /* @__PURE__ */ new Map();
3753
3924
  L2CircuitBreaker = class {
3754
3925
  constructor(threshold, cooldownMs) {
3755
3926
  this.threshold = threshold;
@@ -3961,6 +4132,7 @@ return 0
3961
4132
  opts;
3962
4133
  /** Pre-computed once — opts.namespace never changes after construction. */
3963
4134
  _namespace;
4135
+ prefixLen;
3964
4136
  /** Pre-computed once — disableRedis and redisHost never change after construction. */
3965
4137
  _redisDisabled;
3966
4138
  watchdog;
@@ -4000,6 +4172,52 @@ return 0
4000
4172
  streamClient = null;
4001
4173
  _lastStreamId = "$";
4002
4174
  _destroyed = false;
4175
+ _pendingDiskDeletes = /* @__PURE__ */ new Set();
4176
+ _globalEpoch = 0;
4177
+ _keyMutationEpochs = /* @__PURE__ */ new Map();
4178
+ /**
4179
+ * Pattern tombstones for disk tier.
4180
+ * Files in the disk tier are keyed by SHA-256 of namespacedKey.
4181
+ * Wildcard pattern deletes cannot scan the filesystem synchronously, so we maintain
4182
+ * pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
4183
+ */
4184
+ _patternTombstones = [];
4185
+ _addPatternTombstone(prefix) {
4186
+ const now = Date.now();
4187
+ while (this._patternTombstones.length > 0 && now - this._patternTombstones[0].createdAt > 36e5) {
4188
+ this._patternTombstones.shift();
4189
+ }
4190
+ if (this._patternTombstones.length >= 2e3) {
4191
+ this._patternTombstones.shift();
4192
+ }
4193
+ this._patternTombstones.push({ prefix, createdAt: now });
4194
+ }
4195
+ _isTombstonedByPattern(namespacedKey) {
4196
+ if (this._patternTombstones.length === 0) return false;
4197
+ for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
4198
+ if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
4199
+ return true;
4200
+ }
4201
+ }
4202
+ return false;
4203
+ }
4204
+ _assertActive(operation) {
4205
+ if (this._destroyed) {
4206
+ throw new Error(`TriCacheError: Cannot perform '${operation}' on a destroyed CacheService instance (namespace: '${this._namespace || "(default)"}').`);
4207
+ }
4208
+ }
4209
+ _bumpKeyMutation(namespacedKey) {
4210
+ const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
4211
+ this._keyMutationEpochs.set(namespacedKey, next);
4212
+ if (this._keyMutationEpochs.size > 5e4) {
4213
+ const oldest = this._keyMutationEpochs.keys().next().value;
4214
+ if (oldest !== void 0) this._keyMutationEpochs.delete(oldest);
4215
+ }
4216
+ return next;
4217
+ }
4218
+ _getKeyMutationEpoch(namespacedKey) {
4219
+ return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
4220
+ }
4003
4221
  _ipcServer;
4004
4222
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
4005
4223
  _subDisconnectedAt = null;
@@ -4088,6 +4306,8 @@ return 0
4088
4306
  ),
4089
4307
  snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
4090
4308
  invalidationBackplane: options.invalidationBackplane ?? true,
4309
+ awaitInvalidationBackplane: options.awaitInvalidationBackplane ?? false,
4310
+ lockFailClosed: options.lockFailClosed ?? false,
4091
4311
  oomProtection: options.oomProtection ?? true,
4092
4312
  oomHeapThreshold: options.oomHeapThreshold ?? 0.85,
4093
4313
  oomCheckIntervalMs: options.oomCheckIntervalMs ?? 1e4,
@@ -4121,12 +4341,15 @@ return 0
4121
4341
  redisSentinel: options.redisSentinel,
4122
4342
  redisProtocol: options.redisProtocol,
4123
4343
  useShardedPubSub: options.useShardedPubSub ?? false,
4124
- compression: options.compression ?? "none",
4344
+ compression: options.compression ?? "zstd",
4345
+ customCompressor: options.customCompressor,
4125
4346
  compressionThresholdBytes: options.compressionThresholdBytes ?? 1024,
4126
4347
  strictSingleton: options.strictSingleton ?? false,
4127
4348
  failClosed: options.failClosed ?? false,
4128
4349
  tagStrategy: options.tagStrategy ?? "set",
4129
4350
  tagVersionTtlMs: options.tagVersionTtlMs ?? 5e3,
4351
+ hierarchicalTags: options.hierarchicalTags ?? false,
4352
+ tagHierarchyDelimiter: options.tagHierarchyDelimiter ?? ":",
4130
4353
  cloneStrategy: options.cloneStrategy ?? "none",
4131
4354
  backplaneMode: options.backplaneMode ?? "pubsub",
4132
4355
  backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
@@ -4199,6 +4422,7 @@ return 0
4199
4422
  diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs
4200
4423
  });
4201
4424
  this._namespace = ns;
4425
+ this.prefixLen = ns ? ns.length + 1 : 0;
4202
4426
  this._redisDisabled = this.opts.disableRedis || !this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
4203
4427
  this.watchdog = new TierLatencyWatchdog({
4204
4428
  enabled: options.diskLatencyWatchdog ?? true,
@@ -4308,6 +4532,9 @@ return 0
4308
4532
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
4309
4533
  this.initBackplane();
4310
4534
  const startupPromises = [];
4535
+ if (this.opts.compression === "zstd") {
4536
+ startupPromises.push(initZstd().then(() => void 0));
4537
+ }
4311
4538
  if (this.opts.remoteSnapshot) {
4312
4539
  startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
4313
4540
  }
@@ -4453,7 +4680,9 @@ return 0
4453
4680
  "adaptiveTtl",
4454
4681
  "l2WriteMode",
4455
4682
  "instanceName",
4456
- "invalidationBackplane"
4683
+ "invalidationBackplane",
4684
+ "awaitInvalidationBackplane",
4685
+ "lockFailClosed"
4457
4686
  ];
4458
4687
  /** Returns the names of options that differ between `a` and the live `b`. */
4459
4688
  static optionsDiff(a, b) {
@@ -4494,6 +4723,8 @@ return 0
4494
4723
  frozen: o.frozen,
4495
4724
  adaptiveTtl: o.adaptiveTtl,
4496
4725
  invalidationBackplane: o.invalidationBackplane,
4726
+ awaitInvalidationBackplane: o.awaitInvalidationBackplane,
4727
+ lockFailClosed: o.lockFailClosed,
4497
4728
  strictSingleton: o.strictSingleton,
4498
4729
  remoteSnapshot: o.remoteSnapshot,
4499
4730
  crossRegion: o.crossRegion
@@ -4779,16 +5010,80 @@ return 0
4779
5010
  _applyInvalidationEvent(op, key, tagVersion) {
4780
5011
  if (op === "del") {
4781
5012
  this.l1.delete(key);
5013
+ this._bumpKeyMutation(key);
5014
+ this.inflight.delete(key);
5015
+ this._pendingDiskDeletes.add(key);
4782
5016
  setImmediate(() => {
4783
- if (!this._diskDisabled) this.disk.delete(key);
5017
+ try {
5018
+ if (!this._diskDisabled) this.disk.delete(key);
5019
+ } finally {
5020
+ this._pendingDiskDeletes.delete(key);
5021
+ }
4784
5022
  });
4785
5023
  this._cascadeDependencies(key);
4786
5024
  } else if (op === "del-glob") {
4787
5025
  this.l1.deletePattern(key);
5026
+ const pfx = key.endsWith("*") ? key.slice(0, -1) : key;
5027
+ for (const liveKey of this.l1.liveKeys()) {
5028
+ if (liveKey.startsWith(pfx)) {
5029
+ this._bumpKeyMutation(liveKey);
5030
+ }
5031
+ }
5032
+ for (const inflightKey of Array.from(this.inflight.keys())) {
5033
+ if (inflightKey.startsWith(pfx)) {
5034
+ this._bumpKeyMutation(inflightKey);
5035
+ this.inflight.delete(inflightKey);
5036
+ }
5037
+ }
5038
+ this._addPatternTombstone(pfx);
4788
5039
  } else if (op === "tag_incr") {
4789
5040
  const tag = key;
4790
5041
  const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
4791
- this._setLocalTagVersion(tag, ver, Date.now());
5042
+ this._setLocalTagVersion(tag, ver, performance.now());
5043
+ } else if (op === "tag_pattern_incr") {
5044
+ const pattern = key;
5045
+ const now = performance.now();
5046
+ for (const [tag, info] of this.tagVersions) {
5047
+ if (matchesTagPattern(pattern, tag)) {
5048
+ this._setLocalTagVersion(tag, info.version + 1, now);
5049
+ }
5050
+ }
5051
+ this.l1.scan((k, entry) => {
5052
+ if (entry.tagVersions) {
5053
+ for (const tag of Object.keys(entry.tagVersions)) {
5054
+ if (matchesTagPattern(pattern, tag)) {
5055
+ this.l1.delete(k);
5056
+ this._bumpKeyMutation(k);
5057
+ break;
5058
+ }
5059
+ }
5060
+ }
5061
+ }, 0);
5062
+ } else if (op === "tag_pattern_del") {
5063
+ const pattern = key;
5064
+ const matchedTagKeys = [];
5065
+ const prefix = this.nk("_tag_:");
5066
+ for (const [tagKey, members] of this.tagIndex) {
5067
+ const tag = tagKey.startsWith(prefix) ? tagKey.slice(prefix.length) : tagKey;
5068
+ if (matchesTagPattern(pattern, tag)) {
5069
+ matchedTagKeys.push(tagKey);
5070
+ for (const k of members) {
5071
+ this.l1.delete(k);
5072
+ this._bumpKeyMutation(k);
5073
+ this._pendingDiskDeletes.add(k);
5074
+ setImmediate(() => {
5075
+ try {
5076
+ if (!this._diskDisabled) this.disk.delete(k);
5077
+ } finally {
5078
+ this._pendingDiskDeletes.delete(k);
5079
+ }
5080
+ });
5081
+ }
5082
+ }
5083
+ }
5084
+ for (const tagKey of matchedTagKeys) {
5085
+ this.tagIndex.delete(tagKey);
5086
+ }
4792
5087
  }
4793
5088
  this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
4794
5089
  }
@@ -4796,7 +5091,7 @@ return 0
4796
5091
  _handleBackplaneMessage(message) {
4797
5092
  try {
4798
5093
  const msg = JSON.parse(message);
4799
- 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") {
5094
+ 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") {
4800
5095
  this.logger.warn("Backplane: rejected invalid pubsub message format", {
4801
5096
  raw: typeof message === "string" ? message.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(message)
4802
5097
  });
@@ -4816,7 +5111,11 @@ return 0
4816
5111
  if (!isCrossRegionRelay && this.opts.crossRegion) {
4817
5112
  const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
4818
5113
  if (shouldBroadcast) {
4819
- void this._broadcastCrossRegion(op, key, tagVersion);
5114
+ if (this.opts.awaitInvalidationBackplane) {
5115
+ await this._broadcastCrossRegion(op, key, tagVersion);
5116
+ } else {
5117
+ void this._broadcastCrossRegion(op, key, tagVersion);
5118
+ }
4820
5119
  }
4821
5120
  }
4822
5121
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
@@ -4857,7 +5156,11 @@ return 0
4857
5156
  );
4858
5157
  }
4859
5158
  this.counters.invSent++;
4860
- } catch {
5159
+ } catch (err) {
5160
+ this.logger.warn("Backplane invalidation publish failed", { op, key, error: err.message });
5161
+ if (this.opts.awaitInvalidationBackplane) {
5162
+ throw err;
5163
+ }
4861
5164
  }
4862
5165
  }
4863
5166
  _markCrossRegionEventSeen(id) {
@@ -4975,12 +5278,12 @@ return 0
4975
5278
  * Offloads to worker thread if pool is active and payload exceeds threshold.
4976
5279
  */
4977
5280
  async _serializeAndEncrypt(serialized) {
4978
- const isCompressed2 = this.opts.compression && this.opts.compression !== "none" && serialized.length > this.opts.compressionThresholdBytes;
4979
- if (this._workerPool && (this.enc.isEnabled || isCompressed2) && serialized.length > this.opts.workerThresholdBytes) {
5281
+ const isCompressed2 = (this.opts.customCompressor || this.opts.compression && this.opts.compression !== "none") && serialized.length > this.opts.compressionThresholdBytes;
5282
+ if (this._workerPool && !this.opts.customCompressor && (this.enc.isEnabled || isCompressed2) && serialized.length > this.opts.workerThresholdBytes) {
4980
5283
  return this._workerPool.encrypt(serialized);
4981
5284
  }
4982
5285
  if (isCompressed2) {
4983
- const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression);
5286
+ const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression, this.opts.customCompressor);
4984
5287
  if (this.enc.isEnabled) {
4985
5288
  const encrypted = this.enc.encryptBuffer(compressed);
4986
5289
  return PREFIX_ENC_COMPRESSED + encrypted.toString("base64");
@@ -4995,16 +5298,16 @@ return 0
4995
5298
  */
4996
5299
  async _decryptAndDeserialize(raw) {
4997
5300
  let plain;
4998
- if (this._workerPool && raw.length > this.opts.workerThresholdBytes) {
5301
+ if (this._workerPool && !this.opts.customCompressor && raw.length > this.opts.workerThresholdBytes) {
4999
5302
  plain = await this._workerPool.decrypt(raw);
5000
5303
  } else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
5001
5304
  const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), "base64");
5002
5305
  const decBuf = this.enc.decryptBuffer(encBuf);
5003
- const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
5306
+ const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
5004
5307
  plain = decompressed.toString("utf8");
5005
5308
  } else if (raw.startsWith(PREFIX_COMPRESSED)) {
5006
5309
  const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), "base64");
5007
- const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
5310
+ const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
5008
5311
  plain = decompressed.toString("utf8");
5009
5312
  } else if (raw.startsWith("enc:v1:") || this.enc.isEnabled) {
5010
5313
  plain = this.enc.decrypt(raw);
@@ -5061,6 +5364,7 @@ return 0
5061
5364
  }
5062
5365
  }
5063
5366
  async getRedis() {
5367
+ this._assertActive("getRedis");
5064
5368
  if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
5065
5369
  if (this.redis) return this.redis;
5066
5370
  if (this.redisConnecting) return this.redisConnecting;
@@ -5389,6 +5693,7 @@ return 0
5389
5693
  * Caches negative lookups to avoid repeated DB hits for missing keys.
5390
5694
  */
5391
5695
  async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
5696
+ this._assertActive("get");
5392
5697
  const span = this._startSpan("tricache.get");
5393
5698
  if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
5394
5699
  const k = this.nk(cacheKey);
@@ -5398,7 +5703,7 @@ return 0
5398
5703
  const optRefreshAhead = opts.refreshAhead;
5399
5704
  const optXfetchBeta = opts.xfetchBeta;
5400
5705
  const optNotFoundTtl = opts.notFoundTtl;
5401
- const optTags = opts.tags;
5706
+ const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
5402
5707
  const l1Hit = this.l1.get(k);
5403
5708
  if (l1Hit !== null) {
5404
5709
  let isGenerationalStale = false;
@@ -5420,7 +5725,14 @@ return 0
5420
5725
  if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
5421
5726
  const priority2 = optPriority ?? inferPriority(cacheKey);
5422
5727
  this.revalidating.add(k);
5423
- void this._revalidate(k, fetchFn, ttlSeconds * 1e3, swrGraceMs2, priority2);
5728
+ void this._revalidate(
5729
+ k,
5730
+ fetchFn,
5731
+ ttlSeconds * 1e3,
5732
+ swrGraceMs2,
5733
+ priority2,
5734
+ l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
5735
+ );
5424
5736
  this.counters.swrRevalidations++;
5425
5737
  this.logger.debug("SWR: serving stale, revalidating", { cacheKey });
5426
5738
  } else {
@@ -5439,7 +5751,14 @@ return 0
5439
5751
  if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
5440
5752
  const priority2 = optPriority ?? inferPriority(cacheKey);
5441
5753
  this.revalidating.add(k);
5442
- void this._revalidate(k, fetchFn, entryTtl, optSwr * 1e3, priority2);
5754
+ void this._revalidate(
5755
+ k,
5756
+ fetchFn,
5757
+ entryTtl,
5758
+ optSwr * 1e3,
5759
+ priority2,
5760
+ l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
5761
+ );
5443
5762
  this.counters.swrRevalidations++;
5444
5763
  this.logger.debug(
5445
5764
  shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
@@ -5465,44 +5784,52 @@ return 0
5465
5784
  span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
5466
5785
  return existing;
5467
5786
  }
5787
+ const mutationEpochAtStart = this._getKeyMutationEpoch(k);
5468
5788
  const executionPromise = (async () => {
5469
5789
  try {
5470
- if (!this._diskDisabled) {
5471
- const isDiskAllowed = this.watchdog.isDiskAllowed();
5472
- if (isDiskAllowed) {
5473
- const diskStart = performance.now();
5474
- const diskHit = this.disk.load(k);
5475
- const diskElapsed = performance.now() - diskStart;
5476
- this.watchdog.recordDisk(diskElapsed);
5477
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
5478
- if (diskHit !== null) {
5479
- let isDiskStale = false;
5480
- if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
5481
- const tags = Object.keys(diskHit.tagVersions);
5482
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5483
- for (let i = 0; i < tags.length; i++) {
5484
- if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
5485
- isDiskStale = true;
5486
- break;
5790
+ if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
5791
+ if (this._isTombstonedByPattern(k)) {
5792
+ try {
5793
+ this.disk.delete(k);
5794
+ } catch {
5795
+ }
5796
+ } else {
5797
+ const isDiskAllowed = this.watchdog.isDiskAllowed();
5798
+ if (isDiskAllowed) {
5799
+ const diskStart = performance.now();
5800
+ const diskHit = this.disk.load(k);
5801
+ const diskElapsed = performance.now() - diskStart;
5802
+ this.watchdog.recordDisk(diskElapsed);
5803
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
5804
+ if (diskHit !== null) {
5805
+ let isDiskStale = false;
5806
+ if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
5807
+ const tags = Object.keys(diskHit.tagVersions);
5808
+ const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5809
+ for (let i = 0; i < tags.length; i++) {
5810
+ if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
5811
+ isDiskStale = true;
5812
+ break;
5813
+ }
5487
5814
  }
5488
5815
  }
5489
- }
5490
- if (isDiskStale) {
5491
- this.disk.delete(k);
5492
- } else {
5493
- const promoted = this.l1.importEntries(
5494
- [{ key: k, entry: diskHit }],
5495
- this.opts.forbiddenSnapshotPrefixes
5496
- );
5497
- if (promoted > 0) {
5498
- const l1Check = this.l1.get(k);
5499
- if (l1Check !== null) {
5500
- this.counters.diskHits++;
5501
- this.opts.onHit?.(cacheKey, "disk");
5502
- this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
5503
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
5504
- if (this.opts.frozen) deepFreeze(l1Check.value);
5505
- return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
5816
+ if (isDiskStale) {
5817
+ this.disk.delete(k);
5818
+ } else {
5819
+ const promoted = this.l1.importEntries(
5820
+ [{ key: k, entry: diskHit }],
5821
+ this.opts.forbiddenSnapshotPrefixes
5822
+ );
5823
+ if (promoted > 0) {
5824
+ const l1Check = this.l1.get(k);
5825
+ if (l1Check !== null) {
5826
+ this.counters.diskHits++;
5827
+ this.opts.onHit?.(cacheKey, "disk");
5828
+ this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
5829
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
5830
+ if (this.opts.frozen) deepFreeze(l1Check.value);
5831
+ return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
5832
+ }
5506
5833
  }
5507
5834
  }
5508
5835
  }
@@ -5613,6 +5940,18 @@ return 0
5613
5940
  await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
5614
5941
  }
5615
5942
  }
5943
+ if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
5944
+ this.logger.debug("Aborting in-flight cache commit \u2014 key was mutated or deleted during fetch", { cacheKey });
5945
+ span.setAttribute("cache.aborted_mutation_race", true);
5946
+ const current = this.l1.get(k);
5947
+ if (current && !current.isStale && current.value !== void 0) {
5948
+ const freshVal = current.value;
5949
+ if (this.opts.frozen) deepFreeze(freshVal);
5950
+ return this.opts.cloneStrategy === "structuredClone" && freshVal != null && typeof freshVal === "object" ? structuredClone(freshVal) : freshVal;
5951
+ }
5952
+ if (this.opts.frozen) deepFreeze(data);
5953
+ return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
5954
+ }
5616
5955
  this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
5617
5956
  if (!this._redisDisabled) {
5618
5957
  try {
@@ -5729,22 +6068,40 @@ return 0
5729
6068
  const ttl = options?.ttl ?? 300;
5730
6069
  return this.get(cacheKey, fetchFn, ttl, options);
5731
6070
  }
5732
- async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
6071
+ async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority, knownTagVersions) {
6072
+ const startEpoch = this._getKeyMutationEpoch(cacheKey);
5733
6073
  try {
5734
6074
  const fetchStart = Date.now();
5735
6075
  const data = await fetchFn();
5736
6076
  const delta = Date.now() - fetchStart;
5737
6077
  const staleAt = Date.now() + ttlMs;
6078
+ if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
6079
+ this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during fetch", { cacheKey });
6080
+ return;
6081
+ }
5738
6082
  if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
5739
6083
  let activeTagVersions;
5740
6084
  const l1Existing = this.l1.get(cacheKey);
5741
- if (this.opts.tagStrategy === "generational" && l1Existing?.tagVersions) {
5742
- const tags = Object.keys(l1Existing.tagVersions);
6085
+ const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
6086
+ if (this.opts.tagStrategy === "generational" && tagVersionsSource) {
6087
+ const tags = Object.keys(tagVersionsSource);
5743
6088
  const vers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5744
6089
  activeTagVersions = {};
5745
6090
  for (let i = 0; i < tags.length; i++) {
5746
6091
  activeTagVersions[tags[i]] = vers[i];
5747
6092
  }
6093
+ if (knownTagVersions) {
6094
+ for (const t of tags) {
6095
+ if (knownTagVersions[t] !== void 0 && activeTagVersions[t] !== knownTagVersions[t]) {
6096
+ this.logger.debug("SWR: aborting revalidation commit \u2014 tag version bumped during revalidation", { cacheKey, tag: t });
6097
+ return;
6098
+ }
6099
+ }
6100
+ }
6101
+ }
6102
+ if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
6103
+ this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
6104
+ return;
5748
6105
  }
5749
6106
  this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
5750
6107
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
@@ -5788,6 +6145,7 @@ return 0
5788
6145
  // ── Explicit set / delete ─────────────────────────────────────────────────
5789
6146
  /** Explicitly write a value into L1 (+ L2 in production). */
5790
6147
  async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
6148
+ this._assertActive("set");
5791
6149
  const span = this._startSpan("tricache.set");
5792
6150
  if (this.opts.tracer) {
5793
6151
  span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
@@ -5798,17 +6156,21 @@ return 0
5798
6156
  const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
5799
6157
  const p = priority ?? inferPriority(cacheKey);
5800
6158
  const k = this.nk(cacheKey);
6159
+ this._bumpKeyMutation(k);
6160
+ this.inflight.delete(k);
6161
+ this._pendingDiskDeletes.delete(k);
5801
6162
  this.counters.sets++;
5802
6163
  let activeTagVersions;
5803
- if (opts?.tags?.length) {
6164
+ const tagsToRegister = opts?.tags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
6165
+ if (tagsToRegister?.length) {
5804
6166
  if (this.opts.tagStrategy === "generational") {
5805
- const vers = await Promise.all(opts.tags.map((tag) => this._getTagVersion(tag)));
6167
+ const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
5806
6168
  activeTagVersions = {};
5807
- for (let i = 0; i < opts.tags.length; i++) {
5808
- activeTagVersions[opts.tags[i]] = vers[i];
6169
+ for (let i = 0; i < tagsToRegister.length; i++) {
6170
+ activeTagVersions[tagsToRegister[i]] = vers[i];
5809
6171
  }
5810
6172
  } else {
5811
- await this._registerTags(k, opts.tags, ttlSeconds);
6173
+ await this._registerTags(k, tagsToRegister, ttlSeconds);
5812
6174
  }
5813
6175
  }
5814
6176
  this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
@@ -5852,7 +6214,11 @@ return 0
5852
6214
  this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
5853
6215
  }
5854
6216
  }
5855
- void this.publishInvalidation("del", k);
6217
+ if (this.opts.awaitInvalidationBackplane) {
6218
+ await this.publishInvalidation("del", k);
6219
+ } else {
6220
+ void this.publishInvalidation("del", k);
6221
+ }
5856
6222
  } catch (err) {
5857
6223
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
5858
6224
  span.recordException?.(err);
@@ -5899,6 +6265,7 @@ return 0
5899
6265
  * await cache.delete('user:abc:*'); // all keys for user abc
5900
6266
  */
5901
6267
  async delete(cacheKey) {
6268
+ this._assertActive("delete");
5902
6269
  const span = this._startSpan("tricache.delete");
5903
6270
  if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
5904
6271
  try {
@@ -5906,11 +6273,31 @@ return 0
5906
6273
  const k = this.nk(cacheKey);
5907
6274
  this.counters.deletes++;
5908
6275
  if (isPattern) {
6276
+ const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6277
+ for (const liveKey of this.l1.liveKeys()) {
6278
+ if (liveKey.startsWith(pfx)) {
6279
+ this._bumpKeyMutation(liveKey);
6280
+ }
6281
+ }
6282
+ for (const inflightKey of Array.from(this.inflight.keys())) {
6283
+ if (inflightKey.startsWith(pfx)) {
6284
+ this._bumpKeyMutation(inflightKey);
6285
+ this.inflight.delete(inflightKey);
6286
+ }
6287
+ }
6288
+ this._addPatternTombstone(pfx);
5909
6289
  this.l1.deletePattern(k);
5910
6290
  } else {
6291
+ this._bumpKeyMutation(k);
6292
+ this.inflight.delete(k);
5911
6293
  this.l1.delete(k);
6294
+ this._pendingDiskDeletes.add(k);
5912
6295
  setImmediate(() => {
5913
- if (!this._diskDisabled) this.disk.delete(k);
6296
+ try {
6297
+ if (!this._diskDisabled) this.disk.delete(k);
6298
+ } finally {
6299
+ this._pendingDiskDeletes.delete(k);
6300
+ }
5914
6301
  });
5915
6302
  this._cascadeDependencies(k);
5916
6303
  for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
@@ -5934,7 +6321,11 @@ return 0
5934
6321
  this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
5935
6322
  }
5936
6323
  }
5937
- void this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
6324
+ if (this.opts.awaitInvalidationBackplane) {
6325
+ await this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
6326
+ } else {
6327
+ void this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
6328
+ }
5938
6329
  } catch (err) {
5939
6330
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
5940
6331
  span.recordException?.(err);
@@ -5961,6 +6352,7 @@ return 0
5961
6352
  * fleet-wide.
5962
6353
  */
5963
6354
  async increment(cacheKey, ttlSeconds) {
6355
+ this._assertActive("increment");
5964
6356
  const k = this.nk(cacheKey);
5965
6357
  if (this._redisDisabled) {
5966
6358
  if (!this._incrementFallbackWarned) {
@@ -6002,19 +6394,38 @@ return 0
6002
6394
  * await cache.clear('user:abc'); // flush all keys for one user
6003
6395
  */
6004
6396
  async clear(prefix) {
6397
+ this._assertActive("clear");
6005
6398
  const span = this._startSpan("tricache.clear");
6006
6399
  if (this.opts.tracer) span.setAttribute("cache.prefix", prefix || "*");
6007
6400
  try {
6008
6401
  this.counters.deletes++;
6009
6402
  const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
6010
6403
  if (k) {
6404
+ const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6405
+ for (const liveKey of this.l1.liveKeys()) {
6406
+ if (liveKey.startsWith(pfx)) {
6407
+ this._bumpKeyMutation(liveKey);
6408
+ }
6409
+ }
6410
+ for (const inflightKey of Array.from(this.inflight.keys())) {
6411
+ if (inflightKey.startsWith(pfx)) {
6412
+ this._bumpKeyMutation(inflightKey);
6413
+ this.inflight.delete(inflightKey);
6414
+ }
6415
+ }
6416
+ this._addPatternTombstone(pfx);
6011
6417
  this.l1.deletePattern(k);
6012
6418
  } else {
6419
+ this._globalEpoch++;
6420
+ this.inflight.clear();
6421
+ this._patternTombstones.length = 0;
6013
6422
  this.l1.clear();
6014
6423
  if (!this._diskDisabled) this.disk.clear();
6015
6424
  this._l1Counters.clear();
6016
6425
  this.tagIndex.clear();
6017
6426
  this.tagVersions.clear();
6427
+ this._pendingDiskDeletes.clear();
6428
+ this._keyMutationEpochs.clear();
6018
6429
  }
6019
6430
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6020
6431
  try {
@@ -6026,13 +6437,23 @@ return 0
6026
6437
  this.logger.debug("clear: Redis unavailable", { error: err.message });
6027
6438
  }
6028
6439
  }
6029
- void this.publishInvalidation(
6030
- "del-glob",
6031
- k ?? (this._namespace ? `${this._namespace}:*` : "*"),
6032
- void 0,
6033
- false,
6034
- true
6035
- );
6440
+ if (this.opts.awaitInvalidationBackplane) {
6441
+ await this.publishInvalidation(
6442
+ "del-glob",
6443
+ k ?? (this._namespace ? `${this._namespace}:*` : "*"),
6444
+ void 0,
6445
+ false,
6446
+ true
6447
+ );
6448
+ } else {
6449
+ void this.publishInvalidation(
6450
+ "del-glob",
6451
+ k ?? (this._namespace ? `${this._namespace}:*` : "*"),
6452
+ void 0,
6453
+ false,
6454
+ true
6455
+ );
6456
+ }
6036
6457
  } catch (err) {
6037
6458
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
6038
6459
  span.recordException?.(err);
@@ -6047,6 +6468,7 @@ return 0
6047
6468
  * Returns the number of entries evicted.
6048
6469
  */
6049
6470
  rebalance() {
6471
+ this._assertActive("rebalance");
6050
6472
  return this.l1.rebalance();
6051
6473
  }
6052
6474
  /**
@@ -6055,6 +6477,7 @@ return 0
6055
6477
  * Only reflects L1 state — does not query Redis or disk.
6056
6478
  */
6057
6479
  ttl(cacheKey) {
6480
+ this._assertActive("ttl");
6058
6481
  return this.l1.ttl(this.nk(cacheKey));
6059
6482
  }
6060
6483
  /**
@@ -6062,6 +6485,7 @@ return 0
6062
6485
  * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
6063
6486
  */
6064
6487
  has(cacheKey) {
6488
+ this._assertActive("has");
6065
6489
  return this.l1.has(this.nk(cacheKey));
6066
6490
  }
6067
6491
  // ── Iteration ─────────────────────────────────────────────────────────────
@@ -6072,6 +6496,7 @@ return 0
6072
6496
  * for (const key of cache.keys()) console.log(key);
6073
6497
  */
6074
6498
  *keys() {
6499
+ this._assertActive("keys");
6075
6500
  const prefix = this._namespace ? this._namespace + ":" : "";
6076
6501
  for (const key of this.l1.liveKeys()) {
6077
6502
  if (prefix && !key.startsWith(prefix)) continue;
@@ -6086,6 +6511,7 @@ return 0
6086
6511
  * for (const val of cache.values<User>()) console.log(val.id);
6087
6512
  */
6088
6513
  *values() {
6514
+ this._assertActive("values");
6089
6515
  const prefix = this._namespace ? this._namespace + ":" : "";
6090
6516
  if (!prefix) {
6091
6517
  yield* this.l1.liveValues();
@@ -6104,6 +6530,7 @@ return 0
6104
6530
  * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
6105
6531
  */
6106
6532
  *entries() {
6533
+ this._assertActive("entries");
6107
6534
  const prefix = this._namespace ? this._namespace + ":" : "";
6108
6535
  for (const [key, entry] of this.l1.liveEntries()) {
6109
6536
  if (prefix && !key.startsWith(prefix)) continue;
@@ -6131,6 +6558,7 @@ return 0
6131
6558
  * `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
6132
6559
  */
6133
6560
  scan(fn) {
6561
+ this._assertActive("scan");
6134
6562
  const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
6135
6563
  this.l1.scan((key, entry, pfx) => {
6136
6564
  const value = entry.value !== void 0 ? entry.value : entry.data;
@@ -6144,6 +6572,7 @@ return 0
6144
6572
  * @param newTtlSeconds - The new TTL from now, in seconds.
6145
6573
  */
6146
6574
  async touch(cacheKey, newTtlSeconds) {
6575
+ this._assertActive("touch");
6147
6576
  const k = this.nk(cacheKey);
6148
6577
  const hit = this.l1.touch(k, newTtlSeconds * 1e3);
6149
6578
  if (hit && !this._redisDisabled) {
@@ -6164,6 +6593,7 @@ return 0
6164
6593
  * if (fresh !== null) return fresh; // serve from L1, no network hop
6165
6594
  */
6166
6595
  getIfFresh(cacheKey) {
6596
+ this._assertActive("getIfFresh");
6167
6597
  const k = this.nk(cacheKey);
6168
6598
  const entry = this.l1.getEntry(k);
6169
6599
  if (!entry) return null;
@@ -6181,6 +6611,7 @@ return 0
6181
6611
  * const val = await cache.peek<User>('user:123');
6182
6612
  */
6183
6613
  async peek(cacheKey) {
6614
+ this._assertActive("peek");
6184
6615
  const k = this.nk(cacheKey);
6185
6616
  const l1Hit = this.l1.get(k);
6186
6617
  if (l1Hit !== null) {
@@ -6190,25 +6621,32 @@ return 0
6190
6621
  if (this.opts.frozen) deepFreeze(val);
6191
6622
  return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6192
6623
  }
6193
- if (!this._diskDisabled && this.watchdog.isDiskAllowed()) {
6194
- const diskStart = performance.now();
6195
- const diskHit = this.disk.load(k);
6196
- const diskElapsed = performance.now() - diskStart;
6197
- this.watchdog.recordDisk(diskElapsed);
6198
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6199
- if (diskHit !== null) {
6200
- const promoted = this.l1.importEntries(
6201
- [{ key: k, entry: diskHit }],
6202
- this.opts.forbiddenSnapshotPrefixes
6203
- );
6204
- if (promoted > 0) {
6205
- const l1Check = this.l1.get(k);
6206
- if (l1Check !== null) {
6207
- this.counters.gets++;
6208
- this.counters.diskHits++;
6209
- const val = l1Check.value;
6210
- if (this.opts.frozen) deepFreeze(val);
6211
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6624
+ if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
6625
+ if (this._isTombstonedByPattern(k)) {
6626
+ try {
6627
+ this.disk.delete(k);
6628
+ } catch {
6629
+ }
6630
+ } else if (this.watchdog.isDiskAllowed()) {
6631
+ const diskStart = performance.now();
6632
+ const diskHit = this.disk.load(k);
6633
+ const diskElapsed = performance.now() - diskStart;
6634
+ this.watchdog.recordDisk(diskElapsed);
6635
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6636
+ if (diskHit !== null) {
6637
+ const promoted = this.l1.importEntries(
6638
+ [{ key: k, entry: diskHit }],
6639
+ this.opts.forbiddenSnapshotPrefixes
6640
+ );
6641
+ if (promoted > 0) {
6642
+ const l1Check = this.l1.get(k);
6643
+ if (l1Check !== null) {
6644
+ this.counters.gets++;
6645
+ this.counters.diskHits++;
6646
+ const val = l1Check.value;
6647
+ if (this.opts.frozen) deepFreeze(val);
6648
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6649
+ }
6212
6650
  }
6213
6651
  }
6214
6652
  }
@@ -6246,6 +6684,7 @@ return 0
6246
6684
  * `(key) => number` so heterogeneous TTLs can be batched in one call.
6247
6685
  */
6248
6686
  async mget(keys, fetchFn, ttl = 300, priority) {
6687
+ this._assertActive("mget");
6249
6688
  const span = this._startSpan("tricache.mget");
6250
6689
  if (this.opts.tracer) {
6251
6690
  span.setAttribute("cache.batch.size", keys.length);
@@ -6314,8 +6753,16 @@ return 0
6314
6753
  }
6315
6754
  if (!this._diskDisabled && missKeys.length > 0) {
6316
6755
  for (let j = missKeys.length - 1; j >= 0; j--) {
6317
- if (!this.watchdog.isDiskAllowed()) continue;
6318
6756
  const k = this.nk(missKeys[j]);
6757
+ if (this._pendingDiskDeletes.has(k)) continue;
6758
+ if (this._isTombstonedByPattern(k)) {
6759
+ try {
6760
+ this.disk.delete(k);
6761
+ } catch {
6762
+ }
6763
+ continue;
6764
+ }
6765
+ if (!this.watchdog.isDiskAllowed()) continue;
6319
6766
  const diskStart = performance.now();
6320
6767
  const diskHit = this.disk.load(k);
6321
6768
  const diskElapsed = performance.now() - diskStart;
@@ -6338,16 +6785,23 @@ return 0
6338
6785
  }
6339
6786
  }
6340
6787
  }
6341
- if (missKeys.length > 0) {
6788
+ if (missKeys.length > 0 && fetchFn) {
6342
6789
  this.counters.fetches++;
6343
6790
  const fetched = await fetchFn(missKeys);
6791
+ const isMap = fetched instanceof Map;
6344
6792
  const setPromises = [];
6345
6793
  for (let j = 0; j < missKeys.length; j++) {
6346
- const v = fetched[missKeys[j]];
6794
+ const k = missKeys[j];
6795
+ const v = isMap ? fetched.get(k) : fetched[k];
6347
6796
  result[missIndexes[j]] = v;
6348
- if (v !== void 0) {
6349
- const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
6350
- setPromises.push(this.set(missKeys[j], v, resolvedTtl, priority));
6797
+ if (v !== void 0 && v !== null) {
6798
+ const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
6799
+ setPromises.push(this.set(k, v, resolvedTtl, priority));
6800
+ } else if (v == null && this.opts.notFoundTtl > 0) {
6801
+ setPromises.push(this.set(k, null, this.opts.notFoundTtl, priority));
6802
+ } else if (v === null) {
6803
+ const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
6804
+ setPromises.push(this.set(k, null, resolvedTtl, priority));
6351
6805
  }
6352
6806
  }
6353
6807
  if (setPromises.length > 0) {
@@ -6395,6 +6849,7 @@ return 0
6395
6849
  * });
6396
6850
  */
6397
6851
  async mset(entries) {
6852
+ this._assertActive("mset");
6398
6853
  const span = this._startSpan("tricache.mset");
6399
6854
  const keys = Object.keys(entries);
6400
6855
  if (this.opts.tracer) {
@@ -6422,6 +6877,7 @@ return 0
6422
6877
  * await cache.mdel(['user:1', 'user:2', 'user:3']);
6423
6878
  */
6424
6879
  async mdel(keys) {
6880
+ this._assertActive("mdel");
6425
6881
  const span = this._startSpan("tricache.mdel");
6426
6882
  if (this.opts.tracer) {
6427
6883
  span.setAttribute("cache.batch.size", keys.length);
@@ -6449,6 +6905,7 @@ return 0
6449
6905
  * console.log(`Warmed ${loaded} keys from Redis`);
6450
6906
  */
6451
6907
  async warmFromL2(pattern, opts) {
6908
+ this._assertActive("warmFromL2");
6452
6909
  if (this._redisDisabled) return 0;
6453
6910
  try {
6454
6911
  const client = await this.getRedis();
@@ -6487,20 +6944,109 @@ return 0
6487
6944
  }
6488
6945
  }
6489
6946
  /**
6490
- * Invalidate all keys associated with a tag.
6491
- * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
6947
+ * Discovers all concrete tag names in the system that match `tag` either via
6948
+ * glob wildcards ('*' or '?') or parent-child hierarchy cascading.
6949
+ * Scans local in-memory indices (tagIndex, tagVersions, L1 entries) and Redis (if connected).
6950
+ */
6951
+ async _resolveMatchingTags(tag, shouldCascade) {
6952
+ const isPattern = isWildcardTag(tag);
6953
+ const delim = this.opts.tagHierarchyDelimiter;
6954
+ const matched = /* @__PURE__ */ new Set();
6955
+ const tagMatches = (t) => {
6956
+ if (t === tag) return true;
6957
+ if (isPattern && matchesTagPattern(tag, t)) return true;
6958
+ if (shouldCascade && isChildTag(tag, t, delim)) return true;
6959
+ return false;
6960
+ };
6961
+ if (shouldCascade && !isPattern) {
6962
+ matched.add(tag);
6963
+ }
6964
+ const tagPrefix = this.nk("_tag_:");
6965
+ for (const tagKey of this.tagIndex.keys()) {
6966
+ const t = tagKey.startsWith(tagPrefix) ? tagKey.slice(tagPrefix.length) : tagKey;
6967
+ if (tagMatches(t)) matched.add(t);
6968
+ }
6969
+ for (const t of this.tagVersions.keys()) {
6970
+ if (tagMatches(t)) matched.add(t);
6971
+ }
6972
+ this.l1.scan((_k, entry) => {
6973
+ if (entry.tagVersions) {
6974
+ for (const t of Object.keys(entry.tagVersions)) {
6975
+ if (tagMatches(t)) matched.add(t);
6976
+ }
6977
+ }
6978
+ }, 0);
6979
+ if (!this._redisDisabled) {
6980
+ try {
6981
+ const client = await this.getRedis();
6982
+ if (this.opts.tagStrategy === "generational") {
6983
+ const redisPattern = isPattern ? this.nk(`tag_ver:${tag}`) : this.nk(`tag_ver:${tag}${delim}*`);
6984
+ const scannedKeys = await this._scanKeys(client, redisPattern);
6985
+ const pfx = this.nk("tag_ver:");
6986
+ for (const sk of scannedKeys) {
6987
+ const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
6988
+ if (tagMatches(t)) matched.add(t);
6989
+ }
6990
+ } else {
6991
+ const redisPattern = isPattern ? this.nk(`_tag_:${tag}`) : this.nk(`_tag_:${tag}${delim}*`);
6992
+ const scannedKeys = await this._scanKeys(client, redisPattern);
6993
+ const pfx = this.nk("_tag_:");
6994
+ for (const sk of scannedKeys) {
6995
+ const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
6996
+ if (tagMatches(t)) matched.add(t);
6997
+ }
6998
+ }
6999
+ } catch (err) {
7000
+ this.logger.debug("_resolveMatchingTags: Redis scan failed", { tag, error: err.message });
7001
+ }
7002
+ }
7003
+ return matched;
7004
+ }
7005
+ /**
7006
+ * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
7007
+ * Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
7008
+ *
7009
+ * @param tag Tag name or wildcard glob pattern (e.g. `'catalog'`, `'org:123:*'`, `'*:comments'`).
7010
+ * @param opts Optional invalidation options, including `{ cascade: true }` to invalidate child namespaces.
6492
7011
  *
6493
7012
  * @example
6494
7013
  * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
6495
7014
  * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
7015
+ *
7016
+ * @example
7017
+ * // Wildcard pattern invalidation
7018
+ * await cache.invalidateTag('org:123:*');
7019
+ *
7020
+ * @example
7021
+ * // Hierarchical tag cascading (clears 'org:123' and all child tags like 'org:123:dept:456')
7022
+ * await cache.invalidateTag('org:123', { cascade: true });
6496
7023
  */
6497
- async invalidateTag(tag) {
7024
+ async invalidateTag(tag, opts) {
7025
+ this._assertActive("invalidateTag");
6498
7026
  const span = this._startSpan("tricache.invalidate_tag");
6499
7027
  if (this.opts.tracer) {
6500
7028
  span.setAttribute("cache.tag", tag);
6501
7029
  span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
7030
+ if (opts?.cascade) span.setAttribute("cache.cascade", true);
6502
7031
  }
6503
7032
  try {
7033
+ const isPattern = isWildcardTag(tag);
7034
+ const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
7035
+ if (isPattern || shouldCascade) {
7036
+ const matchedTags = await this._resolveMatchingTags(tag, shouldCascade);
7037
+ const delim = this.opts.tagHierarchyDelimiter;
7038
+ const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
7039
+ if (matchedTags.size > 0) {
7040
+ await this.invalidateTags(Array.from(matchedTags));
7041
+ }
7042
+ const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
7043
+ if (this.opts.awaitInvalidationBackplane) {
7044
+ await this.publishInvalidation(op, broadcastPattern, void 0, false, true);
7045
+ } else {
7046
+ void this.publishInvalidation(op, broadcastPattern, void 0, false, true);
7047
+ }
7048
+ return;
7049
+ }
6504
7050
  if (this.opts.tagStrategy === "generational") {
6505
7051
  let newVer = 1;
6506
7052
  if (!this._redisDisabled) {
@@ -6516,15 +7062,27 @@ return 0
6516
7062
  const current = this.tagVersions.get(tag)?.version ?? 0;
6517
7063
  newVer = current + 1;
6518
7064
  }
6519
- this._setLocalTagVersion(tag, newVer, Date.now());
6520
- void this.publishInvalidation("tag_incr", tag, newVer, false, true);
7065
+ this._setLocalTagVersion(tag, newVer, performance.now());
7066
+ if (this.opts.awaitInvalidationBackplane) {
7067
+ await this.publishInvalidation("tag_incr", tag, newVer, false, true);
7068
+ } else {
7069
+ void this.publishInvalidation("tag_incr", tag, newVer, false, true);
7070
+ }
6521
7071
  return;
6522
7072
  }
6523
7073
  const tagKey = this.nk(`_tag_:${tag}`);
6524
7074
  const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
6525
7075
  for (const k of members) {
6526
7076
  this.l1.delete(k);
6527
- if (!this._diskDisabled) this.disk.delete(k);
7077
+ this._bumpKeyMutation(k);
7078
+ this._pendingDiskDeletes.add(k);
7079
+ setImmediate(() => {
7080
+ try {
7081
+ if (!this._diskDisabled) this.disk.delete(k);
7082
+ } finally {
7083
+ this._pendingDiskDeletes.delete(k);
7084
+ }
7085
+ });
6528
7086
  }
6529
7087
  this.tagIndex.delete(tagKey);
6530
7088
  if (!this._redisDisabled) {
@@ -6551,24 +7109,39 @@ return 0
6551
7109
  }
6552
7110
  /**
6553
7111
  * Invalidate all keys associated with any of the given tags in a single operation.
6554
- * Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
6555
- * reducing latency when invalidating several related tags together.
7112
+ * Supports discrete tags, wildcard glob patterns, and hierarchical cascading.
7113
+ * Combines multiple tag invalidations into Redis pipeline round-trips.
6556
7114
  *
6557
- * Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
6558
- * synchronously before the Redis round-trip.
7115
+ * @param tags Array of tag names or wildcard patterns (e.g. `['case:acme', 'org:*']`).
7116
+ * @param opts Optional invalidation options, including `{ cascade: true }`.
6559
7117
  *
6560
7118
  * @example
6561
- * // Instead of three serial round-trips:
6562
- * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
7119
+ * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:*']);
6563
7120
  */
6564
- async invalidateTags(tags) {
7121
+ async invalidateTags(tags, opts) {
7122
+ this._assertActive("invalidateTags");
6565
7123
  if (tags.length === 0) return;
7124
+ const hasWildcards = tags.some((t) => isWildcardTag(t));
7125
+ const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
7126
+ if (hasWildcards || shouldCascade) {
7127
+ const allResolvedTags = /* @__PURE__ */ new Set();
7128
+ for (const t of tags) {
7129
+ if (isWildcardTag(t) || shouldCascade) {
7130
+ const resolved = await this._resolveMatchingTags(t, shouldCascade);
7131
+ for (const rt of resolved) allResolvedTags.add(rt);
7132
+ } else {
7133
+ allResolvedTags.add(t);
7134
+ }
7135
+ }
7136
+ if (allResolvedTags.size === 0) return;
7137
+ tags = Array.from(allResolvedTags);
7138
+ }
6566
7139
  if (tags.length === 1) {
6567
- await this.invalidateTag(tags[0]);
7140
+ await this.invalidateTag(tags[0], opts);
6568
7141
  return;
6569
7142
  }
6570
7143
  if (this.opts.tagStrategy === "generational") {
6571
- const now = Date.now();
7144
+ const now = performance.now();
6572
7145
  if (!this._redisDisabled) {
6573
7146
  try {
6574
7147
  const client = await this.getRedis();
@@ -6579,7 +7152,11 @@ return 0
6579
7152
  const [err, newVer] = results[i] ?? [null, null];
6580
7153
  const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
6581
7154
  this._setLocalTagVersion(tags[i], ver, now);
6582
- void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7155
+ if (this.opts.awaitInvalidationBackplane) {
7156
+ await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7157
+ } else {
7158
+ void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7159
+ }
6583
7160
  }
6584
7161
  return;
6585
7162
  } catch (err) {
@@ -6589,7 +7166,11 @@ return 0
6589
7166
  for (const tag of tags) {
6590
7167
  const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
6591
7168
  this._setLocalTagVersion(tag, ver, now);
6592
- void this.publishInvalidation("tag_incr", tag, ver, false, true);
7169
+ if (this.opts.awaitInvalidationBackplane) {
7170
+ await this.publishInvalidation("tag_incr", tag, ver, false, true);
7171
+ } else {
7172
+ void this.publishInvalidation("tag_incr", tag, ver, false, true);
7173
+ }
6593
7174
  }
6594
7175
  return;
6595
7176
  }
@@ -6604,7 +7185,15 @@ return 0
6604
7185
  }
6605
7186
  for (const k of allMembers) {
6606
7187
  this.l1.delete(k);
6607
- this.disk.delete(k);
7188
+ this._bumpKeyMutation(k);
7189
+ this._pendingDiskDeletes.add(k);
7190
+ setImmediate(() => {
7191
+ try {
7192
+ if (!this._diskDisabled) this.disk.delete(k);
7193
+ } finally {
7194
+ this._pendingDiskDeletes.delete(k);
7195
+ }
7196
+ });
6608
7197
  }
6609
7198
  if (!this._redisDisabled) {
6610
7199
  try {
@@ -6641,6 +7230,7 @@ return 0
6641
7230
  * `l2` is `null` when Redis is disabled.
6642
7231
  */
6643
7232
  async ping() {
7233
+ this._assertActive("ping");
6644
7234
  const t0 = Date.now();
6645
7235
  this.l1.has("__ping__");
6646
7236
  const l1 = Date.now() - t0;
@@ -6720,6 +7310,7 @@ return 0
6720
7310
  * Returns the number of keys written.
6721
7311
  */
6722
7312
  async drainToL2() {
7313
+ this._assertActive("drainToL2");
6723
7314
  if (this._redisDisabled) return 0;
6724
7315
  try {
6725
7316
  const client = await this.getRedis();
@@ -6763,6 +7354,7 @@ return 0
6763
7354
  * if (!claimed) return res.status(409).json({ error: 'duplicate request' });
6764
7355
  */
6765
7356
  async setIfAbsent(cacheKey, value, ttlSeconds = 300, priority) {
7357
+ this._assertActive("setIfAbsent");
6766
7358
  const k = this.nk(cacheKey);
6767
7359
  if (this.l1.has(k)) return false;
6768
7360
  if (!this._redisDisabled) {
@@ -6781,6 +7373,8 @@ return 0
6781
7373
  }
6782
7374
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
6783
7375
  const p = priority ?? inferPriority(cacheKey);
7376
+ this._bumpKeyMutation(k);
7377
+ this._pendingDiskDeletes.delete(k);
6784
7378
  this.l1.set(k, value, ttlMs, p);
6785
7379
  this.counters.sets++;
6786
7380
  return true;
@@ -6799,6 +7393,7 @@ return 0
6799
7393
  * @param options TTL, acquire timeout, and retry polling intervals.
6800
7394
  */
6801
7395
  async lock(resourceKey, fn, options) {
7396
+ this._assertActive("lock");
6802
7397
  const ttlSeconds = Math.max(1, options?.ttl ?? 30);
6803
7398
  const acquireTimeout = Math.max(0, options?.acquireTimeout ?? 5e3);
6804
7399
  const retryInterval = Math.max(10, options?.retryInterval ?? 100);
@@ -6825,6 +7420,10 @@ return 0
6825
7420
  }
6826
7421
  } catch (err) {
6827
7422
  if (err.message.startsWith("Failed to acquire lock")) throw err;
7423
+ const failClosed = options?.failClosedOnRedisError ?? this.opts.lockFailClosed;
7424
+ if (failClosed) {
7425
+ throw new Error(`Distributed lock acquisition failed for resource "${resourceKey}" due to Redis error: ${err.message}`);
7426
+ }
6828
7427
  this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
6829
7428
  resourceKey,
6830
7429
  error: err.message
@@ -7170,6 +7769,7 @@ return 0
7170
7769
  * the previous key for seamless fallback decryption of existing cache entries.
7171
7770
  */
7172
7771
  async rotateEncryptionKey(newKeyBase64, newMode) {
7772
+ this._assertActive("rotateEncryptionKey");
7173
7773
  this.enc.rotateKey(newKeyBase64, newMode);
7174
7774
  if (this._workerPool) {
7175
7775
  await this._workerPool.drainAndReinit(this.enc.toWorkerInit());
@@ -7179,6 +7779,8 @@ return 0
7179
7779
  /** Close Redis connections and stop all background timers. */
7180
7780
  async destroy() {
7181
7781
  this._destroyed = true;
7782
+ this._pendingDiskDeletes.clear();
7783
+ this._keyMutationEpochs.clear();
7182
7784
  const g = globalThis;
7183
7785
  const key = _CacheService.globalKey(this.opts);
7184
7786
  if (g[key] === this) {