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
@@ -1130,7 +1130,7 @@ var SmartMemoryCache = class {
1130
1130
  };
1131
1131
  return hit;
1132
1132
  }
1133
- set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
1133
+ set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions, setAt) {
1134
1134
  const packed = this.codec.encode(data);
1135
1135
  const size = packed.byteLength;
1136
1136
  this.compressions++;
@@ -1167,7 +1167,7 @@ var SmartMemoryCache = class {
1167
1167
  priority,
1168
1168
  ttlMs,
1169
1169
  delta,
1170
- setAt: now2,
1170
+ setAt: setAt ?? now2,
1171
1171
  tagVersions
1172
1172
  });
1173
1173
  }
@@ -1195,7 +1195,7 @@ var SmartMemoryCache = class {
1195
1195
  }
1196
1196
  const now = Date.now();
1197
1197
  const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
1198
- 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 });
1198
+ 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 });
1199
1199
  if (!existingEntry) this.bloom.add(key);
1200
1200
  this.maybeRebuildBloom();
1201
1201
  this.totalSize += size;
@@ -3731,6 +3731,8 @@ var CacheService = class _CacheService {
3731
3731
  _l1Counters = /* @__PURE__ */ new Map();
3732
3732
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
3733
3733
  tagIndex = /* @__PURE__ */ new Map();
3734
+ /** Reverse index of namespaced key → { tags, expiresAt } for bounded cleanup on eviction/delete */
3735
+ keyTags = /* @__PURE__ */ new Map();
3734
3736
  /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
3735
3737
  tagVersions = /* @__PURE__ */ new Map();
3736
3738
  /**
@@ -3738,6 +3740,9 @@ var CacheService = class _CacheService {
3738
3740
  * When an exact-key delete matches a registered pattern, all dependents are cascaded.
3739
3741
  */
3740
3742
  dependencyIndex = /* @__PURE__ */ new Map();
3743
+ /** Reverse index of namespaced dependent key → source glob patterns */
3744
+ keyDependencies = /* @__PURE__ */ new Map();
3745
+ _cgroupMemoryLimit;
3741
3746
  redis = null;
3742
3747
  redisConnecting = null;
3743
3748
  cb;
@@ -3807,6 +3812,84 @@ var CacheService = class _CacheService {
3807
3812
  _getKeyMutationEpoch(namespacedKey) {
3808
3813
  return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
3809
3814
  }
3815
+ _removeKeyTags(namespacedKey) {
3816
+ const entry = this.keyTags.get(namespacedKey);
3817
+ if (!entry) return;
3818
+ for (const tag of entry.tags) {
3819
+ const tagKey = this.nk(`_tag_:${tag}`);
3820
+ const members = this.tagIndex.get(tagKey);
3821
+ if (members) {
3822
+ members.delete(namespacedKey);
3823
+ if (members.size === 0) this.tagIndex.delete(tagKey);
3824
+ }
3825
+ }
3826
+ this.keyTags.delete(namespacedKey);
3827
+ }
3828
+ _removeKeyDependencies(namespacedKey) {
3829
+ const patterns = this.keyDependencies.get(namespacedKey);
3830
+ if (patterns) {
3831
+ for (const pat of patterns) {
3832
+ const deps = this.dependencyIndex.get(pat);
3833
+ if (deps) {
3834
+ deps.delete(namespacedKey);
3835
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
3836
+ }
3837
+ }
3838
+ this.keyDependencies.delete(namespacedKey);
3839
+ } else if (this.dependencyIndex.size > 0) {
3840
+ for (const [pat, deps] of this.dependencyIndex) {
3841
+ deps.delete(namespacedKey);
3842
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
3843
+ }
3844
+ }
3845
+ }
3846
+ _handleL1Eviction(namespacedKey, reason) {
3847
+ const spilledToDisk = !this._diskDisabled && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
3848
+ if (!spilledToDisk) {
3849
+ this._removeKeyTags(namespacedKey);
3850
+ this._removeKeyDependencies(namespacedKey);
3851
+ }
3852
+ }
3853
+ _removePrefixFromIndices(prefix) {
3854
+ for (const k of Array.from(this.keyTags.keys())) {
3855
+ if (k.startsWith(prefix)) this._removeKeyTags(k);
3856
+ }
3857
+ for (const k of Array.from(this.keyDependencies.keys())) {
3858
+ if (k.startsWith(prefix)) this._removeKeyDependencies(k);
3859
+ }
3860
+ for (const k of Array.from(this._l1Counters.keys())) {
3861
+ if (k.startsWith(prefix)) this._l1Counters.delete(k);
3862
+ }
3863
+ }
3864
+ _sweepExpiredMetadata() {
3865
+ const now = Date.now();
3866
+ for (const [k, c] of this._l1Counters) {
3867
+ if (c.expiresAt <= now) this._l1Counters.delete(k);
3868
+ }
3869
+ for (const [k, meta] of this.keyTags) {
3870
+ if (meta.expiresAt <= now && !this.l1.has(k)) {
3871
+ this._removeKeyTags(k);
3872
+ this._removeKeyDependencies(k);
3873
+ }
3874
+ }
3875
+ }
3876
+ _runOomCheck() {
3877
+ const heap = v82.getHeapStatistics();
3878
+ const heapUsed = heap.used_heap_size / heap.heap_size_limit;
3879
+ const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? process.memoryUsage().rss / this._cgroupMemoryLimit : 0;
3880
+ const used = Math.max(heapUsed, cgroupUsed);
3881
+ if (used >= this.opts.oomHeapThreshold) {
3882
+ const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
3883
+ this.counters.oomEvictions++;
3884
+ this.counters.oomLastAt = Date.now();
3885
+ this.logger.warn("tricache OOM guard: emergency L1 eviction", {
3886
+ heapUsedPct: Math.round(heapUsed * 100),
3887
+ cgroupUsedPct: cgroupUsed > 0 ? Math.round(cgroupUsed * 100) : void 0,
3888
+ threshold: Math.round(this.opts.oomHeapThreshold * 100),
3889
+ evicted
3890
+ });
3891
+ }
3892
+ }
3810
3893
  _ipcServer;
3811
3894
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
3812
3895
  _subDisconnectedAt = null;
@@ -3853,6 +3936,7 @@ var CacheService = class _CacheService {
3853
3936
  constructor(options = {}) {
3854
3937
  const logger = options.logger ?? consoleLogger;
3855
3938
  this.logger = logger;
3939
+ this._cgroupMemoryLimit = readCgroupMemoryLimit();
3856
3940
  const ns = options.namespace?.trim() ?? "";
3857
3941
  const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
3858
3942
  this.enc = new CacheEncryption(
@@ -4036,7 +4120,10 @@ var CacheService = class _CacheService {
4036
4120
  void this.disk.save(key, entry);
4037
4121
  });
4038
4122
  },
4039
- onEviction: options.onEviction,
4123
+ onEviction: (key, reason) => {
4124
+ this._handleL1Eviction(key, reason);
4125
+ options.onEviction?.(key, reason);
4126
+ },
4040
4127
  logger
4041
4128
  });
4042
4129
  if (!this.snapshotLoaded) {
@@ -4074,6 +4161,7 @@ var CacheService = class _CacheService {
4074
4161
  }
4075
4162
  this.cleanupInterval = setInterval(() => {
4076
4163
  const cleaned = this.l1.cleanup();
4164
+ this._sweepExpiredMetadata();
4077
4165
  if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
4078
4166
  }, 5 * 60 * 1e3);
4079
4167
  if (this.cleanupInterval.unref) this.cleanupInterval.unref();
@@ -4086,18 +4174,7 @@ var CacheService = class _CacheService {
4086
4174
  }
4087
4175
  if (this.opts.oomProtection) {
4088
4176
  this.oomInterval = setInterval(() => {
4089
- const heap = v82.getHeapStatistics();
4090
- const used = heap.used_heap_size / heap.heap_size_limit;
4091
- if (used >= this.opts.oomHeapThreshold) {
4092
- const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
4093
- this.counters.oomEvictions++;
4094
- this.counters.oomLastAt = Date.now();
4095
- this.logger.warn("tricache OOM guard: emergency L1 eviction", {
4096
- heapUsedPct: Math.round(used * 100),
4097
- threshold: Math.round(this.opts.oomHeapThreshold * 100),
4098
- evicted
4099
- });
4100
- }
4177
+ this._runOomCheck();
4101
4178
  }, this.opts.oomCheckIntervalMs);
4102
4179
  if (this.oomInterval.unref) this.oomInterval.unref();
4103
4180
  }
@@ -4572,7 +4649,7 @@ var CacheService = class _CacheService {
4572
4649
  else if (f === "src") src = v;
4573
4650
  else if (f === "tagVersion") tagVersionRaw = v;
4574
4651
  }
4575
- const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
4652
+ const validOp = op === "del" || op === "del-glob" || op === "tag_incr" || op === "tag_pattern_incr" || op === "tag_pattern_del";
4576
4653
  if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
4577
4654
  this.logger.warn("Backplane: rejected invalid stream entry", {
4578
4655
  op: String(op).slice(0, 40),
@@ -4834,6 +4911,72 @@ var CacheService = class _CacheService {
4834
4911
  }
4835
4912
  this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
4836
4913
  }
4914
+ async _isGenerationalEntryStale(tagVersions) {
4915
+ if (this.opts.tagStrategy !== "generational" || !tagVersions) return false;
4916
+ const tags = Object.keys(tagVersions);
4917
+ if (tags.length === 0) return false;
4918
+ const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
4919
+ for (let i = 0; i < tags.length; i++) {
4920
+ if (currentVers[i] > tagVersions[tags[i]]) return true;
4921
+ }
4922
+ return false;
4923
+ }
4924
+ async _deleteRedisKeys(client, keys) {
4925
+ if (keys.length === 0) return;
4926
+ const CHUNK_SIZE = 1e3;
4927
+ if (client instanceof RedisCluster) {
4928
+ for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
4929
+ const chunk = keys.slice(i, i + CHUNK_SIZE);
4930
+ const pl = client.pipeline();
4931
+ for (const k of chunk) pl.del(k);
4932
+ await pl.exec();
4933
+ }
4934
+ return;
4935
+ }
4936
+ for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
4937
+ const chunk = keys.slice(i, i + CHUNK_SIZE);
4938
+ await client.del(...chunk);
4939
+ }
4940
+ }
4941
+ async _parseGenerationalRedisHash(k, hashData) {
4942
+ if (!hashData || !hashData.d) return null;
4943
+ let storedTagVersions = {};
4944
+ if (hashData.tv) {
4945
+ try {
4946
+ storedTagVersions = JSON.parse(hashData.tv);
4947
+ } catch {
4948
+ }
4949
+ }
4950
+ if (await this._isGenerationalEntryStale(storedTagVersions)) {
4951
+ const setAtMs = parseInt(hashData.t, 10) || 0;
4952
+ this._deleteIfStale(k, setAtMs);
4953
+ return { stale: true };
4954
+ }
4955
+ const value = await this._decryptAndDeserialize(hashData.d);
4956
+ return { value, tagVersions: storedTagVersions, stale: false };
4957
+ }
4958
+ async _readRedisEntry(client, k, allowAutoPipeline = false) {
4959
+ if (this.opts.tagStrategy === "generational" && typeof client.hgetall === "function") {
4960
+ try {
4961
+ const hashData = await client.hgetall(k);
4962
+ if (typeof hashData === "string") {
4963
+ const value2 = await this._decryptAndDeserialize(hashData);
4964
+ return { value: value2, stale: false };
4965
+ }
4966
+ if (hashData && hashData.d) {
4967
+ return await this._parseGenerationalRedisHash(k, hashData);
4968
+ }
4969
+ return null;
4970
+ } catch (err) {
4971
+ const msg = err instanceof Error ? err.message : String(err);
4972
+ if (!msg.includes("WRONGTYPE")) throw err;
4973
+ }
4974
+ }
4975
+ const raw = allowAutoPipeline && this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
4976
+ if (raw == null) return null;
4977
+ const value = await this._decryptAndDeserialize(raw);
4978
+ return { value, stale: false };
4979
+ }
4837
4980
  async _getTagVersion(tag) {
4838
4981
  const now = performance.now();
4839
4982
  const local = this.tagVersions.get(tag);
@@ -4971,8 +5114,8 @@ var CacheService = class _CacheService {
4971
5114
  return client;
4972
5115
  }
4973
5116
  this.redisConnecting = (async () => {
5117
+ let client = null;
4974
5118
  try {
4975
- let client;
4976
5119
  if (this.opts.redisClusterNodes?.length) {
4977
5120
  client = new RedisCluster(this.opts.redisClusterNodes, {
4978
5121
  redisOptions: {
@@ -5035,14 +5178,45 @@ var CacheService = class _CacheService {
5035
5178
  });
5036
5179
  client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
5037
5180
  }
5181
+ const pendingClient = client;
5038
5182
  await new Promise((resolve, reject) => {
5039
- client.once("ready", resolve);
5040
- client.once("error", (e) => {
5183
+ let settled = false;
5184
+ const cleanupListeners = () => {
5185
+ pendingClient.removeListener?.("ready", onReady);
5186
+ pendingClient.removeListener?.("error", onError);
5187
+ };
5188
+ const onReady = () => {
5189
+ if (settled) return;
5190
+ settled = true;
5191
+ clearTimeout(timer);
5192
+ cleanupListeners();
5193
+ resolve();
5194
+ };
5195
+ const onError = (e) => {
5196
+ if (settled) return;
5197
+ settled = true;
5198
+ clearTimeout(timer);
5199
+ cleanupListeners();
5041
5200
  this._checkAndLogResp3Hint(e);
5042
5201
  reject(e);
5043
- });
5044
- setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
5202
+ };
5203
+ const timer = setTimeout(() => {
5204
+ if (settled) return;
5205
+ settled = true;
5206
+ cleanupListeners();
5207
+ reject(new Error("Redis connection timeout"));
5208
+ }, 15e3);
5209
+ if (timer.unref) timer.unref();
5210
+ pendingClient.once("ready", onReady);
5211
+ pendingClient.once("error", onError);
5045
5212
  });
5213
+ if (this._destroyed) {
5214
+ try {
5215
+ client.disconnect();
5216
+ } catch {
5217
+ }
5218
+ this._assertActive("getRedis");
5219
+ }
5046
5220
  this.cb.onSuccess();
5047
5221
  this.redis = client;
5048
5222
  this.pipeliner = new AutoPipeliner(client, {
@@ -5052,6 +5226,10 @@ var CacheService = class _CacheService {
5052
5226
  this.redisConnecting = null;
5053
5227
  return client;
5054
5228
  } catch (err) {
5229
+ try {
5230
+ client?.disconnect();
5231
+ } catch {
5232
+ }
5055
5233
  this.cb.onFailure();
5056
5234
  this.redisConnecting = null;
5057
5235
  this._checkAndLogResp3Hint(err);
@@ -5295,17 +5473,7 @@ var CacheService = class _CacheService {
5295
5473
  const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
5296
5474
  const l1Hit = this.l1.get(k);
5297
5475
  if (l1Hit !== null) {
5298
- let isGenerationalStale = false;
5299
- if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
5300
- const tags = Object.keys(l1Hit.tagVersions);
5301
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5302
- for (let i = 0; i < tags.length; i++) {
5303
- if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
5304
- isGenerationalStale = true;
5305
- break;
5306
- }
5307
- }
5308
- }
5476
+ const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
5309
5477
  if (isGenerationalStale) {
5310
5478
  this._deleteIfStale(k, l1Hit.setAt ?? 0);
5311
5479
  } else {
@@ -5391,17 +5559,7 @@ var CacheService = class _CacheService {
5391
5559
  this.watchdog.recordDisk(diskElapsed);
5392
5560
  this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
5393
5561
  if (diskHit !== null) {
5394
- let isDiskStale = false;
5395
- if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
5396
- const tags = Object.keys(diskHit.tagVersions);
5397
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5398
- for (let i = 0; i < tags.length; i++) {
5399
- if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
5400
- isDiskStale = true;
5401
- break;
5402
- }
5403
- }
5404
- }
5562
+ const isDiskStale = await this._isGenerationalEntryStale(diskHit.tagVersions);
5405
5563
  if (isDiskStale) {
5406
5564
  this.disk.delete(k);
5407
5565
  } else {
@@ -5429,57 +5587,27 @@ var CacheService = class _CacheService {
5429
5587
  try {
5430
5588
  const client = await this.getRedis();
5431
5589
  const redisStart = performance.now();
5432
- if (this.opts.tagStrategy === "generational") {
5433
- const hashData = await client.hgetall(k);
5434
- const redisElapsed = performance.now() - redisStart;
5435
- this.watchdog.recordRedis(redisElapsed);
5436
- this.cb.onSuccess();
5437
- if (hashData && hashData.d) {
5438
- let isStale = false;
5439
- let storedTagVersions = {};
5440
- if (hashData.tv) {
5441
- try {
5442
- storedTagVersions = JSON.parse(hashData.tv);
5443
- } catch {
5444
- }
5445
- }
5446
- const tags = Object.keys(storedTagVersions);
5447
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5448
- for (let i = 0; i < tags.length; i++) {
5449
- if (currentVers[i] > storedTagVersions[tags[i]]) {
5450
- isStale = true;
5451
- break;
5452
- }
5453
- }
5454
- if (isStale) {
5455
- const setAtMs = parseInt(hashData.t, 10) || 0;
5456
- this._deleteIfStale(k, setAtMs);
5457
- } else {
5458
- const parsed = await this._decryptAndDeserialize(hashData.d);
5459
- this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
5460
- this.counters.l2Hits++;
5461
- this.opts.onHit?.(cacheKey, "l2");
5462
- this.logger.debug("L2 hit (Redis hash)", { cacheKey });
5463
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5464
- if (this.opts.frozen) deepFreeze(parsed);
5465
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
5466
- }
5467
- }
5468
- } else {
5469
- const raw = this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
5470
- const redisElapsed = performance.now() - redisStart;
5471
- this.watchdog.recordRedis(redisElapsed);
5472
- this.cb.onSuccess();
5473
- if (raw) {
5474
- const parsed = await this._decryptAndDeserialize(raw);
5475
- this.l1.set(k, parsed, ttlMs, priority);
5476
- this.counters.l2Hits++;
5477
- this.opts.onHit?.(cacheKey, "l2");
5478
- this.logger.debug("L2 hit (Redis)", { cacheKey });
5479
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5480
- if (this.opts.frozen) deepFreeze(parsed);
5481
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
5590
+ const redisHit = await this._readRedisEntry(client, k, true);
5591
+ const redisElapsed = performance.now() - redisStart;
5592
+ this.watchdog.recordRedis(redisElapsed);
5593
+ this.cb.onSuccess();
5594
+ if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
5595
+ const parsed = redisHit.value;
5596
+ if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
5597
+ this.logger.debug("Aborting L2 promotion \u2014 key was mutated or deleted during Redis read", { cacheKey });
5598
+ span.setAttribute("cache.aborted_mutation_race", true);
5599
+ const current = this.l1.get(k);
5600
+ const liveVal = current && !current.isStale && current.value !== void 0 ? current.value : parsed;
5601
+ if (this.opts.frozen) deepFreeze(liveVal);
5602
+ return this.opts.cloneStrategy === "structuredClone" && liveVal != null && typeof liveVal === "object" ? structuredClone(liveVal) : liveVal;
5482
5603
  }
5604
+ this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, redisHit.tagVersions);
5605
+ this.counters.l2Hits++;
5606
+ this.opts.onHit?.(cacheKey, "l2");
5607
+ this.logger.debug(redisHit.tagVersions ? "L2 hit (Redis hash)" : "L2 hit (Redis)", { cacheKey });
5608
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5609
+ if (this.opts.frozen) deepFreeze(parsed);
5610
+ return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
5483
5611
  }
5484
5612
  } catch (err) {
5485
5613
  this.cb.onFailure();
@@ -5541,20 +5669,20 @@ var CacheService = class _CacheService {
5541
5669
  if (this.opts.frozen) deepFreeze(data);
5542
5670
  return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
5543
5671
  }
5544
- this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
5672
+ const writeTs = Date.now();
5673
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs);
5545
5674
  if (!this._redisDisabled) {
5546
5675
  try {
5547
5676
  const client = await this.getRedis();
5548
5677
  const serialized = JSON.stringify(data);
5549
5678
  const toStore = await this._serializeAndEncrypt(serialized);
5550
5679
  const ttlSec = Math.ceil(effectiveTtl / 1e3);
5551
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
5552
- const now = Date.now();
5680
+ if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
5553
5681
  const tx = client.multi();
5554
5682
  tx.hset(k, {
5555
5683
  d: toStore,
5556
- t: String(now),
5557
- tv: JSON.stringify(activeTagVersions)
5684
+ t: String(writeTs),
5685
+ tv: JSON.stringify(activeTagVersions ?? {})
5558
5686
  });
5559
5687
  tx.expire(k, ttlSec);
5560
5688
  await tx.exec();
@@ -5692,20 +5820,20 @@ var CacheService = class _CacheService {
5692
5820
  this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
5693
5821
  return;
5694
5822
  }
5695
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
5823
+ const writeTs = Date.now();
5824
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs);
5696
5825
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
5697
5826
  try {
5698
5827
  const client = await this.getRedis();
5699
5828
  const s = JSON.stringify(data);
5700
5829
  const stored = await this._serializeAndEncrypt(s);
5701
5830
  const ttlSec = Math.ceil(ttlMs / 1e3);
5702
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
5703
- const now = Date.now();
5831
+ if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
5704
5832
  const tx = client.multi();
5705
5833
  tx.hset(cacheKey, {
5706
5834
  d: stored,
5707
- t: String(now),
5708
- tv: JSON.stringify(activeTagVersions)
5835
+ t: String(writeTs),
5836
+ tv: JSON.stringify(activeTagVersions ?? {})
5709
5837
  });
5710
5838
  tx.expire(cacheKey, ttlSec);
5711
5839
  await tx.exec();
@@ -5762,16 +5890,23 @@ var CacheService = class _CacheService {
5762
5890
  await this._registerTags(k, tagsToRegister, ttlSeconds);
5763
5891
  }
5764
5892
  }
5765
- this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
5766
- if (opts?.dependsOn?.length) {
5767
- for (const pattern of opts.dependsOn) {
5768
- const nsPattern = this.nk(pattern);
5769
- let deps = this.dependencyIndex.get(nsPattern);
5770
- if (!deps) {
5771
- deps = /* @__PURE__ */ new Set();
5772
- this.dependencyIndex.set(nsPattern, deps);
5893
+ const writeTs = Date.now();
5894
+ this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions, writeTs);
5895
+ if (opts?.dependsOn !== void 0) {
5896
+ this._removeKeyDependencies(k);
5897
+ if (opts.dependsOn.length > 0) {
5898
+ const nsPatterns = [];
5899
+ for (const pattern of opts.dependsOn) {
5900
+ const nsPattern = this.nk(pattern);
5901
+ nsPatterns.push(nsPattern);
5902
+ let deps = this.dependencyIndex.get(nsPattern);
5903
+ if (!deps) {
5904
+ deps = /* @__PURE__ */ new Set();
5905
+ this.dependencyIndex.set(nsPattern, deps);
5906
+ }
5907
+ deps.add(k);
5773
5908
  }
5774
- deps.add(k);
5909
+ this.keyDependencies.set(k, nsPatterns);
5775
5910
  }
5776
5911
  }
5777
5912
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
@@ -5780,13 +5915,12 @@ var CacheService = class _CacheService {
5780
5915
  const s = JSON.stringify(data);
5781
5916
  const stored = await this._serializeAndEncrypt(s);
5782
5917
  const ttlSec = Math.ceil(ttlMs / 1e3);
5783
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
5784
- const now = Date.now();
5918
+ if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
5785
5919
  const tx = client.multi();
5786
5920
  tx.hset(k, {
5787
5921
  d: stored,
5788
- t: String(now),
5789
- tv: JSON.stringify(activeTagVersions)
5922
+ t: String(writeTs),
5923
+ tv: JSON.stringify(activeTagVersions ?? {})
5790
5924
  });
5791
5925
  tx.expire(k, ttlSec);
5792
5926
  await tx.exec();
@@ -5821,7 +5955,18 @@ var CacheService = class _CacheService {
5821
5955
  * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
5822
5956
  */
5823
5957
  async _registerTags(k, tags, ttlSeconds) {
5824
- for (const tag of tags) {
5958
+ this._removeKeyTags(k);
5959
+ const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
5960
+ const expiresAt = Date.now() + effectiveTtl * 1e3;
5961
+ if (this.keyTags.size >= 1e5 && !this.keyTags.has(k)) {
5962
+ this._sweepExpiredMetadata();
5963
+ if (this.keyTags.size >= 1e5) {
5964
+ const oldestKey = this.keyTags.keys().next().value;
5965
+ if (oldestKey !== void 0) this._removeKeyTags(oldestKey);
5966
+ }
5967
+ }
5968
+ const uniqueTags = Array.from(new Set(tags));
5969
+ for (const tag of uniqueTags) {
5825
5970
  const tagKey = this.nk(`_tag_:${tag}`);
5826
5971
  let members = this.tagIndex.get(tagKey);
5827
5972
  if (!members) {
@@ -5830,14 +5975,15 @@ var CacheService = class _CacheService {
5830
5975
  }
5831
5976
  members.add(k);
5832
5977
  }
5978
+ this.keyTags.set(k, { tags: uniqueTags, expiresAt });
5833
5979
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
5834
5980
  try {
5835
5981
  const client = await this.getRedis();
5836
5982
  const pl = client.pipeline();
5837
- for (const tag of tags) {
5983
+ for (const tag of uniqueTags) {
5838
5984
  const tagKey = this.nk(`_tag_:${tag}`);
5839
5985
  pl.sadd(tagKey, k);
5840
- pl.expire(tagKey, ttlSeconds + 3600);
5986
+ pl.expire(tagKey, effectiveTtl + 3600);
5841
5987
  }
5842
5988
  await pl.exec();
5843
5989
  this.cb.onSuccess();
@@ -5876,6 +6022,13 @@ var CacheService = class _CacheService {
5876
6022
  }
5877
6023
  this._addPatternTombstone(pfx);
5878
6024
  this.l1.deletePattern(k);
6025
+ this._removePrefixFromIndices(pfx);
6026
+ for (const ktKey of Array.from(this.keyTags.keys())) {
6027
+ if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
6028
+ }
6029
+ for (const kdKey of Array.from(this.keyDependencies.keys())) {
6030
+ if (this._matchesGlob(kdKey, k)) this._removeKeyDependencies(kdKey);
6031
+ }
5879
6032
  } else {
5880
6033
  this._bumpKeyMutation(k);
5881
6034
  this.inflight.delete(k);
@@ -5888,15 +6041,16 @@ var CacheService = class _CacheService {
5888
6041
  this._pendingDiskDeletes.delete(k);
5889
6042
  }
5890
6043
  });
6044
+ this._removeKeyTags(k);
5891
6045
  this._cascadeDependencies(k);
5892
- for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
6046
+ this._removeKeyDependencies(k);
5893
6047
  }
5894
6048
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
5895
6049
  try {
5896
6050
  const client = await this.getRedis();
5897
6051
  if (isPattern) {
5898
6052
  const keys = await this._scanKeys(client, k);
5899
- if (keys.length > 0) await client.del(...keys);
6053
+ await this._deleteRedisKeys(client, keys);
5900
6054
  } else {
5901
6055
  if (this.opts.autoPipeline && this.pipeliner) {
5902
6056
  await this.pipeliner.del(k);
@@ -5958,6 +6112,15 @@ var CacheService = class _CacheService {
5958
6112
  entry.value++;
5959
6113
  return entry.value;
5960
6114
  }
6115
+ if (this._l1Counters.size >= 5e4 && !this._l1Counters.has(k)) {
6116
+ for (const [ck, cv] of this._l1Counters) {
6117
+ if (cv.expiresAt <= now) this._l1Counters.delete(ck);
6118
+ }
6119
+ if (this._l1Counters.size >= 5e4) {
6120
+ const oldest = this._l1Counters.keys().next().value;
6121
+ if (oldest !== void 0) this._l1Counters.delete(oldest);
6122
+ }
6123
+ }
5961
6124
  this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
5962
6125
  return 1;
5963
6126
  }
@@ -6004,6 +6167,7 @@ var CacheService = class _CacheService {
6004
6167
  }
6005
6168
  this._addPatternTombstone(pfx);
6006
6169
  this.l1.deletePattern(k);
6170
+ this._removePrefixFromIndices(pfx);
6007
6171
  } else {
6008
6172
  this._globalEpoch++;
6009
6173
  this.inflight.clear();
@@ -6012,7 +6176,10 @@ var CacheService = class _CacheService {
6012
6176
  if (!this._diskDisabled) this.disk.clear();
6013
6177
  this._l1Counters.clear();
6014
6178
  this.tagIndex.clear();
6179
+ this.keyTags.clear();
6015
6180
  this.tagVersions.clear();
6181
+ this.dependencyIndex.clear();
6182
+ this.keyDependencies.clear();
6016
6183
  this._pendingDiskDeletes.clear();
6017
6184
  this._keyMutationEpochs.clear();
6018
6185
  }
@@ -6021,7 +6188,7 @@ var CacheService = class _CacheService {
6021
6188
  const client = await this.getRedis();
6022
6189
  const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
6023
6190
  const keys = await this._scanKeys(client, pattern);
6024
- if (keys.length > 0) await client.del(...keys);
6191
+ await this._deleteRedisKeys(client, keys);
6025
6192
  } catch (err) {
6026
6193
  this.logger.debug("clear: Redis unavailable", { error: err.message });
6027
6194
  }
@@ -6164,6 +6331,10 @@ var CacheService = class _CacheService {
6164
6331
  this._assertActive("touch");
6165
6332
  const k = this.nk(cacheKey);
6166
6333
  const hit = this.l1.touch(k, newTtlSeconds * 1e3);
6334
+ if (hit) {
6335
+ const kt = this.keyTags.get(k);
6336
+ if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1e3;
6337
+ }
6167
6338
  if (hit && !this._redisDisabled) {
6168
6339
  try {
6169
6340
  const client = await this.getRedis();
@@ -6191,6 +6362,10 @@ var CacheService = class _CacheService {
6191
6362
  if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
6192
6363
  return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
6193
6364
  }
6365
+ _prepareReadValue(val) {
6366
+ if (this.opts.frozen) deepFreeze(val);
6367
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6368
+ }
6194
6369
  /**
6195
6370
  * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
6196
6371
  * Returns the cached value if found and valid, or `null` if absent / expired.
@@ -6204,11 +6379,13 @@ var CacheService = class _CacheService {
6204
6379
  const k = this.nk(cacheKey);
6205
6380
  const l1Hit = this.l1.get(k);
6206
6381
  if (l1Hit !== null) {
6207
- this.counters.gets++;
6208
- this.counters.l1Hits++;
6209
- const val = l1Hit.value;
6210
- if (this.opts.frozen) deepFreeze(val);
6211
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6382
+ if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
6383
+ this._deleteIfStale(k, l1Hit.setAt ?? 0);
6384
+ } else {
6385
+ this.counters.gets++;
6386
+ this.counters.l1Hits++;
6387
+ return this._prepareReadValue(l1Hit.value);
6388
+ }
6212
6389
  }
6213
6390
  if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
6214
6391
  if (this._isTombstonedByPattern(k)) {
@@ -6223,18 +6400,20 @@ var CacheService = class _CacheService {
6223
6400
  this.watchdog.recordDisk(diskElapsed);
6224
6401
  this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6225
6402
  if (diskHit !== null) {
6226
- const promoted = this.l1.importEntries(
6227
- [{ key: k, entry: diskHit }],
6228
- this.opts.forbiddenSnapshotPrefixes
6229
- );
6230
- if (promoted > 0) {
6231
- const l1Check = this.l1.get(k);
6232
- if (l1Check !== null) {
6233
- this.counters.gets++;
6234
- this.counters.diskHits++;
6235
- const val = l1Check.value;
6236
- if (this.opts.frozen) deepFreeze(val);
6237
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6403
+ if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
6404
+ this.disk.delete(k);
6405
+ } else {
6406
+ const promoted = this.l1.importEntries(
6407
+ [{ key: k, entry: diskHit }],
6408
+ this.opts.forbiddenSnapshotPrefixes
6409
+ );
6410
+ if (promoted > 0) {
6411
+ const l1Check = this.l1.get(k);
6412
+ if (l1Check !== null) {
6413
+ this.counters.gets++;
6414
+ this.counters.diskHits++;
6415
+ return this._prepareReadValue(l1Check.value);
6416
+ }
6238
6417
  }
6239
6418
  }
6240
6419
  }
@@ -6244,17 +6423,16 @@ var CacheService = class _CacheService {
6244
6423
  try {
6245
6424
  const client = await this.getRedis();
6246
6425
  const redisStart = performance.now();
6247
- const raw = await client.get(k);
6426
+ const redisHit = await this._readRedisEntry(client, k);
6248
6427
  const redisElapsed = performance.now() - redisStart;
6249
6428
  this.watchdog.recordRedis(redisElapsed);
6250
- if (raw !== null) {
6251
- const parsed = await this._decryptAndDeserialize(raw);
6252
- this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
6429
+ this.cb.onSuccess();
6430
+ if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
6431
+ const parsed = redisHit.value;
6432
+ this.l1.set(k, parsed, 6e4, inferPriority(cacheKey), void 0, void 0, redisHit.tagVersions);
6253
6433
  this.counters.gets++;
6254
6434
  this.counters.l2Hits++;
6255
- this.cb.onSuccess();
6256
- if (this.opts.frozen) deepFreeze(parsed);
6257
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
6435
+ return this._prepareReadValue(parsed);
6258
6436
  }
6259
6437
  } catch (err) {
6260
6438
  this.cb.onFailure();
@@ -6282,12 +6460,20 @@ var CacheService = class _CacheService {
6282
6460
  const result = Array.from({ length: keys.length });
6283
6461
  const missIndexes = [];
6284
6462
  const missKeys = [];
6463
+ const now = Date.now();
6285
6464
  for (let i = 0; i < keys.length; i++) {
6286
6465
  const k = this.nk(keys[i]);
6287
6466
  const entry = this.l1.getEntry(k);
6288
- if (entry && entry.expiresAt > Date.now()) {
6289
- result[i] = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
6290
- this.counters.l1Hits++;
6467
+ if (entry && entry.expiresAt > now) {
6468
+ if (await this._isGenerationalEntryStale(entry.tagVersions)) {
6469
+ this._deleteIfStale(k, entry.setAt ?? 0);
6470
+ missIndexes.push(i);
6471
+ missKeys.push(keys[i]);
6472
+ } else {
6473
+ const val = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
6474
+ result[i] = this._prepareReadValue(val);
6475
+ this.counters.l1Hits++;
6476
+ }
6291
6477
  } else {
6292
6478
  missIndexes.push(i);
6293
6479
  missKeys.push(keys[i]);
@@ -6308,23 +6494,57 @@ var CacheService = class _CacheService {
6308
6494
  const client = await this.getRedis();
6309
6495
  const nsKeys = missKeys.map((k) => this.nk(k));
6310
6496
  const pipeline = client.multi();
6311
- for (const nk of nsKeys) pipeline.get(nk);
6497
+ const useHashPipeline = this.opts.tagStrategy === "generational" && typeof pipeline.hgetall === "function";
6498
+ for (const nk of nsKeys) {
6499
+ if (useHashPipeline) {
6500
+ pipeline.hgetall(nk);
6501
+ } else {
6502
+ pipeline.get(nk);
6503
+ }
6504
+ }
6312
6505
  const redisStart = performance.now();
6313
6506
  const raws = await pipeline.exec();
6314
6507
  const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
6315
6508
  this.watchdog.recordRedis(redisElapsed);
6316
6509
  this.cb.onSuccess();
6317
6510
  for (let j = 0; j < missKeys.length; j++) {
6318
- const raw = raws[j] ? raws[j][1] : null;
6511
+ const tuple = raws[j];
6512
+ const err = tuple ? tuple[0] : null;
6513
+ const rawVal = tuple ? tuple[1] : null;
6319
6514
  const idx = missIndexes[j];
6320
- if (raw) {
6321
- const parsed = await this._decryptAndDeserialize(raw);
6322
- const k = nsKeys[j];
6515
+ const k = nsKeys[j];
6516
+ let parsed;
6517
+ let tagVersions;
6518
+ let hit = false;
6519
+ if (useHashPipeline) {
6520
+ if (err && err.message?.includes("WRONGTYPE")) {
6521
+ const fallbackRaw = await client.get(k);
6522
+ if (fallbackRaw) {
6523
+ parsed = await this._decryptAndDeserialize(fallbackRaw);
6524
+ hit = true;
6525
+ }
6526
+ } else if (!err && typeof rawVal === "string") {
6527
+ parsed = await this._decryptAndDeserialize(rawVal);
6528
+ hit = true;
6529
+ } else if (!err && rawVal && typeof rawVal === "object" && rawVal.d) {
6530
+ const hashHit = await this._parseGenerationalRedisHash(k, rawVal);
6531
+ if (hashHit && !hashHit.stale && hashHit.value !== void 0) {
6532
+ parsed = hashHit.value;
6533
+ tagVersions = hashHit.tagVersions;
6534
+ hit = true;
6535
+ }
6536
+ }
6537
+ } else if (!err && rawVal) {
6538
+ parsed = await this._decryptAndDeserialize(rawVal);
6539
+ hit = true;
6540
+ }
6541
+ if (hit && parsed !== void 0) {
6323
6542
  const p = priority ?? inferPriority(missKeys[j]);
6324
- this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
6543
+ const ttlVal = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
6544
+ this.l1.set(k, parsed, this._jitterTtl(ttlVal * 1e3), p, void 0, void 0, tagVersions);
6325
6545
  this.counters.l2Hits++;
6326
6546
  l2HitCount++;
6327
- result[idx] = parsed;
6547
+ result[idx] = this._prepareReadValue(parsed);
6328
6548
  missIndexes[j] = -1;
6329
6549
  missKeys[j] = "";
6330
6550
  }
@@ -6358,6 +6578,10 @@ var CacheService = class _CacheService {
6358
6578
  this.watchdog.recordDisk(diskElapsed);
6359
6579
  this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6360
6580
  if (diskHit !== null) {
6581
+ if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
6582
+ this.disk.delete(k);
6583
+ continue;
6584
+ }
6361
6585
  const promoted = this.l1.importEntries(
6362
6586
  [{ key: k, entry: diskHit }],
6363
6587
  this.opts.forbiddenSnapshotPrefixes
@@ -6366,7 +6590,7 @@ var CacheService = class _CacheService {
6366
6590
  const l1Check = this.l1.get(k);
6367
6591
  if (l1Check !== null) {
6368
6592
  this.counters.diskHits++;
6369
- result[missIndexes[j]] = l1Check.value;
6593
+ result[missIndexes[j]] = this._prepareReadValue(l1Check.value);
6370
6594
  missIndexes.splice(j, 1);
6371
6595
  missKeys.splice(j, 1);
6372
6596
  }
@@ -6591,6 +6815,136 @@ var CacheService = class _CacheService {
6591
6815
  }
6592
6816
  return matched;
6593
6817
  }
6818
+ async _publishTagInvalidation(op, key, tagVersion) {
6819
+ if (this.opts.awaitInvalidationBackplane) {
6820
+ await this.publishInvalidation(op, key, tagVersion, false, true);
6821
+ } else {
6822
+ void this.publishInvalidation(op, key, tagVersion, false, true);
6823
+ }
6824
+ }
6825
+ _removeTagMembersLocal(keys) {
6826
+ const keyList = Array.isArray(keys) ? keys : Array.from(keys);
6827
+ for (const k of keyList) {
6828
+ this.l1.delete(k);
6829
+ this._bumpKeyMutation(k);
6830
+ this._removeKeyTags(k);
6831
+ this._removeKeyDependencies(k);
6832
+ this._pendingDiskDeletes.add(k);
6833
+ setImmediate(() => {
6834
+ try {
6835
+ if (!this._diskDisabled) this.disk.delete(k);
6836
+ } finally {
6837
+ this._pendingDiskDeletes.delete(k);
6838
+ }
6839
+ });
6840
+ }
6841
+ }
6842
+ /**
6843
+ * Executes invalidation for a single already-resolved concrete tag without
6844
+ * wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
6845
+ */
6846
+ async _invalidateConcreteTag(tag) {
6847
+ if (this.opts.tagStrategy === "generational") {
6848
+ let newVer = 1;
6849
+ if (!this._redisDisabled) {
6850
+ try {
6851
+ const client = await this.getRedis();
6852
+ newVer = await client.incr(this.nk(`tag_ver:${tag}`));
6853
+ } catch (err) {
6854
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
6855
+ const current = this.tagVersions.get(tag)?.version ?? 0;
6856
+ newVer = current + 1;
6857
+ }
6858
+ } else {
6859
+ const current = this.tagVersions.get(tag)?.version ?? 0;
6860
+ newVer = current + 1;
6861
+ }
6862
+ this._setLocalTagVersion(tag, newVer, performance.now());
6863
+ await this._publishTagInvalidation("tag_incr", tag, newVer);
6864
+ return;
6865
+ }
6866
+ const tagKey = this.nk(`_tag_:${tag}`);
6867
+ const members = Array.from(this.tagIndex.get(tagKey) ?? []);
6868
+ this.tagIndex.delete(tagKey);
6869
+ this._removeTagMembersLocal(members);
6870
+ if (!this._redisDisabled) {
6871
+ try {
6872
+ const client = await this.getRedis();
6873
+ const redisMembers = await client.smembers(tagKey);
6874
+ const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers, tagKey])];
6875
+ await this._deleteRedisKeys(client, toDelete);
6876
+ } catch (err) {
6877
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
6878
+ }
6879
+ }
6880
+ }
6881
+ /**
6882
+ * Executes invalidation for an array of already-resolved concrete tags
6883
+ * without re-entering wildcard/cascade resolution or invalidateTag().
6884
+ */
6885
+ async _invalidateConcreteTags(tags) {
6886
+ if (tags.length === 0) return;
6887
+ if (tags.length === 1) {
6888
+ await this._invalidateConcreteTag(tags[0]);
6889
+ return;
6890
+ }
6891
+ if (this.opts.tagStrategy === "generational") {
6892
+ const now = performance.now();
6893
+ if (!this._redisDisabled) {
6894
+ try {
6895
+ const client = await this.getRedis();
6896
+ const pl = client.pipeline();
6897
+ for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
6898
+ const results = await pl.exec();
6899
+ for (let i = 0; i < tags.length; i++) {
6900
+ const [err, newVer] = results[i] ?? [null, null];
6901
+ const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
6902
+ this._setLocalTagVersion(tags[i], ver, now);
6903
+ await this._publishTagInvalidation("tag_incr", tags[i], ver);
6904
+ }
6905
+ return;
6906
+ } catch (err) {
6907
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
6908
+ }
6909
+ }
6910
+ for (const tag of tags) {
6911
+ const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
6912
+ this._setLocalTagVersion(tag, ver, now);
6913
+ await this._publishTagInvalidation("tag_incr", tag, ver);
6914
+ }
6915
+ return;
6916
+ }
6917
+ const tagKeys = [];
6918
+ const allMembers = /* @__PURE__ */ new Set();
6919
+ for (const tag of tags) {
6920
+ const tagKey = this.nk(`_tag_:${tag}`);
6921
+ tagKeys.push(tagKey);
6922
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
6923
+ for (const k of members) allMembers.add(k);
6924
+ this.tagIndex.delete(tagKey);
6925
+ }
6926
+ this._removeTagMembersLocal(allMembers);
6927
+ if (!this._redisDisabled) {
6928
+ try {
6929
+ const client = await this.getRedis();
6930
+ const pl = client.pipeline();
6931
+ for (const tagKey of tagKeys) pl.smembers(tagKey);
6932
+ const smResults = await pl.exec();
6933
+ const toDelete = [...allMembers];
6934
+ for (const [err, redisMembers] of smResults) {
6935
+ if (!err && redisMembers) {
6936
+ for (const k of redisMembers) {
6937
+ if (!allMembers.has(k)) toDelete.push(k);
6938
+ }
6939
+ }
6940
+ }
6941
+ const keysToRemove = [...toDelete, ...tagKeys];
6942
+ await this._deleteRedisKeys(client, keysToRemove);
6943
+ } catch (err) {
6944
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
6945
+ }
6946
+ }
6947
+ }
6594
6948
  /**
6595
6949
  * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
6596
6950
  * Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
@@ -6626,68 +6980,13 @@ var CacheService = class _CacheService {
6626
6980
  const delim = this.opts.tagHierarchyDelimiter;
6627
6981
  const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
6628
6982
  if (matchedTags.size > 0) {
6629
- await this.invalidateTags(Array.from(matchedTags));
6983
+ await this._invalidateConcreteTags(Array.from(matchedTags));
6630
6984
  }
6631
6985
  const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
6632
- if (this.opts.awaitInvalidationBackplane) {
6633
- await this.publishInvalidation(op, broadcastPattern, void 0, false, true);
6634
- } else {
6635
- void this.publishInvalidation(op, broadcastPattern, void 0, false, true);
6636
- }
6986
+ await this._publishTagInvalidation(op, broadcastPattern);
6637
6987
  return;
6638
6988
  }
6639
- if (this.opts.tagStrategy === "generational") {
6640
- let newVer = 1;
6641
- if (!this._redisDisabled) {
6642
- try {
6643
- const client = await this.getRedis();
6644
- newVer = await client.incr(this.nk(`tag_ver:${tag}`));
6645
- } catch (err) {
6646
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
6647
- const current = this.tagVersions.get(tag)?.version ?? 0;
6648
- newVer = current + 1;
6649
- }
6650
- } else {
6651
- const current = this.tagVersions.get(tag)?.version ?? 0;
6652
- newVer = current + 1;
6653
- }
6654
- this._setLocalTagVersion(tag, newVer, performance.now());
6655
- if (this.opts.awaitInvalidationBackplane) {
6656
- await this.publishInvalidation("tag_incr", tag, newVer, false, true);
6657
- } else {
6658
- void this.publishInvalidation("tag_incr", tag, newVer, false, true);
6659
- }
6660
- return;
6661
- }
6662
- const tagKey = this.nk(`_tag_:${tag}`);
6663
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
6664
- for (const k of members) {
6665
- this.l1.delete(k);
6666
- this._bumpKeyMutation(k);
6667
- this._pendingDiskDeletes.add(k);
6668
- setImmediate(() => {
6669
- try {
6670
- if (!this._diskDisabled) this.disk.delete(k);
6671
- } finally {
6672
- this._pendingDiskDeletes.delete(k);
6673
- }
6674
- });
6675
- }
6676
- this.tagIndex.delete(tagKey);
6677
- if (!this._redisDisabled) {
6678
- try {
6679
- const client = await this.getRedis();
6680
- const redisMembers = await client.smembers(tagKey);
6681
- const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
6682
- if (toDelete.length > 0) {
6683
- await client.del(...toDelete, tagKey);
6684
- } else {
6685
- await client.del(tagKey);
6686
- }
6687
- } catch (err) {
6688
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
6689
- }
6690
- }
6989
+ await this._invalidateConcreteTag(tag);
6691
6990
  } catch (err) {
6692
6991
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
6693
6992
  span.recordException?.(err);
@@ -6714,96 +7013,28 @@ var CacheService = class _CacheService {
6714
7013
  const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
6715
7014
  if (hasWildcards || shouldCascade) {
6716
7015
  const allResolvedTags = /* @__PURE__ */ new Set();
7016
+ const broadcastPatterns = /* @__PURE__ */ new Set();
7017
+ const delim = this.opts.tagHierarchyDelimiter;
6717
7018
  for (const t of tags) {
6718
- if (isWildcardTag(t) || shouldCascade) {
7019
+ const tIsPattern = isWildcardTag(t);
7020
+ if (tIsPattern || shouldCascade) {
7021
+ broadcastPatterns.add(tIsPattern ? t : `${t}${delim}*`);
6719
7022
  const resolved = await this._resolveMatchingTags(t, shouldCascade);
6720
7023
  for (const rt of resolved) allResolvedTags.add(rt);
6721
7024
  } else {
6722
7025
  allResolvedTags.add(t);
6723
7026
  }
6724
7027
  }
6725
- if (allResolvedTags.size === 0) return;
6726
- tags = Array.from(allResolvedTags);
6727
- }
6728
- if (tags.length === 1) {
6729
- await this.invalidateTag(tags[0], opts);
6730
- return;
6731
- }
6732
- if (this.opts.tagStrategy === "generational") {
6733
- const now = performance.now();
6734
- if (!this._redisDisabled) {
6735
- try {
6736
- const client = await this.getRedis();
6737
- const pl = client.pipeline();
6738
- for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
6739
- const results = await pl.exec();
6740
- for (let i = 0; i < tags.length; i++) {
6741
- const [err, newVer] = results[i] ?? [null, null];
6742
- const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
6743
- this._setLocalTagVersion(tags[i], ver, now);
6744
- if (this.opts.awaitInvalidationBackplane) {
6745
- await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
6746
- } else {
6747
- void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
6748
- }
6749
- }
6750
- return;
6751
- } catch (err) {
6752
- this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
6753
- }
7028
+ if (allResolvedTags.size > 0) {
7029
+ await this._invalidateConcreteTags(Array.from(allResolvedTags));
6754
7030
  }
6755
- for (const tag of tags) {
6756
- const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
6757
- this._setLocalTagVersion(tag, ver, now);
6758
- if (this.opts.awaitInvalidationBackplane) {
6759
- await this.publishInvalidation("tag_incr", tag, ver, false, true);
6760
- } else {
6761
- void this.publishInvalidation("tag_incr", tag, ver, false, true);
6762
- }
7031
+ const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
7032
+ for (const pattern of broadcastPatterns) {
7033
+ await this._publishTagInvalidation(op, pattern);
6763
7034
  }
6764
7035
  return;
6765
7036
  }
6766
- const tagKeys = [];
6767
- const allMembers = /* @__PURE__ */ new Set();
6768
- for (const tag of tags) {
6769
- const tagKey = this.nk(`_tag_:${tag}`);
6770
- tagKeys.push(tagKey);
6771
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
6772
- for (const k of members) allMembers.add(k);
6773
- this.tagIndex.delete(tagKey);
6774
- }
6775
- for (const k of allMembers) {
6776
- this.l1.delete(k);
6777
- this._bumpKeyMutation(k);
6778
- this._pendingDiskDeletes.add(k);
6779
- setImmediate(() => {
6780
- try {
6781
- if (!this._diskDisabled) this.disk.delete(k);
6782
- } finally {
6783
- this._pendingDiskDeletes.delete(k);
6784
- }
6785
- });
6786
- }
6787
- if (!this._redisDisabled) {
6788
- try {
6789
- const client = await this.getRedis();
6790
- const pl = client.pipeline();
6791
- for (const tagKey of tagKeys) pl.smembers(tagKey);
6792
- const smResults = await pl.exec();
6793
- const toDelete = [...allMembers];
6794
- for (const [err, redisMembers] of smResults) {
6795
- if (!err && redisMembers) {
6796
- for (const k of redisMembers) {
6797
- if (!allMembers.has(k)) toDelete.push(k);
6798
- }
6799
- }
6800
- }
6801
- const keysToRemove = [...toDelete, ...tagKeys];
6802
- if (keysToRemove.length > 0) await client.del(...keysToRemove);
6803
- } catch (err) {
6804
- this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
6805
- }
6806
- }
7037
+ await this._invalidateConcreteTags(Array.from(new Set(tags)));
6807
7038
  }
6808
7039
  /**
6809
7040
  * Get the current generational tag version for a tag (synced with Redis when due).
@@ -7370,6 +7601,13 @@ var CacheService = class _CacheService {
7370
7601
  this._destroyed = true;
7371
7602
  this._pendingDiskDeletes.clear();
7372
7603
  this._keyMutationEpochs.clear();
7604
+ this.inflight.clear();
7605
+ this.revalidating.clear();
7606
+ this._l1Counters.clear();
7607
+ this.tagIndex.clear();
7608
+ this.keyTags.clear();
7609
+ this.dependencyIndex.clear();
7610
+ this.keyDependencies.clear();
7373
7611
  const g = globalThis;
7374
7612
  const key = _CacheService.globalKey(this.opts);
7375
7613
  if (g[key] === this) {