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
@@ -3903,6 +3903,52 @@ var CacheService = class _CacheService {
3903
3903
  streamClient = null;
3904
3904
  _lastStreamId = "$";
3905
3905
  _destroyed = false;
3906
+ _pendingDiskDeletes = /* @__PURE__ */ new Set();
3907
+ _globalEpoch = 0;
3908
+ _keyMutationEpochs = /* @__PURE__ */ new Map();
3909
+ /**
3910
+ * Pattern tombstones for disk tier.
3911
+ * Files in the disk tier are keyed by SHA-256 of namespacedKey.
3912
+ * Wildcard pattern deletes cannot scan the filesystem synchronously, so we maintain
3913
+ * pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
3914
+ */
3915
+ _patternTombstones = [];
3916
+ _addPatternTombstone(prefix) {
3917
+ const now = Date.now();
3918
+ while (this._patternTombstones.length > 0 && now - this._patternTombstones[0].createdAt > 36e5) {
3919
+ this._patternTombstones.shift();
3920
+ }
3921
+ if (this._patternTombstones.length >= 2e3) {
3922
+ this._patternTombstones.shift();
3923
+ }
3924
+ this._patternTombstones.push({ prefix, createdAt: now });
3925
+ }
3926
+ _isTombstonedByPattern(namespacedKey) {
3927
+ if (this._patternTombstones.length === 0) return false;
3928
+ for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
3929
+ if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
3930
+ return true;
3931
+ }
3932
+ }
3933
+ return false;
3934
+ }
3935
+ _assertActive(operation) {
3936
+ if (this._destroyed) {
3937
+ throw new Error(`TriCacheError: Cannot perform '${operation}' on a destroyed CacheService instance (namespace: '${this._namespace || "(default)"}').`);
3938
+ }
3939
+ }
3940
+ _bumpKeyMutation(namespacedKey) {
3941
+ const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
3942
+ this._keyMutationEpochs.set(namespacedKey, next);
3943
+ if (this._keyMutationEpochs.size > 5e4) {
3944
+ const oldest = this._keyMutationEpochs.keys().next().value;
3945
+ if (oldest !== void 0) this._keyMutationEpochs.delete(oldest);
3946
+ }
3947
+ return next;
3948
+ }
3949
+ _getKeyMutationEpoch(namespacedKey) {
3950
+ return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
3951
+ }
3906
3952
  _ipcServer;
3907
3953
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
3908
3954
  _subDisconnectedAt = null;
@@ -3991,6 +4037,8 @@ var CacheService = class _CacheService {
3991
4037
  ),
3992
4038
  snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
3993
4039
  invalidationBackplane: options.invalidationBackplane ?? true,
4040
+ awaitInvalidationBackplane: options.awaitInvalidationBackplane ?? false,
4041
+ lockFailClosed: options.lockFailClosed ?? false,
3994
4042
  oomProtection: options.oomProtection ?? true,
3995
4043
  oomHeapThreshold: options.oomHeapThreshold ?? 0.85,
3996
4044
  oomCheckIntervalMs: options.oomCheckIntervalMs ?? 1e4,
@@ -4356,7 +4404,9 @@ var CacheService = class _CacheService {
4356
4404
  "adaptiveTtl",
4357
4405
  "l2WriteMode",
4358
4406
  "instanceName",
4359
- "invalidationBackplane"
4407
+ "invalidationBackplane",
4408
+ "awaitInvalidationBackplane",
4409
+ "lockFailClosed"
4360
4410
  ];
4361
4411
  /** Returns the names of options that differ between `a` and the live `b`. */
4362
4412
  static optionsDiff(a, b) {
@@ -4397,6 +4447,8 @@ var CacheService = class _CacheService {
4397
4447
  frozen: o.frozen,
4398
4448
  adaptiveTtl: o.adaptiveTtl,
4399
4449
  invalidationBackplane: o.invalidationBackplane,
4450
+ awaitInvalidationBackplane: o.awaitInvalidationBackplane,
4451
+ lockFailClosed: o.lockFailClosed,
4400
4452
  strictSingleton: o.strictSingleton,
4401
4453
  remoteSnapshot: o.remoteSnapshot,
4402
4454
  crossRegion: o.crossRegion
@@ -4682,16 +4734,36 @@ var CacheService = class _CacheService {
4682
4734
  _applyInvalidationEvent(op, key, tagVersion) {
4683
4735
  if (op === "del") {
4684
4736
  this.l1.delete(key);
4737
+ this._bumpKeyMutation(key);
4738
+ this.inflight.delete(key);
4739
+ this._pendingDiskDeletes.add(key);
4685
4740
  setImmediate(() => {
4686
- if (!this._diskDisabled) this.disk.delete(key);
4741
+ try {
4742
+ if (!this._diskDisabled) this.disk.delete(key);
4743
+ } finally {
4744
+ this._pendingDiskDeletes.delete(key);
4745
+ }
4687
4746
  });
4688
4747
  this._cascadeDependencies(key);
4689
4748
  } else if (op === "del-glob") {
4690
4749
  this.l1.deletePattern(key);
4750
+ const pfx = key.endsWith("*") ? key.slice(0, -1) : key;
4751
+ for (const liveKey of this.l1.liveKeys()) {
4752
+ if (liveKey.startsWith(pfx)) {
4753
+ this._bumpKeyMutation(liveKey);
4754
+ }
4755
+ }
4756
+ for (const inflightKey of Array.from(this.inflight.keys())) {
4757
+ if (inflightKey.startsWith(pfx)) {
4758
+ this._bumpKeyMutation(inflightKey);
4759
+ this.inflight.delete(inflightKey);
4760
+ }
4761
+ }
4762
+ this._addPatternTombstone(pfx);
4691
4763
  } else if (op === "tag_incr") {
4692
4764
  const tag = key;
4693
4765
  const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
4694
- this._setLocalTagVersion(tag, ver, Date.now());
4766
+ this._setLocalTagVersion(tag, ver, performance.now());
4695
4767
  }
4696
4768
  this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
4697
4769
  }
@@ -4719,7 +4791,11 @@ var CacheService = class _CacheService {
4719
4791
  if (!isCrossRegionRelay && this.opts.crossRegion) {
4720
4792
  const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
4721
4793
  if (shouldBroadcast) {
4722
- void this._broadcastCrossRegion(op, key, tagVersion);
4794
+ if (this.opts.awaitInvalidationBackplane) {
4795
+ await this._broadcastCrossRegion(op, key, tagVersion);
4796
+ } else {
4797
+ void this._broadcastCrossRegion(op, key, tagVersion);
4798
+ }
4723
4799
  }
4724
4800
  }
4725
4801
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
@@ -4760,7 +4836,11 @@ var CacheService = class _CacheService {
4760
4836
  );
4761
4837
  }
4762
4838
  this.counters.invSent++;
4763
- } catch {
4839
+ } catch (err) {
4840
+ this.logger.warn("Backplane invalidation publish failed", { op, key, error: err.message });
4841
+ if (this.opts.awaitInvalidationBackplane) {
4842
+ throw err;
4843
+ }
4764
4844
  }
4765
4845
  }
4766
4846
  _markCrossRegionEventSeen(id) {
@@ -4964,6 +5044,7 @@ var CacheService = class _CacheService {
4964
5044
  }
4965
5045
  }
4966
5046
  async getRedis() {
5047
+ this._assertActive("getRedis");
4967
5048
  if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
4968
5049
  if (this.redis) return this.redis;
4969
5050
  if (this.redisConnecting) return this.redisConnecting;
@@ -5292,6 +5373,7 @@ var CacheService = class _CacheService {
5292
5373
  * Caches negative lookups to avoid repeated DB hits for missing keys.
5293
5374
  */
5294
5375
  async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
5376
+ this._assertActive("get");
5295
5377
  const span = this._startSpan("tricache.get");
5296
5378
  if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
5297
5379
  const k = this.nk(cacheKey);
@@ -5323,7 +5405,14 @@ var CacheService = class _CacheService {
5323
5405
  if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
5324
5406
  const priority2 = optPriority ?? inferPriority(cacheKey);
5325
5407
  this.revalidating.add(k);
5326
- void this._revalidate(k, fetchFn, ttlSeconds * 1e3, swrGraceMs2, priority2);
5408
+ void this._revalidate(
5409
+ k,
5410
+ fetchFn,
5411
+ ttlSeconds * 1e3,
5412
+ swrGraceMs2,
5413
+ priority2,
5414
+ l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
5415
+ );
5327
5416
  this.counters.swrRevalidations++;
5328
5417
  this.logger.debug("SWR: serving stale, revalidating", { cacheKey });
5329
5418
  } else {
@@ -5342,7 +5431,14 @@ var CacheService = class _CacheService {
5342
5431
  if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
5343
5432
  const priority2 = optPriority ?? inferPriority(cacheKey);
5344
5433
  this.revalidating.add(k);
5345
- void this._revalidate(k, fetchFn, entryTtl, optSwr * 1e3, priority2);
5434
+ void this._revalidate(
5435
+ k,
5436
+ fetchFn,
5437
+ entryTtl,
5438
+ optSwr * 1e3,
5439
+ priority2,
5440
+ l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
5441
+ );
5346
5442
  this.counters.swrRevalidations++;
5347
5443
  this.logger.debug(
5348
5444
  shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
@@ -5368,44 +5464,52 @@ var CacheService = class _CacheService {
5368
5464
  span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
5369
5465
  return existing;
5370
5466
  }
5467
+ const mutationEpochAtStart = this._getKeyMutationEpoch(k);
5371
5468
  const executionPromise = (async () => {
5372
5469
  try {
5373
- if (!this._diskDisabled) {
5374
- const isDiskAllowed = this.watchdog.isDiskAllowed();
5375
- if (isDiskAllowed) {
5376
- const diskStart = performance.now();
5377
- const diskHit = this.disk.load(k);
5378
- const diskElapsed = performance.now() - diskStart;
5379
- this.watchdog.recordDisk(diskElapsed);
5380
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
5381
- if (diskHit !== null) {
5382
- let isDiskStale = false;
5383
- if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
5384
- const tags = Object.keys(diskHit.tagVersions);
5385
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5386
- for (let i = 0; i < tags.length; i++) {
5387
- if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
5388
- isDiskStale = true;
5389
- break;
5470
+ if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
5471
+ if (this._isTombstonedByPattern(k)) {
5472
+ try {
5473
+ this.disk.delete(k);
5474
+ } catch {
5475
+ }
5476
+ } else {
5477
+ const isDiskAllowed = this.watchdog.isDiskAllowed();
5478
+ if (isDiskAllowed) {
5479
+ const diskStart = performance.now();
5480
+ const diskHit = this.disk.load(k);
5481
+ const diskElapsed = performance.now() - diskStart;
5482
+ this.watchdog.recordDisk(diskElapsed);
5483
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
5484
+ if (diskHit !== null) {
5485
+ let isDiskStale = false;
5486
+ if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
5487
+ const tags = Object.keys(diskHit.tagVersions);
5488
+ const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5489
+ for (let i = 0; i < tags.length; i++) {
5490
+ if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
5491
+ isDiskStale = true;
5492
+ break;
5493
+ }
5390
5494
  }
5391
5495
  }
5392
- }
5393
- if (isDiskStale) {
5394
- this.disk.delete(k);
5395
- } else {
5396
- const promoted = this.l1.importEntries(
5397
- [{ key: k, entry: diskHit }],
5398
- this.opts.forbiddenSnapshotPrefixes
5399
- );
5400
- if (promoted > 0) {
5401
- const l1Check = this.l1.get(k);
5402
- if (l1Check !== null) {
5403
- this.counters.diskHits++;
5404
- this.opts.onHit?.(cacheKey, "disk");
5405
- this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
5406
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
5407
- if (this.opts.frozen) deepFreeze(l1Check.value);
5408
- return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
5496
+ if (isDiskStale) {
5497
+ this.disk.delete(k);
5498
+ } else {
5499
+ const promoted = this.l1.importEntries(
5500
+ [{ key: k, entry: diskHit }],
5501
+ this.opts.forbiddenSnapshotPrefixes
5502
+ );
5503
+ if (promoted > 0) {
5504
+ const l1Check = this.l1.get(k);
5505
+ if (l1Check !== null) {
5506
+ this.counters.diskHits++;
5507
+ this.opts.onHit?.(cacheKey, "disk");
5508
+ this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
5509
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
5510
+ if (this.opts.frozen) deepFreeze(l1Check.value);
5511
+ return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
5512
+ }
5409
5513
  }
5410
5514
  }
5411
5515
  }
@@ -5516,6 +5620,18 @@ var CacheService = class _CacheService {
5516
5620
  await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
5517
5621
  }
5518
5622
  }
5623
+ if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
5624
+ this.logger.debug("Aborting in-flight cache commit \u2014 key was mutated or deleted during fetch", { cacheKey });
5625
+ span.setAttribute("cache.aborted_mutation_race", true);
5626
+ const current = this.l1.get(k);
5627
+ if (current && !current.isStale && current.value !== void 0) {
5628
+ const freshVal = current.value;
5629
+ if (this.opts.frozen) deepFreeze(freshVal);
5630
+ return this.opts.cloneStrategy === "structuredClone" && freshVal != null && typeof freshVal === "object" ? structuredClone(freshVal) : freshVal;
5631
+ }
5632
+ if (this.opts.frozen) deepFreeze(data);
5633
+ return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
5634
+ }
5519
5635
  this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
5520
5636
  if (!this._redisDisabled) {
5521
5637
  try {
@@ -5632,22 +5748,40 @@ var CacheService = class _CacheService {
5632
5748
  const ttl = options?.ttl ?? 300;
5633
5749
  return this.get(cacheKey, fetchFn, ttl, options);
5634
5750
  }
5635
- async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
5751
+ async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority, knownTagVersions) {
5752
+ const startEpoch = this._getKeyMutationEpoch(cacheKey);
5636
5753
  try {
5637
5754
  const fetchStart = Date.now();
5638
5755
  const data = await fetchFn();
5639
5756
  const delta = Date.now() - fetchStart;
5640
5757
  const staleAt = Date.now() + ttlMs;
5758
+ if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
5759
+ this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during fetch", { cacheKey });
5760
+ return;
5761
+ }
5641
5762
  if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
5642
5763
  let activeTagVersions;
5643
5764
  const l1Existing = this.l1.get(cacheKey);
5644
- if (this.opts.tagStrategy === "generational" && l1Existing?.tagVersions) {
5645
- const tags = Object.keys(l1Existing.tagVersions);
5765
+ const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
5766
+ if (this.opts.tagStrategy === "generational" && tagVersionsSource) {
5767
+ const tags = Object.keys(tagVersionsSource);
5646
5768
  const vers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5647
5769
  activeTagVersions = {};
5648
5770
  for (let i = 0; i < tags.length; i++) {
5649
5771
  activeTagVersions[tags[i]] = vers[i];
5650
5772
  }
5773
+ if (knownTagVersions) {
5774
+ for (const t of tags) {
5775
+ if (knownTagVersions[t] !== void 0 && activeTagVersions[t] !== knownTagVersions[t]) {
5776
+ this.logger.debug("SWR: aborting revalidation commit \u2014 tag version bumped during revalidation", { cacheKey, tag: t });
5777
+ return;
5778
+ }
5779
+ }
5780
+ }
5781
+ }
5782
+ if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
5783
+ this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
5784
+ return;
5651
5785
  }
5652
5786
  this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
5653
5787
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
@@ -5691,6 +5825,7 @@ var CacheService = class _CacheService {
5691
5825
  // ── Explicit set / delete ─────────────────────────────────────────────────
5692
5826
  /** Explicitly write a value into L1 (+ L2 in production). */
5693
5827
  async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
5828
+ this._assertActive("set");
5694
5829
  const span = this._startSpan("tricache.set");
5695
5830
  if (this.opts.tracer) {
5696
5831
  span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
@@ -5701,6 +5836,9 @@ var CacheService = class _CacheService {
5701
5836
  const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
5702
5837
  const p = priority ?? inferPriority(cacheKey);
5703
5838
  const k = this.nk(cacheKey);
5839
+ this._bumpKeyMutation(k);
5840
+ this.inflight.delete(k);
5841
+ this._pendingDiskDeletes.delete(k);
5704
5842
  this.counters.sets++;
5705
5843
  let activeTagVersions;
5706
5844
  if (opts?.tags?.length) {
@@ -5755,7 +5893,11 @@ var CacheService = class _CacheService {
5755
5893
  this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
5756
5894
  }
5757
5895
  }
5758
- void this.publishInvalidation("del", k);
5896
+ if (this.opts.awaitInvalidationBackplane) {
5897
+ await this.publishInvalidation("del", k);
5898
+ } else {
5899
+ void this.publishInvalidation("del", k);
5900
+ }
5759
5901
  } catch (err) {
5760
5902
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
5761
5903
  span.recordException?.(err);
@@ -5802,6 +5944,7 @@ var CacheService = class _CacheService {
5802
5944
  * await cache.delete('user:abc:*'); // all keys for user abc
5803
5945
  */
5804
5946
  async delete(cacheKey) {
5947
+ this._assertActive("delete");
5805
5948
  const span = this._startSpan("tricache.delete");
5806
5949
  if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
5807
5950
  try {
@@ -5809,11 +5952,31 @@ var CacheService = class _CacheService {
5809
5952
  const k = this.nk(cacheKey);
5810
5953
  this.counters.deletes++;
5811
5954
  if (isPattern) {
5955
+ const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
5956
+ for (const liveKey of this.l1.liveKeys()) {
5957
+ if (liveKey.startsWith(pfx)) {
5958
+ this._bumpKeyMutation(liveKey);
5959
+ }
5960
+ }
5961
+ for (const inflightKey of Array.from(this.inflight.keys())) {
5962
+ if (inflightKey.startsWith(pfx)) {
5963
+ this._bumpKeyMutation(inflightKey);
5964
+ this.inflight.delete(inflightKey);
5965
+ }
5966
+ }
5967
+ this._addPatternTombstone(pfx);
5812
5968
  this.l1.deletePattern(k);
5813
5969
  } else {
5970
+ this._bumpKeyMutation(k);
5971
+ this.inflight.delete(k);
5814
5972
  this.l1.delete(k);
5973
+ this._pendingDiskDeletes.add(k);
5815
5974
  setImmediate(() => {
5816
- if (!this._diskDisabled) this.disk.delete(k);
5975
+ try {
5976
+ if (!this._diskDisabled) this.disk.delete(k);
5977
+ } finally {
5978
+ this._pendingDiskDeletes.delete(k);
5979
+ }
5817
5980
  });
5818
5981
  this._cascadeDependencies(k);
5819
5982
  for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
@@ -5837,7 +6000,11 @@ var CacheService = class _CacheService {
5837
6000
  this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
5838
6001
  }
5839
6002
  }
5840
- void this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
6003
+ if (this.opts.awaitInvalidationBackplane) {
6004
+ await this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
6005
+ } else {
6006
+ void this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
6007
+ }
5841
6008
  } catch (err) {
5842
6009
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
5843
6010
  span.recordException?.(err);
@@ -5864,6 +6031,7 @@ var CacheService = class _CacheService {
5864
6031
  * fleet-wide.
5865
6032
  */
5866
6033
  async increment(cacheKey, ttlSeconds) {
6034
+ this._assertActive("increment");
5867
6035
  const k = this.nk(cacheKey);
5868
6036
  if (this._redisDisabled) {
5869
6037
  if (!this._incrementFallbackWarned) {
@@ -5905,19 +6073,38 @@ var CacheService = class _CacheService {
5905
6073
  * await cache.clear('user:abc'); // flush all keys for one user
5906
6074
  */
5907
6075
  async clear(prefix) {
6076
+ this._assertActive("clear");
5908
6077
  const span = this._startSpan("tricache.clear");
5909
6078
  if (this.opts.tracer) span.setAttribute("cache.prefix", prefix || "*");
5910
6079
  try {
5911
6080
  this.counters.deletes++;
5912
6081
  const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
5913
6082
  if (k) {
6083
+ const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6084
+ for (const liveKey of this.l1.liveKeys()) {
6085
+ if (liveKey.startsWith(pfx)) {
6086
+ this._bumpKeyMutation(liveKey);
6087
+ }
6088
+ }
6089
+ for (const inflightKey of Array.from(this.inflight.keys())) {
6090
+ if (inflightKey.startsWith(pfx)) {
6091
+ this._bumpKeyMutation(inflightKey);
6092
+ this.inflight.delete(inflightKey);
6093
+ }
6094
+ }
6095
+ this._addPatternTombstone(pfx);
5914
6096
  this.l1.deletePattern(k);
5915
6097
  } else {
6098
+ this._globalEpoch++;
6099
+ this.inflight.clear();
6100
+ this._patternTombstones.length = 0;
5916
6101
  this.l1.clear();
5917
6102
  if (!this._diskDisabled) this.disk.clear();
5918
6103
  this._l1Counters.clear();
5919
6104
  this.tagIndex.clear();
5920
6105
  this.tagVersions.clear();
6106
+ this._pendingDiskDeletes.clear();
6107
+ this._keyMutationEpochs.clear();
5921
6108
  }
5922
6109
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
5923
6110
  try {
@@ -5929,13 +6116,23 @@ var CacheService = class _CacheService {
5929
6116
  this.logger.debug("clear: Redis unavailable", { error: err.message });
5930
6117
  }
5931
6118
  }
5932
- void this.publishInvalidation(
5933
- "del-glob",
5934
- k ?? (this._namespace ? `${this._namespace}:*` : "*"),
5935
- void 0,
5936
- false,
5937
- true
5938
- );
6119
+ if (this.opts.awaitInvalidationBackplane) {
6120
+ await this.publishInvalidation(
6121
+ "del-glob",
6122
+ k ?? (this._namespace ? `${this._namespace}:*` : "*"),
6123
+ void 0,
6124
+ false,
6125
+ true
6126
+ );
6127
+ } else {
6128
+ void this.publishInvalidation(
6129
+ "del-glob",
6130
+ k ?? (this._namespace ? `${this._namespace}:*` : "*"),
6131
+ void 0,
6132
+ false,
6133
+ true
6134
+ );
6135
+ }
5939
6136
  } catch (err) {
5940
6137
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
5941
6138
  span.recordException?.(err);
@@ -5950,6 +6147,7 @@ var CacheService = class _CacheService {
5950
6147
  * Returns the number of entries evicted.
5951
6148
  */
5952
6149
  rebalance() {
6150
+ this._assertActive("rebalance");
5953
6151
  return this.l1.rebalance();
5954
6152
  }
5955
6153
  /**
@@ -5958,6 +6156,7 @@ var CacheService = class _CacheService {
5958
6156
  * Only reflects L1 state — does not query Redis or disk.
5959
6157
  */
5960
6158
  ttl(cacheKey) {
6159
+ this._assertActive("ttl");
5961
6160
  return this.l1.ttl(this.nk(cacheKey));
5962
6161
  }
5963
6162
  /**
@@ -5965,6 +6164,7 @@ var CacheService = class _CacheService {
5965
6164
  * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
5966
6165
  */
5967
6166
  has(cacheKey) {
6167
+ this._assertActive("has");
5968
6168
  return this.l1.has(this.nk(cacheKey));
5969
6169
  }
5970
6170
  // ── Iteration ─────────────────────────────────────────────────────────────
@@ -5975,6 +6175,7 @@ var CacheService = class _CacheService {
5975
6175
  * for (const key of cache.keys()) console.log(key);
5976
6176
  */
5977
6177
  *keys() {
6178
+ this._assertActive("keys");
5978
6179
  const prefix = this._namespace ? this._namespace + ":" : "";
5979
6180
  for (const key of this.l1.liveKeys()) {
5980
6181
  if (prefix && !key.startsWith(prefix)) continue;
@@ -5989,6 +6190,7 @@ var CacheService = class _CacheService {
5989
6190
  * for (const val of cache.values<User>()) console.log(val.id);
5990
6191
  */
5991
6192
  *values() {
6193
+ this._assertActive("values");
5992
6194
  const prefix = this._namespace ? this._namespace + ":" : "";
5993
6195
  if (!prefix) {
5994
6196
  yield* this.l1.liveValues();
@@ -6007,6 +6209,7 @@ var CacheService = class _CacheService {
6007
6209
  * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
6008
6210
  */
6009
6211
  *entries() {
6212
+ this._assertActive("entries");
6010
6213
  const prefix = this._namespace ? this._namespace + ":" : "";
6011
6214
  for (const [key, entry] of this.l1.liveEntries()) {
6012
6215
  if (prefix && !key.startsWith(prefix)) continue;
@@ -6034,6 +6237,7 @@ var CacheService = class _CacheService {
6034
6237
  * `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
6035
6238
  */
6036
6239
  scan(fn) {
6240
+ this._assertActive("scan");
6037
6241
  const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
6038
6242
  this.l1.scan((key, entry, pfx) => {
6039
6243
  const value = entry.value !== void 0 ? entry.value : entry.data;
@@ -6047,6 +6251,7 @@ var CacheService = class _CacheService {
6047
6251
  * @param newTtlSeconds - The new TTL from now, in seconds.
6048
6252
  */
6049
6253
  async touch(cacheKey, newTtlSeconds) {
6254
+ this._assertActive("touch");
6050
6255
  const k = this.nk(cacheKey);
6051
6256
  const hit = this.l1.touch(k, newTtlSeconds * 1e3);
6052
6257
  if (hit && !this._redisDisabled) {
@@ -6067,6 +6272,7 @@ var CacheService = class _CacheService {
6067
6272
  * if (fresh !== null) return fresh; // serve from L1, no network hop
6068
6273
  */
6069
6274
  getIfFresh(cacheKey) {
6275
+ this._assertActive("getIfFresh");
6070
6276
  const k = this.nk(cacheKey);
6071
6277
  const entry = this.l1.getEntry(k);
6072
6278
  if (!entry) return null;
@@ -6084,6 +6290,7 @@ var CacheService = class _CacheService {
6084
6290
  * const val = await cache.peek<User>('user:123');
6085
6291
  */
6086
6292
  async peek(cacheKey) {
6293
+ this._assertActive("peek");
6087
6294
  const k = this.nk(cacheKey);
6088
6295
  const l1Hit = this.l1.get(k);
6089
6296
  if (l1Hit !== null) {
@@ -6093,25 +6300,32 @@ var CacheService = class _CacheService {
6093
6300
  if (this.opts.frozen) deepFreeze(val);
6094
6301
  return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6095
6302
  }
6096
- if (!this._diskDisabled && this.watchdog.isDiskAllowed()) {
6097
- const diskStart = performance.now();
6098
- const diskHit = this.disk.load(k);
6099
- const diskElapsed = performance.now() - diskStart;
6100
- this.watchdog.recordDisk(diskElapsed);
6101
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6102
- if (diskHit !== null) {
6103
- const promoted = this.l1.importEntries(
6104
- [{ key: k, entry: diskHit }],
6105
- this.opts.forbiddenSnapshotPrefixes
6106
- );
6107
- if (promoted > 0) {
6108
- const l1Check = this.l1.get(k);
6109
- if (l1Check !== null) {
6110
- this.counters.gets++;
6111
- this.counters.diskHits++;
6112
- const val = l1Check.value;
6113
- if (this.opts.frozen) deepFreeze(val);
6114
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6303
+ if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
6304
+ if (this._isTombstonedByPattern(k)) {
6305
+ try {
6306
+ this.disk.delete(k);
6307
+ } catch {
6308
+ }
6309
+ } else if (this.watchdog.isDiskAllowed()) {
6310
+ const diskStart = performance.now();
6311
+ const diskHit = this.disk.load(k);
6312
+ const diskElapsed = performance.now() - diskStart;
6313
+ this.watchdog.recordDisk(diskElapsed);
6314
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6315
+ if (diskHit !== null) {
6316
+ const promoted = this.l1.importEntries(
6317
+ [{ key: k, entry: diskHit }],
6318
+ this.opts.forbiddenSnapshotPrefixes
6319
+ );
6320
+ if (promoted > 0) {
6321
+ const l1Check = this.l1.get(k);
6322
+ if (l1Check !== null) {
6323
+ this.counters.gets++;
6324
+ this.counters.diskHits++;
6325
+ const val = l1Check.value;
6326
+ if (this.opts.frozen) deepFreeze(val);
6327
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6328
+ }
6115
6329
  }
6116
6330
  }
6117
6331
  }
@@ -6149,6 +6363,7 @@ var CacheService = class _CacheService {
6149
6363
  * `(key) => number` so heterogeneous TTLs can be batched in one call.
6150
6364
  */
6151
6365
  async mget(keys, fetchFn, ttl = 300, priority) {
6366
+ this._assertActive("mget");
6152
6367
  const span = this._startSpan("tricache.mget");
6153
6368
  if (this.opts.tracer) {
6154
6369
  span.setAttribute("cache.batch.size", keys.length);
@@ -6217,8 +6432,16 @@ var CacheService = class _CacheService {
6217
6432
  }
6218
6433
  if (!this._diskDisabled && missKeys.length > 0) {
6219
6434
  for (let j = missKeys.length - 1; j >= 0; j--) {
6220
- if (!this.watchdog.isDiskAllowed()) continue;
6221
6435
  const k = this.nk(missKeys[j]);
6436
+ if (this._pendingDiskDeletes.has(k)) continue;
6437
+ if (this._isTombstonedByPattern(k)) {
6438
+ try {
6439
+ this.disk.delete(k);
6440
+ } catch {
6441
+ }
6442
+ continue;
6443
+ }
6444
+ if (!this.watchdog.isDiskAllowed()) continue;
6222
6445
  const diskStart = performance.now();
6223
6446
  const diskHit = this.disk.load(k);
6224
6447
  const diskElapsed = performance.now() - diskStart;
@@ -6298,6 +6521,7 @@ var CacheService = class _CacheService {
6298
6521
  * });
6299
6522
  */
6300
6523
  async mset(entries) {
6524
+ this._assertActive("mset");
6301
6525
  const span = this._startSpan("tricache.mset");
6302
6526
  const keys = Object.keys(entries);
6303
6527
  if (this.opts.tracer) {
@@ -6325,6 +6549,7 @@ var CacheService = class _CacheService {
6325
6549
  * await cache.mdel(['user:1', 'user:2', 'user:3']);
6326
6550
  */
6327
6551
  async mdel(keys) {
6552
+ this._assertActive("mdel");
6328
6553
  const span = this._startSpan("tricache.mdel");
6329
6554
  if (this.opts.tracer) {
6330
6555
  span.setAttribute("cache.batch.size", keys.length);
@@ -6352,6 +6577,7 @@ var CacheService = class _CacheService {
6352
6577
  * console.log(`Warmed ${loaded} keys from Redis`);
6353
6578
  */
6354
6579
  async warmFromL2(pattern, opts) {
6580
+ this._assertActive("warmFromL2");
6355
6581
  if (this._redisDisabled) return 0;
6356
6582
  try {
6357
6583
  const client = await this.getRedis();
@@ -6398,6 +6624,7 @@ var CacheService = class _CacheService {
6398
6624
  * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
6399
6625
  */
6400
6626
  async invalidateTag(tag) {
6627
+ this._assertActive("invalidateTag");
6401
6628
  const span = this._startSpan("tricache.invalidate_tag");
6402
6629
  if (this.opts.tracer) {
6403
6630
  span.setAttribute("cache.tag", tag);
@@ -6419,15 +6646,27 @@ var CacheService = class _CacheService {
6419
6646
  const current = this.tagVersions.get(tag)?.version ?? 0;
6420
6647
  newVer = current + 1;
6421
6648
  }
6422
- this._setLocalTagVersion(tag, newVer, Date.now());
6423
- void this.publishInvalidation("tag_incr", tag, newVer, false, true);
6649
+ this._setLocalTagVersion(tag, newVer, performance.now());
6650
+ if (this.opts.awaitInvalidationBackplane) {
6651
+ await this.publishInvalidation("tag_incr", tag, newVer, false, true);
6652
+ } else {
6653
+ void this.publishInvalidation("tag_incr", tag, newVer, false, true);
6654
+ }
6424
6655
  return;
6425
6656
  }
6426
6657
  const tagKey = this.nk(`_tag_:${tag}`);
6427
6658
  const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
6428
6659
  for (const k of members) {
6429
6660
  this.l1.delete(k);
6430
- if (!this._diskDisabled) this.disk.delete(k);
6661
+ this._bumpKeyMutation(k);
6662
+ this._pendingDiskDeletes.add(k);
6663
+ setImmediate(() => {
6664
+ try {
6665
+ if (!this._diskDisabled) this.disk.delete(k);
6666
+ } finally {
6667
+ this._pendingDiskDeletes.delete(k);
6668
+ }
6669
+ });
6431
6670
  }
6432
6671
  this.tagIndex.delete(tagKey);
6433
6672
  if (!this._redisDisabled) {
@@ -6465,13 +6704,14 @@ var CacheService = class _CacheService {
6465
6704
  * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
6466
6705
  */
6467
6706
  async invalidateTags(tags) {
6707
+ this._assertActive("invalidateTags");
6468
6708
  if (tags.length === 0) return;
6469
6709
  if (tags.length === 1) {
6470
6710
  await this.invalidateTag(tags[0]);
6471
6711
  return;
6472
6712
  }
6473
6713
  if (this.opts.tagStrategy === "generational") {
6474
- const now = Date.now();
6714
+ const now = performance.now();
6475
6715
  if (!this._redisDisabled) {
6476
6716
  try {
6477
6717
  const client = await this.getRedis();
@@ -6482,7 +6722,11 @@ var CacheService = class _CacheService {
6482
6722
  const [err, newVer] = results[i] ?? [null, null];
6483
6723
  const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
6484
6724
  this._setLocalTagVersion(tags[i], ver, now);
6485
- void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
6725
+ if (this.opts.awaitInvalidationBackplane) {
6726
+ await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
6727
+ } else {
6728
+ void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
6729
+ }
6486
6730
  }
6487
6731
  return;
6488
6732
  } catch (err) {
@@ -6492,7 +6736,11 @@ var CacheService = class _CacheService {
6492
6736
  for (const tag of tags) {
6493
6737
  const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
6494
6738
  this._setLocalTagVersion(tag, ver, now);
6495
- void this.publishInvalidation("tag_incr", tag, ver, false, true);
6739
+ if (this.opts.awaitInvalidationBackplane) {
6740
+ await this.publishInvalidation("tag_incr", tag, ver, false, true);
6741
+ } else {
6742
+ void this.publishInvalidation("tag_incr", tag, ver, false, true);
6743
+ }
6496
6744
  }
6497
6745
  return;
6498
6746
  }
@@ -6507,7 +6755,15 @@ var CacheService = class _CacheService {
6507
6755
  }
6508
6756
  for (const k of allMembers) {
6509
6757
  this.l1.delete(k);
6510
- 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
+ });
6511
6767
  }
6512
6768
  if (!this._redisDisabled) {
6513
6769
  try {
@@ -6544,6 +6800,7 @@ var CacheService = class _CacheService {
6544
6800
  * `l2` is `null` when Redis is disabled.
6545
6801
  */
6546
6802
  async ping() {
6803
+ this._assertActive("ping");
6547
6804
  const t0 = Date.now();
6548
6805
  this.l1.has("__ping__");
6549
6806
  const l1 = Date.now() - t0;
@@ -6623,6 +6880,7 @@ var CacheService = class _CacheService {
6623
6880
  * Returns the number of keys written.
6624
6881
  */
6625
6882
  async drainToL2() {
6883
+ this._assertActive("drainToL2");
6626
6884
  if (this._redisDisabled) return 0;
6627
6885
  try {
6628
6886
  const client = await this.getRedis();
@@ -6666,6 +6924,7 @@ var CacheService = class _CacheService {
6666
6924
  * if (!claimed) return res.status(409).json({ error: 'duplicate request' });
6667
6925
  */
6668
6926
  async setIfAbsent(cacheKey, value, ttlSeconds = 300, priority) {
6927
+ this._assertActive("setIfAbsent");
6669
6928
  const k = this.nk(cacheKey);
6670
6929
  if (this.l1.has(k)) return false;
6671
6930
  if (!this._redisDisabled) {
@@ -6684,6 +6943,8 @@ var CacheService = class _CacheService {
6684
6943
  }
6685
6944
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
6686
6945
  const p = priority ?? inferPriority(cacheKey);
6946
+ this._bumpKeyMutation(k);
6947
+ this._pendingDiskDeletes.delete(k);
6687
6948
  this.l1.set(k, value, ttlMs, p);
6688
6949
  this.counters.sets++;
6689
6950
  return true;
@@ -6702,6 +6963,7 @@ var CacheService = class _CacheService {
6702
6963
  * @param options TTL, acquire timeout, and retry polling intervals.
6703
6964
  */
6704
6965
  async lock(resourceKey, fn, options) {
6966
+ this._assertActive("lock");
6705
6967
  const ttlSeconds = Math.max(1, options?.ttl ?? 30);
6706
6968
  const acquireTimeout = Math.max(0, options?.acquireTimeout ?? 5e3);
6707
6969
  const retryInterval = Math.max(10, options?.retryInterval ?? 100);
@@ -6728,6 +6990,10 @@ var CacheService = class _CacheService {
6728
6990
  }
6729
6991
  } catch (err) {
6730
6992
  if (err.message.startsWith("Failed to acquire lock")) throw err;
6993
+ const failClosed = options?.failClosedOnRedisError ?? this.opts.lockFailClosed;
6994
+ if (failClosed) {
6995
+ throw new Error(`Distributed lock acquisition failed for resource "${resourceKey}" due to Redis error: ${err.message}`);
6996
+ }
6731
6997
  this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
6732
6998
  resourceKey,
6733
6999
  error: err.message
@@ -7073,6 +7339,7 @@ var CacheService = class _CacheService {
7073
7339
  * the previous key for seamless fallback decryption of existing cache entries.
7074
7340
  */
7075
7341
  async rotateEncryptionKey(newKeyBase64, newMode) {
7342
+ this._assertActive("rotateEncryptionKey");
7076
7343
  this.enc.rotateKey(newKeyBase64, newMode);
7077
7344
  if (this._workerPool) {
7078
7345
  await this._workerPool.drainAndReinit(this.enc.toWorkerInit());
@@ -7082,6 +7349,8 @@ var CacheService = class _CacheService {
7082
7349
  /** Close Redis connections and stop all background timers. */
7083
7350
  async destroy() {
7084
7351
  this._destroyed = true;
7352
+ this._pendingDiskDeletes.clear();
7353
+ this._keyMutationEpochs.clear();
7085
7354
  const g = globalThis;
7086
7355
  const key = _CacheService.globalKey(this.opts);
7087
7356
  if (g[key] === this) {