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
@@ -1431,7 +1431,7 @@ var SmartMemoryCache = class {
1431
1431
  };
1432
1432
  return hit;
1433
1433
  }
1434
- set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
1434
+ set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions, setAt) {
1435
1435
  const packed = this.codec.encode(data);
1436
1436
  const size = packed.byteLength;
1437
1437
  this.compressions++;
@@ -1468,7 +1468,7 @@ var SmartMemoryCache = class {
1468
1468
  priority,
1469
1469
  ttlMs,
1470
1470
  delta,
1471
- setAt: now2,
1471
+ setAt: setAt ?? now2,
1472
1472
  tagVersions
1473
1473
  });
1474
1474
  }
@@ -1496,7 +1496,7 @@ var SmartMemoryCache = class {
1496
1496
  }
1497
1497
  const now = Date.now();
1498
1498
  const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
1499
- 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 });
1499
+ 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 });
1500
1500
  if (!existingEntry) this.bloom.add(key);
1501
1501
  this.maybeRebuildBloom();
1502
1502
  this.totalSize += size;
@@ -4038,6 +4038,8 @@ var CacheService = class _CacheService {
4038
4038
  _l1Counters = /* @__PURE__ */ new Map();
4039
4039
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
4040
4040
  tagIndex = /* @__PURE__ */ new Map();
4041
+ /** Reverse index of namespaced key → { tags, expiresAt } for bounded cleanup on eviction/delete */
4042
+ keyTags = /* @__PURE__ */ new Map();
4041
4043
  /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
4042
4044
  tagVersions = /* @__PURE__ */ new Map();
4043
4045
  /**
@@ -4045,6 +4047,9 @@ var CacheService = class _CacheService {
4045
4047
  * When an exact-key delete matches a registered pattern, all dependents are cascaded.
4046
4048
  */
4047
4049
  dependencyIndex = /* @__PURE__ */ new Map();
4050
+ /** Reverse index of namespaced dependent key → source glob patterns */
4051
+ keyDependencies = /* @__PURE__ */ new Map();
4052
+ _cgroupMemoryLimit;
4048
4053
  redis = null;
4049
4054
  redisConnecting = null;
4050
4055
  cb;
@@ -4114,6 +4119,84 @@ var CacheService = class _CacheService {
4114
4119
  _getKeyMutationEpoch(namespacedKey) {
4115
4120
  return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
4116
4121
  }
4122
+ _removeKeyTags(namespacedKey) {
4123
+ const entry = this.keyTags.get(namespacedKey);
4124
+ if (!entry) return;
4125
+ for (const tag of entry.tags) {
4126
+ const tagKey = this.nk(`_tag_:${tag}`);
4127
+ const members = this.tagIndex.get(tagKey);
4128
+ if (members) {
4129
+ members.delete(namespacedKey);
4130
+ if (members.size === 0) this.tagIndex.delete(tagKey);
4131
+ }
4132
+ }
4133
+ this.keyTags.delete(namespacedKey);
4134
+ }
4135
+ _removeKeyDependencies(namespacedKey) {
4136
+ const patterns = this.keyDependencies.get(namespacedKey);
4137
+ if (patterns) {
4138
+ for (const pat of patterns) {
4139
+ const deps = this.dependencyIndex.get(pat);
4140
+ if (deps) {
4141
+ deps.delete(namespacedKey);
4142
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
4143
+ }
4144
+ }
4145
+ this.keyDependencies.delete(namespacedKey);
4146
+ } else if (this.dependencyIndex.size > 0) {
4147
+ for (const [pat, deps] of this.dependencyIndex) {
4148
+ deps.delete(namespacedKey);
4149
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
4150
+ }
4151
+ }
4152
+ }
4153
+ _handleL1Eviction(namespacedKey, reason) {
4154
+ const spilledToDisk = !this._diskDisabled && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
4155
+ if (!spilledToDisk) {
4156
+ this._removeKeyTags(namespacedKey);
4157
+ this._removeKeyDependencies(namespacedKey);
4158
+ }
4159
+ }
4160
+ _removePrefixFromIndices(prefix) {
4161
+ for (const k of Array.from(this.keyTags.keys())) {
4162
+ if (k.startsWith(prefix)) this._removeKeyTags(k);
4163
+ }
4164
+ for (const k of Array.from(this.keyDependencies.keys())) {
4165
+ if (k.startsWith(prefix)) this._removeKeyDependencies(k);
4166
+ }
4167
+ for (const k of Array.from(this._l1Counters.keys())) {
4168
+ if (k.startsWith(prefix)) this._l1Counters.delete(k);
4169
+ }
4170
+ }
4171
+ _sweepExpiredMetadata() {
4172
+ const now = Date.now();
4173
+ for (const [k, c] of this._l1Counters) {
4174
+ if (c.expiresAt <= now) this._l1Counters.delete(k);
4175
+ }
4176
+ for (const [k, meta] of this.keyTags) {
4177
+ if (meta.expiresAt <= now && !this.l1.has(k)) {
4178
+ this._removeKeyTags(k);
4179
+ this._removeKeyDependencies(k);
4180
+ }
4181
+ }
4182
+ }
4183
+ _runOomCheck() {
4184
+ const heap = import_node_v82.default.getHeapStatistics();
4185
+ const heapUsed = heap.used_heap_size / heap.heap_size_limit;
4186
+ const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? process.memoryUsage().rss / this._cgroupMemoryLimit : 0;
4187
+ const used = Math.max(heapUsed, cgroupUsed);
4188
+ if (used >= this.opts.oomHeapThreshold) {
4189
+ const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
4190
+ this.counters.oomEvictions++;
4191
+ this.counters.oomLastAt = Date.now();
4192
+ this.logger.warn("tricache OOM guard: emergency L1 eviction", {
4193
+ heapUsedPct: Math.round(heapUsed * 100),
4194
+ cgroupUsedPct: cgroupUsed > 0 ? Math.round(cgroupUsed * 100) : void 0,
4195
+ threshold: Math.round(this.opts.oomHeapThreshold * 100),
4196
+ evicted
4197
+ });
4198
+ }
4199
+ }
4117
4200
  _ipcServer;
4118
4201
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
4119
4202
  _subDisconnectedAt = null;
@@ -4160,6 +4243,7 @@ var CacheService = class _CacheService {
4160
4243
  constructor(options = {}) {
4161
4244
  const logger = options.logger ?? consoleLogger;
4162
4245
  this.logger = logger;
4246
+ this._cgroupMemoryLimit = readCgroupMemoryLimit();
4163
4247
  const ns = options.namespace?.trim() ?? "";
4164
4248
  const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
4165
4249
  this.enc = new CacheEncryption(
@@ -4343,7 +4427,10 @@ var CacheService = class _CacheService {
4343
4427
  void this.disk.save(key, entry);
4344
4428
  });
4345
4429
  },
4346
- onEviction: options.onEviction,
4430
+ onEviction: (key, reason) => {
4431
+ this._handleL1Eviction(key, reason);
4432
+ options.onEviction?.(key, reason);
4433
+ },
4347
4434
  logger
4348
4435
  });
4349
4436
  if (!this.snapshotLoaded) {
@@ -4381,6 +4468,7 @@ var CacheService = class _CacheService {
4381
4468
  }
4382
4469
  this.cleanupInterval = setInterval(() => {
4383
4470
  const cleaned = this.l1.cleanup();
4471
+ this._sweepExpiredMetadata();
4384
4472
  if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
4385
4473
  }, 5 * 60 * 1e3);
4386
4474
  if (this.cleanupInterval.unref) this.cleanupInterval.unref();
@@ -4393,18 +4481,7 @@ var CacheService = class _CacheService {
4393
4481
  }
4394
4482
  if (this.opts.oomProtection) {
4395
4483
  this.oomInterval = setInterval(() => {
4396
- const heap = import_node_v82.default.getHeapStatistics();
4397
- const used = heap.used_heap_size / heap.heap_size_limit;
4398
- if (used >= this.opts.oomHeapThreshold) {
4399
- const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
4400
- this.counters.oomEvictions++;
4401
- this.counters.oomLastAt = Date.now();
4402
- this.logger.warn("tricache OOM guard: emergency L1 eviction", {
4403
- heapUsedPct: Math.round(used * 100),
4404
- threshold: Math.round(this.opts.oomHeapThreshold * 100),
4405
- evicted
4406
- });
4407
- }
4484
+ this._runOomCheck();
4408
4485
  }, this.opts.oomCheckIntervalMs);
4409
4486
  if (this.oomInterval.unref) this.oomInterval.unref();
4410
4487
  }
@@ -4879,7 +4956,7 @@ var CacheService = class _CacheService {
4879
4956
  else if (f === "src") src = v;
4880
4957
  else if (f === "tagVersion") tagVersionRaw = v;
4881
4958
  }
4882
- const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
4959
+ const validOp = op === "del" || op === "del-glob" || op === "tag_incr" || op === "tag_pattern_incr" || op === "tag_pattern_del";
4883
4960
  if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
4884
4961
  this.logger.warn("Backplane: rejected invalid stream entry", {
4885
4962
  op: String(op).slice(0, 40),
@@ -5141,6 +5218,72 @@ var CacheService = class _CacheService {
5141
5218
  }
5142
5219
  this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
5143
5220
  }
5221
+ async _isGenerationalEntryStale(tagVersions) {
5222
+ if (this.opts.tagStrategy !== "generational" || !tagVersions) return false;
5223
+ const tags = Object.keys(tagVersions);
5224
+ if (tags.length === 0) return false;
5225
+ const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5226
+ for (let i = 0; i < tags.length; i++) {
5227
+ if (currentVers[i] > tagVersions[tags[i]]) return true;
5228
+ }
5229
+ return false;
5230
+ }
5231
+ async _deleteRedisKeys(client, keys) {
5232
+ if (keys.length === 0) return;
5233
+ const CHUNK_SIZE = 1e3;
5234
+ if (client instanceof import_ioredis.Cluster) {
5235
+ for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
5236
+ const chunk = keys.slice(i, i + CHUNK_SIZE);
5237
+ const pl = client.pipeline();
5238
+ for (const k of chunk) pl.del(k);
5239
+ await pl.exec();
5240
+ }
5241
+ return;
5242
+ }
5243
+ for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
5244
+ const chunk = keys.slice(i, i + CHUNK_SIZE);
5245
+ await client.del(...chunk);
5246
+ }
5247
+ }
5248
+ async _parseGenerationalRedisHash(k, hashData) {
5249
+ if (!hashData || !hashData.d) return null;
5250
+ let storedTagVersions = {};
5251
+ if (hashData.tv) {
5252
+ try {
5253
+ storedTagVersions = JSON.parse(hashData.tv);
5254
+ } catch {
5255
+ }
5256
+ }
5257
+ if (await this._isGenerationalEntryStale(storedTagVersions)) {
5258
+ const setAtMs = parseInt(hashData.t, 10) || 0;
5259
+ this._deleteIfStale(k, setAtMs);
5260
+ return { stale: true };
5261
+ }
5262
+ const value = await this._decryptAndDeserialize(hashData.d);
5263
+ return { value, tagVersions: storedTagVersions, stale: false };
5264
+ }
5265
+ async _readRedisEntry(client, k, allowAutoPipeline = false) {
5266
+ if (this.opts.tagStrategy === "generational" && typeof client.hgetall === "function") {
5267
+ try {
5268
+ const hashData = await client.hgetall(k);
5269
+ if (typeof hashData === "string") {
5270
+ const value2 = await this._decryptAndDeserialize(hashData);
5271
+ return { value: value2, stale: false };
5272
+ }
5273
+ if (hashData && hashData.d) {
5274
+ return await this._parseGenerationalRedisHash(k, hashData);
5275
+ }
5276
+ return null;
5277
+ } catch (err) {
5278
+ const msg = err instanceof Error ? err.message : String(err);
5279
+ if (!msg.includes("WRONGTYPE")) throw err;
5280
+ }
5281
+ }
5282
+ const raw = allowAutoPipeline && this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
5283
+ if (raw == null) return null;
5284
+ const value = await this._decryptAndDeserialize(raw);
5285
+ return { value, stale: false };
5286
+ }
5144
5287
  async _getTagVersion(tag) {
5145
5288
  const now = performance.now();
5146
5289
  const local = this.tagVersions.get(tag);
@@ -5278,8 +5421,8 @@ var CacheService = class _CacheService {
5278
5421
  return client;
5279
5422
  }
5280
5423
  this.redisConnecting = (async () => {
5424
+ let client = null;
5281
5425
  try {
5282
- let client;
5283
5426
  if (this.opts.redisClusterNodes?.length) {
5284
5427
  client = new import_ioredis.Cluster(this.opts.redisClusterNodes, {
5285
5428
  redisOptions: {
@@ -5342,14 +5485,45 @@ var CacheService = class _CacheService {
5342
5485
  });
5343
5486
  client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
5344
5487
  }
5488
+ const pendingClient = client;
5345
5489
  await new Promise((resolve, reject) => {
5346
- client.once("ready", resolve);
5347
- client.once("error", (e) => {
5490
+ let settled = false;
5491
+ const cleanupListeners = () => {
5492
+ pendingClient.removeListener?.("ready", onReady);
5493
+ pendingClient.removeListener?.("error", onError);
5494
+ };
5495
+ const onReady = () => {
5496
+ if (settled) return;
5497
+ settled = true;
5498
+ clearTimeout(timer);
5499
+ cleanupListeners();
5500
+ resolve();
5501
+ };
5502
+ const onError = (e) => {
5503
+ if (settled) return;
5504
+ settled = true;
5505
+ clearTimeout(timer);
5506
+ cleanupListeners();
5348
5507
  this._checkAndLogResp3Hint(e);
5349
5508
  reject(e);
5350
- });
5351
- setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
5509
+ };
5510
+ const timer = setTimeout(() => {
5511
+ if (settled) return;
5512
+ settled = true;
5513
+ cleanupListeners();
5514
+ reject(new Error("Redis connection timeout"));
5515
+ }, 15e3);
5516
+ if (timer.unref) timer.unref();
5517
+ pendingClient.once("ready", onReady);
5518
+ pendingClient.once("error", onError);
5352
5519
  });
5520
+ if (this._destroyed) {
5521
+ try {
5522
+ client.disconnect();
5523
+ } catch {
5524
+ }
5525
+ this._assertActive("getRedis");
5526
+ }
5353
5527
  this.cb.onSuccess();
5354
5528
  this.redis = client;
5355
5529
  this.pipeliner = new AutoPipeliner(client, {
@@ -5359,6 +5533,10 @@ var CacheService = class _CacheService {
5359
5533
  this.redisConnecting = null;
5360
5534
  return client;
5361
5535
  } catch (err) {
5536
+ try {
5537
+ client?.disconnect();
5538
+ } catch {
5539
+ }
5362
5540
  this.cb.onFailure();
5363
5541
  this.redisConnecting = null;
5364
5542
  this._checkAndLogResp3Hint(err);
@@ -5602,17 +5780,7 @@ var CacheService = class _CacheService {
5602
5780
  const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
5603
5781
  const l1Hit = this.l1.get(k);
5604
5782
  if (l1Hit !== null) {
5605
- let isGenerationalStale = false;
5606
- if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
5607
- const tags = Object.keys(l1Hit.tagVersions);
5608
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5609
- for (let i = 0; i < tags.length; i++) {
5610
- if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
5611
- isGenerationalStale = true;
5612
- break;
5613
- }
5614
- }
5615
- }
5783
+ const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
5616
5784
  if (isGenerationalStale) {
5617
5785
  this._deleteIfStale(k, l1Hit.setAt ?? 0);
5618
5786
  } else {
@@ -5698,17 +5866,7 @@ var CacheService = class _CacheService {
5698
5866
  this.watchdog.recordDisk(diskElapsed);
5699
5867
  this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
5700
5868
  if (diskHit !== null) {
5701
- let isDiskStale = false;
5702
- if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
5703
- const tags = Object.keys(diskHit.tagVersions);
5704
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5705
- for (let i = 0; i < tags.length; i++) {
5706
- if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
5707
- isDiskStale = true;
5708
- break;
5709
- }
5710
- }
5711
- }
5869
+ const isDiskStale = await this._isGenerationalEntryStale(diskHit.tagVersions);
5712
5870
  if (isDiskStale) {
5713
5871
  this.disk.delete(k);
5714
5872
  } else {
@@ -5736,57 +5894,27 @@ var CacheService = class _CacheService {
5736
5894
  try {
5737
5895
  const client = await this.getRedis();
5738
5896
  const redisStart = performance.now();
5739
- if (this.opts.tagStrategy === "generational") {
5740
- const hashData = await client.hgetall(k);
5741
- const redisElapsed = performance.now() - redisStart;
5742
- this.watchdog.recordRedis(redisElapsed);
5743
- this.cb.onSuccess();
5744
- if (hashData && hashData.d) {
5745
- let isStale = false;
5746
- let storedTagVersions = {};
5747
- if (hashData.tv) {
5748
- try {
5749
- storedTagVersions = JSON.parse(hashData.tv);
5750
- } catch {
5751
- }
5752
- }
5753
- const tags = Object.keys(storedTagVersions);
5754
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5755
- for (let i = 0; i < tags.length; i++) {
5756
- if (currentVers[i] > storedTagVersions[tags[i]]) {
5757
- isStale = true;
5758
- break;
5759
- }
5760
- }
5761
- if (isStale) {
5762
- const setAtMs = parseInt(hashData.t, 10) || 0;
5763
- this._deleteIfStale(k, setAtMs);
5764
- } else {
5765
- const parsed = await this._decryptAndDeserialize(hashData.d);
5766
- this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
5767
- this.counters.l2Hits++;
5768
- this.opts.onHit?.(cacheKey, "l2");
5769
- this.logger.debug("L2 hit (Redis hash)", { cacheKey });
5770
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5771
- if (this.opts.frozen) deepFreeze(parsed);
5772
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
5773
- }
5774
- }
5775
- } else {
5776
- const raw = this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
5777
- const redisElapsed = performance.now() - redisStart;
5778
- this.watchdog.recordRedis(redisElapsed);
5779
- this.cb.onSuccess();
5780
- if (raw) {
5781
- const parsed = await this._decryptAndDeserialize(raw);
5782
- this.l1.set(k, parsed, ttlMs, priority);
5783
- this.counters.l2Hits++;
5784
- this.opts.onHit?.(cacheKey, "l2");
5785
- this.logger.debug("L2 hit (Redis)", { cacheKey });
5786
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5787
- if (this.opts.frozen) deepFreeze(parsed);
5788
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
5897
+ const redisHit = await this._readRedisEntry(client, k, true);
5898
+ const redisElapsed = performance.now() - redisStart;
5899
+ this.watchdog.recordRedis(redisElapsed);
5900
+ this.cb.onSuccess();
5901
+ if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
5902
+ const parsed = redisHit.value;
5903
+ if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
5904
+ this.logger.debug("Aborting L2 promotion \u2014 key was mutated or deleted during Redis read", { cacheKey });
5905
+ span.setAttribute("cache.aborted_mutation_race", true);
5906
+ const current = this.l1.get(k);
5907
+ const liveVal = current && !current.isStale && current.value !== void 0 ? current.value : parsed;
5908
+ if (this.opts.frozen) deepFreeze(liveVal);
5909
+ return this.opts.cloneStrategy === "structuredClone" && liveVal != null && typeof liveVal === "object" ? structuredClone(liveVal) : liveVal;
5789
5910
  }
5911
+ this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, redisHit.tagVersions);
5912
+ this.counters.l2Hits++;
5913
+ this.opts.onHit?.(cacheKey, "l2");
5914
+ this.logger.debug(redisHit.tagVersions ? "L2 hit (Redis hash)" : "L2 hit (Redis)", { cacheKey });
5915
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5916
+ if (this.opts.frozen) deepFreeze(parsed);
5917
+ return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
5790
5918
  }
5791
5919
  } catch (err) {
5792
5920
  this.cb.onFailure();
@@ -5848,20 +5976,20 @@ var CacheService = class _CacheService {
5848
5976
  if (this.opts.frozen) deepFreeze(data);
5849
5977
  return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
5850
5978
  }
5851
- this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
5979
+ const writeTs = Date.now();
5980
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs);
5852
5981
  if (!this._redisDisabled) {
5853
5982
  try {
5854
5983
  const client = await this.getRedis();
5855
5984
  const serialized = JSON.stringify(data);
5856
5985
  const toStore = await this._serializeAndEncrypt(serialized);
5857
5986
  const ttlSec = Math.ceil(effectiveTtl / 1e3);
5858
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
5859
- const now = Date.now();
5987
+ if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
5860
5988
  const tx = client.multi();
5861
5989
  tx.hset(k, {
5862
5990
  d: toStore,
5863
- t: String(now),
5864
- tv: JSON.stringify(activeTagVersions)
5991
+ t: String(writeTs),
5992
+ tv: JSON.stringify(activeTagVersions ?? {})
5865
5993
  });
5866
5994
  tx.expire(k, ttlSec);
5867
5995
  await tx.exec();
@@ -5999,20 +6127,20 @@ var CacheService = class _CacheService {
5999
6127
  this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
6000
6128
  return;
6001
6129
  }
6002
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
6130
+ const writeTs = Date.now();
6131
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs);
6003
6132
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6004
6133
  try {
6005
6134
  const client = await this.getRedis();
6006
6135
  const s = JSON.stringify(data);
6007
6136
  const stored = await this._serializeAndEncrypt(s);
6008
6137
  const ttlSec = Math.ceil(ttlMs / 1e3);
6009
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
6010
- const now = Date.now();
6138
+ if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
6011
6139
  const tx = client.multi();
6012
6140
  tx.hset(cacheKey, {
6013
6141
  d: stored,
6014
- t: String(now),
6015
- tv: JSON.stringify(activeTagVersions)
6142
+ t: String(writeTs),
6143
+ tv: JSON.stringify(activeTagVersions ?? {})
6016
6144
  });
6017
6145
  tx.expire(cacheKey, ttlSec);
6018
6146
  await tx.exec();
@@ -6069,16 +6197,23 @@ var CacheService = class _CacheService {
6069
6197
  await this._registerTags(k, tagsToRegister, ttlSeconds);
6070
6198
  }
6071
6199
  }
6072
- this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
6073
- if (opts?.dependsOn?.length) {
6074
- for (const pattern of opts.dependsOn) {
6075
- const nsPattern = this.nk(pattern);
6076
- let deps = this.dependencyIndex.get(nsPattern);
6077
- if (!deps) {
6078
- deps = /* @__PURE__ */ new Set();
6079
- this.dependencyIndex.set(nsPattern, deps);
6200
+ const writeTs = Date.now();
6201
+ this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions, writeTs);
6202
+ if (opts?.dependsOn !== void 0) {
6203
+ this._removeKeyDependencies(k);
6204
+ if (opts.dependsOn.length > 0) {
6205
+ const nsPatterns = [];
6206
+ for (const pattern of opts.dependsOn) {
6207
+ const nsPattern = this.nk(pattern);
6208
+ nsPatterns.push(nsPattern);
6209
+ let deps = this.dependencyIndex.get(nsPattern);
6210
+ if (!deps) {
6211
+ deps = /* @__PURE__ */ new Set();
6212
+ this.dependencyIndex.set(nsPattern, deps);
6213
+ }
6214
+ deps.add(k);
6080
6215
  }
6081
- deps.add(k);
6216
+ this.keyDependencies.set(k, nsPatterns);
6082
6217
  }
6083
6218
  }
6084
6219
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
@@ -6087,13 +6222,12 @@ var CacheService = class _CacheService {
6087
6222
  const s = JSON.stringify(data);
6088
6223
  const stored = await this._serializeAndEncrypt(s);
6089
6224
  const ttlSec = Math.ceil(ttlMs / 1e3);
6090
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
6091
- const now = Date.now();
6225
+ if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
6092
6226
  const tx = client.multi();
6093
6227
  tx.hset(k, {
6094
6228
  d: stored,
6095
- t: String(now),
6096
- tv: JSON.stringify(activeTagVersions)
6229
+ t: String(writeTs),
6230
+ tv: JSON.stringify(activeTagVersions ?? {})
6097
6231
  });
6098
6232
  tx.expire(k, ttlSec);
6099
6233
  await tx.exec();
@@ -6128,7 +6262,18 @@ var CacheService = class _CacheService {
6128
6262
  * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
6129
6263
  */
6130
6264
  async _registerTags(k, tags, ttlSeconds) {
6131
- for (const tag of tags) {
6265
+ this._removeKeyTags(k);
6266
+ const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
6267
+ const expiresAt = Date.now() + effectiveTtl * 1e3;
6268
+ if (this.keyTags.size >= 1e5 && !this.keyTags.has(k)) {
6269
+ this._sweepExpiredMetadata();
6270
+ if (this.keyTags.size >= 1e5) {
6271
+ const oldestKey = this.keyTags.keys().next().value;
6272
+ if (oldestKey !== void 0) this._removeKeyTags(oldestKey);
6273
+ }
6274
+ }
6275
+ const uniqueTags = Array.from(new Set(tags));
6276
+ for (const tag of uniqueTags) {
6132
6277
  const tagKey = this.nk(`_tag_:${tag}`);
6133
6278
  let members = this.tagIndex.get(tagKey);
6134
6279
  if (!members) {
@@ -6137,14 +6282,15 @@ var CacheService = class _CacheService {
6137
6282
  }
6138
6283
  members.add(k);
6139
6284
  }
6285
+ this.keyTags.set(k, { tags: uniqueTags, expiresAt });
6140
6286
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6141
6287
  try {
6142
6288
  const client = await this.getRedis();
6143
6289
  const pl = client.pipeline();
6144
- for (const tag of tags) {
6290
+ for (const tag of uniqueTags) {
6145
6291
  const tagKey = this.nk(`_tag_:${tag}`);
6146
6292
  pl.sadd(tagKey, k);
6147
- pl.expire(tagKey, ttlSeconds + 3600);
6293
+ pl.expire(tagKey, effectiveTtl + 3600);
6148
6294
  }
6149
6295
  await pl.exec();
6150
6296
  this.cb.onSuccess();
@@ -6183,6 +6329,13 @@ var CacheService = class _CacheService {
6183
6329
  }
6184
6330
  this._addPatternTombstone(pfx);
6185
6331
  this.l1.deletePattern(k);
6332
+ this._removePrefixFromIndices(pfx);
6333
+ for (const ktKey of Array.from(this.keyTags.keys())) {
6334
+ if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
6335
+ }
6336
+ for (const kdKey of Array.from(this.keyDependencies.keys())) {
6337
+ if (this._matchesGlob(kdKey, k)) this._removeKeyDependencies(kdKey);
6338
+ }
6186
6339
  } else {
6187
6340
  this._bumpKeyMutation(k);
6188
6341
  this.inflight.delete(k);
@@ -6195,15 +6348,16 @@ var CacheService = class _CacheService {
6195
6348
  this._pendingDiskDeletes.delete(k);
6196
6349
  }
6197
6350
  });
6351
+ this._removeKeyTags(k);
6198
6352
  this._cascadeDependencies(k);
6199
- for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
6353
+ this._removeKeyDependencies(k);
6200
6354
  }
6201
6355
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6202
6356
  try {
6203
6357
  const client = await this.getRedis();
6204
6358
  if (isPattern) {
6205
6359
  const keys = await this._scanKeys(client, k);
6206
- if (keys.length > 0) await client.del(...keys);
6360
+ await this._deleteRedisKeys(client, keys);
6207
6361
  } else {
6208
6362
  if (this.opts.autoPipeline && this.pipeliner) {
6209
6363
  await this.pipeliner.del(k);
@@ -6265,6 +6419,15 @@ var CacheService = class _CacheService {
6265
6419
  entry.value++;
6266
6420
  return entry.value;
6267
6421
  }
6422
+ if (this._l1Counters.size >= 5e4 && !this._l1Counters.has(k)) {
6423
+ for (const [ck, cv] of this._l1Counters) {
6424
+ if (cv.expiresAt <= now) this._l1Counters.delete(ck);
6425
+ }
6426
+ if (this._l1Counters.size >= 5e4) {
6427
+ const oldest = this._l1Counters.keys().next().value;
6428
+ if (oldest !== void 0) this._l1Counters.delete(oldest);
6429
+ }
6430
+ }
6268
6431
  this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
6269
6432
  return 1;
6270
6433
  }
@@ -6311,6 +6474,7 @@ var CacheService = class _CacheService {
6311
6474
  }
6312
6475
  this._addPatternTombstone(pfx);
6313
6476
  this.l1.deletePattern(k);
6477
+ this._removePrefixFromIndices(pfx);
6314
6478
  } else {
6315
6479
  this._globalEpoch++;
6316
6480
  this.inflight.clear();
@@ -6319,7 +6483,10 @@ var CacheService = class _CacheService {
6319
6483
  if (!this._diskDisabled) this.disk.clear();
6320
6484
  this._l1Counters.clear();
6321
6485
  this.tagIndex.clear();
6486
+ this.keyTags.clear();
6322
6487
  this.tagVersions.clear();
6488
+ this.dependencyIndex.clear();
6489
+ this.keyDependencies.clear();
6323
6490
  this._pendingDiskDeletes.clear();
6324
6491
  this._keyMutationEpochs.clear();
6325
6492
  }
@@ -6328,7 +6495,7 @@ var CacheService = class _CacheService {
6328
6495
  const client = await this.getRedis();
6329
6496
  const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
6330
6497
  const keys = await this._scanKeys(client, pattern);
6331
- if (keys.length > 0) await client.del(...keys);
6498
+ await this._deleteRedisKeys(client, keys);
6332
6499
  } catch (err) {
6333
6500
  this.logger.debug("clear: Redis unavailable", { error: err.message });
6334
6501
  }
@@ -6471,6 +6638,10 @@ var CacheService = class _CacheService {
6471
6638
  this._assertActive("touch");
6472
6639
  const k = this.nk(cacheKey);
6473
6640
  const hit = this.l1.touch(k, newTtlSeconds * 1e3);
6641
+ if (hit) {
6642
+ const kt = this.keyTags.get(k);
6643
+ if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1e3;
6644
+ }
6474
6645
  if (hit && !this._redisDisabled) {
6475
6646
  try {
6476
6647
  const client = await this.getRedis();
@@ -6498,6 +6669,10 @@ var CacheService = class _CacheService {
6498
6669
  if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
6499
6670
  return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
6500
6671
  }
6672
+ _prepareReadValue(val) {
6673
+ if (this.opts.frozen) deepFreeze(val);
6674
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6675
+ }
6501
6676
  /**
6502
6677
  * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
6503
6678
  * Returns the cached value if found and valid, or `null` if absent / expired.
@@ -6511,11 +6686,13 @@ var CacheService = class _CacheService {
6511
6686
  const k = this.nk(cacheKey);
6512
6687
  const l1Hit = this.l1.get(k);
6513
6688
  if (l1Hit !== null) {
6514
- this.counters.gets++;
6515
- this.counters.l1Hits++;
6516
- const val = l1Hit.value;
6517
- if (this.opts.frozen) deepFreeze(val);
6518
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6689
+ if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
6690
+ this._deleteIfStale(k, l1Hit.setAt ?? 0);
6691
+ } else {
6692
+ this.counters.gets++;
6693
+ this.counters.l1Hits++;
6694
+ return this._prepareReadValue(l1Hit.value);
6695
+ }
6519
6696
  }
6520
6697
  if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
6521
6698
  if (this._isTombstonedByPattern(k)) {
@@ -6530,18 +6707,20 @@ var CacheService = class _CacheService {
6530
6707
  this.watchdog.recordDisk(diskElapsed);
6531
6708
  this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6532
6709
  if (diskHit !== null) {
6533
- const promoted = this.l1.importEntries(
6534
- [{ key: k, entry: diskHit }],
6535
- this.opts.forbiddenSnapshotPrefixes
6536
- );
6537
- if (promoted > 0) {
6538
- const l1Check = this.l1.get(k);
6539
- if (l1Check !== null) {
6540
- this.counters.gets++;
6541
- this.counters.diskHits++;
6542
- const val = l1Check.value;
6543
- if (this.opts.frozen) deepFreeze(val);
6544
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6710
+ if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
6711
+ this.disk.delete(k);
6712
+ } else {
6713
+ const promoted = this.l1.importEntries(
6714
+ [{ key: k, entry: diskHit }],
6715
+ this.opts.forbiddenSnapshotPrefixes
6716
+ );
6717
+ if (promoted > 0) {
6718
+ const l1Check = this.l1.get(k);
6719
+ if (l1Check !== null) {
6720
+ this.counters.gets++;
6721
+ this.counters.diskHits++;
6722
+ return this._prepareReadValue(l1Check.value);
6723
+ }
6545
6724
  }
6546
6725
  }
6547
6726
  }
@@ -6551,17 +6730,16 @@ var CacheService = class _CacheService {
6551
6730
  try {
6552
6731
  const client = await this.getRedis();
6553
6732
  const redisStart = performance.now();
6554
- const raw = await client.get(k);
6733
+ const redisHit = await this._readRedisEntry(client, k);
6555
6734
  const redisElapsed = performance.now() - redisStart;
6556
6735
  this.watchdog.recordRedis(redisElapsed);
6557
- if (raw !== null) {
6558
- const parsed = await this._decryptAndDeserialize(raw);
6559
- this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
6736
+ this.cb.onSuccess();
6737
+ if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
6738
+ const parsed = redisHit.value;
6739
+ this.l1.set(k, parsed, 6e4, inferPriority(cacheKey), void 0, void 0, redisHit.tagVersions);
6560
6740
  this.counters.gets++;
6561
6741
  this.counters.l2Hits++;
6562
- this.cb.onSuccess();
6563
- if (this.opts.frozen) deepFreeze(parsed);
6564
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
6742
+ return this._prepareReadValue(parsed);
6565
6743
  }
6566
6744
  } catch (err) {
6567
6745
  this.cb.onFailure();
@@ -6589,12 +6767,20 @@ var CacheService = class _CacheService {
6589
6767
  const result = Array.from({ length: keys.length });
6590
6768
  const missIndexes = [];
6591
6769
  const missKeys = [];
6770
+ const now = Date.now();
6592
6771
  for (let i = 0; i < keys.length; i++) {
6593
6772
  const k = this.nk(keys[i]);
6594
6773
  const entry = this.l1.getEntry(k);
6595
- if (entry && entry.expiresAt > Date.now()) {
6596
- result[i] = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
6597
- this.counters.l1Hits++;
6774
+ if (entry && entry.expiresAt > now) {
6775
+ if (await this._isGenerationalEntryStale(entry.tagVersions)) {
6776
+ this._deleteIfStale(k, entry.setAt ?? 0);
6777
+ missIndexes.push(i);
6778
+ missKeys.push(keys[i]);
6779
+ } else {
6780
+ const val = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
6781
+ result[i] = this._prepareReadValue(val);
6782
+ this.counters.l1Hits++;
6783
+ }
6598
6784
  } else {
6599
6785
  missIndexes.push(i);
6600
6786
  missKeys.push(keys[i]);
@@ -6615,23 +6801,57 @@ var CacheService = class _CacheService {
6615
6801
  const client = await this.getRedis();
6616
6802
  const nsKeys = missKeys.map((k) => this.nk(k));
6617
6803
  const pipeline = client.multi();
6618
- for (const nk of nsKeys) pipeline.get(nk);
6804
+ const useHashPipeline = this.opts.tagStrategy === "generational" && typeof pipeline.hgetall === "function";
6805
+ for (const nk of nsKeys) {
6806
+ if (useHashPipeline) {
6807
+ pipeline.hgetall(nk);
6808
+ } else {
6809
+ pipeline.get(nk);
6810
+ }
6811
+ }
6619
6812
  const redisStart = performance.now();
6620
6813
  const raws = await pipeline.exec();
6621
6814
  const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
6622
6815
  this.watchdog.recordRedis(redisElapsed);
6623
6816
  this.cb.onSuccess();
6624
6817
  for (let j = 0; j < missKeys.length; j++) {
6625
- const raw = raws[j] ? raws[j][1] : null;
6818
+ const tuple = raws[j];
6819
+ const err = tuple ? tuple[0] : null;
6820
+ const rawVal = tuple ? tuple[1] : null;
6626
6821
  const idx = missIndexes[j];
6627
- if (raw) {
6628
- const parsed = await this._decryptAndDeserialize(raw);
6629
- const k = nsKeys[j];
6822
+ const k = nsKeys[j];
6823
+ let parsed;
6824
+ let tagVersions;
6825
+ let hit = false;
6826
+ if (useHashPipeline) {
6827
+ if (err && err.message?.includes("WRONGTYPE")) {
6828
+ const fallbackRaw = await client.get(k);
6829
+ if (fallbackRaw) {
6830
+ parsed = await this._decryptAndDeserialize(fallbackRaw);
6831
+ hit = true;
6832
+ }
6833
+ } else if (!err && typeof rawVal === "string") {
6834
+ parsed = await this._decryptAndDeserialize(rawVal);
6835
+ hit = true;
6836
+ } else if (!err && rawVal && typeof rawVal === "object" && rawVal.d) {
6837
+ const hashHit = await this._parseGenerationalRedisHash(k, rawVal);
6838
+ if (hashHit && !hashHit.stale && hashHit.value !== void 0) {
6839
+ parsed = hashHit.value;
6840
+ tagVersions = hashHit.tagVersions;
6841
+ hit = true;
6842
+ }
6843
+ }
6844
+ } else if (!err && rawVal) {
6845
+ parsed = await this._decryptAndDeserialize(rawVal);
6846
+ hit = true;
6847
+ }
6848
+ if (hit && parsed !== void 0) {
6630
6849
  const p = priority ?? inferPriority(missKeys[j]);
6631
- this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
6850
+ const ttlVal = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
6851
+ this.l1.set(k, parsed, this._jitterTtl(ttlVal * 1e3), p, void 0, void 0, tagVersions);
6632
6852
  this.counters.l2Hits++;
6633
6853
  l2HitCount++;
6634
- result[idx] = parsed;
6854
+ result[idx] = this._prepareReadValue(parsed);
6635
6855
  missIndexes[j] = -1;
6636
6856
  missKeys[j] = "";
6637
6857
  }
@@ -6665,6 +6885,10 @@ var CacheService = class _CacheService {
6665
6885
  this.watchdog.recordDisk(diskElapsed);
6666
6886
  this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6667
6887
  if (diskHit !== null) {
6888
+ if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
6889
+ this.disk.delete(k);
6890
+ continue;
6891
+ }
6668
6892
  const promoted = this.l1.importEntries(
6669
6893
  [{ key: k, entry: diskHit }],
6670
6894
  this.opts.forbiddenSnapshotPrefixes
@@ -6673,7 +6897,7 @@ var CacheService = class _CacheService {
6673
6897
  const l1Check = this.l1.get(k);
6674
6898
  if (l1Check !== null) {
6675
6899
  this.counters.diskHits++;
6676
- result[missIndexes[j]] = l1Check.value;
6900
+ result[missIndexes[j]] = this._prepareReadValue(l1Check.value);
6677
6901
  missIndexes.splice(j, 1);
6678
6902
  missKeys.splice(j, 1);
6679
6903
  }
@@ -6898,6 +7122,136 @@ var CacheService = class _CacheService {
6898
7122
  }
6899
7123
  return matched;
6900
7124
  }
7125
+ async _publishTagInvalidation(op, key, tagVersion) {
7126
+ if (this.opts.awaitInvalidationBackplane) {
7127
+ await this.publishInvalidation(op, key, tagVersion, false, true);
7128
+ } else {
7129
+ void this.publishInvalidation(op, key, tagVersion, false, true);
7130
+ }
7131
+ }
7132
+ _removeTagMembersLocal(keys) {
7133
+ const keyList = Array.isArray(keys) ? keys : Array.from(keys);
7134
+ for (const k of keyList) {
7135
+ this.l1.delete(k);
7136
+ this._bumpKeyMutation(k);
7137
+ this._removeKeyTags(k);
7138
+ this._removeKeyDependencies(k);
7139
+ this._pendingDiskDeletes.add(k);
7140
+ setImmediate(() => {
7141
+ try {
7142
+ if (!this._diskDisabled) this.disk.delete(k);
7143
+ } finally {
7144
+ this._pendingDiskDeletes.delete(k);
7145
+ }
7146
+ });
7147
+ }
7148
+ }
7149
+ /**
7150
+ * Executes invalidation for a single already-resolved concrete tag without
7151
+ * wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
7152
+ */
7153
+ async _invalidateConcreteTag(tag) {
7154
+ if (this.opts.tagStrategy === "generational") {
7155
+ let newVer = 1;
7156
+ if (!this._redisDisabled) {
7157
+ try {
7158
+ const client = await this.getRedis();
7159
+ newVer = await client.incr(this.nk(`tag_ver:${tag}`));
7160
+ } catch (err) {
7161
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7162
+ const current = this.tagVersions.get(tag)?.version ?? 0;
7163
+ newVer = current + 1;
7164
+ }
7165
+ } else {
7166
+ const current = this.tagVersions.get(tag)?.version ?? 0;
7167
+ newVer = current + 1;
7168
+ }
7169
+ this._setLocalTagVersion(tag, newVer, performance.now());
7170
+ await this._publishTagInvalidation("tag_incr", tag, newVer);
7171
+ return;
7172
+ }
7173
+ const tagKey = this.nk(`_tag_:${tag}`);
7174
+ const members = Array.from(this.tagIndex.get(tagKey) ?? []);
7175
+ this.tagIndex.delete(tagKey);
7176
+ this._removeTagMembersLocal(members);
7177
+ if (!this._redisDisabled) {
7178
+ try {
7179
+ const client = await this.getRedis();
7180
+ const redisMembers = await client.smembers(tagKey);
7181
+ const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers, tagKey])];
7182
+ await this._deleteRedisKeys(client, toDelete);
7183
+ } catch (err) {
7184
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7185
+ }
7186
+ }
7187
+ }
7188
+ /**
7189
+ * Executes invalidation for an array of already-resolved concrete tags
7190
+ * without re-entering wildcard/cascade resolution or invalidateTag().
7191
+ */
7192
+ async _invalidateConcreteTags(tags) {
7193
+ if (tags.length === 0) return;
7194
+ if (tags.length === 1) {
7195
+ await this._invalidateConcreteTag(tags[0]);
7196
+ return;
7197
+ }
7198
+ if (this.opts.tagStrategy === "generational") {
7199
+ const now = performance.now();
7200
+ if (!this._redisDisabled) {
7201
+ try {
7202
+ const client = await this.getRedis();
7203
+ const pl = client.pipeline();
7204
+ for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
7205
+ const results = await pl.exec();
7206
+ for (let i = 0; i < tags.length; i++) {
7207
+ const [err, newVer] = results[i] ?? [null, null];
7208
+ const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
7209
+ this._setLocalTagVersion(tags[i], ver, now);
7210
+ await this._publishTagInvalidation("tag_incr", tags[i], ver);
7211
+ }
7212
+ return;
7213
+ } catch (err) {
7214
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7215
+ }
7216
+ }
7217
+ for (const tag of tags) {
7218
+ const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
7219
+ this._setLocalTagVersion(tag, ver, now);
7220
+ await this._publishTagInvalidation("tag_incr", tag, ver);
7221
+ }
7222
+ return;
7223
+ }
7224
+ const tagKeys = [];
7225
+ const allMembers = /* @__PURE__ */ new Set();
7226
+ for (const tag of tags) {
7227
+ const tagKey = this.nk(`_tag_:${tag}`);
7228
+ tagKeys.push(tagKey);
7229
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
7230
+ for (const k of members) allMembers.add(k);
7231
+ this.tagIndex.delete(tagKey);
7232
+ }
7233
+ this._removeTagMembersLocal(allMembers);
7234
+ if (!this._redisDisabled) {
7235
+ try {
7236
+ const client = await this.getRedis();
7237
+ const pl = client.pipeline();
7238
+ for (const tagKey of tagKeys) pl.smembers(tagKey);
7239
+ const smResults = await pl.exec();
7240
+ const toDelete = [...allMembers];
7241
+ for (const [err, redisMembers] of smResults) {
7242
+ if (!err && redisMembers) {
7243
+ for (const k of redisMembers) {
7244
+ if (!allMembers.has(k)) toDelete.push(k);
7245
+ }
7246
+ }
7247
+ }
7248
+ const keysToRemove = [...toDelete, ...tagKeys];
7249
+ await this._deleteRedisKeys(client, keysToRemove);
7250
+ } catch (err) {
7251
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7252
+ }
7253
+ }
7254
+ }
6901
7255
  /**
6902
7256
  * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
6903
7257
  * Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
@@ -6933,68 +7287,13 @@ var CacheService = class _CacheService {
6933
7287
  const delim = this.opts.tagHierarchyDelimiter;
6934
7288
  const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
6935
7289
  if (matchedTags.size > 0) {
6936
- await this.invalidateTags(Array.from(matchedTags));
7290
+ await this._invalidateConcreteTags(Array.from(matchedTags));
6937
7291
  }
6938
7292
  const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
6939
- if (this.opts.awaitInvalidationBackplane) {
6940
- await this.publishInvalidation(op, broadcastPattern, void 0, false, true);
6941
- } else {
6942
- void this.publishInvalidation(op, broadcastPattern, void 0, false, true);
6943
- }
6944
- return;
6945
- }
6946
- if (this.opts.tagStrategy === "generational") {
6947
- let newVer = 1;
6948
- if (!this._redisDisabled) {
6949
- try {
6950
- const client = await this.getRedis();
6951
- newVer = await client.incr(this.nk(`tag_ver:${tag}`));
6952
- } catch (err) {
6953
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
6954
- const current = this.tagVersions.get(tag)?.version ?? 0;
6955
- newVer = current + 1;
6956
- }
6957
- } else {
6958
- const current = this.tagVersions.get(tag)?.version ?? 0;
6959
- newVer = current + 1;
6960
- }
6961
- this._setLocalTagVersion(tag, newVer, performance.now());
6962
- if (this.opts.awaitInvalidationBackplane) {
6963
- await this.publishInvalidation("tag_incr", tag, newVer, false, true);
6964
- } else {
6965
- void this.publishInvalidation("tag_incr", tag, newVer, false, true);
6966
- }
7293
+ await this._publishTagInvalidation(op, broadcastPattern);
6967
7294
  return;
6968
7295
  }
6969
- const tagKey = this.nk(`_tag_:${tag}`);
6970
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
6971
- for (const k of members) {
6972
- this.l1.delete(k);
6973
- this._bumpKeyMutation(k);
6974
- this._pendingDiskDeletes.add(k);
6975
- setImmediate(() => {
6976
- try {
6977
- if (!this._diskDisabled) this.disk.delete(k);
6978
- } finally {
6979
- this._pendingDiskDeletes.delete(k);
6980
- }
6981
- });
6982
- }
6983
- this.tagIndex.delete(tagKey);
6984
- if (!this._redisDisabled) {
6985
- try {
6986
- const client = await this.getRedis();
6987
- const redisMembers = await client.smembers(tagKey);
6988
- const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
6989
- if (toDelete.length > 0) {
6990
- await client.del(...toDelete, tagKey);
6991
- } else {
6992
- await client.del(tagKey);
6993
- }
6994
- } catch (err) {
6995
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
6996
- }
6997
- }
7296
+ await this._invalidateConcreteTag(tag);
6998
7297
  } catch (err) {
6999
7298
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
7000
7299
  span.recordException?.(err);
@@ -7021,96 +7320,28 @@ var CacheService = class _CacheService {
7021
7320
  const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
7022
7321
  if (hasWildcards || shouldCascade) {
7023
7322
  const allResolvedTags = /* @__PURE__ */ new Set();
7323
+ const broadcastPatterns = /* @__PURE__ */ new Set();
7324
+ const delim = this.opts.tagHierarchyDelimiter;
7024
7325
  for (const t of tags) {
7025
- if (isWildcardTag(t) || shouldCascade) {
7326
+ const tIsPattern = isWildcardTag(t);
7327
+ if (tIsPattern || shouldCascade) {
7328
+ broadcastPatterns.add(tIsPattern ? t : `${t}${delim}*`);
7026
7329
  const resolved = await this._resolveMatchingTags(t, shouldCascade);
7027
7330
  for (const rt of resolved) allResolvedTags.add(rt);
7028
7331
  } else {
7029
7332
  allResolvedTags.add(t);
7030
7333
  }
7031
7334
  }
7032
- if (allResolvedTags.size === 0) return;
7033
- tags = Array.from(allResolvedTags);
7034
- }
7035
- if (tags.length === 1) {
7036
- await this.invalidateTag(tags[0], opts);
7037
- return;
7038
- }
7039
- if (this.opts.tagStrategy === "generational") {
7040
- const now = performance.now();
7041
- if (!this._redisDisabled) {
7042
- try {
7043
- const client = await this.getRedis();
7044
- const pl = client.pipeline();
7045
- for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
7046
- const results = await pl.exec();
7047
- for (let i = 0; i < tags.length; i++) {
7048
- const [err, newVer] = results[i] ?? [null, null];
7049
- const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
7050
- this._setLocalTagVersion(tags[i], ver, now);
7051
- if (this.opts.awaitInvalidationBackplane) {
7052
- await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7053
- } else {
7054
- void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7055
- }
7056
- }
7057
- return;
7058
- } catch (err) {
7059
- this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7060
- }
7335
+ if (allResolvedTags.size > 0) {
7336
+ await this._invalidateConcreteTags(Array.from(allResolvedTags));
7061
7337
  }
7062
- for (const tag of tags) {
7063
- const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
7064
- this._setLocalTagVersion(tag, ver, now);
7065
- if (this.opts.awaitInvalidationBackplane) {
7066
- await this.publishInvalidation("tag_incr", tag, ver, false, true);
7067
- } else {
7068
- void this.publishInvalidation("tag_incr", tag, ver, false, true);
7069
- }
7338
+ const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
7339
+ for (const pattern of broadcastPatterns) {
7340
+ await this._publishTagInvalidation(op, pattern);
7070
7341
  }
7071
7342
  return;
7072
7343
  }
7073
- const tagKeys = [];
7074
- const allMembers = /* @__PURE__ */ new Set();
7075
- for (const tag of tags) {
7076
- const tagKey = this.nk(`_tag_:${tag}`);
7077
- tagKeys.push(tagKey);
7078
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
7079
- for (const k of members) allMembers.add(k);
7080
- this.tagIndex.delete(tagKey);
7081
- }
7082
- for (const k of allMembers) {
7083
- this.l1.delete(k);
7084
- this._bumpKeyMutation(k);
7085
- this._pendingDiskDeletes.add(k);
7086
- setImmediate(() => {
7087
- try {
7088
- if (!this._diskDisabled) this.disk.delete(k);
7089
- } finally {
7090
- this._pendingDiskDeletes.delete(k);
7091
- }
7092
- });
7093
- }
7094
- if (!this._redisDisabled) {
7095
- try {
7096
- const client = await this.getRedis();
7097
- const pl = client.pipeline();
7098
- for (const tagKey of tagKeys) pl.smembers(tagKey);
7099
- const smResults = await pl.exec();
7100
- const toDelete = [...allMembers];
7101
- for (const [err, redisMembers] of smResults) {
7102
- if (!err && redisMembers) {
7103
- for (const k of redisMembers) {
7104
- if (!allMembers.has(k)) toDelete.push(k);
7105
- }
7106
- }
7107
- }
7108
- const keysToRemove = [...toDelete, ...tagKeys];
7109
- if (keysToRemove.length > 0) await client.del(...keysToRemove);
7110
- } catch (err) {
7111
- this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7112
- }
7113
- }
7344
+ await this._invalidateConcreteTags(Array.from(new Set(tags)));
7114
7345
  }
7115
7346
  /**
7116
7347
  * Get the current generational tag version for a tag (synced with Redis when due).
@@ -7677,6 +7908,13 @@ var CacheService = class _CacheService {
7677
7908
  this._destroyed = true;
7678
7909
  this._pendingDiskDeletes.clear();
7679
7910
  this._keyMutationEpochs.clear();
7911
+ this.inflight.clear();
7912
+ this.revalidating.clear();
7913
+ this._l1Counters.clear();
7914
+ this.tagIndex.clear();
7915
+ this.keyTags.clear();
7916
+ this.dependencyIndex.clear();
7917
+ this.keyDependencies.clear();
7680
7918
  const g = globalThis;
7681
7919
  const key = _CacheService.globalKey(this.opts);
7682
7920
  if (g[key] === this) {