tricache 0.9.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +7 -3
  2. package/dist/{cache-service-KI5ACF3F.js → cache-service-26GCO3UU.js} +3 -3
  3. package/dist/{cache-service-DVvroyqA.d.ts → cache-service-pJ-nFcVj.d.ts} +29 -12
  4. package/dist/{chunk-XZL45ABR.js → chunk-2AJKEQMZ.js} +54 -1
  5. package/dist/{chunk-PL5J3ZNT.js → chunk-7SZSQS55.js} +201 -34
  6. package/dist/{chunk-LJ5QJB5O.js → chunk-UBWLPKTI.js} +127 -11
  7. package/dist/cli.cjs +376 -50
  8. package/dist/cli.js +4 -4
  9. package/dist/dashboard/index.d.ts +2 -2
  10. package/dist/drizzle/index.cjs +384 -51
  11. package/dist/drizzle/index.d.ts +2 -2
  12. package/dist/drizzle/index.js +1 -1
  13. package/dist/edge/index.cjs +64 -8
  14. package/dist/edge/index.d.ts +3 -3
  15. package/dist/edge/index.js +37 -9
  16. package/dist/hono/index.cjs +384 -51
  17. package/dist/hono/index.d.ts +2 -2
  18. package/dist/hono/index.js +1 -1
  19. package/dist/{hono-VA9A1m0I.d.ts → hono-DuNvciyq.d.ts} +4 -4
  20. package/dist/http/index.cjs +384 -51
  21. package/dist/http/index.d.ts +3 -3
  22. package/dist/http/index.js +8 -8
  23. package/dist/index.cjs +385 -49
  24. package/dist/index.d.ts +35 -6
  25. package/dist/index.js +16 -6
  26. package/dist/nestjs/index.cjs +375 -49
  27. package/dist/nestjs/index.d.ts +2 -2
  28. package/dist/nestjs/index.js +4 -4
  29. package/dist/next/index.cjs +375 -49
  30. package/dist/next/index.d.ts +2 -2
  31. package/dist/next/index.js +3 -3
  32. package/dist/prisma/index.d.ts +2 -2
  33. package/dist/serialize-worker.cjs +127 -9
  34. package/dist/serialize-worker.js +8 -4
  35. package/dist/{types-B_QkVwJ7.d.ts → types-5HXqBfAf.d.ts} +51 -7
  36. package/package.json +7 -4
  37. package/src/cache-service.ts +238 -33
  38. package/src/cli.ts +1 -1
  39. package/src/compression.ts +193 -15
  40. package/src/cross-region.ts +1 -1
  41. package/src/edge/cache.ts +38 -11
  42. package/src/env.d.ts +13 -0
  43. package/src/index.ts +9 -1
  44. package/src/serialize-worker.ts +6 -2
  45. package/src/types.ts +43 -5
  46. package/src/utils/tag-matcher.ts +90 -0
  47. /package/dist/{chunk-QNU7B43J.js → chunk-VXFTFZ5N.js} +0 -0
package/dist/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;
2398
+ return null;
2399
+ }
2400
+ };
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;
2287
2407
  return null;
2288
2408
  }
2289
2409
  };
2290
- const result = algorithm === "gzip" ? tryGzip() ?? tryBrotli() : tryBrotli() ?? tryGzip();
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
  }
@@ -4130,6 +4250,55 @@ function renderTopDashboard(payload) {
4130
4250
  return lines.join("\n");
4131
4251
  }
4132
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
+
4133
4302
  // src/cache-service.ts
4134
4303
  var LUA_COMPARE_AND_DELETE = `
4135
4304
  local currentTs = redis.call('HGET', KEYS[1], 't')
@@ -4148,21 +4317,21 @@ var DEFAULT_CATEGORY_LIMITS = {
4148
4317
  var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
4149
4318
  var DEFAULT_COUNTER_TTL_SECONDS = 60;
4150
4319
  var GLOB_REGEX_CACHE_MAX = 256;
4151
- var globRegexCache = /* @__PURE__ */ new Map();
4320
+ var globRegexCache2 = /* @__PURE__ */ new Map();
4152
4321
  function getGlobRegex(pattern) {
4153
- let re = globRegexCache.get(pattern);
4322
+ let re = globRegexCache2.get(pattern);
4154
4323
  if (re) {
4155
- globRegexCache.delete(pattern);
4156
- globRegexCache.set(pattern, re);
4324
+ globRegexCache2.delete(pattern);
4325
+ globRegexCache2.set(pattern, re);
4157
4326
  return re;
4158
4327
  }
4159
4328
  const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*+/g, ".*");
4160
4329
  re = new RegExp("^" + escaped + "$");
4161
- if (globRegexCache.size >= GLOB_REGEX_CACHE_MAX) {
4162
- const oldestKey = globRegexCache.keys().next().value;
4163
- 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);
4164
4333
  }
4165
- globRegexCache.set(pattern, re);
4334
+ globRegexCache2.set(pattern, re);
4166
4335
  return re;
4167
4336
  }
4168
4337
  var L2CircuitBreaker = class {
@@ -4416,6 +4585,7 @@ var CacheService = class _CacheService {
4416
4585
  opts;
4417
4586
  /** Pre-computed once — opts.namespace never changes after construction. */
4418
4587
  _namespace;
4588
+ prefixLen;
4419
4589
  /** Pre-computed once — disableRedis and redisHost never change after construction. */
4420
4590
  _redisDisabled;
4421
4591
  watchdog;
@@ -4624,12 +4794,15 @@ var CacheService = class _CacheService {
4624
4794
  redisSentinel: options.redisSentinel,
4625
4795
  redisProtocol: options.redisProtocol,
4626
4796
  useShardedPubSub: options.useShardedPubSub ?? false,
4627
- compression: options.compression ?? "none",
4797
+ compression: options.compression ?? "zstd",
4798
+ customCompressor: options.customCompressor,
4628
4799
  compressionThresholdBytes: options.compressionThresholdBytes ?? 1024,
4629
4800
  strictSingleton: options.strictSingleton ?? false,
4630
4801
  failClosed: options.failClosed ?? false,
4631
4802
  tagStrategy: options.tagStrategy ?? "set",
4632
4803
  tagVersionTtlMs: options.tagVersionTtlMs ?? 5e3,
4804
+ hierarchicalTags: options.hierarchicalTags ?? false,
4805
+ tagHierarchyDelimiter: options.tagHierarchyDelimiter ?? ":",
4633
4806
  cloneStrategy: options.cloneStrategy ?? "none",
4634
4807
  backplaneMode: options.backplaneMode ?? "pubsub",
4635
4808
  backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
@@ -4702,6 +4875,7 @@ var CacheService = class _CacheService {
4702
4875
  diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs
4703
4876
  });
4704
4877
  this._namespace = ns;
4878
+ this.prefixLen = ns ? ns.length + 1 : 0;
4705
4879
  this._redisDisabled = this.opts.disableRedis || !this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
4706
4880
  this.watchdog = new TierLatencyWatchdog({
4707
4881
  enabled: options.diskLatencyWatchdog ?? true,
@@ -4811,6 +4985,9 @@ var CacheService = class _CacheService {
4811
4985
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
4812
4986
  this.initBackplane();
4813
4987
  const startupPromises = [];
4988
+ if (this.opts.compression === "zstd") {
4989
+ startupPromises.push(initZstd().then(() => void 0));
4990
+ }
4814
4991
  if (this.opts.remoteSnapshot) {
4815
4992
  startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
4816
4993
  }
@@ -5316,6 +5493,50 @@ var CacheService = class _CacheService {
5316
5493
  const tag = key;
5317
5494
  const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
5318
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
+ }
5319
5540
  }
5320
5541
  this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
5321
5542
  }
@@ -5323,7 +5544,7 @@ var CacheService = class _CacheService {
5323
5544
  _handleBackplaneMessage(message) {
5324
5545
  try {
5325
5546
  const msg = JSON.parse(message);
5326
- 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") {
5327
5548
  this.logger.warn("Backplane: rejected invalid pubsub message format", {
5328
5549
  raw: typeof message === "string" ? message.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(message)
5329
5550
  });
@@ -5510,12 +5731,12 @@ var CacheService = class _CacheService {
5510
5731
  * Offloads to worker thread if pool is active and payload exceeds threshold.
5511
5732
  */
5512
5733
  async _serializeAndEncrypt(serialized) {
5513
- const isCompressed2 = this.opts.compression && this.opts.compression !== "none" && serialized.length > this.opts.compressionThresholdBytes;
5514
- 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) {
5515
5736
  return this._workerPool.encrypt(serialized);
5516
5737
  }
5517
5738
  if (isCompressed2) {
5518
- const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression);
5739
+ const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression, this.opts.customCompressor);
5519
5740
  if (this.enc.isEnabled) {
5520
5741
  const encrypted = this.enc.encryptBuffer(compressed);
5521
5742
  return PREFIX_ENC_COMPRESSED + encrypted.toString("base64");
@@ -5530,16 +5751,16 @@ var CacheService = class _CacheService {
5530
5751
  */
5531
5752
  async _decryptAndDeserialize(raw) {
5532
5753
  let plain;
5533
- if (this._workerPool && raw.length > this.opts.workerThresholdBytes) {
5754
+ if (this._workerPool && !this.opts.customCompressor && raw.length > this.opts.workerThresholdBytes) {
5534
5755
  plain = await this._workerPool.decrypt(raw);
5535
5756
  } else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
5536
5757
  const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), "base64");
5537
5758
  const decBuf = this.enc.decryptBuffer(encBuf);
5538
- 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);
5539
5760
  plain = decompressed.toString("utf8");
5540
5761
  } else if (raw.startsWith(PREFIX_COMPRESSED)) {
5541
5762
  const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), "base64");
5542
- 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);
5543
5764
  plain = decompressed.toString("utf8");
5544
5765
  } else if (raw.startsWith("enc:v1:") || this.enc.isEnabled) {
5545
5766
  plain = this.enc.decrypt(raw);
@@ -5935,7 +6156,7 @@ var CacheService = class _CacheService {
5935
6156
  const optRefreshAhead = opts.refreshAhead;
5936
6157
  const optXfetchBeta = opts.xfetchBeta;
5937
6158
  const optNotFoundTtl = opts.notFoundTtl;
5938
- const optTags = opts.tags;
6159
+ const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
5939
6160
  const l1Hit = this.l1.get(k);
5940
6161
  if (l1Hit !== null) {
5941
6162
  let isGenerationalStale = false;
@@ -6393,15 +6614,16 @@ var CacheService = class _CacheService {
6393
6614
  this._pendingDiskDeletes.delete(k);
6394
6615
  this.counters.sets++;
6395
6616
  let activeTagVersions;
6396
- 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) {
6397
6619
  if (this.opts.tagStrategy === "generational") {
6398
- const vers = await Promise.all(opts.tags.map((tag) => this._getTagVersion(tag)));
6620
+ const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
6399
6621
  activeTagVersions = {};
6400
- for (let i = 0; i < opts.tags.length; i++) {
6401
- activeTagVersions[opts.tags[i]] = vers[i];
6622
+ for (let i = 0; i < tagsToRegister.length; i++) {
6623
+ activeTagVersions[tagsToRegister[i]] = vers[i];
6402
6624
  }
6403
6625
  } else {
6404
- await this._registerTags(k, opts.tags, ttlSeconds);
6626
+ await this._registerTags(k, tagsToRegister, ttlSeconds);
6405
6627
  }
6406
6628
  }
6407
6629
  this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
@@ -7016,16 +7238,23 @@ var CacheService = class _CacheService {
7016
7238
  }
7017
7239
  }
7018
7240
  }
7019
- if (missKeys.length > 0) {
7241
+ if (missKeys.length > 0 && fetchFn) {
7020
7242
  this.counters.fetches++;
7021
7243
  const fetched = await fetchFn(missKeys);
7244
+ const isMap = fetched instanceof Map;
7022
7245
  const setPromises = [];
7023
7246
  for (let j = 0; j < missKeys.length; j++) {
7024
- const v = fetched[missKeys[j]];
7247
+ const k = missKeys[j];
7248
+ const v = isMap ? fetched.get(k) : fetched[k];
7025
7249
  result[missIndexes[j]] = v;
7026
- if (v !== void 0) {
7027
- const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
7028
- 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));
7029
7258
  }
7030
7259
  }
7031
7260
  if (setPromises.length > 0) {
@@ -7168,21 +7397,109 @@ var CacheService = class _CacheService {
7168
7397
  }
7169
7398
  }
7170
7399
  /**
7171
- * Invalidate all keys associated with a tag.
7172
- * 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.
7173
7464
  *
7174
7465
  * @example
7175
7466
  * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
7176
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 });
7177
7476
  */
7178
- async invalidateTag(tag) {
7477
+ async invalidateTag(tag, opts) {
7179
7478
  this._assertActive("invalidateTag");
7180
7479
  const span = this._startSpan("tricache.invalidate_tag");
7181
7480
  if (this.opts.tracer) {
7182
7481
  span.setAttribute("cache.tag", tag);
7183
7482
  span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
7483
+ if (opts?.cascade) span.setAttribute("cache.cascade", true);
7184
7484
  }
7185
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
+ }
7186
7503
  if (this.opts.tagStrategy === "generational") {
7187
7504
  let newVer = 1;
7188
7505
  if (!this._redisDisabled) {
@@ -7245,21 +7562,35 @@ var CacheService = class _CacheService {
7245
7562
  }
7246
7563
  /**
7247
7564
  * Invalidate all keys associated with any of the given tags in a single operation.
7248
- * Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
7249
- * 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.
7250
7567
  *
7251
- * Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
7252
- * 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 }`.
7253
7570
  *
7254
7571
  * @example
7255
- * // Instead of three serial round-trips:
7256
- * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
7572
+ * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:*']);
7257
7573
  */
7258
- async invalidateTags(tags) {
7574
+ async invalidateTags(tags, opts) {
7259
7575
  this._assertActive("invalidateTags");
7260
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
+ }
7261
7592
  if (tags.length === 1) {
7262
- await this.invalidateTag(tags[0]);
7593
+ await this.invalidateTag(tags[0], opts);
7263
7594
  return;
7264
7595
  }
7265
7596
  if (this.opts.tagStrategy === "generational") {
@@ -9821,6 +10152,7 @@ async function startDashboardServer(options) {
9821
10152
  createSigV4SnapshotAdapter,
9822
10153
  deepMergeOptions,
9823
10154
  defaultCodec,
10155
+ expandHierarchicalTags,
9824
10156
  findActiveSockets,
9825
10157
  formatBytes,
9826
10158
  formatDuration,
@@ -9828,6 +10160,10 @@ async function startDashboardServer(options) {
9828
10160
  formatTraceParent,
9829
10161
  getV8HeapLimit,
9830
10162
  handleDashboardRequest,
10163
+ initZstd,
10164
+ isChildTag,
10165
+ isWildcardTag,
10166
+ matchesTagPattern,
9831
10167
  murmur3_32,
9832
10168
  parseTraceParent,
9833
10169
  readCgroupMemoryLimit,