tricache 0.9.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 (47) hide show
  1. package/README.md +7 -3
  2. package/dist/{cache-service-KI5ACF3F.js → cache-service-26GCO3UU.js} +3 -3
  3. package/dist/{cache-service-DVvroyqA.d.ts → cache-service-pJ-nFcVj.d.ts} +29 -12
  4. package/dist/{chunk-XZL45ABR.js → chunk-2AJKEQMZ.js} +54 -1
  5. package/dist/{chunk-PL5J3ZNT.js → chunk-7SZSQS55.js} +201 -34
  6. package/dist/{chunk-LJ5QJB5O.js → chunk-UBWLPKTI.js} +127 -11
  7. package/dist/cli.cjs +376 -50
  8. package/dist/cli.js +4 -4
  9. package/dist/dashboard/index.d.ts +2 -2
  10. package/dist/drizzle/index.cjs +384 -51
  11. package/dist/drizzle/index.d.ts +2 -2
  12. package/dist/drizzle/index.js +1 -1
  13. package/dist/edge/index.cjs +64 -8
  14. package/dist/edge/index.d.ts +3 -3
  15. package/dist/edge/index.js +37 -9
  16. package/dist/hono/index.cjs +384 -51
  17. package/dist/hono/index.d.ts +2 -2
  18. package/dist/hono/index.js +1 -1
  19. package/dist/{hono-VA9A1m0I.d.ts → hono-DuNvciyq.d.ts} +4 -4
  20. package/dist/http/index.cjs +384 -51
  21. package/dist/http/index.d.ts +3 -3
  22. package/dist/http/index.js +8 -8
  23. package/dist/index.cjs +385 -49
  24. package/dist/index.d.ts +35 -6
  25. package/dist/index.js +16 -6
  26. package/dist/nestjs/index.cjs +375 -49
  27. package/dist/nestjs/index.d.ts +2 -2
  28. package/dist/nestjs/index.js +4 -4
  29. package/dist/next/index.cjs +375 -49
  30. package/dist/next/index.d.ts +2 -2
  31. package/dist/next/index.js +3 -3
  32. package/dist/prisma/index.d.ts +2 -2
  33. package/dist/serialize-worker.cjs +127 -9
  34. package/dist/serialize-worker.js +8 -4
  35. package/dist/{types-B_QkVwJ7.d.ts → types-5HXqBfAf.d.ts} +51 -7
  36. package/package.json +7 -4
  37. package/src/cache-service.ts +238 -33
  38. package/src/cli.ts +1 -1
  39. package/src/compression.ts +193 -15
  40. package/src/cross-region.ts +1 -1
  41. package/src/edge/cache.ts +38 -11
  42. package/src/env.d.ts +13 -0
  43. package/src/index.ts +9 -1
  44. package/src/serialize-worker.ts +6 -2
  45. package/src/types.ts +43 -5
  46. package/src/utils/tag-matcher.ts +90 -0
  47. /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
+ }
2065
+ return null;
2066
+ }
2067
+ };
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;
1974
2073
  return null;
1975
2074
  }
1976
2075
  };
1977
- const result = algorithm === "gzip" ? tryGzip() ?? tryBrotli() : tryBrotli() ?? tryGzip();
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;
@@ -4169,12 +4341,15 @@ return 0
4169
4341
  redisSentinel: options.redisSentinel,
4170
4342
  redisProtocol: options.redisProtocol,
4171
4343
  useShardedPubSub: options.useShardedPubSub ?? false,
4172
- compression: options.compression ?? "none",
4344
+ compression: options.compression ?? "zstd",
4345
+ customCompressor: options.customCompressor,
4173
4346
  compressionThresholdBytes: options.compressionThresholdBytes ?? 1024,
4174
4347
  strictSingleton: options.strictSingleton ?? false,
4175
4348
  failClosed: options.failClosed ?? false,
4176
4349
  tagStrategy: options.tagStrategy ?? "set",
4177
4350
  tagVersionTtlMs: options.tagVersionTtlMs ?? 5e3,
4351
+ hierarchicalTags: options.hierarchicalTags ?? false,
4352
+ tagHierarchyDelimiter: options.tagHierarchyDelimiter ?? ":",
4178
4353
  cloneStrategy: options.cloneStrategy ?? "none",
4179
4354
  backplaneMode: options.backplaneMode ?? "pubsub",
4180
4355
  backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
@@ -4247,6 +4422,7 @@ return 0
4247
4422
  diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs
4248
4423
  });
4249
4424
  this._namespace = ns;
4425
+ this.prefixLen = ns ? ns.length + 1 : 0;
4250
4426
  this._redisDisabled = this.opts.disableRedis || !this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
4251
4427
  this.watchdog = new TierLatencyWatchdog({
4252
4428
  enabled: options.diskLatencyWatchdog ?? true,
@@ -4356,6 +4532,9 @@ return 0
4356
4532
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
4357
4533
  this.initBackplane();
4358
4534
  const startupPromises = [];
4535
+ if (this.opts.compression === "zstd") {
4536
+ startupPromises.push(initZstd().then(() => void 0));
4537
+ }
4359
4538
  if (this.opts.remoteSnapshot) {
4360
4539
  startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
4361
4540
  }
@@ -4861,6 +5040,50 @@ return 0
4861
5040
  const tag = key;
4862
5041
  const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
4863
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
+ }
4864
5087
  }
4865
5088
  this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
4866
5089
  }
@@ -4868,7 +5091,7 @@ return 0
4868
5091
  _handleBackplaneMessage(message) {
4869
5092
  try {
4870
5093
  const msg = JSON.parse(message);
4871
- 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") {
4872
5095
  this.logger.warn("Backplane: rejected invalid pubsub message format", {
4873
5096
  raw: typeof message === "string" ? message.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(message)
4874
5097
  });
@@ -5055,12 +5278,12 @@ return 0
5055
5278
  * Offloads to worker thread if pool is active and payload exceeds threshold.
5056
5279
  */
5057
5280
  async _serializeAndEncrypt(serialized) {
5058
- const isCompressed2 = this.opts.compression && this.opts.compression !== "none" && serialized.length > this.opts.compressionThresholdBytes;
5059
- 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) {
5060
5283
  return this._workerPool.encrypt(serialized);
5061
5284
  }
5062
5285
  if (isCompressed2) {
5063
- const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression);
5286
+ const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression, this.opts.customCompressor);
5064
5287
  if (this.enc.isEnabled) {
5065
5288
  const encrypted = this.enc.encryptBuffer(compressed);
5066
5289
  return PREFIX_ENC_COMPRESSED + encrypted.toString("base64");
@@ -5075,16 +5298,16 @@ return 0
5075
5298
  */
5076
5299
  async _decryptAndDeserialize(raw) {
5077
5300
  let plain;
5078
- if (this._workerPool && raw.length > this.opts.workerThresholdBytes) {
5301
+ if (this._workerPool && !this.opts.customCompressor && raw.length > this.opts.workerThresholdBytes) {
5079
5302
  plain = await this._workerPool.decrypt(raw);
5080
5303
  } else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
5081
5304
  const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), "base64");
5082
5305
  const decBuf = this.enc.decryptBuffer(encBuf);
5083
- 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);
5084
5307
  plain = decompressed.toString("utf8");
5085
5308
  } else if (raw.startsWith(PREFIX_COMPRESSED)) {
5086
5309
  const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), "base64");
5087
- 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);
5088
5311
  plain = decompressed.toString("utf8");
5089
5312
  } else if (raw.startsWith("enc:v1:") || this.enc.isEnabled) {
5090
5313
  plain = this.enc.decrypt(raw);
@@ -5480,7 +5703,7 @@ return 0
5480
5703
  const optRefreshAhead = opts.refreshAhead;
5481
5704
  const optXfetchBeta = opts.xfetchBeta;
5482
5705
  const optNotFoundTtl = opts.notFoundTtl;
5483
- const optTags = opts.tags;
5706
+ const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
5484
5707
  const l1Hit = this.l1.get(k);
5485
5708
  if (l1Hit !== null) {
5486
5709
  let isGenerationalStale = false;
@@ -5938,15 +6161,16 @@ return 0
5938
6161
  this._pendingDiskDeletes.delete(k);
5939
6162
  this.counters.sets++;
5940
6163
  let activeTagVersions;
5941
- 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) {
5942
6166
  if (this.opts.tagStrategy === "generational") {
5943
- const vers = await Promise.all(opts.tags.map((tag) => this._getTagVersion(tag)));
6167
+ const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
5944
6168
  activeTagVersions = {};
5945
- for (let i = 0; i < opts.tags.length; i++) {
5946
- activeTagVersions[opts.tags[i]] = vers[i];
6169
+ for (let i = 0; i < tagsToRegister.length; i++) {
6170
+ activeTagVersions[tagsToRegister[i]] = vers[i];
5947
6171
  }
5948
6172
  } else {
5949
- await this._registerTags(k, opts.tags, ttlSeconds);
6173
+ await this._registerTags(k, tagsToRegister, ttlSeconds);
5950
6174
  }
5951
6175
  }
5952
6176
  this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
@@ -6561,16 +6785,23 @@ return 0
6561
6785
  }
6562
6786
  }
6563
6787
  }
6564
- if (missKeys.length > 0) {
6788
+ if (missKeys.length > 0 && fetchFn) {
6565
6789
  this.counters.fetches++;
6566
6790
  const fetched = await fetchFn(missKeys);
6791
+ const isMap = fetched instanceof Map;
6567
6792
  const setPromises = [];
6568
6793
  for (let j = 0; j < missKeys.length; j++) {
6569
- const v = fetched[missKeys[j]];
6794
+ const k = missKeys[j];
6795
+ const v = isMap ? fetched.get(k) : fetched[k];
6570
6796
  result[missIndexes[j]] = v;
6571
- if (v !== void 0) {
6572
- const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
6573
- 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));
6574
6805
  }
6575
6806
  }
6576
6807
  if (setPromises.length > 0) {
@@ -6713,21 +6944,109 @@ return 0
6713
6944
  }
6714
6945
  }
6715
6946
  /**
6716
- * Invalidate all keys associated with a tag.
6717
- * 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.
6718
7011
  *
6719
7012
  * @example
6720
7013
  * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
6721
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 });
6722
7023
  */
6723
- async invalidateTag(tag) {
7024
+ async invalidateTag(tag, opts) {
6724
7025
  this._assertActive("invalidateTag");
6725
7026
  const span = this._startSpan("tricache.invalidate_tag");
6726
7027
  if (this.opts.tracer) {
6727
7028
  span.setAttribute("cache.tag", tag);
6728
7029
  span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
7030
+ if (opts?.cascade) span.setAttribute("cache.cascade", true);
6729
7031
  }
6730
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
+ }
6731
7050
  if (this.opts.tagStrategy === "generational") {
6732
7051
  let newVer = 1;
6733
7052
  if (!this._redisDisabled) {
@@ -6790,21 +7109,35 @@ return 0
6790
7109
  }
6791
7110
  /**
6792
7111
  * Invalidate all keys associated with any of the given tags in a single operation.
6793
- * Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
6794
- * 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.
6795
7114
  *
6796
- * Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
6797
- * 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 }`.
6798
7117
  *
6799
7118
  * @example
6800
- * // Instead of three serial round-trips:
6801
- * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
7119
+ * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:*']);
6802
7120
  */
6803
- async invalidateTags(tags) {
7121
+ async invalidateTags(tags, opts) {
6804
7122
  this._assertActive("invalidateTags");
6805
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
+ }
6806
7139
  if (tags.length === 1) {
6807
- await this.invalidateTag(tags[0]);
7140
+ await this.invalidateTag(tags[0], opts);
6808
7141
  return;
6809
7142
  }
6810
7143
  if (this.opts.tagStrategy === "generational") {
@@ -1,5 +1,5 @@
1
- import { C as CacheService } from '../cache-service-DVvroyqA.js';
2
- import { W as WrapOptions } from '../types-B_QkVwJ7.js';
1
+ import { C as CacheService } from '../cache-service-pJ-nFcVj.js';
2
+ import { W as WrapOptions } from '../types-5HXqBfAf.js';
3
3
  import 'crypto';
4
4
 
5
5
  /**
@@ -9,7 +9,7 @@ async function withCache(query, options = {}) {
9
9
  const { cache, key, ttl = 300, swr, priority, tags, dependsOn, refreshAhead, xfetchBeta, notFoundTtl } = options;
10
10
  let activeCache = cache;
11
11
  if (!activeCache) {
12
- const { CacheService } = await import("../cache-service-KI5ACF3F.js");
12
+ const { CacheService } = await import("../cache-service-26GCO3UU.js");
13
13
  activeCache = CacheService.create();
14
14
  }
15
15
  let cacheKey = key;