tricache 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +1 -1
  2. package/dist/{cache-service-pJ-nFcVj.d.ts → cache-service-CREOp7MM.d.ts} +29 -1
  3. package/dist/{cache-service-26GCO3UU.js → cache-service-MG7PN6MX.js} +1 -1
  4. package/dist/{chunk-VXFTFZ5N.js → chunk-3I5L7K6I.js} +17 -0
  5. package/dist/{chunk-7SZSQS55.js → chunk-JYQFQJNJ.js} +533 -295
  6. package/dist/cli.cjs +534 -296
  7. package/dist/cli.js +2 -2
  8. package/dist/dashboard/index.d.ts +2 -2
  9. package/dist/drizzle/index.cjs +533 -295
  10. package/dist/drizzle/index.d.ts +2 -2
  11. package/dist/drizzle/index.js +1 -1
  12. package/dist/edge/index.cjs +55 -32
  13. package/dist/edge/index.d.ts +3 -3
  14. package/dist/edge/index.js +55 -32
  15. package/dist/hono/index.cjs +533 -295
  16. package/dist/hono/index.d.ts +2 -2
  17. package/dist/hono/index.js +1 -1
  18. package/dist/{hono-DuNvciyq.d.ts → hono-DSV2ve66.d.ts} +8 -1
  19. package/dist/http/index.cjs +585 -316
  20. package/dist/http/index.d.ts +3 -3
  21. package/dist/http/index.js +55 -24
  22. package/dist/index.cjs +550 -295
  23. package/dist/index.d.ts +5 -4
  24. package/dist/index.js +2 -2
  25. package/dist/nestjs/index.cjs +533 -295
  26. package/dist/nestjs/index.d.ts +2 -2
  27. package/dist/nestjs/index.js +2 -2
  28. package/dist/next/index.cjs +535 -303
  29. package/dist/next/index.d.ts +2 -2
  30. package/dist/next/index.js +3 -9
  31. package/dist/prisma/index.d.ts +2 -2
  32. package/dist/{types-5HXqBfAf.d.ts → types-Dyip5wAl.d.ts} +2 -0
  33. package/package.json +1 -1
  34. package/src/adapters/node-redis.ts +19 -0
  35. package/src/cache-service.ts +599 -320
  36. package/src/cli.ts +1 -1
  37. package/src/edge/cache.ts +60 -35
  38. package/src/http/express.ts +55 -16
  39. package/src/http/fastify.ts +3 -7
  40. package/src/next/cache-handler.ts +1 -4
  41. package/src/next/isr-handler.ts +1 -4
  42. package/src/smart-memory-cache.ts +3 -2
  43. package/src/types.ts +2 -0
package/dist/cli.cjs CHANGED
@@ -1427,7 +1427,7 @@ var SmartMemoryCache = class {
1427
1427
  };
1428
1428
  return hit;
1429
1429
  }
1430
- set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
1430
+ set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions, setAt) {
1431
1431
  const packed = this.codec.encode(data);
1432
1432
  const size = packed.byteLength;
1433
1433
  this.compressions++;
@@ -1464,7 +1464,7 @@ var SmartMemoryCache = class {
1464
1464
  priority,
1465
1465
  ttlMs,
1466
1466
  delta,
1467
- setAt: now2,
1467
+ setAt: setAt ?? now2,
1468
1468
  tagVersions
1469
1469
  });
1470
1470
  }
@@ -1492,7 +1492,7 @@ var SmartMemoryCache = class {
1492
1492
  }
1493
1493
  const now = Date.now();
1494
1494
  const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
1495
- this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: now, tagVersions });
1495
+ this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: setAt ?? now, tagVersions });
1496
1496
  if (!existingEntry) this.bloom.add(key);
1497
1497
  this.maybeRebuildBloom();
1498
1498
  this.totalSize += size;
@@ -4249,6 +4249,8 @@ var CacheService = class _CacheService {
4249
4249
  _l1Counters = /* @__PURE__ */ new Map();
4250
4250
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
4251
4251
  tagIndex = /* @__PURE__ */ new Map();
4252
+ /** Reverse index of namespaced key → { tags, expiresAt } for bounded cleanup on eviction/delete */
4253
+ keyTags = /* @__PURE__ */ new Map();
4252
4254
  /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
4253
4255
  tagVersions = /* @__PURE__ */ new Map();
4254
4256
  /**
@@ -4256,6 +4258,9 @@ var CacheService = class _CacheService {
4256
4258
  * When an exact-key delete matches a registered pattern, all dependents are cascaded.
4257
4259
  */
4258
4260
  dependencyIndex = /* @__PURE__ */ new Map();
4261
+ /** Reverse index of namespaced dependent key → source glob patterns */
4262
+ keyDependencies = /* @__PURE__ */ new Map();
4263
+ _cgroupMemoryLimit;
4259
4264
  redis = null;
4260
4265
  redisConnecting = null;
4261
4266
  cb;
@@ -4325,6 +4330,84 @@ var CacheService = class _CacheService {
4325
4330
  _getKeyMutationEpoch(namespacedKey) {
4326
4331
  return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
4327
4332
  }
4333
+ _removeKeyTags(namespacedKey) {
4334
+ const entry = this.keyTags.get(namespacedKey);
4335
+ if (!entry) return;
4336
+ for (const tag of entry.tags) {
4337
+ const tagKey = this.nk(`_tag_:${tag}`);
4338
+ const members = this.tagIndex.get(tagKey);
4339
+ if (members) {
4340
+ members.delete(namespacedKey);
4341
+ if (members.size === 0) this.tagIndex.delete(tagKey);
4342
+ }
4343
+ }
4344
+ this.keyTags.delete(namespacedKey);
4345
+ }
4346
+ _removeKeyDependencies(namespacedKey) {
4347
+ const patterns = this.keyDependencies.get(namespacedKey);
4348
+ if (patterns) {
4349
+ for (const pat of patterns) {
4350
+ const deps = this.dependencyIndex.get(pat);
4351
+ if (deps) {
4352
+ deps.delete(namespacedKey);
4353
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
4354
+ }
4355
+ }
4356
+ this.keyDependencies.delete(namespacedKey);
4357
+ } else if (this.dependencyIndex.size > 0) {
4358
+ for (const [pat, deps] of this.dependencyIndex) {
4359
+ deps.delete(namespacedKey);
4360
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
4361
+ }
4362
+ }
4363
+ }
4364
+ _handleL1Eviction(namespacedKey, reason) {
4365
+ const spilledToDisk = !this._diskDisabled && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
4366
+ if (!spilledToDisk) {
4367
+ this._removeKeyTags(namespacedKey);
4368
+ this._removeKeyDependencies(namespacedKey);
4369
+ }
4370
+ }
4371
+ _removePrefixFromIndices(prefix) {
4372
+ for (const k of Array.from(this.keyTags.keys())) {
4373
+ if (k.startsWith(prefix)) this._removeKeyTags(k);
4374
+ }
4375
+ for (const k of Array.from(this.keyDependencies.keys())) {
4376
+ if (k.startsWith(prefix)) this._removeKeyDependencies(k);
4377
+ }
4378
+ for (const k of Array.from(this._l1Counters.keys())) {
4379
+ if (k.startsWith(prefix)) this._l1Counters.delete(k);
4380
+ }
4381
+ }
4382
+ _sweepExpiredMetadata() {
4383
+ const now = Date.now();
4384
+ for (const [k, c] of this._l1Counters) {
4385
+ if (c.expiresAt <= now) this._l1Counters.delete(k);
4386
+ }
4387
+ for (const [k, meta] of this.keyTags) {
4388
+ if (meta.expiresAt <= now && !this.l1.has(k)) {
4389
+ this._removeKeyTags(k);
4390
+ this._removeKeyDependencies(k);
4391
+ }
4392
+ }
4393
+ }
4394
+ _runOomCheck() {
4395
+ const heap = import_node_v82.default.getHeapStatistics();
4396
+ const heapUsed = heap.used_heap_size / heap.heap_size_limit;
4397
+ const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? process.memoryUsage().rss / this._cgroupMemoryLimit : 0;
4398
+ const used = Math.max(heapUsed, cgroupUsed);
4399
+ if (used >= this.opts.oomHeapThreshold) {
4400
+ const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
4401
+ this.counters.oomEvictions++;
4402
+ this.counters.oomLastAt = Date.now();
4403
+ this.logger.warn("tricache OOM guard: emergency L1 eviction", {
4404
+ heapUsedPct: Math.round(heapUsed * 100),
4405
+ cgroupUsedPct: cgroupUsed > 0 ? Math.round(cgroupUsed * 100) : void 0,
4406
+ threshold: Math.round(this.opts.oomHeapThreshold * 100),
4407
+ evicted
4408
+ });
4409
+ }
4410
+ }
4328
4411
  _ipcServer;
4329
4412
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
4330
4413
  _subDisconnectedAt = null;
@@ -4371,6 +4454,7 @@ var CacheService = class _CacheService {
4371
4454
  constructor(options = {}) {
4372
4455
  const logger = options.logger ?? consoleLogger;
4373
4456
  this.logger = logger;
4457
+ this._cgroupMemoryLimit = readCgroupMemoryLimit();
4374
4458
  const ns = options.namespace?.trim() ?? "";
4375
4459
  const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
4376
4460
  this.enc = new CacheEncryption(
@@ -4554,7 +4638,10 @@ var CacheService = class _CacheService {
4554
4638
  void this.disk.save(key, entry);
4555
4639
  });
4556
4640
  },
4557
- onEviction: options.onEviction,
4641
+ onEviction: (key, reason) => {
4642
+ this._handleL1Eviction(key, reason);
4643
+ options.onEviction?.(key, reason);
4644
+ },
4558
4645
  logger
4559
4646
  });
4560
4647
  if (!this.snapshotLoaded) {
@@ -4592,6 +4679,7 @@ var CacheService = class _CacheService {
4592
4679
  }
4593
4680
  this.cleanupInterval = setInterval(() => {
4594
4681
  const cleaned = this.l1.cleanup();
4682
+ this._sweepExpiredMetadata();
4595
4683
  if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
4596
4684
  }, 5 * 60 * 1e3);
4597
4685
  if (this.cleanupInterval.unref) this.cleanupInterval.unref();
@@ -4604,18 +4692,7 @@ var CacheService = class _CacheService {
4604
4692
  }
4605
4693
  if (this.opts.oomProtection) {
4606
4694
  this.oomInterval = setInterval(() => {
4607
- const heap = import_node_v82.default.getHeapStatistics();
4608
- const used = heap.used_heap_size / heap.heap_size_limit;
4609
- if (used >= this.opts.oomHeapThreshold) {
4610
- const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
4611
- this.counters.oomEvictions++;
4612
- this.counters.oomLastAt = Date.now();
4613
- this.logger.warn("tricache OOM guard: emergency L1 eviction", {
4614
- heapUsedPct: Math.round(used * 100),
4615
- threshold: Math.round(this.opts.oomHeapThreshold * 100),
4616
- evicted
4617
- });
4618
- }
4695
+ this._runOomCheck();
4619
4696
  }, this.opts.oomCheckIntervalMs);
4620
4697
  if (this.oomInterval.unref) this.oomInterval.unref();
4621
4698
  }
@@ -5090,7 +5167,7 @@ var CacheService = class _CacheService {
5090
5167
  else if (f === "src") src = v;
5091
5168
  else if (f === "tagVersion") tagVersionRaw = v;
5092
5169
  }
5093
- const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
5170
+ const validOp = op === "del" || op === "del-glob" || op === "tag_incr" || op === "tag_pattern_incr" || op === "tag_pattern_del";
5094
5171
  if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
5095
5172
  this.logger.warn("Backplane: rejected invalid stream entry", {
5096
5173
  op: String(op).slice(0, 40),
@@ -5352,6 +5429,72 @@ var CacheService = class _CacheService {
5352
5429
  }
5353
5430
  this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
5354
5431
  }
5432
+ async _isGenerationalEntryStale(tagVersions) {
5433
+ if (this.opts.tagStrategy !== "generational" || !tagVersions) return false;
5434
+ const tags = Object.keys(tagVersions);
5435
+ if (tags.length === 0) return false;
5436
+ const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5437
+ for (let i = 0; i < tags.length; i++) {
5438
+ if (currentVers[i] > tagVersions[tags[i]]) return true;
5439
+ }
5440
+ return false;
5441
+ }
5442
+ async _deleteRedisKeys(client, keys) {
5443
+ if (keys.length === 0) return;
5444
+ const CHUNK_SIZE = 1e3;
5445
+ if (client instanceof import_ioredis.Cluster) {
5446
+ for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
5447
+ const chunk = keys.slice(i, i + CHUNK_SIZE);
5448
+ const pl = client.pipeline();
5449
+ for (const k of chunk) pl.del(k);
5450
+ await pl.exec();
5451
+ }
5452
+ return;
5453
+ }
5454
+ for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
5455
+ const chunk = keys.slice(i, i + CHUNK_SIZE);
5456
+ await client.del(...chunk);
5457
+ }
5458
+ }
5459
+ async _parseGenerationalRedisHash(k, hashData) {
5460
+ if (!hashData || !hashData.d) return null;
5461
+ let storedTagVersions = {};
5462
+ if (hashData.tv) {
5463
+ try {
5464
+ storedTagVersions = JSON.parse(hashData.tv);
5465
+ } catch {
5466
+ }
5467
+ }
5468
+ if (await this._isGenerationalEntryStale(storedTagVersions)) {
5469
+ const setAtMs = parseInt(hashData.t, 10) || 0;
5470
+ this._deleteIfStale(k, setAtMs);
5471
+ return { stale: true };
5472
+ }
5473
+ const value = await this._decryptAndDeserialize(hashData.d);
5474
+ return { value, tagVersions: storedTagVersions, stale: false };
5475
+ }
5476
+ async _readRedisEntry(client, k, allowAutoPipeline = false) {
5477
+ if (this.opts.tagStrategy === "generational" && typeof client.hgetall === "function") {
5478
+ try {
5479
+ const hashData = await client.hgetall(k);
5480
+ if (typeof hashData === "string") {
5481
+ const value2 = await this._decryptAndDeserialize(hashData);
5482
+ return { value: value2, stale: false };
5483
+ }
5484
+ if (hashData && hashData.d) {
5485
+ return await this._parseGenerationalRedisHash(k, hashData);
5486
+ }
5487
+ return null;
5488
+ } catch (err) {
5489
+ const msg = err instanceof Error ? err.message : String(err);
5490
+ if (!msg.includes("WRONGTYPE")) throw err;
5491
+ }
5492
+ }
5493
+ const raw = allowAutoPipeline && this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
5494
+ if (raw == null) return null;
5495
+ const value = await this._decryptAndDeserialize(raw);
5496
+ return { value, stale: false };
5497
+ }
5355
5498
  async _getTagVersion(tag) {
5356
5499
  const now = performance.now();
5357
5500
  const local = this.tagVersions.get(tag);
@@ -5489,8 +5632,8 @@ var CacheService = class _CacheService {
5489
5632
  return client;
5490
5633
  }
5491
5634
  this.redisConnecting = (async () => {
5635
+ let client = null;
5492
5636
  try {
5493
- let client;
5494
5637
  if (this.opts.redisClusterNodes?.length) {
5495
5638
  client = new import_ioredis.Cluster(this.opts.redisClusterNodes, {
5496
5639
  redisOptions: {
@@ -5553,14 +5696,45 @@ var CacheService = class _CacheService {
5553
5696
  });
5554
5697
  client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
5555
5698
  }
5699
+ const pendingClient = client;
5556
5700
  await new Promise((resolve, reject) => {
5557
- client.once("ready", resolve);
5558
- client.once("error", (e) => {
5701
+ let settled = false;
5702
+ const cleanupListeners = () => {
5703
+ pendingClient.removeListener?.("ready", onReady);
5704
+ pendingClient.removeListener?.("error", onError);
5705
+ };
5706
+ const onReady = () => {
5707
+ if (settled) return;
5708
+ settled = true;
5709
+ clearTimeout(timer);
5710
+ cleanupListeners();
5711
+ resolve();
5712
+ };
5713
+ const onError = (e) => {
5714
+ if (settled) return;
5715
+ settled = true;
5716
+ clearTimeout(timer);
5717
+ cleanupListeners();
5559
5718
  this._checkAndLogResp3Hint(e);
5560
5719
  reject(e);
5561
- });
5562
- setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
5720
+ };
5721
+ const timer = setTimeout(() => {
5722
+ if (settled) return;
5723
+ settled = true;
5724
+ cleanupListeners();
5725
+ reject(new Error("Redis connection timeout"));
5726
+ }, 15e3);
5727
+ if (timer.unref) timer.unref();
5728
+ pendingClient.once("ready", onReady);
5729
+ pendingClient.once("error", onError);
5563
5730
  });
5731
+ if (this._destroyed) {
5732
+ try {
5733
+ client.disconnect();
5734
+ } catch {
5735
+ }
5736
+ this._assertActive("getRedis");
5737
+ }
5564
5738
  this.cb.onSuccess();
5565
5739
  this.redis = client;
5566
5740
  this.pipeliner = new AutoPipeliner(client, {
@@ -5570,6 +5744,10 @@ var CacheService = class _CacheService {
5570
5744
  this.redisConnecting = null;
5571
5745
  return client;
5572
5746
  } catch (err) {
5747
+ try {
5748
+ client?.disconnect();
5749
+ } catch {
5750
+ }
5573
5751
  this.cb.onFailure();
5574
5752
  this.redisConnecting = null;
5575
5753
  this._checkAndLogResp3Hint(err);
@@ -5813,17 +5991,7 @@ var CacheService = class _CacheService {
5813
5991
  const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
5814
5992
  const l1Hit = this.l1.get(k);
5815
5993
  if (l1Hit !== null) {
5816
- let isGenerationalStale = false;
5817
- if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
5818
- const tags = Object.keys(l1Hit.tagVersions);
5819
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5820
- for (let i = 0; i < tags.length; i++) {
5821
- if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
5822
- isGenerationalStale = true;
5823
- break;
5824
- }
5825
- }
5826
- }
5994
+ const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
5827
5995
  if (isGenerationalStale) {
5828
5996
  this._deleteIfStale(k, l1Hit.setAt ?? 0);
5829
5997
  } else {
@@ -5909,17 +6077,7 @@ var CacheService = class _CacheService {
5909
6077
  this.watchdog.recordDisk(diskElapsed);
5910
6078
  this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
5911
6079
  if (diskHit !== null) {
5912
- let isDiskStale = false;
5913
- if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
5914
- const tags = Object.keys(diskHit.tagVersions);
5915
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5916
- for (let i = 0; i < tags.length; i++) {
5917
- if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
5918
- isDiskStale = true;
5919
- break;
5920
- }
5921
- }
5922
- }
6080
+ const isDiskStale = await this._isGenerationalEntryStale(diskHit.tagVersions);
5923
6081
  if (isDiskStale) {
5924
6082
  this.disk.delete(k);
5925
6083
  } else {
@@ -5947,57 +6105,27 @@ var CacheService = class _CacheService {
5947
6105
  try {
5948
6106
  const client = await this.getRedis();
5949
6107
  const redisStart = performance.now();
5950
- if (this.opts.tagStrategy === "generational") {
5951
- const hashData = await client.hgetall(k);
5952
- const redisElapsed = performance.now() - redisStart;
5953
- this.watchdog.recordRedis(redisElapsed);
5954
- this.cb.onSuccess();
5955
- if (hashData && hashData.d) {
5956
- let isStale = false;
5957
- let storedTagVersions = {};
5958
- if (hashData.tv) {
5959
- try {
5960
- storedTagVersions = JSON.parse(hashData.tv);
5961
- } catch {
5962
- }
5963
- }
5964
- const tags = Object.keys(storedTagVersions);
5965
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5966
- for (let i = 0; i < tags.length; i++) {
5967
- if (currentVers[i] > storedTagVersions[tags[i]]) {
5968
- isStale = true;
5969
- break;
5970
- }
5971
- }
5972
- if (isStale) {
5973
- const setAtMs = parseInt(hashData.t, 10) || 0;
5974
- this._deleteIfStale(k, setAtMs);
5975
- } else {
5976
- const parsed = await this._decryptAndDeserialize(hashData.d);
5977
- this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
5978
- this.counters.l2Hits++;
5979
- this.opts.onHit?.(cacheKey, "l2");
5980
- this.logger.debug("L2 hit (Redis hash)", { cacheKey });
5981
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5982
- if (this.opts.frozen) deepFreeze(parsed);
5983
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
5984
- }
5985
- }
5986
- } else {
5987
- const raw = this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
5988
- const redisElapsed = performance.now() - redisStart;
5989
- this.watchdog.recordRedis(redisElapsed);
5990
- this.cb.onSuccess();
5991
- if (raw) {
5992
- const parsed = await this._decryptAndDeserialize(raw);
5993
- this.l1.set(k, parsed, ttlMs, priority);
5994
- this.counters.l2Hits++;
5995
- this.opts.onHit?.(cacheKey, "l2");
5996
- this.logger.debug("L2 hit (Redis)", { cacheKey });
5997
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5998
- if (this.opts.frozen) deepFreeze(parsed);
5999
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
6108
+ const redisHit = await this._readRedisEntry(client, k, true);
6109
+ const redisElapsed = performance.now() - redisStart;
6110
+ this.watchdog.recordRedis(redisElapsed);
6111
+ this.cb.onSuccess();
6112
+ if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
6113
+ const parsed = redisHit.value;
6114
+ if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
6115
+ this.logger.debug("Aborting L2 promotion \u2014 key was mutated or deleted during Redis read", { cacheKey });
6116
+ span.setAttribute("cache.aborted_mutation_race", true);
6117
+ const current = this.l1.get(k);
6118
+ const liveVal = current && !current.isStale && current.value !== void 0 ? current.value : parsed;
6119
+ if (this.opts.frozen) deepFreeze(liveVal);
6120
+ return this.opts.cloneStrategy === "structuredClone" && liveVal != null && typeof liveVal === "object" ? structuredClone(liveVal) : liveVal;
6000
6121
  }
6122
+ this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, redisHit.tagVersions);
6123
+ this.counters.l2Hits++;
6124
+ this.opts.onHit?.(cacheKey, "l2");
6125
+ this.logger.debug(redisHit.tagVersions ? "L2 hit (Redis hash)" : "L2 hit (Redis)", { cacheKey });
6126
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
6127
+ if (this.opts.frozen) deepFreeze(parsed);
6128
+ return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
6001
6129
  }
6002
6130
  } catch (err) {
6003
6131
  this.cb.onFailure();
@@ -6059,20 +6187,20 @@ var CacheService = class _CacheService {
6059
6187
  if (this.opts.frozen) deepFreeze(data);
6060
6188
  return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
6061
6189
  }
6062
- this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
6190
+ const writeTs = Date.now();
6191
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs);
6063
6192
  if (!this._redisDisabled) {
6064
6193
  try {
6065
6194
  const client = await this.getRedis();
6066
6195
  const serialized = JSON.stringify(data);
6067
6196
  const toStore = await this._serializeAndEncrypt(serialized);
6068
6197
  const ttlSec = Math.ceil(effectiveTtl / 1e3);
6069
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
6070
- const now = Date.now();
6198
+ if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
6071
6199
  const tx = client.multi();
6072
6200
  tx.hset(k, {
6073
6201
  d: toStore,
6074
- t: String(now),
6075
- tv: JSON.stringify(activeTagVersions)
6202
+ t: String(writeTs),
6203
+ tv: JSON.stringify(activeTagVersions ?? {})
6076
6204
  });
6077
6205
  tx.expire(k, ttlSec);
6078
6206
  await tx.exec();
@@ -6210,20 +6338,20 @@ var CacheService = class _CacheService {
6210
6338
  this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
6211
6339
  return;
6212
6340
  }
6213
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
6341
+ const writeTs = Date.now();
6342
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs);
6214
6343
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6215
6344
  try {
6216
6345
  const client = await this.getRedis();
6217
6346
  const s = JSON.stringify(data);
6218
6347
  const stored = await this._serializeAndEncrypt(s);
6219
6348
  const ttlSec = Math.ceil(ttlMs / 1e3);
6220
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
6221
- const now = Date.now();
6349
+ if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
6222
6350
  const tx = client.multi();
6223
6351
  tx.hset(cacheKey, {
6224
6352
  d: stored,
6225
- t: String(now),
6226
- tv: JSON.stringify(activeTagVersions)
6353
+ t: String(writeTs),
6354
+ tv: JSON.stringify(activeTagVersions ?? {})
6227
6355
  });
6228
6356
  tx.expire(cacheKey, ttlSec);
6229
6357
  await tx.exec();
@@ -6280,16 +6408,23 @@ var CacheService = class _CacheService {
6280
6408
  await this._registerTags(k, tagsToRegister, ttlSeconds);
6281
6409
  }
6282
6410
  }
6283
- this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
6284
- if (opts?.dependsOn?.length) {
6285
- for (const pattern of opts.dependsOn) {
6286
- const nsPattern = this.nk(pattern);
6287
- let deps = this.dependencyIndex.get(nsPattern);
6288
- if (!deps) {
6289
- deps = /* @__PURE__ */ new Set();
6290
- this.dependencyIndex.set(nsPattern, deps);
6411
+ const writeTs = Date.now();
6412
+ this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions, writeTs);
6413
+ if (opts?.dependsOn !== void 0) {
6414
+ this._removeKeyDependencies(k);
6415
+ if (opts.dependsOn.length > 0) {
6416
+ const nsPatterns = [];
6417
+ for (const pattern of opts.dependsOn) {
6418
+ const nsPattern = this.nk(pattern);
6419
+ nsPatterns.push(nsPattern);
6420
+ let deps = this.dependencyIndex.get(nsPattern);
6421
+ if (!deps) {
6422
+ deps = /* @__PURE__ */ new Set();
6423
+ this.dependencyIndex.set(nsPattern, deps);
6424
+ }
6425
+ deps.add(k);
6291
6426
  }
6292
- deps.add(k);
6427
+ this.keyDependencies.set(k, nsPatterns);
6293
6428
  }
6294
6429
  }
6295
6430
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
@@ -6298,13 +6433,12 @@ var CacheService = class _CacheService {
6298
6433
  const s = JSON.stringify(data);
6299
6434
  const stored = await this._serializeAndEncrypt(s);
6300
6435
  const ttlSec = Math.ceil(ttlMs / 1e3);
6301
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
6302
- const now = Date.now();
6436
+ if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
6303
6437
  const tx = client.multi();
6304
6438
  tx.hset(k, {
6305
6439
  d: stored,
6306
- t: String(now),
6307
- tv: JSON.stringify(activeTagVersions)
6440
+ t: String(writeTs),
6441
+ tv: JSON.stringify(activeTagVersions ?? {})
6308
6442
  });
6309
6443
  tx.expire(k, ttlSec);
6310
6444
  await tx.exec();
@@ -6339,7 +6473,18 @@ var CacheService = class _CacheService {
6339
6473
  * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
6340
6474
  */
6341
6475
  async _registerTags(k, tags, ttlSeconds) {
6342
- for (const tag of tags) {
6476
+ this._removeKeyTags(k);
6477
+ const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
6478
+ const expiresAt = Date.now() + effectiveTtl * 1e3;
6479
+ if (this.keyTags.size >= 1e5 && !this.keyTags.has(k)) {
6480
+ this._sweepExpiredMetadata();
6481
+ if (this.keyTags.size >= 1e5) {
6482
+ const oldestKey = this.keyTags.keys().next().value;
6483
+ if (oldestKey !== void 0) this._removeKeyTags(oldestKey);
6484
+ }
6485
+ }
6486
+ const uniqueTags = Array.from(new Set(tags));
6487
+ for (const tag of uniqueTags) {
6343
6488
  const tagKey = this.nk(`_tag_:${tag}`);
6344
6489
  let members = this.tagIndex.get(tagKey);
6345
6490
  if (!members) {
@@ -6348,14 +6493,15 @@ var CacheService = class _CacheService {
6348
6493
  }
6349
6494
  members.add(k);
6350
6495
  }
6496
+ this.keyTags.set(k, { tags: uniqueTags, expiresAt });
6351
6497
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6352
6498
  try {
6353
6499
  const client = await this.getRedis();
6354
6500
  const pl = client.pipeline();
6355
- for (const tag of tags) {
6501
+ for (const tag of uniqueTags) {
6356
6502
  const tagKey = this.nk(`_tag_:${tag}`);
6357
6503
  pl.sadd(tagKey, k);
6358
- pl.expire(tagKey, ttlSeconds + 3600);
6504
+ pl.expire(tagKey, effectiveTtl + 3600);
6359
6505
  }
6360
6506
  await pl.exec();
6361
6507
  this.cb.onSuccess();
@@ -6394,6 +6540,13 @@ var CacheService = class _CacheService {
6394
6540
  }
6395
6541
  this._addPatternTombstone(pfx);
6396
6542
  this.l1.deletePattern(k);
6543
+ this._removePrefixFromIndices(pfx);
6544
+ for (const ktKey of Array.from(this.keyTags.keys())) {
6545
+ if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
6546
+ }
6547
+ for (const kdKey of Array.from(this.keyDependencies.keys())) {
6548
+ if (this._matchesGlob(kdKey, k)) this._removeKeyDependencies(kdKey);
6549
+ }
6397
6550
  } else {
6398
6551
  this._bumpKeyMutation(k);
6399
6552
  this.inflight.delete(k);
@@ -6406,15 +6559,16 @@ var CacheService = class _CacheService {
6406
6559
  this._pendingDiskDeletes.delete(k);
6407
6560
  }
6408
6561
  });
6562
+ this._removeKeyTags(k);
6409
6563
  this._cascadeDependencies(k);
6410
- for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
6564
+ this._removeKeyDependencies(k);
6411
6565
  }
6412
6566
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6413
6567
  try {
6414
6568
  const client = await this.getRedis();
6415
6569
  if (isPattern) {
6416
6570
  const keys = await this._scanKeys(client, k);
6417
- if (keys.length > 0) await client.del(...keys);
6571
+ await this._deleteRedisKeys(client, keys);
6418
6572
  } else {
6419
6573
  if (this.opts.autoPipeline && this.pipeliner) {
6420
6574
  await this.pipeliner.del(k);
@@ -6476,6 +6630,15 @@ var CacheService = class _CacheService {
6476
6630
  entry.value++;
6477
6631
  return entry.value;
6478
6632
  }
6633
+ if (this._l1Counters.size >= 5e4 && !this._l1Counters.has(k)) {
6634
+ for (const [ck, cv] of this._l1Counters) {
6635
+ if (cv.expiresAt <= now) this._l1Counters.delete(ck);
6636
+ }
6637
+ if (this._l1Counters.size >= 5e4) {
6638
+ const oldest = this._l1Counters.keys().next().value;
6639
+ if (oldest !== void 0) this._l1Counters.delete(oldest);
6640
+ }
6641
+ }
6479
6642
  this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
6480
6643
  return 1;
6481
6644
  }
@@ -6522,6 +6685,7 @@ var CacheService = class _CacheService {
6522
6685
  }
6523
6686
  this._addPatternTombstone(pfx);
6524
6687
  this.l1.deletePattern(k);
6688
+ this._removePrefixFromIndices(pfx);
6525
6689
  } else {
6526
6690
  this._globalEpoch++;
6527
6691
  this.inflight.clear();
@@ -6530,7 +6694,10 @@ var CacheService = class _CacheService {
6530
6694
  if (!this._diskDisabled) this.disk.clear();
6531
6695
  this._l1Counters.clear();
6532
6696
  this.tagIndex.clear();
6697
+ this.keyTags.clear();
6533
6698
  this.tagVersions.clear();
6699
+ this.dependencyIndex.clear();
6700
+ this.keyDependencies.clear();
6534
6701
  this._pendingDiskDeletes.clear();
6535
6702
  this._keyMutationEpochs.clear();
6536
6703
  }
@@ -6539,7 +6706,7 @@ var CacheService = class _CacheService {
6539
6706
  const client = await this.getRedis();
6540
6707
  const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
6541
6708
  const keys = await this._scanKeys(client, pattern);
6542
- if (keys.length > 0) await client.del(...keys);
6709
+ await this._deleteRedisKeys(client, keys);
6543
6710
  } catch (err) {
6544
6711
  this.logger.debug("clear: Redis unavailable", { error: err.message });
6545
6712
  }
@@ -6682,6 +6849,10 @@ var CacheService = class _CacheService {
6682
6849
  this._assertActive("touch");
6683
6850
  const k = this.nk(cacheKey);
6684
6851
  const hit = this.l1.touch(k, newTtlSeconds * 1e3);
6852
+ if (hit) {
6853
+ const kt = this.keyTags.get(k);
6854
+ if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1e3;
6855
+ }
6685
6856
  if (hit && !this._redisDisabled) {
6686
6857
  try {
6687
6858
  const client = await this.getRedis();
@@ -6709,6 +6880,10 @@ var CacheService = class _CacheService {
6709
6880
  if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
6710
6881
  return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
6711
6882
  }
6883
+ _prepareReadValue(val) {
6884
+ if (this.opts.frozen) deepFreeze(val);
6885
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6886
+ }
6712
6887
  /**
6713
6888
  * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
6714
6889
  * Returns the cached value if found and valid, or `null` if absent / expired.
@@ -6722,11 +6897,13 @@ var CacheService = class _CacheService {
6722
6897
  const k = this.nk(cacheKey);
6723
6898
  const l1Hit = this.l1.get(k);
6724
6899
  if (l1Hit !== null) {
6725
- this.counters.gets++;
6726
- this.counters.l1Hits++;
6727
- const val = l1Hit.value;
6728
- if (this.opts.frozen) deepFreeze(val);
6729
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6900
+ if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
6901
+ this._deleteIfStale(k, l1Hit.setAt ?? 0);
6902
+ } else {
6903
+ this.counters.gets++;
6904
+ this.counters.l1Hits++;
6905
+ return this._prepareReadValue(l1Hit.value);
6906
+ }
6730
6907
  }
6731
6908
  if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
6732
6909
  if (this._isTombstonedByPattern(k)) {
@@ -6741,18 +6918,20 @@ var CacheService = class _CacheService {
6741
6918
  this.watchdog.recordDisk(diskElapsed);
6742
6919
  this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6743
6920
  if (diskHit !== null) {
6744
- const promoted = this.l1.importEntries(
6745
- [{ key: k, entry: diskHit }],
6746
- this.opts.forbiddenSnapshotPrefixes
6747
- );
6748
- if (promoted > 0) {
6749
- const l1Check = this.l1.get(k);
6750
- if (l1Check !== null) {
6751
- this.counters.gets++;
6752
- this.counters.diskHits++;
6753
- const val = l1Check.value;
6754
- if (this.opts.frozen) deepFreeze(val);
6755
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6921
+ if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
6922
+ this.disk.delete(k);
6923
+ } else {
6924
+ const promoted = this.l1.importEntries(
6925
+ [{ key: k, entry: diskHit }],
6926
+ this.opts.forbiddenSnapshotPrefixes
6927
+ );
6928
+ if (promoted > 0) {
6929
+ const l1Check = this.l1.get(k);
6930
+ if (l1Check !== null) {
6931
+ this.counters.gets++;
6932
+ this.counters.diskHits++;
6933
+ return this._prepareReadValue(l1Check.value);
6934
+ }
6756
6935
  }
6757
6936
  }
6758
6937
  }
@@ -6762,17 +6941,16 @@ var CacheService = class _CacheService {
6762
6941
  try {
6763
6942
  const client = await this.getRedis();
6764
6943
  const redisStart = performance.now();
6765
- const raw = await client.get(k);
6944
+ const redisHit = await this._readRedisEntry(client, k);
6766
6945
  const redisElapsed = performance.now() - redisStart;
6767
6946
  this.watchdog.recordRedis(redisElapsed);
6768
- if (raw !== null) {
6769
- const parsed = await this._decryptAndDeserialize(raw);
6770
- this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
6947
+ this.cb.onSuccess();
6948
+ if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
6949
+ const parsed = redisHit.value;
6950
+ this.l1.set(k, parsed, 6e4, inferPriority(cacheKey), void 0, void 0, redisHit.tagVersions);
6771
6951
  this.counters.gets++;
6772
6952
  this.counters.l2Hits++;
6773
- this.cb.onSuccess();
6774
- if (this.opts.frozen) deepFreeze(parsed);
6775
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
6953
+ return this._prepareReadValue(parsed);
6776
6954
  }
6777
6955
  } catch (err) {
6778
6956
  this.cb.onFailure();
@@ -6800,12 +6978,20 @@ var CacheService = class _CacheService {
6800
6978
  const result = Array.from({ length: keys.length });
6801
6979
  const missIndexes = [];
6802
6980
  const missKeys = [];
6981
+ const now = Date.now();
6803
6982
  for (let i = 0; i < keys.length; i++) {
6804
6983
  const k = this.nk(keys[i]);
6805
6984
  const entry = this.l1.getEntry(k);
6806
- if (entry && entry.expiresAt > Date.now()) {
6807
- result[i] = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
6808
- this.counters.l1Hits++;
6985
+ if (entry && entry.expiresAt > now) {
6986
+ if (await this._isGenerationalEntryStale(entry.tagVersions)) {
6987
+ this._deleteIfStale(k, entry.setAt ?? 0);
6988
+ missIndexes.push(i);
6989
+ missKeys.push(keys[i]);
6990
+ } else {
6991
+ const val = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
6992
+ result[i] = this._prepareReadValue(val);
6993
+ this.counters.l1Hits++;
6994
+ }
6809
6995
  } else {
6810
6996
  missIndexes.push(i);
6811
6997
  missKeys.push(keys[i]);
@@ -6826,23 +7012,57 @@ var CacheService = class _CacheService {
6826
7012
  const client = await this.getRedis();
6827
7013
  const nsKeys = missKeys.map((k) => this.nk(k));
6828
7014
  const pipeline = client.multi();
6829
- for (const nk of nsKeys) pipeline.get(nk);
7015
+ const useHashPipeline = this.opts.tagStrategy === "generational" && typeof pipeline.hgetall === "function";
7016
+ for (const nk of nsKeys) {
7017
+ if (useHashPipeline) {
7018
+ pipeline.hgetall(nk);
7019
+ } else {
7020
+ pipeline.get(nk);
7021
+ }
7022
+ }
6830
7023
  const redisStart = performance.now();
6831
7024
  const raws = await pipeline.exec();
6832
7025
  const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
6833
7026
  this.watchdog.recordRedis(redisElapsed);
6834
7027
  this.cb.onSuccess();
6835
7028
  for (let j = 0; j < missKeys.length; j++) {
6836
- const raw = raws[j] ? raws[j][1] : null;
7029
+ const tuple = raws[j];
7030
+ const err = tuple ? tuple[0] : null;
7031
+ const rawVal = tuple ? tuple[1] : null;
6837
7032
  const idx = missIndexes[j];
6838
- if (raw) {
6839
- const parsed = await this._decryptAndDeserialize(raw);
6840
- const k = nsKeys[j];
7033
+ const k = nsKeys[j];
7034
+ let parsed;
7035
+ let tagVersions;
7036
+ let hit = false;
7037
+ if (useHashPipeline) {
7038
+ if (err && err.message?.includes("WRONGTYPE")) {
7039
+ const fallbackRaw = await client.get(k);
7040
+ if (fallbackRaw) {
7041
+ parsed = await this._decryptAndDeserialize(fallbackRaw);
7042
+ hit = true;
7043
+ }
7044
+ } else if (!err && typeof rawVal === "string") {
7045
+ parsed = await this._decryptAndDeserialize(rawVal);
7046
+ hit = true;
7047
+ } else if (!err && rawVal && typeof rawVal === "object" && rawVal.d) {
7048
+ const hashHit = await this._parseGenerationalRedisHash(k, rawVal);
7049
+ if (hashHit && !hashHit.stale && hashHit.value !== void 0) {
7050
+ parsed = hashHit.value;
7051
+ tagVersions = hashHit.tagVersions;
7052
+ hit = true;
7053
+ }
7054
+ }
7055
+ } else if (!err && rawVal) {
7056
+ parsed = await this._decryptAndDeserialize(rawVal);
7057
+ hit = true;
7058
+ }
7059
+ if (hit && parsed !== void 0) {
6841
7060
  const p = priority ?? inferPriority(missKeys[j]);
6842
- this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
7061
+ const ttlVal = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
7062
+ this.l1.set(k, parsed, this._jitterTtl(ttlVal * 1e3), p, void 0, void 0, tagVersions);
6843
7063
  this.counters.l2Hits++;
6844
7064
  l2HitCount++;
6845
- result[idx] = parsed;
7065
+ result[idx] = this._prepareReadValue(parsed);
6846
7066
  missIndexes[j] = -1;
6847
7067
  missKeys[j] = "";
6848
7068
  }
@@ -6876,6 +7096,10 @@ var CacheService = class _CacheService {
6876
7096
  this.watchdog.recordDisk(diskElapsed);
6877
7097
  this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6878
7098
  if (diskHit !== null) {
7099
+ if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
7100
+ this.disk.delete(k);
7101
+ continue;
7102
+ }
6879
7103
  const promoted = this.l1.importEntries(
6880
7104
  [{ key: k, entry: diskHit }],
6881
7105
  this.opts.forbiddenSnapshotPrefixes
@@ -6884,7 +7108,7 @@ var CacheService = class _CacheService {
6884
7108
  const l1Check = this.l1.get(k);
6885
7109
  if (l1Check !== null) {
6886
7110
  this.counters.diskHits++;
6887
- result[missIndexes[j]] = l1Check.value;
7111
+ result[missIndexes[j]] = this._prepareReadValue(l1Check.value);
6888
7112
  missIndexes.splice(j, 1);
6889
7113
  missKeys.splice(j, 1);
6890
7114
  }
@@ -7109,6 +7333,136 @@ var CacheService = class _CacheService {
7109
7333
  }
7110
7334
  return matched;
7111
7335
  }
7336
+ async _publishTagInvalidation(op, key, tagVersion) {
7337
+ if (this.opts.awaitInvalidationBackplane) {
7338
+ await this.publishInvalidation(op, key, tagVersion, false, true);
7339
+ } else {
7340
+ void this.publishInvalidation(op, key, tagVersion, false, true);
7341
+ }
7342
+ }
7343
+ _removeTagMembersLocal(keys) {
7344
+ const keyList = Array.isArray(keys) ? keys : Array.from(keys);
7345
+ for (const k of keyList) {
7346
+ this.l1.delete(k);
7347
+ this._bumpKeyMutation(k);
7348
+ this._removeKeyTags(k);
7349
+ this._removeKeyDependencies(k);
7350
+ this._pendingDiskDeletes.add(k);
7351
+ setImmediate(() => {
7352
+ try {
7353
+ if (!this._diskDisabled) this.disk.delete(k);
7354
+ } finally {
7355
+ this._pendingDiskDeletes.delete(k);
7356
+ }
7357
+ });
7358
+ }
7359
+ }
7360
+ /**
7361
+ * Executes invalidation for a single already-resolved concrete tag without
7362
+ * wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
7363
+ */
7364
+ async _invalidateConcreteTag(tag) {
7365
+ if (this.opts.tagStrategy === "generational") {
7366
+ let newVer = 1;
7367
+ if (!this._redisDisabled) {
7368
+ try {
7369
+ const client = await this.getRedis();
7370
+ newVer = await client.incr(this.nk(`tag_ver:${tag}`));
7371
+ } catch (err) {
7372
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7373
+ const current = this.tagVersions.get(tag)?.version ?? 0;
7374
+ newVer = current + 1;
7375
+ }
7376
+ } else {
7377
+ const current = this.tagVersions.get(tag)?.version ?? 0;
7378
+ newVer = current + 1;
7379
+ }
7380
+ this._setLocalTagVersion(tag, newVer, performance.now());
7381
+ await this._publishTagInvalidation("tag_incr", tag, newVer);
7382
+ return;
7383
+ }
7384
+ const tagKey = this.nk(`_tag_:${tag}`);
7385
+ const members = Array.from(this.tagIndex.get(tagKey) ?? []);
7386
+ this.tagIndex.delete(tagKey);
7387
+ this._removeTagMembersLocal(members);
7388
+ if (!this._redisDisabled) {
7389
+ try {
7390
+ const client = await this.getRedis();
7391
+ const redisMembers = await client.smembers(tagKey);
7392
+ const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers, tagKey])];
7393
+ await this._deleteRedisKeys(client, toDelete);
7394
+ } catch (err) {
7395
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7396
+ }
7397
+ }
7398
+ }
7399
+ /**
7400
+ * Executes invalidation for an array of already-resolved concrete tags
7401
+ * without re-entering wildcard/cascade resolution or invalidateTag().
7402
+ */
7403
+ async _invalidateConcreteTags(tags) {
7404
+ if (tags.length === 0) return;
7405
+ if (tags.length === 1) {
7406
+ await this._invalidateConcreteTag(tags[0]);
7407
+ return;
7408
+ }
7409
+ if (this.opts.tagStrategy === "generational") {
7410
+ const now = performance.now();
7411
+ if (!this._redisDisabled) {
7412
+ try {
7413
+ const client = await this.getRedis();
7414
+ const pl = client.pipeline();
7415
+ for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
7416
+ const results = await pl.exec();
7417
+ for (let i = 0; i < tags.length; i++) {
7418
+ const [err, newVer] = results[i] ?? [null, null];
7419
+ const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
7420
+ this._setLocalTagVersion(tags[i], ver, now);
7421
+ await this._publishTagInvalidation("tag_incr", tags[i], ver);
7422
+ }
7423
+ return;
7424
+ } catch (err) {
7425
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7426
+ }
7427
+ }
7428
+ for (const tag of tags) {
7429
+ const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
7430
+ this._setLocalTagVersion(tag, ver, now);
7431
+ await this._publishTagInvalidation("tag_incr", tag, ver);
7432
+ }
7433
+ return;
7434
+ }
7435
+ const tagKeys = [];
7436
+ const allMembers = /* @__PURE__ */ new Set();
7437
+ for (const tag of tags) {
7438
+ const tagKey = this.nk(`_tag_:${tag}`);
7439
+ tagKeys.push(tagKey);
7440
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
7441
+ for (const k of members) allMembers.add(k);
7442
+ this.tagIndex.delete(tagKey);
7443
+ }
7444
+ this._removeTagMembersLocal(allMembers);
7445
+ if (!this._redisDisabled) {
7446
+ try {
7447
+ const client = await this.getRedis();
7448
+ const pl = client.pipeline();
7449
+ for (const tagKey of tagKeys) pl.smembers(tagKey);
7450
+ const smResults = await pl.exec();
7451
+ const toDelete = [...allMembers];
7452
+ for (const [err, redisMembers] of smResults) {
7453
+ if (!err && redisMembers) {
7454
+ for (const k of redisMembers) {
7455
+ if (!allMembers.has(k)) toDelete.push(k);
7456
+ }
7457
+ }
7458
+ }
7459
+ const keysToRemove = [...toDelete, ...tagKeys];
7460
+ await this._deleteRedisKeys(client, keysToRemove);
7461
+ } catch (err) {
7462
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7463
+ }
7464
+ }
7465
+ }
7112
7466
  /**
7113
7467
  * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
7114
7468
  * Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
@@ -7144,68 +7498,13 @@ var CacheService = class _CacheService {
7144
7498
  const delim = this.opts.tagHierarchyDelimiter;
7145
7499
  const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
7146
7500
  if (matchedTags.size > 0) {
7147
- await this.invalidateTags(Array.from(matchedTags));
7501
+ await this._invalidateConcreteTags(Array.from(matchedTags));
7148
7502
  }
7149
7503
  const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
7150
- if (this.opts.awaitInvalidationBackplane) {
7151
- await this.publishInvalidation(op, broadcastPattern, void 0, false, true);
7152
- } else {
7153
- void this.publishInvalidation(op, broadcastPattern, void 0, false, true);
7154
- }
7155
- return;
7156
- }
7157
- if (this.opts.tagStrategy === "generational") {
7158
- let newVer = 1;
7159
- if (!this._redisDisabled) {
7160
- try {
7161
- const client = await this.getRedis();
7162
- newVer = await client.incr(this.nk(`tag_ver:${tag}`));
7163
- } catch (err) {
7164
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7165
- const current = this.tagVersions.get(tag)?.version ?? 0;
7166
- newVer = current + 1;
7167
- }
7168
- } else {
7169
- const current = this.tagVersions.get(tag)?.version ?? 0;
7170
- newVer = current + 1;
7171
- }
7172
- this._setLocalTagVersion(tag, newVer, performance.now());
7173
- if (this.opts.awaitInvalidationBackplane) {
7174
- await this.publishInvalidation("tag_incr", tag, newVer, false, true);
7175
- } else {
7176
- void this.publishInvalidation("tag_incr", tag, newVer, false, true);
7177
- }
7504
+ await this._publishTagInvalidation(op, broadcastPattern);
7178
7505
  return;
7179
7506
  }
7180
- const tagKey = this.nk(`_tag_:${tag}`);
7181
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
7182
- for (const k of members) {
7183
- this.l1.delete(k);
7184
- this._bumpKeyMutation(k);
7185
- this._pendingDiskDeletes.add(k);
7186
- setImmediate(() => {
7187
- try {
7188
- if (!this._diskDisabled) this.disk.delete(k);
7189
- } finally {
7190
- this._pendingDiskDeletes.delete(k);
7191
- }
7192
- });
7193
- }
7194
- this.tagIndex.delete(tagKey);
7195
- if (!this._redisDisabled) {
7196
- try {
7197
- const client = await this.getRedis();
7198
- const redisMembers = await client.smembers(tagKey);
7199
- const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
7200
- if (toDelete.length > 0) {
7201
- await client.del(...toDelete, tagKey);
7202
- } else {
7203
- await client.del(tagKey);
7204
- }
7205
- } catch (err) {
7206
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7207
- }
7208
- }
7507
+ await this._invalidateConcreteTag(tag);
7209
7508
  } catch (err) {
7210
7509
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
7211
7510
  span.recordException?.(err);
@@ -7232,96 +7531,28 @@ var CacheService = class _CacheService {
7232
7531
  const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
7233
7532
  if (hasWildcards || shouldCascade) {
7234
7533
  const allResolvedTags = /* @__PURE__ */ new Set();
7534
+ const broadcastPatterns = /* @__PURE__ */ new Set();
7535
+ const delim = this.opts.tagHierarchyDelimiter;
7235
7536
  for (const t of tags) {
7236
- if (isWildcardTag(t) || shouldCascade) {
7537
+ const tIsPattern = isWildcardTag(t);
7538
+ if (tIsPattern || shouldCascade) {
7539
+ broadcastPatterns.add(tIsPattern ? t : `${t}${delim}*`);
7237
7540
  const resolved = await this._resolveMatchingTags(t, shouldCascade);
7238
7541
  for (const rt of resolved) allResolvedTags.add(rt);
7239
7542
  } else {
7240
7543
  allResolvedTags.add(t);
7241
7544
  }
7242
7545
  }
7243
- if (allResolvedTags.size === 0) return;
7244
- tags = Array.from(allResolvedTags);
7245
- }
7246
- if (tags.length === 1) {
7247
- await this.invalidateTag(tags[0], opts);
7248
- return;
7249
- }
7250
- if (this.opts.tagStrategy === "generational") {
7251
- const now = performance.now();
7252
- if (!this._redisDisabled) {
7253
- try {
7254
- const client = await this.getRedis();
7255
- const pl = client.pipeline();
7256
- for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
7257
- const results = await pl.exec();
7258
- for (let i = 0; i < tags.length; i++) {
7259
- const [err, newVer] = results[i] ?? [null, null];
7260
- const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
7261
- this._setLocalTagVersion(tags[i], ver, now);
7262
- if (this.opts.awaitInvalidationBackplane) {
7263
- await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7264
- } else {
7265
- void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7266
- }
7267
- }
7268
- return;
7269
- } catch (err) {
7270
- this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7271
- }
7546
+ if (allResolvedTags.size > 0) {
7547
+ await this._invalidateConcreteTags(Array.from(allResolvedTags));
7272
7548
  }
7273
- for (const tag of tags) {
7274
- const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
7275
- this._setLocalTagVersion(tag, ver, now);
7276
- if (this.opts.awaitInvalidationBackplane) {
7277
- await this.publishInvalidation("tag_incr", tag, ver, false, true);
7278
- } else {
7279
- void this.publishInvalidation("tag_incr", tag, ver, false, true);
7280
- }
7549
+ const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
7550
+ for (const pattern of broadcastPatterns) {
7551
+ await this._publishTagInvalidation(op, pattern);
7281
7552
  }
7282
7553
  return;
7283
7554
  }
7284
- const tagKeys = [];
7285
- const allMembers = /* @__PURE__ */ new Set();
7286
- for (const tag of tags) {
7287
- const tagKey = this.nk(`_tag_:${tag}`);
7288
- tagKeys.push(tagKey);
7289
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
7290
- for (const k of members) allMembers.add(k);
7291
- this.tagIndex.delete(tagKey);
7292
- }
7293
- for (const k of allMembers) {
7294
- this.l1.delete(k);
7295
- this._bumpKeyMutation(k);
7296
- this._pendingDiskDeletes.add(k);
7297
- setImmediate(() => {
7298
- try {
7299
- if (!this._diskDisabled) this.disk.delete(k);
7300
- } finally {
7301
- this._pendingDiskDeletes.delete(k);
7302
- }
7303
- });
7304
- }
7305
- if (!this._redisDisabled) {
7306
- try {
7307
- const client = await this.getRedis();
7308
- const pl = client.pipeline();
7309
- for (const tagKey of tagKeys) pl.smembers(tagKey);
7310
- const smResults = await pl.exec();
7311
- const toDelete = [...allMembers];
7312
- for (const [err, redisMembers] of smResults) {
7313
- if (!err && redisMembers) {
7314
- for (const k of redisMembers) {
7315
- if (!allMembers.has(k)) toDelete.push(k);
7316
- }
7317
- }
7318
- }
7319
- const keysToRemove = [...toDelete, ...tagKeys];
7320
- if (keysToRemove.length > 0) await client.del(...keysToRemove);
7321
- } catch (err) {
7322
- this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7323
- }
7324
- }
7555
+ await this._invalidateConcreteTags(Array.from(new Set(tags)));
7325
7556
  }
7326
7557
  /**
7327
7558
  * Get the current generational tag version for a tag (synced with Redis when due).
@@ -7888,6 +8119,13 @@ var CacheService = class _CacheService {
7888
8119
  this._destroyed = true;
7889
8120
  this._pendingDiskDeletes.clear();
7890
8121
  this._keyMutationEpochs.clear();
8122
+ this.inflight.clear();
8123
+ this.revalidating.clear();
8124
+ this._l1Counters.clear();
8125
+ this.tagIndex.clear();
8126
+ this.keyTags.clear();
8127
+ this.dependencyIndex.clear();
8128
+ this.keyDependencies.clear();
7891
8129
  const g = globalThis;
7892
8130
  const key = _CacheService.globalKey(this.opts);
7893
8131
  if (g[key] === this) {
@@ -7991,7 +8229,7 @@ async function runCli(args = process.argv.slice(2)) {
7991
8229
  return;
7992
8230
  }
7993
8231
  if (values.version || command === "version") {
7994
- let version = "1.0.0";
8232
+ let version = "1.0.1";
7995
8233
  try {
7996
8234
  const pkg = JSON.parse((0, import_node_fs3.readFileSync)(new URL("../package.json", import_meta2.url), "utf8"));
7997
8235
  if (pkg?.version) version = pkg.version;