tricache 0.8.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +10 -4
  2. package/dashboards/prometheus-scrape.yml +18 -0
  3. package/dist/{cache-service-5MZXFIGK.js → cache-service-26GCO3UU.js} +3 -3
  4. package/dist/{cache-service-CyLdpo77.d.ts → cache-service-pJ-nFcVj.d.ts} +44 -12
  5. package/dist/{chunk-XZL45ABR.js → chunk-2AJKEQMZ.js} +54 -1
  6. package/dist/{chunk-6PQ5MOWR.js → chunk-7SZSQS55.js} +571 -115
  7. package/dist/chunk-BQRURGGD.js +60 -0
  8. package/dist/chunk-IITRFWHY.js +196 -0
  9. package/dist/{chunk-LJ5QJB5O.js → chunk-UBWLPKTI.js} +127 -11
  10. package/dist/cli.cjs +767 -133
  11. package/dist/cli.js +24 -6
  12. package/dist/dashboard/index.d.ts +2 -2
  13. package/dist/drizzle/index.cjs +734 -132
  14. package/dist/drizzle/index.d.ts +2 -2
  15. package/dist/drizzle/index.js +1 -1
  16. package/dist/edge/index.cjs +163 -46
  17. package/dist/edge/index.d.ts +3 -3
  18. package/dist/edge/index.js +42 -14
  19. package/dist/hono/index.cjs +8093 -0
  20. package/dist/hono/index.d.ts +91 -0
  21. package/dist/hono/index.js +185 -0
  22. package/dist/{hono-DQRS1Xd7.d.ts → hono-DuNvciyq.d.ts} +6 -5
  23. package/dist/http/index.cjs +833 -170
  24. package/dist/http/index.d.ts +6 -30
  25. package/dist/http/index.js +9 -59
  26. package/dist/index.cjs +755 -130
  27. package/dist/index.d.ts +35 -6
  28. package/dist/index.js +16 -6
  29. package/dist/nestjs/index.cjs +725 -130
  30. package/dist/nestjs/index.d.ts +2 -2
  31. package/dist/nestjs/index.js +4 -4
  32. package/dist/next/index.cjs +725 -130
  33. package/dist/next/index.d.ts +2 -2
  34. package/dist/next/index.js +3 -3
  35. package/dist/prisma/index.d.ts +2 -2
  36. package/dist/serialize-worker.cjs +127 -9
  37. package/dist/serialize-worker.js +8 -4
  38. package/dist/{types-B6krw64X.d.ts → types-5HXqBfAf.d.ts} +74 -7
  39. package/dist/utils-CEsU_Z0s.d.ts +27 -0
  40. package/package.json +22 -9
  41. package/src/cache-service.ts +540 -68
  42. package/src/cli.ts +21 -4
  43. package/src/compression.ts +193 -15
  44. package/src/cross-region.ts +1 -1
  45. package/src/edge/cache.ts +38 -11
  46. package/src/edge/hono.ts +123 -42
  47. package/src/env.d.ts +13 -0
  48. package/src/hono/index.ts +316 -0
  49. package/src/http/index.ts +5 -0
  50. package/src/index.ts +9 -1
  51. package/src/ipc-telemetry.ts +29 -1
  52. package/src/serialize-worker.ts +6 -2
  53. package/src/types.ts +68 -5
  54. package/src/utils/tag-matcher.ts +90 -0
  55. package/dist/chunk-ZTSWCFYO.js +0 -135
  56. /package/dist/{chunk-QNU7B43J.js → chunk-VXFTFZ5N.js} +0 -0
package/dist/index.cjs CHANGED
@@ -66,6 +66,7 @@ __export(index_exports, {
66
66
  createSigV4SnapshotAdapter: () => createSigV4SnapshotAdapter,
67
67
  deepMergeOptions: () => deepMergeOptions,
68
68
  defaultCodec: () => defaultCodec,
69
+ expandHierarchicalTags: () => expandHierarchicalTags,
69
70
  findActiveSockets: () => findActiveSockets,
70
71
  formatBytes: () => formatBytes,
71
72
  formatDuration: () => formatDuration,
@@ -73,6 +74,10 @@ __export(index_exports, {
73
74
  formatTraceParent: () => formatTraceParent,
74
75
  getV8HeapLimit: () => getV8HeapLimit,
75
76
  handleDashboardRequest: () => handleDashboardRequest,
77
+ initZstd: () => initZstd,
78
+ isChildTag: () => isChildTag,
79
+ isWildcardTag: () => isWildcardTag,
80
+ matchesTagPattern: () => matchesTagPattern,
76
81
  murmur3_32: () => murmur3_32,
77
82
  parseTraceParent: () => parseTraceParent,
78
83
  readCgroupMemoryLimit: () => readCgroupMemoryLimit,
@@ -2252,13 +2257,38 @@ var import_os2 = __toESM(require("os"), 1);
2252
2257
 
2253
2258
  // src/compression.ts
2254
2259
  var import_zlib = __toESM(require("zlib"), 1);
2260
+ var import_lz4js = __toESM(require("lz4js"), 1);
2261
+ var import_zstd_codec = require("zstd-codec");
2255
2262
  var PREFIX_COMPRESSED = "cmp:v1:";
2256
2263
  var PREFIX_ENC_COMPRESSED = "ecp:v1:";
2257
2264
  var COMPRESSION_MAGIC = Buffer.from([84, 82, 67, 1]);
2265
+ var zstdSimple = null;
2266
+ var zstdInitPromise = null;
2267
+ function initZstd() {
2268
+ if (zstdSimple) return Promise.resolve(zstdSimple);
2269
+ if (!zstdInitPromise) {
2270
+ zstdInitPromise = new Promise((resolve) => {
2271
+ try {
2272
+ import_zstd_codec.ZstdCodec.run((zstd) => {
2273
+ zstdSimple = new zstd.Simple();
2274
+ resolve(zstdSimple);
2275
+ });
2276
+ } catch {
2277
+ resolve(null);
2278
+ }
2279
+ });
2280
+ }
2281
+ return zstdInitPromise;
2282
+ }
2283
+ initZstd().catch(() => {
2284
+ });
2258
2285
  function isCompressed(buf) {
2259
2286
  return buf.length >= 4 && buf[0] === 84 && buf[1] === 82 && buf[2] === 67 && buf[3] === 1;
2260
2287
  }
2261
- function compressBuffer(buf, algorithm) {
2288
+ function compressBuffer(buf, algorithm, custom) {
2289
+ if (custom) {
2290
+ return custom.compress(buf);
2291
+ }
2262
2292
  if (algorithm === "brotli") {
2263
2293
  return import_zlib.default.brotliCompressSync(buf, {
2264
2294
  params: {
@@ -2270,37 +2300,127 @@ function compressBuffer(buf, algorithm) {
2270
2300
  if (algorithm === "gzip") {
2271
2301
  return import_zlib.default.gzipSync(buf, { level: 6 });
2272
2302
  }
2303
+ if (algorithm === "lz4") {
2304
+ return Buffer.from(import_lz4js.default.compress(buf));
2305
+ }
2306
+ if (algorithm === "zstd") {
2307
+ if (!zstdSimple) {
2308
+ return import_zlib.default.brotliCompressSync(buf, {
2309
+ params: { [import_zlib.default.constants.BROTLI_PARAM_QUALITY]: 4 }
2310
+ });
2311
+ }
2312
+ return Buffer.from(zstdSimple.compress(buf));
2313
+ }
2273
2314
  return buf;
2274
2315
  }
2275
- function decompressBuffer(buf, algorithm = "brotli") {
2316
+ var MAX_DECOMPRESS_BYTES = 25 * 1024 * 1024;
2317
+ function decompressBuffer(buf, algorithm = "zstd", custom) {
2318
+ if (custom) {
2319
+ const res = custom.decompress(buf);
2320
+ if (res.length > MAX_DECOMPRESS_BYTES) {
2321
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
2322
+ }
2323
+ return res;
2324
+ }
2325
+ const checkSafety = (decomp) => {
2326
+ if (decomp.length > MAX_DECOMPRESS_BYTES) {
2327
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
2328
+ }
2329
+ return decomp;
2330
+ };
2331
+ if (buf.length >= 4 && buf[0] === 40 && buf[1] === 181 && buf[2] === 47 && buf[3] === 253) {
2332
+ if (zstdSimple) {
2333
+ try {
2334
+ return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
2335
+ } catch (err) {
2336
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
2337
+ }
2338
+ }
2339
+ }
2340
+ if (buf.length >= 4 && buf[0] === 4 && buf[1] === 34 && buf[2] === 77 && buf[3] === 24) {
2341
+ try {
2342
+ return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
2343
+ } catch (err) {
2344
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
2345
+ }
2346
+ }
2347
+ if (buf.length >= 2 && buf[0] === 31 && buf[1] === 139) {
2348
+ try {
2349
+ return import_zlib.default.gunzipSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
2350
+ } catch (err) {
2351
+ if (err?.code === "ERR_BUFFER_TOO_LARGE") {
2352
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
2353
+ }
2354
+ }
2355
+ }
2356
+ if (algorithm === "none") {
2357
+ return buf;
2358
+ }
2359
+ if (algorithm === "lz4") {
2360
+ try {
2361
+ return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
2362
+ } catch (err) {
2363
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
2364
+ }
2365
+ }
2366
+ if (algorithm === "zstd" && zstdSimple) {
2367
+ try {
2368
+ return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
2369
+ } catch (err) {
2370
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
2371
+ }
2372
+ }
2276
2373
  const tryBrotli = () => {
2277
2374
  try {
2278
- return import_zlib.default.brotliDecompressSync(buf);
2279
- } catch {
2375
+ return import_zlib.default.brotliDecompressSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
2376
+ } catch (err) {
2377
+ if (err?.code === "ERR_BUFFER_TOO_LARGE") {
2378
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
2379
+ }
2280
2380
  return null;
2281
2381
  }
2282
2382
  };
2283
2383
  const tryGzip = () => {
2284
2384
  try {
2285
- return import_zlib.default.gunzipSync(buf);
2286
- } catch {
2385
+ return import_zlib.default.gunzipSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
2386
+ } catch (err) {
2387
+ if (err?.code === "ERR_BUFFER_TOO_LARGE") {
2388
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
2389
+ }
2390
+ return null;
2391
+ }
2392
+ };
2393
+ const tryLz4 = () => {
2394
+ try {
2395
+ return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
2396
+ } catch (err) {
2397
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
2287
2398
  return null;
2288
2399
  }
2289
2400
  };
2290
- const result = algorithm === "gzip" ? tryGzip() ?? tryBrotli() : tryBrotli() ?? tryGzip();
2401
+ const tryZstd = () => {
2402
+ if (!zstdSimple) return null;
2403
+ try {
2404
+ return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
2405
+ } catch (err) {
2406
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
2407
+ return null;
2408
+ }
2409
+ };
2410
+ const result = (algorithm === "gzip" ? tryGzip() : null) ?? (algorithm === "lz4" ? tryLz4() : null) ?? (algorithm === "zstd" ? tryZstd() : null) ?? tryBrotli() ?? tryGzip() ?? tryLz4() ?? tryZstd();
2291
2411
  if (result === null) {
2292
2412
  throw new Error(`tricache: corrupt compressed payload (${buf.length} bytes, algorithm=${algorithm})`);
2293
2413
  }
2294
2414
  return result;
2295
2415
  }
2296
- function compressWithHeader(buf, algorithm) {
2416
+ function compressWithHeader(buf, algorithm, custom) {
2297
2417
  if (algorithm === "none") return buf;
2298
- const compressed = compressBuffer(buf, algorithm);
2418
+ const compressed = compressBuffer(buf, algorithm, custom);
2299
2419
  return Buffer.concat([COMPRESSION_MAGIC, compressed]);
2300
2420
  }
2301
- function decompressWithHeader(buf, algorithm = "brotli") {
2421
+ function decompressWithHeader(buf, algorithm = "zstd", custom) {
2302
2422
  if (isCompressed(buf)) {
2303
- return decompressBuffer(buf.subarray(4), algorithm);
2423
+ return decompressBuffer(buf.subarray(4), algorithm, custom);
2304
2424
  }
2305
2425
  return buf;
2306
2426
  }
@@ -4006,6 +4126,26 @@ async function findActiveSockets() {
4006
4126
  active.push(currentPipe);
4007
4127
  } catch {
4008
4128
  }
4129
+ try {
4130
+ const { execFileSync } = await import("child_process");
4131
+ const stdout = execFileSync(
4132
+ "powershell.exe",
4133
+ ["-NoProfile", "-NonInteractive", "-Command", '[System.IO.Directory]::GetFiles("\\\\.\\pipe\\") | Where-Object { $_ -like "*tricache-*" }'],
4134
+ { timeout: 1500, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }
4135
+ );
4136
+ const candidates = stdout.split(/\r?\n/).map((name) => name.trim()).filter((name) => name.length > 0 && !active.includes(name));
4137
+ await Promise.all(
4138
+ candidates.map(async (pipePath) => {
4139
+ const testClient = new IpcTelemetryClient(pipePath);
4140
+ try {
4141
+ await testClient.ping(100);
4142
+ active.push(pipePath);
4143
+ } catch {
4144
+ }
4145
+ })
4146
+ );
4147
+ } catch {
4148
+ }
4009
4149
  return active;
4010
4150
  }
4011
4151
  const dir = process.env.TMPDIR || "/tmp";
@@ -4110,6 +4250,55 @@ function renderTopDashboard(payload) {
4110
4250
  return lines.join("\n");
4111
4251
  }
4112
4252
 
4253
+ // src/utils/tag-matcher.ts
4254
+ var globRegexCache = /* @__PURE__ */ new Map();
4255
+ function isWildcardTag(tag) {
4256
+ return tag.includes("*") || tag.includes("?");
4257
+ }
4258
+ function matchesTagPattern(pattern, tag) {
4259
+ if (pattern === "*" || pattern === tag) return true;
4260
+ if (!pattern.includes("*") && !pattern.includes("?")) return pattern === tag;
4261
+ if (pattern.endsWith("*") && !pattern.slice(0, -1).includes("*") && !pattern.includes("?")) {
4262
+ const prefix = pattern.slice(0, -1);
4263
+ return tag.startsWith(prefix);
4264
+ }
4265
+ if (pattern.startsWith("*") && !pattern.slice(1).includes("*") && !pattern.includes("?")) {
4266
+ const suffix = pattern.slice(1);
4267
+ return tag.endsWith(suffix);
4268
+ }
4269
+ let re = globRegexCache.get(pattern);
4270
+ if (!re) {
4271
+ if (globRegexCache.size >= 1e3) globRegexCache.clear();
4272
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
4273
+ re = new RegExp(`^${escaped}$`);
4274
+ globRegexCache.set(pattern, re);
4275
+ }
4276
+ return re.test(tag);
4277
+ }
4278
+ function isChildTag(parentTag, candidateTag, delimiter = ":") {
4279
+ if (candidateTag === parentTag) return true;
4280
+ const prefix = parentTag.endsWith(delimiter) ? parentTag : `${parentTag}${delimiter}`;
4281
+ return candidateTag.startsWith(prefix);
4282
+ }
4283
+ function expandHierarchicalTags(tags, delimiter = ":") {
4284
+ if (!tags.length) return [];
4285
+ const result = /* @__PURE__ */ new Set();
4286
+ for (const tag of tags) {
4287
+ if (!tag) continue;
4288
+ const parts = tag.split(delimiter).filter((p) => p.length > 0);
4289
+ if (parts.length <= 1) {
4290
+ result.add(tag);
4291
+ continue;
4292
+ }
4293
+ let accumulated = "";
4294
+ for (let i = 0; i < parts.length; i++) {
4295
+ accumulated = i === 0 ? parts[i] : `${accumulated}${delimiter}${parts[i]}`;
4296
+ result.add(accumulated);
4297
+ }
4298
+ }
4299
+ return Array.from(result);
4300
+ }
4301
+
4113
4302
  // src/cache-service.ts
4114
4303
  var LUA_COMPARE_AND_DELETE = `
4115
4304
  local currentTs = redis.call('HGET', KEYS[1], 't')
@@ -4128,21 +4317,21 @@ var DEFAULT_CATEGORY_LIMITS = {
4128
4317
  var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
4129
4318
  var DEFAULT_COUNTER_TTL_SECONDS = 60;
4130
4319
  var GLOB_REGEX_CACHE_MAX = 256;
4131
- var globRegexCache = /* @__PURE__ */ new Map();
4320
+ var globRegexCache2 = /* @__PURE__ */ new Map();
4132
4321
  function getGlobRegex(pattern) {
4133
- let re = globRegexCache.get(pattern);
4322
+ let re = globRegexCache2.get(pattern);
4134
4323
  if (re) {
4135
- globRegexCache.delete(pattern);
4136
- globRegexCache.set(pattern, re);
4324
+ globRegexCache2.delete(pattern);
4325
+ globRegexCache2.set(pattern, re);
4137
4326
  return re;
4138
4327
  }
4139
4328
  const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*+/g, ".*");
4140
4329
  re = new RegExp("^" + escaped + "$");
4141
- if (globRegexCache.size >= GLOB_REGEX_CACHE_MAX) {
4142
- const oldestKey = globRegexCache.keys().next().value;
4143
- if (oldestKey !== void 0) globRegexCache.delete(oldestKey);
4330
+ if (globRegexCache2.size >= GLOB_REGEX_CACHE_MAX) {
4331
+ const oldestKey = globRegexCache2.keys().next().value;
4332
+ if (oldestKey !== void 0) globRegexCache2.delete(oldestKey);
4144
4333
  }
4145
- globRegexCache.set(pattern, re);
4334
+ globRegexCache2.set(pattern, re);
4146
4335
  return re;
4147
4336
  }
4148
4337
  var L2CircuitBreaker = class {
@@ -4396,6 +4585,7 @@ var CacheService = class _CacheService {
4396
4585
  opts;
4397
4586
  /** Pre-computed once — opts.namespace never changes after construction. */
4398
4587
  _namespace;
4588
+ prefixLen;
4399
4589
  /** Pre-computed once — disableRedis and redisHost never change after construction. */
4400
4590
  _redisDisabled;
4401
4591
  watchdog;
@@ -4435,6 +4625,52 @@ var CacheService = class _CacheService {
4435
4625
  streamClient = null;
4436
4626
  _lastStreamId = "$";
4437
4627
  _destroyed = false;
4628
+ _pendingDiskDeletes = /* @__PURE__ */ new Set();
4629
+ _globalEpoch = 0;
4630
+ _keyMutationEpochs = /* @__PURE__ */ new Map();
4631
+ /**
4632
+ * Pattern tombstones for disk tier.
4633
+ * Files in the disk tier are keyed by SHA-256 of namespacedKey.
4634
+ * Wildcard pattern deletes cannot scan the filesystem synchronously, so we maintain
4635
+ * pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
4636
+ */
4637
+ _patternTombstones = [];
4638
+ _addPatternTombstone(prefix) {
4639
+ const now = Date.now();
4640
+ while (this._patternTombstones.length > 0 && now - this._patternTombstones[0].createdAt > 36e5) {
4641
+ this._patternTombstones.shift();
4642
+ }
4643
+ if (this._patternTombstones.length >= 2e3) {
4644
+ this._patternTombstones.shift();
4645
+ }
4646
+ this._patternTombstones.push({ prefix, createdAt: now });
4647
+ }
4648
+ _isTombstonedByPattern(namespacedKey) {
4649
+ if (this._patternTombstones.length === 0) return false;
4650
+ for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
4651
+ if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
4652
+ return true;
4653
+ }
4654
+ }
4655
+ return false;
4656
+ }
4657
+ _assertActive(operation) {
4658
+ if (this._destroyed) {
4659
+ throw new Error(`TriCacheError: Cannot perform '${operation}' on a destroyed CacheService instance (namespace: '${this._namespace || "(default)"}').`);
4660
+ }
4661
+ }
4662
+ _bumpKeyMutation(namespacedKey) {
4663
+ const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
4664
+ this._keyMutationEpochs.set(namespacedKey, next);
4665
+ if (this._keyMutationEpochs.size > 5e4) {
4666
+ const oldest = this._keyMutationEpochs.keys().next().value;
4667
+ if (oldest !== void 0) this._keyMutationEpochs.delete(oldest);
4668
+ }
4669
+ return next;
4670
+ }
4671
+ _getKeyMutationEpoch(namespacedKey) {
4672
+ return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
4673
+ }
4438
4674
  _ipcServer;
4439
4675
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
4440
4676
  _subDisconnectedAt = null;
@@ -4523,6 +4759,8 @@ var CacheService = class _CacheService {
4523
4759
  ),
4524
4760
  snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
4525
4761
  invalidationBackplane: options.invalidationBackplane ?? true,
4762
+ awaitInvalidationBackplane: options.awaitInvalidationBackplane ?? false,
4763
+ lockFailClosed: options.lockFailClosed ?? false,
4526
4764
  oomProtection: options.oomProtection ?? true,
4527
4765
  oomHeapThreshold: options.oomHeapThreshold ?? 0.85,
4528
4766
  oomCheckIntervalMs: options.oomCheckIntervalMs ?? 1e4,
@@ -4556,12 +4794,15 @@ var CacheService = class _CacheService {
4556
4794
  redisSentinel: options.redisSentinel,
4557
4795
  redisProtocol: options.redisProtocol,
4558
4796
  useShardedPubSub: options.useShardedPubSub ?? false,
4559
- compression: options.compression ?? "none",
4797
+ compression: options.compression ?? "zstd",
4798
+ customCompressor: options.customCompressor,
4560
4799
  compressionThresholdBytes: options.compressionThresholdBytes ?? 1024,
4561
4800
  strictSingleton: options.strictSingleton ?? false,
4562
4801
  failClosed: options.failClosed ?? false,
4563
4802
  tagStrategy: options.tagStrategy ?? "set",
4564
4803
  tagVersionTtlMs: options.tagVersionTtlMs ?? 5e3,
4804
+ hierarchicalTags: options.hierarchicalTags ?? false,
4805
+ tagHierarchyDelimiter: options.tagHierarchyDelimiter ?? ":",
4565
4806
  cloneStrategy: options.cloneStrategy ?? "none",
4566
4807
  backplaneMode: options.backplaneMode ?? "pubsub",
4567
4808
  backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
@@ -4634,6 +4875,7 @@ var CacheService = class _CacheService {
4634
4875
  diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs
4635
4876
  });
4636
4877
  this._namespace = ns;
4878
+ this.prefixLen = ns ? ns.length + 1 : 0;
4637
4879
  this._redisDisabled = this.opts.disableRedis || !this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
4638
4880
  this.watchdog = new TierLatencyWatchdog({
4639
4881
  enabled: options.diskLatencyWatchdog ?? true,
@@ -4743,6 +4985,9 @@ var CacheService = class _CacheService {
4743
4985
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
4744
4986
  this.initBackplane();
4745
4987
  const startupPromises = [];
4988
+ if (this.opts.compression === "zstd") {
4989
+ startupPromises.push(initZstd().then(() => void 0));
4990
+ }
4746
4991
  if (this.opts.remoteSnapshot) {
4747
4992
  startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
4748
4993
  }
@@ -4888,7 +5133,9 @@ var CacheService = class _CacheService {
4888
5133
  "adaptiveTtl",
4889
5134
  "l2WriteMode",
4890
5135
  "instanceName",
4891
- "invalidationBackplane"
5136
+ "invalidationBackplane",
5137
+ "awaitInvalidationBackplane",
5138
+ "lockFailClosed"
4892
5139
  ];
4893
5140
  /** Returns the names of options that differ between `a` and the live `b`. */
4894
5141
  static optionsDiff(a, b) {
@@ -4929,6 +5176,8 @@ var CacheService = class _CacheService {
4929
5176
  frozen: o.frozen,
4930
5177
  adaptiveTtl: o.adaptiveTtl,
4931
5178
  invalidationBackplane: o.invalidationBackplane,
5179
+ awaitInvalidationBackplane: o.awaitInvalidationBackplane,
5180
+ lockFailClosed: o.lockFailClosed,
4932
5181
  strictSingleton: o.strictSingleton,
4933
5182
  remoteSnapshot: o.remoteSnapshot,
4934
5183
  crossRegion: o.crossRegion
@@ -5214,16 +5463,80 @@ var CacheService = class _CacheService {
5214
5463
  _applyInvalidationEvent(op, key, tagVersion) {
5215
5464
  if (op === "del") {
5216
5465
  this.l1.delete(key);
5466
+ this._bumpKeyMutation(key);
5467
+ this.inflight.delete(key);
5468
+ this._pendingDiskDeletes.add(key);
5217
5469
  setImmediate(() => {
5218
- if (!this._diskDisabled) this.disk.delete(key);
5470
+ try {
5471
+ if (!this._diskDisabled) this.disk.delete(key);
5472
+ } finally {
5473
+ this._pendingDiskDeletes.delete(key);
5474
+ }
5219
5475
  });
5220
5476
  this._cascadeDependencies(key);
5221
5477
  } else if (op === "del-glob") {
5222
5478
  this.l1.deletePattern(key);
5479
+ const pfx = key.endsWith("*") ? key.slice(0, -1) : key;
5480
+ for (const liveKey of this.l1.liveKeys()) {
5481
+ if (liveKey.startsWith(pfx)) {
5482
+ this._bumpKeyMutation(liveKey);
5483
+ }
5484
+ }
5485
+ for (const inflightKey of Array.from(this.inflight.keys())) {
5486
+ if (inflightKey.startsWith(pfx)) {
5487
+ this._bumpKeyMutation(inflightKey);
5488
+ this.inflight.delete(inflightKey);
5489
+ }
5490
+ }
5491
+ this._addPatternTombstone(pfx);
5223
5492
  } else if (op === "tag_incr") {
5224
5493
  const tag = key;
5225
5494
  const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
5226
- this._setLocalTagVersion(tag, ver, Date.now());
5495
+ this._setLocalTagVersion(tag, ver, performance.now());
5496
+ } else if (op === "tag_pattern_incr") {
5497
+ const pattern = key;
5498
+ const now = performance.now();
5499
+ for (const [tag, info] of this.tagVersions) {
5500
+ if (matchesTagPattern(pattern, tag)) {
5501
+ this._setLocalTagVersion(tag, info.version + 1, now);
5502
+ }
5503
+ }
5504
+ this.l1.scan((k, entry) => {
5505
+ if (entry.tagVersions) {
5506
+ for (const tag of Object.keys(entry.tagVersions)) {
5507
+ if (matchesTagPattern(pattern, tag)) {
5508
+ this.l1.delete(k);
5509
+ this._bumpKeyMutation(k);
5510
+ break;
5511
+ }
5512
+ }
5513
+ }
5514
+ }, 0);
5515
+ } else if (op === "tag_pattern_del") {
5516
+ const pattern = key;
5517
+ const matchedTagKeys = [];
5518
+ const prefix = this.nk("_tag_:");
5519
+ for (const [tagKey, members] of this.tagIndex) {
5520
+ const tag = tagKey.startsWith(prefix) ? tagKey.slice(prefix.length) : tagKey;
5521
+ if (matchesTagPattern(pattern, tag)) {
5522
+ matchedTagKeys.push(tagKey);
5523
+ for (const k of members) {
5524
+ this.l1.delete(k);
5525
+ this._bumpKeyMutation(k);
5526
+ this._pendingDiskDeletes.add(k);
5527
+ setImmediate(() => {
5528
+ try {
5529
+ if (!this._diskDisabled) this.disk.delete(k);
5530
+ } finally {
5531
+ this._pendingDiskDeletes.delete(k);
5532
+ }
5533
+ });
5534
+ }
5535
+ }
5536
+ }
5537
+ for (const tagKey of matchedTagKeys) {
5538
+ this.tagIndex.delete(tagKey);
5539
+ }
5227
5540
  }
5228
5541
  this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
5229
5542
  }
@@ -5231,7 +5544,7 @@ var CacheService = class _CacheService {
5231
5544
  _handleBackplaneMessage(message) {
5232
5545
  try {
5233
5546
  const msg = JSON.parse(message);
5234
- 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") {
5547
+ 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") {
5235
5548
  this.logger.warn("Backplane: rejected invalid pubsub message format", {
5236
5549
  raw: typeof message === "string" ? message.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(message)
5237
5550
  });
@@ -5251,7 +5564,11 @@ var CacheService = class _CacheService {
5251
5564
  if (!isCrossRegionRelay && this.opts.crossRegion) {
5252
5565
  const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
5253
5566
  if (shouldBroadcast) {
5254
- void this._broadcastCrossRegion(op, key, tagVersion);
5567
+ if (this.opts.awaitInvalidationBackplane) {
5568
+ await this._broadcastCrossRegion(op, key, tagVersion);
5569
+ } else {
5570
+ void this._broadcastCrossRegion(op, key, tagVersion);
5571
+ }
5255
5572
  }
5256
5573
  }
5257
5574
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
@@ -5292,7 +5609,11 @@ var CacheService = class _CacheService {
5292
5609
  );
5293
5610
  }
5294
5611
  this.counters.invSent++;
5295
- } catch {
5612
+ } catch (err) {
5613
+ this.logger.warn("Backplane invalidation publish failed", { op, key, error: err.message });
5614
+ if (this.opts.awaitInvalidationBackplane) {
5615
+ throw err;
5616
+ }
5296
5617
  }
5297
5618
  }
5298
5619
  _markCrossRegionEventSeen(id) {
@@ -5410,12 +5731,12 @@ var CacheService = class _CacheService {
5410
5731
  * Offloads to worker thread if pool is active and payload exceeds threshold.
5411
5732
  */
5412
5733
  async _serializeAndEncrypt(serialized) {
5413
- const isCompressed2 = this.opts.compression && this.opts.compression !== "none" && serialized.length > this.opts.compressionThresholdBytes;
5414
- if (this._workerPool && (this.enc.isEnabled || isCompressed2) && serialized.length > this.opts.workerThresholdBytes) {
5734
+ const isCompressed2 = (this.opts.customCompressor || this.opts.compression && this.opts.compression !== "none") && serialized.length > this.opts.compressionThresholdBytes;
5735
+ if (this._workerPool && !this.opts.customCompressor && (this.enc.isEnabled || isCompressed2) && serialized.length > this.opts.workerThresholdBytes) {
5415
5736
  return this._workerPool.encrypt(serialized);
5416
5737
  }
5417
5738
  if (isCompressed2) {
5418
- const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression);
5739
+ const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression, this.opts.customCompressor);
5419
5740
  if (this.enc.isEnabled) {
5420
5741
  const encrypted = this.enc.encryptBuffer(compressed);
5421
5742
  return PREFIX_ENC_COMPRESSED + encrypted.toString("base64");
@@ -5430,16 +5751,16 @@ var CacheService = class _CacheService {
5430
5751
  */
5431
5752
  async _decryptAndDeserialize(raw) {
5432
5753
  let plain;
5433
- if (this._workerPool && raw.length > this.opts.workerThresholdBytes) {
5754
+ if (this._workerPool && !this.opts.customCompressor && raw.length > this.opts.workerThresholdBytes) {
5434
5755
  plain = await this._workerPool.decrypt(raw);
5435
5756
  } else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
5436
5757
  const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), "base64");
5437
5758
  const decBuf = this.enc.decryptBuffer(encBuf);
5438
- const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
5759
+ const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
5439
5760
  plain = decompressed.toString("utf8");
5440
5761
  } else if (raw.startsWith(PREFIX_COMPRESSED)) {
5441
5762
  const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), "base64");
5442
- const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
5763
+ const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
5443
5764
  plain = decompressed.toString("utf8");
5444
5765
  } else if (raw.startsWith("enc:v1:") || this.enc.isEnabled) {
5445
5766
  plain = this.enc.decrypt(raw);
@@ -5496,6 +5817,7 @@ var CacheService = class _CacheService {
5496
5817
  }
5497
5818
  }
5498
5819
  async getRedis() {
5820
+ this._assertActive("getRedis");
5499
5821
  if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
5500
5822
  if (this.redis) return this.redis;
5501
5823
  if (this.redisConnecting) return this.redisConnecting;
@@ -5824,6 +6146,7 @@ var CacheService = class _CacheService {
5824
6146
  * Caches negative lookups to avoid repeated DB hits for missing keys.
5825
6147
  */
5826
6148
  async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
6149
+ this._assertActive("get");
5827
6150
  const span = this._startSpan("tricache.get");
5828
6151
  if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
5829
6152
  const k = this.nk(cacheKey);
@@ -5833,7 +6156,7 @@ var CacheService = class _CacheService {
5833
6156
  const optRefreshAhead = opts.refreshAhead;
5834
6157
  const optXfetchBeta = opts.xfetchBeta;
5835
6158
  const optNotFoundTtl = opts.notFoundTtl;
5836
- const optTags = opts.tags;
6159
+ const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
5837
6160
  const l1Hit = this.l1.get(k);
5838
6161
  if (l1Hit !== null) {
5839
6162
  let isGenerationalStale = false;
@@ -5855,7 +6178,14 @@ var CacheService = class _CacheService {
5855
6178
  if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
5856
6179
  const priority2 = optPriority ?? inferPriority(cacheKey);
5857
6180
  this.revalidating.add(k);
5858
- void this._revalidate(k, fetchFn, ttlSeconds * 1e3, swrGraceMs2, priority2);
6181
+ void this._revalidate(
6182
+ k,
6183
+ fetchFn,
6184
+ ttlSeconds * 1e3,
6185
+ swrGraceMs2,
6186
+ priority2,
6187
+ l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
6188
+ );
5859
6189
  this.counters.swrRevalidations++;
5860
6190
  this.logger.debug("SWR: serving stale, revalidating", { cacheKey });
5861
6191
  } else {
@@ -5874,7 +6204,14 @@ var CacheService = class _CacheService {
5874
6204
  if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
5875
6205
  const priority2 = optPriority ?? inferPriority(cacheKey);
5876
6206
  this.revalidating.add(k);
5877
- void this._revalidate(k, fetchFn, entryTtl, optSwr * 1e3, priority2);
6207
+ void this._revalidate(
6208
+ k,
6209
+ fetchFn,
6210
+ entryTtl,
6211
+ optSwr * 1e3,
6212
+ priority2,
6213
+ l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
6214
+ );
5878
6215
  this.counters.swrRevalidations++;
5879
6216
  this.logger.debug(
5880
6217
  shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
@@ -5900,44 +6237,52 @@ var CacheService = class _CacheService {
5900
6237
  span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
5901
6238
  return existing;
5902
6239
  }
6240
+ const mutationEpochAtStart = this._getKeyMutationEpoch(k);
5903
6241
  const executionPromise = (async () => {
5904
6242
  try {
5905
- if (!this._diskDisabled) {
5906
- const isDiskAllowed = this.watchdog.isDiskAllowed();
5907
- if (isDiskAllowed) {
5908
- const diskStart = performance.now();
5909
- const diskHit = this.disk.load(k);
5910
- const diskElapsed = performance.now() - diskStart;
5911
- this.watchdog.recordDisk(diskElapsed);
5912
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
5913
- if (diskHit !== null) {
5914
- let isDiskStale = false;
5915
- if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
5916
- const tags = Object.keys(diskHit.tagVersions);
5917
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5918
- for (let i = 0; i < tags.length; i++) {
5919
- if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
5920
- isDiskStale = true;
5921
- break;
6243
+ if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
6244
+ if (this._isTombstonedByPattern(k)) {
6245
+ try {
6246
+ this.disk.delete(k);
6247
+ } catch {
6248
+ }
6249
+ } else {
6250
+ const isDiskAllowed = this.watchdog.isDiskAllowed();
6251
+ if (isDiskAllowed) {
6252
+ const diskStart = performance.now();
6253
+ const diskHit = this.disk.load(k);
6254
+ const diskElapsed = performance.now() - diskStart;
6255
+ this.watchdog.recordDisk(diskElapsed);
6256
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6257
+ if (diskHit !== null) {
6258
+ let isDiskStale = false;
6259
+ if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
6260
+ const tags = Object.keys(diskHit.tagVersions);
6261
+ const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
6262
+ for (let i = 0; i < tags.length; i++) {
6263
+ if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
6264
+ isDiskStale = true;
6265
+ break;
6266
+ }
5922
6267
  }
5923
6268
  }
5924
- }
5925
- if (isDiskStale) {
5926
- this.disk.delete(k);
5927
- } else {
5928
- const promoted = this.l1.importEntries(
5929
- [{ key: k, entry: diskHit }],
5930
- this.opts.forbiddenSnapshotPrefixes
5931
- );
5932
- if (promoted > 0) {
5933
- const l1Check = this.l1.get(k);
5934
- if (l1Check !== null) {
5935
- this.counters.diskHits++;
5936
- this.opts.onHit?.(cacheKey, "disk");
5937
- this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
5938
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
5939
- if (this.opts.frozen) deepFreeze(l1Check.value);
5940
- return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
6269
+ if (isDiskStale) {
6270
+ this.disk.delete(k);
6271
+ } else {
6272
+ const promoted = this.l1.importEntries(
6273
+ [{ key: k, entry: diskHit }],
6274
+ this.opts.forbiddenSnapshotPrefixes
6275
+ );
6276
+ if (promoted > 0) {
6277
+ const l1Check = this.l1.get(k);
6278
+ if (l1Check !== null) {
6279
+ this.counters.diskHits++;
6280
+ this.opts.onHit?.(cacheKey, "disk");
6281
+ this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
6282
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
6283
+ if (this.opts.frozen) deepFreeze(l1Check.value);
6284
+ return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
6285
+ }
5941
6286
  }
5942
6287
  }
5943
6288
  }
@@ -6048,6 +6393,18 @@ var CacheService = class _CacheService {
6048
6393
  await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
6049
6394
  }
6050
6395
  }
6396
+ if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
6397
+ this.logger.debug("Aborting in-flight cache commit \u2014 key was mutated or deleted during fetch", { cacheKey });
6398
+ span.setAttribute("cache.aborted_mutation_race", true);
6399
+ const current = this.l1.get(k);
6400
+ if (current && !current.isStale && current.value !== void 0) {
6401
+ const freshVal = current.value;
6402
+ if (this.opts.frozen) deepFreeze(freshVal);
6403
+ return this.opts.cloneStrategy === "structuredClone" && freshVal != null && typeof freshVal === "object" ? structuredClone(freshVal) : freshVal;
6404
+ }
6405
+ if (this.opts.frozen) deepFreeze(data);
6406
+ return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
6407
+ }
6051
6408
  this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
6052
6409
  if (!this._redisDisabled) {
6053
6410
  try {
@@ -6164,22 +6521,40 @@ var CacheService = class _CacheService {
6164
6521
  const ttl = options?.ttl ?? 300;
6165
6522
  return this.get(cacheKey, fetchFn, ttl, options);
6166
6523
  }
6167
- async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
6524
+ async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority, knownTagVersions) {
6525
+ const startEpoch = this._getKeyMutationEpoch(cacheKey);
6168
6526
  try {
6169
6527
  const fetchStart = Date.now();
6170
6528
  const data = await fetchFn();
6171
6529
  const delta = Date.now() - fetchStart;
6172
6530
  const staleAt = Date.now() + ttlMs;
6531
+ if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
6532
+ this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during fetch", { cacheKey });
6533
+ return;
6534
+ }
6173
6535
  if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
6174
6536
  let activeTagVersions;
6175
6537
  const l1Existing = this.l1.get(cacheKey);
6176
- if (this.opts.tagStrategy === "generational" && l1Existing?.tagVersions) {
6177
- const tags = Object.keys(l1Existing.tagVersions);
6538
+ const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
6539
+ if (this.opts.tagStrategy === "generational" && tagVersionsSource) {
6540
+ const tags = Object.keys(tagVersionsSource);
6178
6541
  const vers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
6179
6542
  activeTagVersions = {};
6180
6543
  for (let i = 0; i < tags.length; i++) {
6181
6544
  activeTagVersions[tags[i]] = vers[i];
6182
6545
  }
6546
+ if (knownTagVersions) {
6547
+ for (const t of tags) {
6548
+ if (knownTagVersions[t] !== void 0 && activeTagVersions[t] !== knownTagVersions[t]) {
6549
+ this.logger.debug("SWR: aborting revalidation commit \u2014 tag version bumped during revalidation", { cacheKey, tag: t });
6550
+ return;
6551
+ }
6552
+ }
6553
+ }
6554
+ }
6555
+ if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
6556
+ this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
6557
+ return;
6183
6558
  }
6184
6559
  this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
6185
6560
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
@@ -6223,6 +6598,7 @@ var CacheService = class _CacheService {
6223
6598
  // ── Explicit set / delete ─────────────────────────────────────────────────
6224
6599
  /** Explicitly write a value into L1 (+ L2 in production). */
6225
6600
  async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
6601
+ this._assertActive("set");
6226
6602
  const span = this._startSpan("tricache.set");
6227
6603
  if (this.opts.tracer) {
6228
6604
  span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
@@ -6233,17 +6609,21 @@ var CacheService = class _CacheService {
6233
6609
  const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
6234
6610
  const p = priority ?? inferPriority(cacheKey);
6235
6611
  const k = this.nk(cacheKey);
6612
+ this._bumpKeyMutation(k);
6613
+ this.inflight.delete(k);
6614
+ this._pendingDiskDeletes.delete(k);
6236
6615
  this.counters.sets++;
6237
6616
  let activeTagVersions;
6238
- if (opts?.tags?.length) {
6617
+ const tagsToRegister = opts?.tags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
6618
+ if (tagsToRegister?.length) {
6239
6619
  if (this.opts.tagStrategy === "generational") {
6240
- const vers = await Promise.all(opts.tags.map((tag) => this._getTagVersion(tag)));
6620
+ const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
6241
6621
  activeTagVersions = {};
6242
- for (let i = 0; i < opts.tags.length; i++) {
6243
- activeTagVersions[opts.tags[i]] = vers[i];
6622
+ for (let i = 0; i < tagsToRegister.length; i++) {
6623
+ activeTagVersions[tagsToRegister[i]] = vers[i];
6244
6624
  }
6245
6625
  } else {
6246
- await this._registerTags(k, opts.tags, ttlSeconds);
6626
+ await this._registerTags(k, tagsToRegister, ttlSeconds);
6247
6627
  }
6248
6628
  }
6249
6629
  this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
@@ -6287,7 +6667,11 @@ var CacheService = class _CacheService {
6287
6667
  this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
6288
6668
  }
6289
6669
  }
6290
- void this.publishInvalidation("del", k);
6670
+ if (this.opts.awaitInvalidationBackplane) {
6671
+ await this.publishInvalidation("del", k);
6672
+ } else {
6673
+ void this.publishInvalidation("del", k);
6674
+ }
6291
6675
  } catch (err) {
6292
6676
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
6293
6677
  span.recordException?.(err);
@@ -6334,6 +6718,7 @@ var CacheService = class _CacheService {
6334
6718
  * await cache.delete('user:abc:*'); // all keys for user abc
6335
6719
  */
6336
6720
  async delete(cacheKey) {
6721
+ this._assertActive("delete");
6337
6722
  const span = this._startSpan("tricache.delete");
6338
6723
  if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
6339
6724
  try {
@@ -6341,11 +6726,31 @@ var CacheService = class _CacheService {
6341
6726
  const k = this.nk(cacheKey);
6342
6727
  this.counters.deletes++;
6343
6728
  if (isPattern) {
6729
+ const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6730
+ for (const liveKey of this.l1.liveKeys()) {
6731
+ if (liveKey.startsWith(pfx)) {
6732
+ this._bumpKeyMutation(liveKey);
6733
+ }
6734
+ }
6735
+ for (const inflightKey of Array.from(this.inflight.keys())) {
6736
+ if (inflightKey.startsWith(pfx)) {
6737
+ this._bumpKeyMutation(inflightKey);
6738
+ this.inflight.delete(inflightKey);
6739
+ }
6740
+ }
6741
+ this._addPatternTombstone(pfx);
6344
6742
  this.l1.deletePattern(k);
6345
6743
  } else {
6744
+ this._bumpKeyMutation(k);
6745
+ this.inflight.delete(k);
6346
6746
  this.l1.delete(k);
6747
+ this._pendingDiskDeletes.add(k);
6347
6748
  setImmediate(() => {
6348
- if (!this._diskDisabled) this.disk.delete(k);
6749
+ try {
6750
+ if (!this._diskDisabled) this.disk.delete(k);
6751
+ } finally {
6752
+ this._pendingDiskDeletes.delete(k);
6753
+ }
6349
6754
  });
6350
6755
  this._cascadeDependencies(k);
6351
6756
  for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
@@ -6369,7 +6774,11 @@ var CacheService = class _CacheService {
6369
6774
  this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
6370
6775
  }
6371
6776
  }
6372
- void this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
6777
+ if (this.opts.awaitInvalidationBackplane) {
6778
+ await this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
6779
+ } else {
6780
+ void this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
6781
+ }
6373
6782
  } catch (err) {
6374
6783
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
6375
6784
  span.recordException?.(err);
@@ -6396,6 +6805,7 @@ var CacheService = class _CacheService {
6396
6805
  * fleet-wide.
6397
6806
  */
6398
6807
  async increment(cacheKey, ttlSeconds) {
6808
+ this._assertActive("increment");
6399
6809
  const k = this.nk(cacheKey);
6400
6810
  if (this._redisDisabled) {
6401
6811
  if (!this._incrementFallbackWarned) {
@@ -6437,19 +6847,38 @@ var CacheService = class _CacheService {
6437
6847
  * await cache.clear('user:abc'); // flush all keys for one user
6438
6848
  */
6439
6849
  async clear(prefix) {
6850
+ this._assertActive("clear");
6440
6851
  const span = this._startSpan("tricache.clear");
6441
6852
  if (this.opts.tracer) span.setAttribute("cache.prefix", prefix || "*");
6442
6853
  try {
6443
6854
  this.counters.deletes++;
6444
6855
  const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
6445
6856
  if (k) {
6857
+ const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6858
+ for (const liveKey of this.l1.liveKeys()) {
6859
+ if (liveKey.startsWith(pfx)) {
6860
+ this._bumpKeyMutation(liveKey);
6861
+ }
6862
+ }
6863
+ for (const inflightKey of Array.from(this.inflight.keys())) {
6864
+ if (inflightKey.startsWith(pfx)) {
6865
+ this._bumpKeyMutation(inflightKey);
6866
+ this.inflight.delete(inflightKey);
6867
+ }
6868
+ }
6869
+ this._addPatternTombstone(pfx);
6446
6870
  this.l1.deletePattern(k);
6447
6871
  } else {
6872
+ this._globalEpoch++;
6873
+ this.inflight.clear();
6874
+ this._patternTombstones.length = 0;
6448
6875
  this.l1.clear();
6449
6876
  if (!this._diskDisabled) this.disk.clear();
6450
6877
  this._l1Counters.clear();
6451
6878
  this.tagIndex.clear();
6452
6879
  this.tagVersions.clear();
6880
+ this._pendingDiskDeletes.clear();
6881
+ this._keyMutationEpochs.clear();
6453
6882
  }
6454
6883
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6455
6884
  try {
@@ -6461,13 +6890,23 @@ var CacheService = class _CacheService {
6461
6890
  this.logger.debug("clear: Redis unavailable", { error: err.message });
6462
6891
  }
6463
6892
  }
6464
- void this.publishInvalidation(
6465
- "del-glob",
6466
- k ?? (this._namespace ? `${this._namespace}:*` : "*"),
6467
- void 0,
6468
- false,
6469
- true
6470
- );
6893
+ if (this.opts.awaitInvalidationBackplane) {
6894
+ await this.publishInvalidation(
6895
+ "del-glob",
6896
+ k ?? (this._namespace ? `${this._namespace}:*` : "*"),
6897
+ void 0,
6898
+ false,
6899
+ true
6900
+ );
6901
+ } else {
6902
+ void this.publishInvalidation(
6903
+ "del-glob",
6904
+ k ?? (this._namespace ? `${this._namespace}:*` : "*"),
6905
+ void 0,
6906
+ false,
6907
+ true
6908
+ );
6909
+ }
6471
6910
  } catch (err) {
6472
6911
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
6473
6912
  span.recordException?.(err);
@@ -6482,6 +6921,7 @@ var CacheService = class _CacheService {
6482
6921
  * Returns the number of entries evicted.
6483
6922
  */
6484
6923
  rebalance() {
6924
+ this._assertActive("rebalance");
6485
6925
  return this.l1.rebalance();
6486
6926
  }
6487
6927
  /**
@@ -6490,6 +6930,7 @@ var CacheService = class _CacheService {
6490
6930
  * Only reflects L1 state — does not query Redis or disk.
6491
6931
  */
6492
6932
  ttl(cacheKey) {
6933
+ this._assertActive("ttl");
6493
6934
  return this.l1.ttl(this.nk(cacheKey));
6494
6935
  }
6495
6936
  /**
@@ -6497,6 +6938,7 @@ var CacheService = class _CacheService {
6497
6938
  * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
6498
6939
  */
6499
6940
  has(cacheKey) {
6941
+ this._assertActive("has");
6500
6942
  return this.l1.has(this.nk(cacheKey));
6501
6943
  }
6502
6944
  // ── Iteration ─────────────────────────────────────────────────────────────
@@ -6507,6 +6949,7 @@ var CacheService = class _CacheService {
6507
6949
  * for (const key of cache.keys()) console.log(key);
6508
6950
  */
6509
6951
  *keys() {
6952
+ this._assertActive("keys");
6510
6953
  const prefix = this._namespace ? this._namespace + ":" : "";
6511
6954
  for (const key of this.l1.liveKeys()) {
6512
6955
  if (prefix && !key.startsWith(prefix)) continue;
@@ -6521,6 +6964,7 @@ var CacheService = class _CacheService {
6521
6964
  * for (const val of cache.values<User>()) console.log(val.id);
6522
6965
  */
6523
6966
  *values() {
6967
+ this._assertActive("values");
6524
6968
  const prefix = this._namespace ? this._namespace + ":" : "";
6525
6969
  if (!prefix) {
6526
6970
  yield* this.l1.liveValues();
@@ -6539,6 +6983,7 @@ var CacheService = class _CacheService {
6539
6983
  * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
6540
6984
  */
6541
6985
  *entries() {
6986
+ this._assertActive("entries");
6542
6987
  const prefix = this._namespace ? this._namespace + ":" : "";
6543
6988
  for (const [key, entry] of this.l1.liveEntries()) {
6544
6989
  if (prefix && !key.startsWith(prefix)) continue;
@@ -6566,6 +7011,7 @@ var CacheService = class _CacheService {
6566
7011
  * `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
6567
7012
  */
6568
7013
  scan(fn) {
7014
+ this._assertActive("scan");
6569
7015
  const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
6570
7016
  this.l1.scan((key, entry, pfx) => {
6571
7017
  const value = entry.value !== void 0 ? entry.value : entry.data;
@@ -6579,6 +7025,7 @@ var CacheService = class _CacheService {
6579
7025
  * @param newTtlSeconds - The new TTL from now, in seconds.
6580
7026
  */
6581
7027
  async touch(cacheKey, newTtlSeconds) {
7028
+ this._assertActive("touch");
6582
7029
  const k = this.nk(cacheKey);
6583
7030
  const hit = this.l1.touch(k, newTtlSeconds * 1e3);
6584
7031
  if (hit && !this._redisDisabled) {
@@ -6599,6 +7046,7 @@ var CacheService = class _CacheService {
6599
7046
  * if (fresh !== null) return fresh; // serve from L1, no network hop
6600
7047
  */
6601
7048
  getIfFresh(cacheKey) {
7049
+ this._assertActive("getIfFresh");
6602
7050
  const k = this.nk(cacheKey);
6603
7051
  const entry = this.l1.getEntry(k);
6604
7052
  if (!entry) return null;
@@ -6616,6 +7064,7 @@ var CacheService = class _CacheService {
6616
7064
  * const val = await cache.peek<User>('user:123');
6617
7065
  */
6618
7066
  async peek(cacheKey) {
7067
+ this._assertActive("peek");
6619
7068
  const k = this.nk(cacheKey);
6620
7069
  const l1Hit = this.l1.get(k);
6621
7070
  if (l1Hit !== null) {
@@ -6625,25 +7074,32 @@ var CacheService = class _CacheService {
6625
7074
  if (this.opts.frozen) deepFreeze(val);
6626
7075
  return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6627
7076
  }
6628
- if (!this._diskDisabled && this.watchdog.isDiskAllowed()) {
6629
- const diskStart = performance.now();
6630
- const diskHit = this.disk.load(k);
6631
- const diskElapsed = performance.now() - diskStart;
6632
- this.watchdog.recordDisk(diskElapsed);
6633
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6634
- if (diskHit !== null) {
6635
- const promoted = this.l1.importEntries(
6636
- [{ key: k, entry: diskHit }],
6637
- this.opts.forbiddenSnapshotPrefixes
6638
- );
6639
- if (promoted > 0) {
6640
- const l1Check = this.l1.get(k);
6641
- if (l1Check !== null) {
6642
- this.counters.gets++;
6643
- this.counters.diskHits++;
6644
- const val = l1Check.value;
6645
- if (this.opts.frozen) deepFreeze(val);
6646
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
7077
+ if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
7078
+ if (this._isTombstonedByPattern(k)) {
7079
+ try {
7080
+ this.disk.delete(k);
7081
+ } catch {
7082
+ }
7083
+ } else if (this.watchdog.isDiskAllowed()) {
7084
+ const diskStart = performance.now();
7085
+ const diskHit = this.disk.load(k);
7086
+ const diskElapsed = performance.now() - diskStart;
7087
+ this.watchdog.recordDisk(diskElapsed);
7088
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
7089
+ if (diskHit !== null) {
7090
+ const promoted = this.l1.importEntries(
7091
+ [{ key: k, entry: diskHit }],
7092
+ this.opts.forbiddenSnapshotPrefixes
7093
+ );
7094
+ if (promoted > 0) {
7095
+ const l1Check = this.l1.get(k);
7096
+ if (l1Check !== null) {
7097
+ this.counters.gets++;
7098
+ this.counters.diskHits++;
7099
+ const val = l1Check.value;
7100
+ if (this.opts.frozen) deepFreeze(val);
7101
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
7102
+ }
6647
7103
  }
6648
7104
  }
6649
7105
  }
@@ -6681,6 +7137,7 @@ var CacheService = class _CacheService {
6681
7137
  * `(key) => number` so heterogeneous TTLs can be batched in one call.
6682
7138
  */
6683
7139
  async mget(keys, fetchFn, ttl = 300, priority) {
7140
+ this._assertActive("mget");
6684
7141
  const span = this._startSpan("tricache.mget");
6685
7142
  if (this.opts.tracer) {
6686
7143
  span.setAttribute("cache.batch.size", keys.length);
@@ -6749,8 +7206,16 @@ var CacheService = class _CacheService {
6749
7206
  }
6750
7207
  if (!this._diskDisabled && missKeys.length > 0) {
6751
7208
  for (let j = missKeys.length - 1; j >= 0; j--) {
6752
- if (!this.watchdog.isDiskAllowed()) continue;
6753
7209
  const k = this.nk(missKeys[j]);
7210
+ if (this._pendingDiskDeletes.has(k)) continue;
7211
+ if (this._isTombstonedByPattern(k)) {
7212
+ try {
7213
+ this.disk.delete(k);
7214
+ } catch {
7215
+ }
7216
+ continue;
7217
+ }
7218
+ if (!this.watchdog.isDiskAllowed()) continue;
6754
7219
  const diskStart = performance.now();
6755
7220
  const diskHit = this.disk.load(k);
6756
7221
  const diskElapsed = performance.now() - diskStart;
@@ -6773,16 +7238,23 @@ var CacheService = class _CacheService {
6773
7238
  }
6774
7239
  }
6775
7240
  }
6776
- if (missKeys.length > 0) {
7241
+ if (missKeys.length > 0 && fetchFn) {
6777
7242
  this.counters.fetches++;
6778
7243
  const fetched = await fetchFn(missKeys);
7244
+ const isMap = fetched instanceof Map;
6779
7245
  const setPromises = [];
6780
7246
  for (let j = 0; j < missKeys.length; j++) {
6781
- const v = fetched[missKeys[j]];
7247
+ const k = missKeys[j];
7248
+ const v = isMap ? fetched.get(k) : fetched[k];
6782
7249
  result[missIndexes[j]] = v;
6783
- if (v !== void 0) {
6784
- const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
6785
- setPromises.push(this.set(missKeys[j], v, resolvedTtl, priority));
7250
+ if (v !== void 0 && v !== null) {
7251
+ const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
7252
+ setPromises.push(this.set(k, v, resolvedTtl, priority));
7253
+ } else if (v == null && this.opts.notFoundTtl > 0) {
7254
+ setPromises.push(this.set(k, null, this.opts.notFoundTtl, priority));
7255
+ } else if (v === null) {
7256
+ const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
7257
+ setPromises.push(this.set(k, null, resolvedTtl, priority));
6786
7258
  }
6787
7259
  }
6788
7260
  if (setPromises.length > 0) {
@@ -6830,6 +7302,7 @@ var CacheService = class _CacheService {
6830
7302
  * });
6831
7303
  */
6832
7304
  async mset(entries) {
7305
+ this._assertActive("mset");
6833
7306
  const span = this._startSpan("tricache.mset");
6834
7307
  const keys = Object.keys(entries);
6835
7308
  if (this.opts.tracer) {
@@ -6857,6 +7330,7 @@ var CacheService = class _CacheService {
6857
7330
  * await cache.mdel(['user:1', 'user:2', 'user:3']);
6858
7331
  */
6859
7332
  async mdel(keys) {
7333
+ this._assertActive("mdel");
6860
7334
  const span = this._startSpan("tricache.mdel");
6861
7335
  if (this.opts.tracer) {
6862
7336
  span.setAttribute("cache.batch.size", keys.length);
@@ -6884,6 +7358,7 @@ var CacheService = class _CacheService {
6884
7358
  * console.log(`Warmed ${loaded} keys from Redis`);
6885
7359
  */
6886
7360
  async warmFromL2(pattern, opts) {
7361
+ this._assertActive("warmFromL2");
6887
7362
  if (this._redisDisabled) return 0;
6888
7363
  try {
6889
7364
  const client = await this.getRedis();
@@ -6922,20 +7397,109 @@ var CacheService = class _CacheService {
6922
7397
  }
6923
7398
  }
6924
7399
  /**
6925
- * Invalidate all keys associated with a tag.
6926
- * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
7400
+ * Discovers all concrete tag names in the system that match `tag` either via
7401
+ * glob wildcards ('*' or '?') or parent-child hierarchy cascading.
7402
+ * Scans local in-memory indices (tagIndex, tagVersions, L1 entries) and Redis (if connected).
7403
+ */
7404
+ async _resolveMatchingTags(tag, shouldCascade) {
7405
+ const isPattern = isWildcardTag(tag);
7406
+ const delim = this.opts.tagHierarchyDelimiter;
7407
+ const matched = /* @__PURE__ */ new Set();
7408
+ const tagMatches = (t) => {
7409
+ if (t === tag) return true;
7410
+ if (isPattern && matchesTagPattern(tag, t)) return true;
7411
+ if (shouldCascade && isChildTag(tag, t, delim)) return true;
7412
+ return false;
7413
+ };
7414
+ if (shouldCascade && !isPattern) {
7415
+ matched.add(tag);
7416
+ }
7417
+ const tagPrefix = this.nk("_tag_:");
7418
+ for (const tagKey of this.tagIndex.keys()) {
7419
+ const t = tagKey.startsWith(tagPrefix) ? tagKey.slice(tagPrefix.length) : tagKey;
7420
+ if (tagMatches(t)) matched.add(t);
7421
+ }
7422
+ for (const t of this.tagVersions.keys()) {
7423
+ if (tagMatches(t)) matched.add(t);
7424
+ }
7425
+ this.l1.scan((_k, entry) => {
7426
+ if (entry.tagVersions) {
7427
+ for (const t of Object.keys(entry.tagVersions)) {
7428
+ if (tagMatches(t)) matched.add(t);
7429
+ }
7430
+ }
7431
+ }, 0);
7432
+ if (!this._redisDisabled) {
7433
+ try {
7434
+ const client = await this.getRedis();
7435
+ if (this.opts.tagStrategy === "generational") {
7436
+ const redisPattern = isPattern ? this.nk(`tag_ver:${tag}`) : this.nk(`tag_ver:${tag}${delim}*`);
7437
+ const scannedKeys = await this._scanKeys(client, redisPattern);
7438
+ const pfx = this.nk("tag_ver:");
7439
+ for (const sk of scannedKeys) {
7440
+ const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
7441
+ if (tagMatches(t)) matched.add(t);
7442
+ }
7443
+ } else {
7444
+ const redisPattern = isPattern ? this.nk(`_tag_:${tag}`) : this.nk(`_tag_:${tag}${delim}*`);
7445
+ const scannedKeys = await this._scanKeys(client, redisPattern);
7446
+ const pfx = this.nk("_tag_:");
7447
+ for (const sk of scannedKeys) {
7448
+ const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
7449
+ if (tagMatches(t)) matched.add(t);
7450
+ }
7451
+ }
7452
+ } catch (err) {
7453
+ this.logger.debug("_resolveMatchingTags: Redis scan failed", { tag, error: err.message });
7454
+ }
7455
+ }
7456
+ return matched;
7457
+ }
7458
+ /**
7459
+ * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
7460
+ * Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
7461
+ *
7462
+ * @param tag Tag name or wildcard glob pattern (e.g. `'catalog'`, `'org:123:*'`, `'*:comments'`).
7463
+ * @param opts Optional invalidation options, including `{ cascade: true }` to invalidate child namespaces.
6927
7464
  *
6928
7465
  * @example
6929
7466
  * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
6930
7467
  * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
7468
+ *
7469
+ * @example
7470
+ * // Wildcard pattern invalidation
7471
+ * await cache.invalidateTag('org:123:*');
7472
+ *
7473
+ * @example
7474
+ * // Hierarchical tag cascading (clears 'org:123' and all child tags like 'org:123:dept:456')
7475
+ * await cache.invalidateTag('org:123', { cascade: true });
6931
7476
  */
6932
- async invalidateTag(tag) {
7477
+ async invalidateTag(tag, opts) {
7478
+ this._assertActive("invalidateTag");
6933
7479
  const span = this._startSpan("tricache.invalidate_tag");
6934
7480
  if (this.opts.tracer) {
6935
7481
  span.setAttribute("cache.tag", tag);
6936
7482
  span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
7483
+ if (opts?.cascade) span.setAttribute("cache.cascade", true);
6937
7484
  }
6938
7485
  try {
7486
+ const isPattern = isWildcardTag(tag);
7487
+ const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
7488
+ if (isPattern || shouldCascade) {
7489
+ const matchedTags = await this._resolveMatchingTags(tag, shouldCascade);
7490
+ const delim = this.opts.tagHierarchyDelimiter;
7491
+ const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
7492
+ if (matchedTags.size > 0) {
7493
+ await this.invalidateTags(Array.from(matchedTags));
7494
+ }
7495
+ const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
7496
+ if (this.opts.awaitInvalidationBackplane) {
7497
+ await this.publishInvalidation(op, broadcastPattern, void 0, false, true);
7498
+ } else {
7499
+ void this.publishInvalidation(op, broadcastPattern, void 0, false, true);
7500
+ }
7501
+ return;
7502
+ }
6939
7503
  if (this.opts.tagStrategy === "generational") {
6940
7504
  let newVer = 1;
6941
7505
  if (!this._redisDisabled) {
@@ -6951,15 +7515,27 @@ var CacheService = class _CacheService {
6951
7515
  const current = this.tagVersions.get(tag)?.version ?? 0;
6952
7516
  newVer = current + 1;
6953
7517
  }
6954
- this._setLocalTagVersion(tag, newVer, Date.now());
6955
- void this.publishInvalidation("tag_incr", tag, newVer, false, true);
7518
+ this._setLocalTagVersion(tag, newVer, performance.now());
7519
+ if (this.opts.awaitInvalidationBackplane) {
7520
+ await this.publishInvalidation("tag_incr", tag, newVer, false, true);
7521
+ } else {
7522
+ void this.publishInvalidation("tag_incr", tag, newVer, false, true);
7523
+ }
6956
7524
  return;
6957
7525
  }
6958
7526
  const tagKey = this.nk(`_tag_:${tag}`);
6959
7527
  const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
6960
7528
  for (const k of members) {
6961
7529
  this.l1.delete(k);
6962
- if (!this._diskDisabled) this.disk.delete(k);
7530
+ this._bumpKeyMutation(k);
7531
+ this._pendingDiskDeletes.add(k);
7532
+ setImmediate(() => {
7533
+ try {
7534
+ if (!this._diskDisabled) this.disk.delete(k);
7535
+ } finally {
7536
+ this._pendingDiskDeletes.delete(k);
7537
+ }
7538
+ });
6963
7539
  }
6964
7540
  this.tagIndex.delete(tagKey);
6965
7541
  if (!this._redisDisabled) {
@@ -6986,24 +7562,39 @@ var CacheService = class _CacheService {
6986
7562
  }
6987
7563
  /**
6988
7564
  * Invalidate all keys associated with any of the given tags in a single operation.
6989
- * Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
6990
- * reducing latency when invalidating several related tags together.
7565
+ * Supports discrete tags, wildcard glob patterns, and hierarchical cascading.
7566
+ * Combines multiple tag invalidations into Redis pipeline round-trips.
6991
7567
  *
6992
- * Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
6993
- * synchronously before the Redis round-trip.
7568
+ * @param tags Array of tag names or wildcard patterns (e.g. `['case:acme', 'org:*']`).
7569
+ * @param opts Optional invalidation options, including `{ cascade: true }`.
6994
7570
  *
6995
7571
  * @example
6996
- * // Instead of three serial round-trips:
6997
- * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
7572
+ * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:*']);
6998
7573
  */
6999
- async invalidateTags(tags) {
7574
+ async invalidateTags(tags, opts) {
7575
+ this._assertActive("invalidateTags");
7000
7576
  if (tags.length === 0) return;
7577
+ const hasWildcards = tags.some((t) => isWildcardTag(t));
7578
+ const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
7579
+ if (hasWildcards || shouldCascade) {
7580
+ const allResolvedTags = /* @__PURE__ */ new Set();
7581
+ for (const t of tags) {
7582
+ if (isWildcardTag(t) || shouldCascade) {
7583
+ const resolved = await this._resolveMatchingTags(t, shouldCascade);
7584
+ for (const rt of resolved) allResolvedTags.add(rt);
7585
+ } else {
7586
+ allResolvedTags.add(t);
7587
+ }
7588
+ }
7589
+ if (allResolvedTags.size === 0) return;
7590
+ tags = Array.from(allResolvedTags);
7591
+ }
7001
7592
  if (tags.length === 1) {
7002
- await this.invalidateTag(tags[0]);
7593
+ await this.invalidateTag(tags[0], opts);
7003
7594
  return;
7004
7595
  }
7005
7596
  if (this.opts.tagStrategy === "generational") {
7006
- const now = Date.now();
7597
+ const now = performance.now();
7007
7598
  if (!this._redisDisabled) {
7008
7599
  try {
7009
7600
  const client = await this.getRedis();
@@ -7014,7 +7605,11 @@ var CacheService = class _CacheService {
7014
7605
  const [err, newVer] = results[i] ?? [null, null];
7015
7606
  const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
7016
7607
  this._setLocalTagVersion(tags[i], ver, now);
7017
- void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7608
+ if (this.opts.awaitInvalidationBackplane) {
7609
+ await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7610
+ } else {
7611
+ void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7612
+ }
7018
7613
  }
7019
7614
  return;
7020
7615
  } catch (err) {
@@ -7024,7 +7619,11 @@ var CacheService = class _CacheService {
7024
7619
  for (const tag of tags) {
7025
7620
  const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
7026
7621
  this._setLocalTagVersion(tag, ver, now);
7027
- void this.publishInvalidation("tag_incr", tag, ver, false, true);
7622
+ if (this.opts.awaitInvalidationBackplane) {
7623
+ await this.publishInvalidation("tag_incr", tag, ver, false, true);
7624
+ } else {
7625
+ void this.publishInvalidation("tag_incr", tag, ver, false, true);
7626
+ }
7028
7627
  }
7029
7628
  return;
7030
7629
  }
@@ -7039,7 +7638,15 @@ var CacheService = class _CacheService {
7039
7638
  }
7040
7639
  for (const k of allMembers) {
7041
7640
  this.l1.delete(k);
7042
- this.disk.delete(k);
7641
+ this._bumpKeyMutation(k);
7642
+ this._pendingDiskDeletes.add(k);
7643
+ setImmediate(() => {
7644
+ try {
7645
+ if (!this._diskDisabled) this.disk.delete(k);
7646
+ } finally {
7647
+ this._pendingDiskDeletes.delete(k);
7648
+ }
7649
+ });
7043
7650
  }
7044
7651
  if (!this._redisDisabled) {
7045
7652
  try {
@@ -7076,6 +7683,7 @@ var CacheService = class _CacheService {
7076
7683
  * `l2` is `null` when Redis is disabled.
7077
7684
  */
7078
7685
  async ping() {
7686
+ this._assertActive("ping");
7079
7687
  const t0 = Date.now();
7080
7688
  this.l1.has("__ping__");
7081
7689
  const l1 = Date.now() - t0;
@@ -7155,6 +7763,7 @@ var CacheService = class _CacheService {
7155
7763
  * Returns the number of keys written.
7156
7764
  */
7157
7765
  async drainToL2() {
7766
+ this._assertActive("drainToL2");
7158
7767
  if (this._redisDisabled) return 0;
7159
7768
  try {
7160
7769
  const client = await this.getRedis();
@@ -7198,6 +7807,7 @@ var CacheService = class _CacheService {
7198
7807
  * if (!claimed) return res.status(409).json({ error: 'duplicate request' });
7199
7808
  */
7200
7809
  async setIfAbsent(cacheKey, value, ttlSeconds = 300, priority) {
7810
+ this._assertActive("setIfAbsent");
7201
7811
  const k = this.nk(cacheKey);
7202
7812
  if (this.l1.has(k)) return false;
7203
7813
  if (!this._redisDisabled) {
@@ -7216,6 +7826,8 @@ var CacheService = class _CacheService {
7216
7826
  }
7217
7827
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
7218
7828
  const p = priority ?? inferPriority(cacheKey);
7829
+ this._bumpKeyMutation(k);
7830
+ this._pendingDiskDeletes.delete(k);
7219
7831
  this.l1.set(k, value, ttlMs, p);
7220
7832
  this.counters.sets++;
7221
7833
  return true;
@@ -7234,6 +7846,7 @@ var CacheService = class _CacheService {
7234
7846
  * @param options TTL, acquire timeout, and retry polling intervals.
7235
7847
  */
7236
7848
  async lock(resourceKey, fn, options) {
7849
+ this._assertActive("lock");
7237
7850
  const ttlSeconds = Math.max(1, options?.ttl ?? 30);
7238
7851
  const acquireTimeout = Math.max(0, options?.acquireTimeout ?? 5e3);
7239
7852
  const retryInterval = Math.max(10, options?.retryInterval ?? 100);
@@ -7260,6 +7873,10 @@ var CacheService = class _CacheService {
7260
7873
  }
7261
7874
  } catch (err) {
7262
7875
  if (err.message.startsWith("Failed to acquire lock")) throw err;
7876
+ const failClosed = options?.failClosedOnRedisError ?? this.opts.lockFailClosed;
7877
+ if (failClosed) {
7878
+ throw new Error(`Distributed lock acquisition failed for resource "${resourceKey}" due to Redis error: ${err.message}`);
7879
+ }
7263
7880
  this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
7264
7881
  resourceKey,
7265
7882
  error: err.message
@@ -7605,6 +8222,7 @@ var CacheService = class _CacheService {
7605
8222
  * the previous key for seamless fallback decryption of existing cache entries.
7606
8223
  */
7607
8224
  async rotateEncryptionKey(newKeyBase64, newMode) {
8225
+ this._assertActive("rotateEncryptionKey");
7608
8226
  this.enc.rotateKey(newKeyBase64, newMode);
7609
8227
  if (this._workerPool) {
7610
8228
  await this._workerPool.drainAndReinit(this.enc.toWorkerInit());
@@ -7614,6 +8232,8 @@ var CacheService = class _CacheService {
7614
8232
  /** Close Redis connections and stop all background timers. */
7615
8233
  async destroy() {
7616
8234
  this._destroyed = true;
8235
+ this._pendingDiskDeletes.clear();
8236
+ this._keyMutationEpochs.clear();
7617
8237
  const g = globalThis;
7618
8238
  const key = _CacheService.globalKey(this.opts);
7619
8239
  if (g[key] === this) {
@@ -9532,6 +10152,7 @@ async function startDashboardServer(options) {
9532
10152
  createSigV4SnapshotAdapter,
9533
10153
  deepMergeOptions,
9534
10154
  defaultCodec,
10155
+ expandHierarchicalTags,
9535
10156
  findActiveSockets,
9536
10157
  formatBytes,
9537
10158
  formatDuration,
@@ -9539,6 +10160,10 @@ async function startDashboardServer(options) {
9539
10160
  formatTraceParent,
9540
10161
  getV8HeapLimit,
9541
10162
  handleDashboardRequest,
10163
+ initZstd,
10164
+ isChildTag,
10165
+ isWildcardTag,
10166
+ matchesTagPattern,
9542
10167
  murmur3_32,
9543
10168
  parseTraceParent,
9544
10169
  readCgroupMemoryLimit,