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
@@ -1463,7 +1463,7 @@ var init_smart_memory_cache = __esm({
1463
1463
  };
1464
1464
  return hit;
1465
1465
  }
1466
- set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
1466
+ set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions, setAt) {
1467
1467
  const packed = this.codec.encode(data);
1468
1468
  const size = packed.byteLength;
1469
1469
  this.compressions++;
@@ -1500,7 +1500,7 @@ var init_smart_memory_cache = __esm({
1500
1500
  priority,
1501
1501
  ttlMs,
1502
1502
  delta,
1503
- setAt: now2,
1503
+ setAt: setAt ?? now2,
1504
1504
  tagVersions
1505
1505
  });
1506
1506
  }
@@ -1528,7 +1528,7 @@ var init_smart_memory_cache = __esm({
1528
1528
  }
1529
1529
  const now = Date.now();
1530
1530
  const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
1531
- 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 });
1531
+ 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 });
1532
1532
  if (!existingEntry) this.bloom.add(key);
1533
1533
  this.maybeRebuildBloom();
1534
1534
  this.totalSize += size;
@@ -4142,6 +4142,8 @@ return 0
4142
4142
  _l1Counters = /* @__PURE__ */ new Map();
4143
4143
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
4144
4144
  tagIndex = /* @__PURE__ */ new Map();
4145
+ /** Reverse index of namespaced key → { tags, expiresAt } for bounded cleanup on eviction/delete */
4146
+ keyTags = /* @__PURE__ */ new Map();
4145
4147
  /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
4146
4148
  tagVersions = /* @__PURE__ */ new Map();
4147
4149
  /**
@@ -4149,6 +4151,9 @@ return 0
4149
4151
  * When an exact-key delete matches a registered pattern, all dependents are cascaded.
4150
4152
  */
4151
4153
  dependencyIndex = /* @__PURE__ */ new Map();
4154
+ /** Reverse index of namespaced dependent key → source glob patterns */
4155
+ keyDependencies = /* @__PURE__ */ new Map();
4156
+ _cgroupMemoryLimit;
4152
4157
  redis = null;
4153
4158
  redisConnecting = null;
4154
4159
  cb;
@@ -4218,6 +4223,84 @@ return 0
4218
4223
  _getKeyMutationEpoch(namespacedKey) {
4219
4224
  return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
4220
4225
  }
4226
+ _removeKeyTags(namespacedKey) {
4227
+ const entry = this.keyTags.get(namespacedKey);
4228
+ if (!entry) return;
4229
+ for (const tag of entry.tags) {
4230
+ const tagKey = this.nk(`_tag_:${tag}`);
4231
+ const members = this.tagIndex.get(tagKey);
4232
+ if (members) {
4233
+ members.delete(namespacedKey);
4234
+ if (members.size === 0) this.tagIndex.delete(tagKey);
4235
+ }
4236
+ }
4237
+ this.keyTags.delete(namespacedKey);
4238
+ }
4239
+ _removeKeyDependencies(namespacedKey) {
4240
+ const patterns = this.keyDependencies.get(namespacedKey);
4241
+ if (patterns) {
4242
+ for (const pat of patterns) {
4243
+ const deps = this.dependencyIndex.get(pat);
4244
+ if (deps) {
4245
+ deps.delete(namespacedKey);
4246
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
4247
+ }
4248
+ }
4249
+ this.keyDependencies.delete(namespacedKey);
4250
+ } else if (this.dependencyIndex.size > 0) {
4251
+ for (const [pat, deps] of this.dependencyIndex) {
4252
+ deps.delete(namespacedKey);
4253
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
4254
+ }
4255
+ }
4256
+ }
4257
+ _handleL1Eviction(namespacedKey, reason) {
4258
+ const spilledToDisk = !this._diskDisabled && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
4259
+ if (!spilledToDisk) {
4260
+ this._removeKeyTags(namespacedKey);
4261
+ this._removeKeyDependencies(namespacedKey);
4262
+ }
4263
+ }
4264
+ _removePrefixFromIndices(prefix) {
4265
+ for (const k of Array.from(this.keyTags.keys())) {
4266
+ if (k.startsWith(prefix)) this._removeKeyTags(k);
4267
+ }
4268
+ for (const k of Array.from(this.keyDependencies.keys())) {
4269
+ if (k.startsWith(prefix)) this._removeKeyDependencies(k);
4270
+ }
4271
+ for (const k of Array.from(this._l1Counters.keys())) {
4272
+ if (k.startsWith(prefix)) this._l1Counters.delete(k);
4273
+ }
4274
+ }
4275
+ _sweepExpiredMetadata() {
4276
+ const now = Date.now();
4277
+ for (const [k, c] of this._l1Counters) {
4278
+ if (c.expiresAt <= now) this._l1Counters.delete(k);
4279
+ }
4280
+ for (const [k, meta] of this.keyTags) {
4281
+ if (meta.expiresAt <= now && !this.l1.has(k)) {
4282
+ this._removeKeyTags(k);
4283
+ this._removeKeyDependencies(k);
4284
+ }
4285
+ }
4286
+ }
4287
+ _runOomCheck() {
4288
+ const heap = import_node_v82.default.getHeapStatistics();
4289
+ const heapUsed = heap.used_heap_size / heap.heap_size_limit;
4290
+ const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? process.memoryUsage().rss / this._cgroupMemoryLimit : 0;
4291
+ const used = Math.max(heapUsed, cgroupUsed);
4292
+ if (used >= this.opts.oomHeapThreshold) {
4293
+ const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
4294
+ this.counters.oomEvictions++;
4295
+ this.counters.oomLastAt = Date.now();
4296
+ this.logger.warn("tricache OOM guard: emergency L1 eviction", {
4297
+ heapUsedPct: Math.round(heapUsed * 100),
4298
+ cgroupUsedPct: cgroupUsed > 0 ? Math.round(cgroupUsed * 100) : void 0,
4299
+ threshold: Math.round(this.opts.oomHeapThreshold * 100),
4300
+ evicted
4301
+ });
4302
+ }
4303
+ }
4221
4304
  _ipcServer;
4222
4305
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
4223
4306
  _subDisconnectedAt = null;
@@ -4264,6 +4347,7 @@ return 0
4264
4347
  constructor(options = {}) {
4265
4348
  const logger = options.logger ?? consoleLogger;
4266
4349
  this.logger = logger;
4350
+ this._cgroupMemoryLimit = readCgroupMemoryLimit();
4267
4351
  const ns = options.namespace?.trim() ?? "";
4268
4352
  const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
4269
4353
  this.enc = new CacheEncryption(
@@ -4447,7 +4531,10 @@ return 0
4447
4531
  void this.disk.save(key, entry);
4448
4532
  });
4449
4533
  },
4450
- onEviction: options.onEviction,
4534
+ onEviction: (key, reason) => {
4535
+ this._handleL1Eviction(key, reason);
4536
+ options.onEviction?.(key, reason);
4537
+ },
4451
4538
  logger
4452
4539
  });
4453
4540
  if (!this.snapshotLoaded) {
@@ -4485,6 +4572,7 @@ return 0
4485
4572
  }
4486
4573
  this.cleanupInterval = setInterval(() => {
4487
4574
  const cleaned = this.l1.cleanup();
4575
+ this._sweepExpiredMetadata();
4488
4576
  if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
4489
4577
  }, 5 * 60 * 1e3);
4490
4578
  if (this.cleanupInterval.unref) this.cleanupInterval.unref();
@@ -4497,18 +4585,7 @@ return 0
4497
4585
  }
4498
4586
  if (this.opts.oomProtection) {
4499
4587
  this.oomInterval = setInterval(() => {
4500
- const heap = import_node_v82.default.getHeapStatistics();
4501
- const used = heap.used_heap_size / heap.heap_size_limit;
4502
- if (used >= this.opts.oomHeapThreshold) {
4503
- const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
4504
- this.counters.oomEvictions++;
4505
- this.counters.oomLastAt = Date.now();
4506
- this.logger.warn("tricache OOM guard: emergency L1 eviction", {
4507
- heapUsedPct: Math.round(used * 100),
4508
- threshold: Math.round(this.opts.oomHeapThreshold * 100),
4509
- evicted
4510
- });
4511
- }
4588
+ this._runOomCheck();
4512
4589
  }, this.opts.oomCheckIntervalMs);
4513
4590
  if (this.oomInterval.unref) this.oomInterval.unref();
4514
4591
  }
@@ -4983,7 +5060,7 @@ return 0
4983
5060
  else if (f === "src") src = v;
4984
5061
  else if (f === "tagVersion") tagVersionRaw = v;
4985
5062
  }
4986
- const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
5063
+ const validOp = op === "del" || op === "del-glob" || op === "tag_incr" || op === "tag_pattern_incr" || op === "tag_pattern_del";
4987
5064
  if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
4988
5065
  this.logger.warn("Backplane: rejected invalid stream entry", {
4989
5066
  op: String(op).slice(0, 40),
@@ -5245,6 +5322,72 @@ return 0
5245
5322
  }
5246
5323
  this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
5247
5324
  }
5325
+ async _isGenerationalEntryStale(tagVersions) {
5326
+ if (this.opts.tagStrategy !== "generational" || !tagVersions) return false;
5327
+ const tags = Object.keys(tagVersions);
5328
+ if (tags.length === 0) return false;
5329
+ const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5330
+ for (let i = 0; i < tags.length; i++) {
5331
+ if (currentVers[i] > tagVersions[tags[i]]) return true;
5332
+ }
5333
+ return false;
5334
+ }
5335
+ async _deleteRedisKeys(client, keys) {
5336
+ if (keys.length === 0) return;
5337
+ const CHUNK_SIZE = 1e3;
5338
+ if (client instanceof import_ioredis.Cluster) {
5339
+ for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
5340
+ const chunk = keys.slice(i, i + CHUNK_SIZE);
5341
+ const pl = client.pipeline();
5342
+ for (const k of chunk) pl.del(k);
5343
+ await pl.exec();
5344
+ }
5345
+ return;
5346
+ }
5347
+ for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
5348
+ const chunk = keys.slice(i, i + CHUNK_SIZE);
5349
+ await client.del(...chunk);
5350
+ }
5351
+ }
5352
+ async _parseGenerationalRedisHash(k, hashData) {
5353
+ if (!hashData || !hashData.d) return null;
5354
+ let storedTagVersions = {};
5355
+ if (hashData.tv) {
5356
+ try {
5357
+ storedTagVersions = JSON.parse(hashData.tv);
5358
+ } catch {
5359
+ }
5360
+ }
5361
+ if (await this._isGenerationalEntryStale(storedTagVersions)) {
5362
+ const setAtMs = parseInt(hashData.t, 10) || 0;
5363
+ this._deleteIfStale(k, setAtMs);
5364
+ return { stale: true };
5365
+ }
5366
+ const value = await this._decryptAndDeserialize(hashData.d);
5367
+ return { value, tagVersions: storedTagVersions, stale: false };
5368
+ }
5369
+ async _readRedisEntry(client, k, allowAutoPipeline = false) {
5370
+ if (this.opts.tagStrategy === "generational" && typeof client.hgetall === "function") {
5371
+ try {
5372
+ const hashData = await client.hgetall(k);
5373
+ if (typeof hashData === "string") {
5374
+ const value2 = await this._decryptAndDeserialize(hashData);
5375
+ return { value: value2, stale: false };
5376
+ }
5377
+ if (hashData && hashData.d) {
5378
+ return await this._parseGenerationalRedisHash(k, hashData);
5379
+ }
5380
+ return null;
5381
+ } catch (err) {
5382
+ const msg = err instanceof Error ? err.message : String(err);
5383
+ if (!msg.includes("WRONGTYPE")) throw err;
5384
+ }
5385
+ }
5386
+ const raw = allowAutoPipeline && this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
5387
+ if (raw == null) return null;
5388
+ const value = await this._decryptAndDeserialize(raw);
5389
+ return { value, stale: false };
5390
+ }
5248
5391
  async _getTagVersion(tag) {
5249
5392
  const now = performance.now();
5250
5393
  const local = this.tagVersions.get(tag);
@@ -5382,8 +5525,8 @@ return 0
5382
5525
  return client;
5383
5526
  }
5384
5527
  this.redisConnecting = (async () => {
5528
+ let client = null;
5385
5529
  try {
5386
- let client;
5387
5530
  if (this.opts.redisClusterNodes?.length) {
5388
5531
  client = new import_ioredis.Cluster(this.opts.redisClusterNodes, {
5389
5532
  redisOptions: {
@@ -5446,14 +5589,45 @@ return 0
5446
5589
  });
5447
5590
  client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
5448
5591
  }
5592
+ const pendingClient = client;
5449
5593
  await new Promise((resolve, reject) => {
5450
- client.once("ready", resolve);
5451
- client.once("error", (e) => {
5594
+ let settled = false;
5595
+ const cleanupListeners = () => {
5596
+ pendingClient.removeListener?.("ready", onReady);
5597
+ pendingClient.removeListener?.("error", onError);
5598
+ };
5599
+ const onReady = () => {
5600
+ if (settled) return;
5601
+ settled = true;
5602
+ clearTimeout(timer);
5603
+ cleanupListeners();
5604
+ resolve();
5605
+ };
5606
+ const onError = (e) => {
5607
+ if (settled) return;
5608
+ settled = true;
5609
+ clearTimeout(timer);
5610
+ cleanupListeners();
5452
5611
  this._checkAndLogResp3Hint(e);
5453
5612
  reject(e);
5454
- });
5455
- setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
5613
+ };
5614
+ const timer = setTimeout(() => {
5615
+ if (settled) return;
5616
+ settled = true;
5617
+ cleanupListeners();
5618
+ reject(new Error("Redis connection timeout"));
5619
+ }, 15e3);
5620
+ if (timer.unref) timer.unref();
5621
+ pendingClient.once("ready", onReady);
5622
+ pendingClient.once("error", onError);
5456
5623
  });
5624
+ if (this._destroyed) {
5625
+ try {
5626
+ client.disconnect();
5627
+ } catch {
5628
+ }
5629
+ this._assertActive("getRedis");
5630
+ }
5457
5631
  this.cb.onSuccess();
5458
5632
  this.redis = client;
5459
5633
  this.pipeliner = new AutoPipeliner(client, {
@@ -5463,6 +5637,10 @@ return 0
5463
5637
  this.redisConnecting = null;
5464
5638
  return client;
5465
5639
  } catch (err) {
5640
+ try {
5641
+ client?.disconnect();
5642
+ } catch {
5643
+ }
5466
5644
  this.cb.onFailure();
5467
5645
  this.redisConnecting = null;
5468
5646
  this._checkAndLogResp3Hint(err);
@@ -5706,17 +5884,7 @@ return 0
5706
5884
  const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
5707
5885
  const l1Hit = this.l1.get(k);
5708
5886
  if (l1Hit !== null) {
5709
- let isGenerationalStale = false;
5710
- if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
5711
- const tags = Object.keys(l1Hit.tagVersions);
5712
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5713
- for (let i = 0; i < tags.length; i++) {
5714
- if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
5715
- isGenerationalStale = true;
5716
- break;
5717
- }
5718
- }
5719
- }
5887
+ const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
5720
5888
  if (isGenerationalStale) {
5721
5889
  this._deleteIfStale(k, l1Hit.setAt ?? 0);
5722
5890
  } else {
@@ -5802,17 +5970,7 @@ return 0
5802
5970
  this.watchdog.recordDisk(diskElapsed);
5803
5971
  this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
5804
5972
  if (diskHit !== null) {
5805
- let isDiskStale = false;
5806
- if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
5807
- const tags = Object.keys(diskHit.tagVersions);
5808
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5809
- for (let i = 0; i < tags.length; i++) {
5810
- if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
5811
- isDiskStale = true;
5812
- break;
5813
- }
5814
- }
5815
- }
5973
+ const isDiskStale = await this._isGenerationalEntryStale(diskHit.tagVersions);
5816
5974
  if (isDiskStale) {
5817
5975
  this.disk.delete(k);
5818
5976
  } else {
@@ -5840,57 +5998,27 @@ return 0
5840
5998
  try {
5841
5999
  const client = await this.getRedis();
5842
6000
  const redisStart = performance.now();
5843
- if (this.opts.tagStrategy === "generational") {
5844
- const hashData = await client.hgetall(k);
5845
- const redisElapsed = performance.now() - redisStart;
5846
- this.watchdog.recordRedis(redisElapsed);
5847
- this.cb.onSuccess();
5848
- if (hashData && hashData.d) {
5849
- let isStale = false;
5850
- let storedTagVersions = {};
5851
- if (hashData.tv) {
5852
- try {
5853
- storedTagVersions = JSON.parse(hashData.tv);
5854
- } catch {
5855
- }
5856
- }
5857
- const tags = Object.keys(storedTagVersions);
5858
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5859
- for (let i = 0; i < tags.length; i++) {
5860
- if (currentVers[i] > storedTagVersions[tags[i]]) {
5861
- isStale = true;
5862
- break;
5863
- }
5864
- }
5865
- if (isStale) {
5866
- const setAtMs = parseInt(hashData.t, 10) || 0;
5867
- this._deleteIfStale(k, setAtMs);
5868
- } else {
5869
- const parsed = await this._decryptAndDeserialize(hashData.d);
5870
- this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
5871
- this.counters.l2Hits++;
5872
- this.opts.onHit?.(cacheKey, "l2");
5873
- this.logger.debug("L2 hit (Redis hash)", { cacheKey });
5874
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5875
- if (this.opts.frozen) deepFreeze(parsed);
5876
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
5877
- }
5878
- }
5879
- } else {
5880
- const raw = this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
5881
- const redisElapsed = performance.now() - redisStart;
5882
- this.watchdog.recordRedis(redisElapsed);
5883
- this.cb.onSuccess();
5884
- if (raw) {
5885
- const parsed = await this._decryptAndDeserialize(raw);
5886
- this.l1.set(k, parsed, ttlMs, priority);
5887
- this.counters.l2Hits++;
5888
- this.opts.onHit?.(cacheKey, "l2");
5889
- this.logger.debug("L2 hit (Redis)", { cacheKey });
5890
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5891
- if (this.opts.frozen) deepFreeze(parsed);
5892
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
6001
+ const redisHit = await this._readRedisEntry(client, k, true);
6002
+ const redisElapsed = performance.now() - redisStart;
6003
+ this.watchdog.recordRedis(redisElapsed);
6004
+ this.cb.onSuccess();
6005
+ if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
6006
+ const parsed = redisHit.value;
6007
+ if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
6008
+ this.logger.debug("Aborting L2 promotion \u2014 key was mutated or deleted during Redis read", { cacheKey });
6009
+ span.setAttribute("cache.aborted_mutation_race", true);
6010
+ const current = this.l1.get(k);
6011
+ const liveVal = current && !current.isStale && current.value !== void 0 ? current.value : parsed;
6012
+ if (this.opts.frozen) deepFreeze(liveVal);
6013
+ return this.opts.cloneStrategy === "structuredClone" && liveVal != null && typeof liveVal === "object" ? structuredClone(liveVal) : liveVal;
5893
6014
  }
6015
+ this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, redisHit.tagVersions);
6016
+ this.counters.l2Hits++;
6017
+ this.opts.onHit?.(cacheKey, "l2");
6018
+ this.logger.debug(redisHit.tagVersions ? "L2 hit (Redis hash)" : "L2 hit (Redis)", { cacheKey });
6019
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
6020
+ if (this.opts.frozen) deepFreeze(parsed);
6021
+ return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
5894
6022
  }
5895
6023
  } catch (err) {
5896
6024
  this.cb.onFailure();
@@ -5952,20 +6080,20 @@ return 0
5952
6080
  if (this.opts.frozen) deepFreeze(data);
5953
6081
  return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
5954
6082
  }
5955
- this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
6083
+ const writeTs = Date.now();
6084
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs);
5956
6085
  if (!this._redisDisabled) {
5957
6086
  try {
5958
6087
  const client = await this.getRedis();
5959
6088
  const serialized = JSON.stringify(data);
5960
6089
  const toStore = await this._serializeAndEncrypt(serialized);
5961
6090
  const ttlSec = Math.ceil(effectiveTtl / 1e3);
5962
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
5963
- const now = Date.now();
6091
+ if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
5964
6092
  const tx = client.multi();
5965
6093
  tx.hset(k, {
5966
6094
  d: toStore,
5967
- t: String(now),
5968
- tv: JSON.stringify(activeTagVersions)
6095
+ t: String(writeTs),
6096
+ tv: JSON.stringify(activeTagVersions ?? {})
5969
6097
  });
5970
6098
  tx.expire(k, ttlSec);
5971
6099
  await tx.exec();
@@ -6103,20 +6231,20 @@ return 0
6103
6231
  this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
6104
6232
  return;
6105
6233
  }
6106
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
6234
+ const writeTs = Date.now();
6235
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs);
6107
6236
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6108
6237
  try {
6109
6238
  const client = await this.getRedis();
6110
6239
  const s = JSON.stringify(data);
6111
6240
  const stored = await this._serializeAndEncrypt(s);
6112
6241
  const ttlSec = Math.ceil(ttlMs / 1e3);
6113
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
6114
- const now = Date.now();
6242
+ if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
6115
6243
  const tx = client.multi();
6116
6244
  tx.hset(cacheKey, {
6117
6245
  d: stored,
6118
- t: String(now),
6119
- tv: JSON.stringify(activeTagVersions)
6246
+ t: String(writeTs),
6247
+ tv: JSON.stringify(activeTagVersions ?? {})
6120
6248
  });
6121
6249
  tx.expire(cacheKey, ttlSec);
6122
6250
  await tx.exec();
@@ -6173,16 +6301,23 @@ return 0
6173
6301
  await this._registerTags(k, tagsToRegister, ttlSeconds);
6174
6302
  }
6175
6303
  }
6176
- this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
6177
- if (opts?.dependsOn?.length) {
6178
- for (const pattern of opts.dependsOn) {
6179
- const nsPattern = this.nk(pattern);
6180
- let deps = this.dependencyIndex.get(nsPattern);
6181
- if (!deps) {
6182
- deps = /* @__PURE__ */ new Set();
6183
- this.dependencyIndex.set(nsPattern, deps);
6304
+ const writeTs = Date.now();
6305
+ this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions, writeTs);
6306
+ if (opts?.dependsOn !== void 0) {
6307
+ this._removeKeyDependencies(k);
6308
+ if (opts.dependsOn.length > 0) {
6309
+ const nsPatterns = [];
6310
+ for (const pattern of opts.dependsOn) {
6311
+ const nsPattern = this.nk(pattern);
6312
+ nsPatterns.push(nsPattern);
6313
+ let deps = this.dependencyIndex.get(nsPattern);
6314
+ if (!deps) {
6315
+ deps = /* @__PURE__ */ new Set();
6316
+ this.dependencyIndex.set(nsPattern, deps);
6317
+ }
6318
+ deps.add(k);
6184
6319
  }
6185
- deps.add(k);
6320
+ this.keyDependencies.set(k, nsPatterns);
6186
6321
  }
6187
6322
  }
6188
6323
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
@@ -6191,13 +6326,12 @@ return 0
6191
6326
  const s = JSON.stringify(data);
6192
6327
  const stored = await this._serializeAndEncrypt(s);
6193
6328
  const ttlSec = Math.ceil(ttlMs / 1e3);
6194
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
6195
- const now = Date.now();
6329
+ if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
6196
6330
  const tx = client.multi();
6197
6331
  tx.hset(k, {
6198
6332
  d: stored,
6199
- t: String(now),
6200
- tv: JSON.stringify(activeTagVersions)
6333
+ t: String(writeTs),
6334
+ tv: JSON.stringify(activeTagVersions ?? {})
6201
6335
  });
6202
6336
  tx.expire(k, ttlSec);
6203
6337
  await tx.exec();
@@ -6232,7 +6366,18 @@ return 0
6232
6366
  * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
6233
6367
  */
6234
6368
  async _registerTags(k, tags, ttlSeconds) {
6235
- for (const tag of tags) {
6369
+ this._removeKeyTags(k);
6370
+ const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
6371
+ const expiresAt = Date.now() + effectiveTtl * 1e3;
6372
+ if (this.keyTags.size >= 1e5 && !this.keyTags.has(k)) {
6373
+ this._sweepExpiredMetadata();
6374
+ if (this.keyTags.size >= 1e5) {
6375
+ const oldestKey = this.keyTags.keys().next().value;
6376
+ if (oldestKey !== void 0) this._removeKeyTags(oldestKey);
6377
+ }
6378
+ }
6379
+ const uniqueTags = Array.from(new Set(tags));
6380
+ for (const tag of uniqueTags) {
6236
6381
  const tagKey = this.nk(`_tag_:${tag}`);
6237
6382
  let members = this.tagIndex.get(tagKey);
6238
6383
  if (!members) {
@@ -6241,14 +6386,15 @@ return 0
6241
6386
  }
6242
6387
  members.add(k);
6243
6388
  }
6389
+ this.keyTags.set(k, { tags: uniqueTags, expiresAt });
6244
6390
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6245
6391
  try {
6246
6392
  const client = await this.getRedis();
6247
6393
  const pl = client.pipeline();
6248
- for (const tag of tags) {
6394
+ for (const tag of uniqueTags) {
6249
6395
  const tagKey = this.nk(`_tag_:${tag}`);
6250
6396
  pl.sadd(tagKey, k);
6251
- pl.expire(tagKey, ttlSeconds + 3600);
6397
+ pl.expire(tagKey, effectiveTtl + 3600);
6252
6398
  }
6253
6399
  await pl.exec();
6254
6400
  this.cb.onSuccess();
@@ -6287,6 +6433,13 @@ return 0
6287
6433
  }
6288
6434
  this._addPatternTombstone(pfx);
6289
6435
  this.l1.deletePattern(k);
6436
+ this._removePrefixFromIndices(pfx);
6437
+ for (const ktKey of Array.from(this.keyTags.keys())) {
6438
+ if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
6439
+ }
6440
+ for (const kdKey of Array.from(this.keyDependencies.keys())) {
6441
+ if (this._matchesGlob(kdKey, k)) this._removeKeyDependencies(kdKey);
6442
+ }
6290
6443
  } else {
6291
6444
  this._bumpKeyMutation(k);
6292
6445
  this.inflight.delete(k);
@@ -6299,15 +6452,16 @@ return 0
6299
6452
  this._pendingDiskDeletes.delete(k);
6300
6453
  }
6301
6454
  });
6455
+ this._removeKeyTags(k);
6302
6456
  this._cascadeDependencies(k);
6303
- for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
6457
+ this._removeKeyDependencies(k);
6304
6458
  }
6305
6459
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6306
6460
  try {
6307
6461
  const client = await this.getRedis();
6308
6462
  if (isPattern) {
6309
6463
  const keys = await this._scanKeys(client, k);
6310
- if (keys.length > 0) await client.del(...keys);
6464
+ await this._deleteRedisKeys(client, keys);
6311
6465
  } else {
6312
6466
  if (this.opts.autoPipeline && this.pipeliner) {
6313
6467
  await this.pipeliner.del(k);
@@ -6369,6 +6523,15 @@ return 0
6369
6523
  entry.value++;
6370
6524
  return entry.value;
6371
6525
  }
6526
+ if (this._l1Counters.size >= 5e4 && !this._l1Counters.has(k)) {
6527
+ for (const [ck, cv] of this._l1Counters) {
6528
+ if (cv.expiresAt <= now) this._l1Counters.delete(ck);
6529
+ }
6530
+ if (this._l1Counters.size >= 5e4) {
6531
+ const oldest = this._l1Counters.keys().next().value;
6532
+ if (oldest !== void 0) this._l1Counters.delete(oldest);
6533
+ }
6534
+ }
6372
6535
  this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
6373
6536
  return 1;
6374
6537
  }
@@ -6415,6 +6578,7 @@ return 0
6415
6578
  }
6416
6579
  this._addPatternTombstone(pfx);
6417
6580
  this.l1.deletePattern(k);
6581
+ this._removePrefixFromIndices(pfx);
6418
6582
  } else {
6419
6583
  this._globalEpoch++;
6420
6584
  this.inflight.clear();
@@ -6423,7 +6587,10 @@ return 0
6423
6587
  if (!this._diskDisabled) this.disk.clear();
6424
6588
  this._l1Counters.clear();
6425
6589
  this.tagIndex.clear();
6590
+ this.keyTags.clear();
6426
6591
  this.tagVersions.clear();
6592
+ this.dependencyIndex.clear();
6593
+ this.keyDependencies.clear();
6427
6594
  this._pendingDiskDeletes.clear();
6428
6595
  this._keyMutationEpochs.clear();
6429
6596
  }
@@ -6432,7 +6599,7 @@ return 0
6432
6599
  const client = await this.getRedis();
6433
6600
  const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
6434
6601
  const keys = await this._scanKeys(client, pattern);
6435
- if (keys.length > 0) await client.del(...keys);
6602
+ await this._deleteRedisKeys(client, keys);
6436
6603
  } catch (err) {
6437
6604
  this.logger.debug("clear: Redis unavailable", { error: err.message });
6438
6605
  }
@@ -6575,6 +6742,10 @@ return 0
6575
6742
  this._assertActive("touch");
6576
6743
  const k = this.nk(cacheKey);
6577
6744
  const hit = this.l1.touch(k, newTtlSeconds * 1e3);
6745
+ if (hit) {
6746
+ const kt = this.keyTags.get(k);
6747
+ if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1e3;
6748
+ }
6578
6749
  if (hit && !this._redisDisabled) {
6579
6750
  try {
6580
6751
  const client = await this.getRedis();
@@ -6602,6 +6773,10 @@ return 0
6602
6773
  if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
6603
6774
  return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
6604
6775
  }
6776
+ _prepareReadValue(val) {
6777
+ if (this.opts.frozen) deepFreeze(val);
6778
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6779
+ }
6605
6780
  /**
6606
6781
  * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
6607
6782
  * Returns the cached value if found and valid, or `null` if absent / expired.
@@ -6615,11 +6790,13 @@ return 0
6615
6790
  const k = this.nk(cacheKey);
6616
6791
  const l1Hit = this.l1.get(k);
6617
6792
  if (l1Hit !== null) {
6618
- this.counters.gets++;
6619
- this.counters.l1Hits++;
6620
- const val = l1Hit.value;
6621
- if (this.opts.frozen) deepFreeze(val);
6622
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6793
+ if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
6794
+ this._deleteIfStale(k, l1Hit.setAt ?? 0);
6795
+ } else {
6796
+ this.counters.gets++;
6797
+ this.counters.l1Hits++;
6798
+ return this._prepareReadValue(l1Hit.value);
6799
+ }
6623
6800
  }
6624
6801
  if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
6625
6802
  if (this._isTombstonedByPattern(k)) {
@@ -6634,18 +6811,20 @@ return 0
6634
6811
  this.watchdog.recordDisk(diskElapsed);
6635
6812
  this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6636
6813
  if (diskHit !== null) {
6637
- const promoted = this.l1.importEntries(
6638
- [{ key: k, entry: diskHit }],
6639
- this.opts.forbiddenSnapshotPrefixes
6640
- );
6641
- if (promoted > 0) {
6642
- const l1Check = this.l1.get(k);
6643
- if (l1Check !== null) {
6644
- this.counters.gets++;
6645
- this.counters.diskHits++;
6646
- const val = l1Check.value;
6647
- if (this.opts.frozen) deepFreeze(val);
6648
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6814
+ if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
6815
+ this.disk.delete(k);
6816
+ } else {
6817
+ const promoted = this.l1.importEntries(
6818
+ [{ key: k, entry: diskHit }],
6819
+ this.opts.forbiddenSnapshotPrefixes
6820
+ );
6821
+ if (promoted > 0) {
6822
+ const l1Check = this.l1.get(k);
6823
+ if (l1Check !== null) {
6824
+ this.counters.gets++;
6825
+ this.counters.diskHits++;
6826
+ return this._prepareReadValue(l1Check.value);
6827
+ }
6649
6828
  }
6650
6829
  }
6651
6830
  }
@@ -6655,17 +6834,16 @@ return 0
6655
6834
  try {
6656
6835
  const client = await this.getRedis();
6657
6836
  const redisStart = performance.now();
6658
- const raw = await client.get(k);
6837
+ const redisHit = await this._readRedisEntry(client, k);
6659
6838
  const redisElapsed = performance.now() - redisStart;
6660
6839
  this.watchdog.recordRedis(redisElapsed);
6661
- if (raw !== null) {
6662
- const parsed = await this._decryptAndDeserialize(raw);
6663
- this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
6840
+ this.cb.onSuccess();
6841
+ if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
6842
+ const parsed = redisHit.value;
6843
+ this.l1.set(k, parsed, 6e4, inferPriority(cacheKey), void 0, void 0, redisHit.tagVersions);
6664
6844
  this.counters.gets++;
6665
6845
  this.counters.l2Hits++;
6666
- this.cb.onSuccess();
6667
- if (this.opts.frozen) deepFreeze(parsed);
6668
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
6846
+ return this._prepareReadValue(parsed);
6669
6847
  }
6670
6848
  } catch (err) {
6671
6849
  this.cb.onFailure();
@@ -6693,12 +6871,20 @@ return 0
6693
6871
  const result = Array.from({ length: keys.length });
6694
6872
  const missIndexes = [];
6695
6873
  const missKeys = [];
6874
+ const now = Date.now();
6696
6875
  for (let i = 0; i < keys.length; i++) {
6697
6876
  const k = this.nk(keys[i]);
6698
6877
  const entry = this.l1.getEntry(k);
6699
- if (entry && entry.expiresAt > Date.now()) {
6700
- result[i] = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
6701
- this.counters.l1Hits++;
6878
+ if (entry && entry.expiresAt > now) {
6879
+ if (await this._isGenerationalEntryStale(entry.tagVersions)) {
6880
+ this._deleteIfStale(k, entry.setAt ?? 0);
6881
+ missIndexes.push(i);
6882
+ missKeys.push(keys[i]);
6883
+ } else {
6884
+ const val = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
6885
+ result[i] = this._prepareReadValue(val);
6886
+ this.counters.l1Hits++;
6887
+ }
6702
6888
  } else {
6703
6889
  missIndexes.push(i);
6704
6890
  missKeys.push(keys[i]);
@@ -6719,23 +6905,57 @@ return 0
6719
6905
  const client = await this.getRedis();
6720
6906
  const nsKeys = missKeys.map((k) => this.nk(k));
6721
6907
  const pipeline = client.multi();
6722
- for (const nk of nsKeys) pipeline.get(nk);
6908
+ const useHashPipeline = this.opts.tagStrategy === "generational" && typeof pipeline.hgetall === "function";
6909
+ for (const nk of nsKeys) {
6910
+ if (useHashPipeline) {
6911
+ pipeline.hgetall(nk);
6912
+ } else {
6913
+ pipeline.get(nk);
6914
+ }
6915
+ }
6723
6916
  const redisStart = performance.now();
6724
6917
  const raws = await pipeline.exec();
6725
6918
  const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
6726
6919
  this.watchdog.recordRedis(redisElapsed);
6727
6920
  this.cb.onSuccess();
6728
6921
  for (let j = 0; j < missKeys.length; j++) {
6729
- const raw = raws[j] ? raws[j][1] : null;
6922
+ const tuple = raws[j];
6923
+ const err = tuple ? tuple[0] : null;
6924
+ const rawVal = tuple ? tuple[1] : null;
6730
6925
  const idx = missIndexes[j];
6731
- if (raw) {
6732
- const parsed = await this._decryptAndDeserialize(raw);
6733
- const k = nsKeys[j];
6926
+ const k = nsKeys[j];
6927
+ let parsed;
6928
+ let tagVersions;
6929
+ let hit = false;
6930
+ if (useHashPipeline) {
6931
+ if (err && err.message?.includes("WRONGTYPE")) {
6932
+ const fallbackRaw = await client.get(k);
6933
+ if (fallbackRaw) {
6934
+ parsed = await this._decryptAndDeserialize(fallbackRaw);
6935
+ hit = true;
6936
+ }
6937
+ } else if (!err && typeof rawVal === "string") {
6938
+ parsed = await this._decryptAndDeserialize(rawVal);
6939
+ hit = true;
6940
+ } else if (!err && rawVal && typeof rawVal === "object" && rawVal.d) {
6941
+ const hashHit = await this._parseGenerationalRedisHash(k, rawVal);
6942
+ if (hashHit && !hashHit.stale && hashHit.value !== void 0) {
6943
+ parsed = hashHit.value;
6944
+ tagVersions = hashHit.tagVersions;
6945
+ hit = true;
6946
+ }
6947
+ }
6948
+ } else if (!err && rawVal) {
6949
+ parsed = await this._decryptAndDeserialize(rawVal);
6950
+ hit = true;
6951
+ }
6952
+ if (hit && parsed !== void 0) {
6734
6953
  const p = priority ?? inferPriority(missKeys[j]);
6735
- this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
6954
+ const ttlVal = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
6955
+ this.l1.set(k, parsed, this._jitterTtl(ttlVal * 1e3), p, void 0, void 0, tagVersions);
6736
6956
  this.counters.l2Hits++;
6737
6957
  l2HitCount++;
6738
- result[idx] = parsed;
6958
+ result[idx] = this._prepareReadValue(parsed);
6739
6959
  missIndexes[j] = -1;
6740
6960
  missKeys[j] = "";
6741
6961
  }
@@ -6769,6 +6989,10 @@ return 0
6769
6989
  this.watchdog.recordDisk(diskElapsed);
6770
6990
  this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6771
6991
  if (diskHit !== null) {
6992
+ if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
6993
+ this.disk.delete(k);
6994
+ continue;
6995
+ }
6772
6996
  const promoted = this.l1.importEntries(
6773
6997
  [{ key: k, entry: diskHit }],
6774
6998
  this.opts.forbiddenSnapshotPrefixes
@@ -6777,7 +7001,7 @@ return 0
6777
7001
  const l1Check = this.l1.get(k);
6778
7002
  if (l1Check !== null) {
6779
7003
  this.counters.diskHits++;
6780
- result[missIndexes[j]] = l1Check.value;
7004
+ result[missIndexes[j]] = this._prepareReadValue(l1Check.value);
6781
7005
  missIndexes.splice(j, 1);
6782
7006
  missKeys.splice(j, 1);
6783
7007
  }
@@ -7002,6 +7226,136 @@ return 0
7002
7226
  }
7003
7227
  return matched;
7004
7228
  }
7229
+ async _publishTagInvalidation(op, key, tagVersion) {
7230
+ if (this.opts.awaitInvalidationBackplane) {
7231
+ await this.publishInvalidation(op, key, tagVersion, false, true);
7232
+ } else {
7233
+ void this.publishInvalidation(op, key, tagVersion, false, true);
7234
+ }
7235
+ }
7236
+ _removeTagMembersLocal(keys) {
7237
+ const keyList = Array.isArray(keys) ? keys : Array.from(keys);
7238
+ for (const k of keyList) {
7239
+ this.l1.delete(k);
7240
+ this._bumpKeyMutation(k);
7241
+ this._removeKeyTags(k);
7242
+ this._removeKeyDependencies(k);
7243
+ this._pendingDiskDeletes.add(k);
7244
+ setImmediate(() => {
7245
+ try {
7246
+ if (!this._diskDisabled) this.disk.delete(k);
7247
+ } finally {
7248
+ this._pendingDiskDeletes.delete(k);
7249
+ }
7250
+ });
7251
+ }
7252
+ }
7253
+ /**
7254
+ * Executes invalidation for a single already-resolved concrete tag without
7255
+ * wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
7256
+ */
7257
+ async _invalidateConcreteTag(tag) {
7258
+ if (this.opts.tagStrategy === "generational") {
7259
+ let newVer = 1;
7260
+ if (!this._redisDisabled) {
7261
+ try {
7262
+ const client = await this.getRedis();
7263
+ newVer = await client.incr(this.nk(`tag_ver:${tag}`));
7264
+ } catch (err) {
7265
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7266
+ const current = this.tagVersions.get(tag)?.version ?? 0;
7267
+ newVer = current + 1;
7268
+ }
7269
+ } else {
7270
+ const current = this.tagVersions.get(tag)?.version ?? 0;
7271
+ newVer = current + 1;
7272
+ }
7273
+ this._setLocalTagVersion(tag, newVer, performance.now());
7274
+ await this._publishTagInvalidation("tag_incr", tag, newVer);
7275
+ return;
7276
+ }
7277
+ const tagKey = this.nk(`_tag_:${tag}`);
7278
+ const members = Array.from(this.tagIndex.get(tagKey) ?? []);
7279
+ this.tagIndex.delete(tagKey);
7280
+ this._removeTagMembersLocal(members);
7281
+ if (!this._redisDisabled) {
7282
+ try {
7283
+ const client = await this.getRedis();
7284
+ const redisMembers = await client.smembers(tagKey);
7285
+ const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers, tagKey])];
7286
+ await this._deleteRedisKeys(client, toDelete);
7287
+ } catch (err) {
7288
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7289
+ }
7290
+ }
7291
+ }
7292
+ /**
7293
+ * Executes invalidation for an array of already-resolved concrete tags
7294
+ * without re-entering wildcard/cascade resolution or invalidateTag().
7295
+ */
7296
+ async _invalidateConcreteTags(tags) {
7297
+ if (tags.length === 0) return;
7298
+ if (tags.length === 1) {
7299
+ await this._invalidateConcreteTag(tags[0]);
7300
+ return;
7301
+ }
7302
+ if (this.opts.tagStrategy === "generational") {
7303
+ const now = performance.now();
7304
+ if (!this._redisDisabled) {
7305
+ try {
7306
+ const client = await this.getRedis();
7307
+ const pl = client.pipeline();
7308
+ for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
7309
+ const results = await pl.exec();
7310
+ for (let i = 0; i < tags.length; i++) {
7311
+ const [err, newVer] = results[i] ?? [null, null];
7312
+ const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
7313
+ this._setLocalTagVersion(tags[i], ver, now);
7314
+ await this._publishTagInvalidation("tag_incr", tags[i], ver);
7315
+ }
7316
+ return;
7317
+ } catch (err) {
7318
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7319
+ }
7320
+ }
7321
+ for (const tag of tags) {
7322
+ const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
7323
+ this._setLocalTagVersion(tag, ver, now);
7324
+ await this._publishTagInvalidation("tag_incr", tag, ver);
7325
+ }
7326
+ return;
7327
+ }
7328
+ const tagKeys = [];
7329
+ const allMembers = /* @__PURE__ */ new Set();
7330
+ for (const tag of tags) {
7331
+ const tagKey = this.nk(`_tag_:${tag}`);
7332
+ tagKeys.push(tagKey);
7333
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
7334
+ for (const k of members) allMembers.add(k);
7335
+ this.tagIndex.delete(tagKey);
7336
+ }
7337
+ this._removeTagMembersLocal(allMembers);
7338
+ if (!this._redisDisabled) {
7339
+ try {
7340
+ const client = await this.getRedis();
7341
+ const pl = client.pipeline();
7342
+ for (const tagKey of tagKeys) pl.smembers(tagKey);
7343
+ const smResults = await pl.exec();
7344
+ const toDelete = [...allMembers];
7345
+ for (const [err, redisMembers] of smResults) {
7346
+ if (!err && redisMembers) {
7347
+ for (const k of redisMembers) {
7348
+ if (!allMembers.has(k)) toDelete.push(k);
7349
+ }
7350
+ }
7351
+ }
7352
+ const keysToRemove = [...toDelete, ...tagKeys];
7353
+ await this._deleteRedisKeys(client, keysToRemove);
7354
+ } catch (err) {
7355
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7356
+ }
7357
+ }
7358
+ }
7005
7359
  /**
7006
7360
  * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
7007
7361
  * Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
@@ -7037,68 +7391,13 @@ return 0
7037
7391
  const delim = this.opts.tagHierarchyDelimiter;
7038
7392
  const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
7039
7393
  if (matchedTags.size > 0) {
7040
- await this.invalidateTags(Array.from(matchedTags));
7394
+ await this._invalidateConcreteTags(Array.from(matchedTags));
7041
7395
  }
7042
7396
  const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
7043
- if (this.opts.awaitInvalidationBackplane) {
7044
- await this.publishInvalidation(op, broadcastPattern, void 0, false, true);
7045
- } else {
7046
- void this.publishInvalidation(op, broadcastPattern, void 0, false, true);
7047
- }
7397
+ await this._publishTagInvalidation(op, broadcastPattern);
7048
7398
  return;
7049
7399
  }
7050
- if (this.opts.tagStrategy === "generational") {
7051
- let newVer = 1;
7052
- if (!this._redisDisabled) {
7053
- try {
7054
- const client = await this.getRedis();
7055
- newVer = await client.incr(this.nk(`tag_ver:${tag}`));
7056
- } catch (err) {
7057
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7058
- const current = this.tagVersions.get(tag)?.version ?? 0;
7059
- newVer = current + 1;
7060
- }
7061
- } else {
7062
- const current = this.tagVersions.get(tag)?.version ?? 0;
7063
- newVer = current + 1;
7064
- }
7065
- this._setLocalTagVersion(tag, newVer, performance.now());
7066
- if (this.opts.awaitInvalidationBackplane) {
7067
- await this.publishInvalidation("tag_incr", tag, newVer, false, true);
7068
- } else {
7069
- void this.publishInvalidation("tag_incr", tag, newVer, false, true);
7070
- }
7071
- return;
7072
- }
7073
- const tagKey = this.nk(`_tag_:${tag}`);
7074
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
7075
- for (const k of members) {
7076
- this.l1.delete(k);
7077
- this._bumpKeyMutation(k);
7078
- this._pendingDiskDeletes.add(k);
7079
- setImmediate(() => {
7080
- try {
7081
- if (!this._diskDisabled) this.disk.delete(k);
7082
- } finally {
7083
- this._pendingDiskDeletes.delete(k);
7084
- }
7085
- });
7086
- }
7087
- this.tagIndex.delete(tagKey);
7088
- if (!this._redisDisabled) {
7089
- try {
7090
- const client = await this.getRedis();
7091
- const redisMembers = await client.smembers(tagKey);
7092
- const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
7093
- if (toDelete.length > 0) {
7094
- await client.del(...toDelete, tagKey);
7095
- } else {
7096
- await client.del(tagKey);
7097
- }
7098
- } catch (err) {
7099
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7100
- }
7101
- }
7400
+ await this._invalidateConcreteTag(tag);
7102
7401
  } catch (err) {
7103
7402
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
7104
7403
  span.recordException?.(err);
@@ -7125,96 +7424,28 @@ return 0
7125
7424
  const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
7126
7425
  if (hasWildcards || shouldCascade) {
7127
7426
  const allResolvedTags = /* @__PURE__ */ new Set();
7427
+ const broadcastPatterns = /* @__PURE__ */ new Set();
7428
+ const delim = this.opts.tagHierarchyDelimiter;
7128
7429
  for (const t of tags) {
7129
- if (isWildcardTag(t) || shouldCascade) {
7430
+ const tIsPattern = isWildcardTag(t);
7431
+ if (tIsPattern || shouldCascade) {
7432
+ broadcastPatterns.add(tIsPattern ? t : `${t}${delim}*`);
7130
7433
  const resolved = await this._resolveMatchingTags(t, shouldCascade);
7131
7434
  for (const rt of resolved) allResolvedTags.add(rt);
7132
7435
  } else {
7133
7436
  allResolvedTags.add(t);
7134
7437
  }
7135
7438
  }
7136
- if (allResolvedTags.size === 0) return;
7137
- tags = Array.from(allResolvedTags);
7138
- }
7139
- if (tags.length === 1) {
7140
- await this.invalidateTag(tags[0], opts);
7141
- return;
7142
- }
7143
- if (this.opts.tagStrategy === "generational") {
7144
- const now = performance.now();
7145
- if (!this._redisDisabled) {
7146
- try {
7147
- const client = await this.getRedis();
7148
- const pl = client.pipeline();
7149
- for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
7150
- const results = await pl.exec();
7151
- for (let i = 0; i < tags.length; i++) {
7152
- const [err, newVer] = results[i] ?? [null, null];
7153
- const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
7154
- this._setLocalTagVersion(tags[i], ver, now);
7155
- if (this.opts.awaitInvalidationBackplane) {
7156
- await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7157
- } else {
7158
- void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7159
- }
7160
- }
7161
- return;
7162
- } catch (err) {
7163
- this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7164
- }
7439
+ if (allResolvedTags.size > 0) {
7440
+ await this._invalidateConcreteTags(Array.from(allResolvedTags));
7165
7441
  }
7166
- for (const tag of tags) {
7167
- const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
7168
- this._setLocalTagVersion(tag, ver, now);
7169
- if (this.opts.awaitInvalidationBackplane) {
7170
- await this.publishInvalidation("tag_incr", tag, ver, false, true);
7171
- } else {
7172
- void this.publishInvalidation("tag_incr", tag, ver, false, true);
7173
- }
7442
+ const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
7443
+ for (const pattern of broadcastPatterns) {
7444
+ await this._publishTagInvalidation(op, pattern);
7174
7445
  }
7175
7446
  return;
7176
7447
  }
7177
- const tagKeys = [];
7178
- const allMembers = /* @__PURE__ */ new Set();
7179
- for (const tag of tags) {
7180
- const tagKey = this.nk(`_tag_:${tag}`);
7181
- tagKeys.push(tagKey);
7182
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
7183
- for (const k of members) allMembers.add(k);
7184
- this.tagIndex.delete(tagKey);
7185
- }
7186
- for (const k of allMembers) {
7187
- this.l1.delete(k);
7188
- this._bumpKeyMutation(k);
7189
- this._pendingDiskDeletes.add(k);
7190
- setImmediate(() => {
7191
- try {
7192
- if (!this._diskDisabled) this.disk.delete(k);
7193
- } finally {
7194
- this._pendingDiskDeletes.delete(k);
7195
- }
7196
- });
7197
- }
7198
- if (!this._redisDisabled) {
7199
- try {
7200
- const client = await this.getRedis();
7201
- const pl = client.pipeline();
7202
- for (const tagKey of tagKeys) pl.smembers(tagKey);
7203
- const smResults = await pl.exec();
7204
- const toDelete = [...allMembers];
7205
- for (const [err, redisMembers] of smResults) {
7206
- if (!err && redisMembers) {
7207
- for (const k of redisMembers) {
7208
- if (!allMembers.has(k)) toDelete.push(k);
7209
- }
7210
- }
7211
- }
7212
- const keysToRemove = [...toDelete, ...tagKeys];
7213
- if (keysToRemove.length > 0) await client.del(...keysToRemove);
7214
- } catch (err) {
7215
- this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7216
- }
7217
- }
7448
+ await this._invalidateConcreteTags(Array.from(new Set(tags)));
7218
7449
  }
7219
7450
  /**
7220
7451
  * Get the current generational tag version for a tag (synced with Redis when due).
@@ -7781,6 +8012,13 @@ return 0
7781
8012
  this._destroyed = true;
7782
8013
  this._pendingDiskDeletes.clear();
7783
8014
  this._keyMutationEpochs.clear();
8015
+ this.inflight.clear();
8016
+ this.revalidating.clear();
8017
+ this._l1Counters.clear();
8018
+ this.tagIndex.clear();
8019
+ this.keyTags.clear();
8020
+ this.dependencyIndex.clear();
8021
+ this.keyDependencies.clear();
7784
8022
  const g = globalThis;
7785
8023
  const key = _CacheService.globalKey(this.opts);
7786
8024
  if (g[key] === this) {