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
package/dist/cli.cjs CHANGED
@@ -33,6 +33,7 @@ __export(cli_exports, {
33
33
  runCli: () => runCli
34
34
  });
35
35
  module.exports = __toCommonJS(cli_exports);
36
+ var import_node_fs3 = require("fs");
36
37
  var import_node_util = require("util");
37
38
 
38
39
  // src/cache-service.ts
@@ -3664,6 +3665,26 @@ async function findActiveSockets() {
3664
3665
  active.push(currentPipe);
3665
3666
  } catch {
3666
3667
  }
3668
+ try {
3669
+ const { execFileSync } = await import("child_process");
3670
+ const stdout = execFileSync(
3671
+ "powershell.exe",
3672
+ ["-NoProfile", "-NonInteractive", "-Command", '[System.IO.Directory]::GetFiles("\\\\.\\pipe\\") | Where-Object { $_ -like "*tricache-*" }'],
3673
+ { timeout: 1500, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }
3674
+ );
3675
+ const candidates = stdout.split(/\r?\n/).map((name) => name.trim()).filter((name) => name.length > 0 && !active.includes(name));
3676
+ await Promise.all(
3677
+ candidates.map(async (pipePath) => {
3678
+ const testClient = new IpcTelemetryClient(pipePath);
3679
+ try {
3680
+ await testClient.ping(100);
3681
+ active.push(pipePath);
3682
+ } catch {
3683
+ }
3684
+ })
3685
+ );
3686
+ } catch {
3687
+ }
3667
3688
  return active;
3668
3689
  }
3669
3690
  const dir = process.env.TMPDIR || "/tmp";
@@ -4093,6 +4114,52 @@ var CacheService = class _CacheService {
4093
4114
  streamClient = null;
4094
4115
  _lastStreamId = "$";
4095
4116
  _destroyed = false;
4117
+ _pendingDiskDeletes = /* @__PURE__ */ new Set();
4118
+ _globalEpoch = 0;
4119
+ _keyMutationEpochs = /* @__PURE__ */ new Map();
4120
+ /**
4121
+ * Pattern tombstones for disk tier.
4122
+ * Files in the disk tier are keyed by SHA-256 of namespacedKey.
4123
+ * Wildcard pattern deletes cannot scan the filesystem synchronously, so we maintain
4124
+ * pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
4125
+ */
4126
+ _patternTombstones = [];
4127
+ _addPatternTombstone(prefix) {
4128
+ const now = Date.now();
4129
+ while (this._patternTombstones.length > 0 && now - this._patternTombstones[0].createdAt > 36e5) {
4130
+ this._patternTombstones.shift();
4131
+ }
4132
+ if (this._patternTombstones.length >= 2e3) {
4133
+ this._patternTombstones.shift();
4134
+ }
4135
+ this._patternTombstones.push({ prefix, createdAt: now });
4136
+ }
4137
+ _isTombstonedByPattern(namespacedKey) {
4138
+ if (this._patternTombstones.length === 0) return false;
4139
+ for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
4140
+ if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
4141
+ return true;
4142
+ }
4143
+ }
4144
+ return false;
4145
+ }
4146
+ _assertActive(operation) {
4147
+ if (this._destroyed) {
4148
+ throw new Error(`TriCacheError: Cannot perform '${operation}' on a destroyed CacheService instance (namespace: '${this._namespace || "(default)"}').`);
4149
+ }
4150
+ }
4151
+ _bumpKeyMutation(namespacedKey) {
4152
+ const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
4153
+ this._keyMutationEpochs.set(namespacedKey, next);
4154
+ if (this._keyMutationEpochs.size > 5e4) {
4155
+ const oldest = this._keyMutationEpochs.keys().next().value;
4156
+ if (oldest !== void 0) this._keyMutationEpochs.delete(oldest);
4157
+ }
4158
+ return next;
4159
+ }
4160
+ _getKeyMutationEpoch(namespacedKey) {
4161
+ return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
4162
+ }
4096
4163
  _ipcServer;
4097
4164
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
4098
4165
  _subDisconnectedAt = null;
@@ -4181,6 +4248,8 @@ var CacheService = class _CacheService {
4181
4248
  ),
4182
4249
  snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
4183
4250
  invalidationBackplane: options.invalidationBackplane ?? true,
4251
+ awaitInvalidationBackplane: options.awaitInvalidationBackplane ?? false,
4252
+ lockFailClosed: options.lockFailClosed ?? false,
4184
4253
  oomProtection: options.oomProtection ?? true,
4185
4254
  oomHeapThreshold: options.oomHeapThreshold ?? 0.85,
4186
4255
  oomCheckIntervalMs: options.oomCheckIntervalMs ?? 1e4,
@@ -4546,7 +4615,9 @@ var CacheService = class _CacheService {
4546
4615
  "adaptiveTtl",
4547
4616
  "l2WriteMode",
4548
4617
  "instanceName",
4549
- "invalidationBackplane"
4618
+ "invalidationBackplane",
4619
+ "awaitInvalidationBackplane",
4620
+ "lockFailClosed"
4550
4621
  ];
4551
4622
  /** Returns the names of options that differ between `a` and the live `b`. */
4552
4623
  static optionsDiff(a, b) {
@@ -4587,6 +4658,8 @@ var CacheService = class _CacheService {
4587
4658
  frozen: o.frozen,
4588
4659
  adaptiveTtl: o.adaptiveTtl,
4589
4660
  invalidationBackplane: o.invalidationBackplane,
4661
+ awaitInvalidationBackplane: o.awaitInvalidationBackplane,
4662
+ lockFailClosed: o.lockFailClosed,
4590
4663
  strictSingleton: o.strictSingleton,
4591
4664
  remoteSnapshot: o.remoteSnapshot,
4592
4665
  crossRegion: o.crossRegion
@@ -4872,16 +4945,36 @@ var CacheService = class _CacheService {
4872
4945
  _applyInvalidationEvent(op, key, tagVersion) {
4873
4946
  if (op === "del") {
4874
4947
  this.l1.delete(key);
4948
+ this._bumpKeyMutation(key);
4949
+ this.inflight.delete(key);
4950
+ this._pendingDiskDeletes.add(key);
4875
4951
  setImmediate(() => {
4876
- if (!this._diskDisabled) this.disk.delete(key);
4952
+ try {
4953
+ if (!this._diskDisabled) this.disk.delete(key);
4954
+ } finally {
4955
+ this._pendingDiskDeletes.delete(key);
4956
+ }
4877
4957
  });
4878
4958
  this._cascadeDependencies(key);
4879
4959
  } else if (op === "del-glob") {
4880
4960
  this.l1.deletePattern(key);
4961
+ const pfx = key.endsWith("*") ? key.slice(0, -1) : key;
4962
+ for (const liveKey of this.l1.liveKeys()) {
4963
+ if (liveKey.startsWith(pfx)) {
4964
+ this._bumpKeyMutation(liveKey);
4965
+ }
4966
+ }
4967
+ for (const inflightKey of Array.from(this.inflight.keys())) {
4968
+ if (inflightKey.startsWith(pfx)) {
4969
+ this._bumpKeyMutation(inflightKey);
4970
+ this.inflight.delete(inflightKey);
4971
+ }
4972
+ }
4973
+ this._addPatternTombstone(pfx);
4881
4974
  } else if (op === "tag_incr") {
4882
4975
  const tag = key;
4883
4976
  const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
4884
- this._setLocalTagVersion(tag, ver, Date.now());
4977
+ this._setLocalTagVersion(tag, ver, performance.now());
4885
4978
  }
4886
4979
  this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
4887
4980
  }
@@ -4909,7 +5002,11 @@ var CacheService = class _CacheService {
4909
5002
  if (!isCrossRegionRelay && this.opts.crossRegion) {
4910
5003
  const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
4911
5004
  if (shouldBroadcast) {
4912
- void this._broadcastCrossRegion(op, key, tagVersion);
5005
+ if (this.opts.awaitInvalidationBackplane) {
5006
+ await this._broadcastCrossRegion(op, key, tagVersion);
5007
+ } else {
5008
+ void this._broadcastCrossRegion(op, key, tagVersion);
5009
+ }
4913
5010
  }
4914
5011
  }
4915
5012
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
@@ -4950,7 +5047,11 @@ var CacheService = class _CacheService {
4950
5047
  );
4951
5048
  }
4952
5049
  this.counters.invSent++;
4953
- } catch {
5050
+ } catch (err) {
5051
+ this.logger.warn("Backplane invalidation publish failed", { op, key, error: err.message });
5052
+ if (this.opts.awaitInvalidationBackplane) {
5053
+ throw err;
5054
+ }
4954
5055
  }
4955
5056
  }
4956
5057
  _markCrossRegionEventSeen(id) {
@@ -5154,6 +5255,7 @@ var CacheService = class _CacheService {
5154
5255
  }
5155
5256
  }
5156
5257
  async getRedis() {
5258
+ this._assertActive("getRedis");
5157
5259
  if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
5158
5260
  if (this.redis) return this.redis;
5159
5261
  if (this.redisConnecting) return this.redisConnecting;
@@ -5482,6 +5584,7 @@ var CacheService = class _CacheService {
5482
5584
  * Caches negative lookups to avoid repeated DB hits for missing keys.
5483
5585
  */
5484
5586
  async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
5587
+ this._assertActive("get");
5485
5588
  const span = this._startSpan("tricache.get");
5486
5589
  if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
5487
5590
  const k = this.nk(cacheKey);
@@ -5513,7 +5616,14 @@ var CacheService = class _CacheService {
5513
5616
  if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
5514
5617
  const priority2 = optPriority ?? inferPriority(cacheKey);
5515
5618
  this.revalidating.add(k);
5516
- void this._revalidate(k, fetchFn, ttlSeconds * 1e3, swrGraceMs2, priority2);
5619
+ void this._revalidate(
5620
+ k,
5621
+ fetchFn,
5622
+ ttlSeconds * 1e3,
5623
+ swrGraceMs2,
5624
+ priority2,
5625
+ l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
5626
+ );
5517
5627
  this.counters.swrRevalidations++;
5518
5628
  this.logger.debug("SWR: serving stale, revalidating", { cacheKey });
5519
5629
  } else {
@@ -5532,7 +5642,14 @@ var CacheService = class _CacheService {
5532
5642
  if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
5533
5643
  const priority2 = optPriority ?? inferPriority(cacheKey);
5534
5644
  this.revalidating.add(k);
5535
- void this._revalidate(k, fetchFn, entryTtl, optSwr * 1e3, priority2);
5645
+ void this._revalidate(
5646
+ k,
5647
+ fetchFn,
5648
+ entryTtl,
5649
+ optSwr * 1e3,
5650
+ priority2,
5651
+ l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
5652
+ );
5536
5653
  this.counters.swrRevalidations++;
5537
5654
  this.logger.debug(
5538
5655
  shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
@@ -5558,44 +5675,52 @@ var CacheService = class _CacheService {
5558
5675
  span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
5559
5676
  return existing;
5560
5677
  }
5678
+ const mutationEpochAtStart = this._getKeyMutationEpoch(k);
5561
5679
  const executionPromise = (async () => {
5562
5680
  try {
5563
- if (!this._diskDisabled) {
5564
- const isDiskAllowed = this.watchdog.isDiskAllowed();
5565
- if (isDiskAllowed) {
5566
- const diskStart = performance.now();
5567
- const diskHit = this.disk.load(k);
5568
- const diskElapsed = performance.now() - diskStart;
5569
- this.watchdog.recordDisk(diskElapsed);
5570
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
5571
- if (diskHit !== null) {
5572
- let isDiskStale = false;
5573
- if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
5574
- const tags = Object.keys(diskHit.tagVersions);
5575
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5576
- for (let i = 0; i < tags.length; i++) {
5577
- if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
5578
- isDiskStale = true;
5579
- break;
5681
+ if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
5682
+ if (this._isTombstonedByPattern(k)) {
5683
+ try {
5684
+ this.disk.delete(k);
5685
+ } catch {
5686
+ }
5687
+ } else {
5688
+ const isDiskAllowed = this.watchdog.isDiskAllowed();
5689
+ if (isDiskAllowed) {
5690
+ const diskStart = performance.now();
5691
+ const diskHit = this.disk.load(k);
5692
+ const diskElapsed = performance.now() - diskStart;
5693
+ this.watchdog.recordDisk(diskElapsed);
5694
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
5695
+ if (diskHit !== null) {
5696
+ let isDiskStale = false;
5697
+ if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
5698
+ const tags = Object.keys(diskHit.tagVersions);
5699
+ const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5700
+ for (let i = 0; i < tags.length; i++) {
5701
+ if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
5702
+ isDiskStale = true;
5703
+ break;
5704
+ }
5580
5705
  }
5581
5706
  }
5582
- }
5583
- if (isDiskStale) {
5584
- this.disk.delete(k);
5585
- } else {
5586
- const promoted = this.l1.importEntries(
5587
- [{ key: k, entry: diskHit }],
5588
- this.opts.forbiddenSnapshotPrefixes
5589
- );
5590
- if (promoted > 0) {
5591
- const l1Check = this.l1.get(k);
5592
- if (l1Check !== null) {
5593
- this.counters.diskHits++;
5594
- this.opts.onHit?.(cacheKey, "disk");
5595
- this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
5596
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
5597
- if (this.opts.frozen) deepFreeze(l1Check.value);
5598
- return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
5707
+ if (isDiskStale) {
5708
+ this.disk.delete(k);
5709
+ } else {
5710
+ const promoted = this.l1.importEntries(
5711
+ [{ key: k, entry: diskHit }],
5712
+ this.opts.forbiddenSnapshotPrefixes
5713
+ );
5714
+ if (promoted > 0) {
5715
+ const l1Check = this.l1.get(k);
5716
+ if (l1Check !== null) {
5717
+ this.counters.diskHits++;
5718
+ this.opts.onHit?.(cacheKey, "disk");
5719
+ this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
5720
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
5721
+ if (this.opts.frozen) deepFreeze(l1Check.value);
5722
+ return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
5723
+ }
5599
5724
  }
5600
5725
  }
5601
5726
  }
@@ -5706,6 +5831,18 @@ var CacheService = class _CacheService {
5706
5831
  await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
5707
5832
  }
5708
5833
  }
5834
+ if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
5835
+ this.logger.debug("Aborting in-flight cache commit \u2014 key was mutated or deleted during fetch", { cacheKey });
5836
+ span.setAttribute("cache.aborted_mutation_race", true);
5837
+ const current = this.l1.get(k);
5838
+ if (current && !current.isStale && current.value !== void 0) {
5839
+ const freshVal = current.value;
5840
+ if (this.opts.frozen) deepFreeze(freshVal);
5841
+ return this.opts.cloneStrategy === "structuredClone" && freshVal != null && typeof freshVal === "object" ? structuredClone(freshVal) : freshVal;
5842
+ }
5843
+ if (this.opts.frozen) deepFreeze(data);
5844
+ return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
5845
+ }
5709
5846
  this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
5710
5847
  if (!this._redisDisabled) {
5711
5848
  try {
@@ -5822,22 +5959,40 @@ var CacheService = class _CacheService {
5822
5959
  const ttl = options?.ttl ?? 300;
5823
5960
  return this.get(cacheKey, fetchFn, ttl, options);
5824
5961
  }
5825
- async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
5962
+ async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority, knownTagVersions) {
5963
+ const startEpoch = this._getKeyMutationEpoch(cacheKey);
5826
5964
  try {
5827
5965
  const fetchStart = Date.now();
5828
5966
  const data = await fetchFn();
5829
5967
  const delta = Date.now() - fetchStart;
5830
5968
  const staleAt = Date.now() + ttlMs;
5969
+ if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
5970
+ this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during fetch", { cacheKey });
5971
+ return;
5972
+ }
5831
5973
  if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
5832
5974
  let activeTagVersions;
5833
5975
  const l1Existing = this.l1.get(cacheKey);
5834
- if (this.opts.tagStrategy === "generational" && l1Existing?.tagVersions) {
5835
- const tags = Object.keys(l1Existing.tagVersions);
5976
+ const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
5977
+ if (this.opts.tagStrategy === "generational" && tagVersionsSource) {
5978
+ const tags = Object.keys(tagVersionsSource);
5836
5979
  const vers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5837
5980
  activeTagVersions = {};
5838
5981
  for (let i = 0; i < tags.length; i++) {
5839
5982
  activeTagVersions[tags[i]] = vers[i];
5840
5983
  }
5984
+ if (knownTagVersions) {
5985
+ for (const t of tags) {
5986
+ if (knownTagVersions[t] !== void 0 && activeTagVersions[t] !== knownTagVersions[t]) {
5987
+ this.logger.debug("SWR: aborting revalidation commit \u2014 tag version bumped during revalidation", { cacheKey, tag: t });
5988
+ return;
5989
+ }
5990
+ }
5991
+ }
5992
+ }
5993
+ if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
5994
+ this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
5995
+ return;
5841
5996
  }
5842
5997
  this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
5843
5998
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
@@ -5881,6 +6036,7 @@ var CacheService = class _CacheService {
5881
6036
  // ── Explicit set / delete ─────────────────────────────────────────────────
5882
6037
  /** Explicitly write a value into L1 (+ L2 in production). */
5883
6038
  async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
6039
+ this._assertActive("set");
5884
6040
  const span = this._startSpan("tricache.set");
5885
6041
  if (this.opts.tracer) {
5886
6042
  span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
@@ -5891,6 +6047,9 @@ var CacheService = class _CacheService {
5891
6047
  const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
5892
6048
  const p = priority ?? inferPriority(cacheKey);
5893
6049
  const k = this.nk(cacheKey);
6050
+ this._bumpKeyMutation(k);
6051
+ this.inflight.delete(k);
6052
+ this._pendingDiskDeletes.delete(k);
5894
6053
  this.counters.sets++;
5895
6054
  let activeTagVersions;
5896
6055
  if (opts?.tags?.length) {
@@ -5945,7 +6104,11 @@ var CacheService = class _CacheService {
5945
6104
  this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
5946
6105
  }
5947
6106
  }
5948
- void this.publishInvalidation("del", k);
6107
+ if (this.opts.awaitInvalidationBackplane) {
6108
+ await this.publishInvalidation("del", k);
6109
+ } else {
6110
+ void this.publishInvalidation("del", k);
6111
+ }
5949
6112
  } catch (err) {
5950
6113
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
5951
6114
  span.recordException?.(err);
@@ -5992,6 +6155,7 @@ var CacheService = class _CacheService {
5992
6155
  * await cache.delete('user:abc:*'); // all keys for user abc
5993
6156
  */
5994
6157
  async delete(cacheKey) {
6158
+ this._assertActive("delete");
5995
6159
  const span = this._startSpan("tricache.delete");
5996
6160
  if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
5997
6161
  try {
@@ -5999,11 +6163,31 @@ var CacheService = class _CacheService {
5999
6163
  const k = this.nk(cacheKey);
6000
6164
  this.counters.deletes++;
6001
6165
  if (isPattern) {
6166
+ const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6167
+ for (const liveKey of this.l1.liveKeys()) {
6168
+ if (liveKey.startsWith(pfx)) {
6169
+ this._bumpKeyMutation(liveKey);
6170
+ }
6171
+ }
6172
+ for (const inflightKey of Array.from(this.inflight.keys())) {
6173
+ if (inflightKey.startsWith(pfx)) {
6174
+ this._bumpKeyMutation(inflightKey);
6175
+ this.inflight.delete(inflightKey);
6176
+ }
6177
+ }
6178
+ this._addPatternTombstone(pfx);
6002
6179
  this.l1.deletePattern(k);
6003
6180
  } else {
6181
+ this._bumpKeyMutation(k);
6182
+ this.inflight.delete(k);
6004
6183
  this.l1.delete(k);
6184
+ this._pendingDiskDeletes.add(k);
6005
6185
  setImmediate(() => {
6006
- if (!this._diskDisabled) this.disk.delete(k);
6186
+ try {
6187
+ if (!this._diskDisabled) this.disk.delete(k);
6188
+ } finally {
6189
+ this._pendingDiskDeletes.delete(k);
6190
+ }
6007
6191
  });
6008
6192
  this._cascadeDependencies(k);
6009
6193
  for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
@@ -6027,7 +6211,11 @@ var CacheService = class _CacheService {
6027
6211
  this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
6028
6212
  }
6029
6213
  }
6030
- void this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
6214
+ if (this.opts.awaitInvalidationBackplane) {
6215
+ await this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
6216
+ } else {
6217
+ void this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
6218
+ }
6031
6219
  } catch (err) {
6032
6220
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
6033
6221
  span.recordException?.(err);
@@ -6054,6 +6242,7 @@ var CacheService = class _CacheService {
6054
6242
  * fleet-wide.
6055
6243
  */
6056
6244
  async increment(cacheKey, ttlSeconds) {
6245
+ this._assertActive("increment");
6057
6246
  const k = this.nk(cacheKey);
6058
6247
  if (this._redisDisabled) {
6059
6248
  if (!this._incrementFallbackWarned) {
@@ -6095,19 +6284,38 @@ var CacheService = class _CacheService {
6095
6284
  * await cache.clear('user:abc'); // flush all keys for one user
6096
6285
  */
6097
6286
  async clear(prefix) {
6287
+ this._assertActive("clear");
6098
6288
  const span = this._startSpan("tricache.clear");
6099
6289
  if (this.opts.tracer) span.setAttribute("cache.prefix", prefix || "*");
6100
6290
  try {
6101
6291
  this.counters.deletes++;
6102
6292
  const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
6103
6293
  if (k) {
6294
+ const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6295
+ for (const liveKey of this.l1.liveKeys()) {
6296
+ if (liveKey.startsWith(pfx)) {
6297
+ this._bumpKeyMutation(liveKey);
6298
+ }
6299
+ }
6300
+ for (const inflightKey of Array.from(this.inflight.keys())) {
6301
+ if (inflightKey.startsWith(pfx)) {
6302
+ this._bumpKeyMutation(inflightKey);
6303
+ this.inflight.delete(inflightKey);
6304
+ }
6305
+ }
6306
+ this._addPatternTombstone(pfx);
6104
6307
  this.l1.deletePattern(k);
6105
6308
  } else {
6309
+ this._globalEpoch++;
6310
+ this.inflight.clear();
6311
+ this._patternTombstones.length = 0;
6106
6312
  this.l1.clear();
6107
6313
  if (!this._diskDisabled) this.disk.clear();
6108
6314
  this._l1Counters.clear();
6109
6315
  this.tagIndex.clear();
6110
6316
  this.tagVersions.clear();
6317
+ this._pendingDiskDeletes.clear();
6318
+ this._keyMutationEpochs.clear();
6111
6319
  }
6112
6320
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6113
6321
  try {
@@ -6119,13 +6327,23 @@ var CacheService = class _CacheService {
6119
6327
  this.logger.debug("clear: Redis unavailable", { error: err.message });
6120
6328
  }
6121
6329
  }
6122
- void this.publishInvalidation(
6123
- "del-glob",
6124
- k ?? (this._namespace ? `${this._namespace}:*` : "*"),
6125
- void 0,
6126
- false,
6127
- true
6128
- );
6330
+ if (this.opts.awaitInvalidationBackplane) {
6331
+ await this.publishInvalidation(
6332
+ "del-glob",
6333
+ k ?? (this._namespace ? `${this._namespace}:*` : "*"),
6334
+ void 0,
6335
+ false,
6336
+ true
6337
+ );
6338
+ } else {
6339
+ void this.publishInvalidation(
6340
+ "del-glob",
6341
+ k ?? (this._namespace ? `${this._namespace}:*` : "*"),
6342
+ void 0,
6343
+ false,
6344
+ true
6345
+ );
6346
+ }
6129
6347
  } catch (err) {
6130
6348
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
6131
6349
  span.recordException?.(err);
@@ -6140,6 +6358,7 @@ var CacheService = class _CacheService {
6140
6358
  * Returns the number of entries evicted.
6141
6359
  */
6142
6360
  rebalance() {
6361
+ this._assertActive("rebalance");
6143
6362
  return this.l1.rebalance();
6144
6363
  }
6145
6364
  /**
@@ -6148,6 +6367,7 @@ var CacheService = class _CacheService {
6148
6367
  * Only reflects L1 state — does not query Redis or disk.
6149
6368
  */
6150
6369
  ttl(cacheKey) {
6370
+ this._assertActive("ttl");
6151
6371
  return this.l1.ttl(this.nk(cacheKey));
6152
6372
  }
6153
6373
  /**
@@ -6155,6 +6375,7 @@ var CacheService = class _CacheService {
6155
6375
  * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
6156
6376
  */
6157
6377
  has(cacheKey) {
6378
+ this._assertActive("has");
6158
6379
  return this.l1.has(this.nk(cacheKey));
6159
6380
  }
6160
6381
  // ── Iteration ─────────────────────────────────────────────────────────────
@@ -6165,6 +6386,7 @@ var CacheService = class _CacheService {
6165
6386
  * for (const key of cache.keys()) console.log(key);
6166
6387
  */
6167
6388
  *keys() {
6389
+ this._assertActive("keys");
6168
6390
  const prefix = this._namespace ? this._namespace + ":" : "";
6169
6391
  for (const key of this.l1.liveKeys()) {
6170
6392
  if (prefix && !key.startsWith(prefix)) continue;
@@ -6179,6 +6401,7 @@ var CacheService = class _CacheService {
6179
6401
  * for (const val of cache.values<User>()) console.log(val.id);
6180
6402
  */
6181
6403
  *values() {
6404
+ this._assertActive("values");
6182
6405
  const prefix = this._namespace ? this._namespace + ":" : "";
6183
6406
  if (!prefix) {
6184
6407
  yield* this.l1.liveValues();
@@ -6197,6 +6420,7 @@ var CacheService = class _CacheService {
6197
6420
  * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
6198
6421
  */
6199
6422
  *entries() {
6423
+ this._assertActive("entries");
6200
6424
  const prefix = this._namespace ? this._namespace + ":" : "";
6201
6425
  for (const [key, entry] of this.l1.liveEntries()) {
6202
6426
  if (prefix && !key.startsWith(prefix)) continue;
@@ -6224,6 +6448,7 @@ var CacheService = class _CacheService {
6224
6448
  * `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
6225
6449
  */
6226
6450
  scan(fn) {
6451
+ this._assertActive("scan");
6227
6452
  const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
6228
6453
  this.l1.scan((key, entry, pfx) => {
6229
6454
  const value = entry.value !== void 0 ? entry.value : entry.data;
@@ -6237,6 +6462,7 @@ var CacheService = class _CacheService {
6237
6462
  * @param newTtlSeconds - The new TTL from now, in seconds.
6238
6463
  */
6239
6464
  async touch(cacheKey, newTtlSeconds) {
6465
+ this._assertActive("touch");
6240
6466
  const k = this.nk(cacheKey);
6241
6467
  const hit = this.l1.touch(k, newTtlSeconds * 1e3);
6242
6468
  if (hit && !this._redisDisabled) {
@@ -6257,6 +6483,7 @@ var CacheService = class _CacheService {
6257
6483
  * if (fresh !== null) return fresh; // serve from L1, no network hop
6258
6484
  */
6259
6485
  getIfFresh(cacheKey) {
6486
+ this._assertActive("getIfFresh");
6260
6487
  const k = this.nk(cacheKey);
6261
6488
  const entry = this.l1.getEntry(k);
6262
6489
  if (!entry) return null;
@@ -6274,6 +6501,7 @@ var CacheService = class _CacheService {
6274
6501
  * const val = await cache.peek<User>('user:123');
6275
6502
  */
6276
6503
  async peek(cacheKey) {
6504
+ this._assertActive("peek");
6277
6505
  const k = this.nk(cacheKey);
6278
6506
  const l1Hit = this.l1.get(k);
6279
6507
  if (l1Hit !== null) {
@@ -6283,25 +6511,32 @@ var CacheService = class _CacheService {
6283
6511
  if (this.opts.frozen) deepFreeze(val);
6284
6512
  return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6285
6513
  }
6286
- if (!this._diskDisabled && this.watchdog.isDiskAllowed()) {
6287
- const diskStart = performance.now();
6288
- const diskHit = this.disk.load(k);
6289
- const diskElapsed = performance.now() - diskStart;
6290
- this.watchdog.recordDisk(diskElapsed);
6291
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6292
- if (diskHit !== null) {
6293
- const promoted = this.l1.importEntries(
6294
- [{ key: k, entry: diskHit }],
6295
- this.opts.forbiddenSnapshotPrefixes
6296
- );
6297
- if (promoted > 0) {
6298
- const l1Check = this.l1.get(k);
6299
- if (l1Check !== null) {
6300
- this.counters.gets++;
6301
- this.counters.diskHits++;
6302
- const val = l1Check.value;
6303
- if (this.opts.frozen) deepFreeze(val);
6304
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6514
+ if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
6515
+ if (this._isTombstonedByPattern(k)) {
6516
+ try {
6517
+ this.disk.delete(k);
6518
+ } catch {
6519
+ }
6520
+ } else if (this.watchdog.isDiskAllowed()) {
6521
+ const diskStart = performance.now();
6522
+ const diskHit = this.disk.load(k);
6523
+ const diskElapsed = performance.now() - diskStart;
6524
+ this.watchdog.recordDisk(diskElapsed);
6525
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6526
+ if (diskHit !== null) {
6527
+ const promoted = this.l1.importEntries(
6528
+ [{ key: k, entry: diskHit }],
6529
+ this.opts.forbiddenSnapshotPrefixes
6530
+ );
6531
+ if (promoted > 0) {
6532
+ const l1Check = this.l1.get(k);
6533
+ if (l1Check !== null) {
6534
+ this.counters.gets++;
6535
+ this.counters.diskHits++;
6536
+ const val = l1Check.value;
6537
+ if (this.opts.frozen) deepFreeze(val);
6538
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6539
+ }
6305
6540
  }
6306
6541
  }
6307
6542
  }
@@ -6339,6 +6574,7 @@ var CacheService = class _CacheService {
6339
6574
  * `(key) => number` so heterogeneous TTLs can be batched in one call.
6340
6575
  */
6341
6576
  async mget(keys, fetchFn, ttl = 300, priority) {
6577
+ this._assertActive("mget");
6342
6578
  const span = this._startSpan("tricache.mget");
6343
6579
  if (this.opts.tracer) {
6344
6580
  span.setAttribute("cache.batch.size", keys.length);
@@ -6407,8 +6643,16 @@ var CacheService = class _CacheService {
6407
6643
  }
6408
6644
  if (!this._diskDisabled && missKeys.length > 0) {
6409
6645
  for (let j = missKeys.length - 1; j >= 0; j--) {
6410
- if (!this.watchdog.isDiskAllowed()) continue;
6411
6646
  const k = this.nk(missKeys[j]);
6647
+ if (this._pendingDiskDeletes.has(k)) continue;
6648
+ if (this._isTombstonedByPattern(k)) {
6649
+ try {
6650
+ this.disk.delete(k);
6651
+ } catch {
6652
+ }
6653
+ continue;
6654
+ }
6655
+ if (!this.watchdog.isDiskAllowed()) continue;
6412
6656
  const diskStart = performance.now();
6413
6657
  const diskHit = this.disk.load(k);
6414
6658
  const diskElapsed = performance.now() - diskStart;
@@ -6488,6 +6732,7 @@ var CacheService = class _CacheService {
6488
6732
  * });
6489
6733
  */
6490
6734
  async mset(entries) {
6735
+ this._assertActive("mset");
6491
6736
  const span = this._startSpan("tricache.mset");
6492
6737
  const keys = Object.keys(entries);
6493
6738
  if (this.opts.tracer) {
@@ -6515,6 +6760,7 @@ var CacheService = class _CacheService {
6515
6760
  * await cache.mdel(['user:1', 'user:2', 'user:3']);
6516
6761
  */
6517
6762
  async mdel(keys) {
6763
+ this._assertActive("mdel");
6518
6764
  const span = this._startSpan("tricache.mdel");
6519
6765
  if (this.opts.tracer) {
6520
6766
  span.setAttribute("cache.batch.size", keys.length);
@@ -6542,6 +6788,7 @@ var CacheService = class _CacheService {
6542
6788
  * console.log(`Warmed ${loaded} keys from Redis`);
6543
6789
  */
6544
6790
  async warmFromL2(pattern, opts) {
6791
+ this._assertActive("warmFromL2");
6545
6792
  if (this._redisDisabled) return 0;
6546
6793
  try {
6547
6794
  const client = await this.getRedis();
@@ -6588,6 +6835,7 @@ var CacheService = class _CacheService {
6588
6835
  * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
6589
6836
  */
6590
6837
  async invalidateTag(tag) {
6838
+ this._assertActive("invalidateTag");
6591
6839
  const span = this._startSpan("tricache.invalidate_tag");
6592
6840
  if (this.opts.tracer) {
6593
6841
  span.setAttribute("cache.tag", tag);
@@ -6609,15 +6857,27 @@ var CacheService = class _CacheService {
6609
6857
  const current = this.tagVersions.get(tag)?.version ?? 0;
6610
6858
  newVer = current + 1;
6611
6859
  }
6612
- this._setLocalTagVersion(tag, newVer, Date.now());
6613
- void this.publishInvalidation("tag_incr", tag, newVer, false, true);
6860
+ this._setLocalTagVersion(tag, newVer, performance.now());
6861
+ if (this.opts.awaitInvalidationBackplane) {
6862
+ await this.publishInvalidation("tag_incr", tag, newVer, false, true);
6863
+ } else {
6864
+ void this.publishInvalidation("tag_incr", tag, newVer, false, true);
6865
+ }
6614
6866
  return;
6615
6867
  }
6616
6868
  const tagKey = this.nk(`_tag_:${tag}`);
6617
6869
  const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
6618
6870
  for (const k of members) {
6619
6871
  this.l1.delete(k);
6620
- if (!this._diskDisabled) this.disk.delete(k);
6872
+ this._bumpKeyMutation(k);
6873
+ this._pendingDiskDeletes.add(k);
6874
+ setImmediate(() => {
6875
+ try {
6876
+ if (!this._diskDisabled) this.disk.delete(k);
6877
+ } finally {
6878
+ this._pendingDiskDeletes.delete(k);
6879
+ }
6880
+ });
6621
6881
  }
6622
6882
  this.tagIndex.delete(tagKey);
6623
6883
  if (!this._redisDisabled) {
@@ -6655,13 +6915,14 @@ var CacheService = class _CacheService {
6655
6915
  * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
6656
6916
  */
6657
6917
  async invalidateTags(tags) {
6918
+ this._assertActive("invalidateTags");
6658
6919
  if (tags.length === 0) return;
6659
6920
  if (tags.length === 1) {
6660
6921
  await this.invalidateTag(tags[0]);
6661
6922
  return;
6662
6923
  }
6663
6924
  if (this.opts.tagStrategy === "generational") {
6664
- const now = Date.now();
6925
+ const now = performance.now();
6665
6926
  if (!this._redisDisabled) {
6666
6927
  try {
6667
6928
  const client = await this.getRedis();
@@ -6672,7 +6933,11 @@ var CacheService = class _CacheService {
6672
6933
  const [err, newVer] = results[i] ?? [null, null];
6673
6934
  const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
6674
6935
  this._setLocalTagVersion(tags[i], ver, now);
6675
- void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
6936
+ if (this.opts.awaitInvalidationBackplane) {
6937
+ await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
6938
+ } else {
6939
+ void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
6940
+ }
6676
6941
  }
6677
6942
  return;
6678
6943
  } catch (err) {
@@ -6682,7 +6947,11 @@ var CacheService = class _CacheService {
6682
6947
  for (const tag of tags) {
6683
6948
  const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
6684
6949
  this._setLocalTagVersion(tag, ver, now);
6685
- void this.publishInvalidation("tag_incr", tag, ver, false, true);
6950
+ if (this.opts.awaitInvalidationBackplane) {
6951
+ await this.publishInvalidation("tag_incr", tag, ver, false, true);
6952
+ } else {
6953
+ void this.publishInvalidation("tag_incr", tag, ver, false, true);
6954
+ }
6686
6955
  }
6687
6956
  return;
6688
6957
  }
@@ -6697,7 +6966,15 @@ var CacheService = class _CacheService {
6697
6966
  }
6698
6967
  for (const k of allMembers) {
6699
6968
  this.l1.delete(k);
6700
- this.disk.delete(k);
6969
+ this._bumpKeyMutation(k);
6970
+ this._pendingDiskDeletes.add(k);
6971
+ setImmediate(() => {
6972
+ try {
6973
+ if (!this._diskDisabled) this.disk.delete(k);
6974
+ } finally {
6975
+ this._pendingDiskDeletes.delete(k);
6976
+ }
6977
+ });
6701
6978
  }
6702
6979
  if (!this._redisDisabled) {
6703
6980
  try {
@@ -6734,6 +7011,7 @@ var CacheService = class _CacheService {
6734
7011
  * `l2` is `null` when Redis is disabled.
6735
7012
  */
6736
7013
  async ping() {
7014
+ this._assertActive("ping");
6737
7015
  const t0 = Date.now();
6738
7016
  this.l1.has("__ping__");
6739
7017
  const l1 = Date.now() - t0;
@@ -6813,6 +7091,7 @@ var CacheService = class _CacheService {
6813
7091
  * Returns the number of keys written.
6814
7092
  */
6815
7093
  async drainToL2() {
7094
+ this._assertActive("drainToL2");
6816
7095
  if (this._redisDisabled) return 0;
6817
7096
  try {
6818
7097
  const client = await this.getRedis();
@@ -6856,6 +7135,7 @@ var CacheService = class _CacheService {
6856
7135
  * if (!claimed) return res.status(409).json({ error: 'duplicate request' });
6857
7136
  */
6858
7137
  async setIfAbsent(cacheKey, value, ttlSeconds = 300, priority) {
7138
+ this._assertActive("setIfAbsent");
6859
7139
  const k = this.nk(cacheKey);
6860
7140
  if (this.l1.has(k)) return false;
6861
7141
  if (!this._redisDisabled) {
@@ -6874,6 +7154,8 @@ var CacheService = class _CacheService {
6874
7154
  }
6875
7155
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
6876
7156
  const p = priority ?? inferPriority(cacheKey);
7157
+ this._bumpKeyMutation(k);
7158
+ this._pendingDiskDeletes.delete(k);
6877
7159
  this.l1.set(k, value, ttlMs, p);
6878
7160
  this.counters.sets++;
6879
7161
  return true;
@@ -6892,6 +7174,7 @@ var CacheService = class _CacheService {
6892
7174
  * @param options TTL, acquire timeout, and retry polling intervals.
6893
7175
  */
6894
7176
  async lock(resourceKey, fn, options) {
7177
+ this._assertActive("lock");
6895
7178
  const ttlSeconds = Math.max(1, options?.ttl ?? 30);
6896
7179
  const acquireTimeout = Math.max(0, options?.acquireTimeout ?? 5e3);
6897
7180
  const retryInterval = Math.max(10, options?.retryInterval ?? 100);
@@ -6918,6 +7201,10 @@ var CacheService = class _CacheService {
6918
7201
  }
6919
7202
  } catch (err) {
6920
7203
  if (err.message.startsWith("Failed to acquire lock")) throw err;
7204
+ const failClosed = options?.failClosedOnRedisError ?? this.opts.lockFailClosed;
7205
+ if (failClosed) {
7206
+ throw new Error(`Distributed lock acquisition failed for resource "${resourceKey}" due to Redis error: ${err.message}`);
7207
+ }
6921
7208
  this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
6922
7209
  resourceKey,
6923
7210
  error: err.message
@@ -7263,6 +7550,7 @@ var CacheService = class _CacheService {
7263
7550
  * the previous key for seamless fallback decryption of existing cache entries.
7264
7551
  */
7265
7552
  async rotateEncryptionKey(newKeyBase64, newMode) {
7553
+ this._assertActive("rotateEncryptionKey");
7266
7554
  this.enc.rotateKey(newKeyBase64, newMode);
7267
7555
  if (this._workerPool) {
7268
7556
  await this._workerPool.drainAndReinit(this.enc.toWorkerInit());
@@ -7272,6 +7560,8 @@ var CacheService = class _CacheService {
7272
7560
  /** Close Redis connections and stop all background timers. */
7273
7561
  async destroy() {
7274
7562
  this._destroyed = true;
7563
+ this._pendingDiskDeletes.clear();
7564
+ this._keyMutationEpochs.clear();
7275
7565
  const g = globalThis;
7276
7566
  const key = _CacheService.globalKey(this.opts);
7277
7567
  if (g[key] === this) {
@@ -7338,6 +7628,7 @@ var CacheService = class _CacheService {
7338
7628
  };
7339
7629
 
7340
7630
  // src/cli.ts
7631
+ var import_meta2 = {};
7341
7632
  async function runCli(args = process.argv.slice(2)) {
7342
7633
  const options = {
7343
7634
  redis: { type: "string", short: "r" },
@@ -7374,7 +7665,13 @@ async function runCli(args = process.argv.slice(2)) {
7374
7665
  return;
7375
7666
  }
7376
7667
  if (values.version || command === "version") {
7377
- console.log("tricache v0.8.0");
7668
+ let version = "0.9.0";
7669
+ try {
7670
+ const pkg = JSON.parse((0, import_node_fs3.readFileSync)(new URL("../package.json", import_meta2.url), "utf8"));
7671
+ if (pkg?.version) version = pkg.version;
7672
+ } catch {
7673
+ }
7674
+ console.log(`tricache v${version}`);
7378
7675
  return;
7379
7676
  }
7380
7677
  if (command === "top") {
@@ -7386,10 +7683,18 @@ async function runCli(args = process.argv.slice(2)) {
7386
7683
  const active = await findActiveSockets();
7387
7684
  if (active.length > 0) {
7388
7685
  targetSocket = active[0];
7389
- } else {
7390
- targetSocket = resolveIpcSocketPath(process.pid);
7391
7686
  }
7392
7687
  }
7688
+ if (!targetSocket) {
7689
+ console.error("No active TriCache instances found to monitor.\n");
7690
+ console.error("To use `tricache top`:");
7691
+ console.error(" 1. Ensure your running application enables IPC telemetry:");
7692
+ console.error(" const cache = new CacheService({ namespace: 'my-app', enableIpc: true, ... });\n");
7693
+ console.error(" 2. If the application is already running, specify its PID or socket:");
7694
+ console.error(" npx tricache top --pid <pid>");
7695
+ console.error(" npx tricache top --socket <path>\n");
7696
+ process.exit(1);
7697
+ }
7393
7698
  const client = new IpcTelemetryClient(targetSocket);
7394
7699
  const intervalMs = typeof values.interval === "string" ? Math.max(200, parseInt(values.interval, 10)) : 1e3;
7395
7700
  const isOnce = Boolean(values.once || !process.stdout.isTTY);
@@ -7450,6 +7755,9 @@ async function runCli(args = process.argv.slice(2)) {
7450
7755
  } catch (err) {
7451
7756
  process.stdout.write(`\x1B[HConnecting to ${targetSocket}...
7452
7757
  Error: ${err.message}
7758
+
7759
+ Waiting for TriCache IPC server. Ensure the target process is running with enableIpc: true.
7760
+ Press "q" or Ctrl+C to exit
7453
7761
  `);
7454
7762
  }
7455
7763
  };