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
package/dist/cli.cjs CHANGED
@@ -1911,13 +1911,38 @@ var import_os2 = __toESM(require("os"), 1);
1911
1911
 
1912
1912
  // src/compression.ts
1913
1913
  var import_zlib = __toESM(require("zlib"), 1);
1914
+ var import_lz4js = __toESM(require("lz4js"), 1);
1915
+ var import_zstd_codec = require("zstd-codec");
1914
1916
  var PREFIX_COMPRESSED = "cmp:v1:";
1915
1917
  var PREFIX_ENC_COMPRESSED = "ecp:v1:";
1916
1918
  var COMPRESSION_MAGIC = Buffer.from([84, 82, 67, 1]);
1919
+ var zstdSimple = null;
1920
+ var zstdInitPromise = null;
1921
+ function initZstd() {
1922
+ if (zstdSimple) return Promise.resolve(zstdSimple);
1923
+ if (!zstdInitPromise) {
1924
+ zstdInitPromise = new Promise((resolve) => {
1925
+ try {
1926
+ import_zstd_codec.ZstdCodec.run((zstd) => {
1927
+ zstdSimple = new zstd.Simple();
1928
+ resolve(zstdSimple);
1929
+ });
1930
+ } catch {
1931
+ resolve(null);
1932
+ }
1933
+ });
1934
+ }
1935
+ return zstdInitPromise;
1936
+ }
1937
+ initZstd().catch(() => {
1938
+ });
1917
1939
  function isCompressed(buf) {
1918
1940
  return buf.length >= 4 && buf[0] === 84 && buf[1] === 82 && buf[2] === 67 && buf[3] === 1;
1919
1941
  }
1920
- function compressBuffer(buf, algorithm) {
1942
+ function compressBuffer(buf, algorithm, custom) {
1943
+ if (custom) {
1944
+ return custom.compress(buf);
1945
+ }
1921
1946
  if (algorithm === "brotli") {
1922
1947
  return import_zlib.default.brotliCompressSync(buf, {
1923
1948
  params: {
@@ -1929,37 +1954,127 @@ function compressBuffer(buf, algorithm) {
1929
1954
  if (algorithm === "gzip") {
1930
1955
  return import_zlib.default.gzipSync(buf, { level: 6 });
1931
1956
  }
1957
+ if (algorithm === "lz4") {
1958
+ return Buffer.from(import_lz4js.default.compress(buf));
1959
+ }
1960
+ if (algorithm === "zstd") {
1961
+ if (!zstdSimple) {
1962
+ return import_zlib.default.brotliCompressSync(buf, {
1963
+ params: { [import_zlib.default.constants.BROTLI_PARAM_QUALITY]: 4 }
1964
+ });
1965
+ }
1966
+ return Buffer.from(zstdSimple.compress(buf));
1967
+ }
1932
1968
  return buf;
1933
1969
  }
1934
- function decompressBuffer(buf, algorithm = "brotli") {
1970
+ var MAX_DECOMPRESS_BYTES = 25 * 1024 * 1024;
1971
+ function decompressBuffer(buf, algorithm = "zstd", custom) {
1972
+ if (custom) {
1973
+ const res = custom.decompress(buf);
1974
+ if (res.length > MAX_DECOMPRESS_BYTES) {
1975
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
1976
+ }
1977
+ return res;
1978
+ }
1979
+ const checkSafety = (decomp) => {
1980
+ if (decomp.length > MAX_DECOMPRESS_BYTES) {
1981
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
1982
+ }
1983
+ return decomp;
1984
+ };
1985
+ if (buf.length >= 4 && buf[0] === 40 && buf[1] === 181 && buf[2] === 47 && buf[3] === 253) {
1986
+ if (zstdSimple) {
1987
+ try {
1988
+ return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
1989
+ } catch (err) {
1990
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
1991
+ }
1992
+ }
1993
+ }
1994
+ if (buf.length >= 4 && buf[0] === 4 && buf[1] === 34 && buf[2] === 77 && buf[3] === 24) {
1995
+ try {
1996
+ return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
1997
+ } catch (err) {
1998
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
1999
+ }
2000
+ }
2001
+ if (buf.length >= 2 && buf[0] === 31 && buf[1] === 139) {
2002
+ try {
2003
+ return import_zlib.default.gunzipSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
2004
+ } catch (err) {
2005
+ if (err?.code === "ERR_BUFFER_TOO_LARGE") {
2006
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
2007
+ }
2008
+ }
2009
+ }
2010
+ if (algorithm === "none") {
2011
+ return buf;
2012
+ }
2013
+ if (algorithm === "lz4") {
2014
+ try {
2015
+ return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
2016
+ } catch (err) {
2017
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
2018
+ }
2019
+ }
2020
+ if (algorithm === "zstd" && zstdSimple) {
2021
+ try {
2022
+ return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
2023
+ } catch (err) {
2024
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
2025
+ }
2026
+ }
1935
2027
  const tryBrotli = () => {
1936
2028
  try {
1937
- return import_zlib.default.brotliDecompressSync(buf);
1938
- } catch {
2029
+ return import_zlib.default.brotliDecompressSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
2030
+ } catch (err) {
2031
+ if (err?.code === "ERR_BUFFER_TOO_LARGE") {
2032
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
2033
+ }
1939
2034
  return null;
1940
2035
  }
1941
2036
  };
1942
2037
  const tryGzip = () => {
1943
2038
  try {
1944
- return import_zlib.default.gunzipSync(buf);
1945
- } catch {
2039
+ return import_zlib.default.gunzipSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
2040
+ } catch (err) {
2041
+ if (err?.code === "ERR_BUFFER_TOO_LARGE") {
2042
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
2043
+ }
2044
+ return null;
2045
+ }
2046
+ };
2047
+ const tryLz4 = () => {
2048
+ try {
2049
+ return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
2050
+ } catch (err) {
2051
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
1946
2052
  return null;
1947
2053
  }
1948
2054
  };
1949
- const result = algorithm === "gzip" ? tryGzip() ?? tryBrotli() : tryBrotli() ?? tryGzip();
2055
+ const tryZstd = () => {
2056
+ if (!zstdSimple) return null;
2057
+ try {
2058
+ return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
2059
+ } catch (err) {
2060
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
2061
+ return null;
2062
+ }
2063
+ };
2064
+ const result = (algorithm === "gzip" ? tryGzip() : null) ?? (algorithm === "lz4" ? tryLz4() : null) ?? (algorithm === "zstd" ? tryZstd() : null) ?? tryBrotli() ?? tryGzip() ?? tryLz4() ?? tryZstd();
1950
2065
  if (result === null) {
1951
2066
  throw new Error(`tricache: corrupt compressed payload (${buf.length} bytes, algorithm=${algorithm})`);
1952
2067
  }
1953
2068
  return result;
1954
2069
  }
1955
- function compressWithHeader(buf, algorithm) {
2070
+ function compressWithHeader(buf, algorithm, custom) {
1956
2071
  if (algorithm === "none") return buf;
1957
- const compressed = compressBuffer(buf, algorithm);
2072
+ const compressed = compressBuffer(buf, algorithm, custom);
1958
2073
  return Buffer.concat([COMPRESSION_MAGIC, compressed]);
1959
2074
  }
1960
- function decompressWithHeader(buf, algorithm = "brotli") {
2075
+ function decompressWithHeader(buf, algorithm = "zstd", custom) {
1961
2076
  if (isCompressed(buf)) {
1962
- return decompressBuffer(buf.subarray(4), algorithm);
2077
+ return decompressBuffer(buf.subarray(4), algorithm, custom);
1963
2078
  }
1964
2079
  return buf;
1965
2080
  }
@@ -3789,6 +3904,55 @@ function renderTopDashboard(payload) {
3789
3904
  return lines.join("\n");
3790
3905
  }
3791
3906
 
3907
+ // src/utils/tag-matcher.ts
3908
+ var globRegexCache = /* @__PURE__ */ new Map();
3909
+ function isWildcardTag(tag) {
3910
+ return tag.includes("*") || tag.includes("?");
3911
+ }
3912
+ function matchesTagPattern(pattern, tag) {
3913
+ if (pattern === "*" || pattern === tag) return true;
3914
+ if (!pattern.includes("*") && !pattern.includes("?")) return pattern === tag;
3915
+ if (pattern.endsWith("*") && !pattern.slice(0, -1).includes("*") && !pattern.includes("?")) {
3916
+ const prefix = pattern.slice(0, -1);
3917
+ return tag.startsWith(prefix);
3918
+ }
3919
+ if (pattern.startsWith("*") && !pattern.slice(1).includes("*") && !pattern.includes("?")) {
3920
+ const suffix = pattern.slice(1);
3921
+ return tag.endsWith(suffix);
3922
+ }
3923
+ let re = globRegexCache.get(pattern);
3924
+ if (!re) {
3925
+ if (globRegexCache.size >= 1e3) globRegexCache.clear();
3926
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
3927
+ re = new RegExp(`^${escaped}$`);
3928
+ globRegexCache.set(pattern, re);
3929
+ }
3930
+ return re.test(tag);
3931
+ }
3932
+ function isChildTag(parentTag, candidateTag, delimiter = ":") {
3933
+ if (candidateTag === parentTag) return true;
3934
+ const prefix = parentTag.endsWith(delimiter) ? parentTag : `${parentTag}${delimiter}`;
3935
+ return candidateTag.startsWith(prefix);
3936
+ }
3937
+ function expandHierarchicalTags(tags, delimiter = ":") {
3938
+ if (!tags.length) return [];
3939
+ const result = /* @__PURE__ */ new Set();
3940
+ for (const tag of tags) {
3941
+ if (!tag) continue;
3942
+ const parts = tag.split(delimiter).filter((p) => p.length > 0);
3943
+ if (parts.length <= 1) {
3944
+ result.add(tag);
3945
+ continue;
3946
+ }
3947
+ let accumulated = "";
3948
+ for (let i = 0; i < parts.length; i++) {
3949
+ accumulated = i === 0 ? parts[i] : `${accumulated}${delimiter}${parts[i]}`;
3950
+ result.add(accumulated);
3951
+ }
3952
+ }
3953
+ return Array.from(result);
3954
+ }
3955
+
3792
3956
  // src/cache-service.ts
3793
3957
  var LUA_COMPARE_AND_DELETE = `
3794
3958
  local currentTs = redis.call('HGET', KEYS[1], 't')
@@ -3807,21 +3971,21 @@ var DEFAULT_CATEGORY_LIMITS = {
3807
3971
  var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
3808
3972
  var DEFAULT_COUNTER_TTL_SECONDS = 60;
3809
3973
  var GLOB_REGEX_CACHE_MAX = 256;
3810
- var globRegexCache = /* @__PURE__ */ new Map();
3974
+ var globRegexCache2 = /* @__PURE__ */ new Map();
3811
3975
  function getGlobRegex(pattern) {
3812
- let re = globRegexCache.get(pattern);
3976
+ let re = globRegexCache2.get(pattern);
3813
3977
  if (re) {
3814
- globRegexCache.delete(pattern);
3815
- globRegexCache.set(pattern, re);
3978
+ globRegexCache2.delete(pattern);
3979
+ globRegexCache2.set(pattern, re);
3816
3980
  return re;
3817
3981
  }
3818
3982
  const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*+/g, ".*");
3819
3983
  re = new RegExp("^" + escaped + "$");
3820
- if (globRegexCache.size >= GLOB_REGEX_CACHE_MAX) {
3821
- const oldestKey = globRegexCache.keys().next().value;
3822
- if (oldestKey !== void 0) globRegexCache.delete(oldestKey);
3984
+ if (globRegexCache2.size >= GLOB_REGEX_CACHE_MAX) {
3985
+ const oldestKey = globRegexCache2.keys().next().value;
3986
+ if (oldestKey !== void 0) globRegexCache2.delete(oldestKey);
3823
3987
  }
3824
- globRegexCache.set(pattern, re);
3988
+ globRegexCache2.set(pattern, re);
3825
3989
  return re;
3826
3990
  }
3827
3991
  var L2CircuitBreaker = class {
@@ -4075,6 +4239,7 @@ var CacheService = class _CacheService {
4075
4239
  opts;
4076
4240
  /** Pre-computed once — opts.namespace never changes after construction. */
4077
4241
  _namespace;
4242
+ prefixLen;
4078
4243
  /** Pre-computed once — disableRedis and redisHost never change after construction. */
4079
4244
  _redisDisabled;
4080
4245
  watchdog;
@@ -4283,12 +4448,15 @@ var CacheService = class _CacheService {
4283
4448
  redisSentinel: options.redisSentinel,
4284
4449
  redisProtocol: options.redisProtocol,
4285
4450
  useShardedPubSub: options.useShardedPubSub ?? false,
4286
- compression: options.compression ?? "none",
4451
+ compression: options.compression ?? "zstd",
4452
+ customCompressor: options.customCompressor,
4287
4453
  compressionThresholdBytes: options.compressionThresholdBytes ?? 1024,
4288
4454
  strictSingleton: options.strictSingleton ?? false,
4289
4455
  failClosed: options.failClosed ?? false,
4290
4456
  tagStrategy: options.tagStrategy ?? "set",
4291
4457
  tagVersionTtlMs: options.tagVersionTtlMs ?? 5e3,
4458
+ hierarchicalTags: options.hierarchicalTags ?? false,
4459
+ tagHierarchyDelimiter: options.tagHierarchyDelimiter ?? ":",
4292
4460
  cloneStrategy: options.cloneStrategy ?? "none",
4293
4461
  backplaneMode: options.backplaneMode ?? "pubsub",
4294
4462
  backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
@@ -4361,6 +4529,7 @@ var CacheService = class _CacheService {
4361
4529
  diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs
4362
4530
  });
4363
4531
  this._namespace = ns;
4532
+ this.prefixLen = ns ? ns.length + 1 : 0;
4364
4533
  this._redisDisabled = this.opts.disableRedis || !this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
4365
4534
  this.watchdog = new TierLatencyWatchdog({
4366
4535
  enabled: options.diskLatencyWatchdog ?? true,
@@ -4470,6 +4639,9 @@ var CacheService = class _CacheService {
4470
4639
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
4471
4640
  this.initBackplane();
4472
4641
  const startupPromises = [];
4642
+ if (this.opts.compression === "zstd") {
4643
+ startupPromises.push(initZstd().then(() => void 0));
4644
+ }
4473
4645
  if (this.opts.remoteSnapshot) {
4474
4646
  startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
4475
4647
  }
@@ -4975,6 +5147,50 @@ var CacheService = class _CacheService {
4975
5147
  const tag = key;
4976
5148
  const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
4977
5149
  this._setLocalTagVersion(tag, ver, performance.now());
5150
+ } else if (op === "tag_pattern_incr") {
5151
+ const pattern = key;
5152
+ const now = performance.now();
5153
+ for (const [tag, info] of this.tagVersions) {
5154
+ if (matchesTagPattern(pattern, tag)) {
5155
+ this._setLocalTagVersion(tag, info.version + 1, now);
5156
+ }
5157
+ }
5158
+ this.l1.scan((k, entry) => {
5159
+ if (entry.tagVersions) {
5160
+ for (const tag of Object.keys(entry.tagVersions)) {
5161
+ if (matchesTagPattern(pattern, tag)) {
5162
+ this.l1.delete(k);
5163
+ this._bumpKeyMutation(k);
5164
+ break;
5165
+ }
5166
+ }
5167
+ }
5168
+ }, 0);
5169
+ } else if (op === "tag_pattern_del") {
5170
+ const pattern = key;
5171
+ const matchedTagKeys = [];
5172
+ const prefix = this.nk("_tag_:");
5173
+ for (const [tagKey, members] of this.tagIndex) {
5174
+ const tag = tagKey.startsWith(prefix) ? tagKey.slice(prefix.length) : tagKey;
5175
+ if (matchesTagPattern(pattern, tag)) {
5176
+ matchedTagKeys.push(tagKey);
5177
+ for (const k of members) {
5178
+ this.l1.delete(k);
5179
+ this._bumpKeyMutation(k);
5180
+ this._pendingDiskDeletes.add(k);
5181
+ setImmediate(() => {
5182
+ try {
5183
+ if (!this._diskDisabled) this.disk.delete(k);
5184
+ } finally {
5185
+ this._pendingDiskDeletes.delete(k);
5186
+ }
5187
+ });
5188
+ }
5189
+ }
5190
+ }
5191
+ for (const tagKey of matchedTagKeys) {
5192
+ this.tagIndex.delete(tagKey);
5193
+ }
4978
5194
  }
4979
5195
  this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
4980
5196
  }
@@ -4982,7 +5198,7 @@ var CacheService = class _CacheService {
4982
5198
  _handleBackplaneMessage(message) {
4983
5199
  try {
4984
5200
  const msg = JSON.parse(message);
4985
- 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") {
5201
+ 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") {
4986
5202
  this.logger.warn("Backplane: rejected invalid pubsub message format", {
4987
5203
  raw: typeof message === "string" ? message.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(message)
4988
5204
  });
@@ -5169,12 +5385,12 @@ var CacheService = class _CacheService {
5169
5385
  * Offloads to worker thread if pool is active and payload exceeds threshold.
5170
5386
  */
5171
5387
  async _serializeAndEncrypt(serialized) {
5172
- const isCompressed2 = this.opts.compression && this.opts.compression !== "none" && serialized.length > this.opts.compressionThresholdBytes;
5173
- if (this._workerPool && (this.enc.isEnabled || isCompressed2) && serialized.length > this.opts.workerThresholdBytes) {
5388
+ const isCompressed2 = (this.opts.customCompressor || this.opts.compression && this.opts.compression !== "none") && serialized.length > this.opts.compressionThresholdBytes;
5389
+ if (this._workerPool && !this.opts.customCompressor && (this.enc.isEnabled || isCompressed2) && serialized.length > this.opts.workerThresholdBytes) {
5174
5390
  return this._workerPool.encrypt(serialized);
5175
5391
  }
5176
5392
  if (isCompressed2) {
5177
- const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression);
5393
+ const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression, this.opts.customCompressor);
5178
5394
  if (this.enc.isEnabled) {
5179
5395
  const encrypted = this.enc.encryptBuffer(compressed);
5180
5396
  return PREFIX_ENC_COMPRESSED + encrypted.toString("base64");
@@ -5189,16 +5405,16 @@ var CacheService = class _CacheService {
5189
5405
  */
5190
5406
  async _decryptAndDeserialize(raw) {
5191
5407
  let plain;
5192
- if (this._workerPool && raw.length > this.opts.workerThresholdBytes) {
5408
+ if (this._workerPool && !this.opts.customCompressor && raw.length > this.opts.workerThresholdBytes) {
5193
5409
  plain = await this._workerPool.decrypt(raw);
5194
5410
  } else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
5195
5411
  const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), "base64");
5196
5412
  const decBuf = this.enc.decryptBuffer(encBuf);
5197
- const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
5413
+ const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
5198
5414
  plain = decompressed.toString("utf8");
5199
5415
  } else if (raw.startsWith(PREFIX_COMPRESSED)) {
5200
5416
  const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), "base64");
5201
- const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
5417
+ const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
5202
5418
  plain = decompressed.toString("utf8");
5203
5419
  } else if (raw.startsWith("enc:v1:") || this.enc.isEnabled) {
5204
5420
  plain = this.enc.decrypt(raw);
@@ -5594,7 +5810,7 @@ var CacheService = class _CacheService {
5594
5810
  const optRefreshAhead = opts.refreshAhead;
5595
5811
  const optXfetchBeta = opts.xfetchBeta;
5596
5812
  const optNotFoundTtl = opts.notFoundTtl;
5597
- const optTags = opts.tags;
5813
+ const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
5598
5814
  const l1Hit = this.l1.get(k);
5599
5815
  if (l1Hit !== null) {
5600
5816
  let isGenerationalStale = false;
@@ -6052,15 +6268,16 @@ var CacheService = class _CacheService {
6052
6268
  this._pendingDiskDeletes.delete(k);
6053
6269
  this.counters.sets++;
6054
6270
  let activeTagVersions;
6055
- if (opts?.tags?.length) {
6271
+ const tagsToRegister = opts?.tags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
6272
+ if (tagsToRegister?.length) {
6056
6273
  if (this.opts.tagStrategy === "generational") {
6057
- const vers = await Promise.all(opts.tags.map((tag) => this._getTagVersion(tag)));
6274
+ const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
6058
6275
  activeTagVersions = {};
6059
- for (let i = 0; i < opts.tags.length; i++) {
6060
- activeTagVersions[opts.tags[i]] = vers[i];
6276
+ for (let i = 0; i < tagsToRegister.length; i++) {
6277
+ activeTagVersions[tagsToRegister[i]] = vers[i];
6061
6278
  }
6062
6279
  } else {
6063
- await this._registerTags(k, opts.tags, ttlSeconds);
6280
+ await this._registerTags(k, tagsToRegister, ttlSeconds);
6064
6281
  }
6065
6282
  }
6066
6283
  this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
@@ -6675,16 +6892,23 @@ var CacheService = class _CacheService {
6675
6892
  }
6676
6893
  }
6677
6894
  }
6678
- if (missKeys.length > 0) {
6895
+ if (missKeys.length > 0 && fetchFn) {
6679
6896
  this.counters.fetches++;
6680
6897
  const fetched = await fetchFn(missKeys);
6898
+ const isMap = fetched instanceof Map;
6681
6899
  const setPromises = [];
6682
6900
  for (let j = 0; j < missKeys.length; j++) {
6683
- const v = fetched[missKeys[j]];
6901
+ const k = missKeys[j];
6902
+ const v = isMap ? fetched.get(k) : fetched[k];
6684
6903
  result[missIndexes[j]] = v;
6685
- if (v !== void 0) {
6686
- const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
6687
- setPromises.push(this.set(missKeys[j], v, resolvedTtl, priority));
6904
+ if (v !== void 0 && v !== null) {
6905
+ const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
6906
+ setPromises.push(this.set(k, v, resolvedTtl, priority));
6907
+ } else if (v == null && this.opts.notFoundTtl > 0) {
6908
+ setPromises.push(this.set(k, null, this.opts.notFoundTtl, priority));
6909
+ } else if (v === null) {
6910
+ const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
6911
+ setPromises.push(this.set(k, null, resolvedTtl, priority));
6688
6912
  }
6689
6913
  }
6690
6914
  if (setPromises.length > 0) {
@@ -6827,21 +7051,109 @@ var CacheService = class _CacheService {
6827
7051
  }
6828
7052
  }
6829
7053
  /**
6830
- * Invalidate all keys associated with a tag.
6831
- * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
7054
+ * Discovers all concrete tag names in the system that match `tag` either via
7055
+ * glob wildcards ('*' or '?') or parent-child hierarchy cascading.
7056
+ * Scans local in-memory indices (tagIndex, tagVersions, L1 entries) and Redis (if connected).
7057
+ */
7058
+ async _resolveMatchingTags(tag, shouldCascade) {
7059
+ const isPattern = isWildcardTag(tag);
7060
+ const delim = this.opts.tagHierarchyDelimiter;
7061
+ const matched = /* @__PURE__ */ new Set();
7062
+ const tagMatches = (t) => {
7063
+ if (t === tag) return true;
7064
+ if (isPattern && matchesTagPattern(tag, t)) return true;
7065
+ if (shouldCascade && isChildTag(tag, t, delim)) return true;
7066
+ return false;
7067
+ };
7068
+ if (shouldCascade && !isPattern) {
7069
+ matched.add(tag);
7070
+ }
7071
+ const tagPrefix = this.nk("_tag_:");
7072
+ for (const tagKey of this.tagIndex.keys()) {
7073
+ const t = tagKey.startsWith(tagPrefix) ? tagKey.slice(tagPrefix.length) : tagKey;
7074
+ if (tagMatches(t)) matched.add(t);
7075
+ }
7076
+ for (const t of this.tagVersions.keys()) {
7077
+ if (tagMatches(t)) matched.add(t);
7078
+ }
7079
+ this.l1.scan((_k, entry) => {
7080
+ if (entry.tagVersions) {
7081
+ for (const t of Object.keys(entry.tagVersions)) {
7082
+ if (tagMatches(t)) matched.add(t);
7083
+ }
7084
+ }
7085
+ }, 0);
7086
+ if (!this._redisDisabled) {
7087
+ try {
7088
+ const client = await this.getRedis();
7089
+ if (this.opts.tagStrategy === "generational") {
7090
+ const redisPattern = isPattern ? this.nk(`tag_ver:${tag}`) : this.nk(`tag_ver:${tag}${delim}*`);
7091
+ const scannedKeys = await this._scanKeys(client, redisPattern);
7092
+ const pfx = this.nk("tag_ver:");
7093
+ for (const sk of scannedKeys) {
7094
+ const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
7095
+ if (tagMatches(t)) matched.add(t);
7096
+ }
7097
+ } else {
7098
+ const redisPattern = isPattern ? this.nk(`_tag_:${tag}`) : this.nk(`_tag_:${tag}${delim}*`);
7099
+ const scannedKeys = await this._scanKeys(client, redisPattern);
7100
+ const pfx = this.nk("_tag_:");
7101
+ for (const sk of scannedKeys) {
7102
+ const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
7103
+ if (tagMatches(t)) matched.add(t);
7104
+ }
7105
+ }
7106
+ } catch (err) {
7107
+ this.logger.debug("_resolveMatchingTags: Redis scan failed", { tag, error: err.message });
7108
+ }
7109
+ }
7110
+ return matched;
7111
+ }
7112
+ /**
7113
+ * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
7114
+ * Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
7115
+ *
7116
+ * @param tag Tag name or wildcard glob pattern (e.g. `'catalog'`, `'org:123:*'`, `'*:comments'`).
7117
+ * @param opts Optional invalidation options, including `{ cascade: true }` to invalidate child namespaces.
6832
7118
  *
6833
7119
  * @example
6834
7120
  * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
6835
7121
  * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
7122
+ *
7123
+ * @example
7124
+ * // Wildcard pattern invalidation
7125
+ * await cache.invalidateTag('org:123:*');
7126
+ *
7127
+ * @example
7128
+ * // Hierarchical tag cascading (clears 'org:123' and all child tags like 'org:123:dept:456')
7129
+ * await cache.invalidateTag('org:123', { cascade: true });
6836
7130
  */
6837
- async invalidateTag(tag) {
7131
+ async invalidateTag(tag, opts) {
6838
7132
  this._assertActive("invalidateTag");
6839
7133
  const span = this._startSpan("tricache.invalidate_tag");
6840
7134
  if (this.opts.tracer) {
6841
7135
  span.setAttribute("cache.tag", tag);
6842
7136
  span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
7137
+ if (opts?.cascade) span.setAttribute("cache.cascade", true);
6843
7138
  }
6844
7139
  try {
7140
+ const isPattern = isWildcardTag(tag);
7141
+ const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
7142
+ if (isPattern || shouldCascade) {
7143
+ const matchedTags = await this._resolveMatchingTags(tag, shouldCascade);
7144
+ const delim = this.opts.tagHierarchyDelimiter;
7145
+ const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
7146
+ if (matchedTags.size > 0) {
7147
+ await this.invalidateTags(Array.from(matchedTags));
7148
+ }
7149
+ const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
7150
+ if (this.opts.awaitInvalidationBackplane) {
7151
+ await this.publishInvalidation(op, broadcastPattern, void 0, false, true);
7152
+ } else {
7153
+ void this.publishInvalidation(op, broadcastPattern, void 0, false, true);
7154
+ }
7155
+ return;
7156
+ }
6845
7157
  if (this.opts.tagStrategy === "generational") {
6846
7158
  let newVer = 1;
6847
7159
  if (!this._redisDisabled) {
@@ -6904,21 +7216,35 @@ var CacheService = class _CacheService {
6904
7216
  }
6905
7217
  /**
6906
7218
  * Invalidate all keys associated with any of the given tags in a single operation.
6907
- * Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
6908
- * reducing latency when invalidating several related tags together.
7219
+ * Supports discrete tags, wildcard glob patterns, and hierarchical cascading.
7220
+ * Combines multiple tag invalidations into Redis pipeline round-trips.
6909
7221
  *
6910
- * Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
6911
- * synchronously before the Redis round-trip.
7222
+ * @param tags Array of tag names or wildcard patterns (e.g. `['case:acme', 'org:*']`).
7223
+ * @param opts Optional invalidation options, including `{ cascade: true }`.
6912
7224
  *
6913
7225
  * @example
6914
- * // Instead of three serial round-trips:
6915
- * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
7226
+ * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:*']);
6916
7227
  */
6917
- async invalidateTags(tags) {
7228
+ async invalidateTags(tags, opts) {
6918
7229
  this._assertActive("invalidateTags");
6919
7230
  if (tags.length === 0) return;
7231
+ const hasWildcards = tags.some((t) => isWildcardTag(t));
7232
+ const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
7233
+ if (hasWildcards || shouldCascade) {
7234
+ const allResolvedTags = /* @__PURE__ */ new Set();
7235
+ for (const t of tags) {
7236
+ if (isWildcardTag(t) || shouldCascade) {
7237
+ const resolved = await this._resolveMatchingTags(t, shouldCascade);
7238
+ for (const rt of resolved) allResolvedTags.add(rt);
7239
+ } else {
7240
+ allResolvedTags.add(t);
7241
+ }
7242
+ }
7243
+ if (allResolvedTags.size === 0) return;
7244
+ tags = Array.from(allResolvedTags);
7245
+ }
6920
7246
  if (tags.length === 1) {
6921
- await this.invalidateTag(tags[0]);
7247
+ await this.invalidateTag(tags[0], opts);
6922
7248
  return;
6923
7249
  }
6924
7250
  if (this.opts.tagStrategy === "generational") {
@@ -7665,7 +7991,7 @@ async function runCli(args = process.argv.slice(2)) {
7665
7991
  return;
7666
7992
  }
7667
7993
  if (values.version || command === "version") {
7668
- let version = "0.9.0";
7994
+ let version = "1.0.0";
7669
7995
  try {
7670
7996
  const pkg = JSON.parse((0, import_node_fs3.readFileSync)(new URL("../package.json", import_meta2.url), "utf8"));
7671
7997
  if (pkg?.version) version = pkg.version;
package/dist/cli.js CHANGED
@@ -4,9 +4,9 @@ import {
4
4
  findActiveSockets,
5
5
  renderTopDashboard,
6
6
  resolveIpcSocketPath
7
- } from "./chunk-PL5J3ZNT.js";
8
- import "./chunk-LJ5QJB5O.js";
9
- import "./chunk-XZL45ABR.js";
7
+ } from "./chunk-7SZSQS55.js";
8
+ import "./chunk-UBWLPKTI.js";
9
+ import "./chunk-2AJKEQMZ.js";
10
10
 
11
11
  // src/cli.ts
12
12
  import { readFileSync } from "fs";
@@ -47,7 +47,7 @@ async function runCli(args = process.argv.slice(2)) {
47
47
  return;
48
48
  }
49
49
  if (values.version || command === "version") {
50
- let version = "0.9.0";
50
+ let version = "1.0.0";
51
51
  try {
52
52
  const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
53
53
  if (pkg?.version) version = pkg.version;
@@ -1,6 +1,6 @@
1
1
  import http, { IncomingMessage, ServerResponse } from 'node:http';
2
- import { C as CacheService } from '../cache-service-DVvroyqA.js';
3
- import '../types-B_QkVwJ7.js';
2
+ import { C as CacheService } from '../cache-service-pJ-nFcVj.js';
3
+ import '../types-5HXqBfAf.js';
4
4
  import 'crypto';
5
5
 
6
6
  interface DashboardPeerInstance {