tricache 0.9.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +7 -3
  2. package/dist/{cache-service-DVvroyqA.d.ts → cache-service-CREOp7MM.d.ts} +57 -12
  3. package/dist/{cache-service-KI5ACF3F.js → cache-service-MG7PN6MX.js} +3 -3
  4. package/dist/{chunk-XZL45ABR.js → chunk-2AJKEQMZ.js} +54 -1
  5. package/dist/{chunk-QNU7B43J.js → chunk-3I5L7K6I.js} +17 -0
  6. package/dist/{chunk-PL5J3ZNT.js → chunk-JYQFQJNJ.js} +682 -277
  7. package/dist/{chunk-LJ5QJB5O.js → chunk-UBWLPKTI.js} +127 -11
  8. package/dist/cli.cjs +857 -293
  9. package/dist/cli.js +4 -4
  10. package/dist/dashboard/index.d.ts +2 -2
  11. package/dist/drizzle/index.cjs +865 -294
  12. package/dist/drizzle/index.d.ts +2 -2
  13. package/dist/drizzle/index.js +1 -1
  14. package/dist/edge/index.cjs +115 -36
  15. package/dist/edge/index.d.ts +3 -3
  16. package/dist/edge/index.js +88 -37
  17. package/dist/hono/index.cjs +865 -294
  18. package/dist/hono/index.d.ts +2 -2
  19. package/dist/hono/index.js +1 -1
  20. package/dist/{hono-VA9A1m0I.d.ts → hono-DSV2ve66.d.ts} +11 -4
  21. package/dist/http/index.cjs +917 -315
  22. package/dist/http/index.d.ts +3 -3
  23. package/dist/http/index.js +60 -29
  24. package/dist/index.cjs +885 -294
  25. package/dist/index.d.ts +37 -7
  26. package/dist/index.js +16 -6
  27. package/dist/nestjs/index.cjs +856 -292
  28. package/dist/nestjs/index.d.ts +2 -2
  29. package/dist/nestjs/index.js +4 -4
  30. package/dist/next/index.cjs +858 -300
  31. package/dist/next/index.d.ts +2 -2
  32. package/dist/next/index.js +5 -11
  33. package/dist/prisma/index.d.ts +2 -2
  34. package/dist/serialize-worker.cjs +127 -9
  35. package/dist/serialize-worker.js +8 -4
  36. package/dist/{types-B_QkVwJ7.d.ts → types-Dyip5wAl.d.ts} +53 -7
  37. package/package.json +7 -4
  38. package/src/adapters/node-redis.ts +19 -0
  39. package/src/cache-service.ts +781 -297
  40. package/src/cli.ts +1 -1
  41. package/src/compression.ts +193 -15
  42. package/src/cross-region.ts +1 -1
  43. package/src/edge/cache.ts +94 -42
  44. package/src/env.d.ts +13 -0
  45. package/src/http/express.ts +55 -16
  46. package/src/http/fastify.ts +3 -7
  47. package/src/index.ts +9 -1
  48. package/src/next/cache-handler.ts +1 -4
  49. package/src/next/isr-handler.ts +1 -4
  50. package/src/serialize-worker.ts +6 -2
  51. package/src/smart-memory-cache.ts +3 -2
  52. package/src/types.ts +45 -5
  53. package/src/utils/tag-matcher.ts +90 -0
package/dist/cli.cjs CHANGED
@@ -1427,7 +1427,7 @@ var SmartMemoryCache = class {
1427
1427
  };
1428
1428
  return hit;
1429
1429
  }
1430
- set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
1430
+ set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions, setAt) {
1431
1431
  const packed = this.codec.encode(data);
1432
1432
  const size = packed.byteLength;
1433
1433
  this.compressions++;
@@ -1464,7 +1464,7 @@ var SmartMemoryCache = class {
1464
1464
  priority,
1465
1465
  ttlMs,
1466
1466
  delta,
1467
- setAt: now2,
1467
+ setAt: setAt ?? now2,
1468
1468
  tagVersions
1469
1469
  });
1470
1470
  }
@@ -1492,7 +1492,7 @@ var SmartMemoryCache = class {
1492
1492
  }
1493
1493
  const now = Date.now();
1494
1494
  const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
1495
- this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: now, tagVersions });
1495
+ this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: setAt ?? now, tagVersions });
1496
1496
  if (!existingEntry) this.bloom.add(key);
1497
1497
  this.maybeRebuildBloom();
1498
1498
  this.totalSize += size;
@@ -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;
2052
+ return null;
2053
+ }
2054
+ };
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;
1946
2061
  return null;
1947
2062
  }
1948
2063
  };
1949
- const result = algorithm === "gzip" ? tryGzip() ?? tryBrotli() : tryBrotli() ?? tryGzip();
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;
@@ -4084,6 +4249,8 @@ var CacheService = class _CacheService {
4084
4249
  _l1Counters = /* @__PURE__ */ new Map();
4085
4250
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
4086
4251
  tagIndex = /* @__PURE__ */ new Map();
4252
+ /** Reverse index of namespaced key → { tags, expiresAt } for bounded cleanup on eviction/delete */
4253
+ keyTags = /* @__PURE__ */ new Map();
4087
4254
  /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
4088
4255
  tagVersions = /* @__PURE__ */ new Map();
4089
4256
  /**
@@ -4091,6 +4258,9 @@ var CacheService = class _CacheService {
4091
4258
  * When an exact-key delete matches a registered pattern, all dependents are cascaded.
4092
4259
  */
4093
4260
  dependencyIndex = /* @__PURE__ */ new Map();
4261
+ /** Reverse index of namespaced dependent key → source glob patterns */
4262
+ keyDependencies = /* @__PURE__ */ new Map();
4263
+ _cgroupMemoryLimit;
4094
4264
  redis = null;
4095
4265
  redisConnecting = null;
4096
4266
  cb;
@@ -4160,6 +4330,84 @@ var CacheService = class _CacheService {
4160
4330
  _getKeyMutationEpoch(namespacedKey) {
4161
4331
  return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
4162
4332
  }
4333
+ _removeKeyTags(namespacedKey) {
4334
+ const entry = this.keyTags.get(namespacedKey);
4335
+ if (!entry) return;
4336
+ for (const tag of entry.tags) {
4337
+ const tagKey = this.nk(`_tag_:${tag}`);
4338
+ const members = this.tagIndex.get(tagKey);
4339
+ if (members) {
4340
+ members.delete(namespacedKey);
4341
+ if (members.size === 0) this.tagIndex.delete(tagKey);
4342
+ }
4343
+ }
4344
+ this.keyTags.delete(namespacedKey);
4345
+ }
4346
+ _removeKeyDependencies(namespacedKey) {
4347
+ const patterns = this.keyDependencies.get(namespacedKey);
4348
+ if (patterns) {
4349
+ for (const pat of patterns) {
4350
+ const deps = this.dependencyIndex.get(pat);
4351
+ if (deps) {
4352
+ deps.delete(namespacedKey);
4353
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
4354
+ }
4355
+ }
4356
+ this.keyDependencies.delete(namespacedKey);
4357
+ } else if (this.dependencyIndex.size > 0) {
4358
+ for (const [pat, deps] of this.dependencyIndex) {
4359
+ deps.delete(namespacedKey);
4360
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
4361
+ }
4362
+ }
4363
+ }
4364
+ _handleL1Eviction(namespacedKey, reason) {
4365
+ const spilledToDisk = !this._diskDisabled && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
4366
+ if (!spilledToDisk) {
4367
+ this._removeKeyTags(namespacedKey);
4368
+ this._removeKeyDependencies(namespacedKey);
4369
+ }
4370
+ }
4371
+ _removePrefixFromIndices(prefix) {
4372
+ for (const k of Array.from(this.keyTags.keys())) {
4373
+ if (k.startsWith(prefix)) this._removeKeyTags(k);
4374
+ }
4375
+ for (const k of Array.from(this.keyDependencies.keys())) {
4376
+ if (k.startsWith(prefix)) this._removeKeyDependencies(k);
4377
+ }
4378
+ for (const k of Array.from(this._l1Counters.keys())) {
4379
+ if (k.startsWith(prefix)) this._l1Counters.delete(k);
4380
+ }
4381
+ }
4382
+ _sweepExpiredMetadata() {
4383
+ const now = Date.now();
4384
+ for (const [k, c] of this._l1Counters) {
4385
+ if (c.expiresAt <= now) this._l1Counters.delete(k);
4386
+ }
4387
+ for (const [k, meta] of this.keyTags) {
4388
+ if (meta.expiresAt <= now && !this.l1.has(k)) {
4389
+ this._removeKeyTags(k);
4390
+ this._removeKeyDependencies(k);
4391
+ }
4392
+ }
4393
+ }
4394
+ _runOomCheck() {
4395
+ const heap = import_node_v82.default.getHeapStatistics();
4396
+ const heapUsed = heap.used_heap_size / heap.heap_size_limit;
4397
+ const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? process.memoryUsage().rss / this._cgroupMemoryLimit : 0;
4398
+ const used = Math.max(heapUsed, cgroupUsed);
4399
+ if (used >= this.opts.oomHeapThreshold) {
4400
+ const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
4401
+ this.counters.oomEvictions++;
4402
+ this.counters.oomLastAt = Date.now();
4403
+ this.logger.warn("tricache OOM guard: emergency L1 eviction", {
4404
+ heapUsedPct: Math.round(heapUsed * 100),
4405
+ cgroupUsedPct: cgroupUsed > 0 ? Math.round(cgroupUsed * 100) : void 0,
4406
+ threshold: Math.round(this.opts.oomHeapThreshold * 100),
4407
+ evicted
4408
+ });
4409
+ }
4410
+ }
4163
4411
  _ipcServer;
4164
4412
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
4165
4413
  _subDisconnectedAt = null;
@@ -4206,6 +4454,7 @@ var CacheService = class _CacheService {
4206
4454
  constructor(options = {}) {
4207
4455
  const logger = options.logger ?? consoleLogger;
4208
4456
  this.logger = logger;
4457
+ this._cgroupMemoryLimit = readCgroupMemoryLimit();
4209
4458
  const ns = options.namespace?.trim() ?? "";
4210
4459
  const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
4211
4460
  this.enc = new CacheEncryption(
@@ -4283,12 +4532,15 @@ var CacheService = class _CacheService {
4283
4532
  redisSentinel: options.redisSentinel,
4284
4533
  redisProtocol: options.redisProtocol,
4285
4534
  useShardedPubSub: options.useShardedPubSub ?? false,
4286
- compression: options.compression ?? "none",
4535
+ compression: options.compression ?? "zstd",
4536
+ customCompressor: options.customCompressor,
4287
4537
  compressionThresholdBytes: options.compressionThresholdBytes ?? 1024,
4288
4538
  strictSingleton: options.strictSingleton ?? false,
4289
4539
  failClosed: options.failClosed ?? false,
4290
4540
  tagStrategy: options.tagStrategy ?? "set",
4291
4541
  tagVersionTtlMs: options.tagVersionTtlMs ?? 5e3,
4542
+ hierarchicalTags: options.hierarchicalTags ?? false,
4543
+ tagHierarchyDelimiter: options.tagHierarchyDelimiter ?? ":",
4292
4544
  cloneStrategy: options.cloneStrategy ?? "none",
4293
4545
  backplaneMode: options.backplaneMode ?? "pubsub",
4294
4546
  backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
@@ -4361,6 +4613,7 @@ var CacheService = class _CacheService {
4361
4613
  diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs
4362
4614
  });
4363
4615
  this._namespace = ns;
4616
+ this.prefixLen = ns ? ns.length + 1 : 0;
4364
4617
  this._redisDisabled = this.opts.disableRedis || !this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
4365
4618
  this.watchdog = new TierLatencyWatchdog({
4366
4619
  enabled: options.diskLatencyWatchdog ?? true,
@@ -4385,7 +4638,10 @@ var CacheService = class _CacheService {
4385
4638
  void this.disk.save(key, entry);
4386
4639
  });
4387
4640
  },
4388
- onEviction: options.onEviction,
4641
+ onEviction: (key, reason) => {
4642
+ this._handleL1Eviction(key, reason);
4643
+ options.onEviction?.(key, reason);
4644
+ },
4389
4645
  logger
4390
4646
  });
4391
4647
  if (!this.snapshotLoaded) {
@@ -4423,6 +4679,7 @@ var CacheService = class _CacheService {
4423
4679
  }
4424
4680
  this.cleanupInterval = setInterval(() => {
4425
4681
  const cleaned = this.l1.cleanup();
4682
+ this._sweepExpiredMetadata();
4426
4683
  if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
4427
4684
  }, 5 * 60 * 1e3);
4428
4685
  if (this.cleanupInterval.unref) this.cleanupInterval.unref();
@@ -4435,18 +4692,7 @@ var CacheService = class _CacheService {
4435
4692
  }
4436
4693
  if (this.opts.oomProtection) {
4437
4694
  this.oomInterval = setInterval(() => {
4438
- const heap = import_node_v82.default.getHeapStatistics();
4439
- const used = heap.used_heap_size / heap.heap_size_limit;
4440
- if (used >= this.opts.oomHeapThreshold) {
4441
- const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
4442
- this.counters.oomEvictions++;
4443
- this.counters.oomLastAt = Date.now();
4444
- this.logger.warn("tricache OOM guard: emergency L1 eviction", {
4445
- heapUsedPct: Math.round(used * 100),
4446
- threshold: Math.round(this.opts.oomHeapThreshold * 100),
4447
- evicted
4448
- });
4449
- }
4695
+ this._runOomCheck();
4450
4696
  }, this.opts.oomCheckIntervalMs);
4451
4697
  if (this.oomInterval.unref) this.oomInterval.unref();
4452
4698
  }
@@ -4470,6 +4716,9 @@ var CacheService = class _CacheService {
4470
4716
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
4471
4717
  this.initBackplane();
4472
4718
  const startupPromises = [];
4719
+ if (this.opts.compression === "zstd") {
4720
+ startupPromises.push(initZstd().then(() => void 0));
4721
+ }
4473
4722
  if (this.opts.remoteSnapshot) {
4474
4723
  startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
4475
4724
  }
@@ -4918,7 +5167,7 @@ var CacheService = class _CacheService {
4918
5167
  else if (f === "src") src = v;
4919
5168
  else if (f === "tagVersion") tagVersionRaw = v;
4920
5169
  }
4921
- const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
5170
+ const validOp = op === "del" || op === "del-glob" || op === "tag_incr" || op === "tag_pattern_incr" || op === "tag_pattern_del";
4922
5171
  if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
4923
5172
  this.logger.warn("Backplane: rejected invalid stream entry", {
4924
5173
  op: String(op).slice(0, 40),
@@ -4975,6 +5224,50 @@ var CacheService = class _CacheService {
4975
5224
  const tag = key;
4976
5225
  const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
4977
5226
  this._setLocalTagVersion(tag, ver, performance.now());
5227
+ } else if (op === "tag_pattern_incr") {
5228
+ const pattern = key;
5229
+ const now = performance.now();
5230
+ for (const [tag, info] of this.tagVersions) {
5231
+ if (matchesTagPattern(pattern, tag)) {
5232
+ this._setLocalTagVersion(tag, info.version + 1, now);
5233
+ }
5234
+ }
5235
+ this.l1.scan((k, entry) => {
5236
+ if (entry.tagVersions) {
5237
+ for (const tag of Object.keys(entry.tagVersions)) {
5238
+ if (matchesTagPattern(pattern, tag)) {
5239
+ this.l1.delete(k);
5240
+ this._bumpKeyMutation(k);
5241
+ break;
5242
+ }
5243
+ }
5244
+ }
5245
+ }, 0);
5246
+ } else if (op === "tag_pattern_del") {
5247
+ const pattern = key;
5248
+ const matchedTagKeys = [];
5249
+ const prefix = this.nk("_tag_:");
5250
+ for (const [tagKey, members] of this.tagIndex) {
5251
+ const tag = tagKey.startsWith(prefix) ? tagKey.slice(prefix.length) : tagKey;
5252
+ if (matchesTagPattern(pattern, tag)) {
5253
+ matchedTagKeys.push(tagKey);
5254
+ for (const k of members) {
5255
+ this.l1.delete(k);
5256
+ this._bumpKeyMutation(k);
5257
+ this._pendingDiskDeletes.add(k);
5258
+ setImmediate(() => {
5259
+ try {
5260
+ if (!this._diskDisabled) this.disk.delete(k);
5261
+ } finally {
5262
+ this._pendingDiskDeletes.delete(k);
5263
+ }
5264
+ });
5265
+ }
5266
+ }
5267
+ }
5268
+ for (const tagKey of matchedTagKeys) {
5269
+ this.tagIndex.delete(tagKey);
5270
+ }
4978
5271
  }
4979
5272
  this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
4980
5273
  }
@@ -4982,7 +5275,7 @@ var CacheService = class _CacheService {
4982
5275
  _handleBackplaneMessage(message) {
4983
5276
  try {
4984
5277
  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") {
5278
+ 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
5279
  this.logger.warn("Backplane: rejected invalid pubsub message format", {
4987
5280
  raw: typeof message === "string" ? message.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(message)
4988
5281
  });
@@ -5136,6 +5429,72 @@ var CacheService = class _CacheService {
5136
5429
  }
5137
5430
  this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
5138
5431
  }
5432
+ async _isGenerationalEntryStale(tagVersions) {
5433
+ if (this.opts.tagStrategy !== "generational" || !tagVersions) return false;
5434
+ const tags = Object.keys(tagVersions);
5435
+ if (tags.length === 0) return false;
5436
+ const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5437
+ for (let i = 0; i < tags.length; i++) {
5438
+ if (currentVers[i] > tagVersions[tags[i]]) return true;
5439
+ }
5440
+ return false;
5441
+ }
5442
+ async _deleteRedisKeys(client, keys) {
5443
+ if (keys.length === 0) return;
5444
+ const CHUNK_SIZE = 1e3;
5445
+ if (client instanceof import_ioredis.Cluster) {
5446
+ for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
5447
+ const chunk = keys.slice(i, i + CHUNK_SIZE);
5448
+ const pl = client.pipeline();
5449
+ for (const k of chunk) pl.del(k);
5450
+ await pl.exec();
5451
+ }
5452
+ return;
5453
+ }
5454
+ for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
5455
+ const chunk = keys.slice(i, i + CHUNK_SIZE);
5456
+ await client.del(...chunk);
5457
+ }
5458
+ }
5459
+ async _parseGenerationalRedisHash(k, hashData) {
5460
+ if (!hashData || !hashData.d) return null;
5461
+ let storedTagVersions = {};
5462
+ if (hashData.tv) {
5463
+ try {
5464
+ storedTagVersions = JSON.parse(hashData.tv);
5465
+ } catch {
5466
+ }
5467
+ }
5468
+ if (await this._isGenerationalEntryStale(storedTagVersions)) {
5469
+ const setAtMs = parseInt(hashData.t, 10) || 0;
5470
+ this._deleteIfStale(k, setAtMs);
5471
+ return { stale: true };
5472
+ }
5473
+ const value = await this._decryptAndDeserialize(hashData.d);
5474
+ return { value, tagVersions: storedTagVersions, stale: false };
5475
+ }
5476
+ async _readRedisEntry(client, k, allowAutoPipeline = false) {
5477
+ if (this.opts.tagStrategy === "generational" && typeof client.hgetall === "function") {
5478
+ try {
5479
+ const hashData = await client.hgetall(k);
5480
+ if (typeof hashData === "string") {
5481
+ const value2 = await this._decryptAndDeserialize(hashData);
5482
+ return { value: value2, stale: false };
5483
+ }
5484
+ if (hashData && hashData.d) {
5485
+ return await this._parseGenerationalRedisHash(k, hashData);
5486
+ }
5487
+ return null;
5488
+ } catch (err) {
5489
+ const msg = err instanceof Error ? err.message : String(err);
5490
+ if (!msg.includes("WRONGTYPE")) throw err;
5491
+ }
5492
+ }
5493
+ const raw = allowAutoPipeline && this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
5494
+ if (raw == null) return null;
5495
+ const value = await this._decryptAndDeserialize(raw);
5496
+ return { value, stale: false };
5497
+ }
5139
5498
  async _getTagVersion(tag) {
5140
5499
  const now = performance.now();
5141
5500
  const local = this.tagVersions.get(tag);
@@ -5169,12 +5528,12 @@ var CacheService = class _CacheService {
5169
5528
  * Offloads to worker thread if pool is active and payload exceeds threshold.
5170
5529
  */
5171
5530
  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) {
5531
+ const isCompressed2 = (this.opts.customCompressor || this.opts.compression && this.opts.compression !== "none") && serialized.length > this.opts.compressionThresholdBytes;
5532
+ if (this._workerPool && !this.opts.customCompressor && (this.enc.isEnabled || isCompressed2) && serialized.length > this.opts.workerThresholdBytes) {
5174
5533
  return this._workerPool.encrypt(serialized);
5175
5534
  }
5176
5535
  if (isCompressed2) {
5177
- const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression);
5536
+ const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression, this.opts.customCompressor);
5178
5537
  if (this.enc.isEnabled) {
5179
5538
  const encrypted = this.enc.encryptBuffer(compressed);
5180
5539
  return PREFIX_ENC_COMPRESSED + encrypted.toString("base64");
@@ -5189,16 +5548,16 @@ var CacheService = class _CacheService {
5189
5548
  */
5190
5549
  async _decryptAndDeserialize(raw) {
5191
5550
  let plain;
5192
- if (this._workerPool && raw.length > this.opts.workerThresholdBytes) {
5551
+ if (this._workerPool && !this.opts.customCompressor && raw.length > this.opts.workerThresholdBytes) {
5193
5552
  plain = await this._workerPool.decrypt(raw);
5194
5553
  } else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
5195
5554
  const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), "base64");
5196
5555
  const decBuf = this.enc.decryptBuffer(encBuf);
5197
- const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
5556
+ const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
5198
5557
  plain = decompressed.toString("utf8");
5199
5558
  } else if (raw.startsWith(PREFIX_COMPRESSED)) {
5200
5559
  const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), "base64");
5201
- const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
5560
+ const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
5202
5561
  plain = decompressed.toString("utf8");
5203
5562
  } else if (raw.startsWith("enc:v1:") || this.enc.isEnabled) {
5204
5563
  plain = this.enc.decrypt(raw);
@@ -5273,8 +5632,8 @@ var CacheService = class _CacheService {
5273
5632
  return client;
5274
5633
  }
5275
5634
  this.redisConnecting = (async () => {
5635
+ let client = null;
5276
5636
  try {
5277
- let client;
5278
5637
  if (this.opts.redisClusterNodes?.length) {
5279
5638
  client = new import_ioredis.Cluster(this.opts.redisClusterNodes, {
5280
5639
  redisOptions: {
@@ -5337,14 +5696,45 @@ var CacheService = class _CacheService {
5337
5696
  });
5338
5697
  client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
5339
5698
  }
5699
+ const pendingClient = client;
5340
5700
  await new Promise((resolve, reject) => {
5341
- client.once("ready", resolve);
5342
- client.once("error", (e) => {
5701
+ let settled = false;
5702
+ const cleanupListeners = () => {
5703
+ pendingClient.removeListener?.("ready", onReady);
5704
+ pendingClient.removeListener?.("error", onError);
5705
+ };
5706
+ const onReady = () => {
5707
+ if (settled) return;
5708
+ settled = true;
5709
+ clearTimeout(timer);
5710
+ cleanupListeners();
5711
+ resolve();
5712
+ };
5713
+ const onError = (e) => {
5714
+ if (settled) return;
5715
+ settled = true;
5716
+ clearTimeout(timer);
5717
+ cleanupListeners();
5343
5718
  this._checkAndLogResp3Hint(e);
5344
5719
  reject(e);
5345
- });
5346
- setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
5720
+ };
5721
+ const timer = setTimeout(() => {
5722
+ if (settled) return;
5723
+ settled = true;
5724
+ cleanupListeners();
5725
+ reject(new Error("Redis connection timeout"));
5726
+ }, 15e3);
5727
+ if (timer.unref) timer.unref();
5728
+ pendingClient.once("ready", onReady);
5729
+ pendingClient.once("error", onError);
5347
5730
  });
5731
+ if (this._destroyed) {
5732
+ try {
5733
+ client.disconnect();
5734
+ } catch {
5735
+ }
5736
+ this._assertActive("getRedis");
5737
+ }
5348
5738
  this.cb.onSuccess();
5349
5739
  this.redis = client;
5350
5740
  this.pipeliner = new AutoPipeliner(client, {
@@ -5354,6 +5744,10 @@ var CacheService = class _CacheService {
5354
5744
  this.redisConnecting = null;
5355
5745
  return client;
5356
5746
  } catch (err) {
5747
+ try {
5748
+ client?.disconnect();
5749
+ } catch {
5750
+ }
5357
5751
  this.cb.onFailure();
5358
5752
  this.redisConnecting = null;
5359
5753
  this._checkAndLogResp3Hint(err);
@@ -5594,20 +5988,10 @@ var CacheService = class _CacheService {
5594
5988
  const optRefreshAhead = opts.refreshAhead;
5595
5989
  const optXfetchBeta = opts.xfetchBeta;
5596
5990
  const optNotFoundTtl = opts.notFoundTtl;
5597
- const optTags = opts.tags;
5991
+ const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
5598
5992
  const l1Hit = this.l1.get(k);
5599
5993
  if (l1Hit !== null) {
5600
- let isGenerationalStale = false;
5601
- if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
5602
- const tags = Object.keys(l1Hit.tagVersions);
5603
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5604
- for (let i = 0; i < tags.length; i++) {
5605
- if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
5606
- isGenerationalStale = true;
5607
- break;
5608
- }
5609
- }
5610
- }
5994
+ const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
5611
5995
  if (isGenerationalStale) {
5612
5996
  this._deleteIfStale(k, l1Hit.setAt ?? 0);
5613
5997
  } else {
@@ -5693,17 +6077,7 @@ var CacheService = class _CacheService {
5693
6077
  this.watchdog.recordDisk(diskElapsed);
5694
6078
  this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
5695
6079
  if (diskHit !== null) {
5696
- let isDiskStale = false;
5697
- if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
5698
- const tags = Object.keys(diskHit.tagVersions);
5699
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5700
- for (let i = 0; i < tags.length; i++) {
5701
- if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
5702
- isDiskStale = true;
5703
- break;
5704
- }
5705
- }
5706
- }
6080
+ const isDiskStale = await this._isGenerationalEntryStale(diskHit.tagVersions);
5707
6081
  if (isDiskStale) {
5708
6082
  this.disk.delete(k);
5709
6083
  } else {
@@ -5731,57 +6105,27 @@ var CacheService = class _CacheService {
5731
6105
  try {
5732
6106
  const client = await this.getRedis();
5733
6107
  const redisStart = performance.now();
5734
- if (this.opts.tagStrategy === "generational") {
5735
- const hashData = await client.hgetall(k);
5736
- const redisElapsed = performance.now() - redisStart;
5737
- this.watchdog.recordRedis(redisElapsed);
5738
- this.cb.onSuccess();
5739
- if (hashData && hashData.d) {
5740
- let isStale = false;
5741
- let storedTagVersions = {};
5742
- if (hashData.tv) {
5743
- try {
5744
- storedTagVersions = JSON.parse(hashData.tv);
5745
- } catch {
5746
- }
5747
- }
5748
- const tags = Object.keys(storedTagVersions);
5749
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5750
- for (let i = 0; i < tags.length; i++) {
5751
- if (currentVers[i] > storedTagVersions[tags[i]]) {
5752
- isStale = true;
5753
- break;
5754
- }
5755
- }
5756
- if (isStale) {
5757
- const setAtMs = parseInt(hashData.t, 10) || 0;
5758
- this._deleteIfStale(k, setAtMs);
5759
- } else {
5760
- const parsed = await this._decryptAndDeserialize(hashData.d);
5761
- this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
5762
- this.counters.l2Hits++;
5763
- this.opts.onHit?.(cacheKey, "l2");
5764
- this.logger.debug("L2 hit (Redis hash)", { cacheKey });
5765
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5766
- if (this.opts.frozen) deepFreeze(parsed);
5767
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
5768
- }
5769
- }
5770
- } else {
5771
- const raw = this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
5772
- const redisElapsed = performance.now() - redisStart;
5773
- this.watchdog.recordRedis(redisElapsed);
5774
- this.cb.onSuccess();
5775
- if (raw) {
5776
- const parsed = await this._decryptAndDeserialize(raw);
5777
- this.l1.set(k, parsed, ttlMs, priority);
5778
- this.counters.l2Hits++;
5779
- this.opts.onHit?.(cacheKey, "l2");
5780
- this.logger.debug("L2 hit (Redis)", { cacheKey });
5781
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5782
- if (this.opts.frozen) deepFreeze(parsed);
5783
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
6108
+ const redisHit = await this._readRedisEntry(client, k, true);
6109
+ const redisElapsed = performance.now() - redisStart;
6110
+ this.watchdog.recordRedis(redisElapsed);
6111
+ this.cb.onSuccess();
6112
+ if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
6113
+ const parsed = redisHit.value;
6114
+ if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
6115
+ this.logger.debug("Aborting L2 promotion \u2014 key was mutated or deleted during Redis read", { cacheKey });
6116
+ span.setAttribute("cache.aborted_mutation_race", true);
6117
+ const current = this.l1.get(k);
6118
+ const liveVal = current && !current.isStale && current.value !== void 0 ? current.value : parsed;
6119
+ if (this.opts.frozen) deepFreeze(liveVal);
6120
+ return this.opts.cloneStrategy === "structuredClone" && liveVal != null && typeof liveVal === "object" ? structuredClone(liveVal) : liveVal;
5784
6121
  }
6122
+ this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, redisHit.tagVersions);
6123
+ this.counters.l2Hits++;
6124
+ this.opts.onHit?.(cacheKey, "l2");
6125
+ this.logger.debug(redisHit.tagVersions ? "L2 hit (Redis hash)" : "L2 hit (Redis)", { cacheKey });
6126
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
6127
+ if (this.opts.frozen) deepFreeze(parsed);
6128
+ return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
5785
6129
  }
5786
6130
  } catch (err) {
5787
6131
  this.cb.onFailure();
@@ -5843,20 +6187,20 @@ var CacheService = class _CacheService {
5843
6187
  if (this.opts.frozen) deepFreeze(data);
5844
6188
  return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
5845
6189
  }
5846
- this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
6190
+ const writeTs = Date.now();
6191
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs);
5847
6192
  if (!this._redisDisabled) {
5848
6193
  try {
5849
6194
  const client = await this.getRedis();
5850
6195
  const serialized = JSON.stringify(data);
5851
6196
  const toStore = await this._serializeAndEncrypt(serialized);
5852
6197
  const ttlSec = Math.ceil(effectiveTtl / 1e3);
5853
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
5854
- const now = Date.now();
6198
+ if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
5855
6199
  const tx = client.multi();
5856
6200
  tx.hset(k, {
5857
6201
  d: toStore,
5858
- t: String(now),
5859
- tv: JSON.stringify(activeTagVersions)
6202
+ t: String(writeTs),
6203
+ tv: JSON.stringify(activeTagVersions ?? {})
5860
6204
  });
5861
6205
  tx.expire(k, ttlSec);
5862
6206
  await tx.exec();
@@ -5994,20 +6338,20 @@ var CacheService = class _CacheService {
5994
6338
  this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
5995
6339
  return;
5996
6340
  }
5997
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
6341
+ const writeTs = Date.now();
6342
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs);
5998
6343
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
5999
6344
  try {
6000
6345
  const client = await this.getRedis();
6001
6346
  const s = JSON.stringify(data);
6002
6347
  const stored = await this._serializeAndEncrypt(s);
6003
6348
  const ttlSec = Math.ceil(ttlMs / 1e3);
6004
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
6005
- const now = Date.now();
6349
+ if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
6006
6350
  const tx = client.multi();
6007
6351
  tx.hset(cacheKey, {
6008
6352
  d: stored,
6009
- t: String(now),
6010
- tv: JSON.stringify(activeTagVersions)
6353
+ t: String(writeTs),
6354
+ tv: JSON.stringify(activeTagVersions ?? {})
6011
6355
  });
6012
6356
  tx.expire(cacheKey, ttlSec);
6013
6357
  await tx.exec();
@@ -6052,27 +6396,35 @@ var CacheService = class _CacheService {
6052
6396
  this._pendingDiskDeletes.delete(k);
6053
6397
  this.counters.sets++;
6054
6398
  let activeTagVersions;
6055
- if (opts?.tags?.length) {
6399
+ const tagsToRegister = opts?.tags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
6400
+ if (tagsToRegister?.length) {
6056
6401
  if (this.opts.tagStrategy === "generational") {
6057
- const vers = await Promise.all(opts.tags.map((tag) => this._getTagVersion(tag)));
6402
+ const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
6058
6403
  activeTagVersions = {};
6059
- for (let i = 0; i < opts.tags.length; i++) {
6060
- activeTagVersions[opts.tags[i]] = vers[i];
6404
+ for (let i = 0; i < tagsToRegister.length; i++) {
6405
+ activeTagVersions[tagsToRegister[i]] = vers[i];
6061
6406
  }
6062
6407
  } else {
6063
- await this._registerTags(k, opts.tags, ttlSeconds);
6408
+ await this._registerTags(k, tagsToRegister, ttlSeconds);
6064
6409
  }
6065
6410
  }
6066
- this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
6067
- if (opts?.dependsOn?.length) {
6068
- for (const pattern of opts.dependsOn) {
6069
- const nsPattern = this.nk(pattern);
6070
- let deps = this.dependencyIndex.get(nsPattern);
6071
- if (!deps) {
6072
- deps = /* @__PURE__ */ new Set();
6073
- this.dependencyIndex.set(nsPattern, deps);
6411
+ const writeTs = Date.now();
6412
+ this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions, writeTs);
6413
+ if (opts?.dependsOn !== void 0) {
6414
+ this._removeKeyDependencies(k);
6415
+ if (opts.dependsOn.length > 0) {
6416
+ const nsPatterns = [];
6417
+ for (const pattern of opts.dependsOn) {
6418
+ const nsPattern = this.nk(pattern);
6419
+ nsPatterns.push(nsPattern);
6420
+ let deps = this.dependencyIndex.get(nsPattern);
6421
+ if (!deps) {
6422
+ deps = /* @__PURE__ */ new Set();
6423
+ this.dependencyIndex.set(nsPattern, deps);
6424
+ }
6425
+ deps.add(k);
6074
6426
  }
6075
- deps.add(k);
6427
+ this.keyDependencies.set(k, nsPatterns);
6076
6428
  }
6077
6429
  }
6078
6430
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
@@ -6081,13 +6433,12 @@ var CacheService = class _CacheService {
6081
6433
  const s = JSON.stringify(data);
6082
6434
  const stored = await this._serializeAndEncrypt(s);
6083
6435
  const ttlSec = Math.ceil(ttlMs / 1e3);
6084
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
6085
- const now = Date.now();
6436
+ if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
6086
6437
  const tx = client.multi();
6087
6438
  tx.hset(k, {
6088
6439
  d: stored,
6089
- t: String(now),
6090
- tv: JSON.stringify(activeTagVersions)
6440
+ t: String(writeTs),
6441
+ tv: JSON.stringify(activeTagVersions ?? {})
6091
6442
  });
6092
6443
  tx.expire(k, ttlSec);
6093
6444
  await tx.exec();
@@ -6122,7 +6473,18 @@ var CacheService = class _CacheService {
6122
6473
  * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
6123
6474
  */
6124
6475
  async _registerTags(k, tags, ttlSeconds) {
6125
- for (const tag of tags) {
6476
+ this._removeKeyTags(k);
6477
+ const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
6478
+ const expiresAt = Date.now() + effectiveTtl * 1e3;
6479
+ if (this.keyTags.size >= 1e5 && !this.keyTags.has(k)) {
6480
+ this._sweepExpiredMetadata();
6481
+ if (this.keyTags.size >= 1e5) {
6482
+ const oldestKey = this.keyTags.keys().next().value;
6483
+ if (oldestKey !== void 0) this._removeKeyTags(oldestKey);
6484
+ }
6485
+ }
6486
+ const uniqueTags = Array.from(new Set(tags));
6487
+ for (const tag of uniqueTags) {
6126
6488
  const tagKey = this.nk(`_tag_:${tag}`);
6127
6489
  let members = this.tagIndex.get(tagKey);
6128
6490
  if (!members) {
@@ -6131,14 +6493,15 @@ var CacheService = class _CacheService {
6131
6493
  }
6132
6494
  members.add(k);
6133
6495
  }
6496
+ this.keyTags.set(k, { tags: uniqueTags, expiresAt });
6134
6497
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6135
6498
  try {
6136
6499
  const client = await this.getRedis();
6137
6500
  const pl = client.pipeline();
6138
- for (const tag of tags) {
6501
+ for (const tag of uniqueTags) {
6139
6502
  const tagKey = this.nk(`_tag_:${tag}`);
6140
6503
  pl.sadd(tagKey, k);
6141
- pl.expire(tagKey, ttlSeconds + 3600);
6504
+ pl.expire(tagKey, effectiveTtl + 3600);
6142
6505
  }
6143
6506
  await pl.exec();
6144
6507
  this.cb.onSuccess();
@@ -6177,6 +6540,13 @@ var CacheService = class _CacheService {
6177
6540
  }
6178
6541
  this._addPatternTombstone(pfx);
6179
6542
  this.l1.deletePattern(k);
6543
+ this._removePrefixFromIndices(pfx);
6544
+ for (const ktKey of Array.from(this.keyTags.keys())) {
6545
+ if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
6546
+ }
6547
+ for (const kdKey of Array.from(this.keyDependencies.keys())) {
6548
+ if (this._matchesGlob(kdKey, k)) this._removeKeyDependencies(kdKey);
6549
+ }
6180
6550
  } else {
6181
6551
  this._bumpKeyMutation(k);
6182
6552
  this.inflight.delete(k);
@@ -6189,15 +6559,16 @@ var CacheService = class _CacheService {
6189
6559
  this._pendingDiskDeletes.delete(k);
6190
6560
  }
6191
6561
  });
6562
+ this._removeKeyTags(k);
6192
6563
  this._cascadeDependencies(k);
6193
- for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
6564
+ this._removeKeyDependencies(k);
6194
6565
  }
6195
6566
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6196
6567
  try {
6197
6568
  const client = await this.getRedis();
6198
6569
  if (isPattern) {
6199
6570
  const keys = await this._scanKeys(client, k);
6200
- if (keys.length > 0) await client.del(...keys);
6571
+ await this._deleteRedisKeys(client, keys);
6201
6572
  } else {
6202
6573
  if (this.opts.autoPipeline && this.pipeliner) {
6203
6574
  await this.pipeliner.del(k);
@@ -6259,6 +6630,15 @@ var CacheService = class _CacheService {
6259
6630
  entry.value++;
6260
6631
  return entry.value;
6261
6632
  }
6633
+ if (this._l1Counters.size >= 5e4 && !this._l1Counters.has(k)) {
6634
+ for (const [ck, cv] of this._l1Counters) {
6635
+ if (cv.expiresAt <= now) this._l1Counters.delete(ck);
6636
+ }
6637
+ if (this._l1Counters.size >= 5e4) {
6638
+ const oldest = this._l1Counters.keys().next().value;
6639
+ if (oldest !== void 0) this._l1Counters.delete(oldest);
6640
+ }
6641
+ }
6262
6642
  this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
6263
6643
  return 1;
6264
6644
  }
@@ -6305,6 +6685,7 @@ var CacheService = class _CacheService {
6305
6685
  }
6306
6686
  this._addPatternTombstone(pfx);
6307
6687
  this.l1.deletePattern(k);
6688
+ this._removePrefixFromIndices(pfx);
6308
6689
  } else {
6309
6690
  this._globalEpoch++;
6310
6691
  this.inflight.clear();
@@ -6313,7 +6694,10 @@ var CacheService = class _CacheService {
6313
6694
  if (!this._diskDisabled) this.disk.clear();
6314
6695
  this._l1Counters.clear();
6315
6696
  this.tagIndex.clear();
6697
+ this.keyTags.clear();
6316
6698
  this.tagVersions.clear();
6699
+ this.dependencyIndex.clear();
6700
+ this.keyDependencies.clear();
6317
6701
  this._pendingDiskDeletes.clear();
6318
6702
  this._keyMutationEpochs.clear();
6319
6703
  }
@@ -6322,7 +6706,7 @@ var CacheService = class _CacheService {
6322
6706
  const client = await this.getRedis();
6323
6707
  const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
6324
6708
  const keys = await this._scanKeys(client, pattern);
6325
- if (keys.length > 0) await client.del(...keys);
6709
+ await this._deleteRedisKeys(client, keys);
6326
6710
  } catch (err) {
6327
6711
  this.logger.debug("clear: Redis unavailable", { error: err.message });
6328
6712
  }
@@ -6465,6 +6849,10 @@ var CacheService = class _CacheService {
6465
6849
  this._assertActive("touch");
6466
6850
  const k = this.nk(cacheKey);
6467
6851
  const hit = this.l1.touch(k, newTtlSeconds * 1e3);
6852
+ if (hit) {
6853
+ const kt = this.keyTags.get(k);
6854
+ if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1e3;
6855
+ }
6468
6856
  if (hit && !this._redisDisabled) {
6469
6857
  try {
6470
6858
  const client = await this.getRedis();
@@ -6492,6 +6880,10 @@ var CacheService = class _CacheService {
6492
6880
  if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
6493
6881
  return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
6494
6882
  }
6883
+ _prepareReadValue(val) {
6884
+ if (this.opts.frozen) deepFreeze(val);
6885
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6886
+ }
6495
6887
  /**
6496
6888
  * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
6497
6889
  * Returns the cached value if found and valid, or `null` if absent / expired.
@@ -6505,11 +6897,13 @@ var CacheService = class _CacheService {
6505
6897
  const k = this.nk(cacheKey);
6506
6898
  const l1Hit = this.l1.get(k);
6507
6899
  if (l1Hit !== null) {
6508
- this.counters.gets++;
6509
- this.counters.l1Hits++;
6510
- const val = l1Hit.value;
6511
- if (this.opts.frozen) deepFreeze(val);
6512
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6900
+ if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
6901
+ this._deleteIfStale(k, l1Hit.setAt ?? 0);
6902
+ } else {
6903
+ this.counters.gets++;
6904
+ this.counters.l1Hits++;
6905
+ return this._prepareReadValue(l1Hit.value);
6906
+ }
6513
6907
  }
6514
6908
  if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
6515
6909
  if (this._isTombstonedByPattern(k)) {
@@ -6524,18 +6918,20 @@ var CacheService = class _CacheService {
6524
6918
  this.watchdog.recordDisk(diskElapsed);
6525
6919
  this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6526
6920
  if (diskHit !== null) {
6527
- const promoted = this.l1.importEntries(
6528
- [{ key: k, entry: diskHit }],
6529
- this.opts.forbiddenSnapshotPrefixes
6530
- );
6531
- if (promoted > 0) {
6532
- const l1Check = this.l1.get(k);
6533
- if (l1Check !== null) {
6534
- this.counters.gets++;
6535
- this.counters.diskHits++;
6536
- const val = l1Check.value;
6537
- if (this.opts.frozen) deepFreeze(val);
6538
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6921
+ if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
6922
+ this.disk.delete(k);
6923
+ } else {
6924
+ const promoted = this.l1.importEntries(
6925
+ [{ key: k, entry: diskHit }],
6926
+ this.opts.forbiddenSnapshotPrefixes
6927
+ );
6928
+ if (promoted > 0) {
6929
+ const l1Check = this.l1.get(k);
6930
+ if (l1Check !== null) {
6931
+ this.counters.gets++;
6932
+ this.counters.diskHits++;
6933
+ return this._prepareReadValue(l1Check.value);
6934
+ }
6539
6935
  }
6540
6936
  }
6541
6937
  }
@@ -6545,17 +6941,16 @@ var CacheService = class _CacheService {
6545
6941
  try {
6546
6942
  const client = await this.getRedis();
6547
6943
  const redisStart = performance.now();
6548
- const raw = await client.get(k);
6944
+ const redisHit = await this._readRedisEntry(client, k);
6549
6945
  const redisElapsed = performance.now() - redisStart;
6550
6946
  this.watchdog.recordRedis(redisElapsed);
6551
- if (raw !== null) {
6552
- const parsed = await this._decryptAndDeserialize(raw);
6553
- this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
6947
+ this.cb.onSuccess();
6948
+ if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
6949
+ const parsed = redisHit.value;
6950
+ this.l1.set(k, parsed, 6e4, inferPriority(cacheKey), void 0, void 0, redisHit.tagVersions);
6554
6951
  this.counters.gets++;
6555
6952
  this.counters.l2Hits++;
6556
- this.cb.onSuccess();
6557
- if (this.opts.frozen) deepFreeze(parsed);
6558
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
6953
+ return this._prepareReadValue(parsed);
6559
6954
  }
6560
6955
  } catch (err) {
6561
6956
  this.cb.onFailure();
@@ -6583,12 +6978,20 @@ var CacheService = class _CacheService {
6583
6978
  const result = Array.from({ length: keys.length });
6584
6979
  const missIndexes = [];
6585
6980
  const missKeys = [];
6981
+ const now = Date.now();
6586
6982
  for (let i = 0; i < keys.length; i++) {
6587
6983
  const k = this.nk(keys[i]);
6588
6984
  const entry = this.l1.getEntry(k);
6589
- if (entry && entry.expiresAt > Date.now()) {
6590
- result[i] = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
6591
- this.counters.l1Hits++;
6985
+ if (entry && entry.expiresAt > now) {
6986
+ if (await this._isGenerationalEntryStale(entry.tagVersions)) {
6987
+ this._deleteIfStale(k, entry.setAt ?? 0);
6988
+ missIndexes.push(i);
6989
+ missKeys.push(keys[i]);
6990
+ } else {
6991
+ const val = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
6992
+ result[i] = this._prepareReadValue(val);
6993
+ this.counters.l1Hits++;
6994
+ }
6592
6995
  } else {
6593
6996
  missIndexes.push(i);
6594
6997
  missKeys.push(keys[i]);
@@ -6609,23 +7012,57 @@ var CacheService = class _CacheService {
6609
7012
  const client = await this.getRedis();
6610
7013
  const nsKeys = missKeys.map((k) => this.nk(k));
6611
7014
  const pipeline = client.multi();
6612
- for (const nk of nsKeys) pipeline.get(nk);
7015
+ const useHashPipeline = this.opts.tagStrategy === "generational" && typeof pipeline.hgetall === "function";
7016
+ for (const nk of nsKeys) {
7017
+ if (useHashPipeline) {
7018
+ pipeline.hgetall(nk);
7019
+ } else {
7020
+ pipeline.get(nk);
7021
+ }
7022
+ }
6613
7023
  const redisStart = performance.now();
6614
7024
  const raws = await pipeline.exec();
6615
7025
  const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
6616
7026
  this.watchdog.recordRedis(redisElapsed);
6617
7027
  this.cb.onSuccess();
6618
7028
  for (let j = 0; j < missKeys.length; j++) {
6619
- const raw = raws[j] ? raws[j][1] : null;
7029
+ const tuple = raws[j];
7030
+ const err = tuple ? tuple[0] : null;
7031
+ const rawVal = tuple ? tuple[1] : null;
6620
7032
  const idx = missIndexes[j];
6621
- if (raw) {
6622
- const parsed = await this._decryptAndDeserialize(raw);
6623
- const k = nsKeys[j];
7033
+ const k = nsKeys[j];
7034
+ let parsed;
7035
+ let tagVersions;
7036
+ let hit = false;
7037
+ if (useHashPipeline) {
7038
+ if (err && err.message?.includes("WRONGTYPE")) {
7039
+ const fallbackRaw = await client.get(k);
7040
+ if (fallbackRaw) {
7041
+ parsed = await this._decryptAndDeserialize(fallbackRaw);
7042
+ hit = true;
7043
+ }
7044
+ } else if (!err && typeof rawVal === "string") {
7045
+ parsed = await this._decryptAndDeserialize(rawVal);
7046
+ hit = true;
7047
+ } else if (!err && rawVal && typeof rawVal === "object" && rawVal.d) {
7048
+ const hashHit = await this._parseGenerationalRedisHash(k, rawVal);
7049
+ if (hashHit && !hashHit.stale && hashHit.value !== void 0) {
7050
+ parsed = hashHit.value;
7051
+ tagVersions = hashHit.tagVersions;
7052
+ hit = true;
7053
+ }
7054
+ }
7055
+ } else if (!err && rawVal) {
7056
+ parsed = await this._decryptAndDeserialize(rawVal);
7057
+ hit = true;
7058
+ }
7059
+ if (hit && parsed !== void 0) {
6624
7060
  const p = priority ?? inferPriority(missKeys[j]);
6625
- this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
7061
+ const ttlVal = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
7062
+ this.l1.set(k, parsed, this._jitterTtl(ttlVal * 1e3), p, void 0, void 0, tagVersions);
6626
7063
  this.counters.l2Hits++;
6627
7064
  l2HitCount++;
6628
- result[idx] = parsed;
7065
+ result[idx] = this._prepareReadValue(parsed);
6629
7066
  missIndexes[j] = -1;
6630
7067
  missKeys[j] = "";
6631
7068
  }
@@ -6659,6 +7096,10 @@ var CacheService = class _CacheService {
6659
7096
  this.watchdog.recordDisk(diskElapsed);
6660
7097
  this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6661
7098
  if (diskHit !== null) {
7099
+ if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
7100
+ this.disk.delete(k);
7101
+ continue;
7102
+ }
6662
7103
  const promoted = this.l1.importEntries(
6663
7104
  [{ key: k, entry: diskHit }],
6664
7105
  this.opts.forbiddenSnapshotPrefixes
@@ -6667,7 +7108,7 @@ var CacheService = class _CacheService {
6667
7108
  const l1Check = this.l1.get(k);
6668
7109
  if (l1Check !== null) {
6669
7110
  this.counters.diskHits++;
6670
- result[missIndexes[j]] = l1Check.value;
7111
+ result[missIndexes[j]] = this._prepareReadValue(l1Check.value);
6671
7112
  missIndexes.splice(j, 1);
6672
7113
  missKeys.splice(j, 1);
6673
7114
  }
@@ -6675,16 +7116,23 @@ var CacheService = class _CacheService {
6675
7116
  }
6676
7117
  }
6677
7118
  }
6678
- if (missKeys.length > 0) {
7119
+ if (missKeys.length > 0 && fetchFn) {
6679
7120
  this.counters.fetches++;
6680
7121
  const fetched = await fetchFn(missKeys);
7122
+ const isMap = fetched instanceof Map;
6681
7123
  const setPromises = [];
6682
7124
  for (let j = 0; j < missKeys.length; j++) {
6683
- const v = fetched[missKeys[j]];
7125
+ const k = missKeys[j];
7126
+ const v = isMap ? fetched.get(k) : fetched[k];
6684
7127
  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));
7128
+ if (v !== void 0 && v !== null) {
7129
+ const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
7130
+ setPromises.push(this.set(k, v, resolvedTtl, priority));
7131
+ } else if (v == null && this.opts.notFoundTtl > 0) {
7132
+ setPromises.push(this.set(k, null, this.opts.notFoundTtl, priority));
7133
+ } else if (v === null) {
7134
+ const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
7135
+ setPromises.push(this.set(k, null, resolvedTtl, priority));
6688
7136
  }
6689
7137
  }
6690
7138
  if (setPromises.length > 0) {
@@ -6827,98 +7275,135 @@ var CacheService = class _CacheService {
6827
7275
  }
6828
7276
  }
6829
7277
  /**
6830
- * Invalidate all keys associated with a tag.
6831
- * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
6832
- *
6833
- * @example
6834
- * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
6835
- * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
7278
+ * Discovers all concrete tag names in the system that match `tag` either via
7279
+ * glob wildcards ('*' or '?') or parent-child hierarchy cascading.
7280
+ * Scans local in-memory indices (tagIndex, tagVersions, L1 entries) and Redis (if connected).
6836
7281
  */
6837
- async invalidateTag(tag) {
6838
- this._assertActive("invalidateTag");
6839
- const span = this._startSpan("tricache.invalidate_tag");
6840
- if (this.opts.tracer) {
6841
- span.setAttribute("cache.tag", tag);
6842
- span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
7282
+ async _resolveMatchingTags(tag, shouldCascade) {
7283
+ const isPattern = isWildcardTag(tag);
7284
+ const delim = this.opts.tagHierarchyDelimiter;
7285
+ const matched = /* @__PURE__ */ new Set();
7286
+ const tagMatches = (t) => {
7287
+ if (t === tag) return true;
7288
+ if (isPattern && matchesTagPattern(tag, t)) return true;
7289
+ if (shouldCascade && isChildTag(tag, t, delim)) return true;
7290
+ return false;
7291
+ };
7292
+ if (shouldCascade && !isPattern) {
7293
+ matched.add(tag);
6843
7294
  }
6844
- try {
6845
- if (this.opts.tagStrategy === "generational") {
6846
- let newVer = 1;
6847
- if (!this._redisDisabled) {
6848
- try {
6849
- const client = await this.getRedis();
6850
- newVer = await client.incr(this.nk(`tag_ver:${tag}`));
6851
- } catch (err) {
6852
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
6853
- const current = this.tagVersions.get(tag)?.version ?? 0;
6854
- newVer = current + 1;
6855
- }
6856
- } else {
6857
- const current = this.tagVersions.get(tag)?.version ?? 0;
6858
- newVer = current + 1;
6859
- }
6860
- this._setLocalTagVersion(tag, newVer, performance.now());
6861
- if (this.opts.awaitInvalidationBackplane) {
6862
- await this.publishInvalidation("tag_incr", tag, newVer, false, true);
6863
- } else {
6864
- void this.publishInvalidation("tag_incr", tag, newVer, false, true);
7295
+ const tagPrefix = this.nk("_tag_:");
7296
+ for (const tagKey of this.tagIndex.keys()) {
7297
+ const t = tagKey.startsWith(tagPrefix) ? tagKey.slice(tagPrefix.length) : tagKey;
7298
+ if (tagMatches(t)) matched.add(t);
7299
+ }
7300
+ for (const t of this.tagVersions.keys()) {
7301
+ if (tagMatches(t)) matched.add(t);
7302
+ }
7303
+ this.l1.scan((_k, entry) => {
7304
+ if (entry.tagVersions) {
7305
+ for (const t of Object.keys(entry.tagVersions)) {
7306
+ if (tagMatches(t)) matched.add(t);
6865
7307
  }
6866
- return;
6867
7308
  }
6868
- const tagKey = this.nk(`_tag_:${tag}`);
6869
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
6870
- for (const k of members) {
6871
- this.l1.delete(k);
6872
- this._bumpKeyMutation(k);
6873
- this._pendingDiskDeletes.add(k);
6874
- setImmediate(() => {
6875
- try {
6876
- if (!this._diskDisabled) this.disk.delete(k);
6877
- } finally {
6878
- this._pendingDiskDeletes.delete(k);
7309
+ }, 0);
7310
+ if (!this._redisDisabled) {
7311
+ try {
7312
+ const client = await this.getRedis();
7313
+ if (this.opts.tagStrategy === "generational") {
7314
+ const redisPattern = isPattern ? this.nk(`tag_ver:${tag}`) : this.nk(`tag_ver:${tag}${delim}*`);
7315
+ const scannedKeys = await this._scanKeys(client, redisPattern);
7316
+ const pfx = this.nk("tag_ver:");
7317
+ for (const sk of scannedKeys) {
7318
+ const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
7319
+ if (tagMatches(t)) matched.add(t);
6879
7320
  }
6880
- });
7321
+ } else {
7322
+ const redisPattern = isPattern ? this.nk(`_tag_:${tag}`) : this.nk(`_tag_:${tag}${delim}*`);
7323
+ const scannedKeys = await this._scanKeys(client, redisPattern);
7324
+ const pfx = this.nk("_tag_:");
7325
+ for (const sk of scannedKeys) {
7326
+ const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
7327
+ if (tagMatches(t)) matched.add(t);
7328
+ }
7329
+ }
7330
+ } catch (err) {
7331
+ this.logger.debug("_resolveMatchingTags: Redis scan failed", { tag, error: err.message });
6881
7332
  }
6882
- this.tagIndex.delete(tagKey);
7333
+ }
7334
+ return matched;
7335
+ }
7336
+ async _publishTagInvalidation(op, key, tagVersion) {
7337
+ if (this.opts.awaitInvalidationBackplane) {
7338
+ await this.publishInvalidation(op, key, tagVersion, false, true);
7339
+ } else {
7340
+ void this.publishInvalidation(op, key, tagVersion, false, true);
7341
+ }
7342
+ }
7343
+ _removeTagMembersLocal(keys) {
7344
+ const keyList = Array.isArray(keys) ? keys : Array.from(keys);
7345
+ for (const k of keyList) {
7346
+ this.l1.delete(k);
7347
+ this._bumpKeyMutation(k);
7348
+ this._removeKeyTags(k);
7349
+ this._removeKeyDependencies(k);
7350
+ this._pendingDiskDeletes.add(k);
7351
+ setImmediate(() => {
7352
+ try {
7353
+ if (!this._diskDisabled) this.disk.delete(k);
7354
+ } finally {
7355
+ this._pendingDiskDeletes.delete(k);
7356
+ }
7357
+ });
7358
+ }
7359
+ }
7360
+ /**
7361
+ * Executes invalidation for a single already-resolved concrete tag without
7362
+ * wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
7363
+ */
7364
+ async _invalidateConcreteTag(tag) {
7365
+ if (this.opts.tagStrategy === "generational") {
7366
+ let newVer = 1;
6883
7367
  if (!this._redisDisabled) {
6884
7368
  try {
6885
7369
  const client = await this.getRedis();
6886
- const redisMembers = await client.smembers(tagKey);
6887
- const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
6888
- if (toDelete.length > 0) {
6889
- await client.del(...toDelete, tagKey);
6890
- } else {
6891
- await client.del(tagKey);
6892
- }
7370
+ newVer = await client.incr(this.nk(`tag_ver:${tag}`));
6893
7371
  } catch (err) {
6894
7372
  this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7373
+ const current = this.tagVersions.get(tag)?.version ?? 0;
7374
+ newVer = current + 1;
6895
7375
  }
7376
+ } else {
7377
+ const current = this.tagVersions.get(tag)?.version ?? 0;
7378
+ newVer = current + 1;
7379
+ }
7380
+ this._setLocalTagVersion(tag, newVer, performance.now());
7381
+ await this._publishTagInvalidation("tag_incr", tag, newVer);
7382
+ return;
7383
+ }
7384
+ const tagKey = this.nk(`_tag_:${tag}`);
7385
+ const members = Array.from(this.tagIndex.get(tagKey) ?? []);
7386
+ this.tagIndex.delete(tagKey);
7387
+ this._removeTagMembersLocal(members);
7388
+ if (!this._redisDisabled) {
7389
+ try {
7390
+ const client = await this.getRedis();
7391
+ const redisMembers = await client.smembers(tagKey);
7392
+ const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers, tagKey])];
7393
+ await this._deleteRedisKeys(client, toDelete);
7394
+ } catch (err) {
7395
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
6896
7396
  }
6897
- } catch (err) {
6898
- span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
6899
- span.recordException?.(err);
6900
- throw err;
6901
- } finally {
6902
- span.end();
6903
7397
  }
6904
7398
  }
6905
7399
  /**
6906
- * 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.
6909
- *
6910
- * Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
6911
- * synchronously before the Redis round-trip.
6912
- *
6913
- * @example
6914
- * // Instead of three serial round-trips:
6915
- * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
7400
+ * Executes invalidation for an array of already-resolved concrete tags
7401
+ * without re-entering wildcard/cascade resolution or invalidateTag().
6916
7402
  */
6917
- async invalidateTags(tags) {
6918
- this._assertActive("invalidateTags");
7403
+ async _invalidateConcreteTags(tags) {
6919
7404
  if (tags.length === 0) return;
6920
7405
  if (tags.length === 1) {
6921
- await this.invalidateTag(tags[0]);
7406
+ await this._invalidateConcreteTag(tags[0]);
6922
7407
  return;
6923
7408
  }
6924
7409
  if (this.opts.tagStrategy === "generational") {
@@ -6933,11 +7418,7 @@ var CacheService = class _CacheService {
6933
7418
  const [err, newVer] = results[i] ?? [null, null];
6934
7419
  const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
6935
7420
  this._setLocalTagVersion(tags[i], ver, now);
6936
- if (this.opts.awaitInvalidationBackplane) {
6937
- await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
6938
- } else {
6939
- void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
6940
- }
7421
+ await this._publishTagInvalidation("tag_incr", tags[i], ver);
6941
7422
  }
6942
7423
  return;
6943
7424
  } catch (err) {
@@ -6947,11 +7428,7 @@ var CacheService = class _CacheService {
6947
7428
  for (const tag of tags) {
6948
7429
  const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
6949
7430
  this._setLocalTagVersion(tag, ver, now);
6950
- if (this.opts.awaitInvalidationBackplane) {
6951
- await this.publishInvalidation("tag_incr", tag, ver, false, true);
6952
- } else {
6953
- void this.publishInvalidation("tag_incr", tag, ver, false, true);
6954
- }
7431
+ await this._publishTagInvalidation("tag_incr", tag, ver);
6955
7432
  }
6956
7433
  return;
6957
7434
  }
@@ -6964,18 +7441,7 @@ var CacheService = class _CacheService {
6964
7441
  for (const k of members) allMembers.add(k);
6965
7442
  this.tagIndex.delete(tagKey);
6966
7443
  }
6967
- for (const k of allMembers) {
6968
- this.l1.delete(k);
6969
- this._bumpKeyMutation(k);
6970
- this._pendingDiskDeletes.add(k);
6971
- setImmediate(() => {
6972
- try {
6973
- if (!this._diskDisabled) this.disk.delete(k);
6974
- } finally {
6975
- this._pendingDiskDeletes.delete(k);
6976
- }
6977
- });
6978
- }
7444
+ this._removeTagMembersLocal(allMembers);
6979
7445
  if (!this._redisDisabled) {
6980
7446
  try {
6981
7447
  const client = await this.getRedis();
@@ -6991,12 +7457,103 @@ var CacheService = class _CacheService {
6991
7457
  }
6992
7458
  }
6993
7459
  const keysToRemove = [...toDelete, ...tagKeys];
6994
- if (keysToRemove.length > 0) await client.del(...keysToRemove);
7460
+ await this._deleteRedisKeys(client, keysToRemove);
6995
7461
  } catch (err) {
6996
7462
  this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
6997
7463
  }
6998
7464
  }
6999
7465
  }
7466
+ /**
7467
+ * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
7468
+ * Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
7469
+ *
7470
+ * @param tag Tag name or wildcard glob pattern (e.g. `'catalog'`, `'org:123:*'`, `'*:comments'`).
7471
+ * @param opts Optional invalidation options, including `{ cascade: true }` to invalidate child namespaces.
7472
+ *
7473
+ * @example
7474
+ * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
7475
+ * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
7476
+ *
7477
+ * @example
7478
+ * // Wildcard pattern invalidation
7479
+ * await cache.invalidateTag('org:123:*');
7480
+ *
7481
+ * @example
7482
+ * // Hierarchical tag cascading (clears 'org:123' and all child tags like 'org:123:dept:456')
7483
+ * await cache.invalidateTag('org:123', { cascade: true });
7484
+ */
7485
+ async invalidateTag(tag, opts) {
7486
+ this._assertActive("invalidateTag");
7487
+ const span = this._startSpan("tricache.invalidate_tag");
7488
+ if (this.opts.tracer) {
7489
+ span.setAttribute("cache.tag", tag);
7490
+ span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
7491
+ if (opts?.cascade) span.setAttribute("cache.cascade", true);
7492
+ }
7493
+ try {
7494
+ const isPattern = isWildcardTag(tag);
7495
+ const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
7496
+ if (isPattern || shouldCascade) {
7497
+ const matchedTags = await this._resolveMatchingTags(tag, shouldCascade);
7498
+ const delim = this.opts.tagHierarchyDelimiter;
7499
+ const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
7500
+ if (matchedTags.size > 0) {
7501
+ await this._invalidateConcreteTags(Array.from(matchedTags));
7502
+ }
7503
+ const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
7504
+ await this._publishTagInvalidation(op, broadcastPattern);
7505
+ return;
7506
+ }
7507
+ await this._invalidateConcreteTag(tag);
7508
+ } catch (err) {
7509
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
7510
+ span.recordException?.(err);
7511
+ throw err;
7512
+ } finally {
7513
+ span.end();
7514
+ }
7515
+ }
7516
+ /**
7517
+ * Invalidate all keys associated with any of the given tags in a single operation.
7518
+ * Supports discrete tags, wildcard glob patterns, and hierarchical cascading.
7519
+ * Combines multiple tag invalidations into Redis pipeline round-trips.
7520
+ *
7521
+ * @param tags Array of tag names or wildcard patterns (e.g. `['case:acme', 'org:*']`).
7522
+ * @param opts Optional invalidation options, including `{ cascade: true }`.
7523
+ *
7524
+ * @example
7525
+ * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:*']);
7526
+ */
7527
+ async invalidateTags(tags, opts) {
7528
+ this._assertActive("invalidateTags");
7529
+ if (tags.length === 0) return;
7530
+ const hasWildcards = tags.some((t) => isWildcardTag(t));
7531
+ const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
7532
+ if (hasWildcards || shouldCascade) {
7533
+ const allResolvedTags = /* @__PURE__ */ new Set();
7534
+ const broadcastPatterns = /* @__PURE__ */ new Set();
7535
+ const delim = this.opts.tagHierarchyDelimiter;
7536
+ for (const t of tags) {
7537
+ const tIsPattern = isWildcardTag(t);
7538
+ if (tIsPattern || shouldCascade) {
7539
+ broadcastPatterns.add(tIsPattern ? t : `${t}${delim}*`);
7540
+ const resolved = await this._resolveMatchingTags(t, shouldCascade);
7541
+ for (const rt of resolved) allResolvedTags.add(rt);
7542
+ } else {
7543
+ allResolvedTags.add(t);
7544
+ }
7545
+ }
7546
+ if (allResolvedTags.size > 0) {
7547
+ await this._invalidateConcreteTags(Array.from(allResolvedTags));
7548
+ }
7549
+ const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
7550
+ for (const pattern of broadcastPatterns) {
7551
+ await this._publishTagInvalidation(op, pattern);
7552
+ }
7553
+ return;
7554
+ }
7555
+ await this._invalidateConcreteTags(Array.from(new Set(tags)));
7556
+ }
7000
7557
  /**
7001
7558
  * Get the current generational tag version for a tag (synced with Redis when due).
7002
7559
  */
@@ -7562,6 +8119,13 @@ var CacheService = class _CacheService {
7562
8119
  this._destroyed = true;
7563
8120
  this._pendingDiskDeletes.clear();
7564
8121
  this._keyMutationEpochs.clear();
8122
+ this.inflight.clear();
8123
+ this.revalidating.clear();
8124
+ this._l1Counters.clear();
8125
+ this.tagIndex.clear();
8126
+ this.keyTags.clear();
8127
+ this.dependencyIndex.clear();
8128
+ this.keyDependencies.clear();
7565
8129
  const g = globalThis;
7566
8130
  const key = _CacheService.globalKey(this.opts);
7567
8131
  if (g[key] === this) {
@@ -7665,7 +8229,7 @@ async function runCli(args = process.argv.slice(2)) {
7665
8229
  return;
7666
8230
  }
7667
8231
  if (values.version || command === "version") {
7668
- let version = "0.9.0";
8232
+ let version = "1.0.1";
7669
8233
  try {
7670
8234
  const pkg = JSON.parse((0, import_node_fs3.readFileSync)(new URL("../package.json", import_meta2.url), "utf8"));
7671
8235
  if (pkg?.version) version = pkg.version;