tricache 0.8.0 → 0.9.0

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 (44) hide show
  1. package/README.md +4 -2
  2. package/dashboards/prometheus-scrape.yml +18 -0
  3. package/dist/{cache-service-CyLdpo77.d.ts → cache-service-DVvroyqA.d.ts} +16 -1
  4. package/dist/{cache-service-5MZXFIGK.js → cache-service-KI5ACF3F.js} +1 -1
  5. package/dist/chunk-BQRURGGD.js +60 -0
  6. package/dist/chunk-IITRFWHY.js +196 -0
  7. package/dist/{chunk-6PQ5MOWR.js → chunk-PL5J3ZNT.js} +370 -81
  8. package/dist/cli.cjs +392 -84
  9. package/dist/cli.js +22 -4
  10. package/dist/dashboard/index.d.ts +2 -2
  11. package/dist/drizzle/index.cjs +350 -81
  12. package/dist/drizzle/index.d.ts +2 -2
  13. package/dist/drizzle/index.js +1 -1
  14. package/dist/edge/index.cjs +99 -38
  15. package/dist/edge/index.d.ts +3 -3
  16. package/dist/edge/index.js +5 -5
  17. package/dist/hono/index.cjs +7760 -0
  18. package/dist/hono/index.d.ts +91 -0
  19. package/dist/hono/index.js +185 -0
  20. package/dist/{hono-DQRS1Xd7.d.ts → hono-VA9A1m0I.d.ts} +3 -2
  21. package/dist/http/index.cjs +449 -119
  22. package/dist/http/index.d.ts +6 -30
  23. package/dist/http/index.js +9 -59
  24. package/dist/index.cjs +370 -81
  25. package/dist/index.d.ts +3 -3
  26. package/dist/index.js +1 -1
  27. package/dist/nestjs/index.cjs +350 -81
  28. package/dist/nestjs/index.d.ts +2 -2
  29. package/dist/nestjs/index.js +1 -1
  30. package/dist/next/index.cjs +350 -81
  31. package/dist/next/index.d.ts +2 -2
  32. package/dist/next/index.js +1 -1
  33. package/dist/prisma/index.d.ts +2 -2
  34. package/dist/{types-B6krw64X.d.ts → types-B_QkVwJ7.d.ts} +23 -0
  35. package/dist/utils-CEsU_Z0s.d.ts +27 -0
  36. package/package.json +16 -6
  37. package/src/cache-service.ts +302 -35
  38. package/src/cli.ts +21 -4
  39. package/src/edge/hono.ts +123 -42
  40. package/src/hono/index.ts +316 -0
  41. package/src/http/index.ts +5 -0
  42. package/src/ipc-telemetry.ts +29 -1
  43. package/src/types.ts +25 -0
  44. package/dist/chunk-ZTSWCFYO.js +0 -135
@@ -4000,6 +4000,52 @@ return 0
4000
4000
  streamClient = null;
4001
4001
  _lastStreamId = "$";
4002
4002
  _destroyed = false;
4003
+ _pendingDiskDeletes = /* @__PURE__ */ new Set();
4004
+ _globalEpoch = 0;
4005
+ _keyMutationEpochs = /* @__PURE__ */ new Map();
4006
+ /**
4007
+ * Pattern tombstones for disk tier.
4008
+ * Files in the disk tier are keyed by SHA-256 of namespacedKey.
4009
+ * Wildcard pattern deletes cannot scan the filesystem synchronously, so we maintain
4010
+ * pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
4011
+ */
4012
+ _patternTombstones = [];
4013
+ _addPatternTombstone(prefix) {
4014
+ const now = Date.now();
4015
+ while (this._patternTombstones.length > 0 && now - this._patternTombstones[0].createdAt > 36e5) {
4016
+ this._patternTombstones.shift();
4017
+ }
4018
+ if (this._patternTombstones.length >= 2e3) {
4019
+ this._patternTombstones.shift();
4020
+ }
4021
+ this._patternTombstones.push({ prefix, createdAt: now });
4022
+ }
4023
+ _isTombstonedByPattern(namespacedKey) {
4024
+ if (this._patternTombstones.length === 0) return false;
4025
+ for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
4026
+ if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
4027
+ return true;
4028
+ }
4029
+ }
4030
+ return false;
4031
+ }
4032
+ _assertActive(operation) {
4033
+ if (this._destroyed) {
4034
+ throw new Error(`TriCacheError: Cannot perform '${operation}' on a destroyed CacheService instance (namespace: '${this._namespace || "(default)"}').`);
4035
+ }
4036
+ }
4037
+ _bumpKeyMutation(namespacedKey) {
4038
+ const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
4039
+ this._keyMutationEpochs.set(namespacedKey, next);
4040
+ if (this._keyMutationEpochs.size > 5e4) {
4041
+ const oldest = this._keyMutationEpochs.keys().next().value;
4042
+ if (oldest !== void 0) this._keyMutationEpochs.delete(oldest);
4043
+ }
4044
+ return next;
4045
+ }
4046
+ _getKeyMutationEpoch(namespacedKey) {
4047
+ return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
4048
+ }
4003
4049
  _ipcServer;
4004
4050
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
4005
4051
  _subDisconnectedAt = null;
@@ -4088,6 +4134,8 @@ return 0
4088
4134
  ),
4089
4135
  snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
4090
4136
  invalidationBackplane: options.invalidationBackplane ?? true,
4137
+ awaitInvalidationBackplane: options.awaitInvalidationBackplane ?? false,
4138
+ lockFailClosed: options.lockFailClosed ?? false,
4091
4139
  oomProtection: options.oomProtection ?? true,
4092
4140
  oomHeapThreshold: options.oomHeapThreshold ?? 0.85,
4093
4141
  oomCheckIntervalMs: options.oomCheckIntervalMs ?? 1e4,
@@ -4453,7 +4501,9 @@ return 0
4453
4501
  "adaptiveTtl",
4454
4502
  "l2WriteMode",
4455
4503
  "instanceName",
4456
- "invalidationBackplane"
4504
+ "invalidationBackplane",
4505
+ "awaitInvalidationBackplane",
4506
+ "lockFailClosed"
4457
4507
  ];
4458
4508
  /** Returns the names of options that differ between `a` and the live `b`. */
4459
4509
  static optionsDiff(a, b) {
@@ -4494,6 +4544,8 @@ return 0
4494
4544
  frozen: o.frozen,
4495
4545
  adaptiveTtl: o.adaptiveTtl,
4496
4546
  invalidationBackplane: o.invalidationBackplane,
4547
+ awaitInvalidationBackplane: o.awaitInvalidationBackplane,
4548
+ lockFailClosed: o.lockFailClosed,
4497
4549
  strictSingleton: o.strictSingleton,
4498
4550
  remoteSnapshot: o.remoteSnapshot,
4499
4551
  crossRegion: o.crossRegion
@@ -4779,16 +4831,36 @@ return 0
4779
4831
  _applyInvalidationEvent(op, key, tagVersion) {
4780
4832
  if (op === "del") {
4781
4833
  this.l1.delete(key);
4834
+ this._bumpKeyMutation(key);
4835
+ this.inflight.delete(key);
4836
+ this._pendingDiskDeletes.add(key);
4782
4837
  setImmediate(() => {
4783
- if (!this._diskDisabled) this.disk.delete(key);
4838
+ try {
4839
+ if (!this._diskDisabled) this.disk.delete(key);
4840
+ } finally {
4841
+ this._pendingDiskDeletes.delete(key);
4842
+ }
4784
4843
  });
4785
4844
  this._cascadeDependencies(key);
4786
4845
  } else if (op === "del-glob") {
4787
4846
  this.l1.deletePattern(key);
4847
+ const pfx = key.endsWith("*") ? key.slice(0, -1) : key;
4848
+ for (const liveKey of this.l1.liveKeys()) {
4849
+ if (liveKey.startsWith(pfx)) {
4850
+ this._bumpKeyMutation(liveKey);
4851
+ }
4852
+ }
4853
+ for (const inflightKey of Array.from(this.inflight.keys())) {
4854
+ if (inflightKey.startsWith(pfx)) {
4855
+ this._bumpKeyMutation(inflightKey);
4856
+ this.inflight.delete(inflightKey);
4857
+ }
4858
+ }
4859
+ this._addPatternTombstone(pfx);
4788
4860
  } else if (op === "tag_incr") {
4789
4861
  const tag = key;
4790
4862
  const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
4791
- this._setLocalTagVersion(tag, ver, Date.now());
4863
+ this._setLocalTagVersion(tag, ver, performance.now());
4792
4864
  }
4793
4865
  this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
4794
4866
  }
@@ -4816,7 +4888,11 @@ return 0
4816
4888
  if (!isCrossRegionRelay && this.opts.crossRegion) {
4817
4889
  const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
4818
4890
  if (shouldBroadcast) {
4819
- void this._broadcastCrossRegion(op, key, tagVersion);
4891
+ if (this.opts.awaitInvalidationBackplane) {
4892
+ await this._broadcastCrossRegion(op, key, tagVersion);
4893
+ } else {
4894
+ void this._broadcastCrossRegion(op, key, tagVersion);
4895
+ }
4820
4896
  }
4821
4897
  }
4822
4898
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
@@ -4857,7 +4933,11 @@ return 0
4857
4933
  );
4858
4934
  }
4859
4935
  this.counters.invSent++;
4860
- } catch {
4936
+ } catch (err) {
4937
+ this.logger.warn("Backplane invalidation publish failed", { op, key, error: err.message });
4938
+ if (this.opts.awaitInvalidationBackplane) {
4939
+ throw err;
4940
+ }
4861
4941
  }
4862
4942
  }
4863
4943
  _markCrossRegionEventSeen(id) {
@@ -5061,6 +5141,7 @@ return 0
5061
5141
  }
5062
5142
  }
5063
5143
  async getRedis() {
5144
+ this._assertActive("getRedis");
5064
5145
  if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
5065
5146
  if (this.redis) return this.redis;
5066
5147
  if (this.redisConnecting) return this.redisConnecting;
@@ -5389,6 +5470,7 @@ return 0
5389
5470
  * Caches negative lookups to avoid repeated DB hits for missing keys.
5390
5471
  */
5391
5472
  async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
5473
+ this._assertActive("get");
5392
5474
  const span = this._startSpan("tricache.get");
5393
5475
  if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
5394
5476
  const k = this.nk(cacheKey);
@@ -5420,7 +5502,14 @@ return 0
5420
5502
  if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
5421
5503
  const priority2 = optPriority ?? inferPriority(cacheKey);
5422
5504
  this.revalidating.add(k);
5423
- void this._revalidate(k, fetchFn, ttlSeconds * 1e3, swrGraceMs2, priority2);
5505
+ void this._revalidate(
5506
+ k,
5507
+ fetchFn,
5508
+ ttlSeconds * 1e3,
5509
+ swrGraceMs2,
5510
+ priority2,
5511
+ l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
5512
+ );
5424
5513
  this.counters.swrRevalidations++;
5425
5514
  this.logger.debug("SWR: serving stale, revalidating", { cacheKey });
5426
5515
  } else {
@@ -5439,7 +5528,14 @@ return 0
5439
5528
  if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
5440
5529
  const priority2 = optPriority ?? inferPriority(cacheKey);
5441
5530
  this.revalidating.add(k);
5442
- void this._revalidate(k, fetchFn, entryTtl, optSwr * 1e3, priority2);
5531
+ void this._revalidate(
5532
+ k,
5533
+ fetchFn,
5534
+ entryTtl,
5535
+ optSwr * 1e3,
5536
+ priority2,
5537
+ l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
5538
+ );
5443
5539
  this.counters.swrRevalidations++;
5444
5540
  this.logger.debug(
5445
5541
  shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
@@ -5465,44 +5561,52 @@ return 0
5465
5561
  span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
5466
5562
  return existing;
5467
5563
  }
5564
+ const mutationEpochAtStart = this._getKeyMutationEpoch(k);
5468
5565
  const executionPromise = (async () => {
5469
5566
  try {
5470
- if (!this._diskDisabled) {
5471
- const isDiskAllowed = this.watchdog.isDiskAllowed();
5472
- if (isDiskAllowed) {
5473
- const diskStart = performance.now();
5474
- const diskHit = this.disk.load(k);
5475
- const diskElapsed = performance.now() - diskStart;
5476
- this.watchdog.recordDisk(diskElapsed);
5477
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
5478
- if (diskHit !== null) {
5479
- let isDiskStale = false;
5480
- if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
5481
- const tags = Object.keys(diskHit.tagVersions);
5482
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5483
- for (let i = 0; i < tags.length; i++) {
5484
- if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
5485
- isDiskStale = true;
5486
- break;
5567
+ if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
5568
+ if (this._isTombstonedByPattern(k)) {
5569
+ try {
5570
+ this.disk.delete(k);
5571
+ } catch {
5572
+ }
5573
+ } else {
5574
+ const isDiskAllowed = this.watchdog.isDiskAllowed();
5575
+ if (isDiskAllowed) {
5576
+ const diskStart = performance.now();
5577
+ const diskHit = this.disk.load(k);
5578
+ const diskElapsed = performance.now() - diskStart;
5579
+ this.watchdog.recordDisk(diskElapsed);
5580
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
5581
+ if (diskHit !== null) {
5582
+ let isDiskStale = false;
5583
+ if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
5584
+ const tags = Object.keys(diskHit.tagVersions);
5585
+ const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5586
+ for (let i = 0; i < tags.length; i++) {
5587
+ if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
5588
+ isDiskStale = true;
5589
+ break;
5590
+ }
5487
5591
  }
5488
5592
  }
5489
- }
5490
- if (isDiskStale) {
5491
- this.disk.delete(k);
5492
- } else {
5493
- const promoted = this.l1.importEntries(
5494
- [{ key: k, entry: diskHit }],
5495
- this.opts.forbiddenSnapshotPrefixes
5496
- );
5497
- if (promoted > 0) {
5498
- const l1Check = this.l1.get(k);
5499
- if (l1Check !== null) {
5500
- this.counters.diskHits++;
5501
- this.opts.onHit?.(cacheKey, "disk");
5502
- this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
5503
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
5504
- if (this.opts.frozen) deepFreeze(l1Check.value);
5505
- return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
5593
+ if (isDiskStale) {
5594
+ this.disk.delete(k);
5595
+ } else {
5596
+ const promoted = this.l1.importEntries(
5597
+ [{ key: k, entry: diskHit }],
5598
+ this.opts.forbiddenSnapshotPrefixes
5599
+ );
5600
+ if (promoted > 0) {
5601
+ const l1Check = this.l1.get(k);
5602
+ if (l1Check !== null) {
5603
+ this.counters.diskHits++;
5604
+ this.opts.onHit?.(cacheKey, "disk");
5605
+ this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
5606
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
5607
+ if (this.opts.frozen) deepFreeze(l1Check.value);
5608
+ return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
5609
+ }
5506
5610
  }
5507
5611
  }
5508
5612
  }
@@ -5613,6 +5717,18 @@ return 0
5613
5717
  await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
5614
5718
  }
5615
5719
  }
5720
+ if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
5721
+ this.logger.debug("Aborting in-flight cache commit \u2014 key was mutated or deleted during fetch", { cacheKey });
5722
+ span.setAttribute("cache.aborted_mutation_race", true);
5723
+ const current = this.l1.get(k);
5724
+ if (current && !current.isStale && current.value !== void 0) {
5725
+ const freshVal = current.value;
5726
+ if (this.opts.frozen) deepFreeze(freshVal);
5727
+ return this.opts.cloneStrategy === "structuredClone" && freshVal != null && typeof freshVal === "object" ? structuredClone(freshVal) : freshVal;
5728
+ }
5729
+ if (this.opts.frozen) deepFreeze(data);
5730
+ return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
5731
+ }
5616
5732
  this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
5617
5733
  if (!this._redisDisabled) {
5618
5734
  try {
@@ -5729,22 +5845,40 @@ return 0
5729
5845
  const ttl = options?.ttl ?? 300;
5730
5846
  return this.get(cacheKey, fetchFn, ttl, options);
5731
5847
  }
5732
- async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
5848
+ async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority, knownTagVersions) {
5849
+ const startEpoch = this._getKeyMutationEpoch(cacheKey);
5733
5850
  try {
5734
5851
  const fetchStart = Date.now();
5735
5852
  const data = await fetchFn();
5736
5853
  const delta = Date.now() - fetchStart;
5737
5854
  const staleAt = Date.now() + ttlMs;
5855
+ if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
5856
+ this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during fetch", { cacheKey });
5857
+ return;
5858
+ }
5738
5859
  if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
5739
5860
  let activeTagVersions;
5740
5861
  const l1Existing = this.l1.get(cacheKey);
5741
- if (this.opts.tagStrategy === "generational" && l1Existing?.tagVersions) {
5742
- const tags = Object.keys(l1Existing.tagVersions);
5862
+ const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
5863
+ if (this.opts.tagStrategy === "generational" && tagVersionsSource) {
5864
+ const tags = Object.keys(tagVersionsSource);
5743
5865
  const vers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5744
5866
  activeTagVersions = {};
5745
5867
  for (let i = 0; i < tags.length; i++) {
5746
5868
  activeTagVersions[tags[i]] = vers[i];
5747
5869
  }
5870
+ if (knownTagVersions) {
5871
+ for (const t of tags) {
5872
+ if (knownTagVersions[t] !== void 0 && activeTagVersions[t] !== knownTagVersions[t]) {
5873
+ this.logger.debug("SWR: aborting revalidation commit \u2014 tag version bumped during revalidation", { cacheKey, tag: t });
5874
+ return;
5875
+ }
5876
+ }
5877
+ }
5878
+ }
5879
+ if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
5880
+ this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
5881
+ return;
5748
5882
  }
5749
5883
  this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
5750
5884
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
@@ -5788,6 +5922,7 @@ return 0
5788
5922
  // ── Explicit set / delete ─────────────────────────────────────────────────
5789
5923
  /** Explicitly write a value into L1 (+ L2 in production). */
5790
5924
  async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
5925
+ this._assertActive("set");
5791
5926
  const span = this._startSpan("tricache.set");
5792
5927
  if (this.opts.tracer) {
5793
5928
  span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
@@ -5798,6 +5933,9 @@ return 0
5798
5933
  const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
5799
5934
  const p = priority ?? inferPriority(cacheKey);
5800
5935
  const k = this.nk(cacheKey);
5936
+ this._bumpKeyMutation(k);
5937
+ this.inflight.delete(k);
5938
+ this._pendingDiskDeletes.delete(k);
5801
5939
  this.counters.sets++;
5802
5940
  let activeTagVersions;
5803
5941
  if (opts?.tags?.length) {
@@ -5852,7 +5990,11 @@ return 0
5852
5990
  this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
5853
5991
  }
5854
5992
  }
5855
- void this.publishInvalidation("del", k);
5993
+ if (this.opts.awaitInvalidationBackplane) {
5994
+ await this.publishInvalidation("del", k);
5995
+ } else {
5996
+ void this.publishInvalidation("del", k);
5997
+ }
5856
5998
  } catch (err) {
5857
5999
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
5858
6000
  span.recordException?.(err);
@@ -5899,6 +6041,7 @@ return 0
5899
6041
  * await cache.delete('user:abc:*'); // all keys for user abc
5900
6042
  */
5901
6043
  async delete(cacheKey) {
6044
+ this._assertActive("delete");
5902
6045
  const span = this._startSpan("tricache.delete");
5903
6046
  if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
5904
6047
  try {
@@ -5906,11 +6049,31 @@ return 0
5906
6049
  const k = this.nk(cacheKey);
5907
6050
  this.counters.deletes++;
5908
6051
  if (isPattern) {
6052
+ const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6053
+ for (const liveKey of this.l1.liveKeys()) {
6054
+ if (liveKey.startsWith(pfx)) {
6055
+ this._bumpKeyMutation(liveKey);
6056
+ }
6057
+ }
6058
+ for (const inflightKey of Array.from(this.inflight.keys())) {
6059
+ if (inflightKey.startsWith(pfx)) {
6060
+ this._bumpKeyMutation(inflightKey);
6061
+ this.inflight.delete(inflightKey);
6062
+ }
6063
+ }
6064
+ this._addPatternTombstone(pfx);
5909
6065
  this.l1.deletePattern(k);
5910
6066
  } else {
6067
+ this._bumpKeyMutation(k);
6068
+ this.inflight.delete(k);
5911
6069
  this.l1.delete(k);
6070
+ this._pendingDiskDeletes.add(k);
5912
6071
  setImmediate(() => {
5913
- if (!this._diskDisabled) this.disk.delete(k);
6072
+ try {
6073
+ if (!this._diskDisabled) this.disk.delete(k);
6074
+ } finally {
6075
+ this._pendingDiskDeletes.delete(k);
6076
+ }
5914
6077
  });
5915
6078
  this._cascadeDependencies(k);
5916
6079
  for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
@@ -5934,7 +6097,11 @@ return 0
5934
6097
  this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
5935
6098
  }
5936
6099
  }
5937
- void this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
6100
+ if (this.opts.awaitInvalidationBackplane) {
6101
+ await this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
6102
+ } else {
6103
+ void this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
6104
+ }
5938
6105
  } catch (err) {
5939
6106
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
5940
6107
  span.recordException?.(err);
@@ -5961,6 +6128,7 @@ return 0
5961
6128
  * fleet-wide.
5962
6129
  */
5963
6130
  async increment(cacheKey, ttlSeconds) {
6131
+ this._assertActive("increment");
5964
6132
  const k = this.nk(cacheKey);
5965
6133
  if (this._redisDisabled) {
5966
6134
  if (!this._incrementFallbackWarned) {
@@ -6002,19 +6170,38 @@ return 0
6002
6170
  * await cache.clear('user:abc'); // flush all keys for one user
6003
6171
  */
6004
6172
  async clear(prefix) {
6173
+ this._assertActive("clear");
6005
6174
  const span = this._startSpan("tricache.clear");
6006
6175
  if (this.opts.tracer) span.setAttribute("cache.prefix", prefix || "*");
6007
6176
  try {
6008
6177
  this.counters.deletes++;
6009
6178
  const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
6010
6179
  if (k) {
6180
+ const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6181
+ for (const liveKey of this.l1.liveKeys()) {
6182
+ if (liveKey.startsWith(pfx)) {
6183
+ this._bumpKeyMutation(liveKey);
6184
+ }
6185
+ }
6186
+ for (const inflightKey of Array.from(this.inflight.keys())) {
6187
+ if (inflightKey.startsWith(pfx)) {
6188
+ this._bumpKeyMutation(inflightKey);
6189
+ this.inflight.delete(inflightKey);
6190
+ }
6191
+ }
6192
+ this._addPatternTombstone(pfx);
6011
6193
  this.l1.deletePattern(k);
6012
6194
  } else {
6195
+ this._globalEpoch++;
6196
+ this.inflight.clear();
6197
+ this._patternTombstones.length = 0;
6013
6198
  this.l1.clear();
6014
6199
  if (!this._diskDisabled) this.disk.clear();
6015
6200
  this._l1Counters.clear();
6016
6201
  this.tagIndex.clear();
6017
6202
  this.tagVersions.clear();
6203
+ this._pendingDiskDeletes.clear();
6204
+ this._keyMutationEpochs.clear();
6018
6205
  }
6019
6206
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6020
6207
  try {
@@ -6026,13 +6213,23 @@ return 0
6026
6213
  this.logger.debug("clear: Redis unavailable", { error: err.message });
6027
6214
  }
6028
6215
  }
6029
- void this.publishInvalidation(
6030
- "del-glob",
6031
- k ?? (this._namespace ? `${this._namespace}:*` : "*"),
6032
- void 0,
6033
- false,
6034
- true
6035
- );
6216
+ if (this.opts.awaitInvalidationBackplane) {
6217
+ await this.publishInvalidation(
6218
+ "del-glob",
6219
+ k ?? (this._namespace ? `${this._namespace}:*` : "*"),
6220
+ void 0,
6221
+ false,
6222
+ true
6223
+ );
6224
+ } else {
6225
+ void this.publishInvalidation(
6226
+ "del-glob",
6227
+ k ?? (this._namespace ? `${this._namespace}:*` : "*"),
6228
+ void 0,
6229
+ false,
6230
+ true
6231
+ );
6232
+ }
6036
6233
  } catch (err) {
6037
6234
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
6038
6235
  span.recordException?.(err);
@@ -6047,6 +6244,7 @@ return 0
6047
6244
  * Returns the number of entries evicted.
6048
6245
  */
6049
6246
  rebalance() {
6247
+ this._assertActive("rebalance");
6050
6248
  return this.l1.rebalance();
6051
6249
  }
6052
6250
  /**
@@ -6055,6 +6253,7 @@ return 0
6055
6253
  * Only reflects L1 state — does not query Redis or disk.
6056
6254
  */
6057
6255
  ttl(cacheKey) {
6256
+ this._assertActive("ttl");
6058
6257
  return this.l1.ttl(this.nk(cacheKey));
6059
6258
  }
6060
6259
  /**
@@ -6062,6 +6261,7 @@ return 0
6062
6261
  * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
6063
6262
  */
6064
6263
  has(cacheKey) {
6264
+ this._assertActive("has");
6065
6265
  return this.l1.has(this.nk(cacheKey));
6066
6266
  }
6067
6267
  // ── Iteration ─────────────────────────────────────────────────────────────
@@ -6072,6 +6272,7 @@ return 0
6072
6272
  * for (const key of cache.keys()) console.log(key);
6073
6273
  */
6074
6274
  *keys() {
6275
+ this._assertActive("keys");
6075
6276
  const prefix = this._namespace ? this._namespace + ":" : "";
6076
6277
  for (const key of this.l1.liveKeys()) {
6077
6278
  if (prefix && !key.startsWith(prefix)) continue;
@@ -6086,6 +6287,7 @@ return 0
6086
6287
  * for (const val of cache.values<User>()) console.log(val.id);
6087
6288
  */
6088
6289
  *values() {
6290
+ this._assertActive("values");
6089
6291
  const prefix = this._namespace ? this._namespace + ":" : "";
6090
6292
  if (!prefix) {
6091
6293
  yield* this.l1.liveValues();
@@ -6104,6 +6306,7 @@ return 0
6104
6306
  * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
6105
6307
  */
6106
6308
  *entries() {
6309
+ this._assertActive("entries");
6107
6310
  const prefix = this._namespace ? this._namespace + ":" : "";
6108
6311
  for (const [key, entry] of this.l1.liveEntries()) {
6109
6312
  if (prefix && !key.startsWith(prefix)) continue;
@@ -6131,6 +6334,7 @@ return 0
6131
6334
  * `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
6132
6335
  */
6133
6336
  scan(fn) {
6337
+ this._assertActive("scan");
6134
6338
  const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
6135
6339
  this.l1.scan((key, entry, pfx) => {
6136
6340
  const value = entry.value !== void 0 ? entry.value : entry.data;
@@ -6144,6 +6348,7 @@ return 0
6144
6348
  * @param newTtlSeconds - The new TTL from now, in seconds.
6145
6349
  */
6146
6350
  async touch(cacheKey, newTtlSeconds) {
6351
+ this._assertActive("touch");
6147
6352
  const k = this.nk(cacheKey);
6148
6353
  const hit = this.l1.touch(k, newTtlSeconds * 1e3);
6149
6354
  if (hit && !this._redisDisabled) {
@@ -6164,6 +6369,7 @@ return 0
6164
6369
  * if (fresh !== null) return fresh; // serve from L1, no network hop
6165
6370
  */
6166
6371
  getIfFresh(cacheKey) {
6372
+ this._assertActive("getIfFresh");
6167
6373
  const k = this.nk(cacheKey);
6168
6374
  const entry = this.l1.getEntry(k);
6169
6375
  if (!entry) return null;
@@ -6181,6 +6387,7 @@ return 0
6181
6387
  * const val = await cache.peek<User>('user:123');
6182
6388
  */
6183
6389
  async peek(cacheKey) {
6390
+ this._assertActive("peek");
6184
6391
  const k = this.nk(cacheKey);
6185
6392
  const l1Hit = this.l1.get(k);
6186
6393
  if (l1Hit !== null) {
@@ -6190,25 +6397,32 @@ return 0
6190
6397
  if (this.opts.frozen) deepFreeze(val);
6191
6398
  return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6192
6399
  }
6193
- if (!this._diskDisabled && this.watchdog.isDiskAllowed()) {
6194
- const diskStart = performance.now();
6195
- const diskHit = this.disk.load(k);
6196
- const diskElapsed = performance.now() - diskStart;
6197
- this.watchdog.recordDisk(diskElapsed);
6198
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6199
- if (diskHit !== null) {
6200
- const promoted = this.l1.importEntries(
6201
- [{ key: k, entry: diskHit }],
6202
- this.opts.forbiddenSnapshotPrefixes
6203
- );
6204
- if (promoted > 0) {
6205
- const l1Check = this.l1.get(k);
6206
- if (l1Check !== null) {
6207
- this.counters.gets++;
6208
- this.counters.diskHits++;
6209
- const val = l1Check.value;
6210
- if (this.opts.frozen) deepFreeze(val);
6211
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6400
+ if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
6401
+ if (this._isTombstonedByPattern(k)) {
6402
+ try {
6403
+ this.disk.delete(k);
6404
+ } catch {
6405
+ }
6406
+ } else if (this.watchdog.isDiskAllowed()) {
6407
+ const diskStart = performance.now();
6408
+ const diskHit = this.disk.load(k);
6409
+ const diskElapsed = performance.now() - diskStart;
6410
+ this.watchdog.recordDisk(diskElapsed);
6411
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6412
+ if (diskHit !== null) {
6413
+ const promoted = this.l1.importEntries(
6414
+ [{ key: k, entry: diskHit }],
6415
+ this.opts.forbiddenSnapshotPrefixes
6416
+ );
6417
+ if (promoted > 0) {
6418
+ const l1Check = this.l1.get(k);
6419
+ if (l1Check !== null) {
6420
+ this.counters.gets++;
6421
+ this.counters.diskHits++;
6422
+ const val = l1Check.value;
6423
+ if (this.opts.frozen) deepFreeze(val);
6424
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6425
+ }
6212
6426
  }
6213
6427
  }
6214
6428
  }
@@ -6246,6 +6460,7 @@ return 0
6246
6460
  * `(key) => number` so heterogeneous TTLs can be batched in one call.
6247
6461
  */
6248
6462
  async mget(keys, fetchFn, ttl = 300, priority) {
6463
+ this._assertActive("mget");
6249
6464
  const span = this._startSpan("tricache.mget");
6250
6465
  if (this.opts.tracer) {
6251
6466
  span.setAttribute("cache.batch.size", keys.length);
@@ -6314,8 +6529,16 @@ return 0
6314
6529
  }
6315
6530
  if (!this._diskDisabled && missKeys.length > 0) {
6316
6531
  for (let j = missKeys.length - 1; j >= 0; j--) {
6317
- if (!this.watchdog.isDiskAllowed()) continue;
6318
6532
  const k = this.nk(missKeys[j]);
6533
+ if (this._pendingDiskDeletes.has(k)) continue;
6534
+ if (this._isTombstonedByPattern(k)) {
6535
+ try {
6536
+ this.disk.delete(k);
6537
+ } catch {
6538
+ }
6539
+ continue;
6540
+ }
6541
+ if (!this.watchdog.isDiskAllowed()) continue;
6319
6542
  const diskStart = performance.now();
6320
6543
  const diskHit = this.disk.load(k);
6321
6544
  const diskElapsed = performance.now() - diskStart;
@@ -6395,6 +6618,7 @@ return 0
6395
6618
  * });
6396
6619
  */
6397
6620
  async mset(entries) {
6621
+ this._assertActive("mset");
6398
6622
  const span = this._startSpan("tricache.mset");
6399
6623
  const keys = Object.keys(entries);
6400
6624
  if (this.opts.tracer) {
@@ -6422,6 +6646,7 @@ return 0
6422
6646
  * await cache.mdel(['user:1', 'user:2', 'user:3']);
6423
6647
  */
6424
6648
  async mdel(keys) {
6649
+ this._assertActive("mdel");
6425
6650
  const span = this._startSpan("tricache.mdel");
6426
6651
  if (this.opts.tracer) {
6427
6652
  span.setAttribute("cache.batch.size", keys.length);
@@ -6449,6 +6674,7 @@ return 0
6449
6674
  * console.log(`Warmed ${loaded} keys from Redis`);
6450
6675
  */
6451
6676
  async warmFromL2(pattern, opts) {
6677
+ this._assertActive("warmFromL2");
6452
6678
  if (this._redisDisabled) return 0;
6453
6679
  try {
6454
6680
  const client = await this.getRedis();
@@ -6495,6 +6721,7 @@ return 0
6495
6721
  * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
6496
6722
  */
6497
6723
  async invalidateTag(tag) {
6724
+ this._assertActive("invalidateTag");
6498
6725
  const span = this._startSpan("tricache.invalidate_tag");
6499
6726
  if (this.opts.tracer) {
6500
6727
  span.setAttribute("cache.tag", tag);
@@ -6516,15 +6743,27 @@ return 0
6516
6743
  const current = this.tagVersions.get(tag)?.version ?? 0;
6517
6744
  newVer = current + 1;
6518
6745
  }
6519
- this._setLocalTagVersion(tag, newVer, Date.now());
6520
- void this.publishInvalidation("tag_incr", tag, newVer, false, true);
6746
+ this._setLocalTagVersion(tag, newVer, performance.now());
6747
+ if (this.opts.awaitInvalidationBackplane) {
6748
+ await this.publishInvalidation("tag_incr", tag, newVer, false, true);
6749
+ } else {
6750
+ void this.publishInvalidation("tag_incr", tag, newVer, false, true);
6751
+ }
6521
6752
  return;
6522
6753
  }
6523
6754
  const tagKey = this.nk(`_tag_:${tag}`);
6524
6755
  const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
6525
6756
  for (const k of members) {
6526
6757
  this.l1.delete(k);
6527
- if (!this._diskDisabled) this.disk.delete(k);
6758
+ this._bumpKeyMutation(k);
6759
+ this._pendingDiskDeletes.add(k);
6760
+ setImmediate(() => {
6761
+ try {
6762
+ if (!this._diskDisabled) this.disk.delete(k);
6763
+ } finally {
6764
+ this._pendingDiskDeletes.delete(k);
6765
+ }
6766
+ });
6528
6767
  }
6529
6768
  this.tagIndex.delete(tagKey);
6530
6769
  if (!this._redisDisabled) {
@@ -6562,13 +6801,14 @@ return 0
6562
6801
  * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
6563
6802
  */
6564
6803
  async invalidateTags(tags) {
6804
+ this._assertActive("invalidateTags");
6565
6805
  if (tags.length === 0) return;
6566
6806
  if (tags.length === 1) {
6567
6807
  await this.invalidateTag(tags[0]);
6568
6808
  return;
6569
6809
  }
6570
6810
  if (this.opts.tagStrategy === "generational") {
6571
- const now = Date.now();
6811
+ const now = performance.now();
6572
6812
  if (!this._redisDisabled) {
6573
6813
  try {
6574
6814
  const client = await this.getRedis();
@@ -6579,7 +6819,11 @@ return 0
6579
6819
  const [err, newVer] = results[i] ?? [null, null];
6580
6820
  const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
6581
6821
  this._setLocalTagVersion(tags[i], ver, now);
6582
- void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
6822
+ if (this.opts.awaitInvalidationBackplane) {
6823
+ await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
6824
+ } else {
6825
+ void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
6826
+ }
6583
6827
  }
6584
6828
  return;
6585
6829
  } catch (err) {
@@ -6589,7 +6833,11 @@ return 0
6589
6833
  for (const tag of tags) {
6590
6834
  const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
6591
6835
  this._setLocalTagVersion(tag, ver, now);
6592
- void this.publishInvalidation("tag_incr", tag, ver, false, true);
6836
+ if (this.opts.awaitInvalidationBackplane) {
6837
+ await this.publishInvalidation("tag_incr", tag, ver, false, true);
6838
+ } else {
6839
+ void this.publishInvalidation("tag_incr", tag, ver, false, true);
6840
+ }
6593
6841
  }
6594
6842
  return;
6595
6843
  }
@@ -6604,7 +6852,15 @@ return 0
6604
6852
  }
6605
6853
  for (const k of allMembers) {
6606
6854
  this.l1.delete(k);
6607
- this.disk.delete(k);
6855
+ this._bumpKeyMutation(k);
6856
+ this._pendingDiskDeletes.add(k);
6857
+ setImmediate(() => {
6858
+ try {
6859
+ if (!this._diskDisabled) this.disk.delete(k);
6860
+ } finally {
6861
+ this._pendingDiskDeletes.delete(k);
6862
+ }
6863
+ });
6608
6864
  }
6609
6865
  if (!this._redisDisabled) {
6610
6866
  try {
@@ -6641,6 +6897,7 @@ return 0
6641
6897
  * `l2` is `null` when Redis is disabled.
6642
6898
  */
6643
6899
  async ping() {
6900
+ this._assertActive("ping");
6644
6901
  const t0 = Date.now();
6645
6902
  this.l1.has("__ping__");
6646
6903
  const l1 = Date.now() - t0;
@@ -6720,6 +6977,7 @@ return 0
6720
6977
  * Returns the number of keys written.
6721
6978
  */
6722
6979
  async drainToL2() {
6980
+ this._assertActive("drainToL2");
6723
6981
  if (this._redisDisabled) return 0;
6724
6982
  try {
6725
6983
  const client = await this.getRedis();
@@ -6763,6 +7021,7 @@ return 0
6763
7021
  * if (!claimed) return res.status(409).json({ error: 'duplicate request' });
6764
7022
  */
6765
7023
  async setIfAbsent(cacheKey, value, ttlSeconds = 300, priority) {
7024
+ this._assertActive("setIfAbsent");
6766
7025
  const k = this.nk(cacheKey);
6767
7026
  if (this.l1.has(k)) return false;
6768
7027
  if (!this._redisDisabled) {
@@ -6781,6 +7040,8 @@ return 0
6781
7040
  }
6782
7041
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
6783
7042
  const p = priority ?? inferPriority(cacheKey);
7043
+ this._bumpKeyMutation(k);
7044
+ this._pendingDiskDeletes.delete(k);
6784
7045
  this.l1.set(k, value, ttlMs, p);
6785
7046
  this.counters.sets++;
6786
7047
  return true;
@@ -6799,6 +7060,7 @@ return 0
6799
7060
  * @param options TTL, acquire timeout, and retry polling intervals.
6800
7061
  */
6801
7062
  async lock(resourceKey, fn, options) {
7063
+ this._assertActive("lock");
6802
7064
  const ttlSeconds = Math.max(1, options?.ttl ?? 30);
6803
7065
  const acquireTimeout = Math.max(0, options?.acquireTimeout ?? 5e3);
6804
7066
  const retryInterval = Math.max(10, options?.retryInterval ?? 100);
@@ -6825,6 +7087,10 @@ return 0
6825
7087
  }
6826
7088
  } catch (err) {
6827
7089
  if (err.message.startsWith("Failed to acquire lock")) throw err;
7090
+ const failClosed = options?.failClosedOnRedisError ?? this.opts.lockFailClosed;
7091
+ if (failClosed) {
7092
+ throw new Error(`Distributed lock acquisition failed for resource "${resourceKey}" due to Redis error: ${err.message}`);
7093
+ }
6828
7094
  this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
6829
7095
  resourceKey,
6830
7096
  error: err.message
@@ -7170,6 +7436,7 @@ return 0
7170
7436
  * the previous key for seamless fallback decryption of existing cache entries.
7171
7437
  */
7172
7438
  async rotateEncryptionKey(newKeyBase64, newMode) {
7439
+ this._assertActive("rotateEncryptionKey");
7173
7440
  this.enc.rotateKey(newKeyBase64, newMode);
7174
7441
  if (this._workerPool) {
7175
7442
  await this._workerPool.drainAndReinit(this.enc.toWorkerInit());
@@ -7179,6 +7446,8 @@ return 0
7179
7446
  /** Close Redis connections and stop all background timers. */
7180
7447
  async destroy() {
7181
7448
  this._destroyed = true;
7449
+ this._pendingDiskDeletes.clear();
7450
+ this._keyMutationEpochs.clear();
7182
7451
  const g = globalThis;
7183
7452
  const key = _CacheService.globalKey(this.opts);
7184
7453
  if (g[key] === this) {