tricache 1.0.1 → 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 (96) hide show
  1. package/README.md +36 -28
  2. package/dist/{cache-service-CREOp7MM.d.ts → cache-service-B108FzER.d.ts} +36 -4
  3. package/dist/cache-service-CWI4jkS7.d.cts +963 -0
  4. package/dist/{cache-service-MG7PN6MX.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-3I5L7K6I.js → chunk-VNRDL5RA.js} +102 -140
  10. package/dist/{chunk-JYQFQJNJ.js → chunk-WYF7NOAT.js} +1443 -609
  11. package/dist/cli.cjs +1367 -625
  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 +1370 -624
  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 +227 -123
  23. package/dist/edge/index.d.cts +127 -0
  24. package/dist/edge/index.d.ts +3 -3
  25. package/dist/edge/index.js +201 -117
  26. package/dist/hono/index.cjs +1418 -644
  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-DSV2ve66.d.ts → hono-3rDMYVtY.d.ts} +16 -3
  31. package/dist/hono-C886ok3X.d.cts +391 -0
  32. package/dist/http/index.cjs +1514 -679
  33. package/dist/http/index.d.cts +103 -0
  34. package/dist/http/index.d.ts +13 -5
  35. package/dist/http/index.js +92 -43
  36. package/dist/index.cjs +1671 -790
  37. package/dist/index.d.cts +1006 -0
  38. package/dist/index.d.ts +39 -8
  39. package/dist/index.js +8 -8
  40. package/dist/murmur3-CMGw9PbV.d.cts +98 -0
  41. package/dist/nestjs/index.cjs +1454 -649
  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 +1512 -718
  46. package/dist/next/index.d.cts +232 -0
  47. package/dist/next/index.d.ts +33 -11
  48. package/dist/next/index.js +172 -99
  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-Dyip5wAl.d.ts → types-BA4pz1A0.d.cts} +24 -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 +106 -27
  61. package/src/cache-service.ts +802 -502
  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 +145 -97
  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 +62 -17
  74. package/src/http/fastify.ts +35 -21
  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 +131 -53
  84. package/src/next/index.ts +1 -0
  85. package/src/next/types.ts +21 -0
  86. package/src/prisma/index.ts +12 -1
  87. package/src/smart-memory-cache.ts +63 -26
  88. package/src/types.ts +25 -2
  89. package/src/utils/cgroup.ts +12 -0
  90. package/src/utils/deadline.ts +14 -0
  91. package/src/utils/diagnostics.ts +27 -0
  92. package/src/utils/redis-slot.ts +13 -0
  93. package/src/wasm/bloom-filter-wasm.ts +9 -4
  94. package/src/worker-pool.ts +17 -8
  95. package/src/wtiny-lfu.ts +20 -6
  96. 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, setAt) {
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) {
@@ -1465,10 +1521,12 @@ var SmartMemoryCache = class {
1465
1521
  ttlMs,
1466
1522
  delta,
1467
1523
  setAt: setAt ?? now2,
1468
- tagVersions
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: 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
2552
  }
2406
- let match;
2407
- for (const f of files) {
2408
- if ((f === hash || f.startsWith(hash + "_")) && (!match || f > match)) match = f;
2409
- }
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;
@@ -4253,6 +4658,7 @@ var CacheService = class _CacheService {
4253
4658
  keyTags = /* @__PURE__ */ new Map();
4254
4659
  /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
4255
4660
  tagVersions = /* @__PURE__ */ new Map();
4661
+ _tagRefreshEpoch = 0;
4256
4662
  /**
4257
4663
  * Dependency index: source glob pattern → Set of namespaced dependent keys.
4258
4664
  * When an exact-key delete matches a registered pattern, all dependents are cascaded.
@@ -4283,9 +4689,17 @@ var CacheService = class _CacheService {
4283
4689
  subClient = null;
4284
4690
  streamClient = null;
4285
4691
  _lastStreamId = "$";
4692
+ _restoredSnapshot = false;
4693
+ _backplaneAvailable = false;
4694
+ _otelCleanup = null;
4695
+ _streamRecovering = false;
4696
+ _backplaneDisposers = [];
4286
4697
  _destroyed = false;
4287
4698
  _pendingDiskDeletes = /* @__PURE__ */ new Set();
4288
4699
  _globalEpoch = 0;
4700
+ _pendingSpillCount = 0;
4701
+ _suppressSpills = false;
4702
+ _diskCleanupScheduled = false;
4289
4703
  _keyMutationEpochs = /* @__PURE__ */ new Map();
4290
4704
  /**
4291
4705
  * Pattern tombstones for disk tier.
@@ -4294,20 +4708,24 @@ var CacheService = class _CacheService {
4294
4708
  * pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
4295
4709
  */
4296
4710
  _patternTombstones = [];
4297
- _addPatternTombstone(prefix) {
4711
+ _diskInvalidatedBefore = 0;
4712
+ _addPatternTombstone(pattern) {
4298
4713
  const now = Date.now();
4299
4714
  while (this._patternTombstones.length > 0 && now - this._patternTombstones[0].createdAt > 36e5) {
4300
- this._patternTombstones.shift();
4715
+ const forgotten = this._patternTombstones.shift();
4716
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
4301
4717
  }
4302
4718
  if (this._patternTombstones.length >= 2e3) {
4303
- this._patternTombstones.shift();
4719
+ const forgotten = this._patternTombstones.shift();
4720
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
4304
4721
  }
4305
- this._patternTombstones.push({ prefix, createdAt: now });
4722
+ this._patternTombstones.push({ pattern, createdAt: now });
4306
4723
  }
4307
- _isTombstonedByPattern(namespacedKey) {
4724
+ _isTombstonedByPattern(namespacedKey, setAt = 0) {
4725
+ if (this._diskInvalidatedBefore > 0 && setAt <= this._diskInvalidatedBefore) return true;
4308
4726
  if (this._patternTombstones.length === 0) return false;
4309
4727
  for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
4310
- if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
4728
+ if (setAt <= this._patternTombstones[i].createdAt && this._matchesGlob(namespacedKey, this._patternTombstones[i].pattern)) {
4311
4729
  return true;
4312
4730
  }
4313
4731
  }
@@ -4322,13 +4740,86 @@ var CacheService = class _CacheService {
4322
4740
  const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
4323
4741
  this._keyMutationEpochs.set(namespacedKey, next);
4324
4742
  if (this._keyMutationEpochs.size > 5e4) {
4325
- const oldest = this._keyMutationEpochs.keys().next().value;
4326
- if (oldest !== void 0) this._keyMutationEpochs.delete(oldest);
4743
+ this._globalEpoch++;
4744
+ this._keyMutationEpochs.clear();
4745
+ this._keyMutationEpochs.set(namespacedKey, next);
4327
4746
  }
4328
4747
  return next;
4329
4748
  }
4330
4749
  _getKeyMutationEpoch(namespacedKey) {
4331
- 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);
4332
4823
  }
4333
4824
  _removeKeyTags(namespacedKey) {
4334
4825
  const entry = this.keyTags.get(namespacedKey);
@@ -4362,21 +4853,21 @@ var CacheService = class _CacheService {
4362
4853
  }
4363
4854
  }
4364
4855
  _handleL1Eviction(namespacedKey, reason) {
4365
- const spilledToDisk = !this._diskDisabled && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
4856
+ const spilledToDisk = !this._diskDisabled && !this._suppressSpills && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
4366
4857
  if (!spilledToDisk) {
4367
4858
  this._removeKeyTags(namespacedKey);
4368
4859
  this._removeKeyDependencies(namespacedKey);
4369
4860
  }
4370
4861
  }
4371
- _removePrefixFromIndices(prefix) {
4862
+ _removePatternFromIndices(pattern) {
4372
4863
  for (const k of Array.from(this.keyTags.keys())) {
4373
- if (k.startsWith(prefix)) this._removeKeyTags(k);
4864
+ if (this._matchesGlob(k, pattern)) this._removeKeyTags(k);
4374
4865
  }
4375
4866
  for (const k of Array.from(this.keyDependencies.keys())) {
4376
- if (k.startsWith(prefix)) this._removeKeyDependencies(k);
4867
+ if (this._matchesGlob(k, pattern)) this._removeKeyDependencies(k);
4377
4868
  }
4378
4869
  for (const k of Array.from(this._l1Counters.keys())) {
4379
- if (k.startsWith(prefix)) this._l1Counters.delete(k);
4870
+ if (this._matchesGlob(k, pattern)) this._l1Counters.delete(k);
4380
4871
  }
4381
4872
  }
4382
4873
  _sweepExpiredMetadata() {
@@ -4394,10 +4885,16 @@ var CacheService = class _CacheService {
4394
4885
  _runOomCheck() {
4395
4886
  const heap = import_node_v82.default.getHeapStatistics();
4396
4887
  const heapUsed = heap.used_heap_size / heap.heap_size_limit;
4397
- const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? process.memoryUsage().rss / this._cgroupMemoryLimit : 0;
4888
+ const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? (readCgroupMemoryUsage() ?? process.memoryUsage().rss) / this._cgroupMemoryLimit : 0;
4398
4889
  const used = Math.max(heapUsed, cgroupUsed);
4399
4890
  if (used >= this.opts.oomHeapThreshold) {
4400
- const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
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
+ }
4401
4898
  this.counters.oomEvictions++;
4402
4899
  this.counters.oomLastAt = Date.now();
4403
4900
  this.logger.warn("tricache OOM guard: emergency L1 eviction", {
@@ -4633,9 +5130,13 @@ var CacheService = class _CacheService {
4633
5130
  admissionPolicy: this.opts.l1AdmissionPolicy,
4634
5131
  codec: this.codec,
4635
5132
  diskSpill: (key, entry) => {
4636
- 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++;
4637
5137
  setImmediate(() => {
4638
- void this.disk.save(key, entry);
5138
+ this._pendingSpillCount--;
5139
+ if (!this._destroyed && this._getKeyMutationEpoch(key) === epoch) void this.disk.save(key, entry);
4639
5140
  });
4640
5141
  },
4641
5142
  onEviction: (key, reason) => {
@@ -4714,7 +5215,7 @@ var CacheService = class _CacheService {
4714
5215
  this.instanceId = import_crypto3.default.randomBytes(8).toString("hex");
4715
5216
  this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
4716
5217
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
4717
- 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 }));
4718
5219
  const startupPromises = [];
4719
5220
  if (this.opts.compression === "zstd") {
4720
5221
  startupPromises.push(initZstd().then(() => void 0));
@@ -4725,9 +5226,8 @@ var CacheService = class _CacheService {
4725
5226
  if (this.opts.warmKeys) {
4726
5227
  startupPromises.push(this.warmFromL2(this.opts.warmKeys).then(() => void 0));
4727
5228
  }
4728
- if (startupPromises.length > 0) {
4729
- this._readyPromise = Promise.all(startupPromises).then(() => void 0);
4730
- }
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);
4731
5231
  if (this.opts.meter) {
4732
5232
  this._initOtelMetrics(this.opts.meter);
4733
5233
  const otel = this._otelMetrics;
@@ -4740,7 +5240,10 @@ var CacheService = class _CacheService {
4740
5240
  if (typeof prop === "string" && typeof value === "number" && typeof oldVal === "number") {
4741
5241
  const diff = value - oldVal;
4742
5242
  if (diff > 0 && otel[prop]) {
4743
- otel[prop].add(diff, nsAttr);
5243
+ try {
5244
+ otel[prop].add(diff, nsAttr);
5245
+ } catch {
5246
+ }
4744
5247
  }
4745
5248
  }
4746
5249
  return ok;
@@ -4832,7 +5335,7 @@ var CacheService = class _CacheService {
4832
5335
  return g[key];
4833
5336
  }
4834
5337
  const existing = g[key];
4835
- const diff = _CacheService.optionsDiff(options ?? {}, existing.options);
5338
+ const diff = _CacheService.optionsDiff(options ?? {}, existing.opts);
4836
5339
  if (diff.length > 0) {
4837
5340
  existing.bumpSingletonDivergence();
4838
5341
  const msg = `tricache: singleton already initialised for namespace '${existing.options.namespace || "(default)"}' \u2014 ignoring divergent options: ${diff.join(", ")}`;
@@ -4866,7 +5369,13 @@ var CacheService = class _CacheService {
4866
5369
  "instanceName",
4867
5370
  "invalidationBackplane",
4868
5371
  "awaitInvalidationBackplane",
4869
- "lockFailClosed"
5372
+ "lockFailClosed",
5373
+ "tagStrategy",
5374
+ "cloneStrategy",
5375
+ "compression",
5376
+ "backplaneMode",
5377
+ "redisProtocol",
5378
+ "failClosed"
4870
5379
  ];
4871
5380
  /** Returns the names of options that differ between `a` and the live `b`. */
4872
5381
  static optionsDiff(a, b) {
@@ -4884,12 +5393,12 @@ var CacheService = class _CacheService {
4884
5393
  bumpSingletonDivergence() {
4885
5394
  this.counters.singletonDivergences++;
4886
5395
  }
4887
- /** Read-only view of the options the singleton was constructed with. */
5396
+ /** Sanitized diagnostic view; retain the original options/adapters to reuse configuration. */
4888
5397
  get options() {
4889
5398
  const o = this.opts;
4890
5399
  return {
4891
5400
  namespace: o.namespace,
4892
- 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) },
4893
5402
  l1MaxBytes: o.l1MaxBytes,
4894
5403
  l1MaxEntries: o.l1MaxEntries,
4895
5404
  redisHost: o.redisHost,
@@ -4910,8 +5419,8 @@ var CacheService = class _CacheService {
4910
5419
  awaitInvalidationBackplane: o.awaitInvalidationBackplane,
4911
5420
  lockFailClosed: o.lockFailClosed,
4912
5421
  strictSingleton: o.strictSingleton,
4913
- remoteSnapshot: o.remoteSnapshot,
4914
- crossRegion: o.crossRegion
5422
+ remoteSnapshot: redactDiagnostics(o.remoteSnapshot),
5423
+ crossRegion: redactDiagnostics(o.crossRegion)
4915
5424
  };
4916
5425
  }
4917
5426
  /**
@@ -4994,21 +5503,26 @@ var CacheService = class _CacheService {
4994
5503
  if (this.opts.redisClient && typeof this.opts.redisClient.duplicate === "function") {
4995
5504
  return this.opts.redisClient.duplicate();
4996
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
+ }
4997
5509
  if (this.opts.redisClusterNodes?.length) {
4998
- return new import_ioredis.Cluster(this.opts.redisClusterNodes, {
5510
+ return new import_ioredis2.Cluster(this.opts.redisClusterNodes, {
4999
5511
  redisOptions: {
5000
5512
  tls: this.opts.redisTls ? {} : void 0,
5001
5513
  connectTimeout: 1e4,
5514
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
5002
5515
  maxRetriesPerRequest: null,
5003
5516
  ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
5004
5517
  }
5005
5518
  });
5006
5519
  } else if (this.opts.redisSentinel) {
5007
- return new import_ioredis.Redis({
5520
+ return new import_ioredis2.Redis({
5008
5521
  sentinels: this.opts.redisSentinel.sentinels,
5009
5522
  name: this.opts.redisSentinel.name,
5010
5523
  tls: this.opts.redisTls ? {} : void 0,
5011
5524
  connectTimeout: 1e4,
5525
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
5012
5526
  lazyConnect: true,
5013
5527
  maxRetriesPerRequest: null,
5014
5528
  enableAutoPipelining: false,
@@ -5016,11 +5530,12 @@ var CacheService = class _CacheService {
5016
5530
  ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
5017
5531
  });
5018
5532
  } else {
5019
- return new import_ioredis.Redis({
5533
+ return new import_ioredis2.Redis({
5020
5534
  host: this.opts.redisHost,
5021
5535
  port: this.opts.redisPort,
5022
5536
  tls: this.opts.redisTls ? {} : void 0,
5023
5537
  connectTimeout: 1e4,
5538
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
5024
5539
  lazyConnect: true,
5025
5540
  maxRetriesPerRequest: null,
5026
5541
  enableAutoPipelining: false,
@@ -5030,26 +5545,32 @@ var CacheService = class _CacheService {
5030
5545
  });
5031
5546
  }
5032
5547
  }
5033
- initBackplane() {
5548
+ _listenBackplane(client, event, listener) {
5549
+ client.on?.(event, listener);
5550
+ this._backplaneDisposers.push(() => client.removeListener?.(event, listener));
5551
+ }
5552
+ async initBackplane() {
5034
5553
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
5035
5554
  if (this.opts.backplaneMode === "stream") {
5036
5555
  if (this.streamClient) return;
5037
- void this._startStreamConsumer();
5556
+ await this._startStreamConsumer();
5038
5557
  return;
5039
5558
  }
5040
5559
  if (this.subClient) return;
5041
5560
  const sub = this.createDedicatedRedisClient();
5042
- sub.on("error", (e) => {
5561
+ this.subClient = sub;
5562
+ this._listenBackplane(sub, "error", (e) => {
5043
5563
  this._checkAndLogResp3Hint(e);
5044
5564
  this.logger.debug("Backplane subscriber error", { error: e.message });
5045
5565
  });
5046
- sub.on("close", () => {
5566
+ this._listenBackplane(sub, "close", () => {
5567
+ this._backplaneAvailable = false;
5047
5568
  if (this._subDisconnectedAt === null) {
5048
5569
  this._subDisconnectedAt = Date.now();
5049
5570
  this.logger.debug("Backplane: subscriber disconnected", { at: this._subDisconnectedAt });
5050
5571
  }
5051
5572
  });
5052
- sub.on("ready", () => {
5573
+ this._listenBackplane(sub, "ready", () => {
5053
5574
  if (this._subDisconnectedAt !== null && this.opts.backplaneMaxStalenessMs > 0) {
5054
5575
  const gapMs = Date.now() - this._subDisconnectedAt;
5055
5576
  if (gapMs > this.opts.backplaneMaxStalenessMs) {
@@ -5062,52 +5583,119 @@ var CacheService = class _CacheService {
5062
5583
  }
5063
5584
  this._subDisconnectedAt = null;
5064
5585
  }
5586
+ if (!this._destroyed) this._backplaneAvailable = true;
5065
5587
  });
5066
5588
  const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
5067
5589
  if (isClusterSharded) {
5068
- sub.on("smessage", (_channel, message) => {
5590
+ this._listenBackplane(sub, "smessage", (_channel, message) => {
5069
5591
  this._handleBackplaneMessage(message);
5070
5592
  });
5071
- 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", {
5072
5595
  channel: this.backplaneChannel,
5073
5596
  instanceId: this.instanceId
5074
- })).catch((err) => this.logger.warn("Backplane: sharded subscribe failed", {
5075
- error: err.message
5076
5597
  }));
5077
5598
  } else {
5078
- sub.on("message", (_channel, message) => {
5599
+ this._listenBackplane(sub, "message", (_channel, message) => {
5079
5600
  this._handleBackplaneMessage(message);
5080
5601
  });
5081
- 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", {
5082
5605
  channel: this.backplaneChannel,
5083
5606
  instanceId: this.instanceId
5084
- })).catch((err) => this.logger.warn("Backplane: subscribe failed", {
5085
- error: err.message
5086
5607
  }));
5087
5608
  }
5088
- 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";
5089
5623
  }
5090
5624
  async _startStreamConsumer() {
5625
+ this._streamRecovering ||= this._lastStreamId !== "$" && this._lastStreamId !== "0-0";
5091
5626
  const sub = this.streamClient ?? this.createDedicatedRedisClient();
5092
5627
  this.streamClient = sub;
5628
+ if (typeof sub.xread !== "function") throw new Error("backplaneMode: stream requires a driver supporting XREAD");
5093
5629
  if (typeof sub.on === "function") {
5094
- sub.on("error", (e) => this.logger.debug("Backplane stream consumer error", { error: e.message }));
5095
- 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;
5096
5634
  if (this._subDisconnectedAt === null) {
5097
5635
  this._subDisconnectedAt = Date.now();
5098
5636
  this.logger.debug("Backplane stream: consumer disconnected", { at: this._subDisconnectedAt });
5099
5637
  }
5100
5638
  });
5101
- sub.on("ready", () => {
5639
+ this._listenBackplane(sub, "ready", () => {
5102
5640
  if (this._subDisconnectedAt !== null) {
5103
5641
  this.logger.debug("Backplane stream: consumer reconnected, resuming stream read", { lastId: this._lastStreamId });
5104
5642
  this._subDisconnectedAt = null;
5105
5643
  }
5106
5644
  });
5107
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
+ }
5108
5693
  const runLoop = async () => {
5109
5694
  while (!this._destroyed && !this._redisDisabled) {
5110
5695
  try {
5696
+ if (!initialized) await initialize();
5697
+ if (this._destroyed) break;
5698
+ await checkGap();
5111
5699
  const res = await sub.xread(
5112
5700
  "BLOCK",
5113
5701
  this.opts.backplaneStreamBlockMs,
@@ -5116,19 +5704,10 @@ var CacheService = class _CacheService {
5116
5704
  this._lastStreamId
5117
5705
  );
5118
5706
  if (this._destroyed) break;
5707
+ this._backplaneAvailable = true;
5119
5708
  if (res && res.length > 0) {
5120
- for (const [, entries] of res) {
5121
- if (entries.length > 0) {
5122
- if (this._lastStreamId !== "$") {
5123
- this.counters.streamReplays++;
5124
- }
5125
- for (const [id, fields] of entries) {
5126
- this._lastStreamId = id;
5127
- this.counters.streamEntriesReceived++;
5128
- this._processStreamEntry(fields);
5129
- }
5130
- }
5131
- }
5709
+ apply(res);
5710
+ this._backplaneAvailable = true;
5132
5711
  } else {
5133
5712
  await new Promise((resolve) => setTimeout(resolve, 10));
5134
5713
  }
@@ -5136,10 +5715,9 @@ var CacheService = class _CacheService {
5136
5715
  if (this._destroyed) break;
5137
5716
  const msg = err.message ?? "";
5138
5717
  if (msg.includes("NOGROUP") || msg.includes("smaller than") || msg.includes("trimmed")) {
5139
- this.counters.streamGaps++;
5140
- this.l1.clear();
5141
- this._lastStreamId = "$";
5718
+ this._resetAfterStreamGap();
5142
5719
  }
5720
+ this._backplaneAvailable = false;
5143
5721
  await new Promise((resolve) => setTimeout(resolve, 200));
5144
5722
  }
5145
5723
  }
@@ -5168,7 +5746,7 @@ var CacheService = class _CacheService {
5168
5746
  else if (f === "tagVersion") tagVersionRaw = v;
5169
5747
  }
5170
5748
  const validOp = op === "del" || op === "del-glob" || op === "tag_incr" || op === "tag_pattern_incr" || op === "tag_pattern_del";
5171
- if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
5749
+ if (!validOp || typeof key !== "string" || !key || typeof src !== "string" || !src || (op === "del" || op === "del-glob") && this._namespace && !key.startsWith(`${this._namespace}:`)) {
5172
5750
  this.logger.warn("Backplane: rejected invalid stream entry", {
5173
5751
  op: String(op).slice(0, 40),
5174
5752
  key: typeof key === "string" ? key.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(key)
@@ -5177,8 +5755,8 @@ var CacheService = class _CacheService {
5177
5755
  }
5178
5756
  let tagVersion;
5179
5757
  if (tagVersionRaw !== void 0) {
5180
- const parsed = parseInt(tagVersionRaw, 10);
5181
- if (!Number.isFinite(parsed)) {
5758
+ const parsed = Number(tagVersionRaw);
5759
+ if (!Number.isSafeInteger(parsed) || parsed < 0) {
5182
5760
  this.logger.warn("Backplane: rejected stream entry with non-numeric tagVersion", { key });
5183
5761
  return;
5184
5762
  }
@@ -5196,16 +5774,10 @@ var CacheService = class _CacheService {
5196
5774
  this.l1.delete(key);
5197
5775
  this._bumpKeyMutation(key);
5198
5776
  this.inflight.delete(key);
5199
- this._pendingDiskDeletes.add(key);
5200
- setImmediate(() => {
5201
- try {
5202
- if (!this._diskDisabled) this.disk.delete(key);
5203
- } finally {
5204
- this._pendingDiskDeletes.delete(key);
5205
- }
5206
- });
5777
+ this._invalidateDiskKey(key);
5207
5778
  this._cascadeDependencies(key);
5208
5779
  } else if (op === "del-glob") {
5780
+ this._fenceInvalidation();
5209
5781
  this.l1.deletePattern(key);
5210
5782
  const pfx = key.endsWith("*") ? key.slice(0, -1) : key;
5211
5783
  for (const liveKey of this.l1.liveKeys()) {
@@ -5219,12 +5791,22 @@ var CacheService = class _CacheService {
5219
5791
  this.inflight.delete(inflightKey);
5220
5792
  }
5221
5793
  }
5222
- 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
+ }
5223
5803
  } else if (op === "tag_incr") {
5804
+ this._fenceInvalidation();
5224
5805
  const tag = key;
5225
5806
  const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
5226
5807
  this._setLocalTagVersion(tag, ver, performance.now());
5227
5808
  } else if (op === "tag_pattern_incr") {
5809
+ this._fenceInvalidation();
5228
5810
  const pattern = key;
5229
5811
  const now = performance.now();
5230
5812
  for (const [tag, info] of this.tagVersions) {
@@ -5244,6 +5826,7 @@ var CacheService = class _CacheService {
5244
5826
  }
5245
5827
  }, 0);
5246
5828
  } else if (op === "tag_pattern_del") {
5829
+ this._fenceInvalidation();
5247
5830
  const pattern = key;
5248
5831
  const matchedTagKeys = [];
5249
5832
  const prefix = this.nk("_tag_:");
@@ -5254,14 +5837,7 @@ var CacheService = class _CacheService {
5254
5837
  for (const k of members) {
5255
5838
  this.l1.delete(k);
5256
5839
  this._bumpKeyMutation(k);
5257
- this._pendingDiskDeletes.add(k);
5258
- setImmediate(() => {
5259
- try {
5260
- if (!this._diskDisabled) this.disk.delete(k);
5261
- } finally {
5262
- this._pendingDiskDeletes.delete(k);
5263
- }
5264
- });
5840
+ this._invalidateDiskKey(k);
5265
5841
  }
5266
5842
  }
5267
5843
  }
@@ -5292,6 +5868,7 @@ var CacheService = class _CacheService {
5292
5868
  }
5293
5869
  }
5294
5870
  async publishInvalidation(op, key, tagVersion, isCrossRegionRelay = false, isExplicitInvalidation = false) {
5871
+ if (this.opts.l2WriteMode === "read-only") return;
5295
5872
  if (!isCrossRegionRelay && this.opts.crossRegion) {
5296
5873
  const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
5297
5874
  if (shouldBroadcast) {
@@ -5374,13 +5951,13 @@ var CacheService = class _CacheService {
5374
5951
  timestamp: Date.now(),
5375
5952
  namespace: this._namespace || void 0
5376
5953
  };
5377
- this.counters.crossRegionSent++;
5378
5954
  await cr.relay.broadcast(event);
5955
+ this.counters.crossRegionSent++;
5379
5956
  this.logger.debug("Cross-region invalidation broadcast", { op, key, region: cr.currentRegion });
5380
5957
  } catch (err) {
5381
- this.counters.crossRegionSent = Math.max(0, this.counters.crossRegionSent - 1);
5382
5958
  this.counters.crossRegionErrors++;
5383
5959
  this.logger.warn("Cross-region invalidation broadcast failed", { error: err.message });
5960
+ if (this.opts.awaitInvalidationBackplane) throw err;
5384
5961
  }
5385
5962
  }
5386
5963
  /**
@@ -5391,11 +5968,12 @@ var CacheService = class _CacheService {
5391
5968
  * Returns true if the event was accepted and applied, or false if ignored/deduplicated.
5392
5969
  */
5393
5970
  async receiveCrossRegionInvalidation(event) {
5971
+ this._assertActive("receiveCrossRegionInvalidation");
5394
5972
  const cr = this.opts.crossRegion;
5395
5973
  if (!cr) return false;
5396
- if (!event || typeof event !== "object" || !event.id || !event.originRegion || !event.op || !event.key) {
5974
+ if (!isCrossRegionInvalidationEvent(event)) {
5397
5975
  this.counters.crossRegionErrors++;
5398
- this.logger.warn("Cross-region: rejected invalid event payload", { event });
5976
+ this.logger.warn("Cross-region: rejected invalid event payload");
5399
5977
  return false;
5400
5978
  }
5401
5979
  if (event.originRegion === cr.currentRegion) {
@@ -5406,13 +5984,52 @@ var CacheService = class _CacheService {
5406
5984
  this.counters.crossRegionDeduplicated++;
5407
5985
  return false;
5408
5986
  }
5409
- this._markCrossRegionEventSeen(event.id);
5410
5987
  if (event.namespace !== void 0 && event.namespace !== (this._namespace || void 0)) {
5411
5988
  return false;
5412
5989
  }
5990
+ if ((event.op === "del" || event.op === "del-glob") && this._namespace && !event.key.startsWith(`${this._namespace}:`)) return false;
5991
+ this._markCrossRegionEventSeen(event.id);
5413
5992
  this.counters.crossRegionReceived++;
5414
- this._applyInvalidationEvent(event.op, event.key, event.tagVersion);
5415
- void this.publishInvalidation(event.op, event.key, event.tagVersion, true);
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
+ }
5416
6033
  this.logger.info("Cross-region invalidation applied", {
5417
6034
  op: event.op,
5418
6035
  key: event.key,
@@ -5427,10 +6044,10 @@ var CacheService = class _CacheService {
5427
6044
  const oldestKey = this.tagVersions.keys().next().value;
5428
6045
  if (oldestKey !== void 0) this.tagVersions.delete(oldestKey);
5429
6046
  }
5430
- this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
6047
+ this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now, refreshEpoch: this._tagRefreshEpoch });
5431
6048
  }
5432
6049
  async _isGenerationalEntryStale(tagVersions) {
5433
- if (this.opts.tagStrategy !== "generational" || !tagVersions) return false;
6050
+ if (!tagVersions) return false;
5434
6051
  const tags = Object.keys(tagVersions);
5435
6052
  if (tags.length === 0) return false;
5436
6053
  const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
@@ -5442,13 +6059,23 @@ var CacheService = class _CacheService {
5442
6059
  async _deleteRedisKeys(client, keys) {
5443
6060
  if (keys.length === 0) return;
5444
6061
  const CHUNK_SIZE = 1e3;
5445
- if (client instanceof import_ioredis.Cluster) {
5446
- for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
5447
- const chunk = keys.slice(i, i + CHUNK_SIZE);
5448
- const pl = client.pipeline();
5449
- for (const k of chunk) pl.del(k);
5450
- await pl.exec();
5451
- }
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
+ }));
5452
6079
  return;
5453
6080
  }
5454
6081
  for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
@@ -5461,8 +6088,11 @@ var CacheService = class _CacheService {
5461
6088
  let storedTagVersions = {};
5462
6089
  if (hashData.tv) {
5463
6090
  try {
5464
- storedTagVersions = JSON.parse(hashData.tv);
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;
5465
6094
  } catch {
6095
+ return null;
5466
6096
  }
5467
6097
  }
5468
6098
  if (await this._isGenerationalEntryStale(storedTagVersions)) {
@@ -5471,18 +6101,48 @@ var CacheService = class _CacheService {
5471
6101
  return { stale: true };
5472
6102
  }
5473
6103
  const value = await this._decryptAndDeserialize(hashData.d);
5474
- return { value, tagVersions: storedTagVersions, stale: false };
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
+ };
5475
6126
  }
5476
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
+ };
5477
6137
  if (this.opts.tagStrategy === "generational" && typeof client.hgetall === "function") {
5478
6138
  try {
5479
- const hashData = await client.hgetall(k);
6139
+ const { raw: hashData, ttlMs: ttlMs2 } = await read(true);
5480
6140
  if (typeof hashData === "string") {
5481
6141
  const value2 = await this._decryptAndDeserialize(hashData);
5482
- return { value: value2, stale: false };
6142
+ return withExpiry({ value: value2, stale: false }, ttlMs2);
5483
6143
  }
5484
6144
  if (hashData && hashData.d) {
5485
- return await this._parseGenerationalRedisHash(k, hashData);
6145
+ return withExpiry(await this._parseGenerationalRedisHash(k, hashData), ttlMs2);
5486
6146
  }
5487
6147
  return null;
5488
6148
  } catch (err) {
@@ -5490,28 +6150,163 @@ var CacheService = class _CacheService {
5490
6150
  if (!msg.includes("WRONGTYPE")) throw err;
5491
6151
  }
5492
6152
  }
5493
- const raw = allowAutoPipeline && this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
6153
+ const { raw, ttlMs } = await read(false);
5494
6154
  if (raw == null) return null;
6155
+ if (typeof raw !== "string") return null;
5495
6156
  const value = await this._decryptAndDeserialize(raw);
5496
- return { value, stale: false };
6157
+ return withExpiry({ value, stale: false }, ttlMs);
5497
6158
  }
5498
6159
  async _getTagVersion(tag) {
5499
6160
  const now = performance.now();
5500
6161
  const local = this.tagVersions.get(tag);
5501
- if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
6162
+ if (local && (local.refreshEpoch ?? 0) === this._tagRefreshEpoch && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
5502
6163
  return local.version;
5503
6164
  }
5504
6165
  if (!this._redisDisabled) {
5505
6166
  try {
5506
6167
  const client = await this.getRedis();
5507
6168
  const raw = await client.get(this.nk(`tag_ver:${tag}`));
5508
- const version = raw ? parseInt(raw, 10) : 0;
5509
- this._setLocalTagVersion(tag, version, now);
5510
- 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;
5511
6179
  } catch {
5512
6180
  }
5513
6181
  }
5514
- 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();
5515
6310
  }
5516
6311
  _deleteIfStale(k, setAtMs) {
5517
6312
  this.l1.deleteIfSetBefore(k, setAtMs);
@@ -5564,7 +6359,7 @@ var CacheService = class _CacheService {
5564
6359
  } else {
5565
6360
  plain = raw;
5566
6361
  }
5567
- return JSON.parse(plain);
6362
+ return plain === "undefined" ? void 0 : JSON.parse(plain);
5568
6363
  }
5569
6364
  /**
5570
6365
  * Scan all keys matching `pattern` across single-node or Cluster clients.
@@ -5572,7 +6367,7 @@ var CacheService = class _CacheService {
5572
6367
  */
5573
6368
  async _scanKeys(client, pattern) {
5574
6369
  const keys = [];
5575
- if (client instanceof import_ioredis.Cluster) {
6370
+ if (client instanceof import_ioredis2.Cluster) {
5576
6371
  const masters = client.nodes("master");
5577
6372
  await Promise.all(masters.map(
5578
6373
  (node) => new Promise((resolve, reject) => {
@@ -5635,7 +6430,7 @@ var CacheService = class _CacheService {
5635
6430
  let client = null;
5636
6431
  try {
5637
6432
  if (this.opts.redisClusterNodes?.length) {
5638
- client = new import_ioredis.Cluster(this.opts.redisClusterNodes, {
6433
+ client = new import_ioredis2.Cluster(this.opts.redisClusterNodes, {
5639
6434
  redisOptions: {
5640
6435
  tls: this.opts.redisTls ? {} : void 0,
5641
6436
  connectTimeout: 1e4,
@@ -5655,7 +6450,7 @@ var CacheService = class _CacheService {
5655
6450
  });
5656
6451
  client.on("reconnecting", () => this.logger.debug("Redis Cluster reconnecting"));
5657
6452
  } else if (this.opts.redisSentinel) {
5658
- client = new import_ioredis.Redis({
6453
+ client = new import_ioredis2.Redis({
5659
6454
  sentinels: this.opts.redisSentinel.sentinels,
5660
6455
  name: this.opts.redisSentinel.name,
5661
6456
  tls: this.opts.redisTls ? {} : void 0,
@@ -5675,7 +6470,7 @@ var CacheService = class _CacheService {
5675
6470
  });
5676
6471
  client.on("reconnecting", () => this.logger.debug("Redis Sentinel reconnecting"));
5677
6472
  } else {
5678
- client = new import_ioredis.Redis({
6473
+ client = new import_ioredis2.Redis({
5679
6474
  host: this.opts.redisHost,
5680
6475
  port: this.opts.redisPort,
5681
6476
  tls: this.opts.redisTls ? {} : void 0,
@@ -5767,7 +6562,12 @@ var CacheService = class _CacheService {
5767
6562
  try {
5768
6563
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
5769
6564
  if (entries.length === 0) return;
5770
- 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
+ };
5771
6571
  const packed = this.codec.encode(payload);
5772
6572
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
5773
6573
  const dest = altPath ?? this.opts.snapshotPath;
@@ -5835,6 +6635,9 @@ var CacheService = class _CacheService {
5835
6635
  return;
5836
6636
  }
5837
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);
5838
6641
  this.logger.info("Cache snapshot loaded (L1 is warm)", {
5839
6642
  loaded,
5840
6643
  total: snapshot.entries.length,
@@ -5859,7 +6662,12 @@ var CacheService = class _CacheService {
5859
6662
  try {
5860
6663
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
5861
6664
  if (entries.length === 0) return false;
5862
- 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
+ };
5863
6671
  const packed = this.codec.encode(payload);
5864
6672
  let final;
5865
6673
  if (this.opts.remoteSnapshot.envelope) {
@@ -5890,13 +6698,16 @@ var CacheService = class _CacheService {
5890
6698
  async loadRemoteSnapshot() {
5891
6699
  if (!this.opts.remoteSnapshot) return 0;
5892
6700
  const maxAgeMs = this.opts.remoteSnapshot.maxAgeMs ?? this.opts.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE;
6701
+ const epoch = this._globalEpoch;
5893
6702
  try {
5894
6703
  const raw = await this.opts.remoteSnapshot.adapter.get();
6704
+ if (this._destroyed || this._globalEpoch !== epoch) return 0;
5895
6705
  if (!raw || raw.length === 0) {
5896
6706
  this.logger.debug("Remote snapshot not found or empty \u2014 starting cold");
5897
6707
  return 0;
5898
6708
  }
5899
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");
5900
6711
  let buf;
5901
6712
  try {
5902
6713
  if (EnvelopeEncryption.isEnvelope(rawBuf)) {
@@ -5942,7 +6753,12 @@ var CacheService = class _CacheService {
5942
6753
  this.logger.warn("Remote snapshot rejected: entries is not an array");
5943
6754
  return 0;
5944
6755
  }
5945
- 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);
5946
6762
  this.counters.remoteSnapshotDownloads++;
5947
6763
  this.counters.remoteSnapshotLastDownloadedAt = Date.now();
5948
6764
  this.logger.info("Remote cache snapshot loaded (L1 hydrated)", {
@@ -5994,7 +6810,7 @@ var CacheService = class _CacheService {
5994
6810
  const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
5995
6811
  if (isGenerationalStale) {
5996
6812
  this._deleteIfStale(k, l1Hit.setAt ?? 0);
5997
- } else {
6813
+ } else if (!l1Hit.isStale || optSwr > 0) {
5998
6814
  if (l1Hit.isStale) {
5999
6815
  const swrGraceMs2 = optSwr * 1e3;
6000
6816
  if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
@@ -6057,49 +6873,29 @@ var CacheService = class _CacheService {
6057
6873
  this.counters.stampedes++;
6058
6874
  this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch/read", { cacheKey });
6059
6875
  span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
6060
- return existing;
6876
+ return this._prepareReadValue(await existing);
6061
6877
  }
6062
6878
  const mutationEpochAtStart = this._getKeyMutationEpoch(k);
6063
- const executionPromise = (async () => {
6879
+ const executionPromise = Promise.resolve().then(async () => {
6064
6880
  try {
6065
- if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
6066
- if (this._isTombstonedByPattern(k)) {
6067
- try {
6068
- this.disk.delete(k);
6069
- } catch {
6070
- }
6071
- } else {
6072
- const isDiskAllowed = this.watchdog.isDiskAllowed();
6073
- if (isDiskAllowed) {
6074
- const diskStart = performance.now();
6075
- const diskHit = this.disk.load(k);
6076
- const diskElapsed = performance.now() - diskStart;
6077
- this.watchdog.recordDisk(diskElapsed);
6078
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6079
- if (diskHit !== null) {
6080
- const isDiskStale = await this._isGenerationalEntryStale(diskHit.tagVersions);
6081
- if (isDiskStale) {
6082
- this.disk.delete(k);
6083
- } else {
6084
- const promoted = this.l1.importEntries(
6085
- [{ key: k, entry: diskHit }],
6086
- this.opts.forbiddenSnapshotPrefixes
6087
- );
6088
- if (promoted > 0) {
6089
- const l1Check = this.l1.get(k);
6090
- if (l1Check !== null) {
6091
- this.counters.diskHits++;
6092
- this.opts.onHit?.(cacheKey, "disk");
6093
- this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
6094
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
6095
- if (this.opts.frozen) deepFreeze(l1Check.value);
6096
- return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
6097
- }
6098
- }
6099
- }
6100
- }
6101
- }
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
+ );
6102
6897
  }
6898
+ return diskHit.value;
6103
6899
  }
6104
6900
  if (!this._redisDisabled) {
6105
6901
  try {
@@ -6109,23 +6905,26 @@ var CacheService = class _CacheService {
6109
6905
  const redisElapsed = performance.now() - redisStart;
6110
6906
  this.watchdog.recordRedis(redisElapsed);
6111
6907
  this.cb.onSuccess();
6112
- if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
6908
+ if (redisHit && !redisHit.stale && (redisHit.staleAt === void 0 || redisHit.staleAt > Date.now() || optSwr > 0)) {
6113
6909
  const parsed = redisHit.value;
6114
6910
  if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
6115
6911
  this.logger.debug("Aborting L2 promotion \u2014 key was mutated or deleted during Redis read", { cacheKey });
6116
6912
  span.setAttribute("cache.aborted_mutation_race", true);
6117
6913
  const current = this.l1.get(k);
6118
- const liveVal = current && !current.isStale && current.value !== void 0 ? current.value : parsed;
6119
- if (this.opts.frozen) deepFreeze(liveVal);
6120
- return this.opts.cloneStrategy === "structuredClone" && liveVal != null && typeof liveVal === "object" ? structuredClone(liveVal) : liveVal;
6914
+ const liveVal = current && !current.isStale ? current.value : parsed;
6915
+ return liveVal;
6121
6916
  }
6122
- this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, redisHit.tagVersions);
6917
+ if (!this._promoteRedisEntry(k, redisHit, ttlMs, priority)) throw new Error("Redis entry expired during promotion");
6123
6918
  this.counters.l2Hits++;
6124
6919
  this.opts.onHit?.(cacheKey, "l2");
6125
6920
  this.logger.debug(redisHit.tagVersions ? "L2 hit (Redis hash)" : "L2 hit (Redis)", { cacheKey });
6126
6921
  span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
6127
- if (this.opts.frozen) deepFreeze(parsed);
6128
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
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);
6926
+ }
6927
+ return parsed;
6129
6928
  }
6130
6929
  } catch (err) {
6131
6930
  this.cb.onFailure();
@@ -6135,6 +6934,7 @@ var CacheService = class _CacheService {
6135
6934
  span.setAttribute("cache.hit", false).setAttribute("cache.hit_tier", "miss");
6136
6935
  this.opts.onMiss?.(cacheKey);
6137
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;
6138
6938
  const fetchStart = Date.now();
6139
6939
  let data;
6140
6940
  try {
@@ -6163,50 +6963,41 @@ var CacheService = class _CacheService {
6163
6963
  }
6164
6964
  const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
6165
6965
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
6166
- let activeTagVersions;
6966
+ const activeTagVersions = tagSnapshot;
6167
6967
  if (optTags?.length) {
6168
6968
  if (this.opts.tagStrategy === "generational") {
6169
- const vers = await Promise.all(optTags.map((tag) => this._getTagVersion(tag)));
6170
- activeTagVersions = {};
6171
- for (let i = 0; i < optTags.length; i++) {
6172
- activeTagVersions[optTags[i]] = vers[i];
6173
- }
6969
+ if (await this._isGenerationalEntryStale(tagSnapshot)) return data;
6174
6970
  } else {
6175
- await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
6971
+ await this._registerTags(k, optTags, Math.ceil(storeTtl / 1e3));
6176
6972
  }
6177
6973
  }
6178
6974
  if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
6179
6975
  this.logger.debug("Aborting in-flight cache commit \u2014 key was mutated or deleted during fetch", { cacheKey });
6180
6976
  span.setAttribute("cache.aborted_mutation_race", true);
6181
6977
  const current = this.l1.get(k);
6182
- if (current && !current.isStale && current.value !== void 0) {
6978
+ if (current && !current.isStale) {
6183
6979
  const freshVal = current.value;
6184
- if (this.opts.frozen) deepFreeze(freshVal);
6185
- return this.opts.cloneStrategy === "structuredClone" && freshVal != null && typeof freshVal === "object" ? structuredClone(freshVal) : freshVal;
6980
+ return freshVal;
6186
6981
  }
6187
- if (this.opts.frozen) deepFreeze(data);
6188
- return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
6982
+ return data;
6189
6983
  }
6190
6984
  const writeTs = Date.now();
6191
- this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs);
6192
- if (!this._redisDisabled) {
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") {
6193
6989
  try {
6194
- const client = await this.getRedis();
6195
- const serialized = JSON.stringify(data);
6196
- const toStore = await this._serializeAndEncrypt(serialized);
6197
- const ttlSec = Math.ceil(effectiveTtl / 1e3);
6198
- if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
6199
- const tx = client.multi();
6200
- tx.hset(k, {
6201
- d: toStore,
6202
- t: String(writeTs),
6203
- tv: JSON.stringify(activeTagVersions ?? {})
6204
- });
6205
- tx.expire(k, ttlSec);
6206
- await tx.exec();
6207
- } else {
6208
- await client.setex(k, ttlSec, toStore);
6209
- }
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
+ );
6210
7001
  this.cb.onSuccess();
6211
7002
  this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
6212
7003
  } catch {
@@ -6216,15 +7007,14 @@ var CacheService = class _CacheService {
6216
7007
  } else {
6217
7008
  this.logger.debug("Cached L1", { cacheKey });
6218
7009
  }
6219
- if (this.opts.frozen) deepFreeze(data);
6220
- return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
7010
+ return data;
6221
7011
  } finally {
6222
- this.inflight.delete(k);
7012
+ if (this.inflight.get(k) === executionPromise) this.inflight.delete(k);
6223
7013
  span.end();
6224
7014
  }
6225
- })();
7015
+ });
6226
7016
  this.inflight.set(k, executionPromise);
6227
- return executionPromise;
7017
+ return this._prepareReadValue(await executionPromise);
6228
7018
  }
6229
7019
  /**
6230
7020
  * Graceful shutdown flusher for Kubernetes preStop hooks, NestJS onApplicationShutdown,
@@ -6305,6 +7095,9 @@ var CacheService = class _CacheService {
6305
7095
  }
6306
7096
  async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority, knownTagVersions) {
6307
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;
6308
7101
  try {
6309
7102
  const fetchStart = Date.now();
6310
7103
  const data = await fetchFn();
@@ -6319,14 +7112,14 @@ var CacheService = class _CacheService {
6319
7112
  const l1Existing = this.l1.get(cacheKey);
6320
7113
  const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
6321
7114
  if (this.opts.tagStrategy === "generational" && tagVersionsSource) {
6322
- const tags = Object.keys(tagVersionsSource);
6323
- 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)));
6324
7117
  activeTagVersions = {};
6325
- for (let i = 0; i < tags.length; i++) {
6326
- activeTagVersions[tags[i]] = vers[i];
7118
+ for (let i = 0; i < tags2.length; i++) {
7119
+ activeTagVersions[tags2[i]] = vers[i];
6327
7120
  }
6328
7121
  if (knownTagVersions) {
6329
- for (const t of tags) {
7122
+ for (const t of tags2) {
6330
7123
  if (knownTagVersions[t] !== void 0 && activeTagVersions[t] !== knownTagVersions[t]) {
6331
7124
  this.logger.debug("SWR: aborting revalidation commit \u2014 tag version bumped during revalidation", { cacheKey, tag: t });
6332
7125
  return;
@@ -6339,31 +7132,28 @@ var CacheService = class _CacheService {
6339
7132
  return;
6340
7133
  }
6341
7134
  const writeTs = Date.now();
6342
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs);
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 });
6343
7138
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6344
7139
  try {
6345
- const client = await this.getRedis();
6346
- const s = JSON.stringify(data);
6347
- const stored = await this._serializeAndEncrypt(s);
6348
- const ttlSec = Math.ceil(ttlMs / 1e3);
6349
- if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
6350
- const tx = client.multi();
6351
- tx.hset(cacheKey, {
6352
- d: stored,
6353
- t: String(writeTs),
6354
- tv: JSON.stringify(activeTagVersions ?? {})
6355
- });
6356
- tx.expire(cacheKey, ttlSec);
6357
- await tx.exec();
6358
- } else {
6359
- await client.setex(cacheKey, ttlSec, stored);
6360
- }
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
+ );
6361
7151
  } catch {
6362
7152
  }
6363
7153
  }
6364
7154
  this.logger.debug("SWR: revalidation complete", { cacheKey });
6365
7155
  } catch (err) {
6366
- if (this.opts.staleIfError > 0) {
7156
+ if (this.opts.staleIfError > 0 && this._getKeyMutationEpoch(cacheKey) === startEpoch) {
6367
7157
  const additionalMs = this.opts.staleIfError * 1e3;
6368
7158
  this.l1.bumpExpiry(cacheKey, additionalMs);
6369
7159
  this.logger.debug("SWR: revalidation failed, stale-if-error extending expiry", {
@@ -6391,12 +7181,16 @@ var CacheService = class _CacheService {
6391
7181
  const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
6392
7182
  const p = priority ?? inferPriority(cacheKey);
6393
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;
6394
7187
  this._bumpKeyMutation(k);
7188
+ const epoch = this._getKeyMutationEpoch(k);
6395
7189
  this.inflight.delete(k);
6396
- this._pendingDiskDeletes.delete(k);
7190
+ this._invalidateDiskKey(k);
6397
7191
  this.counters.sets++;
6398
7192
  let activeTagVersions;
6399
- 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;
6400
7194
  if (tagsToRegister?.length) {
6401
7195
  if (this.opts.tagStrategy === "generational") {
6402
7196
  const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
@@ -6405,50 +7199,27 @@ var CacheService = class _CacheService {
6405
7199
  activeTagVersions[tagsToRegister[i]] = vers[i];
6406
7200
  }
6407
7201
  } else {
6408
- await this._registerTags(k, tagsToRegister, ttlSeconds);
7202
+ await this._registerTags(k, tagsToRegister, effectiveTtlSeconds);
6409
7203
  }
6410
7204
  }
7205
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return;
6411
7206
  const writeTs = Date.now();
6412
- this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions, writeTs);
6413
- if (opts?.dependsOn !== void 0) {
6414
- this._removeKeyDependencies(k);
6415
- if (opts.dependsOn.length > 0) {
6416
- const nsPatterns = [];
6417
- for (const pattern of opts.dependsOn) {
6418
- const nsPattern = this.nk(pattern);
6419
- nsPatterns.push(nsPattern);
6420
- let deps = this.dependencyIndex.get(nsPattern);
6421
- if (!deps) {
6422
- deps = /* @__PURE__ */ new Set();
6423
- this.dependencyIndex.set(nsPattern, deps);
6424
- }
6425
- deps.add(k);
6426
- }
6427
- this.keyDependencies.set(k, nsPatterns);
6428
- }
6429
- }
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);
6430
7210
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6431
7211
  try {
6432
- const client = await this.getRedis();
6433
- const s = JSON.stringify(data);
6434
- const stored = await this._serializeAndEncrypt(s);
6435
- const ttlSec = Math.ceil(ttlMs / 1e3);
6436
- if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
6437
- const tx = client.multi();
6438
- tx.hset(k, {
6439
- d: stored,
6440
- t: String(writeTs),
6441
- tv: JSON.stringify(activeTagVersions ?? {})
6442
- });
6443
- tx.expire(k, ttlSec);
6444
- await tx.exec();
6445
- } else {
6446
- if (this.opts.autoPipeline && this.pipeliner) {
6447
- await this.pipeliner.setex(k, ttlSec, stored);
6448
- } else {
6449
- await client.setex(k, ttlSec, stored);
6450
- }
6451
- }
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
+ );
6452
7223
  this.cb.onSuccess();
6453
7224
  } catch (err) {
6454
7225
  this.cb.onFailure();
@@ -6473,27 +7244,10 @@ var CacheService = class _CacheService {
6473
7244
  * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
6474
7245
  */
6475
7246
  async _registerTags(k, tags, ttlSeconds) {
6476
- this._removeKeyTags(k);
6477
7247
  const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
6478
7248
  const expiresAt = Date.now() + effectiveTtl * 1e3;
6479
- if (this.keyTags.size >= 1e5 && !this.keyTags.has(k)) {
6480
- this._sweepExpiredMetadata();
6481
- if (this.keyTags.size >= 1e5) {
6482
- const oldestKey = this.keyTags.keys().next().value;
6483
- if (oldestKey !== void 0) this._removeKeyTags(oldestKey);
6484
- }
6485
- }
6486
7249
  const uniqueTags = Array.from(new Set(tags));
6487
- for (const tag of uniqueTags) {
6488
- const tagKey = this.nk(`_tag_:${tag}`);
6489
- let members = this.tagIndex.get(tagKey);
6490
- if (!members) {
6491
- members = /* @__PURE__ */ new Set();
6492
- this.tagIndex.set(tagKey, members);
6493
- }
6494
- members.add(k);
6495
- }
6496
- this.keyTags.set(k, { tags: uniqueTags, expiresAt });
7250
+ this._rememberTags(k, uniqueTags, expiresAt);
6497
7251
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6498
7252
  try {
6499
7253
  const client = await this.getRedis();
@@ -6526,6 +7280,7 @@ var CacheService = class _CacheService {
6526
7280
  const k = this.nk(cacheKey);
6527
7281
  this.counters.deletes++;
6528
7282
  if (isPattern) {
7283
+ this._fenceInvalidation();
6529
7284
  const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6530
7285
  for (const liveKey of this.l1.liveKeys()) {
6531
7286
  if (liveKey.startsWith(pfx)) {
@@ -6538,9 +7293,9 @@ var CacheService = class _CacheService {
6538
7293
  this.inflight.delete(inflightKey);
6539
7294
  }
6540
7295
  }
6541
- this._addPatternTombstone(pfx);
7296
+ this._addPatternTombstone(k);
6542
7297
  this.l1.deletePattern(k);
6543
- this._removePrefixFromIndices(pfx);
7298
+ this._removePatternFromIndices(k);
6544
7299
  for (const ktKey of Array.from(this.keyTags.keys())) {
6545
7300
  if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
6546
7301
  }
@@ -6551,14 +7306,7 @@ var CacheService = class _CacheService {
6551
7306
  this._bumpKeyMutation(k);
6552
7307
  this.inflight.delete(k);
6553
7308
  this.l1.delete(k);
6554
- this._pendingDiskDeletes.add(k);
6555
- setImmediate(() => {
6556
- try {
6557
- if (!this._diskDisabled) this.disk.delete(k);
6558
- } finally {
6559
- this._pendingDiskDeletes.delete(k);
6560
- }
6561
- });
7309
+ this._invalidateDiskKey(k);
6562
7310
  this._removeKeyTags(k);
6563
7311
  this._cascadeDependencies(k);
6564
7312
  this._removeKeyDependencies(k);
@@ -6615,7 +7363,7 @@ var CacheService = class _CacheService {
6615
7363
  async increment(cacheKey, ttlSeconds) {
6616
7364
  this._assertActive("increment");
6617
7365
  const k = this.nk(cacheKey);
6618
- if (this._redisDisabled) {
7366
+ if (this._redisDisabled || this.opts.l2WriteMode === "read-only") {
6619
7367
  if (!this._incrementFallbackWarned) {
6620
7368
  this._incrementFallbackWarned = true;
6621
7369
  this.logger.warn(
@@ -6671,6 +7419,7 @@ var CacheService = class _CacheService {
6671
7419
  this.counters.deletes++;
6672
7420
  const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
6673
7421
  if (k) {
7422
+ this._fenceInvalidation();
6674
7423
  const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6675
7424
  for (const liveKey of this.l1.liveKeys()) {
6676
7425
  if (liveKey.startsWith(pfx)) {
@@ -6683,9 +7432,9 @@ var CacheService = class _CacheService {
6683
7432
  this.inflight.delete(inflightKey);
6684
7433
  }
6685
7434
  }
6686
- this._addPatternTombstone(pfx);
7435
+ this._addPatternTombstone(k);
6687
7436
  this.l1.deletePattern(k);
6688
- this._removePrefixFromIndices(pfx);
7437
+ this._removePatternFromIndices(k);
6689
7438
  } else {
6690
7439
  this._globalEpoch++;
6691
7440
  this.inflight.clear();
@@ -6835,28 +7584,34 @@ var CacheService = class _CacheService {
6835
7584
  this._assertActive("scan");
6836
7585
  const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
6837
7586
  this.l1.scan((key, entry, pfx) => {
6838
- const value = entry.value !== void 0 ? entry.value : entry.data;
6839
- fn(key, value, pfx);
7587
+ fn(key, this._prepareReadValue(this.l1.resolveValue(entry)), pfx);
6840
7588
  }, prefixLen);
6841
7589
  }
6842
7590
  /**
6843
- * 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.
6844
7592
  * Returns `false` if the key is absent or already expired.
6845
7593
  *
6846
7594
  * @param newTtlSeconds - The new TTL from now, in seconds.
6847
7595
  */
6848
7596
  async touch(cacheKey, newTtlSeconds) {
6849
7597
  this._assertActive("touch");
7598
+ if (!Number.isFinite(newTtlSeconds) || newTtlSeconds <= 0) throw new Error("touch TTL must be finite and positive");
6850
7599
  const k = this.nk(cacheKey);
7600
+ const epoch = this._getKeyMutationEpoch(k);
6851
7601
  const hit = this.l1.touch(k, newTtlSeconds * 1e3);
7602
+ const entry = this.l1.getEntry(k);
6852
7603
  if (hit) {
6853
7604
  const kt = this.keyTags.get(k);
6854
7605
  if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1e3;
6855
7606
  }
6856
- if (hit && !this._redisDisabled) {
7607
+ if (hit && !this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6857
7608
  try {
6858
7609
  const client = await this.getRedis();
6859
- 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();
6860
7615
  } catch {
6861
7616
  }
6862
7617
  }
@@ -6878,7 +7633,8 @@ var CacheService = class _CacheService {
6878
7633
  const now = Date.now();
6879
7634
  if (entry.expiresAt <= now) return null;
6880
7635
  if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
6881
- 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));
6882
7638
  }
6883
7639
  _prepareReadValue(val) {
6884
7640
  if (this.opts.frozen) deepFreeze(val);
@@ -6895,49 +7651,23 @@ var CacheService = class _CacheService {
6895
7651
  async peek(cacheKey) {
6896
7652
  this._assertActive("peek");
6897
7653
  const k = this.nk(cacheKey);
7654
+ const epoch = this._getKeyMutationEpoch(k);
7655
+ this.counters.gets++;
6898
7656
  const l1Hit = this.l1.get(k);
6899
7657
  if (l1Hit !== null) {
6900
7658
  if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
6901
7659
  this._deleteIfStale(k, l1Hit.setAt ?? 0);
6902
7660
  } else {
6903
- this.counters.gets++;
6904
7661
  this.counters.l1Hits++;
6905
7662
  return this._prepareReadValue(l1Hit.value);
6906
7663
  }
6907
7664
  }
6908
- if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
6909
- if (this._isTombstonedByPattern(k)) {
6910
- try {
6911
- this.disk.delete(k);
6912
- } catch {
6913
- }
6914
- } else if (this.watchdog.isDiskAllowed()) {
6915
- const diskStart = performance.now();
6916
- const diskHit = this.disk.load(k);
6917
- const diskElapsed = performance.now() - diskStart;
6918
- this.watchdog.recordDisk(diskElapsed);
6919
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6920
- if (diskHit !== null) {
6921
- if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
6922
- this.disk.delete(k);
6923
- } else {
6924
- const promoted = this.l1.importEntries(
6925
- [{ key: k, entry: diskHit }],
6926
- this.opts.forbiddenSnapshotPrefixes
6927
- );
6928
- if (promoted > 0) {
6929
- const l1Check = this.l1.get(k);
6930
- if (l1Check !== null) {
6931
- this.counters.gets++;
6932
- this.counters.diskHits++;
6933
- return this._prepareReadValue(l1Check.value);
6934
- }
6935
- }
6936
- }
6937
- }
6938
- }
7665
+ const diskHit = await this._readDiskEntry(k, epoch);
7666
+ if (diskHit) {
7667
+ this.counters.diskHits++;
7668
+ return this._prepareReadValue(diskHit.value);
6939
7669
  }
6940
- if (!this._redisDisabled && !this.cb.isOpen) {
7670
+ if (!this._redisDisabled) {
6941
7671
  try {
6942
7672
  const client = await this.getRedis();
6943
7673
  const redisStart = performance.now();
@@ -6945,10 +7675,10 @@ var CacheService = class _CacheService {
6945
7675
  const redisElapsed = performance.now() - redisStart;
6946
7676
  this.watchdog.recordRedis(redisElapsed);
6947
7677
  this.cb.onSuccess();
6948
- if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
7678
+ if (redisHit && !redisHit.stale) {
6949
7679
  const parsed = redisHit.value;
6950
- this.l1.set(k, parsed, 6e4, inferPriority(cacheKey), void 0, void 0, redisHit.tagVersions);
6951
- this.counters.gets++;
7680
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return null;
7681
+ if (!this._promoteRedisEntry(k, redisHit, 6e4, inferPriority(cacheKey))) return null;
6952
7682
  this.counters.l2Hits++;
6953
7683
  return this._prepareReadValue(parsed);
6954
7684
  }
@@ -6970,6 +7700,8 @@ var CacheService = class _CacheService {
6970
7700
  */
6971
7701
  async mget(keys, fetchFn, ttl = 300, priority) {
6972
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))]));
6973
7705
  const span = this._startSpan("tricache.mget");
6974
7706
  if (this.opts.tracer) {
6975
7707
  span.setAttribute("cache.batch.size", keys.length);
@@ -6982,7 +7714,7 @@ var CacheService = class _CacheService {
6982
7714
  for (let i = 0; i < keys.length; i++) {
6983
7715
  const k = this.nk(keys[i]);
6984
7716
  const entry = this.l1.getEntry(k);
6985
- if (entry && entry.expiresAt > now) {
7717
+ if (entry && entry.expiresAt > now && (entry.staleAt === void 0 || entry.staleAt > now)) {
6986
7718
  if (await this._isGenerationalEntryStale(entry.tagVersions)) {
6987
7719
  this._deleteIfStale(k, entry.setAt ?? 0);
6988
7720
  missIndexes.push(i);
@@ -7011,64 +7743,24 @@ var CacheService = class _CacheService {
7011
7743
  try {
7012
7744
  const client = await this.getRedis();
7013
7745
  const nsKeys = missKeys.map((k) => this.nk(k));
7014
- const pipeline = client.multi();
7015
- const useHashPipeline = this.opts.tagStrategy === "generational" && typeof pipeline.hgetall === "function";
7016
- for (const nk of nsKeys) {
7017
- if (useHashPipeline) {
7018
- pipeline.hgetall(nk);
7019
- } else {
7020
- pipeline.get(nk);
7021
- }
7022
- }
7023
- const redisStart = performance.now();
7024
- const raws = await pipeline.exec();
7025
- const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
7026
- this.watchdog.recordRedis(redisElapsed);
7027
- this.cb.onSuccess();
7746
+ const remoteEntries = await this._readRedisBatch(client, nsKeys);
7028
7747
  for (let j = 0; j < missKeys.length; j++) {
7029
- const tuple = raws[j];
7030
- const err = tuple ? tuple[0] : null;
7031
- const rawVal = tuple ? tuple[1] : null;
7032
7748
  const idx = missIndexes[j];
7033
7749
  const k = nsKeys[j];
7034
- let parsed;
7035
- let tagVersions;
7036
- let hit = false;
7037
- if (useHashPipeline) {
7038
- if (err && err.message?.includes("WRONGTYPE")) {
7039
- const fallbackRaw = await client.get(k);
7040
- if (fallbackRaw) {
7041
- parsed = await this._decryptAndDeserialize(fallbackRaw);
7042
- hit = true;
7043
- }
7044
- } else if (!err && typeof rawVal === "string") {
7045
- parsed = await this._decryptAndDeserialize(rawVal);
7046
- hit = true;
7047
- } else if (!err && rawVal && typeof rawVal === "object" && rawVal.d) {
7048
- const hashHit = await this._parseGenerationalRedisHash(k, rawVal);
7049
- if (hashHit && !hashHit.stale && hashHit.value !== void 0) {
7050
- parsed = hashHit.value;
7051
- tagVersions = hashHit.tagVersions;
7052
- hit = true;
7053
- }
7054
- }
7055
- } else if (!err && rawVal) {
7056
- parsed = await this._decryptAndDeserialize(rawVal);
7057
- hit = true;
7058
- }
7059
- if (hit && parsed !== void 0) {
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)) {
7060
7752
  const p = priority ?? inferPriority(missKeys[j]);
7061
7753
  const ttlVal = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
7062
- this.l1.set(k, parsed, this._jitterTtl(ttlVal * 1e3), p, void 0, void 0, tagVersions);
7754
+ if (!this._promoteRedisEntry(k, entry, this._jitterTtl(ttlVal * 1e3), p)) continue;
7063
7755
  this.counters.l2Hits++;
7064
7756
  l2HitCount++;
7065
- result[idx] = this._prepareReadValue(parsed);
7757
+ result[idx] = this._prepareReadValue(entry.value);
7066
7758
  missIndexes[j] = -1;
7067
7759
  missKeys[j] = "";
7068
7760
  }
7069
7761
  }
7070
7762
  const remainingIdx = missIndexes.filter((i) => i >= 0);
7071
- const remainingKeys = missKeys.filter((k) => k !== "");
7763
+ const remainingKeys = missKeys.filter((_key, index) => missIndexes[index] >= 0);
7072
7764
  missIndexes.length = 0;
7073
7765
  missKeys.length = 0;
7074
7766
  missIndexes.push(...remainingIdx);
@@ -7081,62 +7773,64 @@ var CacheService = class _CacheService {
7081
7773
  if (!this._diskDisabled && missKeys.length > 0) {
7082
7774
  for (let j = missKeys.length - 1; j >= 0; j--) {
7083
7775
  const k = this.nk(missKeys[j]);
7084
- if (this._pendingDiskDeletes.has(k)) continue;
7085
- if (this._isTombstonedByPattern(k)) {
7086
- try {
7087
- this.disk.delete(k);
7088
- } catch {
7089
- }
7090
- continue;
7091
- }
7092
- if (!this.watchdog.isDiskAllowed()) continue;
7093
- const diskStart = performance.now();
7094
- const diskHit = this.disk.load(k);
7095
- const diskElapsed = performance.now() - diskStart;
7096
- this.watchdog.recordDisk(diskElapsed);
7097
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
7098
- if (diskHit !== null) {
7099
- if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
7100
- this.disk.delete(k);
7101
- continue;
7102
- }
7103
- const promoted = this.l1.importEntries(
7104
- [{ key: k, entry: diskHit }],
7105
- this.opts.forbiddenSnapshotPrefixes
7106
- );
7107
- if (promoted > 0) {
7108
- const l1Check = this.l1.get(k);
7109
- if (l1Check !== null) {
7110
- this.counters.diskHits++;
7111
- result[missIndexes[j]] = this._prepareReadValue(l1Check.value);
7112
- missIndexes.splice(j, 1);
7113
- missKeys.splice(j, 1);
7114
- }
7115
- }
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);
7116
7782
  }
7117
7783
  }
7118
7784
  }
7119
7785
  if (missKeys.length > 0 && fetchFn) {
7120
- this.counters.fetches++;
7121
- const fetched = await fetchFn(missKeys);
7122
- const isMap = fetched instanceof Map;
7123
- const setPromises = [];
7786
+ const owned = /* @__PURE__ */ new Map();
7787
+ const waiting = [];
7124
7788
  for (let j = 0; j < missKeys.length; j++) {
7125
- const k = missKeys[j];
7126
- const v = isMap ? fetched.get(k) : fetched[k];
7127
- result[missIndexes[j]] = v;
7128
- if (v !== void 0 && v !== null) {
7129
- const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
7130
- setPromises.push(this.set(k, v, resolvedTtl, priority));
7131
- } else if (v == null && this.opts.notFoundTtl > 0) {
7132
- setPromises.push(this.set(k, null, this.opts.notFoundTtl, priority));
7133
- } else if (v === null) {
7134
- const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
7135
- 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++;
7136
7803
  }
7804
+ const index = missIndexes[j];
7805
+ waiting.push(promise.then((value) => {
7806
+ result[index] = this._prepareReadValue(value);
7807
+ }));
7137
7808
  }
7138
- if (setPromises.length > 0) {
7139
- 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
+ }
7140
7834
  }
7141
7835
  }
7142
7836
  if (this.opts.tracer) {
@@ -7189,7 +7883,7 @@ var CacheService = class _CacheService {
7189
7883
  try {
7190
7884
  await Promise.all(keys.map((key) => {
7191
7885
  const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
7192
- const hasOpts = tags?.length || dependsOn?.length;
7886
+ const hasOpts = tags !== void 0 || dependsOn !== void 0;
7193
7887
  return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
7194
7888
  }));
7195
7889
  } catch (err) {
@@ -7241,26 +7935,21 @@ var CacheService = class _CacheService {
7241
7935
  try {
7242
7936
  const client = await this.getRedis();
7243
7937
  const nsPattern = this.nk(pattern);
7244
- 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
+ });
7245
7942
  if (matchedKeys.length === 0) {
7246
7943
  this.cb.onSuccess();
7247
7944
  return 0;
7248
7945
  }
7249
- const pl = client.pipeline();
7250
- for (const k of matchedKeys) pl.get(k);
7251
- const results = await pl.exec();
7252
- this.cb.onSuccess();
7946
+ const epochs = new Map(matchedKeys.map((key) => [key, this._getKeyMutationEpoch(key)]));
7947
+ const results = await this._readRedisBatch(client, matchedKeys);
7253
7948
  let loaded = 0;
7254
- for (let i = 0; i < matchedKeys.length; i++) {
7255
- const [err, raw] = results[i];
7256
- if (err || raw == null) continue;
7257
- try {
7258
- const parsed = await this._decryptAndDeserialize(raw);
7259
- const remainingMs = 10 * 60 * 1e3;
7260
- this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
7261
- loaded++;
7262
- } catch {
7263
- }
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++;
7264
7953
  }
7265
7954
  this.logger.info("warmFromL2 complete", {
7266
7955
  pattern,
@@ -7347,14 +8036,7 @@ var CacheService = class _CacheService {
7347
8036
  this._bumpKeyMutation(k);
7348
8037
  this._removeKeyTags(k);
7349
8038
  this._removeKeyDependencies(k);
7350
- this._pendingDiskDeletes.add(k);
7351
- setImmediate(() => {
7352
- try {
7353
- if (!this._diskDisabled) this.disk.delete(k);
7354
- } finally {
7355
- this._pendingDiskDeletes.delete(k);
7356
- }
7357
- });
8039
+ this._invalidateDiskKey(k);
7358
8040
  }
7359
8041
  }
7360
8042
  /**
@@ -7362,9 +8044,10 @@ var CacheService = class _CacheService {
7362
8044
  * wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
7363
8045
  */
7364
8046
  async _invalidateConcreteTag(tag) {
8047
+ this._fenceInvalidation();
7365
8048
  if (this.opts.tagStrategy === "generational") {
7366
8049
  let newVer = 1;
7367
- if (!this._redisDisabled) {
8050
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7368
8051
  try {
7369
8052
  const client = await this.getRedis();
7370
8053
  newVer = await client.incr(this.nk(`tag_ver:${tag}`));
@@ -7382,19 +8065,23 @@ var CacheService = class _CacheService {
7382
8065
  return;
7383
8066
  }
7384
8067
  const tagKey = this.nk(`_tag_:${tag}`);
7385
- const members = Array.from(this.tagIndex.get(tagKey) ?? []);
8068
+ const members = new Set(this.tagIndex.get(tagKey) ?? []);
7386
8069
  this.tagIndex.delete(tagKey);
7387
8070
  this._removeTagMembersLocal(members);
7388
- if (!this._redisDisabled) {
8071
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7389
8072
  try {
7390
8073
  const client = await this.getRedis();
7391
8074
  const redisMembers = await client.smembers(tagKey);
8075
+ for (const key of redisMembers) members.add(key);
8076
+ this._removeTagMembersLocal(redisMembers);
7392
8077
  const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers, tagKey])];
7393
8078
  await this._deleteRedisKeys(client, toDelete);
7394
8079
  } catch (err) {
7395
8080
  this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7396
8081
  }
7397
8082
  }
8083
+ await Promise.all([...members].map((key) => this._publishTagInvalidation("del", key)));
8084
+ await this._publishTagInvalidation("tag_pattern_del", tag);
7398
8085
  }
7399
8086
  /**
7400
8087
  * Executes invalidation for an array of already-resolved concrete tags
@@ -7406,9 +8093,10 @@ var CacheService = class _CacheService {
7406
8093
  await this._invalidateConcreteTag(tags[0]);
7407
8094
  return;
7408
8095
  }
8096
+ this._fenceInvalidation();
7409
8097
  if (this.opts.tagStrategy === "generational") {
7410
8098
  const now = performance.now();
7411
- if (!this._redisDisabled) {
8099
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7412
8100
  try {
7413
8101
  const client = await this.getRedis();
7414
8102
  const pl = client.pipeline();
@@ -7442,7 +8130,7 @@ var CacheService = class _CacheService {
7442
8130
  this.tagIndex.delete(tagKey);
7443
8131
  }
7444
8132
  this._removeTagMembersLocal(allMembers);
7445
- if (!this._redisDisabled) {
8133
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7446
8134
  try {
7447
8135
  const client = await this.getRedis();
7448
8136
  const pl = client.pipeline();
@@ -7453,15 +8141,19 @@ var CacheService = class _CacheService {
7453
8141
  if (!err && redisMembers) {
7454
8142
  for (const k of redisMembers) {
7455
8143
  if (!allMembers.has(k)) toDelete.push(k);
8144
+ allMembers.add(k);
7456
8145
  }
7457
8146
  }
7458
8147
  }
7459
8148
  const keysToRemove = [...toDelete, ...tagKeys];
7460
8149
  await this._deleteRedisKeys(client, keysToRemove);
8150
+ this._removeTagMembersLocal(allMembers);
7461
8151
  } catch (err) {
7462
8152
  this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7463
8153
  }
7464
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);
7465
8157
  }
7466
8158
  /**
7467
8159
  * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
@@ -7615,19 +8307,23 @@ var CacheService = class _CacheService {
7615
8307
  const diskLowSpace = !this._diskDisabled && this.disk.hostVolumeLowSpace;
7616
8308
  const circuitOpen = this.cb.isOpen;
7617
8309
  const latencyBypass = watchdogTel.bypassActive;
7618
- const degraded = circuitOpen || latencyBypass || diskPruning || diskLowSpace;
7619
- 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);
7620
8313
  const reasons = [];
7621
8314
  if (circuitOpen) reasons.push("redis_circuit_breaker_open");
7622
8315
  if (latencyBypass) reasons.push(`disk_latency_bypass_stage_${watchdogTel.bypassStage}`);
7623
8316
  if (diskPruning) reasons.push("disk_quota_watermark_pruning_active");
7624
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");
7625
8320
  return {
7626
8321
  healthy,
7627
8322
  degraded,
7628
8323
  reasons,
7629
8324
  details: {
7630
- redisConnected: !circuitOpen && !this._redisDisabled,
8325
+ redisConnected: !this._destroyed && !circuitOpen && !!this.redis && (this.redis.status === "ready" || this.redis.isOpen === true),
8326
+ backplaneReady: this._backplaneAvailable,
7631
8327
  circuitBreakerState: this.cb.currentState,
7632
8328
  diskPruningActive: diskPruning,
7633
8329
  diskHostVolumeLowSpace: diskLowSpace,
@@ -7649,23 +8345,28 @@ var CacheService = class _CacheService {
7649
8345
  */
7650
8346
  async drainToL2() {
7651
8347
  this._assertActive("drainToL2");
7652
- if (this._redisDisabled) return 0;
8348
+ if (this._redisDisabled || this.opts.l2WriteMode === "read-only") return 0;
7653
8349
  try {
7654
- const client = await this.getRedis();
7655
8350
  const entries = this.l1.exportEntries([]);
7656
- const now = Date.now();
7657
8351
  if (entries.length === 0) return 0;
7658
- const pl = client.pipeline();
7659
- for (const { key, entry } of entries) {
7660
- const remainingMs = entry.expiresAt - now;
7661
- if (remainingMs <= 0) continue;
7662
- const ttlSecs = Math.max(1, Math.ceil(remainingMs / 1e3));
7663
- const s = JSON.stringify(entry.value);
7664
- const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
7665
- pl.setex(key, ttlSecs, stored);
7666
- }
7667
- await pl.exec();
7668
- 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;
7669
8370
  } catch (err) {
7670
8371
  this.logger.debug("drainToL2: Redis unavailable", { error: err.message });
7671
8372
  return 0;
@@ -7695,7 +8396,7 @@ var CacheService = class _CacheService {
7695
8396
  this._assertActive("setIfAbsent");
7696
8397
  const k = this.nk(cacheKey);
7697
8398
  if (this.l1.has(k)) return false;
7698
- if (!this._redisDisabled) {
8399
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7699
8400
  try {
7700
8401
  const client = await this.getRedis();
7701
8402
  const serialized = JSON.stringify(value);
@@ -7712,7 +8413,7 @@ var CacheService = class _CacheService {
7712
8413
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
7713
8414
  const p = priority ?? inferPriority(cacheKey);
7714
8415
  this._bumpKeyMutation(k);
7715
- this._pendingDiskDeletes.delete(k);
8416
+ this._invalidateDiskKey(k);
7716
8417
  this.l1.set(k, value, ttlMs, p);
7717
8418
  this.counters.sets++;
7718
8419
  return true;
@@ -7739,7 +8440,7 @@ var CacheService = class _CacheService {
7739
8440
  const token = import_crypto3.default.randomUUID();
7740
8441
  const deadline = Date.now() + acquireTimeout;
7741
8442
  let acquired = false;
7742
- if (!this._redisDisabled) {
8443
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7743
8444
  let client = null;
7744
8445
  try {
7745
8446
  client = await this.getRedis();
@@ -7834,7 +8535,9 @@ var CacheService = class _CacheService {
7834
8535
  const gDiskFiles = meter.createObservableGauge("tricache.disk.files", { description: "Current L1.5 disk file count" });
7835
8536
  const gDiskBytes = meter.createObservableGauge("tricache.disk.bytes", { description: "Current L1.5 disk size in bytes" });
7836
8537
  const gBloomFpr = meter.createObservableGauge("tricache.bloom.fpr", { description: "Bloom filter false-positive rate" });
7837
- meter.addBatchObservableCallback((observableResult) => {
8538
+ const observables = [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr];
8539
+ const callback = (observableResult) => {
8540
+ if (this._destroyed) return;
7838
8541
  const stats = this.stats();
7839
8542
  const l1 = stats.l1;
7840
8543
  const disk = stats.disk;
@@ -7847,7 +8550,9 @@ var CacheService = class _CacheService {
7847
8550
  observableResult.observe(gDiskFiles, disk.files, attrs);
7848
8551
  observableResult.observe(gDiskBytes, disk.sizeKB * 1024, attrs);
7849
8552
  observableResult.observe(gBloomFpr, fpr, attrs);
7850
- }, [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr]);
8553
+ };
8554
+ meter.addBatchObservableCallback(callback, observables);
8555
+ this._otelCleanup = () => meter.removeBatchObservableCallback?.(callback, observables);
7851
8556
  } catch (err) {
7852
8557
  this.logger.warn("Failed to initialize OpenTelemetry metrics meter", { error: err.message });
7853
8558
  }
@@ -8117,6 +8822,16 @@ var CacheService = class _CacheService {
8117
8822
  /** Close Redis connections and stop all background timers. */
8118
8823
  async destroy() {
8119
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();
8120
8835
  this._pendingDiskDeletes.clear();
8121
8836
  this._keyMutationEpochs.clear();
8122
8837
  this.inflight.clear();
@@ -8146,6 +8861,12 @@ var CacheService = class _CacheService {
8146
8861
  this._workerPool = null;
8147
8862
  }
8148
8863
  if (this.subClient) {
8864
+ if (this.opts.redisSubClient) {
8865
+ try {
8866
+ await this.subClient.unsubscribe?.(this.backplaneChannel);
8867
+ } catch {
8868
+ }
8869
+ }
8149
8870
  if (!this.opts.redisSubClient) {
8150
8871
  try {
8151
8872
  this.subClient.disconnect();
@@ -8155,7 +8876,7 @@ var CacheService = class _CacheService {
8155
8876
  this.subClient = null;
8156
8877
  }
8157
8878
  if (this.streamClient) {
8158
- try {
8879
+ if (!this.opts.redisSubClient) try {
8159
8880
  this.streamClient.disconnect();
8160
8881
  } catch {
8161
8882
  }
@@ -8192,6 +8913,7 @@ var CacheService = class _CacheService {
8192
8913
  };
8193
8914
 
8194
8915
  // src/cli.ts
8916
+ var import_ioredis3 = require("ioredis");
8195
8917
  var import_meta2 = {};
8196
8918
  async function runCli(args = process.argv.slice(2)) {
8197
8919
  const options = {
@@ -8229,7 +8951,7 @@ async function runCli(args = process.argv.slice(2)) {
8229
8951
  return;
8230
8952
  }
8231
8953
  if (values.version || command === "version") {
8232
- let version = "1.0.1";
8954
+ let version = "1.0.2";
8233
8955
  try {
8234
8956
  const pkg = JSON.parse((0, import_node_fs3.readFileSync)(new URL("../package.json", import_meta2.url), "utf8"));
8235
8957
  if (pkg?.version) version = pkg.version;
@@ -8332,16 +9054,35 @@ Press "q" or Ctrl+C to exit
8332
9054
  return;
8333
9055
  }
8334
9056
  const redisStr = typeof values.redis === "string" ? values.redis : void 0;
8335
- const redisHost = redisStr ? redisStr.replace(/^redis:\/\//, "").split(":")[0] : void 0;
8336
- 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
+ }
8337
9077
  const namespace = typeof values.namespace === "string" ? values.namespace : void 0;
8338
9078
  const diskCacheDir = typeof values.disk === "string" ? values.disk : void 0;
8339
9079
  const cache = new CacheService({
8340
9080
  redisHost,
8341
9081
  redisPort,
9082
+ redisClient,
8342
9083
  namespace,
8343
9084
  diskCacheDir,
8344
- disableRedis: !redisHost
9085
+ disableRedis: !redisClient
8345
9086
  });
8346
9087
  try {
8347
9088
  if (command === "inspect") {
@@ -8393,6 +9134,7 @@ Press "q" or Ctrl+C to exit
8393
9134
  }
8394
9135
  } finally {
8395
9136
  await cache.destroy();
9137
+ redisClient?.disconnect();
8396
9138
  }
8397
9139
  }
8398
9140
  function printHelp() {