tricache 1.0.0 → 1.0.2

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 (97) hide show
  1. package/README.md +36 -28
  2. package/dist/{cache-service-pJ-nFcVj.d.ts → cache-service-B108FzER.d.ts} +63 -3
  3. package/dist/cache-service-CWI4jkS7.d.cts +963 -0
  4. package/dist/{cache-service-26GCO3UU.js → cache-service-GYPZFB7O.js} +2 -2
  5. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  6. package/dist/{chunk-2AJKEQMZ.js → chunk-H4GFLQ26.js} +7 -4
  7. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  8. package/dist/chunk-OYDU3SMI.js +89 -0
  9. package/dist/{chunk-VXFTFZ5N.js → chunk-VNRDL5RA.js} +117 -138
  10. package/dist/{chunk-7SZSQS55.js → chunk-WYF7NOAT.js} +1831 -759
  11. package/dist/cli.cjs +1757 -777
  12. package/dist/cli.d.cts +12 -0
  13. package/dist/cli.js +27 -6
  14. package/dist/dashboard/index.cjs +111 -29
  15. package/dist/dashboard/index.d.cts +185 -0
  16. package/dist/dashboard/index.d.ts +5 -3
  17. package/dist/dashboard/index.js +1 -1
  18. package/dist/drizzle/index.cjs +1757 -773
  19. package/dist/drizzle/index.d.cts +46 -0
  20. package/dist/drizzle/index.d.ts +2 -2
  21. package/dist/drizzle/index.js +1 -1
  22. package/dist/edge/index.cjs +280 -153
  23. package/dist/edge/index.d.cts +127 -0
  24. package/dist/edge/index.d.ts +3 -3
  25. package/dist/edge/index.js +254 -147
  26. package/dist/hono/index.cjs +1805 -793
  27. package/dist/hono/index.d.cts +93 -0
  28. package/dist/hono/index.d.ts +7 -5
  29. package/dist/hono/index.js +16 -9
  30. package/dist/{hono-DuNvciyq.d.ts → hono-3rDMYVtY.d.ts} +23 -3
  31. package/dist/hono-C886ok3X.d.cts +391 -0
  32. package/dist/http/index.cjs +1946 -842
  33. package/dist/http/index.d.cts +103 -0
  34. package/dist/http/index.d.ts +13 -5
  35. package/dist/http/index.js +137 -57
  36. package/dist/index.cjs +2073 -937
  37. package/dist/index.d.cts +1006 -0
  38. package/dist/index.d.ts +40 -8
  39. package/dist/index.js +8 -8
  40. package/dist/murmur3-CMGw9PbV.d.cts +98 -0
  41. package/dist/nestjs/index.cjs +1849 -806
  42. package/dist/nestjs/index.d.cts +285 -0
  43. package/dist/nestjs/index.d.ts +103 -30
  44. package/dist/nestjs/index.js +115 -32
  45. package/dist/next/index.cjs +1913 -887
  46. package/dist/next/index.d.cts +232 -0
  47. package/dist/next/index.d.ts +33 -11
  48. package/dist/next/index.js +174 -107
  49. package/dist/prisma/index.cjs +11 -1
  50. package/dist/prisma/index.d.cts +62 -0
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +11 -1
  53. package/dist/serialize-worker.d.cts +2 -0
  54. package/dist/{types-5HXqBfAf.d.ts → types-BA4pz1A0.d.cts} +26 -9
  55. package/dist/types-BA4pz1A0.d.ts +1519 -0
  56. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  57. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  58. package/package.json +96 -36
  59. package/src/adapters/auto-pipeliner.ts +107 -24
  60. package/src/adapters/node-redis.ts +123 -25
  61. package/src/cache-service.ts +1238 -659
  62. package/src/cli.ts +24 -6
  63. package/src/cross-region.ts +21 -3
  64. package/src/dashboard/handler.ts +26 -6
  65. package/src/dashboard/html.ts +35 -10
  66. package/src/dashboard/index.ts +35 -13
  67. package/src/dashboard/types.ts +3 -1
  68. package/src/disk-tier.ts +171 -65
  69. package/src/edge/cache.ts +202 -129
  70. package/src/edge/hono.ts +23 -6
  71. package/src/edge/types.ts +2 -0
  72. package/src/hono/index.ts +19 -9
  73. package/src/http/express.ts +110 -26
  74. package/src/http/fastify.ts +38 -28
  75. package/src/http/utils.ts +54 -20
  76. package/src/ipc-telemetry.ts +35 -9
  77. package/src/nestjs/decorators.ts +1 -1
  78. package/src/nestjs/index.ts +2 -0
  79. package/src/nestjs/keyv-adapter.ts +68 -0
  80. package/src/nestjs/tricache.module.ts +13 -11
  81. package/src/nestjs/tricache.store.ts +51 -20
  82. package/src/nestjs/types.ts +29 -15
  83. package/src/next/cache-handler.ts +132 -57
  84. package/src/next/index.ts +1 -0
  85. package/src/next/isr-handler.ts +1 -4
  86. package/src/next/types.ts +21 -0
  87. package/src/prisma/index.ts +12 -1
  88. package/src/smart-memory-cache.ts +65 -27
  89. package/src/types.ts +27 -2
  90. package/src/utils/cgroup.ts +12 -0
  91. package/src/utils/deadline.ts +14 -0
  92. package/src/utils/diagnostics.ts +27 -0
  93. package/src/utils/redis-slot.ts +13 -0
  94. package/src/wasm/bloom-filter-wasm.ts +9 -4
  95. package/src/worker-pool.ts +17 -8
  96. package/src/wtiny-lfu.ts +20 -6
  97. package/dist/chunk-BQRURGGD.js +0 -60
package/dist/cli.cjs CHANGED
@@ -37,7 +37,7 @@ var import_node_fs3 = require("fs");
37
37
  var import_node_util = require("util");
38
38
 
39
39
  // src/cache-service.ts
40
- var import_ioredis = require("ioredis");
40
+ var import_ioredis2 = require("ioredis");
41
41
 
42
42
  // src/codec.ts
43
43
  var import_msgpackr = require("msgpackr");
@@ -72,6 +72,15 @@ var defaultCodec = new CacheCodec({
72
72
  moreTypes: true
73
73
  });
74
74
 
75
+ // src/cross-region.ts
76
+ var import_node_crypto = require("crypto");
77
+ function isCrossRegionInvalidationEvent(value) {
78
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
79
+ const event = value;
80
+ const text = (key, max) => typeof event[key] === "string" && event[key].length > 0 && event[key].length <= max;
81
+ return text("id", 256) && text("originRegion", 128) && text("originInstanceId", 256) && text("key", 8192) && typeof event.op === "string" && ["del", "del-glob", "tag_incr", "tag_pattern_incr", "tag_pattern_del"].includes(event.op) && typeof event.timestamp === "number" && Number.isFinite(event.timestamp) && event.timestamp >= 0 && (event.namespace === void 0 || typeof event.namespace === "string") && (event.tagVersion === void 0 || Number.isSafeInteger(event.tagVersion) && Number(event.tagVersion) >= 0);
82
+ }
83
+
75
84
  // src/cache-service.ts
76
85
  var import_crypto3 = __toESM(require("crypto"), 1);
77
86
  var import_os3 = __toESM(require("os"), 1);
@@ -98,7 +107,8 @@ try {
98
107
  _workerFile = jsPath;
99
108
  }
100
109
  } catch {
101
- _workerFile = (0, import_path.join)(__dirname, "serialize-worker.js");
110
+ const sibling = (0, import_path.join)(__dirname, "serialize-worker.js");
111
+ _workerFile = (0, import_fs.existsSync)(sibling) ? sibling : (0, import_path.join)((0, import_path.dirname)(__dirname), "serialize-worker.js");
102
112
  }
103
113
  function getTransferableArrayBuffer(buf) {
104
114
  if (buf.buffer instanceof ArrayBuffer) {
@@ -131,6 +141,7 @@ var WorkerPool = class {
131
141
  }
132
142
  _spawnWorkers(opts) {
133
143
  const size = Math.max(1, opts.size ?? Math.min(4, availableCpus()));
144
+ if (!Number.isInteger(size) || size > 32 || !(0, import_fs.existsSync)(_workerFile)) throw new Error("Worker pool unavailable or invalid worker count");
134
145
  const workerData = {
135
146
  keyBase64: opts.keyBase64,
136
147
  mode: opts.mode,
@@ -144,7 +155,8 @@ var WorkerPool = class {
144
155
  const createWorker = (index) => {
145
156
  const worker = new import_worker_threads.Worker(_workerFile, {
146
157
  workerData,
147
- execArgv: _workerExecArgv.length > 0 ? _workerExecArgv : void 0
158
+ execArgv: _workerExecArgv
159
+ // Do not inherit --input-type/eval or application loader flags.
148
160
  });
149
161
  const pending = pendingList[index] ?? /* @__PURE__ */ new Map();
150
162
  if (!pendingList[index]) pendingList[index] = pending;
@@ -174,7 +186,7 @@ var WorkerPool = class {
174
186
  }
175
187
  pending.clear();
176
188
  worker.unref();
177
- if (this._available && exitCode !== 0 && workers[index] === worker) {
189
+ if (this._available && this.workers === workers && workers[index] === worker) {
178
190
  try {
179
191
  workers[index] = createWorker(index);
180
192
  } catch {
@@ -184,9 +196,12 @@ var WorkerPool = class {
184
196
  worker.unref();
185
197
  return worker;
186
198
  };
187
- for (let i = 0; i < size; i++) {
188
- const worker = createWorker(i);
189
- workers.push(worker);
199
+ try {
200
+ for (let i = 0; i < size; i++) workers.push(createWorker(i));
201
+ } catch (error) {
202
+ for (const worker of workers) void worker.terminate().catch(() => {
203
+ });
204
+ throw error;
190
205
  }
191
206
  return { workers, pending: pendingList };
192
207
  }
@@ -213,7 +228,7 @@ var WorkerPool = class {
213
228
  entry.reject(new Error("WorkerPool replaced during key rotation"));
214
229
  }
215
230
  oldPending[i]?.clear();
216
- oldWorkers[i]?.terminate().catch(() => {
231
+ await oldWorkers[i]?.terminate().catch(() => {
217
232
  });
218
233
  }
219
234
  }
@@ -255,7 +270,13 @@ var WorkerPool = class {
255
270
  return new Promise((resolve, reject) => {
256
271
  pending.set(id, { resolve, reject });
257
272
  worker.ref();
258
- worker.postMessage({ id, type, payload: dataToSend }, transferList);
273
+ try {
274
+ worker.postMessage({ id, type, payload: dataToSend }, transferList);
275
+ } catch (error) {
276
+ pending.delete(id);
277
+ if (pending.size === 0) worker.unref();
278
+ reject(error);
279
+ }
259
280
  });
260
281
  }
261
282
  /** Terminate all worker threads. In-flight promises are rejected. */
@@ -766,8 +787,9 @@ var EnvelopeEncryption = class {
766
787
 
767
788
  // src/wtiny-lfu.ts
768
789
  var WTinyLfuPolicy = class {
769
- constructor(capacity, sketch, windowPercent = 0.01, protectedPercent = 0.8) {
790
+ constructor(capacity, sketch, windowPercent = 0.01, protectedPercent = 0.8, canEvict) {
770
791
  this.sketch = sketch;
792
+ this.canEvict = canEvict;
771
793
  this.maxTotal = Math.max(2, capacity);
772
794
  this.maxWindow = Math.max(1, Math.floor(this.maxTotal * windowPercent));
773
795
  const mainCapacity = Math.max(1, this.maxTotal - this.maxWindow);
@@ -775,6 +797,7 @@ var WTinyLfuPolicy = class {
775
797
  this.maxProbation = Math.max(1, mainCapacity - this.maxProtected);
776
798
  }
777
799
  sketch;
800
+ canEvict;
778
801
  maxTotal;
779
802
  maxWindow;
780
803
  maxProtected;
@@ -854,15 +877,33 @@ var WTinyLfuPolicy = class {
854
877
  }
855
878
  let victimKey;
856
879
  let victimIsProbation = true;
857
- if (this.probation.size > 0) {
858
- victimKey = this.probation.values().next().value;
859
- } else {
860
- victimKey = this.protected_.values().next().value;
880
+ for (const candidate of this.probation) {
881
+ if (!this.canEvict || this.canEvict(candidate)) {
882
+ victimKey = candidate;
883
+ break;
884
+ }
885
+ }
886
+ if (victimKey === void 0) {
887
+ for (const candidate of this.protected_) {
888
+ if (!this.canEvict || this.canEvict(candidate)) {
889
+ victimKey = candidate;
890
+ break;
891
+ }
892
+ }
861
893
  victimIsProbation = false;
862
894
  }
895
+ if (victimKey === void 0) {
896
+ if (this.canEvict && !this.canEvict(candKey)) {
897
+ this.window.delete(key);
898
+ this.window.add(candKey);
899
+ return { admit: false, candidateKey: key };
900
+ }
901
+ this.rejectionCount++;
902
+ return { admit: false, candidateKey: candKey };
903
+ }
863
904
  const candFreq = this.sketch.estimate(candKey);
864
905
  const victimFreq = this.sketch.estimate(victimKey);
865
- if (candFreq > victimFreq) {
906
+ if (this.canEvict && !this.canEvict(candKey) || candFreq > victimFreq) {
866
907
  if (victimIsProbation) {
867
908
  this.probation.delete(victimKey);
868
909
  } else {
@@ -936,9 +977,12 @@ function base64ToUint8Array(base64) {
936
977
  var BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
937
978
  var KEY_STAGING_OFFSET = 2e4;
938
979
  var MAX_KEY_BYTES = 512;
939
- var BLOOM_WASM_MODULE = new WebAssembly.Module(
940
- base64ToUint8Array(BLOOM_WASM_BASE64)
941
- );
980
+ var bloomWasmModule;
981
+ function getBloomWasmModule() {
982
+ return bloomWasmModule ??= new WebAssembly.Module(
983
+ base64ToUint8Array(BLOOM_WASM_BASE64)
984
+ );
985
+ }
942
986
  var WasmBloomFilter = class {
943
987
  exports;
944
988
  mem;
@@ -950,7 +994,7 @@ var WasmBloomFilter = class {
950
994
  /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
951
995
  _insertionCount = 0;
952
996
  constructor() {
953
- const instance = new WebAssembly.Instance(BLOOM_WASM_MODULE, {});
997
+ const instance = new WebAssembly.Instance(getBloomWasmModule(), {});
954
998
  this.exports = instance.exports;
955
999
  this.mem = new Uint8Array(this.exports.memory.buffer);
956
1000
  this.stagingTarget = new Uint8Array(this.exports.memory.buffer, KEY_STAGING_OFFSET, MAX_KEY_BYTES);
@@ -1082,8 +1126,9 @@ var JsBloomFilter = class {
1082
1126
  };
1083
1127
  function createBloomFilter(logger, maxEntries) {
1084
1128
  const LN2_SQ = Math.LN2 * Math.LN2;
1085
- const optimalBits = Math.ceil(-maxEntries * Math.log(0.01) / LN2_SQ);
1086
- const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / maxEntries)));
1129
+ const capacity = Math.max(1, maxEntries);
1130
+ const optimalBits = Math.ceil(-capacity * Math.log(0.01) / LN2_SQ);
1131
+ const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / capacity)));
1087
1132
  try {
1088
1133
  const wasm = new WasmBloomFilter();
1089
1134
  if (wasm.maxCapacity >= maxEntries) {
@@ -1207,7 +1252,10 @@ var SmartMemoryCache = class {
1207
1252
  this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
1208
1253
  this.categoryPrefixes = Object.keys(opts.categories).filter((k) => k !== "default");
1209
1254
  if (opts.admissionPolicy === "wtinylfu") {
1210
- this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch);
1255
+ this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch, 0.01, 0.8, (key) => {
1256
+ const entry = this.cache.get(key);
1257
+ return !entry || entry.priority !== 4 || entry.expiresAt <= Date.now();
1258
+ });
1211
1259
  }
1212
1260
  if (existing) {
1213
1261
  for (const [k, v] of existing) this.cache.set(k, v);
@@ -1286,6 +1334,7 @@ var SmartMemoryCache = class {
1286
1334
  const MAX_EVICT_PASSES = 64;
1287
1335
  let passes = 0;
1288
1336
  do {
1337
+ const before = this.cache.size;
1289
1338
  this.smartEvict(category, catOvf);
1290
1339
  const lim2 = this.getCategoryLimit(category);
1291
1340
  const catCnt2 = this.categoryCount.get(category) ?? 0;
@@ -1293,6 +1342,7 @@ var SmartMemoryCache = class {
1293
1342
  catOvf = catCnt2 >= lim2.maxEntries || catSz2 + neededSize > lim2.maxSizeBytes;
1294
1343
  glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
1295
1344
  passes++;
1345
+ if (this.cache.size === before) break;
1296
1346
  } while ((catOvf || glbOvf) && passes < MAX_EVICT_PASSES);
1297
1347
  }
1298
1348
  score(entry, catBonus, now, key) {
@@ -1423,20 +1473,26 @@ var SmartMemoryCache = class {
1423
1473
  delta: entry.delta,
1424
1474
  fetchedAt: now,
1425
1475
  tagVersions: entry.tagVersions,
1426
- setAt: entry.setAt
1476
+ setAt: entry.setAt,
1477
+ tags: entry.tags,
1478
+ dependsOn: entry.dependsOn
1427
1479
  };
1428
1480
  return hit;
1429
1481
  }
1430
- set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
1482
+ set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions, setAt, tags, dependsOn) {
1431
1483
  const packed = this.codec.encode(data);
1484
+ return this.storePacked(key, packed, data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn);
1485
+ }
1486
+ storePacked(key, packed, data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn) {
1432
1487
  const size = packed.byteLength;
1433
1488
  this.compressions++;
1434
1489
  this.sketch.increment(key);
1435
1490
  const cat = this.getCategory(key);
1436
1491
  const lim = this.getCategoryLimit(cat);
1437
- if (size > lim.maxSizeBytes * 0.5) {
1492
+ if (!Number.isFinite(ttlMs) || ttlMs <= 0 || this.opts.maxEntries <= 0 || lim.maxEntries <= 0 || size > this.opts.maxBytes || size > lim.maxSizeBytes * 0.5) {
1493
+ this.delete(key);
1438
1494
  this.opts.logger.debug("SmartMemoryCache: entry too large, skipping", { key, sizeBytes: size });
1439
- return;
1495
+ return false;
1440
1496
  }
1441
1497
  const existingEntry = this.cache.get(key);
1442
1498
  if (existingEntry) {
@@ -1464,11 +1520,13 @@ var SmartMemoryCache = class {
1464
1520
  priority,
1465
1521
  ttlMs,
1466
1522
  delta,
1467
- setAt: now2,
1468
- tagVersions
1523
+ setAt: setAt ?? now2,
1524
+ tagVersions,
1525
+ tags,
1526
+ dependsOn
1469
1527
  });
1470
1528
  }
1471
- return;
1529
+ return false;
1472
1530
  } else if (decision.candidateKey) {
1473
1531
  const candEntry = this.cache.get(decision.candidateKey);
1474
1532
  if (candEntry && this.opts.diskSpill) {
@@ -1484,15 +1542,19 @@ var SmartMemoryCache = class {
1484
1542
  this._delete(decision.evictKey, "capacity");
1485
1543
  }
1486
1544
  const catSz = this.categorySize.get(cat) ?? 0;
1487
- if (catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
1545
+ if ((this.categoryCount.get(cat) ?? 0) >= lim.maxEntries || this.cache.size >= this.opts.maxEntries || catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
1488
1546
  this.ensureCapacity(cat, size);
1489
1547
  }
1490
1548
  } else {
1491
1549
  this.ensureCapacity(cat, size);
1492
1550
  }
1551
+ if (this.cache.size >= this.opts.maxEntries || (this.categoryCount.get(cat) ?? 0) >= lim.maxEntries || this.totalSize + size > this.opts.maxBytes || (this.categorySize.get(cat) ?? 0) + size > lim.maxSizeBytes) {
1552
+ this.wtinyPolicy?.onDelete(key);
1553
+ return false;
1554
+ }
1493
1555
  const now = Date.now();
1494
1556
  const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
1495
- this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: now, tagVersions });
1557
+ this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: setAt ?? now, tagVersions, tags, dependsOn });
1496
1558
  if (!existingEntry) this.bloom.add(key);
1497
1559
  this.maybeRebuildBloom();
1498
1560
  this.totalSize += size;
@@ -1504,6 +1566,7 @@ var SmartMemoryCache = class {
1504
1566
  this.categoryKeys.set(cat, ks);
1505
1567
  }
1506
1568
  ks.add(key);
1569
+ return true;
1507
1570
  }
1508
1571
  delete(key) {
1509
1572
  const deleted = this._delete(key, "manual");
@@ -1705,25 +1768,48 @@ var SmartMemoryCache = class {
1705
1768
  if (entry.expiresAt <= now) continue;
1706
1769
  if (entry.priority === 4) continue;
1707
1770
  if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
1708
- out.push({ key, entry: { ...entry } });
1771
+ const { value: _value, ...stored } = entry;
1772
+ out.push({ key, entry: { ...stored } });
1709
1773
  }
1710
1774
  return out;
1711
1775
  }
1712
1776
  importEntries(entries, forbiddenPrefixes) {
1713
1777
  const now = Date.now();
1714
1778
  let loaded = 0;
1715
- for (const { key, entry } of entries) {
1716
- if (entry.expiresAt <= now) continue;
1779
+ for (const item of entries) {
1780
+ if (!item || typeof item.key !== "string" || !item.entry) continue;
1781
+ const { key, entry } = item;
1782
+ if (!Number.isFinite(entry.expiresAt) || entry.expiresAt <= now) continue;
1717
1783
  if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
1718
1784
  if (this.cache.has(key)) continue;
1719
- const rawData = entry.data;
1720
- const data = !entry.isCompressed ? this.codec.encode(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
1721
- const value = entry.size <= LARGE_VALUE_BYTES ? this.codec.decode(data) : void 0;
1722
- this.cache.set(key, { ...entry, data, value, isCompressed: true });
1723
- this.bloom.add(key);
1724
- loaded++;
1725
- }
1726
- this.recalculateStats();
1785
+ try {
1786
+ const rawData = entry.data;
1787
+ const data = !entry.isCompressed ? this.codec.encode(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : null;
1788
+ if (!data) continue;
1789
+ const value = data.length <= LARGE_VALUE_BYTES ? this.codec.decode(data) : void 0;
1790
+ if (this.storePacked(
1791
+ key,
1792
+ data,
1793
+ value,
1794
+ entry.expiresAt - now,
1795
+ entry.priority,
1796
+ entry.staleAt,
1797
+ entry.delta,
1798
+ entry.tagVersions,
1799
+ entry.setAt,
1800
+ entry.tags,
1801
+ entry.dependsOn
1802
+ )) {
1803
+ const restored = this.cache.get(key);
1804
+ restored.expiresAt = entry.expiresAt;
1805
+ restored.ttlMs = entry.ttlMs ?? entry.expiresAt - now;
1806
+ restored.hits = Number.isFinite(entry.hits) ? Math.max(1, entry.hits) : 1;
1807
+ restored.lastAccess = Number.isFinite(entry.lastAccess) ? entry.lastAccess : now;
1808
+ loaded++;
1809
+ }
1810
+ } catch {
1811
+ }
1812
+ }
1727
1813
  return loaded;
1728
1814
  }
1729
1815
  // ── Iterators ─────────────────────────────────────────────────────────────
@@ -2087,6 +2173,9 @@ var BoundedDiskQueue = class {
2087
2173
  this.writeTimeoutMs = writeTimeoutMs;
2088
2174
  this.failureThreshold = failureThreshold;
2089
2175
  this.cooldownMs = cooldownMs;
2176
+ if (!Number.isInteger(maxConcurrent) || maxConcurrent < 1 || !Number.isInteger(maxPending) || maxPending < 0 || !Number.isFinite(writeTimeoutMs) || writeTimeoutMs <= 0 || !Number.isInteger(failureThreshold) || failureThreshold < 1 || !Number.isFinite(cooldownMs) || cooldownMs < 0) {
2177
+ throw new Error("Disk queue limits and timeout must be finite positive values (pending/cooldown may be zero)");
2178
+ }
2090
2179
  }
2091
2180
  maxConcurrent;
2092
2181
  maxPending;
@@ -2099,6 +2188,17 @@ var BoundedDiskQueue = class {
2099
2188
  consecutiveFailures = 0;
2100
2189
  circuitState = "closed";
2101
2190
  lastStateChangeMonotonic = performance.now();
2191
+ get isSaturated() {
2192
+ return this.active >= this.maxConcurrent && this.queue.length >= this.maxPending;
2193
+ }
2194
+ releaseSlot() {
2195
+ if (this.circuitState === "open") {
2196
+ for (const next2 of this.queue.splice(0)) next2(false);
2197
+ }
2198
+ const next = this.queue.shift();
2199
+ if (next) next(true);
2200
+ else this.active--;
2201
+ }
2102
2202
  async schedule(task) {
2103
2203
  const now = performance.now();
2104
2204
  if (this.circuitState === "open") {
@@ -2114,18 +2214,25 @@ var BoundedDiskQueue = class {
2114
2214
  this.spillsDropped++;
2115
2215
  return null;
2116
2216
  }
2117
- if (this.queue.length >= this.maxPending) {
2217
+ if (this.isSaturated) {
2118
2218
  this.spillsDropped++;
2119
2219
  return null;
2120
2220
  }
2121
2221
  if (this.active >= this.maxConcurrent) {
2122
- await new Promise((resolve) => this.queue.push(resolve));
2222
+ const admitted = await new Promise((resolve) => this.queue.push(resolve));
2223
+ if (!admitted) {
2224
+ this.spillsDropped++;
2225
+ return null;
2226
+ }
2227
+ } else {
2228
+ this.active++;
2123
2229
  }
2124
- this.active++;
2125
2230
  let timeoutId = null;
2231
+ const work = Promise.resolve().then(task);
2232
+ void work.then(() => this.releaseSlot(), () => this.releaseSlot());
2126
2233
  try {
2127
2234
  const result = await Promise.race([
2128
- task(),
2235
+ work,
2129
2236
  new Promise((_, reject) => {
2130
2237
  timeoutId = setTimeout(
2131
2238
  () => reject(new Error(`Disk write exceeded timeout of ${this.writeTimeoutMs}ms`)),
@@ -2144,14 +2251,12 @@ var BoundedDiskQueue = class {
2144
2251
  if (this.consecutiveFailures >= this.failureThreshold || this.circuitState === "half-open") {
2145
2252
  this.circuitState = "open";
2146
2253
  this.lastStateChangeMonotonic = performance.now();
2254
+ for (const next of this.queue.splice(0)) next(false);
2147
2255
  }
2148
2256
  this.spillsDropped++;
2149
2257
  return null;
2150
2258
  } finally {
2151
2259
  if (timeoutId) clearTimeout(timeoutId);
2152
- this.active--;
2153
- const next = this.queue.shift();
2154
- if (next) next();
2155
2260
  }
2156
2261
  }
2157
2262
  getStats() {
@@ -2225,6 +2330,13 @@ var DiskTier = class {
2225
2330
  usageCounted = false;
2226
2331
  fileCount = 0;
2227
2332
  // maintained in-memory; avoids walkCacheFiles() in stats
2333
+ reservedBytes = 0;
2334
+ reservedFiles = 0;
2335
+ saveSequence = 0;
2336
+ epoch = 0;
2337
+ pendingSaves = /* @__PURE__ */ new Map();
2338
+ closed = false;
2339
+ invalidatedKeys = /* @__PURE__ */ new Set();
2228
2340
  /** Next bucket index (0–255) for the staggered janitor wheel. */
2229
2341
  _nextJanitorBucket = 0;
2230
2342
  // ── High-watermark pruning & host volume health state ─────────────────────
@@ -2265,6 +2377,7 @@ var DiskTier = class {
2265
2377
  }
2266
2378
  // ── Helpers ───────────────────────────────────────────────────────────────
2267
2379
  ensureDir() {
2380
+ if (this.closed) return;
2268
2381
  if (this.dirReady) return;
2269
2382
  try {
2270
2383
  import_fs2.default.mkdirSync(this.opts.dir, { recursive: true, mode: 448 });
@@ -2386,8 +2499,24 @@ var DiskTier = class {
2386
2499
  *
2387
2500
  * 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
2388
2501
  */
2389
- hashToWritePath(hash, expiresAt) {
2390
- return import_path2.default.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiresAt.toString(16).padStart(12, "0")}`);
2502
+ hashToWritePath(hash, expiresAt, setAt) {
2503
+ const expiry = Math.floor(expiresAt).toString(16).padStart(12, "0");
2504
+ if (setAt === void 0) return import_path2.default.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}`);
2505
+ const written = Math.floor(setAt).toString(16).padStart(12, "0");
2506
+ const sequence = (++this.saveSequence).toString(16).padStart(12, "0");
2507
+ return import_path2.default.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}_${written}_${sequence}_${import_crypto2.default.randomBytes(6).toString("hex")}`);
2508
+ }
2509
+ findFilePaths(hash) {
2510
+ const bucket = import_path2.default.join(this.opts.dir, hash.slice(0, 2));
2511
+ try {
2512
+ return import_fs2.default.readdirSync(bucket).filter((file) => !file.endsWith(".tmp") && (file === hash || file.startsWith(hash + "_"))).map((file) => import_path2.default.join(bucket, file));
2513
+ } catch {
2514
+ return [];
2515
+ }
2516
+ }
2517
+ fileWrittenAt(file) {
2518
+ const parts = import_path2.default.basename(file).split("_");
2519
+ return parts.length >= 4 ? parseInt(parts[2], 16) : import_fs2.default.statSync(file).mtimeMs;
2391
2520
  }
2392
2521
  /**
2393
2522
  * Find the on-disk file for a key hash, handling all filename generations:
@@ -2396,19 +2525,31 @@ var DiskTier = class {
2396
2525
  * Returns null when the bucket dir does not exist or the key is absent.
2397
2526
  */
2398
2527
  findFilePath(hash) {
2399
- const bucketPath = import_path2.default.join(this.opts.dir, hash.slice(0, 2));
2400
- let files;
2528
+ let match = null;
2529
+ let newest = -Infinity;
2530
+ let sequence = -1;
2531
+ for (const file of this.findFilePaths(hash)) {
2532
+ try {
2533
+ const written = this.fileWrittenAt(file);
2534
+ const order = parseInt(import_path2.default.basename(file).split("_")[3] ?? "0", 16);
2535
+ if (written > newest || written === newest && order > sequence) {
2536
+ match = file;
2537
+ newest = written;
2538
+ sequence = order;
2539
+ }
2540
+ } catch {
2541
+ }
2542
+ }
2543
+ return match;
2544
+ }
2545
+ removeFile(filePath) {
2401
2546
  try {
2402
- files = import_fs2.default.readdirSync(bucketPath);
2547
+ const size = import_fs2.default.statSync(filePath).size;
2548
+ import_fs2.default.unlinkSync(filePath);
2549
+ this.diskUsageBytes = Math.max(0, this.diskUsageBytes - size);
2550
+ this.fileCount = Math.max(0, this.fileCount - 1);
2403
2551
  } catch {
2404
- return null;
2405
- }
2406
- let match;
2407
- for (const f of files) {
2408
- if ((f === hash || f.startsWith(hash + "_")) && (!match || f > match)) match = f;
2409
2552
  }
2410
- if (!match) return null;
2411
- return import_path2.default.join(bucketPath, match);
2412
2553
  }
2413
2554
  /**
2414
2555
  * Recursively list all cache file paths across the 2-level sharded subdirs.
@@ -2483,6 +2624,7 @@ var DiskTier = class {
2483
2624
  * so the Node.js event loop is never stalled waiting for disk I/O.
2484
2625
  */
2485
2626
  async save(key, entry) {
2627
+ if (this.closed || this.diskQueue.isSaturated) return;
2486
2628
  if (this.isForbidden(key)) return;
2487
2629
  if (entry.expiresAt <= Date.now()) return;
2488
2630
  this.ensureDir();
@@ -2491,7 +2633,7 @@ var DiskTier = class {
2491
2633
  if (++this._writeCounter % 2e3 === 0) {
2492
2634
  this.checkHostVolumeHealth();
2493
2635
  }
2494
- if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes >= this.opts.maxBytes) {
2636
+ if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes + this.reservedBytes >= this.opts.maxBytes) {
2495
2637
  this._spillsShedTotal++;
2496
2638
  return;
2497
2639
  }
@@ -2500,11 +2642,12 @@ var DiskTier = class {
2500
2642
  }
2501
2643
  let final;
2502
2644
  try {
2645
+ const { value: _value, ...storedEntry } = entry;
2503
2646
  const payload = {
2504
2647
  version: DISK_TIER_VERSION,
2505
2648
  key,
2506
2649
  entry: {
2507
- ...entry,
2650
+ ...storedEntry,
2508
2651
  data: entry.data instanceof Uint8Array ? Buffer.from(entry.data) : entry.data
2509
2652
  },
2510
2653
  writtenAt: Date.now()
@@ -2517,24 +2660,46 @@ var DiskTier = class {
2517
2660
  }
2518
2661
  const header = Buffer.allocUnsafe(V2_HEADER_LEN);
2519
2662
  DISK_MAGIC_V2.copy(header, 0);
2520
- header.writeBigUInt64LE(BigInt(entry.expiresAt), 8);
2663
+ header.writeBigUInt64LE(BigInt(Math.floor(entry.expiresAt)), 8);
2521
2664
  final = Buffer.concat([header, this.encryptV2(toEncrypt)]);
2665
+ if (final.length > this.opts.entryMaxBytes || this.diskUsageBytes + this.reservedBytes + final.length > this.opts.maxBytes) return;
2522
2666
  } catch (err) {
2523
2667
  this.opts.logger.debug("DiskTier: pack/encrypt failed", { key: key.slice(0, 50), error: err.message });
2524
2668
  return;
2525
2669
  }
2526
2670
  const hash = this.keyToHash(key);
2527
- const filePath = this.hashToWritePath(hash, entry.expiresAt);
2671
+ const setAt = entry.setAt ?? Date.now();
2672
+ if ((this.pendingSaves.get(key)?.setAt ?? 0) > setAt) return;
2673
+ const filePath = this.hashToWritePath(hash, entry.expiresAt, setAt);
2528
2674
  const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${import_crypto2.default.randomBytes(6).toString("hex")}.tmp`;
2529
- this.diskUsageBytes += final.length;
2530
- this.fileCount++;
2675
+ const token = Symbol(key);
2676
+ const epoch = this.epoch;
2677
+ this.pendingSaves.set(key, { token, setAt });
2678
+ const current = () => !this.closed && this.epoch === epoch && this.pendingSaves.get(key)?.token === token;
2679
+ let started = false;
2680
+ let released = false;
2681
+ let accounted = false;
2682
+ const releaseReservation = () => {
2683
+ if (released) return;
2684
+ released = true;
2685
+ this.reservedBytes = Math.max(0, this.reservedBytes - final.length);
2686
+ this.reservedFiles = Math.max(0, this.reservedFiles - 1);
2687
+ if (this.pendingSaves.get(key)?.token === token) this.pendingSaves.delete(key);
2688
+ };
2689
+ this.reservedBytes += final.length;
2690
+ this.reservedFiles++;
2531
2691
  if (this.diskUsageBytes >= this.opts.maxBytes * 0.8 && !this._isPruning) {
2532
2692
  void this.triggerChunkedPrune();
2533
2693
  }
2534
2694
  const result = await this.diskQueue.schedule(async () => {
2695
+ started = true;
2535
2696
  try {
2697
+ if (!current()) return false;
2698
+ const previous = this.findFilePath(hash);
2699
+ if (previous && this.fileWrittenAt(previous) > setAt) return false;
2536
2700
  await import_fs2.default.promises.mkdir(import_path2.default.dirname(filePath), { recursive: true });
2537
2701
  await import_fs2.default.promises.writeFile(tmpPath, final, { mode: 384 });
2702
+ if (!current()) return false;
2538
2703
  try {
2539
2704
  await import_fs2.default.promises.rename(tmpPath, filePath);
2540
2705
  } catch (renameErr) {
@@ -2546,6 +2711,20 @@ var DiskTier = class {
2546
2711
  throw renameErr;
2547
2712
  }
2548
2713
  }
2714
+ if (!current()) {
2715
+ try {
2716
+ await import_fs2.default.promises.unlink(filePath);
2717
+ } catch {
2718
+ }
2719
+ return false;
2720
+ }
2721
+ for (const previousPath of this.findFilePaths(hash)) {
2722
+ if (previousPath !== filePath) this.removeFile(previousPath);
2723
+ }
2724
+ this.diskUsageBytes += final.length;
2725
+ this.fileCount++;
2726
+ accounted = true;
2727
+ this.invalidatedKeys.delete(key);
2549
2728
  if (this._db) {
2550
2729
  const priority = typeof entry.priority === "number" ? entry.priority : 2;
2551
2730
  const lastAccess = typeof entry.lastAccess === "number" ? entry.lastAccess : Date.now();
@@ -2558,23 +2737,25 @@ var DiskTier = class {
2558
2737
  await import_fs2.default.promises.unlink(tmpPath);
2559
2738
  } catch {
2560
2739
  }
2561
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
2562
- this.fileCount = Math.max(0, this.fileCount - 1);
2563
- if (this._db) try {
2564
- this._stmtDelete.run(hash);
2565
- } catch {
2566
- }
2740
+ if (accounted) this.removeFile(filePath);
2567
2741
  this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
2568
2742
  throw err;
2743
+ } finally {
2744
+ try {
2745
+ await import_fs2.default.promises.unlink(tmpPath);
2746
+ } catch {
2747
+ }
2748
+ releaseReservation();
2749
+ if (this.invalidatedKeys.has(key) && !this.pendingSaves.has(key)) this.delete(key, true);
2569
2750
  }
2570
2751
  });
2571
- if (result === null) {
2572
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
2573
- this.fileCount = Math.max(0, this.fileCount - 1);
2752
+ if (result === null && !started) {
2753
+ releaseReservation();
2574
2754
  }
2575
2755
  }
2576
2756
  /** Load a key from disk, or return null on miss/expiry/corruption. */
2577
2757
  load(key) {
2758
+ if (this.invalidatedKeys.has(key) || this.closed) return null;
2578
2759
  if (this.isForbidden(key)) return null;
2579
2760
  this.ensureDir();
2580
2761
  if (!this.dirReady) return null;
@@ -2602,8 +2783,8 @@ var DiskTier = class {
2602
2783
  try {
2603
2784
  if (!this._db) {
2604
2785
  const filename = import_path2.default.basename(filePath);
2605
- if (filename.length === 77 && filename[64] === "_") {
2606
- const expiresAt = parseInt(filename.slice(65), 16);
2786
+ if (filename.length >= 77 && filename[64] === "_") {
2787
+ const expiresAt = parseInt(filename.slice(65, 77), 16);
2607
2788
  if (expiresAt <= Date.now()) {
2608
2789
  try {
2609
2790
  const sz = import_fs2.default.statSync(filePath).size;
@@ -2624,12 +2805,7 @@ var DiskTier = class {
2624
2805
  return null;
2625
2806
  }
2626
2807
  const raw = import_fs2.default.readFileSync(filePath);
2627
- try {
2628
- import_fs2.default.unlinkSync(filePath);
2629
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
2630
- this.fileCount = Math.max(0, this.fileCount - 1);
2631
- } catch {
2632
- }
2808
+ for (const storedPath of this.findFilePaths(hash)) this.removeFile(storedPath);
2633
2809
  if (this._db) this._stmtDelete.run(hash);
2634
2810
  let decrypted;
2635
2811
  if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
@@ -2664,25 +2840,24 @@ var DiskTier = class {
2664
2840
  return null;
2665
2841
  }
2666
2842
  }
2667
- /** Explicitly delete a key from disk (cache invalidation). */
2668
- delete(key) {
2843
+ /** Synchronously fence queued/running saves while leaving filesystem cleanup deferred. */
2844
+ invalidate(key) {
2845
+ this.pendingSaves.delete(key);
2846
+ this.invalidatedKeys.add(key);
2847
+ }
2848
+ /** Delete all versions; deferred cleanup must not cancel a newer save. */
2849
+ delete(key, invalidatedOnly = false) {
2850
+ if (invalidatedOnly && (!this.invalidatedKeys.has(key) || this.pendingSaves.has(key))) return;
2851
+ if (!invalidatedOnly) this.pendingSaves.delete(key);
2669
2852
  const hash = this.keyToHash(key);
2670
- let filePath;
2853
+ const files = new Set(this.findFilePaths(hash));
2671
2854
  if (this._db) {
2672
2855
  const row = this._stmtSelect.get(hash);
2673
- filePath = row?.file_path ?? null;
2856
+ if (row?.file_path) files.add(row.file_path);
2674
2857
  this._stmtDelete.run(hash);
2675
- } else {
2676
- filePath = this.findFilePath(hash);
2677
- }
2678
- if (!filePath) return;
2679
- try {
2680
- const stat = import_fs2.default.statSync(filePath);
2681
- import_fs2.default.unlinkSync(filePath);
2682
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
2683
- this.fileCount = Math.max(0, this.fileCount - 1);
2684
- } catch {
2685
2858
  }
2859
+ for (const file of files) this.removeFile(file);
2860
+ this.invalidatedKeys.delete(key);
2686
2861
  }
2687
2862
  /** Purge all expired entries. Returns number deleted. */
2688
2863
  purgeExpired() {
@@ -2718,8 +2893,8 @@ var DiskTier = class {
2718
2893
  }
2719
2894
  continue;
2720
2895
  }
2721
- if (filename.length === 77 && filename[64] === "_") {
2722
- const expiresAt = parseInt(filename.slice(65), 16);
2896
+ if (filename.length >= 77 && filename[64] === "_") {
2897
+ const expiresAt = parseInt(filename.slice(65, 77), 16);
2723
2898
  if (expiresAt <= now) {
2724
2899
  try {
2725
2900
  const sz = import_fs2.default.statSync(filePath).size;
@@ -2839,8 +3014,8 @@ var DiskTier = class {
2839
3014
  }
2840
3015
  continue;
2841
3016
  }
2842
- if (file.length === 77 && file[64] === "_") {
2843
- const expiresAt = parseInt(file.slice(65), 16);
3017
+ if (file.length >= 77 && file[64] === "_") {
3018
+ const expiresAt = parseInt(file.slice(65, 77), 16);
2844
3019
  if (expiresAt <= now2) {
2845
3020
  const fp = import_path2.default.join(orphanBucketP, file);
2846
3021
  try {
@@ -2880,8 +3055,8 @@ var DiskTier = class {
2880
3055
  }
2881
3056
  continue;
2882
3057
  }
2883
- if (file.length === 77 && file[64] === "_") {
2884
- const expiresAt = parseInt(file.slice(65), 16);
3058
+ if (file.length >= 77 && file[64] === "_") {
3059
+ const expiresAt = parseInt(file.slice(65, 77), 16);
2885
3060
  if (expiresAt <= now) {
2886
3061
  const filePath2 = import_path2.default.join(bucketPath, file);
2887
3062
  try {
@@ -2954,6 +3129,9 @@ var DiskTier = class {
2954
3129
  }
2955
3130
  /** Delete every file in the disk cache. Returns the count deleted. */
2956
3131
  clear() {
3132
+ this.epoch++;
3133
+ this.pendingSaves.clear();
3134
+ this.invalidatedKeys.clear();
2957
3135
  this.ensureDir();
2958
3136
  if (!this.dirReady) return 0;
2959
3137
  let cleared = 0;
@@ -3017,6 +3195,7 @@ var DiskTier = class {
3017
3195
  * yielding to the event loop via setImmediate between chunks.
3018
3196
  */
3019
3197
  async triggerChunkedPrune() {
3198
+ if (this.closed) return 0;
3020
3199
  if (this._isPruning) return 0;
3021
3200
  this._isPruning = true;
3022
3201
  this._pruneRounds++;
@@ -3025,7 +3204,7 @@ var DiskTier = class {
3025
3204
  this.ensureUsageCounted();
3026
3205
  const targetBytes = Math.floor(this.opts.maxBytes * 0.6);
3027
3206
  if (this._db && this._stmtPruneChunk) {
3028
- while (this.diskUsageBytes > targetBytes) {
3207
+ while (!this.closed && this.diskUsageBytes > targetBytes) {
3029
3208
  const rows = this._stmtPruneChunk.all();
3030
3209
  if (!rows || rows.length === 0) break;
3031
3210
  for (const row of rows) {
@@ -3048,7 +3227,7 @@ var DiskTier = class {
3048
3227
  }
3049
3228
  }
3050
3229
  } else {
3051
- while (this.diskUsageBytes > targetBytes) {
3230
+ while (!this.closed && this.diskUsageBytes > targetBytes) {
3052
3231
  const files = this.walkCacheFiles();
3053
3232
  if (files.length === 0) break;
3054
3233
  const chunk = files.slice(0, 500);
@@ -3116,6 +3295,10 @@ var DiskTier = class {
3116
3295
  }
3117
3296
  /** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
3118
3297
  close() {
3298
+ this.closed = true;
3299
+ this.epoch++;
3300
+ this.pendingSaves.clear();
3301
+ this.invalidatedKeys.clear();
3119
3302
  if (this._db) {
3120
3303
  try {
3121
3304
  this._db.close();
@@ -3358,6 +3541,17 @@ function readCgroupMemoryLimit() {
3358
3541
  }
3359
3542
  return Infinity;
3360
3543
  }
3544
+ function readCgroupMemoryUsage() {
3545
+ if (process.platform !== "linux") return null;
3546
+ for (const file of ["/sys/fs/cgroup/memory.current", "/sys/fs/cgroup/memory/memory.usage_in_bytes"]) {
3547
+ try {
3548
+ const value = Number(import_node_fs.default.readFileSync(file, "utf8").trim());
3549
+ if (Number.isFinite(value) && value >= 0) return value;
3550
+ } catch {
3551
+ }
3552
+ }
3553
+ return null;
3554
+ }
3361
3555
  function getV8HeapLimit() {
3362
3556
  try {
3363
3557
  const stats = import_node_v8.default.getHeapStatistics();
@@ -3381,7 +3575,81 @@ function resolveAutonomousL1MaxBytes(options) {
3381
3575
  return Math.max(MIN_AUTONOMOUS_L1_FLOOR_BYTES, Math.floor(resolved));
3382
3576
  }
3383
3577
 
3578
+ // src/utils/diagnostics.ts
3579
+ function redactDiagnostics(value, seen = /* @__PURE__ */ new WeakSet(), depth = 0) {
3580
+ if (typeof value === "string" && /^[a-z][a-z\d+.-]*:\/\//i.test(value)) {
3581
+ try {
3582
+ const url = new URL(value);
3583
+ if (url.username) url.username = "[REDACTED]";
3584
+ if (url.password) url.password = "[REDACTED]";
3585
+ for (const key of url.searchParams.keys()) {
3586
+ if (/key|token|secret|password|credential|authorization|cookie/i.test(key)) url.searchParams.set(key, "[REDACTED]");
3587
+ }
3588
+ return url.toString();
3589
+ } catch {
3590
+ return "[REDACTED URL]";
3591
+ }
3592
+ }
3593
+ if (value == null || typeof value !== "object") return typeof value === "function" ? void 0 : value;
3594
+ if (depth >= 8) return "[OMITTED]";
3595
+ if (seen.has(value)) return "[CIRCULAR]";
3596
+ seen.add(value);
3597
+ if (Array.isArray(value)) return value.map((item) => redactDiagnostics(item, seen, depth + 1));
3598
+ const result = {};
3599
+ for (const [key, item] of Object.entries(value)) {
3600
+ if (typeof item === "function") continue;
3601
+ result[key] = /key|token|secret|password|credential|authorization|cookie|headers/i.test(key) ? item == null ? item : "[REDACTED]" : redactDiagnostics(item, seen, depth + 1);
3602
+ }
3603
+ return result;
3604
+ }
3605
+
3606
+ // src/utils/redis-slot.ts
3607
+ function redisHashSlot(key) {
3608
+ const open = key.indexOf("{");
3609
+ const close = open < 0 ? -1 : key.indexOf("}", open + 1);
3610
+ const bytes = Buffer.from(close > open + 1 ? key.slice(open + 1, close) : key, "utf8");
3611
+ let crc = 0;
3612
+ for (const byte of bytes) {
3613
+ crc ^= byte << 8;
3614
+ for (let bit = 0; bit < 8; bit++) crc = crc << 1 ^ (crc & 32768 ? 4129 : 0);
3615
+ crc &= 65535;
3616
+ }
3617
+ return crc & 16383;
3618
+ }
3619
+
3620
+ // src/utils/deadline.ts
3621
+ async function withDeadline(operation, timeoutMs, label) {
3622
+ let timer;
3623
+ try {
3624
+ return await Promise.race([
3625
+ operation,
3626
+ new Promise((_resolve, reject) => {
3627
+ timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs);
3628
+ })
3629
+ ]);
3630
+ } finally {
3631
+ if (timer) clearTimeout(timer);
3632
+ }
3633
+ }
3634
+
3384
3635
  // src/adapters/auto-pipeliner.ts
3636
+ var import_ioredis = require("ioredis");
3637
+ async function readRedisValue(client, key, hash = false) {
3638
+ if (typeof client.pttl === "function" && typeof client.multi === "function") {
3639
+ const transaction = client.multi();
3640
+ if (typeof transaction.pttl === "function" && (!hash || typeof transaction.hgetall === "function")) {
3641
+ if (hash) transaction.hgetall(key);
3642
+ else transaction.get(key);
3643
+ transaction.pttl(key);
3644
+ const results = await transaction.exec();
3645
+ if (!results) throw new Error("Redis read transaction aborted");
3646
+ if (results[0]?.[0]) throw results[0][0];
3647
+ if (results[1]?.[0]) throw results[1][0];
3648
+ return { raw: results[0]?.[1] ?? null, ttlMs: Number(results[1]?.[1]) };
3649
+ }
3650
+ }
3651
+ return { raw: await (hash ? client.hgetall(key) : client.get(key)) };
3652
+ }
3385
3653
  var AutoPipeliner = class {
3386
3654
  constructor(client, options) {
3387
3655
  this.client = client;
@@ -3413,6 +3681,17 @@ var AutoPipeliner = class {
3413
3681
  this.enqueue({ type: "get", key, resolve, reject });
3414
3682
  });
3415
3683
  }
3684
+ async read(key, hash = false) {
3685
+ if (!hash && typeof this.client.pttl !== "function") return { raw: await this.get(key) };
3686
+ if (!this.enabled || !this.supportsPipelines() || typeof this.client.pttl !== "function") {
3687
+ return readRedisValue(this.client, key, hash);
3688
+ }
3689
+ const probe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
3690
+ if (typeof probe.pttl !== "function" || hash && typeof probe.hgetall !== "function") {
3691
+ return readRedisValue(this.client, key, hash);
3692
+ }
3693
+ return new Promise((resolve, reject) => this.enqueue({ type: "read", key, hash, resolve, reject }));
3694
+ }
3416
3695
  async setex(key, seconds, value) {
3417
3696
  if (!this.enabled || !this.supportsPipelines()) {
3418
3697
  if (typeof this.client.setex === "function") {
@@ -3426,8 +3705,18 @@ var AutoPipeliner = class {
3426
3705
  this.enqueue({ type: "setex", key, seconds, value, resolve, reject });
3427
3706
  });
3428
3707
  }
3708
+ async setpx(key, milliseconds, value) {
3709
+ if (!this.enabled || !this.supportsPipelines()) {
3710
+ await this.client.set(key, value, "PX", milliseconds);
3711
+ return;
3712
+ }
3713
+ return new Promise((resolve, reject) => this.enqueue({ type: "setpx", key, milliseconds, value, resolve, reject }));
3714
+ }
3429
3715
  async del(...keys) {
3430
3716
  if (keys.length === 0) return 0;
3717
+ if (this.client instanceof import_ioredis.Cluster && keys.length > 1) {
3718
+ return (await Promise.all(keys.map((key) => this.del(key)))).reduce((sum, value) => sum + value, 0);
3719
+ }
3431
3720
  if (!this.enabled || !this.supportsPipelines()) {
3432
3721
  return this.client.del(...keys);
3433
3722
  }
@@ -3461,44 +3750,72 @@ var AutoPipeliner = class {
3461
3750
  this.scheduled = false;
3462
3751
  this.statsInternal.batchesDispatched++;
3463
3752
  this.statsInternal.operationsBatched += batch.length;
3464
- const pipe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
3465
- for (const op of batch) {
3466
- switch (op.type) {
3467
- case "get":
3468
- pipe.get(op.key);
3469
- break;
3470
- case "setex":
3471
- pipe.setex(op.key, op.seconds, op.value);
3472
- break;
3473
- case "del":
3474
- pipe.del(...op.keys);
3475
- break;
3476
- }
3753
+ if (this.client instanceof import_ioredis.Cluster) {
3754
+ const groups = /* @__PURE__ */ new Map();
3755
+ for (const operation of batch) {
3756
+ const key = operation.type === "del" ? operation.keys[0] : operation.key;
3757
+ const slot = redisHashSlot(key);
3758
+ const master = this.client.slots[slot]?.[0] ?? String(slot);
3759
+ const members = groups.get(master) ?? [];
3760
+ members.push(operation);
3761
+ groups.set(master, members);
3762
+ }
3763
+ await Promise.all([...groups.values()].map((members) => this.dispatch(members)));
3764
+ return;
3477
3765
  }
3766
+ await this.dispatch(batch);
3767
+ }
3768
+ async dispatch(batch) {
3478
3769
  try {
3770
+ const pipe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
3771
+ const indexes = [];
3772
+ let commandCount = 0;
3773
+ for (const op of batch) {
3774
+ indexes.push(commandCount++);
3775
+ switch (op.type) {
3776
+ case "get":
3777
+ pipe.get(op.key);
3778
+ break;
3779
+ case "setex":
3780
+ pipe.setex(op.key, op.seconds, op.value);
3781
+ break;
3782
+ case "setpx":
3783
+ pipe.set(op.key, op.value, "PX", op.milliseconds);
3784
+ break;
3785
+ case "del":
3786
+ pipe.del(...op.keys);
3787
+ break;
3788
+ case "read":
3789
+ if (op.hash) pipe.hgetall(op.key);
3790
+ else pipe.get(op.key);
3791
+ pipe.pttl(op.key);
3792
+ commandCount++;
3793
+ break;
3794
+ }
3795
+ }
3479
3796
  const results = await pipe.exec();
3480
3797
  if (!results) {
3481
3798
  for (const op of batch) {
3482
- if (op.type === "get") op.resolve(null);
3483
- else if (op.type === "del") op.resolve(0);
3484
- else op.resolve();
3799
+ op.reject(new Error("Redis pipeline aborted"));
3485
3800
  }
3486
3801
  return;
3487
3802
  }
3488
3803
  for (let i = 0; i < batch.length; i++) {
3489
3804
  const op = batch[i];
3490
- const resTuple = results[i];
3805
+ const resTuple = results[indexes[i]];
3491
3806
  if (!resTuple) {
3492
- if (op.type === "get") op.resolve(null);
3493
- else if (op.type === "del") op.resolve(0);
3494
- else op.resolve();
3807
+ op.reject(new Error("Missing Redis pipeline result"));
3495
3808
  continue;
3496
3809
  }
3497
3810
  const [err, val] = resTuple;
3498
3811
  if (err) {
3499
3812
  op.reject(err instanceof Error ? err : new Error(String(err)));
3500
3813
  } else {
3501
- if (op.type === "get") {
3814
+ if (op.type === "read") {
3815
+ const ttlResult = results[indexes[i] + 1];
3816
+ if (!ttlResult || ttlResult[0]) op.reject(ttlResult?.[0] ?? new Error("Missing Redis PTTL result"));
3817
+ else op.resolve({ raw: val, ttlMs: Number(ttlResult[1]) });
3818
+ } else if (op.type === "get") {
3502
3819
  op.resolve(val != null ? String(val) : null);
3503
3820
  } else if (op.type === "del") {
3504
3821
  op.resolve(typeof val === "number" ? val : Number(val) || 0);
@@ -3535,6 +3852,8 @@ var IpcTelemetryServer = class {
3535
3852
  server = null;
3536
3853
  socketPath;
3537
3854
  _closed = false;
3855
+ _starting = null;
3856
+ sockets = /* @__PURE__ */ new Set();
3538
3857
  _exitHandler = null;
3539
3858
  _sigintHandler = null;
3540
3859
  _sigtermHandler = null;
@@ -3542,10 +3861,23 @@ var IpcTelemetryServer = class {
3542
3861
  * Start listening on the IPC socket / pipe.
3543
3862
  */
3544
3863
  async start() {
3545
- if (this.server && this.server.listening) return;
3864
+ if (this._closed || this.server?.listening) return;
3865
+ if (this._starting) return this._starting;
3866
+ this._starting = this.startInternal();
3867
+ try {
3868
+ await this._starting;
3869
+ } finally {
3870
+ this._starting = null;
3871
+ }
3872
+ }
3873
+ async startInternal() {
3546
3874
  if (process.platform !== "win32" && import_node_fs2.default.existsSync(this.socketPath)) {
3547
3875
  await new Promise((resolve) => {
3548
3876
  const testSocket = import_node_net.default.createConnection(this.socketPath);
3877
+ testSocket.setTimeout(1e3, () => {
3878
+ testSocket.destroy();
3879
+ resolve();
3880
+ });
3549
3881
  testSocket.once("connect", () => {
3550
3882
  testSocket.destroy();
3551
3883
  resolve();
@@ -3560,17 +3892,37 @@ var IpcTelemetryServer = class {
3560
3892
  });
3561
3893
  });
3562
3894
  }
3895
+ if (this._closed) return;
3563
3896
  this.server = import_node_net.default.createServer((socket) => {
3897
+ if (this._closed) {
3898
+ socket.destroy();
3899
+ return;
3900
+ }
3901
+ this.sockets.add(socket);
3902
+ socket.once("close", () => this.sockets.delete(socket));
3903
+ socket.setTimeout(5e3, () => socket.destroy());
3564
3904
  let buffer = "";
3905
+ let pending = 0;
3565
3906
  socket.on("data", (chunk) => {
3907
+ if (Buffer.byteLength(buffer) + chunk.length > 4096 || socket.writableLength > 65536) {
3908
+ socket.destroy();
3909
+ return;
3910
+ }
3566
3911
  buffer += chunk.toString("utf8");
3567
3912
  let newlineIndex;
3568
3913
  while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
3569
3914
  const line = buffer.slice(0, newlineIndex).trim();
3570
3915
  buffer = buffer.slice(newlineIndex + 1);
3571
3916
  if (!line) continue;
3917
+ if (++pending > 8) {
3918
+ socket.destroy();
3919
+ return;
3920
+ }
3572
3921
  setImmediate(() => {
3573
- if (socket.destroyed) return;
3922
+ if (socket.destroyed) {
3923
+ pending--;
3924
+ return;
3925
+ }
3574
3926
  try {
3575
3927
  let cmd = line;
3576
3928
  try {
@@ -3595,6 +3947,8 @@ var IpcTelemetryServer = class {
3595
3947
  if (!socket.destroyed) {
3596
3948
  socket.write(JSON.stringify({ error: err.message }) + "\n");
3597
3949
  }
3950
+ } finally {
3951
+ pending--;
3598
3952
  }
3599
3953
  });
3600
3954
  }
@@ -3602,21 +3956,38 @@ var IpcTelemetryServer = class {
3602
3956
  socket.on("error", () => {
3603
3957
  });
3604
3958
  });
3959
+ this.server.maxConnections = 128;
3605
3960
  await new Promise((resolve, reject) => {
3606
- this.server.once("error", reject);
3607
- this.server.listen(this.socketPath, () => {
3608
- this.server.removeListener("error", reject);
3961
+ const server = this.server;
3962
+ const cleanup = () => {
3963
+ server.off("error", failed);
3964
+ server.off("close", closed);
3965
+ };
3966
+ const failed = (error) => {
3967
+ cleanup();
3968
+ reject(error);
3969
+ };
3970
+ const closed = () => {
3971
+ cleanup();
3972
+ resolve();
3973
+ };
3974
+ server.once("error", failed);
3975
+ server.once("close", closed);
3976
+ server.listen(this.socketPath, () => {
3977
+ cleanup();
3609
3978
  resolve();
3610
3979
  });
3611
3980
  });
3981
+ if (this._closed) {
3982
+ if (this.server.listening) this.server.close();
3983
+ return;
3984
+ }
3612
3985
  this._exitHandler = () => this._unlinkSocket();
3613
3986
  this._sigintHandler = () => {
3614
3987
  this._unlinkSocket();
3615
- process.exit(0);
3616
3988
  };
3617
3989
  this._sigtermHandler = () => {
3618
3990
  this._unlinkSocket();
3619
- process.exit(0);
3620
3991
  };
3621
3992
  process.once("exit", this._exitHandler);
3622
3993
  process.once("SIGINT", this._sigintHandler);
@@ -3646,6 +4017,7 @@ var IpcTelemetryServer = class {
3646
4017
  _unlinkSocket() {
3647
4018
  if (this._closed) return;
3648
4019
  this._closed = true;
4020
+ for (const socket of this.sockets) socket.destroy();
3649
4021
  try {
3650
4022
  this.server?.close();
3651
4023
  } catch {
@@ -3663,6 +4035,9 @@ var IpcTelemetryServer = class {
3663
4035
  * Gracefully close the IPC telemetry server and clean up handlers and sockets.
3664
4036
  */
3665
4037
  async close() {
4038
+ this._unlinkSocket();
4039
+ await this._starting?.catch(() => {
4040
+ });
3666
4041
  if (this._exitHandler) {
3667
4042
  process.removeListener("exit", this._exitHandler);
3668
4043
  this._exitHandler = null;
@@ -3675,7 +4050,6 @@ var IpcTelemetryServer = class {
3675
4050
  process.removeListener("SIGTERM", this._sigtermHandler);
3676
4051
  this._sigtermHandler = null;
3677
4052
  }
3678
- this._unlinkSocket();
3679
4053
  return new Promise((resolve) => {
3680
4054
  if (!this.server || !this.server.listening) {
3681
4055
  resolve();
@@ -3961,6 +4335,37 @@ if currentTs and currentTs == ARGV[1] then
3961
4335
  end
3962
4336
  return 0
3963
4337
  `;
4338
+ var LUA_READ_CACHE_ENTRY = `
4339
+ local kind = redis.call('TYPE', KEYS[1]).ok
4340
+ if kind == 'string' then
4341
+ return { kind, redis.call('GET', KEYS[1]), redis.call('PTTL', KEYS[1]) }
4342
+ elseif kind == 'hash' then
4343
+ return { kind, redis.call('HGETALL', KEYS[1]), redis.call('PTTL', KEYS[1]) }
4344
+ end
4345
+ return { 'none', false, -2 }
4346
+ `;
4347
+ var LUA_MAX_TAG_VERSION = `
4348
+ local current = tonumber(redis.call('GET', KEYS[1]) or '0')
4349
+ local floor = tonumber(ARGV[1])
4350
+ if current < floor then redis.call('SET', KEYS[1], floor) return floor end
4351
+ return current
4352
+ `;
4353
+ var LUA_RECEIVE_TAG_VERSION = `
4354
+ local current = tonumber(redis.call('GET', KEYS[1]) or '0')
4355
+ local next = math.max(current + 1, tonumber(ARGV[1]))
4356
+ redis.call('SET', KEYS[1], next)
4357
+ return next
4358
+ `;
4359
+ var LUA_TOUCH_CACHE_ENTRY = `
4360
+ local kind = redis.call('TYPE', KEYS[1]).ok
4361
+ if kind == 'hash' then
4362
+ if redis.call('HGET', KEYS[1], 't') ~= ARGV[1] then return 0 end
4363
+ redis.call('HSET', KEYS[1], 'e', ARGV[2])
4364
+ elseif kind ~= 'string' then
4365
+ return 0
4366
+ end
4367
+ return redis.call('PEXPIRE', KEYS[1], ARGV[3])
4368
+ `;
3964
4369
  var SNAPSHOT_VERSION = 1;
3965
4370
  var DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
3966
4371
  var INDEFINITE_TTL_SECONDS = 31536e3;
@@ -4249,13 +4654,19 @@ var CacheService = class _CacheService {
4249
4654
  _l1Counters = /* @__PURE__ */ new Map();
4250
4655
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
4251
4656
  tagIndex = /* @__PURE__ */ new Map();
4657
+ /** Reverse index of namespaced key → { tags, expiresAt } for bounded cleanup on eviction/delete */
4658
+ keyTags = /* @__PURE__ */ new Map();
4252
4659
  /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
4253
4660
  tagVersions = /* @__PURE__ */ new Map();
4661
+ _tagRefreshEpoch = 0;
4254
4662
  /**
4255
4663
  * Dependency index: source glob pattern → Set of namespaced dependent keys.
4256
4664
  * When an exact-key delete matches a registered pattern, all dependents are cascaded.
4257
4665
  */
4258
4666
  dependencyIndex = /* @__PURE__ */ new Map();
4667
+ /** Reverse index of namespaced dependent key → source glob patterns */
4668
+ keyDependencies = /* @__PURE__ */ new Map();
4669
+ _cgroupMemoryLimit;
4259
4670
  redis = null;
4260
4671
  redisConnecting = null;
4261
4672
  cb;
@@ -4278,9 +4689,17 @@ var CacheService = class _CacheService {
4278
4689
  subClient = null;
4279
4690
  streamClient = null;
4280
4691
  _lastStreamId = "$";
4692
+ _restoredSnapshot = false;
4693
+ _backplaneAvailable = false;
4694
+ _otelCleanup = null;
4695
+ _streamRecovering = false;
4696
+ _backplaneDisposers = [];
4281
4697
  _destroyed = false;
4282
4698
  _pendingDiskDeletes = /* @__PURE__ */ new Set();
4283
4699
  _globalEpoch = 0;
4700
+ _pendingSpillCount = 0;
4701
+ _suppressSpills = false;
4702
+ _diskCleanupScheduled = false;
4284
4703
  _keyMutationEpochs = /* @__PURE__ */ new Map();
4285
4704
  /**
4286
4705
  * Pattern tombstones for disk tier.
@@ -4289,20 +4708,24 @@ var CacheService = class _CacheService {
4289
4708
  * pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
4290
4709
  */
4291
4710
  _patternTombstones = [];
4292
- _addPatternTombstone(prefix) {
4711
+ _diskInvalidatedBefore = 0;
4712
+ _addPatternTombstone(pattern) {
4293
4713
  const now = Date.now();
4294
4714
  while (this._patternTombstones.length > 0 && now - this._patternTombstones[0].createdAt > 36e5) {
4295
- this._patternTombstones.shift();
4715
+ const forgotten = this._patternTombstones.shift();
4716
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
4296
4717
  }
4297
4718
  if (this._patternTombstones.length >= 2e3) {
4298
- this._patternTombstones.shift();
4719
+ const forgotten = this._patternTombstones.shift();
4720
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
4299
4721
  }
4300
- this._patternTombstones.push({ prefix, createdAt: now });
4722
+ this._patternTombstones.push({ pattern, createdAt: now });
4301
4723
  }
4302
- _isTombstonedByPattern(namespacedKey) {
4724
+ _isTombstonedByPattern(namespacedKey, setAt = 0) {
4725
+ if (this._diskInvalidatedBefore > 0 && setAt <= this._diskInvalidatedBefore) return true;
4303
4726
  if (this._patternTombstones.length === 0) return false;
4304
4727
  for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
4305
- if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
4728
+ if (setAt <= this._patternTombstones[i].createdAt && this._matchesGlob(namespacedKey, this._patternTombstones[i].pattern)) {
4306
4729
  return true;
4307
4730
  }
4308
4731
  }
@@ -4317,13 +4740,170 @@ var CacheService = class _CacheService {
4317
4740
  const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
4318
4741
  this._keyMutationEpochs.set(namespacedKey, next);
4319
4742
  if (this._keyMutationEpochs.size > 5e4) {
4320
- const oldest = this._keyMutationEpochs.keys().next().value;
4321
- if (oldest !== void 0) this._keyMutationEpochs.delete(oldest);
4743
+ this._globalEpoch++;
4744
+ this._keyMutationEpochs.clear();
4745
+ this._keyMutationEpochs.set(namespacedKey, next);
4322
4746
  }
4323
4747
  return next;
4324
4748
  }
4325
4749
  _getKeyMutationEpoch(namespacedKey) {
4326
- return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
4750
+ return `${this._globalEpoch}:${this._keyMutationEpochs.get(namespacedKey) ?? 0}`;
4751
+ }
4752
+ /** Capture a commit fence before asynchronous computation outside the cache. */
4753
+ captureMutationFence(cacheKey) {
4754
+ this._assertActive("captureMutationFence");
4755
+ const key = this.nk(cacheKey);
4756
+ const epoch = this._getKeyMutationEpoch(key);
4757
+ return () => !this._destroyed && this._getKeyMutationEpoch(key) === epoch;
4758
+ }
4759
+ /** Force tag re-sync without forgetting locally observed monotonic generations. */
4760
+ refreshTagVersions() {
4761
+ this._assertActive("refreshTagVersions");
4762
+ this._tagRefreshEpoch++;
4763
+ }
4764
+ _fenceInvalidation() {
4765
+ this._globalEpoch++;
4766
+ this.inflight.clear();
4767
+ }
4768
+ _invalidateDiskKey(key) {
4769
+ if (this._diskDisabled) return;
4770
+ this.disk.invalidate(key);
4771
+ this._pendingDiskDeletes.add(key);
4772
+ this._scheduleDiskCleanup();
4773
+ }
4774
+ _scheduleDiskCleanup() {
4775
+ if (this._diskCleanupScheduled || this._pendingDiskDeletes.size === 0) return;
4776
+ this._diskCleanupScheduled = true;
4777
+ setImmediate(() => {
4778
+ this._diskCleanupScheduled = false;
4779
+ if (this._destroyed) return;
4780
+ let processed = 0;
4781
+ for (const key of this._pendingDiskDeletes) {
4782
+ try {
4783
+ this.disk.delete(key, true);
4784
+ } finally {
4785
+ this._pendingDiskDeletes.delete(key);
4786
+ }
4787
+ if (++processed >= 16) break;
4788
+ }
4789
+ this._scheduleDiskCleanup();
4790
+ });
4791
+ }
4792
+ _registerDependencies(key, patterns) {
4793
+ this._removeKeyDependencies(key);
4794
+ if (!patterns?.length) return;
4795
+ const namespaced = [...new Set(patterns.map((pattern) => this.nk(pattern)))];
4796
+ for (const pattern of namespaced) {
4797
+ const dependents = this.dependencyIndex.get(pattern) ?? /* @__PURE__ */ new Set();
4798
+ dependents.add(key);
4799
+ this.dependencyIndex.set(pattern, dependents);
4800
+ }
4801
+ this.keyDependencies.set(key, namespaced);
4802
+ }
4803
+ _rememberTags(key, tags, expiresAt) {
4804
+ this._removeKeyTags(key);
4805
+ if (!tags.length) return;
4806
+ if (this.keyTags.size >= 1e5) {
4807
+ this._sweepExpiredMetadata();
4808
+ const oldest = this.keyTags.keys().next().value;
4809
+ if (this.keyTags.size >= 1e5 && oldest !== void 0) this._removeKeyTags(oldest);
4810
+ }
4811
+ const unique = [...new Set(tags)];
4812
+ for (const tag of unique) {
4813
+ const tagKey = this.nk(`_tag_:${tag}`);
4814
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
4815
+ members.add(key);
4816
+ this.tagIndex.set(tagKey, members);
4817
+ }
4818
+ this.keyTags.set(key, { tags: unique, expiresAt });
4819
+ }
4820
+ _restoreEntryMetadata(key, entry) {
4821
+ if (entry.tags?.length) this._rememberTags(key, entry.tags, entry.expiresAt);
4822
+ if (entry.dependsOn?.length) this._registerDependencies(key, entry.dependsOn);
4823
+ }
4824
+ _removeKeyTags(namespacedKey) {
4825
+ const entry = this.keyTags.get(namespacedKey);
4826
+ if (!entry) return;
4827
+ for (const tag of entry.tags) {
4828
+ const tagKey = this.nk(`_tag_:${tag}`);
4829
+ const members = this.tagIndex.get(tagKey);
4830
+ if (members) {
4831
+ members.delete(namespacedKey);
4832
+ if (members.size === 0) this.tagIndex.delete(tagKey);
4833
+ }
4834
+ }
4835
+ this.keyTags.delete(namespacedKey);
4836
+ }
4837
+ _removeKeyDependencies(namespacedKey) {
4838
+ const patterns = this.keyDependencies.get(namespacedKey);
4839
+ if (patterns) {
4840
+ for (const pat of patterns) {
4841
+ const deps = this.dependencyIndex.get(pat);
4842
+ if (deps) {
4843
+ deps.delete(namespacedKey);
4844
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
4845
+ }
4846
+ }
4847
+ this.keyDependencies.delete(namespacedKey);
4848
+ } else if (this.dependencyIndex.size > 0) {
4849
+ for (const [pat, deps] of this.dependencyIndex) {
4850
+ deps.delete(namespacedKey);
4851
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
4852
+ }
4853
+ }
4854
+ }
4855
+ _handleL1Eviction(namespacedKey, reason) {
4856
+ const spilledToDisk = !this._diskDisabled && !this._suppressSpills && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
4857
+ if (!spilledToDisk) {
4858
+ this._removeKeyTags(namespacedKey);
4859
+ this._removeKeyDependencies(namespacedKey);
4860
+ }
4861
+ }
4862
+ _removePatternFromIndices(pattern) {
4863
+ for (const k of Array.from(this.keyTags.keys())) {
4864
+ if (this._matchesGlob(k, pattern)) this._removeKeyTags(k);
4865
+ }
4866
+ for (const k of Array.from(this.keyDependencies.keys())) {
4867
+ if (this._matchesGlob(k, pattern)) this._removeKeyDependencies(k);
4868
+ }
4869
+ for (const k of Array.from(this._l1Counters.keys())) {
4870
+ if (this._matchesGlob(k, pattern)) this._l1Counters.delete(k);
4871
+ }
4872
+ }
4873
+ _sweepExpiredMetadata() {
4874
+ const now = Date.now();
4875
+ for (const [k, c] of this._l1Counters) {
4876
+ if (c.expiresAt <= now) this._l1Counters.delete(k);
4877
+ }
4878
+ for (const [k, meta] of this.keyTags) {
4879
+ if (meta.expiresAt <= now && !this.l1.has(k)) {
4880
+ this._removeKeyTags(k);
4881
+ this._removeKeyDependencies(k);
4882
+ }
4883
+ }
4884
+ }
4885
+ _runOomCheck() {
4886
+ const heap = import_node_v82.default.getHeapStatistics();
4887
+ const heapUsed = heap.used_heap_size / heap.heap_size_limit;
4888
+ const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? (readCgroupMemoryUsage() ?? process.memoryUsage().rss) / this._cgroupMemoryLimit : 0;
4889
+ const used = Math.max(heapUsed, cgroupUsed);
4890
+ if (used >= this.opts.oomHeapThreshold) {
4891
+ this._suppressSpills = cgroupUsed >= this.opts.oomHeapThreshold;
4892
+ let evicted;
4893
+ try {
4894
+ evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
4895
+ } finally {
4896
+ this._suppressSpills = false;
4897
+ }
4898
+ this.counters.oomEvictions++;
4899
+ this.counters.oomLastAt = Date.now();
4900
+ this.logger.warn("tricache OOM guard: emergency L1 eviction", {
4901
+ heapUsedPct: Math.round(heapUsed * 100),
4902
+ cgroupUsedPct: cgroupUsed > 0 ? Math.round(cgroupUsed * 100) : void 0,
4903
+ threshold: Math.round(this.opts.oomHeapThreshold * 100),
4904
+ evicted
4905
+ });
4906
+ }
4327
4907
  }
4328
4908
  _ipcServer;
4329
4909
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
@@ -4371,6 +4951,7 @@ var CacheService = class _CacheService {
4371
4951
  constructor(options = {}) {
4372
4952
  const logger = options.logger ?? consoleLogger;
4373
4953
  this.logger = logger;
4954
+ this._cgroupMemoryLimit = readCgroupMemoryLimit();
4374
4955
  const ns = options.namespace?.trim() ?? "";
4375
4956
  const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
4376
4957
  this.enc = new CacheEncryption(
@@ -4549,12 +5130,19 @@ var CacheService = class _CacheService {
4549
5130
  admissionPolicy: this.opts.l1AdmissionPolicy,
4550
5131
  codec: this.codec,
4551
5132
  diskSpill: (key, entry) => {
4552
- if (this._diskDisabled) return;
5133
+ if (this._diskDisabled || this._suppressSpills) return;
5134
+ if (this._pendingSpillCount >= (this.opts.diskMaxPendingWrites ?? 512)) return;
5135
+ const epoch = this._getKeyMutationEpoch(key);
5136
+ this._pendingSpillCount++;
4553
5137
  setImmediate(() => {
4554
- void this.disk.save(key, entry);
5138
+ this._pendingSpillCount--;
5139
+ if (!this._destroyed && this._getKeyMutationEpoch(key) === epoch) void this.disk.save(key, entry);
4555
5140
  });
4556
5141
  },
4557
- onEviction: options.onEviction,
5142
+ onEviction: (key, reason) => {
5143
+ this._handleL1Eviction(key, reason);
5144
+ options.onEviction?.(key, reason);
5145
+ },
4558
5146
  logger
4559
5147
  });
4560
5148
  if (!this.snapshotLoaded) {
@@ -4592,6 +5180,7 @@ var CacheService = class _CacheService {
4592
5180
  }
4593
5181
  this.cleanupInterval = setInterval(() => {
4594
5182
  const cleaned = this.l1.cleanup();
5183
+ this._sweepExpiredMetadata();
4595
5184
  if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
4596
5185
  }, 5 * 60 * 1e3);
4597
5186
  if (this.cleanupInterval.unref) this.cleanupInterval.unref();
@@ -4604,18 +5193,7 @@ var CacheService = class _CacheService {
4604
5193
  }
4605
5194
  if (this.opts.oomProtection) {
4606
5195
  this.oomInterval = setInterval(() => {
4607
- const heap = import_node_v82.default.getHeapStatistics();
4608
- const used = heap.used_heap_size / heap.heap_size_limit;
4609
- if (used >= this.opts.oomHeapThreshold) {
4610
- const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
4611
- this.counters.oomEvictions++;
4612
- this.counters.oomLastAt = Date.now();
4613
- this.logger.warn("tricache OOM guard: emergency L1 eviction", {
4614
- heapUsedPct: Math.round(used * 100),
4615
- threshold: Math.round(this.opts.oomHeapThreshold * 100),
4616
- evicted
4617
- });
4618
- }
5196
+ this._runOomCheck();
4619
5197
  }, this.opts.oomCheckIntervalMs);
4620
5198
  if (this.oomInterval.unref) this.oomInterval.unref();
4621
5199
  }
@@ -4637,7 +5215,7 @@ var CacheService = class _CacheService {
4637
5215
  this.instanceId = import_crypto3.default.randomBytes(8).toString("hex");
4638
5216
  this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
4639
5217
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
4640
- this.initBackplane();
5218
+ const startBackplane = () => withDeadline(this.initBackplane(), this.opts.redisCommandTimeoutMs ?? 2500, "Backplane initialization").catch((error) => this.logger.warn("Backplane initialization failed; continuing with local degradation", { error: error.message }));
4641
5219
  const startupPromises = [];
4642
5220
  if (this.opts.compression === "zstd") {
4643
5221
  startupPromises.push(initZstd().then(() => void 0));
@@ -4648,9 +5226,8 @@ var CacheService = class _CacheService {
4648
5226
  if (this.opts.warmKeys) {
4649
5227
  startupPromises.push(this.warmFromL2(this.opts.warmKeys).then(() => void 0));
4650
5228
  }
4651
- if (startupPromises.length > 0) {
4652
- this._readyPromise = Promise.all(startupPromises).then(() => void 0);
4653
- }
5229
+ const backplaneReady = this.opts.remoteSnapshot || this.opts.warmKeys ? Promise.all(startupPromises).then(startBackplane) : startBackplane();
5230
+ this._readyPromise = Promise.all([...startupPromises, backplaneReady]).then(() => void 0);
4654
5231
  if (this.opts.meter) {
4655
5232
  this._initOtelMetrics(this.opts.meter);
4656
5233
  const otel = this._otelMetrics;
@@ -4663,7 +5240,10 @@ var CacheService = class _CacheService {
4663
5240
  if (typeof prop === "string" && typeof value === "number" && typeof oldVal === "number") {
4664
5241
  const diff = value - oldVal;
4665
5242
  if (diff > 0 && otel[prop]) {
4666
- otel[prop].add(diff, nsAttr);
5243
+ try {
5244
+ otel[prop].add(diff, nsAttr);
5245
+ } catch {
5246
+ }
4667
5247
  }
4668
5248
  }
4669
5249
  return ok;
@@ -4755,7 +5335,7 @@ var CacheService = class _CacheService {
4755
5335
  return g[key];
4756
5336
  }
4757
5337
  const existing = g[key];
4758
- const diff = _CacheService.optionsDiff(options ?? {}, existing.options);
5338
+ const diff = _CacheService.optionsDiff(options ?? {}, existing.opts);
4759
5339
  if (diff.length > 0) {
4760
5340
  existing.bumpSingletonDivergence();
4761
5341
  const msg = `tricache: singleton already initialised for namespace '${existing.options.namespace || "(default)"}' \u2014 ignoring divergent options: ${diff.join(", ")}`;
@@ -4789,7 +5369,13 @@ var CacheService = class _CacheService {
4789
5369
  "instanceName",
4790
5370
  "invalidationBackplane",
4791
5371
  "awaitInvalidationBackplane",
4792
- "lockFailClosed"
5372
+ "lockFailClosed",
5373
+ "tagStrategy",
5374
+ "cloneStrategy",
5375
+ "compression",
5376
+ "backplaneMode",
5377
+ "redisProtocol",
5378
+ "failClosed"
4793
5379
  ];
4794
5380
  /** Returns the names of options that differ between `a` and the live `b`. */
4795
5381
  static optionsDiff(a, b) {
@@ -4807,12 +5393,12 @@ var CacheService = class _CacheService {
4807
5393
  bumpSingletonDivergence() {
4808
5394
  this.counters.singletonDivergences++;
4809
5395
  }
4810
- /** Read-only view of the options the singleton was constructed with. */
5396
+ /** Sanitized diagnostic view; retain the original options/adapters to reuse configuration. */
4811
5397
  get options() {
4812
5398
  const o = this.opts;
4813
5399
  return {
4814
5400
  namespace: o.namespace,
4815
- logger: o.logger,
5401
+ logger: { debug: o.logger.debug.bind(o.logger), info: o.logger.info.bind(o.logger), warn: o.logger.warn.bind(o.logger), error: o.logger.error.bind(o.logger) },
4816
5402
  l1MaxBytes: o.l1MaxBytes,
4817
5403
  l1MaxEntries: o.l1MaxEntries,
4818
5404
  redisHost: o.redisHost,
@@ -4833,8 +5419,8 @@ var CacheService = class _CacheService {
4833
5419
  awaitInvalidationBackplane: o.awaitInvalidationBackplane,
4834
5420
  lockFailClosed: o.lockFailClosed,
4835
5421
  strictSingleton: o.strictSingleton,
4836
- remoteSnapshot: o.remoteSnapshot,
4837
- crossRegion: o.crossRegion
5422
+ remoteSnapshot: redactDiagnostics(o.remoteSnapshot),
5423
+ crossRegion: redactDiagnostics(o.crossRegion)
4838
5424
  };
4839
5425
  }
4840
5426
  /**
@@ -4917,21 +5503,26 @@ var CacheService = class _CacheService {
4917
5503
  if (this.opts.redisClient && typeof this.opts.redisClient.duplicate === "function") {
4918
5504
  return this.opts.redisClient.duplicate();
4919
5505
  }
5506
+ if (this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel) {
5507
+ throw new Error("Invalidation backplane requires redisSubClient or a driver supporting duplicate()");
5508
+ }
4920
5509
  if (this.opts.redisClusterNodes?.length) {
4921
- return new import_ioredis.Cluster(this.opts.redisClusterNodes, {
5510
+ return new import_ioredis2.Cluster(this.opts.redisClusterNodes, {
4922
5511
  redisOptions: {
4923
5512
  tls: this.opts.redisTls ? {} : void 0,
4924
5513
  connectTimeout: 1e4,
5514
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
4925
5515
  maxRetriesPerRequest: null,
4926
5516
  ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
4927
5517
  }
4928
5518
  });
4929
5519
  } else if (this.opts.redisSentinel) {
4930
- return new import_ioredis.Redis({
5520
+ return new import_ioredis2.Redis({
4931
5521
  sentinels: this.opts.redisSentinel.sentinels,
4932
5522
  name: this.opts.redisSentinel.name,
4933
5523
  tls: this.opts.redisTls ? {} : void 0,
4934
5524
  connectTimeout: 1e4,
5525
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
4935
5526
  lazyConnect: true,
4936
5527
  maxRetriesPerRequest: null,
4937
5528
  enableAutoPipelining: false,
@@ -4939,11 +5530,12 @@ var CacheService = class _CacheService {
4939
5530
  ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
4940
5531
  });
4941
5532
  } else {
4942
- return new import_ioredis.Redis({
5533
+ return new import_ioredis2.Redis({
4943
5534
  host: this.opts.redisHost,
4944
5535
  port: this.opts.redisPort,
4945
5536
  tls: this.opts.redisTls ? {} : void 0,
4946
5537
  connectTimeout: 1e4,
5538
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
4947
5539
  lazyConnect: true,
4948
5540
  maxRetriesPerRequest: null,
4949
5541
  enableAutoPipelining: false,
@@ -4953,26 +5545,32 @@ var CacheService = class _CacheService {
4953
5545
  });
4954
5546
  }
4955
5547
  }
4956
- initBackplane() {
5548
+ _listenBackplane(client, event, listener) {
5549
+ client.on?.(event, listener);
5550
+ this._backplaneDisposers.push(() => client.removeListener?.(event, listener));
5551
+ }
5552
+ async initBackplane() {
4957
5553
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
4958
5554
  if (this.opts.backplaneMode === "stream") {
4959
5555
  if (this.streamClient) return;
4960
- void this._startStreamConsumer();
5556
+ await this._startStreamConsumer();
4961
5557
  return;
4962
5558
  }
4963
5559
  if (this.subClient) return;
4964
5560
  const sub = this.createDedicatedRedisClient();
4965
- sub.on("error", (e) => {
5561
+ this.subClient = sub;
5562
+ this._listenBackplane(sub, "error", (e) => {
4966
5563
  this._checkAndLogResp3Hint(e);
4967
5564
  this.logger.debug("Backplane subscriber error", { error: e.message });
4968
5565
  });
4969
- sub.on("close", () => {
5566
+ this._listenBackplane(sub, "close", () => {
5567
+ this._backplaneAvailable = false;
4970
5568
  if (this._subDisconnectedAt === null) {
4971
5569
  this._subDisconnectedAt = Date.now();
4972
5570
  this.logger.debug("Backplane: subscriber disconnected", { at: this._subDisconnectedAt });
4973
5571
  }
4974
5572
  });
4975
- sub.on("ready", () => {
5573
+ this._listenBackplane(sub, "ready", () => {
4976
5574
  if (this._subDisconnectedAt !== null && this.opts.backplaneMaxStalenessMs > 0) {
4977
5575
  const gapMs = Date.now() - this._subDisconnectedAt;
4978
5576
  if (gapMs > this.opts.backplaneMaxStalenessMs) {
@@ -4985,52 +5583,119 @@ var CacheService = class _CacheService {
4985
5583
  }
4986
5584
  this._subDisconnectedAt = null;
4987
5585
  }
5586
+ if (!this._destroyed) this._backplaneAvailable = true;
4988
5587
  });
4989
5588
  const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
4990
5589
  if (isClusterSharded) {
4991
- sub.on("smessage", (_channel, message) => {
5590
+ this._listenBackplane(sub, "smessage", (_channel, message) => {
4992
5591
  this._handleBackplaneMessage(message);
4993
5592
  });
4994
- sub.ssubscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: sharded subscribed", {
5593
+ if (typeof sub.connect === "function" && (sub.isOpen === false || sub.status === "wait")) await sub.connect();
5594
+ await sub.ssubscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: sharded subscribed", {
4995
5595
  channel: this.backplaneChannel,
4996
5596
  instanceId: this.instanceId
4997
- })).catch((err) => this.logger.warn("Backplane: sharded subscribe failed", {
4998
- error: err.message
4999
5597
  }));
5000
5598
  } else {
5001
- sub.on("message", (_channel, message) => {
5599
+ this._listenBackplane(sub, "message", (_channel, message) => {
5002
5600
  this._handleBackplaneMessage(message);
5003
5601
  });
5004
- sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
5602
+ if (typeof sub.connect === "function" && (sub.isOpen === false || sub.status === "wait")) await sub.connect();
5603
+ if (this._destroyed) return;
5604
+ await sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
5005
5605
  channel: this.backplaneChannel,
5006
5606
  instanceId: this.instanceId
5007
- })).catch((err) => this.logger.warn("Backplane: subscribe failed", {
5008
- error: err.message
5009
5607
  }));
5010
5608
  }
5011
- this.subClient = sub;
5609
+ if (!this._destroyed) this._backplaneAvailable = true;
5610
+ }
5611
+ _resetAfterStreamGap() {
5612
+ this.counters.streamGaps++;
5613
+ this._fenceInvalidation();
5614
+ this.l1.clear();
5615
+ this.tagIndex.clear();
5616
+ this.keyTags.clear();
5617
+ this.tagVersions.clear();
5618
+ this.dependencyIndex.clear();
5619
+ this.keyDependencies.clear();
5620
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, Date.now());
5621
+ this._addPatternTombstone(this.nk("*"));
5622
+ this._lastStreamId = "0-0";
5012
5623
  }
5013
5624
  async _startStreamConsumer() {
5625
+ this._streamRecovering ||= this._lastStreamId !== "$" && this._lastStreamId !== "0-0";
5014
5626
  const sub = this.streamClient ?? this.createDedicatedRedisClient();
5015
5627
  this.streamClient = sub;
5628
+ if (typeof sub.xread !== "function") throw new Error("backplaneMode: stream requires a driver supporting XREAD");
5016
5629
  if (typeof sub.on === "function") {
5017
- sub.on("error", (e) => this.logger.debug("Backplane stream consumer error", { error: e.message }));
5018
- sub.on("close", () => {
5630
+ this._listenBackplane(sub, "error", (e) => this.logger.debug("Backplane stream consumer error", { error: e.message }));
5631
+ this._listenBackplane(sub, "close", () => {
5632
+ this._streamRecovering = true;
5633
+ this._backplaneAvailable = false;
5019
5634
  if (this._subDisconnectedAt === null) {
5020
5635
  this._subDisconnectedAt = Date.now();
5021
5636
  this.logger.debug("Backplane stream: consumer disconnected", { at: this._subDisconnectedAt });
5022
5637
  }
5023
5638
  });
5024
- sub.on("ready", () => {
5639
+ this._listenBackplane(sub, "ready", () => {
5025
5640
  if (this._subDisconnectedAt !== null) {
5026
5641
  this.logger.debug("Backplane stream: consumer reconnected, resuming stream read", { lastId: this._lastStreamId });
5027
5642
  this._subDisconnectedAt = null;
5028
5643
  }
5029
5644
  });
5030
5645
  }
5646
+ const checkGap = async () => {
5647
+ if (this._lastStreamId === "$" || this._lastStreamId === "0-0" || typeof sub.xrange !== "function") return;
5648
+ const first = await sub.xrange(this.backplaneStreamKey, "-", "+", "COUNT", 1);
5649
+ const firstId = first?.[0]?.[0];
5650
+ if (!firstId) return;
5651
+ const [firstMs, firstSequence] = firstId.split("-").map(BigInt);
5652
+ const [lastMs, lastSequence] = this._lastStreamId.split("-").map(BigInt);
5653
+ if (firstMs > lastMs || firstMs === lastMs && firstSequence > lastSequence) this._resetAfterStreamGap();
5654
+ };
5655
+ const apply = (response) => {
5656
+ if (this._destroyed || !response) return;
5657
+ if (this._streamRecovering && response.some(([, entries]) => entries.length > 0)) {
5658
+ this.counters.streamReplays++;
5659
+ this._streamRecovering = false;
5660
+ }
5661
+ for (const [, entries] of response) {
5662
+ for (const [id, fields] of entries) {
5663
+ this._lastStreamId = id;
5664
+ this.counters.streamEntriesReceived++;
5665
+ this._processStreamEntry(fields);
5666
+ }
5667
+ }
5668
+ };
5669
+ let initialized = false;
5670
+ const initialize = async () => {
5671
+ if (typeof sub.connect === "function" && (sub.isOpen === false || sub.status === "wait")) await sub.connect();
5672
+ if (this._destroyed) return;
5673
+ if (this._lastStreamId === "$") {
5674
+ if (this._restoredSnapshot) this._resetAfterStreamGap();
5675
+ else if (typeof sub.xrevrange === "function") {
5676
+ const latest = await sub.xrevrange(this.backplaneStreamKey, "+", "-", "COUNT", 1);
5677
+ this._lastStreamId = latest?.[0]?.[0] ?? "0-0";
5678
+ } else this._lastStreamId = "0-0";
5679
+ }
5680
+ if (typeof sub.xrange === "function") {
5681
+ await checkGap();
5682
+ apply(await sub.xread("STREAMS", this.backplaneStreamKey, this._lastStreamId));
5683
+ }
5684
+ initialized = true;
5685
+ this._backplaneAvailable = true;
5686
+ };
5687
+ try {
5688
+ await initialize();
5689
+ } catch (error) {
5690
+ this._backplaneAvailable = false;
5691
+ this.logger.warn("Backplane stream initialization failed; retrying in consumer loop", { error: error.message });
5692
+ }
5031
5693
  const runLoop = async () => {
5032
5694
  while (!this._destroyed && !this._redisDisabled) {
5033
5695
  try {
5696
+ if (!initialized) await initialize();
5697
+ if (this._destroyed) break;
5698
+ await checkGap();
5034
5699
  const res = await sub.xread(
5035
5700
  "BLOCK",
5036
5701
  this.opts.backplaneStreamBlockMs,
@@ -5039,19 +5704,10 @@ var CacheService = class _CacheService {
5039
5704
  this._lastStreamId
5040
5705
  );
5041
5706
  if (this._destroyed) break;
5707
+ this._backplaneAvailable = true;
5042
5708
  if (res && res.length > 0) {
5043
- for (const [, entries] of res) {
5044
- if (entries.length > 0) {
5045
- if (this._lastStreamId !== "$") {
5046
- this.counters.streamReplays++;
5047
- }
5048
- for (const [id, fields] of entries) {
5049
- this._lastStreamId = id;
5050
- this.counters.streamEntriesReceived++;
5051
- this._processStreamEntry(fields);
5052
- }
5053
- }
5054
- }
5709
+ apply(res);
5710
+ this._backplaneAvailable = true;
5055
5711
  } else {
5056
5712
  await new Promise((resolve) => setTimeout(resolve, 10));
5057
5713
  }
@@ -5059,10 +5715,9 @@ var CacheService = class _CacheService {
5059
5715
  if (this._destroyed) break;
5060
5716
  const msg = err.message ?? "";
5061
5717
  if (msg.includes("NOGROUP") || msg.includes("smaller than") || msg.includes("trimmed")) {
5062
- this.counters.streamGaps++;
5063
- this.l1.clear();
5064
- this._lastStreamId = "$";
5718
+ this._resetAfterStreamGap();
5065
5719
  }
5720
+ this._backplaneAvailable = false;
5066
5721
  await new Promise((resolve) => setTimeout(resolve, 200));
5067
5722
  }
5068
5723
  }
@@ -5090,8 +5745,8 @@ var CacheService = class _CacheService {
5090
5745
  else if (f === "src") src = v;
5091
5746
  else if (f === "tagVersion") tagVersionRaw = v;
5092
5747
  }
5093
- const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
5094
- if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
5748
+ const validOp = op === "del" || op === "del-glob" || op === "tag_incr" || op === "tag_pattern_incr" || op === "tag_pattern_del";
5749
+ if (!validOp || typeof key !== "string" || !key || typeof src !== "string" || !src || (op === "del" || op === "del-glob") && this._namespace && !key.startsWith(`${this._namespace}:`)) {
5095
5750
  this.logger.warn("Backplane: rejected invalid stream entry", {
5096
5751
  op: String(op).slice(0, 40),
5097
5752
  key: typeof key === "string" ? key.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(key)
@@ -5100,8 +5755,8 @@ var CacheService = class _CacheService {
5100
5755
  }
5101
5756
  let tagVersion;
5102
5757
  if (tagVersionRaw !== void 0) {
5103
- const parsed = parseInt(tagVersionRaw, 10);
5104
- if (!Number.isFinite(parsed)) {
5758
+ const parsed = Number(tagVersionRaw);
5759
+ if (!Number.isSafeInteger(parsed) || parsed < 0) {
5105
5760
  this.logger.warn("Backplane: rejected stream entry with non-numeric tagVersion", { key });
5106
5761
  return;
5107
5762
  }
@@ -5119,16 +5774,10 @@ var CacheService = class _CacheService {
5119
5774
  this.l1.delete(key);
5120
5775
  this._bumpKeyMutation(key);
5121
5776
  this.inflight.delete(key);
5122
- this._pendingDiskDeletes.add(key);
5123
- setImmediate(() => {
5124
- try {
5125
- if (!this._diskDisabled) this.disk.delete(key);
5126
- } finally {
5127
- this._pendingDiskDeletes.delete(key);
5128
- }
5129
- });
5777
+ this._invalidateDiskKey(key);
5130
5778
  this._cascadeDependencies(key);
5131
5779
  } else if (op === "del-glob") {
5780
+ this._fenceInvalidation();
5132
5781
  this.l1.deletePattern(key);
5133
5782
  const pfx = key.endsWith("*") ? key.slice(0, -1) : key;
5134
5783
  for (const liveKey of this.l1.liveKeys()) {
@@ -5142,12 +5791,22 @@ var CacheService = class _CacheService {
5142
5791
  this.inflight.delete(inflightKey);
5143
5792
  }
5144
5793
  }
5145
- this._addPatternTombstone(pfx);
5794
+ this._addPatternTombstone(key);
5795
+ this._removePatternFromIndices(key);
5796
+ if (key === this.nk("*")) {
5797
+ this.tagIndex.clear();
5798
+ this.keyTags.clear();
5799
+ this.tagVersions.clear();
5800
+ this.dependencyIndex.clear();
5801
+ this.keyDependencies.clear();
5802
+ }
5146
5803
  } else if (op === "tag_incr") {
5804
+ this._fenceInvalidation();
5147
5805
  const tag = key;
5148
5806
  const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
5149
5807
  this._setLocalTagVersion(tag, ver, performance.now());
5150
5808
  } else if (op === "tag_pattern_incr") {
5809
+ this._fenceInvalidation();
5151
5810
  const pattern = key;
5152
5811
  const now = performance.now();
5153
5812
  for (const [tag, info] of this.tagVersions) {
@@ -5167,6 +5826,7 @@ var CacheService = class _CacheService {
5167
5826
  }
5168
5827
  }, 0);
5169
5828
  } else if (op === "tag_pattern_del") {
5829
+ this._fenceInvalidation();
5170
5830
  const pattern = key;
5171
5831
  const matchedTagKeys = [];
5172
5832
  const prefix = this.nk("_tag_:");
@@ -5177,14 +5837,7 @@ var CacheService = class _CacheService {
5177
5837
  for (const k of members) {
5178
5838
  this.l1.delete(k);
5179
5839
  this._bumpKeyMutation(k);
5180
- this._pendingDiskDeletes.add(k);
5181
- setImmediate(() => {
5182
- try {
5183
- if (!this._diskDisabled) this.disk.delete(k);
5184
- } finally {
5185
- this._pendingDiskDeletes.delete(k);
5186
- }
5187
- });
5840
+ this._invalidateDiskKey(k);
5188
5841
  }
5189
5842
  }
5190
5843
  }
@@ -5215,6 +5868,7 @@ var CacheService = class _CacheService {
5215
5868
  }
5216
5869
  }
5217
5870
  async publishInvalidation(op, key, tagVersion, isCrossRegionRelay = false, isExplicitInvalidation = false) {
5871
+ if (this.opts.l2WriteMode === "read-only") return;
5218
5872
  if (!isCrossRegionRelay && this.opts.crossRegion) {
5219
5873
  const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
5220
5874
  if (shouldBroadcast) {
@@ -5297,13 +5951,13 @@ var CacheService = class _CacheService {
5297
5951
  timestamp: Date.now(),
5298
5952
  namespace: this._namespace || void 0
5299
5953
  };
5300
- this.counters.crossRegionSent++;
5301
5954
  await cr.relay.broadcast(event);
5955
+ this.counters.crossRegionSent++;
5302
5956
  this.logger.debug("Cross-region invalidation broadcast", { op, key, region: cr.currentRegion });
5303
5957
  } catch (err) {
5304
- this.counters.crossRegionSent = Math.max(0, this.counters.crossRegionSent - 1);
5305
5958
  this.counters.crossRegionErrors++;
5306
5959
  this.logger.warn("Cross-region invalidation broadcast failed", { error: err.message });
5960
+ if (this.opts.awaitInvalidationBackplane) throw err;
5307
5961
  }
5308
5962
  }
5309
5963
  /**
@@ -5314,11 +5968,12 @@ var CacheService = class _CacheService {
5314
5968
  * Returns true if the event was accepted and applied, or false if ignored/deduplicated.
5315
5969
  */
5316
5970
  async receiveCrossRegionInvalidation(event) {
5971
+ this._assertActive("receiveCrossRegionInvalidation");
5317
5972
  const cr = this.opts.crossRegion;
5318
5973
  if (!cr) return false;
5319
- if (!event || typeof event !== "object" || !event.id || !event.originRegion || !event.op || !event.key) {
5974
+ if (!isCrossRegionInvalidationEvent(event)) {
5320
5975
  this.counters.crossRegionErrors++;
5321
- this.logger.warn("Cross-region: rejected invalid event payload", { event });
5976
+ this.logger.warn("Cross-region: rejected invalid event payload");
5322
5977
  return false;
5323
5978
  }
5324
5979
  if (event.originRegion === cr.currentRegion) {
@@ -5329,16 +5984,55 @@ var CacheService = class _CacheService {
5329
5984
  this.counters.crossRegionDeduplicated++;
5330
5985
  return false;
5331
5986
  }
5332
- this._markCrossRegionEventSeen(event.id);
5333
5987
  if (event.namespace !== void 0 && event.namespace !== (this._namespace || void 0)) {
5334
5988
  return false;
5335
5989
  }
5990
+ if ((event.op === "del" || event.op === "del-glob") && this._namespace && !event.key.startsWith(`${this._namespace}:`)) return false;
5991
+ this._markCrossRegionEventSeen(event.id);
5336
5992
  this.counters.crossRegionReceived++;
5337
- this._applyInvalidationEvent(event.op, event.key, event.tagVersion);
5338
- void this.publishInvalidation(event.op, event.key, event.tagVersion, true);
5339
- this.logger.info("Cross-region invalidation applied", {
5340
- op: event.op,
5341
- key: event.key,
5993
+ const localTags = /* @__PURE__ */ new Set([...this.tagVersions.keys(), ...[...this.tagIndex.keys()].map((key) => this.unnk(key).replace(/^_tag_:/, ""))]);
5994
+ let version = event.tagVersion;
5995
+ if (event.op === "tag_incr") version = Math.max((this.tagVersions.get(event.key)?.version ?? 0) + 1, version ?? 0);
5996
+ this._applyInvalidationEvent(event.op, event.key, version);
5997
+ try {
5998
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
5999
+ const client = await this.getRedis();
6000
+ if (event.op === "del" || event.op === "del-glob") {
6001
+ await this._deleteRedisKeys(client, event.op === "del" ? [event.key] : await this._scanKeys(client, event.key));
6002
+ } else if (event.op === "tag_incr") {
6003
+ version = Number(await client.eval(LUA_RECEIVE_TAG_VERSION, 1, this.nk(`tag_ver:${event.key}`), String(version)));
6004
+ this._setLocalTagVersion(event.key, version);
6005
+ } else {
6006
+ const matched = await this._resolveMatchingTags(event.key, false);
6007
+ for (const tag of localTags) if (matchesTagPattern(event.key, tag)) matched.add(tag);
6008
+ for (const tag of matched) {
6009
+ if (event.op === "tag_pattern_incr") {
6010
+ const floor = this.tagVersions.get(tag)?.version ?? 1;
6011
+ const next = Number(await client.eval(LUA_RECEIVE_TAG_VERSION, 1, this.nk(`tag_ver:${tag}`), String(floor)));
6012
+ this._setLocalTagVersion(tag, next);
6013
+ await this.publishInvalidation("tag_incr", tag, next, true);
6014
+ } else {
6015
+ const tagKey = this.nk(`_tag_:${tag}`);
6016
+ const members = await client.smembers(tagKey);
6017
+ this._removeTagMembersLocal(members);
6018
+ await this._deleteRedisKeys(client, [...members, tagKey]);
6019
+ await Promise.all(members.map((key) => this.publishInvalidation("del", key, void 0, true)));
6020
+ }
6021
+ }
6022
+ }
6023
+ this.cb.onSuccess();
6024
+ }
6025
+ await this.publishInvalidation(event.op, event.key, version, true);
6026
+ } catch (error) {
6027
+ this._seenCrossRegionEvents.delete(event.id);
6028
+ this.counters.crossRegionErrors++;
6029
+ this.logger.warn("Cross-region regional invalidation failed", { error: error.message });
6030
+ if (this.opts.awaitInvalidationBackplane) throw error;
6031
+ return false;
6032
+ }
6033
+ this.logger.info("Cross-region invalidation applied", {
6034
+ op: event.op,
6035
+ key: event.key,
5342
6036
  originRegion: event.originRegion
5343
6037
  });
5344
6038
  return true;
@@ -5350,25 +6044,269 @@ var CacheService = class _CacheService {
5350
6044
  const oldestKey = this.tagVersions.keys().next().value;
5351
6045
  if (oldestKey !== void 0) this.tagVersions.delete(oldestKey);
5352
6046
  }
5353
- this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
6047
+ this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now, refreshEpoch: this._tagRefreshEpoch });
6048
+ }
6049
+ async _isGenerationalEntryStale(tagVersions) {
6050
+ if (!tagVersions) return false;
6051
+ const tags = Object.keys(tagVersions);
6052
+ if (tags.length === 0) return false;
6053
+ const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
6054
+ for (let i = 0; i < tags.length; i++) {
6055
+ if (currentVers[i] > tagVersions[tags[i]]) return true;
6056
+ }
6057
+ return false;
6058
+ }
6059
+ async _deleteRedisKeys(client, keys) {
6060
+ if (keys.length === 0) return;
6061
+ const CHUNK_SIZE = 1e3;
6062
+ if (client instanceof import_ioredis2.Cluster) {
6063
+ const groups = /* @__PURE__ */ new Map();
6064
+ for (const key of keys) {
6065
+ const slot = redisHashSlot(key);
6066
+ const master = client.slots?.[slot]?.[0] ?? String(slot);
6067
+ const members = groups.get(master) ?? [];
6068
+ members.push(key);
6069
+ groups.set(master, members);
6070
+ }
6071
+ await Promise.all([...groups.values()].map(async (members) => {
6072
+ for (let offset = 0; offset < members.length; offset += CHUNK_SIZE) {
6073
+ const pipeline = client.pipeline();
6074
+ for (const key of members.slice(offset, offset + CHUNK_SIZE)) pipeline.del(key);
6075
+ const result = await pipeline.exec();
6076
+ if (!result || result.some(([error]) => error)) throw new Error("Redis Cluster delete failed");
6077
+ }
6078
+ }));
6079
+ return;
6080
+ }
6081
+ for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
6082
+ const chunk = keys.slice(i, i + CHUNK_SIZE);
6083
+ await client.del(...chunk);
6084
+ }
6085
+ }
6086
+ async _parseGenerationalRedisHash(k, hashData) {
6087
+ if (!hashData || !hashData.d) return null;
6088
+ let storedTagVersions = {};
6089
+ if (hashData.tv) {
6090
+ try {
6091
+ const parsed = JSON.parse(hashData.tv);
6092
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || Object.values(parsed).some((version) => !Number.isSafeInteger(version) || Number(version) < 0)) return null;
6093
+ storedTagVersions = parsed;
6094
+ } catch {
6095
+ return null;
6096
+ }
6097
+ }
6098
+ if (await this._isGenerationalEntryStale(storedTagVersions)) {
6099
+ const setAtMs = parseInt(hashData.t, 10) || 0;
6100
+ this._deleteIfStale(k, setAtMs);
6101
+ return { stale: true };
6102
+ }
6103
+ const value = await this._decryptAndDeserialize(hashData.d);
6104
+ const expiresAt = Number(hashData.e);
6105
+ const staleAt = Number(hashData.s);
6106
+ let tags;
6107
+ let dependsOn;
6108
+ try {
6109
+ const parsedTags = hashData.tags ? JSON.parse(hashData.tags) : Object.keys(storedTagVersions);
6110
+ const parsedDependencies = hashData.deps ? JSON.parse(hashData.deps) : void 0;
6111
+ if (Array.isArray(parsedTags) && parsedTags.every((tag) => typeof tag === "string")) tags = parsedTags;
6112
+ if (Array.isArray(parsedDependencies) && parsedDependencies.every((pattern) => typeof pattern === "string")) dependsOn = parsedDependencies;
6113
+ } catch {
6114
+ return null;
6115
+ }
6116
+ return {
6117
+ value,
6118
+ tagVersions: storedTagVersions,
6119
+ stale: false,
6120
+ tags,
6121
+ dependsOn,
6122
+ setAt: Number(hashData.t) || void 0,
6123
+ expiresAt: Number.isFinite(expiresAt) && expiresAt > 0 ? expiresAt : void 0,
6124
+ staleAt: Number.isFinite(staleAt) && staleAt > 0 ? staleAt : void 0
6125
+ };
6126
+ }
6127
+ async _readRedisEntry(client, k, allowAutoPipeline = false) {
6128
+ const readStartedAt = Date.now();
6129
+ const read = async (hash) => allowAutoPipeline && this.opts.autoPipeline && this.pipeliner ? this.pipeliner.read(k, hash) : readRedisValue(client, k, hash);
6130
+ const withExpiry = (entry, ttlMs2) => {
6131
+ if (!entry || ttlMs2 === -2 || ttlMs2 === 0) return null;
6132
+ if (ttlMs2 !== void 0 && Number.isFinite(ttlMs2) && ttlMs2 > 0) {
6133
+ entry.expiresAt = Math.min(entry.expiresAt ?? Infinity, readStartedAt + ttlMs2);
6134
+ }
6135
+ return entry.expiresAt !== void 0 && entry.expiresAt <= Date.now() ? null : entry;
6136
+ };
6137
+ if (this.opts.tagStrategy === "generational" && typeof client.hgetall === "function") {
6138
+ try {
6139
+ const { raw: hashData, ttlMs: ttlMs2 } = await read(true);
6140
+ if (typeof hashData === "string") {
6141
+ const value2 = await this._decryptAndDeserialize(hashData);
6142
+ return withExpiry({ value: value2, stale: false }, ttlMs2);
6143
+ }
6144
+ if (hashData && hashData.d) {
6145
+ return withExpiry(await this._parseGenerationalRedisHash(k, hashData), ttlMs2);
6146
+ }
6147
+ return null;
6148
+ } catch (err) {
6149
+ const msg = err instanceof Error ? err.message : String(err);
6150
+ if (!msg.includes("WRONGTYPE")) throw err;
6151
+ }
6152
+ }
6153
+ const { raw, ttlMs } = await read(false);
6154
+ if (raw == null) return null;
6155
+ if (typeof raw !== "string") return null;
6156
+ const value = await this._decryptAndDeserialize(raw);
6157
+ return withExpiry({ value, stale: false }, ttlMs);
5354
6158
  }
5355
6159
  async _getTagVersion(tag) {
5356
6160
  const now = performance.now();
5357
6161
  const local = this.tagVersions.get(tag);
5358
- if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
6162
+ if (local && (local.refreshEpoch ?? 0) === this._tagRefreshEpoch && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
5359
6163
  return local.version;
5360
6164
  }
5361
6165
  if (!this._redisDisabled) {
5362
6166
  try {
5363
6167
  const client = await this.getRedis();
5364
6168
  const raw = await client.get(this.nk(`tag_ver:${tag}`));
5365
- const version = raw ? parseInt(raw, 10) : 0;
5366
- this._setLocalTagVersion(tag, version, now);
5367
- return version;
6169
+ const parsed = raw ? Number(raw) : 0;
6170
+ if (!Number.isSafeInteger(parsed) || parsed < 0) throw new Error("Invalid Redis tag generation");
6171
+ const version2 = Math.max(this.tagVersions.get(tag)?.version ?? 0, parsed);
6172
+ if (this.opts.l2WriteMode === "read-write") {
6173
+ if (raw === null) await client.set(this.nk(`tag_ver:${tag}`), String(version2), "NX");
6174
+ else if (version2 > parsed) await client.eval(LUA_MAX_TAG_VERSION, 1, this.nk(`tag_ver:${tag}`), String(version2));
6175
+ }
6176
+ this._setLocalTagVersion(tag, version2, now);
6177
+ this.cb.onSuccess();
6178
+ return version2;
5368
6179
  } catch {
5369
6180
  }
5370
6181
  }
5371
- return local?.version ?? 0;
6182
+ const version = this.tagVersions.get(tag)?.version ?? local?.version ?? 0;
6183
+ if (this._redisDisabled) this._setLocalTagVersion(tag, version, now);
6184
+ return version;
6185
+ }
6186
+ async _readRedisBatch(client, keys) {
6187
+ const entries = /* @__PURE__ */ new Map();
6188
+ const groups = /* @__PURE__ */ new Map();
6189
+ for (const key of new Set(keys)) {
6190
+ const group = client instanceof import_ioredis2.Cluster ? client.slots[redisHashSlot(key)]?.[0] ?? String(redisHashSlot(key)) : "single";
6191
+ const members = groups.get(group) ?? [];
6192
+ members.push(key);
6193
+ groups.set(group, members);
6194
+ }
6195
+ await Promise.all([...groups.values()].map(async (members) => {
6196
+ for (let offset = 0; offset < members.length; offset += 1e3) {
6197
+ const chunk = members.slice(offset, offset + 1e3);
6198
+ const pipeline = typeof client.pipeline === "function" ? client.pipeline() : client.multi();
6199
+ const timedScripts = typeof pipeline.eval === "function";
6200
+ const hashes = this.opts.tagStrategy === "generational" && typeof pipeline.hgetall === "function";
6201
+ for (const key of chunk) {
6202
+ if (timedScripts) pipeline.eval(LUA_READ_CACHE_ENTRY, 1, key);
6203
+ else if (hashes) pipeline.hgetall(key);
6204
+ else pipeline.get(key);
6205
+ }
6206
+ const startedAt = Date.now();
6207
+ const start = performance.now();
6208
+ const results = await pipeline.exec();
6209
+ this.watchdog.recordRedis(performance.now() - start);
6210
+ if (!results) throw new Error("Redis batch read aborted");
6211
+ for (let index = 0; index < chunk.length; index++) {
6212
+ try {
6213
+ const tuple = results[index];
6214
+ if (!tuple) continue;
6215
+ let [error, raw] = tuple;
6216
+ let ttl;
6217
+ if (error?.message?.includes("WRONGTYPE")) {
6218
+ const fallback = await this._readRedisEntry(client, chunk[index]);
6219
+ if (fallback && !fallback.stale) entries.set(chunk[index], fallback);
6220
+ continue;
6221
+ }
6222
+ if (error) continue;
6223
+ if (timedScripts) {
6224
+ if (!Array.isArray(raw) || raw[0] === "none") continue;
6225
+ const kind = raw[0];
6226
+ ttl = Number(raw[2]);
6227
+ const payload = raw[1];
6228
+ if (kind === "hash") {
6229
+ if (!Array.isArray(payload) || payload.length % 2 !== 0) continue;
6230
+ raw = Object.fromEntries(Array.from({ length: payload.length / 2 }, (_unused, i) => [String(payload[i * 2]), String(payload[i * 2 + 1])]));
6231
+ } else if (kind === "string") raw = payload;
6232
+ else continue;
6233
+ if (ttl === -2 || ttl === 0) continue;
6234
+ }
6235
+ const entry = typeof raw === "string" ? { value: await this._decryptAndDeserialize(raw), stale: false } : raw && typeof raw === "object" && "d" in raw ? await this._parseGenerationalRedisHash(chunk[index], raw) : null;
6236
+ if (!entry || entry.stale) continue;
6237
+ if (ttl !== void 0 && ttl > 0) entry.expiresAt = Math.min(entry.expiresAt ?? Infinity, startedAt + ttl);
6238
+ if (entry.expiresAt !== void 0 && entry.expiresAt <= Date.now()) continue;
6239
+ entries.set(chunk[index], entry);
6240
+ } catch (error) {
6241
+ this.logger.debug("mget: skipping invalid remote entry", { key: chunk[index], error: error.message });
6242
+ }
6243
+ }
6244
+ }
6245
+ }));
6246
+ this.cb.onSuccess();
6247
+ return entries;
6248
+ }
6249
+ _promoteRedisEntry(key, entry, fallbackTtlMs, priority) {
6250
+ const expiresAt = entry.expiresAt ?? Date.now() + fallbackTtlMs;
6251
+ if (expiresAt <= Date.now()) return false;
6252
+ const admitted = this.l1.set(
6253
+ key,
6254
+ entry.value,
6255
+ expiresAt - Date.now(),
6256
+ priority,
6257
+ entry.staleAt,
6258
+ void 0,
6259
+ entry.tagVersions,
6260
+ entry.setAt,
6261
+ entry.tags,
6262
+ entry.dependsOn
6263
+ );
6264
+ if (admitted) this._restoreEntryMetadata(key, { ...entry, expiresAt });
6265
+ return true;
6266
+ }
6267
+ async _readDiskEntry(key, epoch) {
6268
+ if (this._diskDisabled || this._pendingDiskDeletes.has(key) || !this.watchdog.isDiskAllowed()) return null;
6269
+ const start = performance.now();
6270
+ const entry = this.disk.load(key);
6271
+ const elapsed = performance.now() - start;
6272
+ this.watchdog.recordDisk(elapsed);
6273
+ this.watchdog.onCanaryResult(entry !== null, elapsed);
6274
+ if (!entry || this._isTombstonedByPattern(key, entry.setAt ?? 0) || await this._isGenerationalEntryStale(entry.tagVersions) || this._destroyed || this._getKeyMutationEpoch(key) !== epoch || entry.expiresAt <= Date.now()) return null;
6275
+ this.l1.importEntries([{ key, entry }], this.opts.forbiddenSnapshotPrefixes);
6276
+ const hit = this.l1.get(key);
6277
+ const value = hit ? hit.value : entry.isCompressed ? this.codec.decode(entry.data) : JSON.parse(entry.data);
6278
+ this._restoreEntryMetadata(key, entry);
6279
+ return { value, entry };
6280
+ }
6281
+ /** Common write policy and metadata across get/set/revalidation/draining. */
6282
+ async _writeRedisEntry(key, data, expiresAt, setAt, tagVersions, staleAt, tags, dependsOn, canCommit = () => true) {
6283
+ if (this._redisDisabled || this.opts.l2WriteMode !== "read-write" || !canCommit() || this._destroyed) return;
6284
+ const client = await this.getRedis();
6285
+ const stored = await this._serializeAndEncrypt(JSON.stringify(data) ?? "undefined");
6286
+ if (!canCommit() || this._destroyed) return;
6287
+ const useHash = this.opts.tagStrategy === "generational" && (tagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function");
6288
+ const remaining = (useHash ? expiresAt : staleAt ?? expiresAt) - Date.now();
6289
+ if (remaining <= 0) return;
6290
+ const ttl = Math.max(1, Math.ceil(remaining / 1e3));
6291
+ if (useHash) {
6292
+ const transaction = client.multi();
6293
+ transaction.del(key);
6294
+ const hash = { d: stored, t: String(setAt), tv: JSON.stringify(tagVersions ?? {}), e: String(expiresAt) };
6295
+ if (staleAt !== void 0) hash.s = String(staleAt);
6296
+ if (tags?.length) hash.tags = JSON.stringify(tags);
6297
+ if (dependsOn?.length) hash.deps = JSON.stringify(dependsOn);
6298
+ transaction.hset(key, hash);
6299
+ transaction.expire(key, ttl);
6300
+ const result = await transaction.exec();
6301
+ if (!result || result.some(([error]) => error)) throw new Error("Redis cache write transaction failed");
6302
+ } else if (this.opts.autoPipeline && this.pipeliner) {
6303
+ if (typeof client.pttl === "function" && typeof client.set === "function") await this.pipeliner.setpx(key, Math.ceil(remaining), stored);
6304
+ else await this.pipeliner.setex(key, ttl, stored);
6305
+ } else {
6306
+ if (typeof client.pttl === "function" && typeof client.set === "function") await client.set(key, stored, "PX", Math.ceil(remaining));
6307
+ else await client.setex(key, ttl, stored);
6308
+ }
6309
+ this.cb.onSuccess();
5372
6310
  }
5373
6311
  _deleteIfStale(k, setAtMs) {
5374
6312
  this.l1.deleteIfSetBefore(k, setAtMs);
@@ -5421,7 +6359,7 @@ var CacheService = class _CacheService {
5421
6359
  } else {
5422
6360
  plain = raw;
5423
6361
  }
5424
- return JSON.parse(plain);
6362
+ return plain === "undefined" ? void 0 : JSON.parse(plain);
5425
6363
  }
5426
6364
  /**
5427
6365
  * Scan all keys matching `pattern` across single-node or Cluster clients.
@@ -5429,7 +6367,7 @@ var CacheService = class _CacheService {
5429
6367
  */
5430
6368
  async _scanKeys(client, pattern) {
5431
6369
  const keys = [];
5432
- if (client instanceof import_ioredis.Cluster) {
6370
+ if (client instanceof import_ioredis2.Cluster) {
5433
6371
  const masters = client.nodes("master");
5434
6372
  await Promise.all(masters.map(
5435
6373
  (node) => new Promise((resolve, reject) => {
@@ -5489,10 +6427,10 @@ var CacheService = class _CacheService {
5489
6427
  return client;
5490
6428
  }
5491
6429
  this.redisConnecting = (async () => {
6430
+ let client = null;
5492
6431
  try {
5493
- let client;
5494
6432
  if (this.opts.redisClusterNodes?.length) {
5495
- client = new import_ioredis.Cluster(this.opts.redisClusterNodes, {
6433
+ client = new import_ioredis2.Cluster(this.opts.redisClusterNodes, {
5496
6434
  redisOptions: {
5497
6435
  tls: this.opts.redisTls ? {} : void 0,
5498
6436
  connectTimeout: 1e4,
@@ -5512,7 +6450,7 @@ var CacheService = class _CacheService {
5512
6450
  });
5513
6451
  client.on("reconnecting", () => this.logger.debug("Redis Cluster reconnecting"));
5514
6452
  } else if (this.opts.redisSentinel) {
5515
- client = new import_ioredis.Redis({
6453
+ client = new import_ioredis2.Redis({
5516
6454
  sentinels: this.opts.redisSentinel.sentinels,
5517
6455
  name: this.opts.redisSentinel.name,
5518
6456
  tls: this.opts.redisTls ? {} : void 0,
@@ -5532,7 +6470,7 @@ var CacheService = class _CacheService {
5532
6470
  });
5533
6471
  client.on("reconnecting", () => this.logger.debug("Redis Sentinel reconnecting"));
5534
6472
  } else {
5535
- client = new import_ioredis.Redis({
6473
+ client = new import_ioredis2.Redis({
5536
6474
  host: this.opts.redisHost,
5537
6475
  port: this.opts.redisPort,
5538
6476
  tls: this.opts.redisTls ? {} : void 0,
@@ -5553,14 +6491,45 @@ var CacheService = class _CacheService {
5553
6491
  });
5554
6492
  client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
5555
6493
  }
6494
+ const pendingClient = client;
5556
6495
  await new Promise((resolve, reject) => {
5557
- client.once("ready", resolve);
5558
- client.once("error", (e) => {
6496
+ let settled = false;
6497
+ const cleanupListeners = () => {
6498
+ pendingClient.removeListener?.("ready", onReady);
6499
+ pendingClient.removeListener?.("error", onError);
6500
+ };
6501
+ const onReady = () => {
6502
+ if (settled) return;
6503
+ settled = true;
6504
+ clearTimeout(timer);
6505
+ cleanupListeners();
6506
+ resolve();
6507
+ };
6508
+ const onError = (e) => {
6509
+ if (settled) return;
6510
+ settled = true;
6511
+ clearTimeout(timer);
6512
+ cleanupListeners();
5559
6513
  this._checkAndLogResp3Hint(e);
5560
6514
  reject(e);
5561
- });
5562
- setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
6515
+ };
6516
+ const timer = setTimeout(() => {
6517
+ if (settled) return;
6518
+ settled = true;
6519
+ cleanupListeners();
6520
+ reject(new Error("Redis connection timeout"));
6521
+ }, 15e3);
6522
+ if (timer.unref) timer.unref();
6523
+ pendingClient.once("ready", onReady);
6524
+ pendingClient.once("error", onError);
5563
6525
  });
6526
+ if (this._destroyed) {
6527
+ try {
6528
+ client.disconnect();
6529
+ } catch {
6530
+ }
6531
+ this._assertActive("getRedis");
6532
+ }
5564
6533
  this.cb.onSuccess();
5565
6534
  this.redis = client;
5566
6535
  this.pipeliner = new AutoPipeliner(client, {
@@ -5570,6 +6539,10 @@ var CacheService = class _CacheService {
5570
6539
  this.redisConnecting = null;
5571
6540
  return client;
5572
6541
  } catch (err) {
6542
+ try {
6543
+ client?.disconnect();
6544
+ } catch {
6545
+ }
5573
6546
  this.cb.onFailure();
5574
6547
  this.redisConnecting = null;
5575
6548
  this._checkAndLogResp3Hint(err);
@@ -5589,7 +6562,12 @@ var CacheService = class _CacheService {
5589
6562
  try {
5590
6563
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
5591
6564
  if (entries.length === 0) return;
5592
- const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
6565
+ const payload = {
6566
+ version: SNAPSHOT_VERSION,
6567
+ writtenAt: Date.now(),
6568
+ entries,
6569
+ streamId: this.opts.backplaneMode === "stream" && this._lastStreamId !== "$" ? this._lastStreamId : void 0
6570
+ };
5593
6571
  const packed = this.codec.encode(payload);
5594
6572
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
5595
6573
  const dest = altPath ?? this.opts.snapshotPath;
@@ -5657,6 +6635,9 @@ var CacheService = class _CacheService {
5657
6635
  return;
5658
6636
  }
5659
6637
  const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
6638
+ this._restoredSnapshot ||= loaded > 0;
6639
+ if (typeof snapshot.streamId === "string" && /^\d{1,20}-\d{1,20}$/.test(snapshot.streamId)) this._lastStreamId = snapshot.streamId;
6640
+ for (const { key, entry } of snapshot.entries) if (this.l1.has(key)) this._restoreEntryMetadata(key, entry);
5660
6641
  this.logger.info("Cache snapshot loaded (L1 is warm)", {
5661
6642
  loaded,
5662
6643
  total: snapshot.entries.length,
@@ -5681,7 +6662,12 @@ var CacheService = class _CacheService {
5681
6662
  try {
5682
6663
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
5683
6664
  if (entries.length === 0) return false;
5684
- const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
6665
+ const payload = {
6666
+ version: SNAPSHOT_VERSION,
6667
+ writtenAt: Date.now(),
6668
+ entries,
6669
+ streamId: this.opts.backplaneMode === "stream" && this._lastStreamId !== "$" ? this._lastStreamId : void 0
6670
+ };
5685
6671
  const packed = this.codec.encode(payload);
5686
6672
  let final;
5687
6673
  if (this.opts.remoteSnapshot.envelope) {
@@ -5712,13 +6698,16 @@ var CacheService = class _CacheService {
5712
6698
  async loadRemoteSnapshot() {
5713
6699
  if (!this.opts.remoteSnapshot) return 0;
5714
6700
  const maxAgeMs = this.opts.remoteSnapshot.maxAgeMs ?? this.opts.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE;
6701
+ const epoch = this._globalEpoch;
5715
6702
  try {
5716
6703
  const raw = await this.opts.remoteSnapshot.adapter.get();
6704
+ if (this._destroyed || this._globalEpoch !== epoch) return 0;
5717
6705
  if (!raw || raw.length === 0) {
5718
6706
  this.logger.debug("Remote snapshot not found or empty \u2014 starting cold");
5719
6707
  return 0;
5720
6708
  }
5721
6709
  const rawBuf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
6710
+ if (rawBuf.length > SNAPSHOT_MAX_FILE_BYTES) throw new Error("Remote snapshot exceeds size limit");
5722
6711
  let buf;
5723
6712
  try {
5724
6713
  if (EnvelopeEncryption.isEnvelope(rawBuf)) {
@@ -5764,7 +6753,12 @@ var CacheService = class _CacheService {
5764
6753
  this.logger.warn("Remote snapshot rejected: entries is not an array");
5765
6754
  return 0;
5766
6755
  }
5767
- const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
6756
+ if (this._destroyed || this._globalEpoch !== epoch) return 0;
6757
+ const eligible = snapshot.entries.filter((item) => item && !this._keyMutationEpochs.has(item.key));
6758
+ const loaded = this.l1.importEntries(eligible, this.opts.forbiddenSnapshotPrefixes);
6759
+ this._restoredSnapshot ||= loaded > 0;
6760
+ if (typeof snapshot.streamId === "string" && /^\d{1,20}-\d{1,20}$/.test(snapshot.streamId)) this._lastStreamId = snapshot.streamId;
6761
+ for (const { key, entry } of eligible) if (this.l1.has(key)) this._restoreEntryMetadata(key, entry);
5768
6762
  this.counters.remoteSnapshotDownloads++;
5769
6763
  this.counters.remoteSnapshotLastDownloadedAt = Date.now();
5770
6764
  this.logger.info("Remote cache snapshot loaded (L1 hydrated)", {
@@ -5813,20 +6807,10 @@ var CacheService = class _CacheService {
5813
6807
  const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
5814
6808
  const l1Hit = this.l1.get(k);
5815
6809
  if (l1Hit !== null) {
5816
- let isGenerationalStale = false;
5817
- if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
5818
- const tags = Object.keys(l1Hit.tagVersions);
5819
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5820
- for (let i = 0; i < tags.length; i++) {
5821
- if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
5822
- isGenerationalStale = true;
5823
- break;
5824
- }
5825
- }
5826
- }
6810
+ const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
5827
6811
  if (isGenerationalStale) {
5828
6812
  this._deleteIfStale(k, l1Hit.setAt ?? 0);
5829
- } else {
6813
+ } else if (!l1Hit.isStale || optSwr > 0) {
5830
6814
  if (l1Hit.isStale) {
5831
6815
  const swrGraceMs2 = optSwr * 1e3;
5832
6816
  if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
@@ -5889,115 +6873,58 @@ var CacheService = class _CacheService {
5889
6873
  this.counters.stampedes++;
5890
6874
  this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch/read", { cacheKey });
5891
6875
  span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
5892
- return existing;
6876
+ return this._prepareReadValue(await existing);
5893
6877
  }
5894
6878
  const mutationEpochAtStart = this._getKeyMutationEpoch(k);
5895
- const executionPromise = (async () => {
6879
+ const executionPromise = Promise.resolve().then(async () => {
5896
6880
  try {
5897
- if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
5898
- if (this._isTombstonedByPattern(k)) {
5899
- try {
5900
- this.disk.delete(k);
5901
- } catch {
5902
- }
5903
- } else {
5904
- const isDiskAllowed = this.watchdog.isDiskAllowed();
5905
- if (isDiskAllowed) {
5906
- const diskStart = performance.now();
5907
- const diskHit = this.disk.load(k);
5908
- const diskElapsed = performance.now() - diskStart;
5909
- this.watchdog.recordDisk(diskElapsed);
5910
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
5911
- if (diskHit !== null) {
5912
- let isDiskStale = false;
5913
- if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
5914
- const tags = Object.keys(diskHit.tagVersions);
5915
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5916
- for (let i = 0; i < tags.length; i++) {
5917
- if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
5918
- isDiskStale = true;
5919
- break;
5920
- }
5921
- }
5922
- }
5923
- if (isDiskStale) {
5924
- this.disk.delete(k);
5925
- } else {
5926
- const promoted = this.l1.importEntries(
5927
- [{ key: k, entry: diskHit }],
5928
- this.opts.forbiddenSnapshotPrefixes
5929
- );
5930
- if (promoted > 0) {
5931
- const l1Check = this.l1.get(k);
5932
- if (l1Check !== null) {
5933
- this.counters.diskHits++;
5934
- this.opts.onHit?.(cacheKey, "disk");
5935
- this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
5936
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
5937
- if (this.opts.frozen) deepFreeze(l1Check.value);
5938
- return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
5939
- }
5940
- }
5941
- }
5942
- }
5943
- }
6881
+ const diskHit = await this._readDiskEntry(k, mutationEpochAtStart);
6882
+ if (diskHit && (diskHit.entry.staleAt === void 0 || diskHit.entry.staleAt > Date.now() || optSwr > 0)) {
6883
+ this.counters.diskHits++;
6884
+ this.opts.onHit?.(cacheKey, "disk");
6885
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
6886
+ if (diskHit.entry.staleAt !== void 0 && diskHit.entry.staleAt <= Date.now() && optSwr > 0 && !this.revalidating.has(k)) {
6887
+ this.revalidating.add(k);
6888
+ this.counters.swrRevalidations++;
6889
+ void this._revalidate(
6890
+ k,
6891
+ fetchFn,
6892
+ ttlMs,
6893
+ swrGraceMs,
6894
+ priority,
6895
+ diskHit.entry.tagVersions ?? Object.fromEntries((diskHit.entry.tags ?? []).map((tag) => [tag, 0]))
6896
+ );
5944
6897
  }
6898
+ return diskHit.value;
5945
6899
  }
5946
6900
  if (!this._redisDisabled) {
5947
6901
  try {
5948
6902
  const client = await this.getRedis();
5949
6903
  const redisStart = performance.now();
5950
- if (this.opts.tagStrategy === "generational") {
5951
- const hashData = await client.hgetall(k);
5952
- const redisElapsed = performance.now() - redisStart;
5953
- this.watchdog.recordRedis(redisElapsed);
5954
- this.cb.onSuccess();
5955
- if (hashData && hashData.d) {
5956
- let isStale = false;
5957
- let storedTagVersions = {};
5958
- if (hashData.tv) {
5959
- try {
5960
- storedTagVersions = JSON.parse(hashData.tv);
5961
- } catch {
5962
- }
5963
- }
5964
- const tags = Object.keys(storedTagVersions);
5965
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5966
- for (let i = 0; i < tags.length; i++) {
5967
- if (currentVers[i] > storedTagVersions[tags[i]]) {
5968
- isStale = true;
5969
- break;
5970
- }
5971
- }
5972
- if (isStale) {
5973
- const setAtMs = parseInt(hashData.t, 10) || 0;
5974
- this._deleteIfStale(k, setAtMs);
5975
- } else {
5976
- const parsed = await this._decryptAndDeserialize(hashData.d);
5977
- this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
5978
- this.counters.l2Hits++;
5979
- this.opts.onHit?.(cacheKey, "l2");
5980
- this.logger.debug("L2 hit (Redis hash)", { cacheKey });
5981
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5982
- if (this.opts.frozen) deepFreeze(parsed);
5983
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
5984
- }
6904
+ const redisHit = await this._readRedisEntry(client, k, true);
6905
+ const redisElapsed = performance.now() - redisStart;
6906
+ this.watchdog.recordRedis(redisElapsed);
6907
+ this.cb.onSuccess();
6908
+ if (redisHit && !redisHit.stale && (redisHit.staleAt === void 0 || redisHit.staleAt > Date.now() || optSwr > 0)) {
6909
+ const parsed = redisHit.value;
6910
+ if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
6911
+ this.logger.debug("Aborting L2 promotion \u2014 key was mutated or deleted during Redis read", { cacheKey });
6912
+ span.setAttribute("cache.aborted_mutation_race", true);
6913
+ const current = this.l1.get(k);
6914
+ const liveVal = current && !current.isStale ? current.value : parsed;
6915
+ return liveVal;
5985
6916
  }
5986
- } else {
5987
- const raw = this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
5988
- const redisElapsed = performance.now() - redisStart;
5989
- this.watchdog.recordRedis(redisElapsed);
5990
- this.cb.onSuccess();
5991
- if (raw) {
5992
- const parsed = await this._decryptAndDeserialize(raw);
5993
- this.l1.set(k, parsed, ttlMs, priority);
5994
- this.counters.l2Hits++;
5995
- this.opts.onHit?.(cacheKey, "l2");
5996
- this.logger.debug("L2 hit (Redis)", { cacheKey });
5997
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5998
- if (this.opts.frozen) deepFreeze(parsed);
5999
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
6917
+ if (!this._promoteRedisEntry(k, redisHit, ttlMs, priority)) throw new Error("Redis entry expired during promotion");
6918
+ this.counters.l2Hits++;
6919
+ this.opts.onHit?.(cacheKey, "l2");
6920
+ this.logger.debug(redisHit.tagVersions ? "L2 hit (Redis hash)" : "L2 hit (Redis)", { cacheKey });
6921
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
6922
+ if (redisHit.staleAt !== void 0 && redisHit.staleAt <= Date.now() && optSwr > 0 && !this.revalidating.has(k)) {
6923
+ this.revalidating.add(k);
6924
+ this.counters.swrRevalidations++;
6925
+ void this._revalidate(k, fetchFn, ttlMs, swrGraceMs, priority, redisHit.tagVersions);
6000
6926
  }
6927
+ return parsed;
6001
6928
  }
6002
6929
  } catch (err) {
6003
6930
  this.cb.onFailure();
@@ -6007,6 +6934,7 @@ var CacheService = class _CacheService {
6007
6934
  span.setAttribute("cache.hit", false).setAttribute("cache.hit_tier", "miss");
6008
6935
  this.opts.onMiss?.(cacheKey);
6009
6936
  this.counters.fetches++;
6937
+ const tagSnapshot = this.opts.tagStrategy === "generational" && optTags?.length ? Object.fromEntries(await Promise.all(optTags.map(async (tag) => [tag, await this._getTagVersion(tag)]))) : void 0;
6010
6938
  const fetchStart = Date.now();
6011
6939
  let data;
6012
6940
  try {
@@ -6035,50 +6963,41 @@ var CacheService = class _CacheService {
6035
6963
  }
6036
6964
  const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
6037
6965
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
6038
- let activeTagVersions;
6966
+ const activeTagVersions = tagSnapshot;
6039
6967
  if (optTags?.length) {
6040
6968
  if (this.opts.tagStrategy === "generational") {
6041
- const vers = await Promise.all(optTags.map((tag) => this._getTagVersion(tag)));
6042
- activeTagVersions = {};
6043
- for (let i = 0; i < optTags.length; i++) {
6044
- activeTagVersions[optTags[i]] = vers[i];
6045
- }
6969
+ if (await this._isGenerationalEntryStale(tagSnapshot)) return data;
6046
6970
  } else {
6047
- await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
6971
+ await this._registerTags(k, optTags, Math.ceil(storeTtl / 1e3));
6048
6972
  }
6049
6973
  }
6050
6974
  if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
6051
6975
  this.logger.debug("Aborting in-flight cache commit \u2014 key was mutated or deleted during fetch", { cacheKey });
6052
6976
  span.setAttribute("cache.aborted_mutation_race", true);
6053
6977
  const current = this.l1.get(k);
6054
- if (current && !current.isStale && current.value !== void 0) {
6978
+ if (current && !current.isStale) {
6055
6979
  const freshVal = current.value;
6056
- if (this.opts.frozen) deepFreeze(freshVal);
6057
- return this.opts.cloneStrategy === "structuredClone" && freshVal != null && typeof freshVal === "object" ? structuredClone(freshVal) : freshVal;
6980
+ return freshVal;
6058
6981
  }
6059
- if (this.opts.frozen) deepFreeze(data);
6060
- return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
6982
+ return data;
6061
6983
  }
6062
- this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
6063
- if (!this._redisDisabled) {
6984
+ const writeTs = Date.now();
6985
+ this._invalidateDiskKey(k);
6986
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs, optTags, opts.dependsOn);
6987
+ this._restoreEntryMetadata(k, { tags: optTags, dependsOn: opts.dependsOn, expiresAt: writeTs + storeTtl });
6988
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6064
6989
  try {
6065
- const client = await this.getRedis();
6066
- const serialized = JSON.stringify(data);
6067
- const toStore = await this._serializeAndEncrypt(serialized);
6068
- const ttlSec = Math.ceil(effectiveTtl / 1e3);
6069
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
6070
- const now = Date.now();
6071
- const tx = client.multi();
6072
- tx.hset(k, {
6073
- d: toStore,
6074
- t: String(now),
6075
- tv: JSON.stringify(activeTagVersions)
6076
- });
6077
- tx.expire(k, ttlSec);
6078
- await tx.exec();
6079
- } else {
6080
- await client.setex(k, ttlSec, toStore);
6081
- }
6990
+ await this._writeRedisEntry(
6991
+ k,
6992
+ data,
6993
+ writeTs + storeTtl,
6994
+ writeTs,
6995
+ activeTagVersions,
6996
+ staleAt,
6997
+ optTags,
6998
+ opts.dependsOn,
6999
+ () => this._getKeyMutationEpoch(k) === mutationEpochAtStart
7000
+ );
6082
7001
  this.cb.onSuccess();
6083
7002
  this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
6084
7003
  } catch {
@@ -6088,15 +7007,14 @@ var CacheService = class _CacheService {
6088
7007
  } else {
6089
7008
  this.logger.debug("Cached L1", { cacheKey });
6090
7009
  }
6091
- if (this.opts.frozen) deepFreeze(data);
6092
- return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
7010
+ return data;
6093
7011
  } finally {
6094
- this.inflight.delete(k);
7012
+ if (this.inflight.get(k) === executionPromise) this.inflight.delete(k);
6095
7013
  span.end();
6096
7014
  }
6097
- })();
7015
+ });
6098
7016
  this.inflight.set(k, executionPromise);
6099
- return executionPromise;
7017
+ return this._prepareReadValue(await executionPromise);
6100
7018
  }
6101
7019
  /**
6102
7020
  * Graceful shutdown flusher for Kubernetes preStop hooks, NestJS onApplicationShutdown,
@@ -6177,6 +7095,9 @@ var CacheService = class _CacheService {
6177
7095
  }
6178
7096
  async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority, knownTagVersions) {
6179
7097
  const startEpoch = this._getKeyMutationEpoch(cacheKey);
7098
+ const previous = this.l1.getEntry(cacheKey);
7099
+ const tags = previous?.tags ?? Object.keys(knownTagVersions ?? {});
7100
+ const dependencies = previous?.dependsOn;
6180
7101
  try {
6181
7102
  const fetchStart = Date.now();
6182
7103
  const data = await fetchFn();
@@ -6191,14 +7112,14 @@ var CacheService = class _CacheService {
6191
7112
  const l1Existing = this.l1.get(cacheKey);
6192
7113
  const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
6193
7114
  if (this.opts.tagStrategy === "generational" && tagVersionsSource) {
6194
- const tags = Object.keys(tagVersionsSource);
6195
- const vers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
7115
+ const tags2 = Object.keys(tagVersionsSource);
7116
+ const vers = await Promise.all(tags2.map((tag) => this._getTagVersion(tag)));
6196
7117
  activeTagVersions = {};
6197
- for (let i = 0; i < tags.length; i++) {
6198
- activeTagVersions[tags[i]] = vers[i];
7118
+ for (let i = 0; i < tags2.length; i++) {
7119
+ activeTagVersions[tags2[i]] = vers[i];
6199
7120
  }
6200
7121
  if (knownTagVersions) {
6201
- for (const t of tags) {
7122
+ for (const t of tags2) {
6202
7123
  if (knownTagVersions[t] !== void 0 && activeTagVersions[t] !== knownTagVersions[t]) {
6203
7124
  this.logger.debug("SWR: aborting revalidation commit \u2014 tag version bumped during revalidation", { cacheKey, tag: t });
6204
7125
  return;
@@ -6210,32 +7131,29 @@ var CacheService = class _CacheService {
6210
7131
  this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
6211
7132
  return;
6212
7133
  }
6213
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
7134
+ const writeTs = Date.now();
7135
+ this._invalidateDiskKey(cacheKey);
7136
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs, tags, dependencies);
7137
+ this._restoreEntryMetadata(cacheKey, { tags, dependsOn: dependencies, expiresAt: writeTs + ttlMs + swrGraceMs });
6214
7138
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6215
7139
  try {
6216
- const client = await this.getRedis();
6217
- const s = JSON.stringify(data);
6218
- const stored = await this._serializeAndEncrypt(s);
6219
- const ttlSec = Math.ceil(ttlMs / 1e3);
6220
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
6221
- const now = Date.now();
6222
- const tx = client.multi();
6223
- tx.hset(cacheKey, {
6224
- d: stored,
6225
- t: String(now),
6226
- tv: JSON.stringify(activeTagVersions)
6227
- });
6228
- tx.expire(cacheKey, ttlSec);
6229
- await tx.exec();
6230
- } else {
6231
- await client.setex(cacheKey, ttlSec, stored);
6232
- }
7140
+ await this._writeRedisEntry(
7141
+ cacheKey,
7142
+ data,
7143
+ writeTs + ttlMs + swrGraceMs,
7144
+ writeTs,
7145
+ activeTagVersions,
7146
+ staleAt,
7147
+ tags,
7148
+ dependencies,
7149
+ () => this._getKeyMutationEpoch(cacheKey) === startEpoch
7150
+ );
6233
7151
  } catch {
6234
7152
  }
6235
7153
  }
6236
7154
  this.logger.debug("SWR: revalidation complete", { cacheKey });
6237
7155
  } catch (err) {
6238
- if (this.opts.staleIfError > 0) {
7156
+ if (this.opts.staleIfError > 0 && this._getKeyMutationEpoch(cacheKey) === startEpoch) {
6239
7157
  const additionalMs = this.opts.staleIfError * 1e3;
6240
7158
  this.l1.bumpExpiry(cacheKey, additionalMs);
6241
7159
  this.logger.debug("SWR: revalidation failed, stale-if-error extending expiry", {
@@ -6263,12 +7181,16 @@ var CacheService = class _CacheService {
6263
7181
  const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
6264
7182
  const p = priority ?? inferPriority(cacheKey);
6265
7183
  const k = this.nk(cacheKey);
7184
+ const existingEntry = this.l1.getEntry(k);
7185
+ const requestedTags = opts?.tags ?? existingEntry?.tags ?? this.keyTags.get(k)?.tags;
7186
+ const requestedDependencies = opts?.dependsOn ?? existingEntry?.dependsOn;
6266
7187
  this._bumpKeyMutation(k);
7188
+ const epoch = this._getKeyMutationEpoch(k);
6267
7189
  this.inflight.delete(k);
6268
- this._pendingDiskDeletes.delete(k);
7190
+ this._invalidateDiskKey(k);
6269
7191
  this.counters.sets++;
6270
7192
  let activeTagVersions;
6271
- const tagsToRegister = opts?.tags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
7193
+ const tagsToRegister = requestedTags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(requestedTags, this.opts.tagHierarchyDelimiter) : requestedTags : void 0;
6272
7194
  if (tagsToRegister?.length) {
6273
7195
  if (this.opts.tagStrategy === "generational") {
6274
7196
  const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
@@ -6277,44 +7199,27 @@ var CacheService = class _CacheService {
6277
7199
  activeTagVersions[tagsToRegister[i]] = vers[i];
6278
7200
  }
6279
7201
  } else {
6280
- await this._registerTags(k, tagsToRegister, ttlSeconds);
6281
- }
6282
- }
6283
- this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
6284
- if (opts?.dependsOn?.length) {
6285
- for (const pattern of opts.dependsOn) {
6286
- const nsPattern = this.nk(pattern);
6287
- let deps = this.dependencyIndex.get(nsPattern);
6288
- if (!deps) {
6289
- deps = /* @__PURE__ */ new Set();
6290
- this.dependencyIndex.set(nsPattern, deps);
6291
- }
6292
- deps.add(k);
7202
+ await this._registerTags(k, tagsToRegister, effectiveTtlSeconds);
6293
7203
  }
6294
7204
  }
7205
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return;
7206
+ const writeTs = Date.now();
7207
+ this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions, writeTs, tagsToRegister, requestedDependencies);
7208
+ this._rememberTags(k, tagsToRegister ?? [], writeTs + ttlMs);
7209
+ this._registerDependencies(k, requestedDependencies);
6295
7210
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6296
7211
  try {
6297
- const client = await this.getRedis();
6298
- const s = JSON.stringify(data);
6299
- const stored = await this._serializeAndEncrypt(s);
6300
- const ttlSec = Math.ceil(ttlMs / 1e3);
6301
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
6302
- const now = Date.now();
6303
- const tx = client.multi();
6304
- tx.hset(k, {
6305
- d: stored,
6306
- t: String(now),
6307
- tv: JSON.stringify(activeTagVersions)
6308
- });
6309
- tx.expire(k, ttlSec);
6310
- await tx.exec();
6311
- } else {
6312
- if (this.opts.autoPipeline && this.pipeliner) {
6313
- await this.pipeliner.setex(k, ttlSec, stored);
6314
- } else {
6315
- await client.setex(k, ttlSec, stored);
6316
- }
6317
- }
7212
+ await this._writeRedisEntry(
7213
+ k,
7214
+ data,
7215
+ writeTs + ttlMs,
7216
+ writeTs,
7217
+ activeTagVersions,
7218
+ void 0,
7219
+ tagsToRegister,
7220
+ requestedDependencies,
7221
+ () => this._getKeyMutationEpoch(k) === epoch
7222
+ );
6318
7223
  this.cb.onSuccess();
6319
7224
  } catch (err) {
6320
7225
  this.cb.onFailure();
@@ -6339,23 +7244,18 @@ var CacheService = class _CacheService {
6339
7244
  * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
6340
7245
  */
6341
7246
  async _registerTags(k, tags, ttlSeconds) {
6342
- for (const tag of tags) {
6343
- const tagKey = this.nk(`_tag_:${tag}`);
6344
- let members = this.tagIndex.get(tagKey);
6345
- if (!members) {
6346
- members = /* @__PURE__ */ new Set();
6347
- this.tagIndex.set(tagKey, members);
6348
- }
6349
- members.add(k);
6350
- }
7247
+ const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
7248
+ const expiresAt = Date.now() + effectiveTtl * 1e3;
7249
+ const uniqueTags = Array.from(new Set(tags));
7250
+ this._rememberTags(k, uniqueTags, expiresAt);
6351
7251
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6352
7252
  try {
6353
7253
  const client = await this.getRedis();
6354
7254
  const pl = client.pipeline();
6355
- for (const tag of tags) {
7255
+ for (const tag of uniqueTags) {
6356
7256
  const tagKey = this.nk(`_tag_:${tag}`);
6357
7257
  pl.sadd(tagKey, k);
6358
- pl.expire(tagKey, ttlSeconds + 3600);
7258
+ pl.expire(tagKey, effectiveTtl + 3600);
6359
7259
  }
6360
7260
  await pl.exec();
6361
7261
  this.cb.onSuccess();
@@ -6380,6 +7280,7 @@ var CacheService = class _CacheService {
6380
7280
  const k = this.nk(cacheKey);
6381
7281
  this.counters.deletes++;
6382
7282
  if (isPattern) {
7283
+ this._fenceInvalidation();
6383
7284
  const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6384
7285
  for (const liveKey of this.l1.liveKeys()) {
6385
7286
  if (liveKey.startsWith(pfx)) {
@@ -6392,29 +7293,30 @@ var CacheService = class _CacheService {
6392
7293
  this.inflight.delete(inflightKey);
6393
7294
  }
6394
7295
  }
6395
- this._addPatternTombstone(pfx);
7296
+ this._addPatternTombstone(k);
6396
7297
  this.l1.deletePattern(k);
7298
+ this._removePatternFromIndices(k);
7299
+ for (const ktKey of Array.from(this.keyTags.keys())) {
7300
+ if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
7301
+ }
7302
+ for (const kdKey of Array.from(this.keyDependencies.keys())) {
7303
+ if (this._matchesGlob(kdKey, k)) this._removeKeyDependencies(kdKey);
7304
+ }
6397
7305
  } else {
6398
7306
  this._bumpKeyMutation(k);
6399
7307
  this.inflight.delete(k);
6400
7308
  this.l1.delete(k);
6401
- this._pendingDiskDeletes.add(k);
6402
- setImmediate(() => {
6403
- try {
6404
- if (!this._diskDisabled) this.disk.delete(k);
6405
- } finally {
6406
- this._pendingDiskDeletes.delete(k);
6407
- }
6408
- });
7309
+ this._invalidateDiskKey(k);
7310
+ this._removeKeyTags(k);
6409
7311
  this._cascadeDependencies(k);
6410
- for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
7312
+ this._removeKeyDependencies(k);
6411
7313
  }
6412
7314
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6413
7315
  try {
6414
7316
  const client = await this.getRedis();
6415
7317
  if (isPattern) {
6416
7318
  const keys = await this._scanKeys(client, k);
6417
- if (keys.length > 0) await client.del(...keys);
7319
+ await this._deleteRedisKeys(client, keys);
6418
7320
  } else {
6419
7321
  if (this.opts.autoPipeline && this.pipeliner) {
6420
7322
  await this.pipeliner.del(k);
@@ -6461,7 +7363,7 @@ var CacheService = class _CacheService {
6461
7363
  async increment(cacheKey, ttlSeconds) {
6462
7364
  this._assertActive("increment");
6463
7365
  const k = this.nk(cacheKey);
6464
- if (this._redisDisabled) {
7366
+ if (this._redisDisabled || this.opts.l2WriteMode === "read-only") {
6465
7367
  if (!this._incrementFallbackWarned) {
6466
7368
  this._incrementFallbackWarned = true;
6467
7369
  this.logger.warn(
@@ -6476,6 +7378,15 @@ var CacheService = class _CacheService {
6476
7378
  entry.value++;
6477
7379
  return entry.value;
6478
7380
  }
7381
+ if (this._l1Counters.size >= 5e4 && !this._l1Counters.has(k)) {
7382
+ for (const [ck, cv] of this._l1Counters) {
7383
+ if (cv.expiresAt <= now) this._l1Counters.delete(ck);
7384
+ }
7385
+ if (this._l1Counters.size >= 5e4) {
7386
+ const oldest = this._l1Counters.keys().next().value;
7387
+ if (oldest !== void 0) this._l1Counters.delete(oldest);
7388
+ }
7389
+ }
6479
7390
  this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
6480
7391
  return 1;
6481
7392
  }
@@ -6508,6 +7419,7 @@ var CacheService = class _CacheService {
6508
7419
  this.counters.deletes++;
6509
7420
  const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
6510
7421
  if (k) {
7422
+ this._fenceInvalidation();
6511
7423
  const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6512
7424
  for (const liveKey of this.l1.liveKeys()) {
6513
7425
  if (liveKey.startsWith(pfx)) {
@@ -6520,8 +7432,9 @@ var CacheService = class _CacheService {
6520
7432
  this.inflight.delete(inflightKey);
6521
7433
  }
6522
7434
  }
6523
- this._addPatternTombstone(pfx);
7435
+ this._addPatternTombstone(k);
6524
7436
  this.l1.deletePattern(k);
7437
+ this._removePatternFromIndices(k);
6525
7438
  } else {
6526
7439
  this._globalEpoch++;
6527
7440
  this.inflight.clear();
@@ -6530,7 +7443,10 @@ var CacheService = class _CacheService {
6530
7443
  if (!this._diskDisabled) this.disk.clear();
6531
7444
  this._l1Counters.clear();
6532
7445
  this.tagIndex.clear();
7446
+ this.keyTags.clear();
6533
7447
  this.tagVersions.clear();
7448
+ this.dependencyIndex.clear();
7449
+ this.keyDependencies.clear();
6534
7450
  this._pendingDiskDeletes.clear();
6535
7451
  this._keyMutationEpochs.clear();
6536
7452
  }
@@ -6539,7 +7455,7 @@ var CacheService = class _CacheService {
6539
7455
  const client = await this.getRedis();
6540
7456
  const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
6541
7457
  const keys = await this._scanKeys(client, pattern);
6542
- if (keys.length > 0) await client.del(...keys);
7458
+ await this._deleteRedisKeys(client, keys);
6543
7459
  } catch (err) {
6544
7460
  this.logger.debug("clear: Redis unavailable", { error: err.message });
6545
7461
  }
@@ -6668,24 +7584,34 @@ var CacheService = class _CacheService {
6668
7584
  this._assertActive("scan");
6669
7585
  const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
6670
7586
  this.l1.scan((key, entry, pfx) => {
6671
- const value = entry.value !== void 0 ? entry.value : entry.data;
6672
- fn(key, value, pfx);
7587
+ fn(key, this._prepareReadValue(this.l1.resolveValue(entry)), pfx);
6673
7588
  }, prefixLen);
6674
7589
  }
6675
7590
  /**
6676
- * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
7591
+ * Extend the TTL of a key in L1 and Redis without fetching.
6677
7592
  * Returns `false` if the key is absent or already expired.
6678
7593
  *
6679
7594
  * @param newTtlSeconds - The new TTL from now, in seconds.
6680
7595
  */
6681
7596
  async touch(cacheKey, newTtlSeconds) {
6682
7597
  this._assertActive("touch");
7598
+ if (!Number.isFinite(newTtlSeconds) || newTtlSeconds <= 0) throw new Error("touch TTL must be finite and positive");
6683
7599
  const k = this.nk(cacheKey);
7600
+ const epoch = this._getKeyMutationEpoch(k);
6684
7601
  const hit = this.l1.touch(k, newTtlSeconds * 1e3);
6685
- if (hit && !this._redisDisabled) {
7602
+ const entry = this.l1.getEntry(k);
7603
+ if (hit) {
7604
+ const kt = this.keyTags.get(k);
7605
+ if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1e3;
7606
+ }
7607
+ if (hit && !this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6686
7608
  try {
6687
7609
  const client = await this.getRedis();
6688
- void client.expire(k, newTtlSeconds);
7610
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return hit;
7611
+ if (entry && typeof client.pttl === "function" && typeof client.eval === "function") {
7612
+ await client.eval(LUA_TOUCH_CACHE_ENTRY, 1, k, String(entry.setAt ?? 0), String(entry.expiresAt), String(Math.ceil(newTtlSeconds * 1e3)));
7613
+ } else await client.expire(k, Math.ceil(newTtlSeconds));
7614
+ this.cb.onSuccess();
6689
7615
  } catch {
6690
7616
  }
6691
7617
  }
@@ -6707,7 +7633,12 @@ var CacheService = class _CacheService {
6707
7633
  const now = Date.now();
6708
7634
  if (entry.expiresAt <= now) return null;
6709
7635
  if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
6710
- return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
7636
+ if (entry.tagVersions && Object.entries(entry.tagVersions).some(([tag, version]) => (this.tagVersions.get(tag)?.version ?? 0) > version)) return null;
7637
+ return this._prepareReadValue(entry.value !== void 0 ? entry.value : this.codec.decode(entry.data));
7638
+ }
7639
+ _prepareReadValue(val) {
7640
+ if (this.opts.frozen) deepFreeze(val);
7641
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6711
7642
  }
6712
7643
  /**
6713
7644
  * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
@@ -6720,59 +7651,36 @@ var CacheService = class _CacheService {
6720
7651
  async peek(cacheKey) {
6721
7652
  this._assertActive("peek");
6722
7653
  const k = this.nk(cacheKey);
7654
+ const epoch = this._getKeyMutationEpoch(k);
7655
+ this.counters.gets++;
6723
7656
  const l1Hit = this.l1.get(k);
6724
7657
  if (l1Hit !== null) {
6725
- this.counters.gets++;
6726
- this.counters.l1Hits++;
6727
- const val = l1Hit.value;
6728
- if (this.opts.frozen) deepFreeze(val);
6729
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6730
- }
6731
- if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
6732
- if (this._isTombstonedByPattern(k)) {
6733
- try {
6734
- this.disk.delete(k);
6735
- } catch {
6736
- }
6737
- } else if (this.watchdog.isDiskAllowed()) {
6738
- const diskStart = performance.now();
6739
- const diskHit = this.disk.load(k);
6740
- const diskElapsed = performance.now() - diskStart;
6741
- this.watchdog.recordDisk(diskElapsed);
6742
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6743
- if (diskHit !== null) {
6744
- const promoted = this.l1.importEntries(
6745
- [{ key: k, entry: diskHit }],
6746
- this.opts.forbiddenSnapshotPrefixes
6747
- );
6748
- if (promoted > 0) {
6749
- const l1Check = this.l1.get(k);
6750
- if (l1Check !== null) {
6751
- this.counters.gets++;
6752
- this.counters.diskHits++;
6753
- const val = l1Check.value;
6754
- if (this.opts.frozen) deepFreeze(val);
6755
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6756
- }
6757
- }
6758
- }
7658
+ if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
7659
+ this._deleteIfStale(k, l1Hit.setAt ?? 0);
7660
+ } else {
7661
+ this.counters.l1Hits++;
7662
+ return this._prepareReadValue(l1Hit.value);
6759
7663
  }
6760
7664
  }
6761
- if (!this._redisDisabled && !this.cb.isOpen) {
7665
+ const diskHit = await this._readDiskEntry(k, epoch);
7666
+ if (diskHit) {
7667
+ this.counters.diskHits++;
7668
+ return this._prepareReadValue(diskHit.value);
7669
+ }
7670
+ if (!this._redisDisabled) {
6762
7671
  try {
6763
7672
  const client = await this.getRedis();
6764
7673
  const redisStart = performance.now();
6765
- const raw = await client.get(k);
7674
+ const redisHit = await this._readRedisEntry(client, k);
6766
7675
  const redisElapsed = performance.now() - redisStart;
6767
7676
  this.watchdog.recordRedis(redisElapsed);
6768
- if (raw !== null) {
6769
- const parsed = await this._decryptAndDeserialize(raw);
6770
- this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
6771
- this.counters.gets++;
7677
+ this.cb.onSuccess();
7678
+ if (redisHit && !redisHit.stale) {
7679
+ const parsed = redisHit.value;
7680
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return null;
7681
+ if (!this._promoteRedisEntry(k, redisHit, 6e4, inferPriority(cacheKey))) return null;
6772
7682
  this.counters.l2Hits++;
6773
- this.cb.onSuccess();
6774
- if (this.opts.frozen) deepFreeze(parsed);
6775
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
7683
+ return this._prepareReadValue(parsed);
6776
7684
  }
6777
7685
  } catch (err) {
6778
7686
  this.cb.onFailure();
@@ -6792,6 +7700,8 @@ var CacheService = class _CacheService {
6792
7700
  */
6793
7701
  async mget(keys, fetchFn, ttl = 300, priority) {
6794
7702
  this._assertActive("mget");
7703
+ this.counters.gets += keys.length;
7704
+ const epochs = new Map(keys.map((key) => [this.nk(key), this._getKeyMutationEpoch(this.nk(key))]));
6795
7705
  const span = this._startSpan("tricache.mget");
6796
7706
  if (this.opts.tracer) {
6797
7707
  span.setAttribute("cache.batch.size", keys.length);
@@ -6800,12 +7710,20 @@ var CacheService = class _CacheService {
6800
7710
  const result = Array.from({ length: keys.length });
6801
7711
  const missIndexes = [];
6802
7712
  const missKeys = [];
7713
+ const now = Date.now();
6803
7714
  for (let i = 0; i < keys.length; i++) {
6804
7715
  const k = this.nk(keys[i]);
6805
7716
  const entry = this.l1.getEntry(k);
6806
- if (entry && entry.expiresAt > Date.now()) {
6807
- result[i] = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
6808
- this.counters.l1Hits++;
7717
+ if (entry && entry.expiresAt > now && (entry.staleAt === void 0 || entry.staleAt > now)) {
7718
+ if (await this._isGenerationalEntryStale(entry.tagVersions)) {
7719
+ this._deleteIfStale(k, entry.setAt ?? 0);
7720
+ missIndexes.push(i);
7721
+ missKeys.push(keys[i]);
7722
+ } else {
7723
+ const val = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
7724
+ result[i] = this._prepareReadValue(val);
7725
+ this.counters.l1Hits++;
7726
+ }
6809
7727
  } else {
6810
7728
  missIndexes.push(i);
6811
7729
  missKeys.push(keys[i]);
@@ -6825,30 +7743,24 @@ var CacheService = class _CacheService {
6825
7743
  try {
6826
7744
  const client = await this.getRedis();
6827
7745
  const nsKeys = missKeys.map((k) => this.nk(k));
6828
- const pipeline = client.multi();
6829
- for (const nk of nsKeys) pipeline.get(nk);
6830
- const redisStart = performance.now();
6831
- const raws = await pipeline.exec();
6832
- const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
6833
- this.watchdog.recordRedis(redisElapsed);
6834
- this.cb.onSuccess();
7746
+ const remoteEntries = await this._readRedisBatch(client, nsKeys);
6835
7747
  for (let j = 0; j < missKeys.length; j++) {
6836
- const raw = raws[j] ? raws[j][1] : null;
6837
7748
  const idx = missIndexes[j];
6838
- if (raw) {
6839
- const parsed = await this._decryptAndDeserialize(raw);
6840
- const k = nsKeys[j];
7749
+ const k = nsKeys[j];
7750
+ const entry = remoteEntries.get(k);
7751
+ if (entry && (entry.staleAt === void 0 || entry.staleAt > Date.now()) && !this._destroyed && this._getKeyMutationEpoch(k) === epochs.get(k)) {
6841
7752
  const p = priority ?? inferPriority(missKeys[j]);
6842
- this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
7753
+ const ttlVal = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
7754
+ if (!this._promoteRedisEntry(k, entry, this._jitterTtl(ttlVal * 1e3), p)) continue;
6843
7755
  this.counters.l2Hits++;
6844
7756
  l2HitCount++;
6845
- result[idx] = parsed;
7757
+ result[idx] = this._prepareReadValue(entry.value);
6846
7758
  missIndexes[j] = -1;
6847
7759
  missKeys[j] = "";
6848
7760
  }
6849
7761
  }
6850
7762
  const remainingIdx = missIndexes.filter((i) => i >= 0);
6851
- const remainingKeys = missKeys.filter((k) => k !== "");
7763
+ const remainingKeys = missKeys.filter((_key, index) => missIndexes[index] >= 0);
6852
7764
  missIndexes.length = 0;
6853
7765
  missKeys.length = 0;
6854
7766
  missIndexes.push(...remainingIdx);
@@ -6861,58 +7773,64 @@ var CacheService = class _CacheService {
6861
7773
  if (!this._diskDisabled && missKeys.length > 0) {
6862
7774
  for (let j = missKeys.length - 1; j >= 0; j--) {
6863
7775
  const k = this.nk(missKeys[j]);
6864
- if (this._pendingDiskDeletes.has(k)) continue;
6865
- if (this._isTombstonedByPattern(k)) {
6866
- try {
6867
- this.disk.delete(k);
6868
- } catch {
6869
- }
6870
- continue;
6871
- }
6872
- if (!this.watchdog.isDiskAllowed()) continue;
6873
- const diskStart = performance.now();
6874
- const diskHit = this.disk.load(k);
6875
- const diskElapsed = performance.now() - diskStart;
6876
- this.watchdog.recordDisk(diskElapsed);
6877
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6878
- if (diskHit !== null) {
6879
- const promoted = this.l1.importEntries(
6880
- [{ key: k, entry: diskHit }],
6881
- this.opts.forbiddenSnapshotPrefixes
6882
- );
6883
- if (promoted > 0) {
6884
- const l1Check = this.l1.get(k);
6885
- if (l1Check !== null) {
6886
- this.counters.diskHits++;
6887
- result[missIndexes[j]] = l1Check.value;
6888
- missIndexes.splice(j, 1);
6889
- missKeys.splice(j, 1);
6890
- }
6891
- }
7776
+ const diskHit = await this._readDiskEntry(k, epochs.get(k));
7777
+ if (diskHit && (diskHit.entry.staleAt === void 0 || diskHit.entry.staleAt > Date.now())) {
7778
+ this.counters.diskHits++;
7779
+ result[missIndexes[j]] = this._prepareReadValue(diskHit.value);
7780
+ missIndexes.splice(j, 1);
7781
+ missKeys.splice(j, 1);
6892
7782
  }
6893
7783
  }
6894
7784
  }
6895
7785
  if (missKeys.length > 0 && fetchFn) {
6896
- this.counters.fetches++;
6897
- const fetched = await fetchFn(missKeys);
6898
- const isMap = fetched instanceof Map;
6899
- const setPromises = [];
7786
+ const owned = /* @__PURE__ */ new Map();
7787
+ const waiting = [];
6900
7788
  for (let j = 0; j < missKeys.length; j++) {
6901
- const k = missKeys[j];
6902
- const v = isMap ? fetched.get(k) : fetched[k];
6903
- result[missIndexes[j]] = v;
6904
- if (v !== void 0 && v !== null) {
6905
- const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
6906
- setPromises.push(this.set(k, v, resolvedTtl, priority));
6907
- } else if (v == null && this.opts.notFoundTtl > 0) {
6908
- setPromises.push(this.set(k, null, this.opts.notFoundTtl, priority));
6909
- } else if (v === null) {
6910
- const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
6911
- setPromises.push(this.set(k, null, resolvedTtl, priority));
7789
+ const key = missKeys[j];
7790
+ const namespaced = this.nk(key);
7791
+ let promise = this.inflight.get(namespaced);
7792
+ if (!promise) {
7793
+ let resolve;
7794
+ let reject;
7795
+ promise = new Promise((yes, no) => {
7796
+ resolve = yes;
7797
+ reject = no;
7798
+ });
7799
+ owned.set(key, { promise, resolve, reject });
7800
+ this.inflight.set(namespaced, promise);
7801
+ } else {
7802
+ this.counters.stampedes++;
6912
7803
  }
7804
+ const index = missIndexes[j];
7805
+ waiting.push(promise.then((value) => {
7806
+ result[index] = this._prepareReadValue(value);
7807
+ }));
6913
7808
  }
6914
- if (setPromises.length > 0) {
6915
- await Promise.all(setPromises);
7809
+ const settled = Promise.allSettled(waiting);
7810
+ try {
7811
+ if (owned.size > 0) {
7812
+ this.counters.fetches++;
7813
+ const fetched = await fetchFn([...owned.keys()]);
7814
+ await Promise.all([...owned].map(async ([key, entry]) => {
7815
+ const value = fetched instanceof Map ? fetched.get(key) : Object.hasOwn(fetched, key) ? fetched[key] : void 0;
7816
+ if (!this._destroyed && this._getKeyMutationEpoch(this.nk(key)) === epochs.get(this.nk(key))) {
7817
+ const resolvedTtl = value == null && this.opts.notFoundTtl > 0 ? this.opts.notFoundTtl : typeof ttl === "function" ? ttl(key) : ttl;
7818
+ if (value !== void 0 || this.opts.notFoundTtl > 0) await this.set(key, value === void 0 && this.opts.notFoundTtl > 0 ? null : value, resolvedTtl, priority);
7819
+ }
7820
+ entry.resolve(value);
7821
+ }));
7822
+ }
7823
+ const outcomes = await settled;
7824
+ const failed = outcomes.find((outcome) => outcome.status === "rejected");
7825
+ if (failed?.status === "rejected") throw failed.reason;
7826
+ } catch (error) {
7827
+ for (const entry of owned.values()) entry.reject(error);
7828
+ throw error;
7829
+ } finally {
7830
+ for (const [key, entry] of owned) {
7831
+ const namespaced = this.nk(key);
7832
+ if (this.inflight.get(namespaced) === entry.promise) this.inflight.delete(namespaced);
7833
+ }
6916
7834
  }
6917
7835
  }
6918
7836
  if (this.opts.tracer) {
@@ -6965,7 +7883,7 @@ var CacheService = class _CacheService {
6965
7883
  try {
6966
7884
  await Promise.all(keys.map((key) => {
6967
7885
  const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
6968
- const hasOpts = tags?.length || dependsOn?.length;
7886
+ const hasOpts = tags !== void 0 || dependsOn !== void 0;
6969
7887
  return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
6970
7888
  }));
6971
7889
  } catch (err) {
@@ -7017,26 +7935,21 @@ var CacheService = class _CacheService {
7017
7935
  try {
7018
7936
  const client = await this.getRedis();
7019
7937
  const nsPattern = this.nk(pattern);
7020
- const matchedKeys = await this._scanKeys(client, nsPattern);
7938
+ const matchedKeys = (await this._scanKeys(client, nsPattern)).filter((key) => {
7939
+ const raw = this.unnk(key);
7940
+ return !raw.startsWith("_tag_:") && !raw.startsWith("tag_ver:") && !raw.startsWith("lock:") && key !== this.backplaneStreamKey;
7941
+ });
7021
7942
  if (matchedKeys.length === 0) {
7022
7943
  this.cb.onSuccess();
7023
7944
  return 0;
7024
7945
  }
7025
- const pl = client.pipeline();
7026
- for (const k of matchedKeys) pl.get(k);
7027
- const results = await pl.exec();
7028
- this.cb.onSuccess();
7946
+ const epochs = new Map(matchedKeys.map((key) => [key, this._getKeyMutationEpoch(key)]));
7947
+ const results = await this._readRedisBatch(client, matchedKeys);
7029
7948
  let loaded = 0;
7030
- for (let i = 0; i < matchedKeys.length; i++) {
7031
- const [err, raw] = results[i];
7032
- if (err || raw == null) continue;
7033
- try {
7034
- const parsed = await this._decryptAndDeserialize(raw);
7035
- const remainingMs = 10 * 60 * 1e3;
7036
- this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
7037
- loaded++;
7038
- } catch {
7039
- }
7949
+ for (const key of matchedKeys) {
7950
+ const entry = results.get(key);
7951
+ if (!entry || this._destroyed || this._getKeyMutationEpoch(key) !== epochs.get(key)) continue;
7952
+ if (this._promoteRedisEntry(key, entry, 10 * 60 * 1e3, opts?.priority ?? inferPriority(this.unnk(key))) && this.l1.has(key)) loaded++;
7040
7953
  }
7041
7954
  this.logger.info("warmFromL2 complete", {
7042
7955
  pattern,
@@ -7109,6 +8022,139 @@ var CacheService = class _CacheService {
7109
8022
  }
7110
8023
  return matched;
7111
8024
  }
8025
+ async _publishTagInvalidation(op, key, tagVersion) {
8026
+ if (this.opts.awaitInvalidationBackplane) {
8027
+ await this.publishInvalidation(op, key, tagVersion, false, true);
8028
+ } else {
8029
+ void this.publishInvalidation(op, key, tagVersion, false, true);
8030
+ }
8031
+ }
8032
+ _removeTagMembersLocal(keys) {
8033
+ const keyList = Array.isArray(keys) ? keys : Array.from(keys);
8034
+ for (const k of keyList) {
8035
+ this.l1.delete(k);
8036
+ this._bumpKeyMutation(k);
8037
+ this._removeKeyTags(k);
8038
+ this._removeKeyDependencies(k);
8039
+ this._invalidateDiskKey(k);
8040
+ }
8041
+ }
8042
+ /**
8043
+ * Executes invalidation for a single already-resolved concrete tag without
8044
+ * wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
8045
+ */
8046
+ async _invalidateConcreteTag(tag) {
8047
+ this._fenceInvalidation();
8048
+ if (this.opts.tagStrategy === "generational") {
8049
+ let newVer = 1;
8050
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
8051
+ try {
8052
+ const client = await this.getRedis();
8053
+ newVer = await client.incr(this.nk(`tag_ver:${tag}`));
8054
+ } catch (err) {
8055
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
8056
+ const current = this.tagVersions.get(tag)?.version ?? 0;
8057
+ newVer = current + 1;
8058
+ }
8059
+ } else {
8060
+ const current = this.tagVersions.get(tag)?.version ?? 0;
8061
+ newVer = current + 1;
8062
+ }
8063
+ this._setLocalTagVersion(tag, newVer, performance.now());
8064
+ await this._publishTagInvalidation("tag_incr", tag, newVer);
8065
+ return;
8066
+ }
8067
+ const tagKey = this.nk(`_tag_:${tag}`);
8068
+ const members = new Set(this.tagIndex.get(tagKey) ?? []);
8069
+ this.tagIndex.delete(tagKey);
8070
+ this._removeTagMembersLocal(members);
8071
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
8072
+ try {
8073
+ const client = await this.getRedis();
8074
+ const redisMembers = await client.smembers(tagKey);
8075
+ for (const key of redisMembers) members.add(key);
8076
+ this._removeTagMembersLocal(redisMembers);
8077
+ const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers, tagKey])];
8078
+ await this._deleteRedisKeys(client, toDelete);
8079
+ } catch (err) {
8080
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
8081
+ }
8082
+ }
8083
+ await Promise.all([...members].map((key) => this._publishTagInvalidation("del", key)));
8084
+ await this._publishTagInvalidation("tag_pattern_del", tag);
8085
+ }
8086
+ /**
8087
+ * Executes invalidation for an array of already-resolved concrete tags
8088
+ * without re-entering wildcard/cascade resolution or invalidateTag().
8089
+ */
8090
+ async _invalidateConcreteTags(tags) {
8091
+ if (tags.length === 0) return;
8092
+ if (tags.length === 1) {
8093
+ await this._invalidateConcreteTag(tags[0]);
8094
+ return;
8095
+ }
8096
+ this._fenceInvalidation();
8097
+ if (this.opts.tagStrategy === "generational") {
8098
+ const now = performance.now();
8099
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
8100
+ try {
8101
+ const client = await this.getRedis();
8102
+ const pl = client.pipeline();
8103
+ for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
8104
+ const results = await pl.exec();
8105
+ for (let i = 0; i < tags.length; i++) {
8106
+ const [err, newVer] = results[i] ?? [null, null];
8107
+ const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
8108
+ this._setLocalTagVersion(tags[i], ver, now);
8109
+ await this._publishTagInvalidation("tag_incr", tags[i], ver);
8110
+ }
8111
+ return;
8112
+ } catch (err) {
8113
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
8114
+ }
8115
+ }
8116
+ for (const tag of tags) {
8117
+ const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
8118
+ this._setLocalTagVersion(tag, ver, now);
8119
+ await this._publishTagInvalidation("tag_incr", tag, ver);
8120
+ }
8121
+ return;
8122
+ }
8123
+ const tagKeys = [];
8124
+ const allMembers = /* @__PURE__ */ new Set();
8125
+ for (const tag of tags) {
8126
+ const tagKey = this.nk(`_tag_:${tag}`);
8127
+ tagKeys.push(tagKey);
8128
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
8129
+ for (const k of members) allMembers.add(k);
8130
+ this.tagIndex.delete(tagKey);
8131
+ }
8132
+ this._removeTagMembersLocal(allMembers);
8133
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
8134
+ try {
8135
+ const client = await this.getRedis();
8136
+ const pl = client.pipeline();
8137
+ for (const tagKey of tagKeys) pl.smembers(tagKey);
8138
+ const smResults = await pl.exec();
8139
+ const toDelete = [...allMembers];
8140
+ for (const [err, redisMembers] of smResults) {
8141
+ if (!err && redisMembers) {
8142
+ for (const k of redisMembers) {
8143
+ if (!allMembers.has(k)) toDelete.push(k);
8144
+ allMembers.add(k);
8145
+ }
8146
+ }
8147
+ }
8148
+ const keysToRemove = [...toDelete, ...tagKeys];
8149
+ await this._deleteRedisKeys(client, keysToRemove);
8150
+ this._removeTagMembersLocal(allMembers);
8151
+ } catch (err) {
8152
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
8153
+ }
8154
+ }
8155
+ await Promise.all([...allMembers].map((key) => this._publishTagInvalidation("del", key)));
8156
+ for (const tag of tags) await this._publishTagInvalidation("tag_pattern_del", tag);
8157
+ }
7112
8158
  /**
7113
8159
  * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
7114
8160
  * Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
@@ -7144,68 +8190,13 @@ var CacheService = class _CacheService {
7144
8190
  const delim = this.opts.tagHierarchyDelimiter;
7145
8191
  const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
7146
8192
  if (matchedTags.size > 0) {
7147
- await this.invalidateTags(Array.from(matchedTags));
8193
+ await this._invalidateConcreteTags(Array.from(matchedTags));
7148
8194
  }
7149
8195
  const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
7150
- if (this.opts.awaitInvalidationBackplane) {
7151
- await this.publishInvalidation(op, broadcastPattern, void 0, false, true);
7152
- } else {
7153
- void this.publishInvalidation(op, broadcastPattern, void 0, false, true);
7154
- }
8196
+ await this._publishTagInvalidation(op, broadcastPattern);
7155
8197
  return;
7156
8198
  }
7157
- if (this.opts.tagStrategy === "generational") {
7158
- let newVer = 1;
7159
- if (!this._redisDisabled) {
7160
- try {
7161
- const client = await this.getRedis();
7162
- newVer = await client.incr(this.nk(`tag_ver:${tag}`));
7163
- } catch (err) {
7164
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7165
- const current = this.tagVersions.get(tag)?.version ?? 0;
7166
- newVer = current + 1;
7167
- }
7168
- } else {
7169
- const current = this.tagVersions.get(tag)?.version ?? 0;
7170
- newVer = current + 1;
7171
- }
7172
- this._setLocalTagVersion(tag, newVer, performance.now());
7173
- if (this.opts.awaitInvalidationBackplane) {
7174
- await this.publishInvalidation("tag_incr", tag, newVer, false, true);
7175
- } else {
7176
- void this.publishInvalidation("tag_incr", tag, newVer, false, true);
7177
- }
7178
- return;
7179
- }
7180
- const tagKey = this.nk(`_tag_:${tag}`);
7181
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
7182
- for (const k of members) {
7183
- this.l1.delete(k);
7184
- this._bumpKeyMutation(k);
7185
- this._pendingDiskDeletes.add(k);
7186
- setImmediate(() => {
7187
- try {
7188
- if (!this._diskDisabled) this.disk.delete(k);
7189
- } finally {
7190
- this._pendingDiskDeletes.delete(k);
7191
- }
7192
- });
7193
- }
7194
- this.tagIndex.delete(tagKey);
7195
- if (!this._redisDisabled) {
7196
- try {
7197
- const client = await this.getRedis();
7198
- const redisMembers = await client.smembers(tagKey);
7199
- const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
7200
- if (toDelete.length > 0) {
7201
- await client.del(...toDelete, tagKey);
7202
- } else {
7203
- await client.del(tagKey);
7204
- }
7205
- } catch (err) {
7206
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7207
- }
7208
- }
8199
+ await this._invalidateConcreteTag(tag);
7209
8200
  } catch (err) {
7210
8201
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
7211
8202
  span.recordException?.(err);
@@ -7232,96 +8223,28 @@ var CacheService = class _CacheService {
7232
8223
  const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
7233
8224
  if (hasWildcards || shouldCascade) {
7234
8225
  const allResolvedTags = /* @__PURE__ */ new Set();
8226
+ const broadcastPatterns = /* @__PURE__ */ new Set();
8227
+ const delim = this.opts.tagHierarchyDelimiter;
7235
8228
  for (const t of tags) {
7236
- if (isWildcardTag(t) || shouldCascade) {
8229
+ const tIsPattern = isWildcardTag(t);
8230
+ if (tIsPattern || shouldCascade) {
8231
+ broadcastPatterns.add(tIsPattern ? t : `${t}${delim}*`);
7237
8232
  const resolved = await this._resolveMatchingTags(t, shouldCascade);
7238
8233
  for (const rt of resolved) allResolvedTags.add(rt);
7239
8234
  } else {
7240
8235
  allResolvedTags.add(t);
7241
8236
  }
7242
8237
  }
7243
- if (allResolvedTags.size === 0) return;
7244
- tags = Array.from(allResolvedTags);
7245
- }
7246
- if (tags.length === 1) {
7247
- await this.invalidateTag(tags[0], opts);
7248
- return;
7249
- }
7250
- if (this.opts.tagStrategy === "generational") {
7251
- const now = performance.now();
7252
- if (!this._redisDisabled) {
7253
- try {
7254
- const client = await this.getRedis();
7255
- const pl = client.pipeline();
7256
- for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
7257
- const results = await pl.exec();
7258
- for (let i = 0; i < tags.length; i++) {
7259
- const [err, newVer] = results[i] ?? [null, null];
7260
- const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
7261
- this._setLocalTagVersion(tags[i], ver, now);
7262
- if (this.opts.awaitInvalidationBackplane) {
7263
- await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7264
- } else {
7265
- void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7266
- }
7267
- }
7268
- return;
7269
- } catch (err) {
7270
- this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7271
- }
8238
+ if (allResolvedTags.size > 0) {
8239
+ await this._invalidateConcreteTags(Array.from(allResolvedTags));
7272
8240
  }
7273
- for (const tag of tags) {
7274
- const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
7275
- this._setLocalTagVersion(tag, ver, now);
7276
- if (this.opts.awaitInvalidationBackplane) {
7277
- await this.publishInvalidation("tag_incr", tag, ver, false, true);
7278
- } else {
7279
- void this.publishInvalidation("tag_incr", tag, ver, false, true);
7280
- }
8241
+ const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
8242
+ for (const pattern of broadcastPatterns) {
8243
+ await this._publishTagInvalidation(op, pattern);
7281
8244
  }
7282
8245
  return;
7283
8246
  }
7284
- const tagKeys = [];
7285
- const allMembers = /* @__PURE__ */ new Set();
7286
- for (const tag of tags) {
7287
- const tagKey = this.nk(`_tag_:${tag}`);
7288
- tagKeys.push(tagKey);
7289
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
7290
- for (const k of members) allMembers.add(k);
7291
- this.tagIndex.delete(tagKey);
7292
- }
7293
- for (const k of allMembers) {
7294
- this.l1.delete(k);
7295
- this._bumpKeyMutation(k);
7296
- this._pendingDiskDeletes.add(k);
7297
- setImmediate(() => {
7298
- try {
7299
- if (!this._diskDisabled) this.disk.delete(k);
7300
- } finally {
7301
- this._pendingDiskDeletes.delete(k);
7302
- }
7303
- });
7304
- }
7305
- if (!this._redisDisabled) {
7306
- try {
7307
- const client = await this.getRedis();
7308
- const pl = client.pipeline();
7309
- for (const tagKey of tagKeys) pl.smembers(tagKey);
7310
- const smResults = await pl.exec();
7311
- const toDelete = [...allMembers];
7312
- for (const [err, redisMembers] of smResults) {
7313
- if (!err && redisMembers) {
7314
- for (const k of redisMembers) {
7315
- if (!allMembers.has(k)) toDelete.push(k);
7316
- }
7317
- }
7318
- }
7319
- const keysToRemove = [...toDelete, ...tagKeys];
7320
- if (keysToRemove.length > 0) await client.del(...keysToRemove);
7321
- } catch (err) {
7322
- this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7323
- }
7324
- }
8247
+ await this._invalidateConcreteTags(Array.from(new Set(tags)));
7325
8248
  }
7326
8249
  /**
7327
8250
  * Get the current generational tag version for a tag (synced with Redis when due).
@@ -7384,19 +8307,23 @@ var CacheService = class _CacheService {
7384
8307
  const diskLowSpace = !this._diskDisabled && this.disk.hostVolumeLowSpace;
7385
8308
  const circuitOpen = this.cb.isOpen;
7386
8309
  const latencyBypass = watchdogTel.bypassActive;
7387
- const degraded = circuitOpen || latencyBypass || diskPruning || diskLowSpace;
7388
- const healthy = this.opts.failReadinessOnDegraded ? !degraded : true;
8310
+ const backplaneUnavailable = this.opts.invalidationBackplane && !this._redisDisabled && !this._backplaneAvailable;
8311
+ const degraded = this._destroyed || circuitOpen || latencyBypass || diskPruning || diskLowSpace || backplaneUnavailable;
8312
+ const healthy = !this._destroyed && (this.opts.failReadinessOnDegraded ? !degraded : true);
7389
8313
  const reasons = [];
7390
8314
  if (circuitOpen) reasons.push("redis_circuit_breaker_open");
7391
8315
  if (latencyBypass) reasons.push(`disk_latency_bypass_stage_${watchdogTel.bypassStage}`);
7392
8316
  if (diskPruning) reasons.push("disk_quota_watermark_pruning_active");
7393
8317
  if (diskLowSpace) reasons.push("disk_host_volume_low_space");
8318
+ if (backplaneUnavailable) reasons.push("invalidation_backplane_unavailable");
8319
+ if (this._destroyed) reasons.push("cache_destroyed");
7394
8320
  return {
7395
8321
  healthy,
7396
8322
  degraded,
7397
8323
  reasons,
7398
8324
  details: {
7399
- redisConnected: !circuitOpen && !this._redisDisabled,
8325
+ redisConnected: !this._destroyed && !circuitOpen && !!this.redis && (this.redis.status === "ready" || this.redis.isOpen === true),
8326
+ backplaneReady: this._backplaneAvailable,
7400
8327
  circuitBreakerState: this.cb.currentState,
7401
8328
  diskPruningActive: diskPruning,
7402
8329
  diskHostVolumeLowSpace: diskLowSpace,
@@ -7418,23 +8345,28 @@ var CacheService = class _CacheService {
7418
8345
  */
7419
8346
  async drainToL2() {
7420
8347
  this._assertActive("drainToL2");
7421
- if (this._redisDisabled) return 0;
8348
+ if (this._redisDisabled || this.opts.l2WriteMode === "read-only") return 0;
7422
8349
  try {
7423
- const client = await this.getRedis();
7424
8350
  const entries = this.l1.exportEntries([]);
7425
- const now = Date.now();
7426
8351
  if (entries.length === 0) return 0;
7427
- const pl = client.pipeline();
7428
- for (const { key, entry } of entries) {
7429
- const remainingMs = entry.expiresAt - now;
7430
- if (remainingMs <= 0) continue;
7431
- const ttlSecs = Math.max(1, Math.ceil(remainingMs / 1e3));
7432
- const s = JSON.stringify(entry.value);
7433
- const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
7434
- pl.setex(key, ttlSecs, stored);
7435
- }
7436
- await pl.exec();
7437
- return entries.length;
8352
+ let written = 0;
8353
+ await Promise.all(entries.map(async ({ key, entry }) => {
8354
+ const epoch = this._getKeyMutationEpoch(key);
8355
+ if (entry.expiresAt <= Date.now()) return;
8356
+ await this._writeRedisEntry(
8357
+ key,
8358
+ this.l1.resolveValue(entry),
8359
+ entry.expiresAt,
8360
+ entry.setAt ?? Date.now(),
8361
+ entry.tagVersions,
8362
+ entry.staleAt,
8363
+ entry.tags,
8364
+ entry.dependsOn,
8365
+ () => this._getKeyMutationEpoch(key) === epoch
8366
+ );
8367
+ written++;
8368
+ }));
8369
+ return written;
7438
8370
  } catch (err) {
7439
8371
  this.logger.debug("drainToL2: Redis unavailable", { error: err.message });
7440
8372
  return 0;
@@ -7464,7 +8396,7 @@ var CacheService = class _CacheService {
7464
8396
  this._assertActive("setIfAbsent");
7465
8397
  const k = this.nk(cacheKey);
7466
8398
  if (this.l1.has(k)) return false;
7467
- if (!this._redisDisabled) {
8399
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7468
8400
  try {
7469
8401
  const client = await this.getRedis();
7470
8402
  const serialized = JSON.stringify(value);
@@ -7481,7 +8413,7 @@ var CacheService = class _CacheService {
7481
8413
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
7482
8414
  const p = priority ?? inferPriority(cacheKey);
7483
8415
  this._bumpKeyMutation(k);
7484
- this._pendingDiskDeletes.delete(k);
8416
+ this._invalidateDiskKey(k);
7485
8417
  this.l1.set(k, value, ttlMs, p);
7486
8418
  this.counters.sets++;
7487
8419
  return true;
@@ -7508,7 +8440,7 @@ var CacheService = class _CacheService {
7508
8440
  const token = import_crypto3.default.randomUUID();
7509
8441
  const deadline = Date.now() + acquireTimeout;
7510
8442
  let acquired = false;
7511
- if (!this._redisDisabled) {
8443
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7512
8444
  let client = null;
7513
8445
  try {
7514
8446
  client = await this.getRedis();
@@ -7603,7 +8535,9 @@ var CacheService = class _CacheService {
7603
8535
  const gDiskFiles = meter.createObservableGauge("tricache.disk.files", { description: "Current L1.5 disk file count" });
7604
8536
  const gDiskBytes = meter.createObservableGauge("tricache.disk.bytes", { description: "Current L1.5 disk size in bytes" });
7605
8537
  const gBloomFpr = meter.createObservableGauge("tricache.bloom.fpr", { description: "Bloom filter false-positive rate" });
7606
- meter.addBatchObservableCallback((observableResult) => {
8538
+ const observables = [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr];
8539
+ const callback = (observableResult) => {
8540
+ if (this._destroyed) return;
7607
8541
  const stats = this.stats();
7608
8542
  const l1 = stats.l1;
7609
8543
  const disk = stats.disk;
@@ -7616,7 +8550,9 @@ var CacheService = class _CacheService {
7616
8550
  observableResult.observe(gDiskFiles, disk.files, attrs);
7617
8551
  observableResult.observe(gDiskBytes, disk.sizeKB * 1024, attrs);
7618
8552
  observableResult.observe(gBloomFpr, fpr, attrs);
7619
- }, [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr]);
8553
+ };
8554
+ meter.addBatchObservableCallback(callback, observables);
8555
+ this._otelCleanup = () => meter.removeBatchObservableCallback?.(callback, observables);
7620
8556
  } catch (err) {
7621
8557
  this.logger.warn("Failed to initialize OpenTelemetry metrics meter", { error: err.message });
7622
8558
  }
@@ -7886,8 +8822,25 @@ var CacheService = class _CacheService {
7886
8822
  /** Close Redis connections and stop all background timers. */
7887
8823
  async destroy() {
7888
8824
  this._destroyed = true;
8825
+ this._fenceInvalidation();
8826
+ this._backplaneAvailable = false;
8827
+ this.l1.clear();
8828
+ try {
8829
+ this._otelCleanup?.();
8830
+ } catch {
8831
+ }
8832
+ this._otelCleanup = null;
8833
+ this.tagVersions.clear();
8834
+ for (const dispose of this._backplaneDisposers.splice(0)) dispose();
7889
8835
  this._pendingDiskDeletes.clear();
7890
8836
  this._keyMutationEpochs.clear();
8837
+ this.inflight.clear();
8838
+ this.revalidating.clear();
8839
+ this._l1Counters.clear();
8840
+ this.tagIndex.clear();
8841
+ this.keyTags.clear();
8842
+ this.dependencyIndex.clear();
8843
+ this.keyDependencies.clear();
7891
8844
  const g = globalThis;
7892
8845
  const key = _CacheService.globalKey(this.opts);
7893
8846
  if (g[key] === this) {
@@ -7908,6 +8861,12 @@ var CacheService = class _CacheService {
7908
8861
  this._workerPool = null;
7909
8862
  }
7910
8863
  if (this.subClient) {
8864
+ if (this.opts.redisSubClient) {
8865
+ try {
8866
+ await this.subClient.unsubscribe?.(this.backplaneChannel);
8867
+ } catch {
8868
+ }
8869
+ }
7911
8870
  if (!this.opts.redisSubClient) {
7912
8871
  try {
7913
8872
  this.subClient.disconnect();
@@ -7917,7 +8876,7 @@ var CacheService = class _CacheService {
7917
8876
  this.subClient = null;
7918
8877
  }
7919
8878
  if (this.streamClient) {
7920
- try {
8879
+ if (!this.opts.redisSubClient) try {
7921
8880
  this.streamClient.disconnect();
7922
8881
  } catch {
7923
8882
  }
@@ -7954,6 +8913,7 @@ var CacheService = class _CacheService {
7954
8913
  };
7955
8914
 
7956
8915
  // src/cli.ts
8916
+ var import_ioredis3 = require("ioredis");
7957
8917
  var import_meta2 = {};
7958
8918
  async function runCli(args = process.argv.slice(2)) {
7959
8919
  const options = {
@@ -7991,7 +8951,7 @@ async function runCli(args = process.argv.slice(2)) {
7991
8951
  return;
7992
8952
  }
7993
8953
  if (values.version || command === "version") {
7994
- let version = "1.0.0";
8954
+ let version = "1.0.2";
7995
8955
  try {
7996
8956
  const pkg = JSON.parse((0, import_node_fs3.readFileSync)(new URL("../package.json", import_meta2.url), "utf8"));
7997
8957
  if (pkg?.version) version = pkg.version;
@@ -8094,16 +9054,35 @@ Press "q" or Ctrl+C to exit
8094
9054
  return;
8095
9055
  }
8096
9056
  const redisStr = typeof values.redis === "string" ? values.redis : void 0;
8097
- const redisHost = redisStr ? redisStr.replace(/^redis:\/\//, "").split(":")[0] : void 0;
8098
- const redisPort = typeof values.port === "string" ? parseInt(values.port, 10) : redisStr && redisStr.includes(":") ? parseInt(redisStr.split(":")[1], 10) : 6379;
9057
+ let redisHost;
9058
+ let redisPort = 6379;
9059
+ let redisClient;
9060
+ if (redisStr) {
9061
+ try {
9062
+ const url = new URL(redisStr.includes("://") ? redisStr : `redis://${redisStr}`);
9063
+ if (url.protocol !== "redis:" && url.protocol !== "rediss:") throw new Error("Unsupported Redis URL scheme");
9064
+ redisPort = Number(typeof values.port === "string" ? values.port : url.port || 6379);
9065
+ if (!Number.isInteger(redisPort) || redisPort < 1 || redisPort > 65535) throw new Error("Invalid Redis port");
9066
+ url.port = String(redisPort);
9067
+ redisHost = url.hostname;
9068
+ redisClient = new import_ioredis3.Redis(url.toString(), { lazyConnect: true, commandTimeout: 2500, maxRetriesPerRequest: 1 });
9069
+ redisClient.on("error", () => {
9070
+ });
9071
+ } catch {
9072
+ console.error("Invalid Redis host, URL, or port");
9073
+ process.exitCode = 1;
9074
+ return;
9075
+ }
9076
+ }
8099
9077
  const namespace = typeof values.namespace === "string" ? values.namespace : void 0;
8100
9078
  const diskCacheDir = typeof values.disk === "string" ? values.disk : void 0;
8101
9079
  const cache = new CacheService({
8102
9080
  redisHost,
8103
9081
  redisPort,
9082
+ redisClient,
8104
9083
  namespace,
8105
9084
  diskCacheDir,
8106
- disableRedis: !redisHost
9085
+ disableRedis: !redisClient
8107
9086
  });
8108
9087
  try {
8109
9088
  if (command === "inspect") {
@@ -8155,6 +9134,7 @@ Press "q" or Ctrl+C to exit
8155
9134
  }
8156
9135
  } finally {
8157
9136
  await cache.destroy();
9137
+ redisClient?.disconnect();
8158
9138
  }
8159
9139
  }
8160
9140
  function printHelp() {