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/index.cjs CHANGED
@@ -1773,7 +1773,7 @@ var SmartMemoryCache = class {
1773
1773
  };
1774
1774
  return hit;
1775
1775
  }
1776
- set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
1776
+ set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions, setAt) {
1777
1777
  const packed = this.codec.encode(data);
1778
1778
  const size = packed.byteLength;
1779
1779
  this.compressions++;
@@ -1810,7 +1810,7 @@ var SmartMemoryCache = class {
1810
1810
  priority,
1811
1811
  ttlMs,
1812
1812
  delta,
1813
- setAt: now2,
1813
+ setAt: setAt ?? now2,
1814
1814
  tagVersions
1815
1815
  });
1816
1816
  }
@@ -1838,7 +1838,7 @@ var SmartMemoryCache = class {
1838
1838
  }
1839
1839
  const now = Date.now();
1840
1840
  const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
1841
- 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 });
1841
+ 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 });
1842
1842
  if (!existingEntry) this.bloom.add(key);
1843
1843
  this.maybeRebuildBloom();
1844
1844
  this.totalSize += size;
@@ -4595,6 +4595,8 @@ var CacheService = class _CacheService {
4595
4595
  _l1Counters = /* @__PURE__ */ new Map();
4596
4596
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
4597
4597
  tagIndex = /* @__PURE__ */ new Map();
4598
+ /** Reverse index of namespaced key → { tags, expiresAt } for bounded cleanup on eviction/delete */
4599
+ keyTags = /* @__PURE__ */ new Map();
4598
4600
  /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
4599
4601
  tagVersions = /* @__PURE__ */ new Map();
4600
4602
  /**
@@ -4602,6 +4604,9 @@ var CacheService = class _CacheService {
4602
4604
  * When an exact-key delete matches a registered pattern, all dependents are cascaded.
4603
4605
  */
4604
4606
  dependencyIndex = /* @__PURE__ */ new Map();
4607
+ /** Reverse index of namespaced dependent key → source glob patterns */
4608
+ keyDependencies = /* @__PURE__ */ new Map();
4609
+ _cgroupMemoryLimit;
4605
4610
  redis = null;
4606
4611
  redisConnecting = null;
4607
4612
  cb;
@@ -4671,6 +4676,84 @@ var CacheService = class _CacheService {
4671
4676
  _getKeyMutationEpoch(namespacedKey) {
4672
4677
  return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
4673
4678
  }
4679
+ _removeKeyTags(namespacedKey) {
4680
+ const entry = this.keyTags.get(namespacedKey);
4681
+ if (!entry) return;
4682
+ for (const tag of entry.tags) {
4683
+ const tagKey = this.nk(`_tag_:${tag}`);
4684
+ const members = this.tagIndex.get(tagKey);
4685
+ if (members) {
4686
+ members.delete(namespacedKey);
4687
+ if (members.size === 0) this.tagIndex.delete(tagKey);
4688
+ }
4689
+ }
4690
+ this.keyTags.delete(namespacedKey);
4691
+ }
4692
+ _removeKeyDependencies(namespacedKey) {
4693
+ const patterns = this.keyDependencies.get(namespacedKey);
4694
+ if (patterns) {
4695
+ for (const pat of patterns) {
4696
+ const deps = this.dependencyIndex.get(pat);
4697
+ if (deps) {
4698
+ deps.delete(namespacedKey);
4699
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
4700
+ }
4701
+ }
4702
+ this.keyDependencies.delete(namespacedKey);
4703
+ } else if (this.dependencyIndex.size > 0) {
4704
+ for (const [pat, deps] of this.dependencyIndex) {
4705
+ deps.delete(namespacedKey);
4706
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
4707
+ }
4708
+ }
4709
+ }
4710
+ _handleL1Eviction(namespacedKey, reason) {
4711
+ const spilledToDisk = !this._diskDisabled && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
4712
+ if (!spilledToDisk) {
4713
+ this._removeKeyTags(namespacedKey);
4714
+ this._removeKeyDependencies(namespacedKey);
4715
+ }
4716
+ }
4717
+ _removePrefixFromIndices(prefix) {
4718
+ for (const k of Array.from(this.keyTags.keys())) {
4719
+ if (k.startsWith(prefix)) this._removeKeyTags(k);
4720
+ }
4721
+ for (const k of Array.from(this.keyDependencies.keys())) {
4722
+ if (k.startsWith(prefix)) this._removeKeyDependencies(k);
4723
+ }
4724
+ for (const k of Array.from(this._l1Counters.keys())) {
4725
+ if (k.startsWith(prefix)) this._l1Counters.delete(k);
4726
+ }
4727
+ }
4728
+ _sweepExpiredMetadata() {
4729
+ const now = Date.now();
4730
+ for (const [k, c] of this._l1Counters) {
4731
+ if (c.expiresAt <= now) this._l1Counters.delete(k);
4732
+ }
4733
+ for (const [k, meta] of this.keyTags) {
4734
+ if (meta.expiresAt <= now && !this.l1.has(k)) {
4735
+ this._removeKeyTags(k);
4736
+ this._removeKeyDependencies(k);
4737
+ }
4738
+ }
4739
+ }
4740
+ _runOomCheck() {
4741
+ const heap = import_node_v82.default.getHeapStatistics();
4742
+ const heapUsed = heap.used_heap_size / heap.heap_size_limit;
4743
+ const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? process.memoryUsage().rss / this._cgroupMemoryLimit : 0;
4744
+ const used = Math.max(heapUsed, cgroupUsed);
4745
+ if (used >= this.opts.oomHeapThreshold) {
4746
+ const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
4747
+ this.counters.oomEvictions++;
4748
+ this.counters.oomLastAt = Date.now();
4749
+ this.logger.warn("tricache OOM guard: emergency L1 eviction", {
4750
+ heapUsedPct: Math.round(heapUsed * 100),
4751
+ cgroupUsedPct: cgroupUsed > 0 ? Math.round(cgroupUsed * 100) : void 0,
4752
+ threshold: Math.round(this.opts.oomHeapThreshold * 100),
4753
+ evicted
4754
+ });
4755
+ }
4756
+ }
4674
4757
  _ipcServer;
4675
4758
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
4676
4759
  _subDisconnectedAt = null;
@@ -4717,6 +4800,7 @@ var CacheService = class _CacheService {
4717
4800
  constructor(options = {}) {
4718
4801
  const logger = options.logger ?? consoleLogger;
4719
4802
  this.logger = logger;
4803
+ this._cgroupMemoryLimit = readCgroupMemoryLimit();
4720
4804
  const ns = options.namespace?.trim() ?? "";
4721
4805
  const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
4722
4806
  this.enc = new CacheEncryption(
@@ -4900,7 +4984,10 @@ var CacheService = class _CacheService {
4900
4984
  void this.disk.save(key, entry);
4901
4985
  });
4902
4986
  },
4903
- onEviction: options.onEviction,
4987
+ onEviction: (key, reason) => {
4988
+ this._handleL1Eviction(key, reason);
4989
+ options.onEviction?.(key, reason);
4990
+ },
4904
4991
  logger
4905
4992
  });
4906
4993
  if (!this.snapshotLoaded) {
@@ -4938,6 +5025,7 @@ var CacheService = class _CacheService {
4938
5025
  }
4939
5026
  this.cleanupInterval = setInterval(() => {
4940
5027
  const cleaned = this.l1.cleanup();
5028
+ this._sweepExpiredMetadata();
4941
5029
  if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
4942
5030
  }, 5 * 60 * 1e3);
4943
5031
  if (this.cleanupInterval.unref) this.cleanupInterval.unref();
@@ -4950,18 +5038,7 @@ var CacheService = class _CacheService {
4950
5038
  }
4951
5039
  if (this.opts.oomProtection) {
4952
5040
  this.oomInterval = setInterval(() => {
4953
- const heap = import_node_v82.default.getHeapStatistics();
4954
- const used = heap.used_heap_size / heap.heap_size_limit;
4955
- if (used >= this.opts.oomHeapThreshold) {
4956
- const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
4957
- this.counters.oomEvictions++;
4958
- this.counters.oomLastAt = Date.now();
4959
- this.logger.warn("tricache OOM guard: emergency L1 eviction", {
4960
- heapUsedPct: Math.round(used * 100),
4961
- threshold: Math.round(this.opts.oomHeapThreshold * 100),
4962
- evicted
4963
- });
4964
- }
5041
+ this._runOomCheck();
4965
5042
  }, this.opts.oomCheckIntervalMs);
4966
5043
  if (this.oomInterval.unref) this.oomInterval.unref();
4967
5044
  }
@@ -5436,7 +5513,7 @@ var CacheService = class _CacheService {
5436
5513
  else if (f === "src") src = v;
5437
5514
  else if (f === "tagVersion") tagVersionRaw = v;
5438
5515
  }
5439
- const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
5516
+ const validOp = op === "del" || op === "del-glob" || op === "tag_incr" || op === "tag_pattern_incr" || op === "tag_pattern_del";
5440
5517
  if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
5441
5518
  this.logger.warn("Backplane: rejected invalid stream entry", {
5442
5519
  op: String(op).slice(0, 40),
@@ -5698,6 +5775,72 @@ var CacheService = class _CacheService {
5698
5775
  }
5699
5776
  this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
5700
5777
  }
5778
+ async _isGenerationalEntryStale(tagVersions) {
5779
+ if (this.opts.tagStrategy !== "generational" || !tagVersions) return false;
5780
+ const tags = Object.keys(tagVersions);
5781
+ if (tags.length === 0) return false;
5782
+ const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5783
+ for (let i = 0; i < tags.length; i++) {
5784
+ if (currentVers[i] > tagVersions[tags[i]]) return true;
5785
+ }
5786
+ return false;
5787
+ }
5788
+ async _deleteRedisKeys(client, keys) {
5789
+ if (keys.length === 0) return;
5790
+ const CHUNK_SIZE = 1e3;
5791
+ if (client instanceof import_ioredis.Cluster) {
5792
+ for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
5793
+ const chunk = keys.slice(i, i + CHUNK_SIZE);
5794
+ const pl = client.pipeline();
5795
+ for (const k of chunk) pl.del(k);
5796
+ await pl.exec();
5797
+ }
5798
+ return;
5799
+ }
5800
+ for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
5801
+ const chunk = keys.slice(i, i + CHUNK_SIZE);
5802
+ await client.del(...chunk);
5803
+ }
5804
+ }
5805
+ async _parseGenerationalRedisHash(k, hashData) {
5806
+ if (!hashData || !hashData.d) return null;
5807
+ let storedTagVersions = {};
5808
+ if (hashData.tv) {
5809
+ try {
5810
+ storedTagVersions = JSON.parse(hashData.tv);
5811
+ } catch {
5812
+ }
5813
+ }
5814
+ if (await this._isGenerationalEntryStale(storedTagVersions)) {
5815
+ const setAtMs = parseInt(hashData.t, 10) || 0;
5816
+ this._deleteIfStale(k, setAtMs);
5817
+ return { stale: true };
5818
+ }
5819
+ const value = await this._decryptAndDeserialize(hashData.d);
5820
+ return { value, tagVersions: storedTagVersions, stale: false };
5821
+ }
5822
+ async _readRedisEntry(client, k, allowAutoPipeline = false) {
5823
+ if (this.opts.tagStrategy === "generational" && typeof client.hgetall === "function") {
5824
+ try {
5825
+ const hashData = await client.hgetall(k);
5826
+ if (typeof hashData === "string") {
5827
+ const value2 = await this._decryptAndDeserialize(hashData);
5828
+ return { value: value2, stale: false };
5829
+ }
5830
+ if (hashData && hashData.d) {
5831
+ return await this._parseGenerationalRedisHash(k, hashData);
5832
+ }
5833
+ return null;
5834
+ } catch (err) {
5835
+ const msg = err instanceof Error ? err.message : String(err);
5836
+ if (!msg.includes("WRONGTYPE")) throw err;
5837
+ }
5838
+ }
5839
+ const raw = allowAutoPipeline && this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
5840
+ if (raw == null) return null;
5841
+ const value = await this._decryptAndDeserialize(raw);
5842
+ return { value, stale: false };
5843
+ }
5701
5844
  async _getTagVersion(tag) {
5702
5845
  const now = performance.now();
5703
5846
  const local = this.tagVersions.get(tag);
@@ -5835,8 +5978,8 @@ var CacheService = class _CacheService {
5835
5978
  return client;
5836
5979
  }
5837
5980
  this.redisConnecting = (async () => {
5981
+ let client = null;
5838
5982
  try {
5839
- let client;
5840
5983
  if (this.opts.redisClusterNodes?.length) {
5841
5984
  client = new import_ioredis.Cluster(this.opts.redisClusterNodes, {
5842
5985
  redisOptions: {
@@ -5899,14 +6042,45 @@ var CacheService = class _CacheService {
5899
6042
  });
5900
6043
  client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
5901
6044
  }
6045
+ const pendingClient = client;
5902
6046
  await new Promise((resolve, reject) => {
5903
- client.once("ready", resolve);
5904
- client.once("error", (e) => {
6047
+ let settled = false;
6048
+ const cleanupListeners = () => {
6049
+ pendingClient.removeListener?.("ready", onReady);
6050
+ pendingClient.removeListener?.("error", onError);
6051
+ };
6052
+ const onReady = () => {
6053
+ if (settled) return;
6054
+ settled = true;
6055
+ clearTimeout(timer);
6056
+ cleanupListeners();
6057
+ resolve();
6058
+ };
6059
+ const onError = (e) => {
6060
+ if (settled) return;
6061
+ settled = true;
6062
+ clearTimeout(timer);
6063
+ cleanupListeners();
5905
6064
  this._checkAndLogResp3Hint(e);
5906
6065
  reject(e);
5907
- });
5908
- setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
6066
+ };
6067
+ const timer = setTimeout(() => {
6068
+ if (settled) return;
6069
+ settled = true;
6070
+ cleanupListeners();
6071
+ reject(new Error("Redis connection timeout"));
6072
+ }, 15e3);
6073
+ if (timer.unref) timer.unref();
6074
+ pendingClient.once("ready", onReady);
6075
+ pendingClient.once("error", onError);
5909
6076
  });
6077
+ if (this._destroyed) {
6078
+ try {
6079
+ client.disconnect();
6080
+ } catch {
6081
+ }
6082
+ this._assertActive("getRedis");
6083
+ }
5910
6084
  this.cb.onSuccess();
5911
6085
  this.redis = client;
5912
6086
  this.pipeliner = new AutoPipeliner(client, {
@@ -5916,6 +6090,10 @@ var CacheService = class _CacheService {
5916
6090
  this.redisConnecting = null;
5917
6091
  return client;
5918
6092
  } catch (err) {
6093
+ try {
6094
+ client?.disconnect();
6095
+ } catch {
6096
+ }
5919
6097
  this.cb.onFailure();
5920
6098
  this.redisConnecting = null;
5921
6099
  this._checkAndLogResp3Hint(err);
@@ -6159,17 +6337,7 @@ var CacheService = class _CacheService {
6159
6337
  const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
6160
6338
  const l1Hit = this.l1.get(k);
6161
6339
  if (l1Hit !== null) {
6162
- let isGenerationalStale = false;
6163
- if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
6164
- const tags = Object.keys(l1Hit.tagVersions);
6165
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
6166
- for (let i = 0; i < tags.length; i++) {
6167
- if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
6168
- isGenerationalStale = true;
6169
- break;
6170
- }
6171
- }
6172
- }
6340
+ const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
6173
6341
  if (isGenerationalStale) {
6174
6342
  this._deleteIfStale(k, l1Hit.setAt ?? 0);
6175
6343
  } else {
@@ -6255,17 +6423,7 @@ var CacheService = class _CacheService {
6255
6423
  this.watchdog.recordDisk(diskElapsed);
6256
6424
  this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6257
6425
  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
- }
6267
- }
6268
- }
6426
+ const isDiskStale = await this._isGenerationalEntryStale(diskHit.tagVersions);
6269
6427
  if (isDiskStale) {
6270
6428
  this.disk.delete(k);
6271
6429
  } else {
@@ -6293,57 +6451,27 @@ var CacheService = class _CacheService {
6293
6451
  try {
6294
6452
  const client = await this.getRedis();
6295
6453
  const redisStart = performance.now();
6296
- if (this.opts.tagStrategy === "generational") {
6297
- const hashData = await client.hgetall(k);
6298
- const redisElapsed = performance.now() - redisStart;
6299
- this.watchdog.recordRedis(redisElapsed);
6300
- this.cb.onSuccess();
6301
- if (hashData && hashData.d) {
6302
- let isStale = false;
6303
- let storedTagVersions = {};
6304
- if (hashData.tv) {
6305
- try {
6306
- storedTagVersions = JSON.parse(hashData.tv);
6307
- } catch {
6308
- }
6309
- }
6310
- const tags = Object.keys(storedTagVersions);
6311
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
6312
- for (let i = 0; i < tags.length; i++) {
6313
- if (currentVers[i] > storedTagVersions[tags[i]]) {
6314
- isStale = true;
6315
- break;
6316
- }
6317
- }
6318
- if (isStale) {
6319
- const setAtMs = parseInt(hashData.t, 10) || 0;
6320
- this._deleteIfStale(k, setAtMs);
6321
- } else {
6322
- const parsed = await this._decryptAndDeserialize(hashData.d);
6323
- this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
6324
- this.counters.l2Hits++;
6325
- this.opts.onHit?.(cacheKey, "l2");
6326
- this.logger.debug("L2 hit (Redis hash)", { cacheKey });
6327
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
6328
- if (this.opts.frozen) deepFreeze(parsed);
6329
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
6330
- }
6331
- }
6332
- } else {
6333
- const raw = this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
6334
- const redisElapsed = performance.now() - redisStart;
6335
- this.watchdog.recordRedis(redisElapsed);
6336
- this.cb.onSuccess();
6337
- if (raw) {
6338
- const parsed = await this._decryptAndDeserialize(raw);
6339
- this.l1.set(k, parsed, ttlMs, priority);
6340
- this.counters.l2Hits++;
6341
- this.opts.onHit?.(cacheKey, "l2");
6342
- this.logger.debug("L2 hit (Redis)", { cacheKey });
6343
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
6344
- if (this.opts.frozen) deepFreeze(parsed);
6345
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
6454
+ const redisHit = await this._readRedisEntry(client, k, true);
6455
+ const redisElapsed = performance.now() - redisStart;
6456
+ this.watchdog.recordRedis(redisElapsed);
6457
+ this.cb.onSuccess();
6458
+ if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
6459
+ const parsed = redisHit.value;
6460
+ if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
6461
+ this.logger.debug("Aborting L2 promotion \u2014 key was mutated or deleted during Redis read", { cacheKey });
6462
+ span.setAttribute("cache.aborted_mutation_race", true);
6463
+ const current = this.l1.get(k);
6464
+ const liveVal = current && !current.isStale && current.value !== void 0 ? current.value : parsed;
6465
+ if (this.opts.frozen) deepFreeze(liveVal);
6466
+ return this.opts.cloneStrategy === "structuredClone" && liveVal != null && typeof liveVal === "object" ? structuredClone(liveVal) : liveVal;
6346
6467
  }
6468
+ this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, redisHit.tagVersions);
6469
+ this.counters.l2Hits++;
6470
+ this.opts.onHit?.(cacheKey, "l2");
6471
+ this.logger.debug(redisHit.tagVersions ? "L2 hit (Redis hash)" : "L2 hit (Redis)", { cacheKey });
6472
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
6473
+ if (this.opts.frozen) deepFreeze(parsed);
6474
+ return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
6347
6475
  }
6348
6476
  } catch (err) {
6349
6477
  this.cb.onFailure();
@@ -6405,20 +6533,20 @@ var CacheService = class _CacheService {
6405
6533
  if (this.opts.frozen) deepFreeze(data);
6406
6534
  return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
6407
6535
  }
6408
- this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
6536
+ const writeTs = Date.now();
6537
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs);
6409
6538
  if (!this._redisDisabled) {
6410
6539
  try {
6411
6540
  const client = await this.getRedis();
6412
6541
  const serialized = JSON.stringify(data);
6413
6542
  const toStore = await this._serializeAndEncrypt(serialized);
6414
6543
  const ttlSec = Math.ceil(effectiveTtl / 1e3);
6415
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
6416
- const now = Date.now();
6544
+ if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
6417
6545
  const tx = client.multi();
6418
6546
  tx.hset(k, {
6419
6547
  d: toStore,
6420
- t: String(now),
6421
- tv: JSON.stringify(activeTagVersions)
6548
+ t: String(writeTs),
6549
+ tv: JSON.stringify(activeTagVersions ?? {})
6422
6550
  });
6423
6551
  tx.expire(k, ttlSec);
6424
6552
  await tx.exec();
@@ -6556,20 +6684,20 @@ var CacheService = class _CacheService {
6556
6684
  this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
6557
6685
  return;
6558
6686
  }
6559
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
6687
+ const writeTs = Date.now();
6688
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs);
6560
6689
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6561
6690
  try {
6562
6691
  const client = await this.getRedis();
6563
6692
  const s = JSON.stringify(data);
6564
6693
  const stored = await this._serializeAndEncrypt(s);
6565
6694
  const ttlSec = Math.ceil(ttlMs / 1e3);
6566
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
6567
- const now = Date.now();
6695
+ if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
6568
6696
  const tx = client.multi();
6569
6697
  tx.hset(cacheKey, {
6570
6698
  d: stored,
6571
- t: String(now),
6572
- tv: JSON.stringify(activeTagVersions)
6699
+ t: String(writeTs),
6700
+ tv: JSON.stringify(activeTagVersions ?? {})
6573
6701
  });
6574
6702
  tx.expire(cacheKey, ttlSec);
6575
6703
  await tx.exec();
@@ -6626,16 +6754,23 @@ var CacheService = class _CacheService {
6626
6754
  await this._registerTags(k, tagsToRegister, ttlSeconds);
6627
6755
  }
6628
6756
  }
6629
- this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
6630
- if (opts?.dependsOn?.length) {
6631
- for (const pattern of opts.dependsOn) {
6632
- const nsPattern = this.nk(pattern);
6633
- let deps = this.dependencyIndex.get(nsPattern);
6634
- if (!deps) {
6635
- deps = /* @__PURE__ */ new Set();
6636
- this.dependencyIndex.set(nsPattern, deps);
6757
+ const writeTs = Date.now();
6758
+ this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions, writeTs);
6759
+ if (opts?.dependsOn !== void 0) {
6760
+ this._removeKeyDependencies(k);
6761
+ if (opts.dependsOn.length > 0) {
6762
+ const nsPatterns = [];
6763
+ for (const pattern of opts.dependsOn) {
6764
+ const nsPattern = this.nk(pattern);
6765
+ nsPatterns.push(nsPattern);
6766
+ let deps = this.dependencyIndex.get(nsPattern);
6767
+ if (!deps) {
6768
+ deps = /* @__PURE__ */ new Set();
6769
+ this.dependencyIndex.set(nsPattern, deps);
6770
+ }
6771
+ deps.add(k);
6637
6772
  }
6638
- deps.add(k);
6773
+ this.keyDependencies.set(k, nsPatterns);
6639
6774
  }
6640
6775
  }
6641
6776
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
@@ -6644,13 +6779,12 @@ var CacheService = class _CacheService {
6644
6779
  const s = JSON.stringify(data);
6645
6780
  const stored = await this._serializeAndEncrypt(s);
6646
6781
  const ttlSec = Math.ceil(ttlMs / 1e3);
6647
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
6648
- const now = Date.now();
6782
+ if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
6649
6783
  const tx = client.multi();
6650
6784
  tx.hset(k, {
6651
6785
  d: stored,
6652
- t: String(now),
6653
- tv: JSON.stringify(activeTagVersions)
6786
+ t: String(writeTs),
6787
+ tv: JSON.stringify(activeTagVersions ?? {})
6654
6788
  });
6655
6789
  tx.expire(k, ttlSec);
6656
6790
  await tx.exec();
@@ -6685,7 +6819,18 @@ var CacheService = class _CacheService {
6685
6819
  * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
6686
6820
  */
6687
6821
  async _registerTags(k, tags, ttlSeconds) {
6688
- for (const tag of tags) {
6822
+ this._removeKeyTags(k);
6823
+ const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
6824
+ const expiresAt = Date.now() + effectiveTtl * 1e3;
6825
+ if (this.keyTags.size >= 1e5 && !this.keyTags.has(k)) {
6826
+ this._sweepExpiredMetadata();
6827
+ if (this.keyTags.size >= 1e5) {
6828
+ const oldestKey = this.keyTags.keys().next().value;
6829
+ if (oldestKey !== void 0) this._removeKeyTags(oldestKey);
6830
+ }
6831
+ }
6832
+ const uniqueTags = Array.from(new Set(tags));
6833
+ for (const tag of uniqueTags) {
6689
6834
  const tagKey = this.nk(`_tag_:${tag}`);
6690
6835
  let members = this.tagIndex.get(tagKey);
6691
6836
  if (!members) {
@@ -6694,14 +6839,15 @@ var CacheService = class _CacheService {
6694
6839
  }
6695
6840
  members.add(k);
6696
6841
  }
6842
+ this.keyTags.set(k, { tags: uniqueTags, expiresAt });
6697
6843
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6698
6844
  try {
6699
6845
  const client = await this.getRedis();
6700
6846
  const pl = client.pipeline();
6701
- for (const tag of tags) {
6847
+ for (const tag of uniqueTags) {
6702
6848
  const tagKey = this.nk(`_tag_:${tag}`);
6703
6849
  pl.sadd(tagKey, k);
6704
- pl.expire(tagKey, ttlSeconds + 3600);
6850
+ pl.expire(tagKey, effectiveTtl + 3600);
6705
6851
  }
6706
6852
  await pl.exec();
6707
6853
  this.cb.onSuccess();
@@ -6740,6 +6886,13 @@ var CacheService = class _CacheService {
6740
6886
  }
6741
6887
  this._addPatternTombstone(pfx);
6742
6888
  this.l1.deletePattern(k);
6889
+ this._removePrefixFromIndices(pfx);
6890
+ for (const ktKey of Array.from(this.keyTags.keys())) {
6891
+ if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
6892
+ }
6893
+ for (const kdKey of Array.from(this.keyDependencies.keys())) {
6894
+ if (this._matchesGlob(kdKey, k)) this._removeKeyDependencies(kdKey);
6895
+ }
6743
6896
  } else {
6744
6897
  this._bumpKeyMutation(k);
6745
6898
  this.inflight.delete(k);
@@ -6752,15 +6905,16 @@ var CacheService = class _CacheService {
6752
6905
  this._pendingDiskDeletes.delete(k);
6753
6906
  }
6754
6907
  });
6908
+ this._removeKeyTags(k);
6755
6909
  this._cascadeDependencies(k);
6756
- for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
6910
+ this._removeKeyDependencies(k);
6757
6911
  }
6758
6912
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6759
6913
  try {
6760
6914
  const client = await this.getRedis();
6761
6915
  if (isPattern) {
6762
6916
  const keys = await this._scanKeys(client, k);
6763
- if (keys.length > 0) await client.del(...keys);
6917
+ await this._deleteRedisKeys(client, keys);
6764
6918
  } else {
6765
6919
  if (this.opts.autoPipeline && this.pipeliner) {
6766
6920
  await this.pipeliner.del(k);
@@ -6822,6 +6976,15 @@ var CacheService = class _CacheService {
6822
6976
  entry.value++;
6823
6977
  return entry.value;
6824
6978
  }
6979
+ if (this._l1Counters.size >= 5e4 && !this._l1Counters.has(k)) {
6980
+ for (const [ck, cv] of this._l1Counters) {
6981
+ if (cv.expiresAt <= now) this._l1Counters.delete(ck);
6982
+ }
6983
+ if (this._l1Counters.size >= 5e4) {
6984
+ const oldest = this._l1Counters.keys().next().value;
6985
+ if (oldest !== void 0) this._l1Counters.delete(oldest);
6986
+ }
6987
+ }
6825
6988
  this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
6826
6989
  return 1;
6827
6990
  }
@@ -6868,6 +7031,7 @@ var CacheService = class _CacheService {
6868
7031
  }
6869
7032
  this._addPatternTombstone(pfx);
6870
7033
  this.l1.deletePattern(k);
7034
+ this._removePrefixFromIndices(pfx);
6871
7035
  } else {
6872
7036
  this._globalEpoch++;
6873
7037
  this.inflight.clear();
@@ -6876,7 +7040,10 @@ var CacheService = class _CacheService {
6876
7040
  if (!this._diskDisabled) this.disk.clear();
6877
7041
  this._l1Counters.clear();
6878
7042
  this.tagIndex.clear();
7043
+ this.keyTags.clear();
6879
7044
  this.tagVersions.clear();
7045
+ this.dependencyIndex.clear();
7046
+ this.keyDependencies.clear();
6880
7047
  this._pendingDiskDeletes.clear();
6881
7048
  this._keyMutationEpochs.clear();
6882
7049
  }
@@ -6885,7 +7052,7 @@ var CacheService = class _CacheService {
6885
7052
  const client = await this.getRedis();
6886
7053
  const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
6887
7054
  const keys = await this._scanKeys(client, pattern);
6888
- if (keys.length > 0) await client.del(...keys);
7055
+ await this._deleteRedisKeys(client, keys);
6889
7056
  } catch (err) {
6890
7057
  this.logger.debug("clear: Redis unavailable", { error: err.message });
6891
7058
  }
@@ -7028,6 +7195,10 @@ var CacheService = class _CacheService {
7028
7195
  this._assertActive("touch");
7029
7196
  const k = this.nk(cacheKey);
7030
7197
  const hit = this.l1.touch(k, newTtlSeconds * 1e3);
7198
+ if (hit) {
7199
+ const kt = this.keyTags.get(k);
7200
+ if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1e3;
7201
+ }
7031
7202
  if (hit && !this._redisDisabled) {
7032
7203
  try {
7033
7204
  const client = await this.getRedis();
@@ -7055,6 +7226,10 @@ var CacheService = class _CacheService {
7055
7226
  if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
7056
7227
  return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
7057
7228
  }
7229
+ _prepareReadValue(val) {
7230
+ if (this.opts.frozen) deepFreeze(val);
7231
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
7232
+ }
7058
7233
  /**
7059
7234
  * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
7060
7235
  * Returns the cached value if found and valid, or `null` if absent / expired.
@@ -7068,11 +7243,13 @@ var CacheService = class _CacheService {
7068
7243
  const k = this.nk(cacheKey);
7069
7244
  const l1Hit = this.l1.get(k);
7070
7245
  if (l1Hit !== null) {
7071
- this.counters.gets++;
7072
- this.counters.l1Hits++;
7073
- const val = l1Hit.value;
7074
- if (this.opts.frozen) deepFreeze(val);
7075
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
7246
+ if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
7247
+ this._deleteIfStale(k, l1Hit.setAt ?? 0);
7248
+ } else {
7249
+ this.counters.gets++;
7250
+ this.counters.l1Hits++;
7251
+ return this._prepareReadValue(l1Hit.value);
7252
+ }
7076
7253
  }
7077
7254
  if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
7078
7255
  if (this._isTombstonedByPattern(k)) {
@@ -7087,18 +7264,20 @@ var CacheService = class _CacheService {
7087
7264
  this.watchdog.recordDisk(diskElapsed);
7088
7265
  this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
7089
7266
  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;
7267
+ if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
7268
+ this.disk.delete(k);
7269
+ } else {
7270
+ const promoted = this.l1.importEntries(
7271
+ [{ key: k, entry: diskHit }],
7272
+ this.opts.forbiddenSnapshotPrefixes
7273
+ );
7274
+ if (promoted > 0) {
7275
+ const l1Check = this.l1.get(k);
7276
+ if (l1Check !== null) {
7277
+ this.counters.gets++;
7278
+ this.counters.diskHits++;
7279
+ return this._prepareReadValue(l1Check.value);
7280
+ }
7102
7281
  }
7103
7282
  }
7104
7283
  }
@@ -7108,17 +7287,16 @@ var CacheService = class _CacheService {
7108
7287
  try {
7109
7288
  const client = await this.getRedis();
7110
7289
  const redisStart = performance.now();
7111
- const raw = await client.get(k);
7290
+ const redisHit = await this._readRedisEntry(client, k);
7112
7291
  const redisElapsed = performance.now() - redisStart;
7113
7292
  this.watchdog.recordRedis(redisElapsed);
7114
- if (raw !== null) {
7115
- const parsed = await this._decryptAndDeserialize(raw);
7116
- this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
7293
+ this.cb.onSuccess();
7294
+ if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
7295
+ const parsed = redisHit.value;
7296
+ this.l1.set(k, parsed, 6e4, inferPriority(cacheKey), void 0, void 0, redisHit.tagVersions);
7117
7297
  this.counters.gets++;
7118
7298
  this.counters.l2Hits++;
7119
- this.cb.onSuccess();
7120
- if (this.opts.frozen) deepFreeze(parsed);
7121
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
7299
+ return this._prepareReadValue(parsed);
7122
7300
  }
7123
7301
  } catch (err) {
7124
7302
  this.cb.onFailure();
@@ -7146,12 +7324,20 @@ var CacheService = class _CacheService {
7146
7324
  const result = Array.from({ length: keys.length });
7147
7325
  const missIndexes = [];
7148
7326
  const missKeys = [];
7327
+ const now = Date.now();
7149
7328
  for (let i = 0; i < keys.length; i++) {
7150
7329
  const k = this.nk(keys[i]);
7151
7330
  const entry = this.l1.getEntry(k);
7152
- if (entry && entry.expiresAt > Date.now()) {
7153
- result[i] = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
7154
- this.counters.l1Hits++;
7331
+ if (entry && entry.expiresAt > now) {
7332
+ if (await this._isGenerationalEntryStale(entry.tagVersions)) {
7333
+ this._deleteIfStale(k, entry.setAt ?? 0);
7334
+ missIndexes.push(i);
7335
+ missKeys.push(keys[i]);
7336
+ } else {
7337
+ const val = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
7338
+ result[i] = this._prepareReadValue(val);
7339
+ this.counters.l1Hits++;
7340
+ }
7155
7341
  } else {
7156
7342
  missIndexes.push(i);
7157
7343
  missKeys.push(keys[i]);
@@ -7172,23 +7358,57 @@ var CacheService = class _CacheService {
7172
7358
  const client = await this.getRedis();
7173
7359
  const nsKeys = missKeys.map((k) => this.nk(k));
7174
7360
  const pipeline = client.multi();
7175
- for (const nk of nsKeys) pipeline.get(nk);
7361
+ const useHashPipeline = this.opts.tagStrategy === "generational" && typeof pipeline.hgetall === "function";
7362
+ for (const nk of nsKeys) {
7363
+ if (useHashPipeline) {
7364
+ pipeline.hgetall(nk);
7365
+ } else {
7366
+ pipeline.get(nk);
7367
+ }
7368
+ }
7176
7369
  const redisStart = performance.now();
7177
7370
  const raws = await pipeline.exec();
7178
7371
  const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
7179
7372
  this.watchdog.recordRedis(redisElapsed);
7180
7373
  this.cb.onSuccess();
7181
7374
  for (let j = 0; j < missKeys.length; j++) {
7182
- const raw = raws[j] ? raws[j][1] : null;
7375
+ const tuple = raws[j];
7376
+ const err = tuple ? tuple[0] : null;
7377
+ const rawVal = tuple ? tuple[1] : null;
7183
7378
  const idx = missIndexes[j];
7184
- if (raw) {
7185
- const parsed = await this._decryptAndDeserialize(raw);
7186
- const k = nsKeys[j];
7379
+ const k = nsKeys[j];
7380
+ let parsed;
7381
+ let tagVersions;
7382
+ let hit = false;
7383
+ if (useHashPipeline) {
7384
+ if (err && err.message?.includes("WRONGTYPE")) {
7385
+ const fallbackRaw = await client.get(k);
7386
+ if (fallbackRaw) {
7387
+ parsed = await this._decryptAndDeserialize(fallbackRaw);
7388
+ hit = true;
7389
+ }
7390
+ } else if (!err && typeof rawVal === "string") {
7391
+ parsed = await this._decryptAndDeserialize(rawVal);
7392
+ hit = true;
7393
+ } else if (!err && rawVal && typeof rawVal === "object" && rawVal.d) {
7394
+ const hashHit = await this._parseGenerationalRedisHash(k, rawVal);
7395
+ if (hashHit && !hashHit.stale && hashHit.value !== void 0) {
7396
+ parsed = hashHit.value;
7397
+ tagVersions = hashHit.tagVersions;
7398
+ hit = true;
7399
+ }
7400
+ }
7401
+ } else if (!err && rawVal) {
7402
+ parsed = await this._decryptAndDeserialize(rawVal);
7403
+ hit = true;
7404
+ }
7405
+ if (hit && parsed !== void 0) {
7187
7406
  const p = priority ?? inferPriority(missKeys[j]);
7188
- this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
7407
+ const ttlVal = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
7408
+ this.l1.set(k, parsed, this._jitterTtl(ttlVal * 1e3), p, void 0, void 0, tagVersions);
7189
7409
  this.counters.l2Hits++;
7190
7410
  l2HitCount++;
7191
- result[idx] = parsed;
7411
+ result[idx] = this._prepareReadValue(parsed);
7192
7412
  missIndexes[j] = -1;
7193
7413
  missKeys[j] = "";
7194
7414
  }
@@ -7222,6 +7442,10 @@ var CacheService = class _CacheService {
7222
7442
  this.watchdog.recordDisk(diskElapsed);
7223
7443
  this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
7224
7444
  if (diskHit !== null) {
7445
+ if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
7446
+ this.disk.delete(k);
7447
+ continue;
7448
+ }
7225
7449
  const promoted = this.l1.importEntries(
7226
7450
  [{ key: k, entry: diskHit }],
7227
7451
  this.opts.forbiddenSnapshotPrefixes
@@ -7230,7 +7454,7 @@ var CacheService = class _CacheService {
7230
7454
  const l1Check = this.l1.get(k);
7231
7455
  if (l1Check !== null) {
7232
7456
  this.counters.diskHits++;
7233
- result[missIndexes[j]] = l1Check.value;
7457
+ result[missIndexes[j]] = this._prepareReadValue(l1Check.value);
7234
7458
  missIndexes.splice(j, 1);
7235
7459
  missKeys.splice(j, 1);
7236
7460
  }
@@ -7455,6 +7679,136 @@ var CacheService = class _CacheService {
7455
7679
  }
7456
7680
  return matched;
7457
7681
  }
7682
+ async _publishTagInvalidation(op, key, tagVersion) {
7683
+ if (this.opts.awaitInvalidationBackplane) {
7684
+ await this.publishInvalidation(op, key, tagVersion, false, true);
7685
+ } else {
7686
+ void this.publishInvalidation(op, key, tagVersion, false, true);
7687
+ }
7688
+ }
7689
+ _removeTagMembersLocal(keys) {
7690
+ const keyList = Array.isArray(keys) ? keys : Array.from(keys);
7691
+ for (const k of keyList) {
7692
+ this.l1.delete(k);
7693
+ this._bumpKeyMutation(k);
7694
+ this._removeKeyTags(k);
7695
+ this._removeKeyDependencies(k);
7696
+ this._pendingDiskDeletes.add(k);
7697
+ setImmediate(() => {
7698
+ try {
7699
+ if (!this._diskDisabled) this.disk.delete(k);
7700
+ } finally {
7701
+ this._pendingDiskDeletes.delete(k);
7702
+ }
7703
+ });
7704
+ }
7705
+ }
7706
+ /**
7707
+ * Executes invalidation for a single already-resolved concrete tag without
7708
+ * wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
7709
+ */
7710
+ async _invalidateConcreteTag(tag) {
7711
+ if (this.opts.tagStrategy === "generational") {
7712
+ let newVer = 1;
7713
+ if (!this._redisDisabled) {
7714
+ try {
7715
+ const client = await this.getRedis();
7716
+ newVer = await client.incr(this.nk(`tag_ver:${tag}`));
7717
+ } catch (err) {
7718
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7719
+ const current = this.tagVersions.get(tag)?.version ?? 0;
7720
+ newVer = current + 1;
7721
+ }
7722
+ } else {
7723
+ const current = this.tagVersions.get(tag)?.version ?? 0;
7724
+ newVer = current + 1;
7725
+ }
7726
+ this._setLocalTagVersion(tag, newVer, performance.now());
7727
+ await this._publishTagInvalidation("tag_incr", tag, newVer);
7728
+ return;
7729
+ }
7730
+ const tagKey = this.nk(`_tag_:${tag}`);
7731
+ const members = Array.from(this.tagIndex.get(tagKey) ?? []);
7732
+ this.tagIndex.delete(tagKey);
7733
+ this._removeTagMembersLocal(members);
7734
+ if (!this._redisDisabled) {
7735
+ try {
7736
+ const client = await this.getRedis();
7737
+ const redisMembers = await client.smembers(tagKey);
7738
+ const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers, tagKey])];
7739
+ await this._deleteRedisKeys(client, toDelete);
7740
+ } catch (err) {
7741
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7742
+ }
7743
+ }
7744
+ }
7745
+ /**
7746
+ * Executes invalidation for an array of already-resolved concrete tags
7747
+ * without re-entering wildcard/cascade resolution or invalidateTag().
7748
+ */
7749
+ async _invalidateConcreteTags(tags) {
7750
+ if (tags.length === 0) return;
7751
+ if (tags.length === 1) {
7752
+ await this._invalidateConcreteTag(tags[0]);
7753
+ return;
7754
+ }
7755
+ if (this.opts.tagStrategy === "generational") {
7756
+ const now = performance.now();
7757
+ if (!this._redisDisabled) {
7758
+ try {
7759
+ const client = await this.getRedis();
7760
+ const pl = client.pipeline();
7761
+ for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
7762
+ const results = await pl.exec();
7763
+ for (let i = 0; i < tags.length; i++) {
7764
+ const [err, newVer] = results[i] ?? [null, null];
7765
+ const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
7766
+ this._setLocalTagVersion(tags[i], ver, now);
7767
+ await this._publishTagInvalidation("tag_incr", tags[i], ver);
7768
+ }
7769
+ return;
7770
+ } catch (err) {
7771
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7772
+ }
7773
+ }
7774
+ for (const tag of tags) {
7775
+ const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
7776
+ this._setLocalTagVersion(tag, ver, now);
7777
+ await this._publishTagInvalidation("tag_incr", tag, ver);
7778
+ }
7779
+ return;
7780
+ }
7781
+ const tagKeys = [];
7782
+ const allMembers = /* @__PURE__ */ new Set();
7783
+ for (const tag of tags) {
7784
+ const tagKey = this.nk(`_tag_:${tag}`);
7785
+ tagKeys.push(tagKey);
7786
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
7787
+ for (const k of members) allMembers.add(k);
7788
+ this.tagIndex.delete(tagKey);
7789
+ }
7790
+ this._removeTagMembersLocal(allMembers);
7791
+ if (!this._redisDisabled) {
7792
+ try {
7793
+ const client = await this.getRedis();
7794
+ const pl = client.pipeline();
7795
+ for (const tagKey of tagKeys) pl.smembers(tagKey);
7796
+ const smResults = await pl.exec();
7797
+ const toDelete = [...allMembers];
7798
+ for (const [err, redisMembers] of smResults) {
7799
+ if (!err && redisMembers) {
7800
+ for (const k of redisMembers) {
7801
+ if (!allMembers.has(k)) toDelete.push(k);
7802
+ }
7803
+ }
7804
+ }
7805
+ const keysToRemove = [...toDelete, ...tagKeys];
7806
+ await this._deleteRedisKeys(client, keysToRemove);
7807
+ } catch (err) {
7808
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7809
+ }
7810
+ }
7811
+ }
7458
7812
  /**
7459
7813
  * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
7460
7814
  * Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
@@ -7490,68 +7844,13 @@ var CacheService = class _CacheService {
7490
7844
  const delim = this.opts.tagHierarchyDelimiter;
7491
7845
  const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
7492
7846
  if (matchedTags.size > 0) {
7493
- await this.invalidateTags(Array.from(matchedTags));
7847
+ await this._invalidateConcreteTags(Array.from(matchedTags));
7494
7848
  }
7495
7849
  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
- }
7850
+ await this._publishTagInvalidation(op, broadcastPattern);
7501
7851
  return;
7502
7852
  }
7503
- if (this.opts.tagStrategy === "generational") {
7504
- let newVer = 1;
7505
- if (!this._redisDisabled) {
7506
- try {
7507
- const client = await this.getRedis();
7508
- newVer = await client.incr(this.nk(`tag_ver:${tag}`));
7509
- } catch (err) {
7510
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7511
- const current = this.tagVersions.get(tag)?.version ?? 0;
7512
- newVer = current + 1;
7513
- }
7514
- } else {
7515
- const current = this.tagVersions.get(tag)?.version ?? 0;
7516
- newVer = current + 1;
7517
- }
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
- }
7524
- return;
7525
- }
7526
- const tagKey = this.nk(`_tag_:${tag}`);
7527
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
7528
- for (const k of members) {
7529
- this.l1.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
- });
7539
- }
7540
- this.tagIndex.delete(tagKey);
7541
- if (!this._redisDisabled) {
7542
- try {
7543
- const client = await this.getRedis();
7544
- const redisMembers = await client.smembers(tagKey);
7545
- const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
7546
- if (toDelete.length > 0) {
7547
- await client.del(...toDelete, tagKey);
7548
- } else {
7549
- await client.del(tagKey);
7550
- }
7551
- } catch (err) {
7552
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7553
- }
7554
- }
7853
+ await this._invalidateConcreteTag(tag);
7555
7854
  } catch (err) {
7556
7855
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
7557
7856
  span.recordException?.(err);
@@ -7578,96 +7877,28 @@ var CacheService = class _CacheService {
7578
7877
  const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
7579
7878
  if (hasWildcards || shouldCascade) {
7580
7879
  const allResolvedTags = /* @__PURE__ */ new Set();
7880
+ const broadcastPatterns = /* @__PURE__ */ new Set();
7881
+ const delim = this.opts.tagHierarchyDelimiter;
7581
7882
  for (const t of tags) {
7582
- if (isWildcardTag(t) || shouldCascade) {
7883
+ const tIsPattern = isWildcardTag(t);
7884
+ if (tIsPattern || shouldCascade) {
7885
+ broadcastPatterns.add(tIsPattern ? t : `${t}${delim}*`);
7583
7886
  const resolved = await this._resolveMatchingTags(t, shouldCascade);
7584
7887
  for (const rt of resolved) allResolvedTags.add(rt);
7585
7888
  } else {
7586
7889
  allResolvedTags.add(t);
7587
7890
  }
7588
7891
  }
7589
- if (allResolvedTags.size === 0) return;
7590
- tags = Array.from(allResolvedTags);
7591
- }
7592
- if (tags.length === 1) {
7593
- await this.invalidateTag(tags[0], opts);
7594
- return;
7595
- }
7596
- if (this.opts.tagStrategy === "generational") {
7597
- const now = performance.now();
7598
- if (!this._redisDisabled) {
7599
- try {
7600
- const client = await this.getRedis();
7601
- const pl = client.pipeline();
7602
- for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
7603
- const results = await pl.exec();
7604
- for (let i = 0; i < tags.length; i++) {
7605
- const [err, newVer] = results[i] ?? [null, null];
7606
- const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
7607
- this._setLocalTagVersion(tags[i], ver, now);
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
- }
7613
- }
7614
- return;
7615
- } catch (err) {
7616
- this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7617
- }
7892
+ if (allResolvedTags.size > 0) {
7893
+ await this._invalidateConcreteTags(Array.from(allResolvedTags));
7618
7894
  }
7619
- for (const tag of tags) {
7620
- const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
7621
- this._setLocalTagVersion(tag, ver, now);
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
- }
7895
+ const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
7896
+ for (const pattern of broadcastPatterns) {
7897
+ await this._publishTagInvalidation(op, pattern);
7627
7898
  }
7628
7899
  return;
7629
7900
  }
7630
- const tagKeys = [];
7631
- const allMembers = /* @__PURE__ */ new Set();
7632
- for (const tag of tags) {
7633
- const tagKey = this.nk(`_tag_:${tag}`);
7634
- tagKeys.push(tagKey);
7635
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
7636
- for (const k of members) allMembers.add(k);
7637
- this.tagIndex.delete(tagKey);
7638
- }
7639
- for (const k of allMembers) {
7640
- this.l1.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
- });
7650
- }
7651
- if (!this._redisDisabled) {
7652
- try {
7653
- const client = await this.getRedis();
7654
- const pl = client.pipeline();
7655
- for (const tagKey of tagKeys) pl.smembers(tagKey);
7656
- const smResults = await pl.exec();
7657
- const toDelete = [...allMembers];
7658
- for (const [err, redisMembers] of smResults) {
7659
- if (!err && redisMembers) {
7660
- for (const k of redisMembers) {
7661
- if (!allMembers.has(k)) toDelete.push(k);
7662
- }
7663
- }
7664
- }
7665
- const keysToRemove = [...toDelete, ...tagKeys];
7666
- if (keysToRemove.length > 0) await client.del(...keysToRemove);
7667
- } catch (err) {
7668
- this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7669
- }
7670
- }
7901
+ await this._invalidateConcreteTags(Array.from(new Set(tags)));
7671
7902
  }
7672
7903
  /**
7673
7904
  * Get the current generational tag version for a tag (synced with Redis when due).
@@ -8234,6 +8465,13 @@ var CacheService = class _CacheService {
8234
8465
  this._destroyed = true;
8235
8466
  this._pendingDiskDeletes.clear();
8236
8467
  this._keyMutationEpochs.clear();
8468
+ this.inflight.clear();
8469
+ this.revalidating.clear();
8470
+ this._l1Counters.clear();
8471
+ this.tagIndex.clear();
8472
+ this.keyTags.clear();
8473
+ this.dependencyIndex.clear();
8474
+ this.keyDependencies.clear();
8237
8475
  const g = globalThis;
8238
8476
  const key = _CacheService.globalKey(this.opts);
8239
8477
  if (g[key] === this) {
@@ -8708,6 +8946,14 @@ var NodeRedisPipelineAdapter = class {
8708
8946
  }
8709
8947
  return this;
8710
8948
  }
8949
+ hgetall(key) {
8950
+ if (typeof this.multiInstance.hGetAll === "function") {
8951
+ this.multiInstance.hGetAll(key);
8952
+ } else {
8953
+ this.multiInstance.hgetall(key);
8954
+ }
8955
+ return this;
8956
+ }
8711
8957
  async exec() {
8712
8958
  const raw = await this.multiInstance.exec();
8713
8959
  if (!raw) return null;
@@ -8849,6 +9095,15 @@ var NodeRedisAdapter = class _NodeRedisAdapter {
8849
9095
  }
8850
9096
  return void 0;
8851
9097
  }
9098
+ async hgetall(key) {
9099
+ if (typeof this.client.hGetAll === "function") {
9100
+ return await this.client.hGetAll(key) ?? {};
9101
+ }
9102
+ if (typeof this.client.hgetall === "function") {
9103
+ return await this.client.hgetall(key) ?? {};
9104
+ }
9105
+ return {};
9106
+ }
8852
9107
  async publish(channel, message) {
8853
9108
  return await this.client.publish(channel, message);
8854
9109
  }