tricache 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +36 -28
  2. package/dist/{cache-service-pJ-nFcVj.d.ts → cache-service-B108FzER.d.ts} +63 -3
  3. package/dist/cache-service-CWI4jkS7.d.cts +963 -0
  4. package/dist/{cache-service-26GCO3UU.js → cache-service-GYPZFB7O.js} +2 -2
  5. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  6. package/dist/{chunk-2AJKEQMZ.js → chunk-H4GFLQ26.js} +7 -4
  7. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  8. package/dist/chunk-OYDU3SMI.js +89 -0
  9. package/dist/{chunk-VXFTFZ5N.js → chunk-VNRDL5RA.js} +117 -138
  10. package/dist/{chunk-7SZSQS55.js → chunk-WYF7NOAT.js} +1831 -759
  11. package/dist/cli.cjs +1757 -777
  12. package/dist/cli.d.cts +12 -0
  13. package/dist/cli.js +27 -6
  14. package/dist/dashboard/index.cjs +111 -29
  15. package/dist/dashboard/index.d.cts +185 -0
  16. package/dist/dashboard/index.d.ts +5 -3
  17. package/dist/dashboard/index.js +1 -1
  18. package/dist/drizzle/index.cjs +1757 -773
  19. package/dist/drizzle/index.d.cts +46 -0
  20. package/dist/drizzle/index.d.ts +2 -2
  21. package/dist/drizzle/index.js +1 -1
  22. package/dist/edge/index.cjs +280 -153
  23. package/dist/edge/index.d.cts +127 -0
  24. package/dist/edge/index.d.ts +3 -3
  25. package/dist/edge/index.js +254 -147
  26. package/dist/hono/index.cjs +1805 -793
  27. package/dist/hono/index.d.cts +93 -0
  28. package/dist/hono/index.d.ts +7 -5
  29. package/dist/hono/index.js +16 -9
  30. package/dist/{hono-DuNvciyq.d.ts → hono-3rDMYVtY.d.ts} +23 -3
  31. package/dist/hono-C886ok3X.d.cts +391 -0
  32. package/dist/http/index.cjs +1946 -842
  33. package/dist/http/index.d.cts +103 -0
  34. package/dist/http/index.d.ts +13 -5
  35. package/dist/http/index.js +137 -57
  36. package/dist/index.cjs +2073 -937
  37. package/dist/index.d.cts +1006 -0
  38. package/dist/index.d.ts +40 -8
  39. package/dist/index.js +8 -8
  40. package/dist/murmur3-CMGw9PbV.d.cts +98 -0
  41. package/dist/nestjs/index.cjs +1849 -806
  42. package/dist/nestjs/index.d.cts +285 -0
  43. package/dist/nestjs/index.d.ts +103 -30
  44. package/dist/nestjs/index.js +115 -32
  45. package/dist/next/index.cjs +1913 -887
  46. package/dist/next/index.d.cts +232 -0
  47. package/dist/next/index.d.ts +33 -11
  48. package/dist/next/index.js +174 -107
  49. package/dist/prisma/index.cjs +11 -1
  50. package/dist/prisma/index.d.cts +62 -0
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +11 -1
  53. package/dist/serialize-worker.d.cts +2 -0
  54. package/dist/{types-5HXqBfAf.d.ts → types-BA4pz1A0.d.cts} +26 -9
  55. package/dist/types-BA4pz1A0.d.ts +1519 -0
  56. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  57. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  58. package/package.json +96 -36
  59. package/src/adapters/auto-pipeliner.ts +107 -24
  60. package/src/adapters/node-redis.ts +123 -25
  61. package/src/cache-service.ts +1238 -659
  62. package/src/cli.ts +24 -6
  63. package/src/cross-region.ts +21 -3
  64. package/src/dashboard/handler.ts +26 -6
  65. package/src/dashboard/html.ts +35 -10
  66. package/src/dashboard/index.ts +35 -13
  67. package/src/dashboard/types.ts +3 -1
  68. package/src/disk-tier.ts +171 -65
  69. package/src/edge/cache.ts +202 -129
  70. package/src/edge/hono.ts +23 -6
  71. package/src/edge/types.ts +2 -0
  72. package/src/hono/index.ts +19 -9
  73. package/src/http/express.ts +110 -26
  74. package/src/http/fastify.ts +38 -28
  75. package/src/http/utils.ts +54 -20
  76. package/src/ipc-telemetry.ts +35 -9
  77. package/src/nestjs/decorators.ts +1 -1
  78. package/src/nestjs/index.ts +2 -0
  79. package/src/nestjs/keyv-adapter.ts +68 -0
  80. package/src/nestjs/tricache.module.ts +13 -11
  81. package/src/nestjs/tricache.store.ts +51 -20
  82. package/src/nestjs/types.ts +29 -15
  83. package/src/next/cache-handler.ts +132 -57
  84. package/src/next/index.ts +1 -0
  85. package/src/next/isr-handler.ts +1 -4
  86. package/src/next/types.ts +21 -0
  87. package/src/prisma/index.ts +12 -1
  88. package/src/smart-memory-cache.ts +65 -27
  89. package/src/types.ts +27 -2
  90. package/src/utils/cgroup.ts +12 -0
  91. package/src/utils/deadline.ts +14 -0
  92. package/src/utils/diagnostics.ts +27 -0
  93. package/src/utils/redis-slot.ts +13 -0
  94. package/src/wasm/bloom-filter-wasm.ts +9 -4
  95. package/src/worker-pool.ts +17 -8
  96. package/src/wtiny-lfu.ts +20 -6
  97. package/dist/chunk-BQRURGGD.js +0 -60
@@ -40,7 +40,7 @@ __export(next_exports, {
40
40
  module.exports = __toCommonJS(next_exports);
41
41
 
42
42
  // src/cache-service.ts
43
- var import_ioredis = require("ioredis");
43
+ var import_ioredis2 = require("ioredis");
44
44
 
45
45
  // src/codec.ts
46
46
  var import_msgpackr = require("msgpackr");
@@ -75,6 +75,15 @@ var defaultCodec = new CacheCodec({
75
75
  moreTypes: true
76
76
  });
77
77
 
78
+ // src/cross-region.ts
79
+ var import_node_crypto = require("crypto");
80
+ function isCrossRegionInvalidationEvent(value) {
81
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
82
+ const event = value;
83
+ const text = (key, max) => typeof event[key] === "string" && event[key].length > 0 && event[key].length <= max;
84
+ 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);
85
+ }
86
+
78
87
  // src/cache-service.ts
79
88
  var import_crypto3 = __toESM(require("crypto"), 1);
80
89
  var import_os3 = __toESM(require("os"), 1);
@@ -101,7 +110,8 @@ try {
101
110
  _workerFile = jsPath;
102
111
  }
103
112
  } catch {
104
- _workerFile = (0, import_path.join)(__dirname, "serialize-worker.js");
113
+ const sibling = (0, import_path.join)(__dirname, "serialize-worker.js");
114
+ _workerFile = (0, import_fs.existsSync)(sibling) ? sibling : (0, import_path.join)((0, import_path.dirname)(__dirname), "serialize-worker.js");
105
115
  }
106
116
  function getTransferableArrayBuffer(buf) {
107
117
  if (buf.buffer instanceof ArrayBuffer) {
@@ -134,6 +144,7 @@ var WorkerPool = class {
134
144
  }
135
145
  _spawnWorkers(opts) {
136
146
  const size = Math.max(1, opts.size ?? Math.min(4, availableCpus()));
147
+ if (!Number.isInteger(size) || size > 32 || !(0, import_fs.existsSync)(_workerFile)) throw new Error("Worker pool unavailable or invalid worker count");
137
148
  const workerData = {
138
149
  keyBase64: opts.keyBase64,
139
150
  mode: opts.mode,
@@ -147,7 +158,8 @@ var WorkerPool = class {
147
158
  const createWorker = (index) => {
148
159
  const worker = new import_worker_threads.Worker(_workerFile, {
149
160
  workerData,
150
- execArgv: _workerExecArgv.length > 0 ? _workerExecArgv : void 0
161
+ execArgv: _workerExecArgv
162
+ // Do not inherit --input-type/eval or application loader flags.
151
163
  });
152
164
  const pending = pendingList[index] ?? /* @__PURE__ */ new Map();
153
165
  if (!pendingList[index]) pendingList[index] = pending;
@@ -177,7 +189,7 @@ var WorkerPool = class {
177
189
  }
178
190
  pending.clear();
179
191
  worker.unref();
180
- if (this._available && exitCode !== 0 && workers[index] === worker) {
192
+ if (this._available && this.workers === workers && workers[index] === worker) {
181
193
  try {
182
194
  workers[index] = createWorker(index);
183
195
  } catch {
@@ -187,9 +199,12 @@ var WorkerPool = class {
187
199
  worker.unref();
188
200
  return worker;
189
201
  };
190
- for (let i = 0; i < size; i++) {
191
- const worker = createWorker(i);
192
- workers.push(worker);
202
+ try {
203
+ for (let i = 0; i < size; i++) workers.push(createWorker(i));
204
+ } catch (error) {
205
+ for (const worker of workers) void worker.terminate().catch(() => {
206
+ });
207
+ throw error;
193
208
  }
194
209
  return { workers, pending: pendingList };
195
210
  }
@@ -216,7 +231,7 @@ var WorkerPool = class {
216
231
  entry.reject(new Error("WorkerPool replaced during key rotation"));
217
232
  }
218
233
  oldPending[i]?.clear();
219
- oldWorkers[i]?.terminate().catch(() => {
234
+ await oldWorkers[i]?.terminate().catch(() => {
220
235
  });
221
236
  }
222
237
  }
@@ -258,7 +273,13 @@ var WorkerPool = class {
258
273
  return new Promise((resolve, reject) => {
259
274
  pending.set(id, { resolve, reject });
260
275
  worker.ref();
261
- worker.postMessage({ id, type, payload: dataToSend }, transferList);
276
+ try {
277
+ worker.postMessage({ id, type, payload: dataToSend }, transferList);
278
+ } catch (error) {
279
+ pending.delete(id);
280
+ if (pending.size === 0) worker.unref();
281
+ reject(error);
282
+ }
262
283
  });
263
284
  }
264
285
  /** Terminate all worker threads. In-flight promises are rejected. */
@@ -769,8 +790,9 @@ var EnvelopeEncryption = class {
769
790
 
770
791
  // src/wtiny-lfu.ts
771
792
  var WTinyLfuPolicy = class {
772
- constructor(capacity, sketch, windowPercent = 0.01, protectedPercent = 0.8) {
793
+ constructor(capacity, sketch, windowPercent = 0.01, protectedPercent = 0.8, canEvict) {
773
794
  this.sketch = sketch;
795
+ this.canEvict = canEvict;
774
796
  this.maxTotal = Math.max(2, capacity);
775
797
  this.maxWindow = Math.max(1, Math.floor(this.maxTotal * windowPercent));
776
798
  const mainCapacity = Math.max(1, this.maxTotal - this.maxWindow);
@@ -778,6 +800,7 @@ var WTinyLfuPolicy = class {
778
800
  this.maxProbation = Math.max(1, mainCapacity - this.maxProtected);
779
801
  }
780
802
  sketch;
803
+ canEvict;
781
804
  maxTotal;
782
805
  maxWindow;
783
806
  maxProtected;
@@ -857,15 +880,33 @@ var WTinyLfuPolicy = class {
857
880
  }
858
881
  let victimKey;
859
882
  let victimIsProbation = true;
860
- if (this.probation.size > 0) {
861
- victimKey = this.probation.values().next().value;
862
- } else {
863
- victimKey = this.protected_.values().next().value;
883
+ for (const candidate of this.probation) {
884
+ if (!this.canEvict || this.canEvict(candidate)) {
885
+ victimKey = candidate;
886
+ break;
887
+ }
888
+ }
889
+ if (victimKey === void 0) {
890
+ for (const candidate of this.protected_) {
891
+ if (!this.canEvict || this.canEvict(candidate)) {
892
+ victimKey = candidate;
893
+ break;
894
+ }
895
+ }
864
896
  victimIsProbation = false;
865
897
  }
898
+ if (victimKey === void 0) {
899
+ if (this.canEvict && !this.canEvict(candKey)) {
900
+ this.window.delete(key);
901
+ this.window.add(candKey);
902
+ return { admit: false, candidateKey: key };
903
+ }
904
+ this.rejectionCount++;
905
+ return { admit: false, candidateKey: candKey };
906
+ }
866
907
  const candFreq = this.sketch.estimate(candKey);
867
908
  const victimFreq = this.sketch.estimate(victimKey);
868
- if (candFreq > victimFreq) {
909
+ if (this.canEvict && !this.canEvict(candKey) || candFreq > victimFreq) {
869
910
  if (victimIsProbation) {
870
911
  this.probation.delete(victimKey);
871
912
  } else {
@@ -939,9 +980,12 @@ function base64ToUint8Array(base64) {
939
980
  var BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
940
981
  var KEY_STAGING_OFFSET = 2e4;
941
982
  var MAX_KEY_BYTES = 512;
942
- var BLOOM_WASM_MODULE = new WebAssembly.Module(
943
- base64ToUint8Array(BLOOM_WASM_BASE64)
944
- );
983
+ var bloomWasmModule;
984
+ function getBloomWasmModule() {
985
+ return bloomWasmModule ??= new WebAssembly.Module(
986
+ base64ToUint8Array(BLOOM_WASM_BASE64)
987
+ );
988
+ }
945
989
  var WasmBloomFilter = class {
946
990
  exports;
947
991
  mem;
@@ -953,7 +997,7 @@ var WasmBloomFilter = class {
953
997
  /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
954
998
  _insertionCount = 0;
955
999
  constructor() {
956
- const instance = new WebAssembly.Instance(BLOOM_WASM_MODULE, {});
1000
+ const instance = new WebAssembly.Instance(getBloomWasmModule(), {});
957
1001
  this.exports = instance.exports;
958
1002
  this.mem = new Uint8Array(this.exports.memory.buffer);
959
1003
  this.stagingTarget = new Uint8Array(this.exports.memory.buffer, KEY_STAGING_OFFSET, MAX_KEY_BYTES);
@@ -1085,8 +1129,9 @@ var JsBloomFilter = class {
1085
1129
  };
1086
1130
  function createBloomFilter(logger, maxEntries) {
1087
1131
  const LN2_SQ = Math.LN2 * Math.LN2;
1088
- const optimalBits = Math.ceil(-maxEntries * Math.log(0.01) / LN2_SQ);
1089
- const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / maxEntries)));
1132
+ const capacity = Math.max(1, maxEntries);
1133
+ const optimalBits = Math.ceil(-capacity * Math.log(0.01) / LN2_SQ);
1134
+ const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / capacity)));
1090
1135
  try {
1091
1136
  const wasm = new WasmBloomFilter();
1092
1137
  if (wasm.maxCapacity >= maxEntries) {
@@ -1210,7 +1255,10 @@ var SmartMemoryCache = class {
1210
1255
  this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
1211
1256
  this.categoryPrefixes = Object.keys(opts.categories).filter((k) => k !== "default");
1212
1257
  if (opts.admissionPolicy === "wtinylfu") {
1213
- this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch);
1258
+ this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch, 0.01, 0.8, (key) => {
1259
+ const entry = this.cache.get(key);
1260
+ return !entry || entry.priority !== 4 || entry.expiresAt <= Date.now();
1261
+ });
1214
1262
  }
1215
1263
  if (existing) {
1216
1264
  for (const [k, v] of existing) this.cache.set(k, v);
@@ -1289,6 +1337,7 @@ var SmartMemoryCache = class {
1289
1337
  const MAX_EVICT_PASSES = 64;
1290
1338
  let passes = 0;
1291
1339
  do {
1340
+ const before = this.cache.size;
1292
1341
  this.smartEvict(category, catOvf);
1293
1342
  const lim2 = this.getCategoryLimit(category);
1294
1343
  const catCnt2 = this.categoryCount.get(category) ?? 0;
@@ -1296,6 +1345,7 @@ var SmartMemoryCache = class {
1296
1345
  catOvf = catCnt2 >= lim2.maxEntries || catSz2 + neededSize > lim2.maxSizeBytes;
1297
1346
  glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
1298
1347
  passes++;
1348
+ if (this.cache.size === before) break;
1299
1349
  } while ((catOvf || glbOvf) && passes < MAX_EVICT_PASSES);
1300
1350
  }
1301
1351
  score(entry, catBonus, now, key) {
@@ -1426,20 +1476,26 @@ var SmartMemoryCache = class {
1426
1476
  delta: entry.delta,
1427
1477
  fetchedAt: now,
1428
1478
  tagVersions: entry.tagVersions,
1429
- setAt: entry.setAt
1479
+ setAt: entry.setAt,
1480
+ tags: entry.tags,
1481
+ dependsOn: entry.dependsOn
1430
1482
  };
1431
1483
  return hit;
1432
1484
  }
1433
- set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
1485
+ set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions, setAt, tags, dependsOn) {
1434
1486
  const packed = this.codec.encode(data);
1487
+ return this.storePacked(key, packed, data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn);
1488
+ }
1489
+ storePacked(key, packed, data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn) {
1435
1490
  const size = packed.byteLength;
1436
1491
  this.compressions++;
1437
1492
  this.sketch.increment(key);
1438
1493
  const cat = this.getCategory(key);
1439
1494
  const lim = this.getCategoryLimit(cat);
1440
- if (size > lim.maxSizeBytes * 0.5) {
1495
+ if (!Number.isFinite(ttlMs) || ttlMs <= 0 || this.opts.maxEntries <= 0 || lim.maxEntries <= 0 || size > this.opts.maxBytes || size > lim.maxSizeBytes * 0.5) {
1496
+ this.delete(key);
1441
1497
  this.opts.logger.debug("SmartMemoryCache: entry too large, skipping", { key, sizeBytes: size });
1442
- return;
1498
+ return false;
1443
1499
  }
1444
1500
  const existingEntry = this.cache.get(key);
1445
1501
  if (existingEntry) {
@@ -1467,11 +1523,13 @@ var SmartMemoryCache = class {
1467
1523
  priority,
1468
1524
  ttlMs,
1469
1525
  delta,
1470
- setAt: now2,
1471
- tagVersions
1526
+ setAt: setAt ?? now2,
1527
+ tagVersions,
1528
+ tags,
1529
+ dependsOn
1472
1530
  });
1473
1531
  }
1474
- return;
1532
+ return false;
1475
1533
  } else if (decision.candidateKey) {
1476
1534
  const candEntry = this.cache.get(decision.candidateKey);
1477
1535
  if (candEntry && this.opts.diskSpill) {
@@ -1487,15 +1545,19 @@ var SmartMemoryCache = class {
1487
1545
  this._delete(decision.evictKey, "capacity");
1488
1546
  }
1489
1547
  const catSz = this.categorySize.get(cat) ?? 0;
1490
- if (catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
1548
+ if ((this.categoryCount.get(cat) ?? 0) >= lim.maxEntries || this.cache.size >= this.opts.maxEntries || catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
1491
1549
  this.ensureCapacity(cat, size);
1492
1550
  }
1493
1551
  } else {
1494
1552
  this.ensureCapacity(cat, size);
1495
1553
  }
1554
+ 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) {
1555
+ this.wtinyPolicy?.onDelete(key);
1556
+ return false;
1557
+ }
1496
1558
  const now = Date.now();
1497
1559
  const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
1498
- this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: now, tagVersions });
1560
+ 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 });
1499
1561
  if (!existingEntry) this.bloom.add(key);
1500
1562
  this.maybeRebuildBloom();
1501
1563
  this.totalSize += size;
@@ -1507,6 +1569,7 @@ var SmartMemoryCache = class {
1507
1569
  this.categoryKeys.set(cat, ks);
1508
1570
  }
1509
1571
  ks.add(key);
1572
+ return true;
1510
1573
  }
1511
1574
  delete(key) {
1512
1575
  const deleted = this._delete(key, "manual");
@@ -1708,25 +1771,48 @@ var SmartMemoryCache = class {
1708
1771
  if (entry.expiresAt <= now) continue;
1709
1772
  if (entry.priority === 4) continue;
1710
1773
  if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
1711
- out.push({ key, entry: { ...entry } });
1774
+ const { value: _value, ...stored } = entry;
1775
+ out.push({ key, entry: { ...stored } });
1712
1776
  }
1713
1777
  return out;
1714
1778
  }
1715
1779
  importEntries(entries, forbiddenPrefixes) {
1716
1780
  const now = Date.now();
1717
1781
  let loaded = 0;
1718
- for (const { key, entry } of entries) {
1719
- if (entry.expiresAt <= now) continue;
1782
+ for (const item of entries) {
1783
+ if (!item || typeof item.key !== "string" || !item.entry) continue;
1784
+ const { key, entry } = item;
1785
+ if (!Number.isFinite(entry.expiresAt) || entry.expiresAt <= now) continue;
1720
1786
  if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
1721
1787
  if (this.cache.has(key)) continue;
1722
- const rawData = entry.data;
1723
- const data = !entry.isCompressed ? this.codec.encode(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
1724
- const value = entry.size <= LARGE_VALUE_BYTES ? this.codec.decode(data) : void 0;
1725
- this.cache.set(key, { ...entry, data, value, isCompressed: true });
1726
- this.bloom.add(key);
1727
- loaded++;
1728
- }
1729
- this.recalculateStats();
1788
+ try {
1789
+ const rawData = entry.data;
1790
+ const data = !entry.isCompressed ? this.codec.encode(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : null;
1791
+ if (!data) continue;
1792
+ const value = data.length <= LARGE_VALUE_BYTES ? this.codec.decode(data) : void 0;
1793
+ if (this.storePacked(
1794
+ key,
1795
+ data,
1796
+ value,
1797
+ entry.expiresAt - now,
1798
+ entry.priority,
1799
+ entry.staleAt,
1800
+ entry.delta,
1801
+ entry.tagVersions,
1802
+ entry.setAt,
1803
+ entry.tags,
1804
+ entry.dependsOn
1805
+ )) {
1806
+ const restored = this.cache.get(key);
1807
+ restored.expiresAt = entry.expiresAt;
1808
+ restored.ttlMs = entry.ttlMs ?? entry.expiresAt - now;
1809
+ restored.hits = Number.isFinite(entry.hits) ? Math.max(1, entry.hits) : 1;
1810
+ restored.lastAccess = Number.isFinite(entry.lastAccess) ? entry.lastAccess : now;
1811
+ loaded++;
1812
+ }
1813
+ } catch {
1814
+ }
1815
+ }
1730
1816
  return loaded;
1731
1817
  }
1732
1818
  // ── Iterators ─────────────────────────────────────────────────────────────
@@ -2090,6 +2176,9 @@ var BoundedDiskQueue = class {
2090
2176
  this.writeTimeoutMs = writeTimeoutMs;
2091
2177
  this.failureThreshold = failureThreshold;
2092
2178
  this.cooldownMs = cooldownMs;
2179
+ 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) {
2180
+ throw new Error("Disk queue limits and timeout must be finite positive values (pending/cooldown may be zero)");
2181
+ }
2093
2182
  }
2094
2183
  maxConcurrent;
2095
2184
  maxPending;
@@ -2102,6 +2191,17 @@ var BoundedDiskQueue = class {
2102
2191
  consecutiveFailures = 0;
2103
2192
  circuitState = "closed";
2104
2193
  lastStateChangeMonotonic = performance.now();
2194
+ get isSaturated() {
2195
+ return this.active >= this.maxConcurrent && this.queue.length >= this.maxPending;
2196
+ }
2197
+ releaseSlot() {
2198
+ if (this.circuitState === "open") {
2199
+ for (const next2 of this.queue.splice(0)) next2(false);
2200
+ }
2201
+ const next = this.queue.shift();
2202
+ if (next) next(true);
2203
+ else this.active--;
2204
+ }
2105
2205
  async schedule(task) {
2106
2206
  const now = performance.now();
2107
2207
  if (this.circuitState === "open") {
@@ -2117,18 +2217,25 @@ var BoundedDiskQueue = class {
2117
2217
  this.spillsDropped++;
2118
2218
  return null;
2119
2219
  }
2120
- if (this.queue.length >= this.maxPending) {
2220
+ if (this.isSaturated) {
2121
2221
  this.spillsDropped++;
2122
2222
  return null;
2123
2223
  }
2124
2224
  if (this.active >= this.maxConcurrent) {
2125
- await new Promise((resolve) => this.queue.push(resolve));
2225
+ const admitted = await new Promise((resolve) => this.queue.push(resolve));
2226
+ if (!admitted) {
2227
+ this.spillsDropped++;
2228
+ return null;
2229
+ }
2230
+ } else {
2231
+ this.active++;
2126
2232
  }
2127
- this.active++;
2128
2233
  let timeoutId = null;
2234
+ const work = Promise.resolve().then(task);
2235
+ void work.then(() => this.releaseSlot(), () => this.releaseSlot());
2129
2236
  try {
2130
2237
  const result = await Promise.race([
2131
- task(),
2238
+ work,
2132
2239
  new Promise((_, reject) => {
2133
2240
  timeoutId = setTimeout(
2134
2241
  () => reject(new Error(`Disk write exceeded timeout of ${this.writeTimeoutMs}ms`)),
@@ -2147,14 +2254,12 @@ var BoundedDiskQueue = class {
2147
2254
  if (this.consecutiveFailures >= this.failureThreshold || this.circuitState === "half-open") {
2148
2255
  this.circuitState = "open";
2149
2256
  this.lastStateChangeMonotonic = performance.now();
2257
+ for (const next of this.queue.splice(0)) next(false);
2150
2258
  }
2151
2259
  this.spillsDropped++;
2152
2260
  return null;
2153
2261
  } finally {
2154
2262
  if (timeoutId) clearTimeout(timeoutId);
2155
- this.active--;
2156
- const next = this.queue.shift();
2157
- if (next) next();
2158
2263
  }
2159
2264
  }
2160
2265
  getStats() {
@@ -2228,6 +2333,13 @@ var DiskTier = class {
2228
2333
  usageCounted = false;
2229
2334
  fileCount = 0;
2230
2335
  // maintained in-memory; avoids walkCacheFiles() in stats
2336
+ reservedBytes = 0;
2337
+ reservedFiles = 0;
2338
+ saveSequence = 0;
2339
+ epoch = 0;
2340
+ pendingSaves = /* @__PURE__ */ new Map();
2341
+ closed = false;
2342
+ invalidatedKeys = /* @__PURE__ */ new Set();
2231
2343
  /** Next bucket index (0–255) for the staggered janitor wheel. */
2232
2344
  _nextJanitorBucket = 0;
2233
2345
  // ── High-watermark pruning & host volume health state ─────────────────────
@@ -2268,6 +2380,7 @@ var DiskTier = class {
2268
2380
  }
2269
2381
  // ── Helpers ───────────────────────────────────────────────────────────────
2270
2382
  ensureDir() {
2383
+ if (this.closed) return;
2271
2384
  if (this.dirReady) return;
2272
2385
  try {
2273
2386
  import_fs2.default.mkdirSync(this.opts.dir, { recursive: true, mode: 448 });
@@ -2389,8 +2502,24 @@ var DiskTier = class {
2389
2502
  *
2390
2503
  * 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
2391
2504
  */
2392
- hashToWritePath(hash, expiresAt) {
2393
- return import_path2.default.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiresAt.toString(16).padStart(12, "0")}`);
2505
+ hashToWritePath(hash, expiresAt, setAt) {
2506
+ const expiry = Math.floor(expiresAt).toString(16).padStart(12, "0");
2507
+ if (setAt === void 0) return import_path2.default.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}`);
2508
+ const written = Math.floor(setAt).toString(16).padStart(12, "0");
2509
+ const sequence = (++this.saveSequence).toString(16).padStart(12, "0");
2510
+ return import_path2.default.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}_${written}_${sequence}_${import_crypto2.default.randomBytes(6).toString("hex")}`);
2511
+ }
2512
+ findFilePaths(hash) {
2513
+ const bucket = import_path2.default.join(this.opts.dir, hash.slice(0, 2));
2514
+ try {
2515
+ return import_fs2.default.readdirSync(bucket).filter((file) => !file.endsWith(".tmp") && (file === hash || file.startsWith(hash + "_"))).map((file) => import_path2.default.join(bucket, file));
2516
+ } catch {
2517
+ return [];
2518
+ }
2519
+ }
2520
+ fileWrittenAt(file) {
2521
+ const parts = import_path2.default.basename(file).split("_");
2522
+ return parts.length >= 4 ? parseInt(parts[2], 16) : import_fs2.default.statSync(file).mtimeMs;
2394
2523
  }
2395
2524
  /**
2396
2525
  * Find the on-disk file for a key hash, handling all filename generations:
@@ -2399,19 +2528,31 @@ var DiskTier = class {
2399
2528
  * Returns null when the bucket dir does not exist or the key is absent.
2400
2529
  */
2401
2530
  findFilePath(hash) {
2402
- const bucketPath = import_path2.default.join(this.opts.dir, hash.slice(0, 2));
2403
- let files;
2531
+ let match = null;
2532
+ let newest = -Infinity;
2533
+ let sequence = -1;
2534
+ for (const file of this.findFilePaths(hash)) {
2535
+ try {
2536
+ const written = this.fileWrittenAt(file);
2537
+ const order = parseInt(import_path2.default.basename(file).split("_")[3] ?? "0", 16);
2538
+ if (written > newest || written === newest && order > sequence) {
2539
+ match = file;
2540
+ newest = written;
2541
+ sequence = order;
2542
+ }
2543
+ } catch {
2544
+ }
2545
+ }
2546
+ return match;
2547
+ }
2548
+ removeFile(filePath) {
2404
2549
  try {
2405
- files = import_fs2.default.readdirSync(bucketPath);
2550
+ const size = import_fs2.default.statSync(filePath).size;
2551
+ import_fs2.default.unlinkSync(filePath);
2552
+ this.diskUsageBytes = Math.max(0, this.diskUsageBytes - size);
2553
+ this.fileCount = Math.max(0, this.fileCount - 1);
2406
2554
  } catch {
2407
- return null;
2408
- }
2409
- let match;
2410
- for (const f of files) {
2411
- if ((f === hash || f.startsWith(hash + "_")) && (!match || f > match)) match = f;
2412
2555
  }
2413
- if (!match) return null;
2414
- return import_path2.default.join(bucketPath, match);
2415
2556
  }
2416
2557
  /**
2417
2558
  * Recursively list all cache file paths across the 2-level sharded subdirs.
@@ -2486,6 +2627,7 @@ var DiskTier = class {
2486
2627
  * so the Node.js event loop is never stalled waiting for disk I/O.
2487
2628
  */
2488
2629
  async save(key, entry) {
2630
+ if (this.closed || this.diskQueue.isSaturated) return;
2489
2631
  if (this.isForbidden(key)) return;
2490
2632
  if (entry.expiresAt <= Date.now()) return;
2491
2633
  this.ensureDir();
@@ -2494,7 +2636,7 @@ var DiskTier = class {
2494
2636
  if (++this._writeCounter % 2e3 === 0) {
2495
2637
  this.checkHostVolumeHealth();
2496
2638
  }
2497
- if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes >= this.opts.maxBytes) {
2639
+ if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes + this.reservedBytes >= this.opts.maxBytes) {
2498
2640
  this._spillsShedTotal++;
2499
2641
  return;
2500
2642
  }
@@ -2503,11 +2645,12 @@ var DiskTier = class {
2503
2645
  }
2504
2646
  let final;
2505
2647
  try {
2648
+ const { value: _value, ...storedEntry } = entry;
2506
2649
  const payload = {
2507
2650
  version: DISK_TIER_VERSION,
2508
2651
  key,
2509
2652
  entry: {
2510
- ...entry,
2653
+ ...storedEntry,
2511
2654
  data: entry.data instanceof Uint8Array ? Buffer.from(entry.data) : entry.data
2512
2655
  },
2513
2656
  writtenAt: Date.now()
@@ -2520,24 +2663,46 @@ var DiskTier = class {
2520
2663
  }
2521
2664
  const header = Buffer.allocUnsafe(V2_HEADER_LEN);
2522
2665
  DISK_MAGIC_V2.copy(header, 0);
2523
- header.writeBigUInt64LE(BigInt(entry.expiresAt), 8);
2666
+ header.writeBigUInt64LE(BigInt(Math.floor(entry.expiresAt)), 8);
2524
2667
  final = Buffer.concat([header, this.encryptV2(toEncrypt)]);
2668
+ if (final.length > this.opts.entryMaxBytes || this.diskUsageBytes + this.reservedBytes + final.length > this.opts.maxBytes) return;
2525
2669
  } catch (err) {
2526
2670
  this.opts.logger.debug("DiskTier: pack/encrypt failed", { key: key.slice(0, 50), error: err.message });
2527
2671
  return;
2528
2672
  }
2529
2673
  const hash = this.keyToHash(key);
2530
- const filePath = this.hashToWritePath(hash, entry.expiresAt);
2674
+ const setAt = entry.setAt ?? Date.now();
2675
+ if ((this.pendingSaves.get(key)?.setAt ?? 0) > setAt) return;
2676
+ const filePath = this.hashToWritePath(hash, entry.expiresAt, setAt);
2531
2677
  const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${import_crypto2.default.randomBytes(6).toString("hex")}.tmp`;
2532
- this.diskUsageBytes += final.length;
2533
- this.fileCount++;
2678
+ const token = Symbol(key);
2679
+ const epoch = this.epoch;
2680
+ this.pendingSaves.set(key, { token, setAt });
2681
+ const current = () => !this.closed && this.epoch === epoch && this.pendingSaves.get(key)?.token === token;
2682
+ let started = false;
2683
+ let released = false;
2684
+ let accounted = false;
2685
+ const releaseReservation = () => {
2686
+ if (released) return;
2687
+ released = true;
2688
+ this.reservedBytes = Math.max(0, this.reservedBytes - final.length);
2689
+ this.reservedFiles = Math.max(0, this.reservedFiles - 1);
2690
+ if (this.pendingSaves.get(key)?.token === token) this.pendingSaves.delete(key);
2691
+ };
2692
+ this.reservedBytes += final.length;
2693
+ this.reservedFiles++;
2534
2694
  if (this.diskUsageBytes >= this.opts.maxBytes * 0.8 && !this._isPruning) {
2535
2695
  void this.triggerChunkedPrune();
2536
2696
  }
2537
2697
  const result = await this.diskQueue.schedule(async () => {
2698
+ started = true;
2538
2699
  try {
2700
+ if (!current()) return false;
2701
+ const previous = this.findFilePath(hash);
2702
+ if (previous && this.fileWrittenAt(previous) > setAt) return false;
2539
2703
  await import_fs2.default.promises.mkdir(import_path2.default.dirname(filePath), { recursive: true });
2540
2704
  await import_fs2.default.promises.writeFile(tmpPath, final, { mode: 384 });
2705
+ if (!current()) return false;
2541
2706
  try {
2542
2707
  await import_fs2.default.promises.rename(tmpPath, filePath);
2543
2708
  } catch (renameErr) {
@@ -2549,6 +2714,20 @@ var DiskTier = class {
2549
2714
  throw renameErr;
2550
2715
  }
2551
2716
  }
2717
+ if (!current()) {
2718
+ try {
2719
+ await import_fs2.default.promises.unlink(filePath);
2720
+ } catch {
2721
+ }
2722
+ return false;
2723
+ }
2724
+ for (const previousPath of this.findFilePaths(hash)) {
2725
+ if (previousPath !== filePath) this.removeFile(previousPath);
2726
+ }
2727
+ this.diskUsageBytes += final.length;
2728
+ this.fileCount++;
2729
+ accounted = true;
2730
+ this.invalidatedKeys.delete(key);
2552
2731
  if (this._db) {
2553
2732
  const priority = typeof entry.priority === "number" ? entry.priority : 2;
2554
2733
  const lastAccess = typeof entry.lastAccess === "number" ? entry.lastAccess : Date.now();
@@ -2561,23 +2740,25 @@ var DiskTier = class {
2561
2740
  await import_fs2.default.promises.unlink(tmpPath);
2562
2741
  } catch {
2563
2742
  }
2564
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
2565
- this.fileCount = Math.max(0, this.fileCount - 1);
2566
- if (this._db) try {
2567
- this._stmtDelete.run(hash);
2568
- } catch {
2569
- }
2743
+ if (accounted) this.removeFile(filePath);
2570
2744
  this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
2571
2745
  throw err;
2746
+ } finally {
2747
+ try {
2748
+ await import_fs2.default.promises.unlink(tmpPath);
2749
+ } catch {
2750
+ }
2751
+ releaseReservation();
2752
+ if (this.invalidatedKeys.has(key) && !this.pendingSaves.has(key)) this.delete(key, true);
2572
2753
  }
2573
2754
  });
2574
- if (result === null) {
2575
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
2576
- this.fileCount = Math.max(0, this.fileCount - 1);
2755
+ if (result === null && !started) {
2756
+ releaseReservation();
2577
2757
  }
2578
2758
  }
2579
2759
  /** Load a key from disk, or return null on miss/expiry/corruption. */
2580
2760
  load(key) {
2761
+ if (this.invalidatedKeys.has(key) || this.closed) return null;
2581
2762
  if (this.isForbidden(key)) return null;
2582
2763
  this.ensureDir();
2583
2764
  if (!this.dirReady) return null;
@@ -2605,8 +2786,8 @@ var DiskTier = class {
2605
2786
  try {
2606
2787
  if (!this._db) {
2607
2788
  const filename = import_path2.default.basename(filePath);
2608
- if (filename.length === 77 && filename[64] === "_") {
2609
- const expiresAt = parseInt(filename.slice(65), 16);
2789
+ if (filename.length >= 77 && filename[64] === "_") {
2790
+ const expiresAt = parseInt(filename.slice(65, 77), 16);
2610
2791
  if (expiresAt <= Date.now()) {
2611
2792
  try {
2612
2793
  const sz = import_fs2.default.statSync(filePath).size;
@@ -2627,12 +2808,7 @@ var DiskTier = class {
2627
2808
  return null;
2628
2809
  }
2629
2810
  const raw = import_fs2.default.readFileSync(filePath);
2630
- try {
2631
- import_fs2.default.unlinkSync(filePath);
2632
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
2633
- this.fileCount = Math.max(0, this.fileCount - 1);
2634
- } catch {
2635
- }
2811
+ for (const storedPath of this.findFilePaths(hash)) this.removeFile(storedPath);
2636
2812
  if (this._db) this._stmtDelete.run(hash);
2637
2813
  let decrypted;
2638
2814
  if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
@@ -2667,25 +2843,24 @@ var DiskTier = class {
2667
2843
  return null;
2668
2844
  }
2669
2845
  }
2670
- /** Explicitly delete a key from disk (cache invalidation). */
2671
- delete(key) {
2846
+ /** Synchronously fence queued/running saves while leaving filesystem cleanup deferred. */
2847
+ invalidate(key) {
2848
+ this.pendingSaves.delete(key);
2849
+ this.invalidatedKeys.add(key);
2850
+ }
2851
+ /** Delete all versions; deferred cleanup must not cancel a newer save. */
2852
+ delete(key, invalidatedOnly = false) {
2853
+ if (invalidatedOnly && (!this.invalidatedKeys.has(key) || this.pendingSaves.has(key))) return;
2854
+ if (!invalidatedOnly) this.pendingSaves.delete(key);
2672
2855
  const hash = this.keyToHash(key);
2673
- let filePath;
2856
+ const files = new Set(this.findFilePaths(hash));
2674
2857
  if (this._db) {
2675
2858
  const row = this._stmtSelect.get(hash);
2676
- filePath = row?.file_path ?? null;
2859
+ if (row?.file_path) files.add(row.file_path);
2677
2860
  this._stmtDelete.run(hash);
2678
- } else {
2679
- filePath = this.findFilePath(hash);
2680
- }
2681
- if (!filePath) return;
2682
- try {
2683
- const stat = import_fs2.default.statSync(filePath);
2684
- import_fs2.default.unlinkSync(filePath);
2685
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
2686
- this.fileCount = Math.max(0, this.fileCount - 1);
2687
- } catch {
2688
2861
  }
2862
+ for (const file of files) this.removeFile(file);
2863
+ this.invalidatedKeys.delete(key);
2689
2864
  }
2690
2865
  /** Purge all expired entries. Returns number deleted. */
2691
2866
  purgeExpired() {
@@ -2721,8 +2896,8 @@ var DiskTier = class {
2721
2896
  }
2722
2897
  continue;
2723
2898
  }
2724
- if (filename.length === 77 && filename[64] === "_") {
2725
- const expiresAt = parseInt(filename.slice(65), 16);
2899
+ if (filename.length >= 77 && filename[64] === "_") {
2900
+ const expiresAt = parseInt(filename.slice(65, 77), 16);
2726
2901
  if (expiresAt <= now) {
2727
2902
  try {
2728
2903
  const sz = import_fs2.default.statSync(filePath).size;
@@ -2842,8 +3017,8 @@ var DiskTier = class {
2842
3017
  }
2843
3018
  continue;
2844
3019
  }
2845
- if (file.length === 77 && file[64] === "_") {
2846
- const expiresAt = parseInt(file.slice(65), 16);
3020
+ if (file.length >= 77 && file[64] === "_") {
3021
+ const expiresAt = parseInt(file.slice(65, 77), 16);
2847
3022
  if (expiresAt <= now2) {
2848
3023
  const fp = import_path2.default.join(orphanBucketP, file);
2849
3024
  try {
@@ -2883,8 +3058,8 @@ var DiskTier = class {
2883
3058
  }
2884
3059
  continue;
2885
3060
  }
2886
- if (file.length === 77 && file[64] === "_") {
2887
- const expiresAt = parseInt(file.slice(65), 16);
3061
+ if (file.length >= 77 && file[64] === "_") {
3062
+ const expiresAt = parseInt(file.slice(65, 77), 16);
2888
3063
  if (expiresAt <= now) {
2889
3064
  const filePath2 = import_path2.default.join(bucketPath, file);
2890
3065
  try {
@@ -2957,6 +3132,9 @@ var DiskTier = class {
2957
3132
  }
2958
3133
  /** Delete every file in the disk cache. Returns the count deleted. */
2959
3134
  clear() {
3135
+ this.epoch++;
3136
+ this.pendingSaves.clear();
3137
+ this.invalidatedKeys.clear();
2960
3138
  this.ensureDir();
2961
3139
  if (!this.dirReady) return 0;
2962
3140
  let cleared = 0;
@@ -3020,6 +3198,7 @@ var DiskTier = class {
3020
3198
  * yielding to the event loop via setImmediate between chunks.
3021
3199
  */
3022
3200
  async triggerChunkedPrune() {
3201
+ if (this.closed) return 0;
3023
3202
  if (this._isPruning) return 0;
3024
3203
  this._isPruning = true;
3025
3204
  this._pruneRounds++;
@@ -3028,7 +3207,7 @@ var DiskTier = class {
3028
3207
  this.ensureUsageCounted();
3029
3208
  const targetBytes = Math.floor(this.opts.maxBytes * 0.6);
3030
3209
  if (this._db && this._stmtPruneChunk) {
3031
- while (this.diskUsageBytes > targetBytes) {
3210
+ while (!this.closed && this.diskUsageBytes > targetBytes) {
3032
3211
  const rows = this._stmtPruneChunk.all();
3033
3212
  if (!rows || rows.length === 0) break;
3034
3213
  for (const row of rows) {
@@ -3051,7 +3230,7 @@ var DiskTier = class {
3051
3230
  }
3052
3231
  }
3053
3232
  } else {
3054
- while (this.diskUsageBytes > targetBytes) {
3233
+ while (!this.closed && this.diskUsageBytes > targetBytes) {
3055
3234
  const files = this.walkCacheFiles();
3056
3235
  if (files.length === 0) break;
3057
3236
  const chunk = files.slice(0, 500);
@@ -3119,6 +3298,10 @@ var DiskTier = class {
3119
3298
  }
3120
3299
  /** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
3121
3300
  close() {
3301
+ this.closed = true;
3302
+ this.epoch++;
3303
+ this.pendingSaves.clear();
3304
+ this.invalidatedKeys.clear();
3122
3305
  if (this._db) {
3123
3306
  try {
3124
3307
  this._db.close();
@@ -3361,6 +3544,17 @@ function readCgroupMemoryLimit() {
3361
3544
  }
3362
3545
  return Infinity;
3363
3546
  }
3547
+ function readCgroupMemoryUsage() {
3548
+ if (process.platform !== "linux") return null;
3549
+ for (const file of ["/sys/fs/cgroup/memory.current", "/sys/fs/cgroup/memory/memory.usage_in_bytes"]) {
3550
+ try {
3551
+ const value = Number(import_node_fs.default.readFileSync(file, "utf8").trim());
3552
+ if (Number.isFinite(value) && value >= 0) return value;
3553
+ } catch {
3554
+ }
3555
+ }
3556
+ return null;
3557
+ }
3364
3558
  function getV8HeapLimit() {
3365
3559
  try {
3366
3560
  const stats = import_node_v8.default.getHeapStatistics();
@@ -3384,7 +3578,81 @@ function resolveAutonomousL1MaxBytes(options) {
3384
3578
  return Math.max(MIN_AUTONOMOUS_L1_FLOOR_BYTES, Math.floor(resolved));
3385
3579
  }
3386
3580
 
3581
+ // src/utils/diagnostics.ts
3582
+ function redactDiagnostics(value, seen = /* @__PURE__ */ new WeakSet(), depth = 0) {
3583
+ if (typeof value === "string" && /^[a-z][a-z\d+.-]*:\/\//i.test(value)) {
3584
+ try {
3585
+ const url = new URL(value);
3586
+ if (url.username) url.username = "[REDACTED]";
3587
+ if (url.password) url.password = "[REDACTED]";
3588
+ for (const key of url.searchParams.keys()) {
3589
+ if (/key|token|secret|password|credential|authorization|cookie/i.test(key)) url.searchParams.set(key, "[REDACTED]");
3590
+ }
3591
+ return url.toString();
3592
+ } catch {
3593
+ return "[REDACTED URL]";
3594
+ }
3595
+ }
3596
+ if (value == null || typeof value !== "object") return typeof value === "function" ? void 0 : value;
3597
+ if (depth >= 8) return "[OMITTED]";
3598
+ if (seen.has(value)) return "[CIRCULAR]";
3599
+ seen.add(value);
3600
+ if (Array.isArray(value)) return value.map((item) => redactDiagnostics(item, seen, depth + 1));
3601
+ const result = {};
3602
+ for (const [key, item] of Object.entries(value)) {
3603
+ if (typeof item === "function") continue;
3604
+ result[key] = /key|token|secret|password|credential|authorization|cookie|headers/i.test(key) ? item == null ? item : "[REDACTED]" : redactDiagnostics(item, seen, depth + 1);
3605
+ }
3606
+ return result;
3607
+ }
3608
+
3609
+ // src/utils/redis-slot.ts
3610
+ function redisHashSlot(key) {
3611
+ const open = key.indexOf("{");
3612
+ const close = open < 0 ? -1 : key.indexOf("}", open + 1);
3613
+ const bytes = Buffer.from(close > open + 1 ? key.slice(open + 1, close) : key, "utf8");
3614
+ let crc = 0;
3615
+ for (const byte of bytes) {
3616
+ crc ^= byte << 8;
3617
+ for (let bit = 0; bit < 8; bit++) crc = crc << 1 ^ (crc & 32768 ? 4129 : 0);
3618
+ crc &= 65535;
3619
+ }
3620
+ return crc & 16383;
3621
+ }
3622
+
3623
+ // src/utils/deadline.ts
3624
+ async function withDeadline(operation, timeoutMs, label) {
3625
+ let timer;
3626
+ try {
3627
+ return await Promise.race([
3628
+ operation,
3629
+ new Promise((_resolve, reject) => {
3630
+ timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs);
3631
+ })
3632
+ ]);
3633
+ } finally {
3634
+ if (timer) clearTimeout(timer);
3635
+ }
3636
+ }
3637
+
3387
3638
  // src/adapters/auto-pipeliner.ts
3639
+ var import_ioredis = require("ioredis");
3640
+ async function readRedisValue(client, key, hash = false) {
3641
+ if (typeof client.pttl === "function" && typeof client.multi === "function") {
3642
+ const transaction = client.multi();
3643
+ if (typeof transaction.pttl === "function" && (!hash || typeof transaction.hgetall === "function")) {
3644
+ if (hash) transaction.hgetall(key);
3645
+ else transaction.get(key);
3646
+ transaction.pttl(key);
3647
+ const results = await transaction.exec();
3648
+ if (!results) throw new Error("Redis read transaction aborted");
3649
+ if (results[0]?.[0]) throw results[0][0];
3650
+ if (results[1]?.[0]) throw results[1][0];
3651
+ return { raw: results[0]?.[1] ?? null, ttlMs: Number(results[1]?.[1]) };
3652
+ }
3653
+ }
3654
+ return { raw: await (hash ? client.hgetall(key) : client.get(key)) };
3655
+ }
3388
3656
  var AutoPipeliner = class {
3389
3657
  constructor(client, options) {
3390
3658
  this.client = client;
@@ -3416,6 +3684,17 @@ var AutoPipeliner = class {
3416
3684
  this.enqueue({ type: "get", key, resolve, reject });
3417
3685
  });
3418
3686
  }
3687
+ async read(key, hash = false) {
3688
+ if (!hash && typeof this.client.pttl !== "function") return { raw: await this.get(key) };
3689
+ if (!this.enabled || !this.supportsPipelines() || typeof this.client.pttl !== "function") {
3690
+ return readRedisValue(this.client, key, hash);
3691
+ }
3692
+ const probe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
3693
+ if (typeof probe.pttl !== "function" || hash && typeof probe.hgetall !== "function") {
3694
+ return readRedisValue(this.client, key, hash);
3695
+ }
3696
+ return new Promise((resolve, reject) => this.enqueue({ type: "read", key, hash, resolve, reject }));
3697
+ }
3419
3698
  async setex(key, seconds, value) {
3420
3699
  if (!this.enabled || !this.supportsPipelines()) {
3421
3700
  if (typeof this.client.setex === "function") {
@@ -3429,8 +3708,18 @@ var AutoPipeliner = class {
3429
3708
  this.enqueue({ type: "setex", key, seconds, value, resolve, reject });
3430
3709
  });
3431
3710
  }
3711
+ async setpx(key, milliseconds, value) {
3712
+ if (!this.enabled || !this.supportsPipelines()) {
3713
+ await this.client.set(key, value, "PX", milliseconds);
3714
+ return;
3715
+ }
3716
+ return new Promise((resolve, reject) => this.enqueue({ type: "setpx", key, milliseconds, value, resolve, reject }));
3717
+ }
3432
3718
  async del(...keys) {
3433
3719
  if (keys.length === 0) return 0;
3720
+ if (this.client instanceof import_ioredis.Cluster && keys.length > 1) {
3721
+ return (await Promise.all(keys.map((key) => this.del(key)))).reduce((sum, value) => sum + value, 0);
3722
+ }
3434
3723
  if (!this.enabled || !this.supportsPipelines()) {
3435
3724
  return this.client.del(...keys);
3436
3725
  }
@@ -3464,44 +3753,72 @@ var AutoPipeliner = class {
3464
3753
  this.scheduled = false;
3465
3754
  this.statsInternal.batchesDispatched++;
3466
3755
  this.statsInternal.operationsBatched += batch.length;
3467
- const pipe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
3468
- for (const op of batch) {
3469
- switch (op.type) {
3470
- case "get":
3471
- pipe.get(op.key);
3472
- break;
3473
- case "setex":
3474
- pipe.setex(op.key, op.seconds, op.value);
3475
- break;
3476
- case "del":
3477
- pipe.del(...op.keys);
3478
- break;
3479
- }
3756
+ if (this.client instanceof import_ioredis.Cluster) {
3757
+ const groups = /* @__PURE__ */ new Map();
3758
+ for (const operation of batch) {
3759
+ const key = operation.type === "del" ? operation.keys[0] : operation.key;
3760
+ const slot = redisHashSlot(key);
3761
+ const master = this.client.slots[slot]?.[0] ?? String(slot);
3762
+ const members = groups.get(master) ?? [];
3763
+ members.push(operation);
3764
+ groups.set(master, members);
3765
+ }
3766
+ await Promise.all([...groups.values()].map((members) => this.dispatch(members)));
3767
+ return;
3480
3768
  }
3769
+ await this.dispatch(batch);
3770
+ }
3771
+ async dispatch(batch) {
3481
3772
  try {
3773
+ const pipe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
3774
+ const indexes = [];
3775
+ let commandCount = 0;
3776
+ for (const op of batch) {
3777
+ indexes.push(commandCount++);
3778
+ switch (op.type) {
3779
+ case "get":
3780
+ pipe.get(op.key);
3781
+ break;
3782
+ case "setex":
3783
+ pipe.setex(op.key, op.seconds, op.value);
3784
+ break;
3785
+ case "setpx":
3786
+ pipe.set(op.key, op.value, "PX", op.milliseconds);
3787
+ break;
3788
+ case "del":
3789
+ pipe.del(...op.keys);
3790
+ break;
3791
+ case "read":
3792
+ if (op.hash) pipe.hgetall(op.key);
3793
+ else pipe.get(op.key);
3794
+ pipe.pttl(op.key);
3795
+ commandCount++;
3796
+ break;
3797
+ }
3798
+ }
3482
3799
  const results = await pipe.exec();
3483
3800
  if (!results) {
3484
3801
  for (const op of batch) {
3485
- if (op.type === "get") op.resolve(null);
3486
- else if (op.type === "del") op.resolve(0);
3487
- else op.resolve();
3802
+ op.reject(new Error("Redis pipeline aborted"));
3488
3803
  }
3489
3804
  return;
3490
3805
  }
3491
3806
  for (let i = 0; i < batch.length; i++) {
3492
3807
  const op = batch[i];
3493
- const resTuple = results[i];
3808
+ const resTuple = results[indexes[i]];
3494
3809
  if (!resTuple) {
3495
- if (op.type === "get") op.resolve(null);
3496
- else if (op.type === "del") op.resolve(0);
3497
- else op.resolve();
3810
+ op.reject(new Error("Missing Redis pipeline result"));
3498
3811
  continue;
3499
3812
  }
3500
3813
  const [err, val] = resTuple;
3501
3814
  if (err) {
3502
3815
  op.reject(err instanceof Error ? err : new Error(String(err)));
3503
3816
  } else {
3504
- if (op.type === "get") {
3817
+ if (op.type === "read") {
3818
+ const ttlResult = results[indexes[i] + 1];
3819
+ if (!ttlResult || ttlResult[0]) op.reject(ttlResult?.[0] ?? new Error("Missing Redis PTTL result"));
3820
+ else op.resolve({ raw: val, ttlMs: Number(ttlResult[1]) });
3821
+ } else if (op.type === "get") {
3505
3822
  op.resolve(val != null ? String(val) : null);
3506
3823
  } else if (op.type === "del") {
3507
3824
  op.resolve(typeof val === "number" ? val : Number(val) || 0);
@@ -3538,6 +3855,8 @@ var IpcTelemetryServer = class {
3538
3855
  server = null;
3539
3856
  socketPath;
3540
3857
  _closed = false;
3858
+ _starting = null;
3859
+ sockets = /* @__PURE__ */ new Set();
3541
3860
  _exitHandler = null;
3542
3861
  _sigintHandler = null;
3543
3862
  _sigtermHandler = null;
@@ -3545,10 +3864,23 @@ var IpcTelemetryServer = class {
3545
3864
  * Start listening on the IPC socket / pipe.
3546
3865
  */
3547
3866
  async start() {
3548
- if (this.server && this.server.listening) return;
3867
+ if (this._closed || this.server?.listening) return;
3868
+ if (this._starting) return this._starting;
3869
+ this._starting = this.startInternal();
3870
+ try {
3871
+ await this._starting;
3872
+ } finally {
3873
+ this._starting = null;
3874
+ }
3875
+ }
3876
+ async startInternal() {
3549
3877
  if (process.platform !== "win32" && import_node_fs2.default.existsSync(this.socketPath)) {
3550
3878
  await new Promise((resolve) => {
3551
3879
  const testSocket = import_node_net.default.createConnection(this.socketPath);
3880
+ testSocket.setTimeout(1e3, () => {
3881
+ testSocket.destroy();
3882
+ resolve();
3883
+ });
3552
3884
  testSocket.once("connect", () => {
3553
3885
  testSocket.destroy();
3554
3886
  resolve();
@@ -3563,17 +3895,37 @@ var IpcTelemetryServer = class {
3563
3895
  });
3564
3896
  });
3565
3897
  }
3898
+ if (this._closed) return;
3566
3899
  this.server = import_node_net.default.createServer((socket) => {
3900
+ if (this._closed) {
3901
+ socket.destroy();
3902
+ return;
3903
+ }
3904
+ this.sockets.add(socket);
3905
+ socket.once("close", () => this.sockets.delete(socket));
3906
+ socket.setTimeout(5e3, () => socket.destroy());
3567
3907
  let buffer = "";
3908
+ let pending = 0;
3568
3909
  socket.on("data", (chunk) => {
3910
+ if (Buffer.byteLength(buffer) + chunk.length > 4096 || socket.writableLength > 65536) {
3911
+ socket.destroy();
3912
+ return;
3913
+ }
3569
3914
  buffer += chunk.toString("utf8");
3570
3915
  let newlineIndex;
3571
3916
  while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
3572
3917
  const line = buffer.slice(0, newlineIndex).trim();
3573
3918
  buffer = buffer.slice(newlineIndex + 1);
3574
3919
  if (!line) continue;
3920
+ if (++pending > 8) {
3921
+ socket.destroy();
3922
+ return;
3923
+ }
3575
3924
  setImmediate(() => {
3576
- if (socket.destroyed) return;
3925
+ if (socket.destroyed) {
3926
+ pending--;
3927
+ return;
3928
+ }
3577
3929
  try {
3578
3930
  let cmd = line;
3579
3931
  try {
@@ -3598,6 +3950,8 @@ var IpcTelemetryServer = class {
3598
3950
  if (!socket.destroyed) {
3599
3951
  socket.write(JSON.stringify({ error: err.message }) + "\n");
3600
3952
  }
3953
+ } finally {
3954
+ pending--;
3601
3955
  }
3602
3956
  });
3603
3957
  }
@@ -3605,21 +3959,38 @@ var IpcTelemetryServer = class {
3605
3959
  socket.on("error", () => {
3606
3960
  });
3607
3961
  });
3962
+ this.server.maxConnections = 128;
3608
3963
  await new Promise((resolve, reject) => {
3609
- this.server.once("error", reject);
3610
- this.server.listen(this.socketPath, () => {
3611
- this.server.removeListener("error", reject);
3964
+ const server = this.server;
3965
+ const cleanup = () => {
3966
+ server.off("error", failed);
3967
+ server.off("close", closed);
3968
+ };
3969
+ const failed = (error) => {
3970
+ cleanup();
3971
+ reject(error);
3972
+ };
3973
+ const closed = () => {
3974
+ cleanup();
3975
+ resolve();
3976
+ };
3977
+ server.once("error", failed);
3978
+ server.once("close", closed);
3979
+ server.listen(this.socketPath, () => {
3980
+ cleanup();
3612
3981
  resolve();
3613
3982
  });
3614
3983
  });
3984
+ if (this._closed) {
3985
+ if (this.server.listening) this.server.close();
3986
+ return;
3987
+ }
3615
3988
  this._exitHandler = () => this._unlinkSocket();
3616
3989
  this._sigintHandler = () => {
3617
3990
  this._unlinkSocket();
3618
- process.exit(0);
3619
3991
  };
3620
3992
  this._sigtermHandler = () => {
3621
3993
  this._unlinkSocket();
3622
- process.exit(0);
3623
3994
  };
3624
3995
  process.once("exit", this._exitHandler);
3625
3996
  process.once("SIGINT", this._sigintHandler);
@@ -3649,6 +4020,7 @@ var IpcTelemetryServer = class {
3649
4020
  _unlinkSocket() {
3650
4021
  if (this._closed) return;
3651
4022
  this._closed = true;
4023
+ for (const socket of this.sockets) socket.destroy();
3652
4024
  try {
3653
4025
  this.server?.close();
3654
4026
  } catch {
@@ -3666,6 +4038,9 @@ var IpcTelemetryServer = class {
3666
4038
  * Gracefully close the IPC telemetry server and clean up handlers and sockets.
3667
4039
  */
3668
4040
  async close() {
4041
+ this._unlinkSocket();
4042
+ await this._starting?.catch(() => {
4043
+ });
3669
4044
  if (this._exitHandler) {
3670
4045
  process.removeListener("exit", this._exitHandler);
3671
4046
  this._exitHandler = null;
@@ -3678,7 +4053,6 @@ var IpcTelemetryServer = class {
3678
4053
  process.removeListener("SIGTERM", this._sigtermHandler);
3679
4054
  this._sigtermHandler = null;
3680
4055
  }
3681
- this._unlinkSocket();
3682
4056
  return new Promise((resolve) => {
3683
4057
  if (!this.server || !this.server.listening) {
3684
4058
  resolve();
@@ -3749,6 +4123,37 @@ if currentTs and currentTs == ARGV[1] then
3749
4123
  end
3750
4124
  return 0
3751
4125
  `;
4126
+ var LUA_READ_CACHE_ENTRY = `
4127
+ local kind = redis.call('TYPE', KEYS[1]).ok
4128
+ if kind == 'string' then
4129
+ return { kind, redis.call('GET', KEYS[1]), redis.call('PTTL', KEYS[1]) }
4130
+ elseif kind == 'hash' then
4131
+ return { kind, redis.call('HGETALL', KEYS[1]), redis.call('PTTL', KEYS[1]) }
4132
+ end
4133
+ return { 'none', false, -2 }
4134
+ `;
4135
+ var LUA_MAX_TAG_VERSION = `
4136
+ local current = tonumber(redis.call('GET', KEYS[1]) or '0')
4137
+ local floor = tonumber(ARGV[1])
4138
+ if current < floor then redis.call('SET', KEYS[1], floor) return floor end
4139
+ return current
4140
+ `;
4141
+ var LUA_RECEIVE_TAG_VERSION = `
4142
+ local current = tonumber(redis.call('GET', KEYS[1]) or '0')
4143
+ local next = math.max(current + 1, tonumber(ARGV[1]))
4144
+ redis.call('SET', KEYS[1], next)
4145
+ return next
4146
+ `;
4147
+ var LUA_TOUCH_CACHE_ENTRY = `
4148
+ local kind = redis.call('TYPE', KEYS[1]).ok
4149
+ if kind == 'hash' then
4150
+ if redis.call('HGET', KEYS[1], 't') ~= ARGV[1] then return 0 end
4151
+ redis.call('HSET', KEYS[1], 'e', ARGV[2])
4152
+ elseif kind ~= 'string' then
4153
+ return 0
4154
+ end
4155
+ return redis.call('PEXPIRE', KEYS[1], ARGV[3])
4156
+ `;
3752
4157
  var SNAPSHOT_VERSION = 1;
3753
4158
  var DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
3754
4159
  var INDEFINITE_TTL_SECONDS = 31536e3;
@@ -4037,13 +4442,19 @@ var CacheService = class _CacheService {
4037
4442
  _l1Counters = /* @__PURE__ */ new Map();
4038
4443
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
4039
4444
  tagIndex = /* @__PURE__ */ new Map();
4445
+ /** Reverse index of namespaced key → { tags, expiresAt } for bounded cleanup on eviction/delete */
4446
+ keyTags = /* @__PURE__ */ new Map();
4040
4447
  /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
4041
4448
  tagVersions = /* @__PURE__ */ new Map();
4449
+ _tagRefreshEpoch = 0;
4042
4450
  /**
4043
4451
  * Dependency index: source glob pattern → Set of namespaced dependent keys.
4044
4452
  * When an exact-key delete matches a registered pattern, all dependents are cascaded.
4045
4453
  */
4046
4454
  dependencyIndex = /* @__PURE__ */ new Map();
4455
+ /** Reverse index of namespaced dependent key → source glob patterns */
4456
+ keyDependencies = /* @__PURE__ */ new Map();
4457
+ _cgroupMemoryLimit;
4047
4458
  redis = null;
4048
4459
  redisConnecting = null;
4049
4460
  cb;
@@ -4066,9 +4477,17 @@ var CacheService = class _CacheService {
4066
4477
  subClient = null;
4067
4478
  streamClient = null;
4068
4479
  _lastStreamId = "$";
4480
+ _restoredSnapshot = false;
4481
+ _backplaneAvailable = false;
4482
+ _otelCleanup = null;
4483
+ _streamRecovering = false;
4484
+ _backplaneDisposers = [];
4069
4485
  _destroyed = false;
4070
4486
  _pendingDiskDeletes = /* @__PURE__ */ new Set();
4071
4487
  _globalEpoch = 0;
4488
+ _pendingSpillCount = 0;
4489
+ _suppressSpills = false;
4490
+ _diskCleanupScheduled = false;
4072
4491
  _keyMutationEpochs = /* @__PURE__ */ new Map();
4073
4492
  /**
4074
4493
  * Pattern tombstones for disk tier.
@@ -4077,20 +4496,24 @@ var CacheService = class _CacheService {
4077
4496
  * pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
4078
4497
  */
4079
4498
  _patternTombstones = [];
4080
- _addPatternTombstone(prefix) {
4499
+ _diskInvalidatedBefore = 0;
4500
+ _addPatternTombstone(pattern) {
4081
4501
  const now = Date.now();
4082
4502
  while (this._patternTombstones.length > 0 && now - this._patternTombstones[0].createdAt > 36e5) {
4083
- this._patternTombstones.shift();
4503
+ const forgotten = this._patternTombstones.shift();
4504
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
4084
4505
  }
4085
4506
  if (this._patternTombstones.length >= 2e3) {
4086
- this._patternTombstones.shift();
4507
+ const forgotten = this._patternTombstones.shift();
4508
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
4087
4509
  }
4088
- this._patternTombstones.push({ prefix, createdAt: now });
4510
+ this._patternTombstones.push({ pattern, createdAt: now });
4089
4511
  }
4090
- _isTombstonedByPattern(namespacedKey) {
4512
+ _isTombstonedByPattern(namespacedKey, setAt = 0) {
4513
+ if (this._diskInvalidatedBefore > 0 && setAt <= this._diskInvalidatedBefore) return true;
4091
4514
  if (this._patternTombstones.length === 0) return false;
4092
4515
  for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
4093
- if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
4516
+ if (setAt <= this._patternTombstones[i].createdAt && this._matchesGlob(namespacedKey, this._patternTombstones[i].pattern)) {
4094
4517
  return true;
4095
4518
  }
4096
4519
  }
@@ -4105,13 +4528,170 @@ var CacheService = class _CacheService {
4105
4528
  const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
4106
4529
  this._keyMutationEpochs.set(namespacedKey, next);
4107
4530
  if (this._keyMutationEpochs.size > 5e4) {
4108
- const oldest = this._keyMutationEpochs.keys().next().value;
4109
- if (oldest !== void 0) this._keyMutationEpochs.delete(oldest);
4531
+ this._globalEpoch++;
4532
+ this._keyMutationEpochs.clear();
4533
+ this._keyMutationEpochs.set(namespacedKey, next);
4110
4534
  }
4111
4535
  return next;
4112
4536
  }
4113
4537
  _getKeyMutationEpoch(namespacedKey) {
4114
- return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
4538
+ return `${this._globalEpoch}:${this._keyMutationEpochs.get(namespacedKey) ?? 0}`;
4539
+ }
4540
+ /** Capture a commit fence before asynchronous computation outside the cache. */
4541
+ captureMutationFence(cacheKey) {
4542
+ this._assertActive("captureMutationFence");
4543
+ const key = this.nk(cacheKey);
4544
+ const epoch = this._getKeyMutationEpoch(key);
4545
+ return () => !this._destroyed && this._getKeyMutationEpoch(key) === epoch;
4546
+ }
4547
+ /** Force tag re-sync without forgetting locally observed monotonic generations. */
4548
+ refreshTagVersions() {
4549
+ this._assertActive("refreshTagVersions");
4550
+ this._tagRefreshEpoch++;
4551
+ }
4552
+ _fenceInvalidation() {
4553
+ this._globalEpoch++;
4554
+ this.inflight.clear();
4555
+ }
4556
+ _invalidateDiskKey(key) {
4557
+ if (this._diskDisabled) return;
4558
+ this.disk.invalidate(key);
4559
+ this._pendingDiskDeletes.add(key);
4560
+ this._scheduleDiskCleanup();
4561
+ }
4562
+ _scheduleDiskCleanup() {
4563
+ if (this._diskCleanupScheduled || this._pendingDiskDeletes.size === 0) return;
4564
+ this._diskCleanupScheduled = true;
4565
+ setImmediate(() => {
4566
+ this._diskCleanupScheduled = false;
4567
+ if (this._destroyed) return;
4568
+ let processed = 0;
4569
+ for (const key of this._pendingDiskDeletes) {
4570
+ try {
4571
+ this.disk.delete(key, true);
4572
+ } finally {
4573
+ this._pendingDiskDeletes.delete(key);
4574
+ }
4575
+ if (++processed >= 16) break;
4576
+ }
4577
+ this._scheduleDiskCleanup();
4578
+ });
4579
+ }
4580
+ _registerDependencies(key, patterns) {
4581
+ this._removeKeyDependencies(key);
4582
+ if (!patterns?.length) return;
4583
+ const namespaced = [...new Set(patterns.map((pattern) => this.nk(pattern)))];
4584
+ for (const pattern of namespaced) {
4585
+ const dependents = this.dependencyIndex.get(pattern) ?? /* @__PURE__ */ new Set();
4586
+ dependents.add(key);
4587
+ this.dependencyIndex.set(pattern, dependents);
4588
+ }
4589
+ this.keyDependencies.set(key, namespaced);
4590
+ }
4591
+ _rememberTags(key, tags, expiresAt) {
4592
+ this._removeKeyTags(key);
4593
+ if (!tags.length) return;
4594
+ if (this.keyTags.size >= 1e5) {
4595
+ this._sweepExpiredMetadata();
4596
+ const oldest = this.keyTags.keys().next().value;
4597
+ if (this.keyTags.size >= 1e5 && oldest !== void 0) this._removeKeyTags(oldest);
4598
+ }
4599
+ const unique = [...new Set(tags)];
4600
+ for (const tag of unique) {
4601
+ const tagKey = this.nk(`_tag_:${tag}`);
4602
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
4603
+ members.add(key);
4604
+ this.tagIndex.set(tagKey, members);
4605
+ }
4606
+ this.keyTags.set(key, { tags: unique, expiresAt });
4607
+ }
4608
+ _restoreEntryMetadata(key, entry) {
4609
+ if (entry.tags?.length) this._rememberTags(key, entry.tags, entry.expiresAt);
4610
+ if (entry.dependsOn?.length) this._registerDependencies(key, entry.dependsOn);
4611
+ }
4612
+ _removeKeyTags(namespacedKey) {
4613
+ const entry = this.keyTags.get(namespacedKey);
4614
+ if (!entry) return;
4615
+ for (const tag of entry.tags) {
4616
+ const tagKey = this.nk(`_tag_:${tag}`);
4617
+ const members = this.tagIndex.get(tagKey);
4618
+ if (members) {
4619
+ members.delete(namespacedKey);
4620
+ if (members.size === 0) this.tagIndex.delete(tagKey);
4621
+ }
4622
+ }
4623
+ this.keyTags.delete(namespacedKey);
4624
+ }
4625
+ _removeKeyDependencies(namespacedKey) {
4626
+ const patterns = this.keyDependencies.get(namespacedKey);
4627
+ if (patterns) {
4628
+ for (const pat of patterns) {
4629
+ const deps = this.dependencyIndex.get(pat);
4630
+ if (deps) {
4631
+ deps.delete(namespacedKey);
4632
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
4633
+ }
4634
+ }
4635
+ this.keyDependencies.delete(namespacedKey);
4636
+ } else if (this.dependencyIndex.size > 0) {
4637
+ for (const [pat, deps] of this.dependencyIndex) {
4638
+ deps.delete(namespacedKey);
4639
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
4640
+ }
4641
+ }
4642
+ }
4643
+ _handleL1Eviction(namespacedKey, reason) {
4644
+ const spilledToDisk = !this._diskDisabled && !this._suppressSpills && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
4645
+ if (!spilledToDisk) {
4646
+ this._removeKeyTags(namespacedKey);
4647
+ this._removeKeyDependencies(namespacedKey);
4648
+ }
4649
+ }
4650
+ _removePatternFromIndices(pattern) {
4651
+ for (const k of Array.from(this.keyTags.keys())) {
4652
+ if (this._matchesGlob(k, pattern)) this._removeKeyTags(k);
4653
+ }
4654
+ for (const k of Array.from(this.keyDependencies.keys())) {
4655
+ if (this._matchesGlob(k, pattern)) this._removeKeyDependencies(k);
4656
+ }
4657
+ for (const k of Array.from(this._l1Counters.keys())) {
4658
+ if (this._matchesGlob(k, pattern)) this._l1Counters.delete(k);
4659
+ }
4660
+ }
4661
+ _sweepExpiredMetadata() {
4662
+ const now = Date.now();
4663
+ for (const [k, c] of this._l1Counters) {
4664
+ if (c.expiresAt <= now) this._l1Counters.delete(k);
4665
+ }
4666
+ for (const [k, meta] of this.keyTags) {
4667
+ if (meta.expiresAt <= now && !this.l1.has(k)) {
4668
+ this._removeKeyTags(k);
4669
+ this._removeKeyDependencies(k);
4670
+ }
4671
+ }
4672
+ }
4673
+ _runOomCheck() {
4674
+ const heap = import_node_v82.default.getHeapStatistics();
4675
+ const heapUsed = heap.used_heap_size / heap.heap_size_limit;
4676
+ const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? (readCgroupMemoryUsage() ?? process.memoryUsage().rss) / this._cgroupMemoryLimit : 0;
4677
+ const used = Math.max(heapUsed, cgroupUsed);
4678
+ if (used >= this.opts.oomHeapThreshold) {
4679
+ this._suppressSpills = cgroupUsed >= this.opts.oomHeapThreshold;
4680
+ let evicted;
4681
+ try {
4682
+ evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
4683
+ } finally {
4684
+ this._suppressSpills = false;
4685
+ }
4686
+ this.counters.oomEvictions++;
4687
+ this.counters.oomLastAt = Date.now();
4688
+ this.logger.warn("tricache OOM guard: emergency L1 eviction", {
4689
+ heapUsedPct: Math.round(heapUsed * 100),
4690
+ cgroupUsedPct: cgroupUsed > 0 ? Math.round(cgroupUsed * 100) : void 0,
4691
+ threshold: Math.round(this.opts.oomHeapThreshold * 100),
4692
+ evicted
4693
+ });
4694
+ }
4115
4695
  }
4116
4696
  _ipcServer;
4117
4697
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
@@ -4159,6 +4739,7 @@ var CacheService = class _CacheService {
4159
4739
  constructor(options = {}) {
4160
4740
  const logger = options.logger ?? consoleLogger;
4161
4741
  this.logger = logger;
4742
+ this._cgroupMemoryLimit = readCgroupMemoryLimit();
4162
4743
  const ns = options.namespace?.trim() ?? "";
4163
4744
  const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
4164
4745
  this.enc = new CacheEncryption(
@@ -4337,12 +4918,19 @@ var CacheService = class _CacheService {
4337
4918
  admissionPolicy: this.opts.l1AdmissionPolicy,
4338
4919
  codec: this.codec,
4339
4920
  diskSpill: (key, entry) => {
4340
- if (this._diskDisabled) return;
4921
+ if (this._diskDisabled || this._suppressSpills) return;
4922
+ if (this._pendingSpillCount >= (this.opts.diskMaxPendingWrites ?? 512)) return;
4923
+ const epoch = this._getKeyMutationEpoch(key);
4924
+ this._pendingSpillCount++;
4341
4925
  setImmediate(() => {
4342
- void this.disk.save(key, entry);
4926
+ this._pendingSpillCount--;
4927
+ if (!this._destroyed && this._getKeyMutationEpoch(key) === epoch) void this.disk.save(key, entry);
4343
4928
  });
4344
4929
  },
4345
- onEviction: options.onEviction,
4930
+ onEviction: (key, reason) => {
4931
+ this._handleL1Eviction(key, reason);
4932
+ options.onEviction?.(key, reason);
4933
+ },
4346
4934
  logger
4347
4935
  });
4348
4936
  if (!this.snapshotLoaded) {
@@ -4380,6 +4968,7 @@ var CacheService = class _CacheService {
4380
4968
  }
4381
4969
  this.cleanupInterval = setInterval(() => {
4382
4970
  const cleaned = this.l1.cleanup();
4971
+ this._sweepExpiredMetadata();
4383
4972
  if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
4384
4973
  }, 5 * 60 * 1e3);
4385
4974
  if (this.cleanupInterval.unref) this.cleanupInterval.unref();
@@ -4392,18 +4981,7 @@ var CacheService = class _CacheService {
4392
4981
  }
4393
4982
  if (this.opts.oomProtection) {
4394
4983
  this.oomInterval = setInterval(() => {
4395
- const heap = import_node_v82.default.getHeapStatistics();
4396
- const used = heap.used_heap_size / heap.heap_size_limit;
4397
- if (used >= this.opts.oomHeapThreshold) {
4398
- const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
4399
- this.counters.oomEvictions++;
4400
- this.counters.oomLastAt = Date.now();
4401
- this.logger.warn("tricache OOM guard: emergency L1 eviction", {
4402
- heapUsedPct: Math.round(used * 100),
4403
- threshold: Math.round(this.opts.oomHeapThreshold * 100),
4404
- evicted
4405
- });
4406
- }
4984
+ this._runOomCheck();
4407
4985
  }, this.opts.oomCheckIntervalMs);
4408
4986
  if (this.oomInterval.unref) this.oomInterval.unref();
4409
4987
  }
@@ -4425,7 +5003,7 @@ var CacheService = class _CacheService {
4425
5003
  this.instanceId = import_crypto3.default.randomBytes(8).toString("hex");
4426
5004
  this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
4427
5005
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
4428
- this.initBackplane();
5006
+ 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 }));
4429
5007
  const startupPromises = [];
4430
5008
  if (this.opts.compression === "zstd") {
4431
5009
  startupPromises.push(initZstd().then(() => void 0));
@@ -4436,9 +5014,8 @@ var CacheService = class _CacheService {
4436
5014
  if (this.opts.warmKeys) {
4437
5015
  startupPromises.push(this.warmFromL2(this.opts.warmKeys).then(() => void 0));
4438
5016
  }
4439
- if (startupPromises.length > 0) {
4440
- this._readyPromise = Promise.all(startupPromises).then(() => void 0);
4441
- }
5017
+ const backplaneReady = this.opts.remoteSnapshot || this.opts.warmKeys ? Promise.all(startupPromises).then(startBackplane) : startBackplane();
5018
+ this._readyPromise = Promise.all([...startupPromises, backplaneReady]).then(() => void 0);
4442
5019
  if (this.opts.meter) {
4443
5020
  this._initOtelMetrics(this.opts.meter);
4444
5021
  const otel = this._otelMetrics;
@@ -4451,7 +5028,10 @@ var CacheService = class _CacheService {
4451
5028
  if (typeof prop === "string" && typeof value === "number" && typeof oldVal === "number") {
4452
5029
  const diff = value - oldVal;
4453
5030
  if (diff > 0 && otel[prop]) {
4454
- otel[prop].add(diff, nsAttr);
5031
+ try {
5032
+ otel[prop].add(diff, nsAttr);
5033
+ } catch {
5034
+ }
4455
5035
  }
4456
5036
  }
4457
5037
  return ok;
@@ -4543,7 +5123,7 @@ var CacheService = class _CacheService {
4543
5123
  return g[key];
4544
5124
  }
4545
5125
  const existing = g[key];
4546
- const diff = _CacheService.optionsDiff(options ?? {}, existing.options);
5126
+ const diff = _CacheService.optionsDiff(options ?? {}, existing.opts);
4547
5127
  if (diff.length > 0) {
4548
5128
  existing.bumpSingletonDivergence();
4549
5129
  const msg = `tricache: singleton already initialised for namespace '${existing.options.namespace || "(default)"}' \u2014 ignoring divergent options: ${diff.join(", ")}`;
@@ -4577,7 +5157,13 @@ var CacheService = class _CacheService {
4577
5157
  "instanceName",
4578
5158
  "invalidationBackplane",
4579
5159
  "awaitInvalidationBackplane",
4580
- "lockFailClosed"
5160
+ "lockFailClosed",
5161
+ "tagStrategy",
5162
+ "cloneStrategy",
5163
+ "compression",
5164
+ "backplaneMode",
5165
+ "redisProtocol",
5166
+ "failClosed"
4581
5167
  ];
4582
5168
  /** Returns the names of options that differ between `a` and the live `b`. */
4583
5169
  static optionsDiff(a, b) {
@@ -4595,12 +5181,12 @@ var CacheService = class _CacheService {
4595
5181
  bumpSingletonDivergence() {
4596
5182
  this.counters.singletonDivergences++;
4597
5183
  }
4598
- /** Read-only view of the options the singleton was constructed with. */
5184
+ /** Sanitized diagnostic view; retain the original options/adapters to reuse configuration. */
4599
5185
  get options() {
4600
5186
  const o = this.opts;
4601
5187
  return {
4602
5188
  namespace: o.namespace,
4603
- logger: o.logger,
5189
+ 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) },
4604
5190
  l1MaxBytes: o.l1MaxBytes,
4605
5191
  l1MaxEntries: o.l1MaxEntries,
4606
5192
  redisHost: o.redisHost,
@@ -4621,8 +5207,8 @@ var CacheService = class _CacheService {
4621
5207
  awaitInvalidationBackplane: o.awaitInvalidationBackplane,
4622
5208
  lockFailClosed: o.lockFailClosed,
4623
5209
  strictSingleton: o.strictSingleton,
4624
- remoteSnapshot: o.remoteSnapshot,
4625
- crossRegion: o.crossRegion
5210
+ remoteSnapshot: redactDiagnostics(o.remoteSnapshot),
5211
+ crossRegion: redactDiagnostics(o.crossRegion)
4626
5212
  };
4627
5213
  }
4628
5214
  /**
@@ -4705,21 +5291,26 @@ var CacheService = class _CacheService {
4705
5291
  if (this.opts.redisClient && typeof this.opts.redisClient.duplicate === "function") {
4706
5292
  return this.opts.redisClient.duplicate();
4707
5293
  }
5294
+ if (this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel) {
5295
+ throw new Error("Invalidation backplane requires redisSubClient or a driver supporting duplicate()");
5296
+ }
4708
5297
  if (this.opts.redisClusterNodes?.length) {
4709
- return new import_ioredis.Cluster(this.opts.redisClusterNodes, {
5298
+ return new import_ioredis2.Cluster(this.opts.redisClusterNodes, {
4710
5299
  redisOptions: {
4711
5300
  tls: this.opts.redisTls ? {} : void 0,
4712
5301
  connectTimeout: 1e4,
5302
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
4713
5303
  maxRetriesPerRequest: null,
4714
5304
  ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
4715
5305
  }
4716
5306
  });
4717
5307
  } else if (this.opts.redisSentinel) {
4718
- return new import_ioredis.Redis({
5308
+ return new import_ioredis2.Redis({
4719
5309
  sentinels: this.opts.redisSentinel.sentinels,
4720
5310
  name: this.opts.redisSentinel.name,
4721
5311
  tls: this.opts.redisTls ? {} : void 0,
4722
5312
  connectTimeout: 1e4,
5313
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
4723
5314
  lazyConnect: true,
4724
5315
  maxRetriesPerRequest: null,
4725
5316
  enableAutoPipelining: false,
@@ -4727,11 +5318,12 @@ var CacheService = class _CacheService {
4727
5318
  ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
4728
5319
  });
4729
5320
  } else {
4730
- return new import_ioredis.Redis({
5321
+ return new import_ioredis2.Redis({
4731
5322
  host: this.opts.redisHost,
4732
5323
  port: this.opts.redisPort,
4733
5324
  tls: this.opts.redisTls ? {} : void 0,
4734
5325
  connectTimeout: 1e4,
5326
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
4735
5327
  lazyConnect: true,
4736
5328
  maxRetriesPerRequest: null,
4737
5329
  enableAutoPipelining: false,
@@ -4741,26 +5333,32 @@ var CacheService = class _CacheService {
4741
5333
  });
4742
5334
  }
4743
5335
  }
4744
- initBackplane() {
5336
+ _listenBackplane(client, event, listener) {
5337
+ client.on?.(event, listener);
5338
+ this._backplaneDisposers.push(() => client.removeListener?.(event, listener));
5339
+ }
5340
+ async initBackplane() {
4745
5341
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
4746
5342
  if (this.opts.backplaneMode === "stream") {
4747
5343
  if (this.streamClient) return;
4748
- void this._startStreamConsumer();
5344
+ await this._startStreamConsumer();
4749
5345
  return;
4750
5346
  }
4751
5347
  if (this.subClient) return;
4752
5348
  const sub = this.createDedicatedRedisClient();
4753
- sub.on("error", (e) => {
5349
+ this.subClient = sub;
5350
+ this._listenBackplane(sub, "error", (e) => {
4754
5351
  this._checkAndLogResp3Hint(e);
4755
5352
  this.logger.debug("Backplane subscriber error", { error: e.message });
4756
5353
  });
4757
- sub.on("close", () => {
5354
+ this._listenBackplane(sub, "close", () => {
5355
+ this._backplaneAvailable = false;
4758
5356
  if (this._subDisconnectedAt === null) {
4759
5357
  this._subDisconnectedAt = Date.now();
4760
5358
  this.logger.debug("Backplane: subscriber disconnected", { at: this._subDisconnectedAt });
4761
5359
  }
4762
5360
  });
4763
- sub.on("ready", () => {
5361
+ this._listenBackplane(sub, "ready", () => {
4764
5362
  if (this._subDisconnectedAt !== null && this.opts.backplaneMaxStalenessMs > 0) {
4765
5363
  const gapMs = Date.now() - this._subDisconnectedAt;
4766
5364
  if (gapMs > this.opts.backplaneMaxStalenessMs) {
@@ -4773,52 +5371,119 @@ var CacheService = class _CacheService {
4773
5371
  }
4774
5372
  this._subDisconnectedAt = null;
4775
5373
  }
5374
+ if (!this._destroyed) this._backplaneAvailable = true;
4776
5375
  });
4777
5376
  const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
4778
5377
  if (isClusterSharded) {
4779
- sub.on("smessage", (_channel, message) => {
5378
+ this._listenBackplane(sub, "smessage", (_channel, message) => {
4780
5379
  this._handleBackplaneMessage(message);
4781
5380
  });
4782
- sub.ssubscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: sharded subscribed", {
5381
+ if (typeof sub.connect === "function" && (sub.isOpen === false || sub.status === "wait")) await sub.connect();
5382
+ await sub.ssubscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: sharded subscribed", {
4783
5383
  channel: this.backplaneChannel,
4784
5384
  instanceId: this.instanceId
4785
- })).catch((err) => this.logger.warn("Backplane: sharded subscribe failed", {
4786
- error: err.message
4787
5385
  }));
4788
5386
  } else {
4789
- sub.on("message", (_channel, message) => {
5387
+ this._listenBackplane(sub, "message", (_channel, message) => {
4790
5388
  this._handleBackplaneMessage(message);
4791
5389
  });
4792
- sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
5390
+ if (typeof sub.connect === "function" && (sub.isOpen === false || sub.status === "wait")) await sub.connect();
5391
+ if (this._destroyed) return;
5392
+ await sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
4793
5393
  channel: this.backplaneChannel,
4794
5394
  instanceId: this.instanceId
4795
- })).catch((err) => this.logger.warn("Backplane: subscribe failed", {
4796
- error: err.message
4797
5395
  }));
4798
5396
  }
4799
- this.subClient = sub;
5397
+ if (!this._destroyed) this._backplaneAvailable = true;
5398
+ }
5399
+ _resetAfterStreamGap() {
5400
+ this.counters.streamGaps++;
5401
+ this._fenceInvalidation();
5402
+ this.l1.clear();
5403
+ this.tagIndex.clear();
5404
+ this.keyTags.clear();
5405
+ this.tagVersions.clear();
5406
+ this.dependencyIndex.clear();
5407
+ this.keyDependencies.clear();
5408
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, Date.now());
5409
+ this._addPatternTombstone(this.nk("*"));
5410
+ this._lastStreamId = "0-0";
4800
5411
  }
4801
5412
  async _startStreamConsumer() {
5413
+ this._streamRecovering ||= this._lastStreamId !== "$" && this._lastStreamId !== "0-0";
4802
5414
  const sub = this.streamClient ?? this.createDedicatedRedisClient();
4803
5415
  this.streamClient = sub;
5416
+ if (typeof sub.xread !== "function") throw new Error("backplaneMode: stream requires a driver supporting XREAD");
4804
5417
  if (typeof sub.on === "function") {
4805
- sub.on("error", (e) => this.logger.debug("Backplane stream consumer error", { error: e.message }));
4806
- sub.on("close", () => {
5418
+ this._listenBackplane(sub, "error", (e) => this.logger.debug("Backplane stream consumer error", { error: e.message }));
5419
+ this._listenBackplane(sub, "close", () => {
5420
+ this._streamRecovering = true;
5421
+ this._backplaneAvailable = false;
4807
5422
  if (this._subDisconnectedAt === null) {
4808
5423
  this._subDisconnectedAt = Date.now();
4809
5424
  this.logger.debug("Backplane stream: consumer disconnected", { at: this._subDisconnectedAt });
4810
5425
  }
4811
5426
  });
4812
- sub.on("ready", () => {
5427
+ this._listenBackplane(sub, "ready", () => {
4813
5428
  if (this._subDisconnectedAt !== null) {
4814
5429
  this.logger.debug("Backplane stream: consumer reconnected, resuming stream read", { lastId: this._lastStreamId });
4815
5430
  this._subDisconnectedAt = null;
4816
5431
  }
4817
5432
  });
4818
5433
  }
5434
+ const checkGap = async () => {
5435
+ if (this._lastStreamId === "$" || this._lastStreamId === "0-0" || typeof sub.xrange !== "function") return;
5436
+ const first = await sub.xrange(this.backplaneStreamKey, "-", "+", "COUNT", 1);
5437
+ const firstId = first?.[0]?.[0];
5438
+ if (!firstId) return;
5439
+ const [firstMs, firstSequence] = firstId.split("-").map(BigInt);
5440
+ const [lastMs, lastSequence] = this._lastStreamId.split("-").map(BigInt);
5441
+ if (firstMs > lastMs || firstMs === lastMs && firstSequence > lastSequence) this._resetAfterStreamGap();
5442
+ };
5443
+ const apply = (response) => {
5444
+ if (this._destroyed || !response) return;
5445
+ if (this._streamRecovering && response.some(([, entries]) => entries.length > 0)) {
5446
+ this.counters.streamReplays++;
5447
+ this._streamRecovering = false;
5448
+ }
5449
+ for (const [, entries] of response) {
5450
+ for (const [id, fields] of entries) {
5451
+ this._lastStreamId = id;
5452
+ this.counters.streamEntriesReceived++;
5453
+ this._processStreamEntry(fields);
5454
+ }
5455
+ }
5456
+ };
5457
+ let initialized = false;
5458
+ const initialize = async () => {
5459
+ if (typeof sub.connect === "function" && (sub.isOpen === false || sub.status === "wait")) await sub.connect();
5460
+ if (this._destroyed) return;
5461
+ if (this._lastStreamId === "$") {
5462
+ if (this._restoredSnapshot) this._resetAfterStreamGap();
5463
+ else if (typeof sub.xrevrange === "function") {
5464
+ const latest = await sub.xrevrange(this.backplaneStreamKey, "+", "-", "COUNT", 1);
5465
+ this._lastStreamId = latest?.[0]?.[0] ?? "0-0";
5466
+ } else this._lastStreamId = "0-0";
5467
+ }
5468
+ if (typeof sub.xrange === "function") {
5469
+ await checkGap();
5470
+ apply(await sub.xread("STREAMS", this.backplaneStreamKey, this._lastStreamId));
5471
+ }
5472
+ initialized = true;
5473
+ this._backplaneAvailable = true;
5474
+ };
5475
+ try {
5476
+ await initialize();
5477
+ } catch (error) {
5478
+ this._backplaneAvailable = false;
5479
+ this.logger.warn("Backplane stream initialization failed; retrying in consumer loop", { error: error.message });
5480
+ }
4819
5481
  const runLoop = async () => {
4820
5482
  while (!this._destroyed && !this._redisDisabled) {
4821
5483
  try {
5484
+ if (!initialized) await initialize();
5485
+ if (this._destroyed) break;
5486
+ await checkGap();
4822
5487
  const res = await sub.xread(
4823
5488
  "BLOCK",
4824
5489
  this.opts.backplaneStreamBlockMs,
@@ -4827,19 +5492,10 @@ var CacheService = class _CacheService {
4827
5492
  this._lastStreamId
4828
5493
  );
4829
5494
  if (this._destroyed) break;
5495
+ this._backplaneAvailable = true;
4830
5496
  if (res && res.length > 0) {
4831
- for (const [, entries] of res) {
4832
- if (entries.length > 0) {
4833
- if (this._lastStreamId !== "$") {
4834
- this.counters.streamReplays++;
4835
- }
4836
- for (const [id, fields] of entries) {
4837
- this._lastStreamId = id;
4838
- this.counters.streamEntriesReceived++;
4839
- this._processStreamEntry(fields);
4840
- }
4841
- }
4842
- }
5497
+ apply(res);
5498
+ this._backplaneAvailable = true;
4843
5499
  } else {
4844
5500
  await new Promise((resolve) => setTimeout(resolve, 10));
4845
5501
  }
@@ -4847,10 +5503,9 @@ var CacheService = class _CacheService {
4847
5503
  if (this._destroyed) break;
4848
5504
  const msg = err.message ?? "";
4849
5505
  if (msg.includes("NOGROUP") || msg.includes("smaller than") || msg.includes("trimmed")) {
4850
- this.counters.streamGaps++;
4851
- this.l1.clear();
4852
- this._lastStreamId = "$";
5506
+ this._resetAfterStreamGap();
4853
5507
  }
5508
+ this._backplaneAvailable = false;
4854
5509
  await new Promise((resolve) => setTimeout(resolve, 200));
4855
5510
  }
4856
5511
  }
@@ -4878,8 +5533,8 @@ var CacheService = class _CacheService {
4878
5533
  else if (f === "src") src = v;
4879
5534
  else if (f === "tagVersion") tagVersionRaw = v;
4880
5535
  }
4881
- const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
4882
- if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
5536
+ const validOp = op === "del" || op === "del-glob" || op === "tag_incr" || op === "tag_pattern_incr" || op === "tag_pattern_del";
5537
+ if (!validOp || typeof key !== "string" || !key || typeof src !== "string" || !src || (op === "del" || op === "del-glob") && this._namespace && !key.startsWith(`${this._namespace}:`)) {
4883
5538
  this.logger.warn("Backplane: rejected invalid stream entry", {
4884
5539
  op: String(op).slice(0, 40),
4885
5540
  key: typeof key === "string" ? key.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(key)
@@ -4888,8 +5543,8 @@ var CacheService = class _CacheService {
4888
5543
  }
4889
5544
  let tagVersion;
4890
5545
  if (tagVersionRaw !== void 0) {
4891
- const parsed = parseInt(tagVersionRaw, 10);
4892
- if (!Number.isFinite(parsed)) {
5546
+ const parsed = Number(tagVersionRaw);
5547
+ if (!Number.isSafeInteger(parsed) || parsed < 0) {
4893
5548
  this.logger.warn("Backplane: rejected stream entry with non-numeric tagVersion", { key });
4894
5549
  return;
4895
5550
  }
@@ -4907,16 +5562,10 @@ var CacheService = class _CacheService {
4907
5562
  this.l1.delete(key);
4908
5563
  this._bumpKeyMutation(key);
4909
5564
  this.inflight.delete(key);
4910
- this._pendingDiskDeletes.add(key);
4911
- setImmediate(() => {
4912
- try {
4913
- if (!this._diskDisabled) this.disk.delete(key);
4914
- } finally {
4915
- this._pendingDiskDeletes.delete(key);
4916
- }
4917
- });
5565
+ this._invalidateDiskKey(key);
4918
5566
  this._cascadeDependencies(key);
4919
5567
  } else if (op === "del-glob") {
5568
+ this._fenceInvalidation();
4920
5569
  this.l1.deletePattern(key);
4921
5570
  const pfx = key.endsWith("*") ? key.slice(0, -1) : key;
4922
5571
  for (const liveKey of this.l1.liveKeys()) {
@@ -4930,12 +5579,22 @@ var CacheService = class _CacheService {
4930
5579
  this.inflight.delete(inflightKey);
4931
5580
  }
4932
5581
  }
4933
- this._addPatternTombstone(pfx);
5582
+ this._addPatternTombstone(key);
5583
+ this._removePatternFromIndices(key);
5584
+ if (key === this.nk("*")) {
5585
+ this.tagIndex.clear();
5586
+ this.keyTags.clear();
5587
+ this.tagVersions.clear();
5588
+ this.dependencyIndex.clear();
5589
+ this.keyDependencies.clear();
5590
+ }
4934
5591
  } else if (op === "tag_incr") {
5592
+ this._fenceInvalidation();
4935
5593
  const tag = key;
4936
5594
  const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
4937
5595
  this._setLocalTagVersion(tag, ver, performance.now());
4938
5596
  } else if (op === "tag_pattern_incr") {
5597
+ this._fenceInvalidation();
4939
5598
  const pattern = key;
4940
5599
  const now = performance.now();
4941
5600
  for (const [tag, info] of this.tagVersions) {
@@ -4955,6 +5614,7 @@ var CacheService = class _CacheService {
4955
5614
  }
4956
5615
  }, 0);
4957
5616
  } else if (op === "tag_pattern_del") {
5617
+ this._fenceInvalidation();
4958
5618
  const pattern = key;
4959
5619
  const matchedTagKeys = [];
4960
5620
  const prefix = this.nk("_tag_:");
@@ -4965,14 +5625,7 @@ var CacheService = class _CacheService {
4965
5625
  for (const k of members) {
4966
5626
  this.l1.delete(k);
4967
5627
  this._bumpKeyMutation(k);
4968
- this._pendingDiskDeletes.add(k);
4969
- setImmediate(() => {
4970
- try {
4971
- if (!this._diskDisabled) this.disk.delete(k);
4972
- } finally {
4973
- this._pendingDiskDeletes.delete(k);
4974
- }
4975
- });
5628
+ this._invalidateDiskKey(k);
4976
5629
  }
4977
5630
  }
4978
5631
  }
@@ -5003,6 +5656,7 @@ var CacheService = class _CacheService {
5003
5656
  }
5004
5657
  }
5005
5658
  async publishInvalidation(op, key, tagVersion, isCrossRegionRelay = false, isExplicitInvalidation = false) {
5659
+ if (this.opts.l2WriteMode === "read-only") return;
5006
5660
  if (!isCrossRegionRelay && this.opts.crossRegion) {
5007
5661
  const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
5008
5662
  if (shouldBroadcast) {
@@ -5085,13 +5739,13 @@ var CacheService = class _CacheService {
5085
5739
  timestamp: Date.now(),
5086
5740
  namespace: this._namespace || void 0
5087
5741
  };
5088
- this.counters.crossRegionSent++;
5089
5742
  await cr.relay.broadcast(event);
5743
+ this.counters.crossRegionSent++;
5090
5744
  this.logger.debug("Cross-region invalidation broadcast", { op, key, region: cr.currentRegion });
5091
5745
  } catch (err) {
5092
- this.counters.crossRegionSent = Math.max(0, this.counters.crossRegionSent - 1);
5093
5746
  this.counters.crossRegionErrors++;
5094
5747
  this.logger.warn("Cross-region invalidation broadcast failed", { error: err.message });
5748
+ if (this.opts.awaitInvalidationBackplane) throw err;
5095
5749
  }
5096
5750
  }
5097
5751
  /**
@@ -5102,11 +5756,12 @@ var CacheService = class _CacheService {
5102
5756
  * Returns true if the event was accepted and applied, or false if ignored/deduplicated.
5103
5757
  */
5104
5758
  async receiveCrossRegionInvalidation(event) {
5759
+ this._assertActive("receiveCrossRegionInvalidation");
5105
5760
  const cr = this.opts.crossRegion;
5106
5761
  if (!cr) return false;
5107
- if (!event || typeof event !== "object" || !event.id || !event.originRegion || !event.op || !event.key) {
5762
+ if (!isCrossRegionInvalidationEvent(event)) {
5108
5763
  this.counters.crossRegionErrors++;
5109
- this.logger.warn("Cross-region: rejected invalid event payload", { event });
5764
+ this.logger.warn("Cross-region: rejected invalid event payload");
5110
5765
  return false;
5111
5766
  }
5112
5767
  if (event.originRegion === cr.currentRegion) {
@@ -5117,46 +5772,329 @@ var CacheService = class _CacheService {
5117
5772
  this.counters.crossRegionDeduplicated++;
5118
5773
  return false;
5119
5774
  }
5120
- this._markCrossRegionEventSeen(event.id);
5121
5775
  if (event.namespace !== void 0 && event.namespace !== (this._namespace || void 0)) {
5122
5776
  return false;
5123
5777
  }
5778
+ if ((event.op === "del" || event.op === "del-glob") && this._namespace && !event.key.startsWith(`${this._namespace}:`)) return false;
5779
+ this._markCrossRegionEventSeen(event.id);
5124
5780
  this.counters.crossRegionReceived++;
5125
- this._applyInvalidationEvent(event.op, event.key, event.tagVersion);
5126
- void this.publishInvalidation(event.op, event.key, event.tagVersion, true);
5127
- this.logger.info("Cross-region invalidation applied", {
5128
- op: event.op,
5129
- key: event.key,
5130
- originRegion: event.originRegion
5131
- });
5132
- return true;
5133
- }
5134
- _setLocalTagVersion(tag, version, now = performance.now()) {
5135
- const existing = this.tagVersions.get(tag)?.version ?? 0;
5136
- const finalVersion = Math.max(existing, version);
5137
- if (this.tagVersions.size >= 1e4 && !this.tagVersions.has(tag)) {
5138
- const oldestKey = this.tagVersions.keys().next().value;
5781
+ const localTags = /* @__PURE__ */ new Set([...this.tagVersions.keys(), ...[...this.tagIndex.keys()].map((key) => this.unnk(key).replace(/^_tag_:/, ""))]);
5782
+ let version = event.tagVersion;
5783
+ if (event.op === "tag_incr") version = Math.max((this.tagVersions.get(event.key)?.version ?? 0) + 1, version ?? 0);
5784
+ this._applyInvalidationEvent(event.op, event.key, version);
5785
+ try {
5786
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
5787
+ const client = await this.getRedis();
5788
+ if (event.op === "del" || event.op === "del-glob") {
5789
+ await this._deleteRedisKeys(client, event.op === "del" ? [event.key] : await this._scanKeys(client, event.key));
5790
+ } else if (event.op === "tag_incr") {
5791
+ version = Number(await client.eval(LUA_RECEIVE_TAG_VERSION, 1, this.nk(`tag_ver:${event.key}`), String(version)));
5792
+ this._setLocalTagVersion(event.key, version);
5793
+ } else {
5794
+ const matched = await this._resolveMatchingTags(event.key, false);
5795
+ for (const tag of localTags) if (matchesTagPattern(event.key, tag)) matched.add(tag);
5796
+ for (const tag of matched) {
5797
+ if (event.op === "tag_pattern_incr") {
5798
+ const floor = this.tagVersions.get(tag)?.version ?? 1;
5799
+ const next = Number(await client.eval(LUA_RECEIVE_TAG_VERSION, 1, this.nk(`tag_ver:${tag}`), String(floor)));
5800
+ this._setLocalTagVersion(tag, next);
5801
+ await this.publishInvalidation("tag_incr", tag, next, true);
5802
+ } else {
5803
+ const tagKey = this.nk(`_tag_:${tag}`);
5804
+ const members = await client.smembers(tagKey);
5805
+ this._removeTagMembersLocal(members);
5806
+ await this._deleteRedisKeys(client, [...members, tagKey]);
5807
+ await Promise.all(members.map((key) => this.publishInvalidation("del", key, void 0, true)));
5808
+ }
5809
+ }
5810
+ }
5811
+ this.cb.onSuccess();
5812
+ }
5813
+ await this.publishInvalidation(event.op, event.key, version, true);
5814
+ } catch (error) {
5815
+ this._seenCrossRegionEvents.delete(event.id);
5816
+ this.counters.crossRegionErrors++;
5817
+ this.logger.warn("Cross-region regional invalidation failed", { error: error.message });
5818
+ if (this.opts.awaitInvalidationBackplane) throw error;
5819
+ return false;
5820
+ }
5821
+ this.logger.info("Cross-region invalidation applied", {
5822
+ op: event.op,
5823
+ key: event.key,
5824
+ originRegion: event.originRegion
5825
+ });
5826
+ return true;
5827
+ }
5828
+ _setLocalTagVersion(tag, version, now = performance.now()) {
5829
+ const existing = this.tagVersions.get(tag)?.version ?? 0;
5830
+ const finalVersion = Math.max(existing, version);
5831
+ if (this.tagVersions.size >= 1e4 && !this.tagVersions.has(tag)) {
5832
+ const oldestKey = this.tagVersions.keys().next().value;
5139
5833
  if (oldestKey !== void 0) this.tagVersions.delete(oldestKey);
5140
5834
  }
5141
- this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
5835
+ this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now, refreshEpoch: this._tagRefreshEpoch });
5836
+ }
5837
+ async _isGenerationalEntryStale(tagVersions) {
5838
+ if (!tagVersions) return false;
5839
+ const tags = Object.keys(tagVersions);
5840
+ if (tags.length === 0) return false;
5841
+ const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5842
+ for (let i = 0; i < tags.length; i++) {
5843
+ if (currentVers[i] > tagVersions[tags[i]]) return true;
5844
+ }
5845
+ return false;
5846
+ }
5847
+ async _deleteRedisKeys(client, keys) {
5848
+ if (keys.length === 0) return;
5849
+ const CHUNK_SIZE = 1e3;
5850
+ if (client instanceof import_ioredis2.Cluster) {
5851
+ const groups = /* @__PURE__ */ new Map();
5852
+ for (const key of keys) {
5853
+ const slot = redisHashSlot(key);
5854
+ const master = client.slots?.[slot]?.[0] ?? String(slot);
5855
+ const members = groups.get(master) ?? [];
5856
+ members.push(key);
5857
+ groups.set(master, members);
5858
+ }
5859
+ await Promise.all([...groups.values()].map(async (members) => {
5860
+ for (let offset = 0; offset < members.length; offset += CHUNK_SIZE) {
5861
+ const pipeline = client.pipeline();
5862
+ for (const key of members.slice(offset, offset + CHUNK_SIZE)) pipeline.del(key);
5863
+ const result = await pipeline.exec();
5864
+ if (!result || result.some(([error]) => error)) throw new Error("Redis Cluster delete failed");
5865
+ }
5866
+ }));
5867
+ return;
5868
+ }
5869
+ for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
5870
+ const chunk = keys.slice(i, i + CHUNK_SIZE);
5871
+ await client.del(...chunk);
5872
+ }
5873
+ }
5874
+ async _parseGenerationalRedisHash(k, hashData) {
5875
+ if (!hashData || !hashData.d) return null;
5876
+ let storedTagVersions = {};
5877
+ if (hashData.tv) {
5878
+ try {
5879
+ const parsed = JSON.parse(hashData.tv);
5880
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || Object.values(parsed).some((version) => !Number.isSafeInteger(version) || Number(version) < 0)) return null;
5881
+ storedTagVersions = parsed;
5882
+ } catch {
5883
+ return null;
5884
+ }
5885
+ }
5886
+ if (await this._isGenerationalEntryStale(storedTagVersions)) {
5887
+ const setAtMs = parseInt(hashData.t, 10) || 0;
5888
+ this._deleteIfStale(k, setAtMs);
5889
+ return { stale: true };
5890
+ }
5891
+ const value = await this._decryptAndDeserialize(hashData.d);
5892
+ const expiresAt = Number(hashData.e);
5893
+ const staleAt = Number(hashData.s);
5894
+ let tags;
5895
+ let dependsOn;
5896
+ try {
5897
+ const parsedTags = hashData.tags ? JSON.parse(hashData.tags) : Object.keys(storedTagVersions);
5898
+ const parsedDependencies = hashData.deps ? JSON.parse(hashData.deps) : void 0;
5899
+ if (Array.isArray(parsedTags) && parsedTags.every((tag) => typeof tag === "string")) tags = parsedTags;
5900
+ if (Array.isArray(parsedDependencies) && parsedDependencies.every((pattern) => typeof pattern === "string")) dependsOn = parsedDependencies;
5901
+ } catch {
5902
+ return null;
5903
+ }
5904
+ return {
5905
+ value,
5906
+ tagVersions: storedTagVersions,
5907
+ stale: false,
5908
+ tags,
5909
+ dependsOn,
5910
+ setAt: Number(hashData.t) || void 0,
5911
+ expiresAt: Number.isFinite(expiresAt) && expiresAt > 0 ? expiresAt : void 0,
5912
+ staleAt: Number.isFinite(staleAt) && staleAt > 0 ? staleAt : void 0
5913
+ };
5914
+ }
5915
+ async _readRedisEntry(client, k, allowAutoPipeline = false) {
5916
+ const readStartedAt = Date.now();
5917
+ const read = async (hash) => allowAutoPipeline && this.opts.autoPipeline && this.pipeliner ? this.pipeliner.read(k, hash) : readRedisValue(client, k, hash);
5918
+ const withExpiry = (entry, ttlMs2) => {
5919
+ if (!entry || ttlMs2 === -2 || ttlMs2 === 0) return null;
5920
+ if (ttlMs2 !== void 0 && Number.isFinite(ttlMs2) && ttlMs2 > 0) {
5921
+ entry.expiresAt = Math.min(entry.expiresAt ?? Infinity, readStartedAt + ttlMs2);
5922
+ }
5923
+ return entry.expiresAt !== void 0 && entry.expiresAt <= Date.now() ? null : entry;
5924
+ };
5925
+ if (this.opts.tagStrategy === "generational" && typeof client.hgetall === "function") {
5926
+ try {
5927
+ const { raw: hashData, ttlMs: ttlMs2 } = await read(true);
5928
+ if (typeof hashData === "string") {
5929
+ const value2 = await this._decryptAndDeserialize(hashData);
5930
+ return withExpiry({ value: value2, stale: false }, ttlMs2);
5931
+ }
5932
+ if (hashData && hashData.d) {
5933
+ return withExpiry(await this._parseGenerationalRedisHash(k, hashData), ttlMs2);
5934
+ }
5935
+ return null;
5936
+ } catch (err) {
5937
+ const msg = err instanceof Error ? err.message : String(err);
5938
+ if (!msg.includes("WRONGTYPE")) throw err;
5939
+ }
5940
+ }
5941
+ const { raw, ttlMs } = await read(false);
5942
+ if (raw == null) return null;
5943
+ if (typeof raw !== "string") return null;
5944
+ const value = await this._decryptAndDeserialize(raw);
5945
+ return withExpiry({ value, stale: false }, ttlMs);
5142
5946
  }
5143
5947
  async _getTagVersion(tag) {
5144
5948
  const now = performance.now();
5145
5949
  const local = this.tagVersions.get(tag);
5146
- if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
5950
+ if (local && (local.refreshEpoch ?? 0) === this._tagRefreshEpoch && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
5147
5951
  return local.version;
5148
5952
  }
5149
5953
  if (!this._redisDisabled) {
5150
5954
  try {
5151
5955
  const client = await this.getRedis();
5152
5956
  const raw = await client.get(this.nk(`tag_ver:${tag}`));
5153
- const version = raw ? parseInt(raw, 10) : 0;
5154
- this._setLocalTagVersion(tag, version, now);
5155
- return version;
5957
+ const parsed = raw ? Number(raw) : 0;
5958
+ if (!Number.isSafeInteger(parsed) || parsed < 0) throw new Error("Invalid Redis tag generation");
5959
+ const version2 = Math.max(this.tagVersions.get(tag)?.version ?? 0, parsed);
5960
+ if (this.opts.l2WriteMode === "read-write") {
5961
+ if (raw === null) await client.set(this.nk(`tag_ver:${tag}`), String(version2), "NX");
5962
+ else if (version2 > parsed) await client.eval(LUA_MAX_TAG_VERSION, 1, this.nk(`tag_ver:${tag}`), String(version2));
5963
+ }
5964
+ this._setLocalTagVersion(tag, version2, now);
5965
+ this.cb.onSuccess();
5966
+ return version2;
5156
5967
  } catch {
5157
5968
  }
5158
5969
  }
5159
- return local?.version ?? 0;
5970
+ const version = this.tagVersions.get(tag)?.version ?? local?.version ?? 0;
5971
+ if (this._redisDisabled) this._setLocalTagVersion(tag, version, now);
5972
+ return version;
5973
+ }
5974
+ async _readRedisBatch(client, keys) {
5975
+ const entries = /* @__PURE__ */ new Map();
5976
+ const groups = /* @__PURE__ */ new Map();
5977
+ for (const key of new Set(keys)) {
5978
+ const group = client instanceof import_ioredis2.Cluster ? client.slots[redisHashSlot(key)]?.[0] ?? String(redisHashSlot(key)) : "single";
5979
+ const members = groups.get(group) ?? [];
5980
+ members.push(key);
5981
+ groups.set(group, members);
5982
+ }
5983
+ await Promise.all([...groups.values()].map(async (members) => {
5984
+ for (let offset = 0; offset < members.length; offset += 1e3) {
5985
+ const chunk = members.slice(offset, offset + 1e3);
5986
+ const pipeline = typeof client.pipeline === "function" ? client.pipeline() : client.multi();
5987
+ const timedScripts = typeof pipeline.eval === "function";
5988
+ const hashes = this.opts.tagStrategy === "generational" && typeof pipeline.hgetall === "function";
5989
+ for (const key of chunk) {
5990
+ if (timedScripts) pipeline.eval(LUA_READ_CACHE_ENTRY, 1, key);
5991
+ else if (hashes) pipeline.hgetall(key);
5992
+ else pipeline.get(key);
5993
+ }
5994
+ const startedAt = Date.now();
5995
+ const start = performance.now();
5996
+ const results = await pipeline.exec();
5997
+ this.watchdog.recordRedis(performance.now() - start);
5998
+ if (!results) throw new Error("Redis batch read aborted");
5999
+ for (let index = 0; index < chunk.length; index++) {
6000
+ try {
6001
+ const tuple = results[index];
6002
+ if (!tuple) continue;
6003
+ let [error, raw] = tuple;
6004
+ let ttl;
6005
+ if (error?.message?.includes("WRONGTYPE")) {
6006
+ const fallback = await this._readRedisEntry(client, chunk[index]);
6007
+ if (fallback && !fallback.stale) entries.set(chunk[index], fallback);
6008
+ continue;
6009
+ }
6010
+ if (error) continue;
6011
+ if (timedScripts) {
6012
+ if (!Array.isArray(raw) || raw[0] === "none") continue;
6013
+ const kind = raw[0];
6014
+ ttl = Number(raw[2]);
6015
+ const payload = raw[1];
6016
+ if (kind === "hash") {
6017
+ if (!Array.isArray(payload) || payload.length % 2 !== 0) continue;
6018
+ raw = Object.fromEntries(Array.from({ length: payload.length / 2 }, (_unused, i) => [String(payload[i * 2]), String(payload[i * 2 + 1])]));
6019
+ } else if (kind === "string") raw = payload;
6020
+ else continue;
6021
+ if (ttl === -2 || ttl === 0) continue;
6022
+ }
6023
+ 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;
6024
+ if (!entry || entry.stale) continue;
6025
+ if (ttl !== void 0 && ttl > 0) entry.expiresAt = Math.min(entry.expiresAt ?? Infinity, startedAt + ttl);
6026
+ if (entry.expiresAt !== void 0 && entry.expiresAt <= Date.now()) continue;
6027
+ entries.set(chunk[index], entry);
6028
+ } catch (error) {
6029
+ this.logger.debug("mget: skipping invalid remote entry", { key: chunk[index], error: error.message });
6030
+ }
6031
+ }
6032
+ }
6033
+ }));
6034
+ this.cb.onSuccess();
6035
+ return entries;
6036
+ }
6037
+ _promoteRedisEntry(key, entry, fallbackTtlMs, priority) {
6038
+ const expiresAt = entry.expiresAt ?? Date.now() + fallbackTtlMs;
6039
+ if (expiresAt <= Date.now()) return false;
6040
+ const admitted = this.l1.set(
6041
+ key,
6042
+ entry.value,
6043
+ expiresAt - Date.now(),
6044
+ priority,
6045
+ entry.staleAt,
6046
+ void 0,
6047
+ entry.tagVersions,
6048
+ entry.setAt,
6049
+ entry.tags,
6050
+ entry.dependsOn
6051
+ );
6052
+ if (admitted) this._restoreEntryMetadata(key, { ...entry, expiresAt });
6053
+ return true;
6054
+ }
6055
+ async _readDiskEntry(key, epoch) {
6056
+ if (this._diskDisabled || this._pendingDiskDeletes.has(key) || !this.watchdog.isDiskAllowed()) return null;
6057
+ const start = performance.now();
6058
+ const entry = this.disk.load(key);
6059
+ const elapsed = performance.now() - start;
6060
+ this.watchdog.recordDisk(elapsed);
6061
+ this.watchdog.onCanaryResult(entry !== null, elapsed);
6062
+ 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;
6063
+ this.l1.importEntries([{ key, entry }], this.opts.forbiddenSnapshotPrefixes);
6064
+ const hit = this.l1.get(key);
6065
+ const value = hit ? hit.value : entry.isCompressed ? this.codec.decode(entry.data) : JSON.parse(entry.data);
6066
+ this._restoreEntryMetadata(key, entry);
6067
+ return { value, entry };
6068
+ }
6069
+ /** Common write policy and metadata across get/set/revalidation/draining. */
6070
+ async _writeRedisEntry(key, data, expiresAt, setAt, tagVersions, staleAt, tags, dependsOn, canCommit = () => true) {
6071
+ if (this._redisDisabled || this.opts.l2WriteMode !== "read-write" || !canCommit() || this._destroyed) return;
6072
+ const client = await this.getRedis();
6073
+ const stored = await this._serializeAndEncrypt(JSON.stringify(data) ?? "undefined");
6074
+ if (!canCommit() || this._destroyed) return;
6075
+ const useHash = this.opts.tagStrategy === "generational" && (tagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function");
6076
+ const remaining = (useHash ? expiresAt : staleAt ?? expiresAt) - Date.now();
6077
+ if (remaining <= 0) return;
6078
+ const ttl = Math.max(1, Math.ceil(remaining / 1e3));
6079
+ if (useHash) {
6080
+ const transaction = client.multi();
6081
+ transaction.del(key);
6082
+ const hash = { d: stored, t: String(setAt), tv: JSON.stringify(tagVersions ?? {}), e: String(expiresAt) };
6083
+ if (staleAt !== void 0) hash.s = String(staleAt);
6084
+ if (tags?.length) hash.tags = JSON.stringify(tags);
6085
+ if (dependsOn?.length) hash.deps = JSON.stringify(dependsOn);
6086
+ transaction.hset(key, hash);
6087
+ transaction.expire(key, ttl);
6088
+ const result = await transaction.exec();
6089
+ if (!result || result.some(([error]) => error)) throw new Error("Redis cache write transaction failed");
6090
+ } else if (this.opts.autoPipeline && this.pipeliner) {
6091
+ if (typeof client.pttl === "function" && typeof client.set === "function") await this.pipeliner.setpx(key, Math.ceil(remaining), stored);
6092
+ else await this.pipeliner.setex(key, ttl, stored);
6093
+ } else {
6094
+ if (typeof client.pttl === "function" && typeof client.set === "function") await client.set(key, stored, "PX", Math.ceil(remaining));
6095
+ else await client.setex(key, ttl, stored);
6096
+ }
6097
+ this.cb.onSuccess();
5160
6098
  }
5161
6099
  _deleteIfStale(k, setAtMs) {
5162
6100
  this.l1.deleteIfSetBefore(k, setAtMs);
@@ -5209,7 +6147,7 @@ var CacheService = class _CacheService {
5209
6147
  } else {
5210
6148
  plain = raw;
5211
6149
  }
5212
- return JSON.parse(plain);
6150
+ return plain === "undefined" ? void 0 : JSON.parse(plain);
5213
6151
  }
5214
6152
  /**
5215
6153
  * Scan all keys matching `pattern` across single-node or Cluster clients.
@@ -5217,7 +6155,7 @@ var CacheService = class _CacheService {
5217
6155
  */
5218
6156
  async _scanKeys(client, pattern) {
5219
6157
  const keys = [];
5220
- if (client instanceof import_ioredis.Cluster) {
6158
+ if (client instanceof import_ioredis2.Cluster) {
5221
6159
  const masters = client.nodes("master");
5222
6160
  await Promise.all(masters.map(
5223
6161
  (node) => new Promise((resolve, reject) => {
@@ -5277,10 +6215,10 @@ var CacheService = class _CacheService {
5277
6215
  return client;
5278
6216
  }
5279
6217
  this.redisConnecting = (async () => {
6218
+ let client = null;
5280
6219
  try {
5281
- let client;
5282
6220
  if (this.opts.redisClusterNodes?.length) {
5283
- client = new import_ioredis.Cluster(this.opts.redisClusterNodes, {
6221
+ client = new import_ioredis2.Cluster(this.opts.redisClusterNodes, {
5284
6222
  redisOptions: {
5285
6223
  tls: this.opts.redisTls ? {} : void 0,
5286
6224
  connectTimeout: 1e4,
@@ -5300,7 +6238,7 @@ var CacheService = class _CacheService {
5300
6238
  });
5301
6239
  client.on("reconnecting", () => this.logger.debug("Redis Cluster reconnecting"));
5302
6240
  } else if (this.opts.redisSentinel) {
5303
- client = new import_ioredis.Redis({
6241
+ client = new import_ioredis2.Redis({
5304
6242
  sentinels: this.opts.redisSentinel.sentinels,
5305
6243
  name: this.opts.redisSentinel.name,
5306
6244
  tls: this.opts.redisTls ? {} : void 0,
@@ -5320,7 +6258,7 @@ var CacheService = class _CacheService {
5320
6258
  });
5321
6259
  client.on("reconnecting", () => this.logger.debug("Redis Sentinel reconnecting"));
5322
6260
  } else {
5323
- client = new import_ioredis.Redis({
6261
+ client = new import_ioredis2.Redis({
5324
6262
  host: this.opts.redisHost,
5325
6263
  port: this.opts.redisPort,
5326
6264
  tls: this.opts.redisTls ? {} : void 0,
@@ -5341,14 +6279,45 @@ var CacheService = class _CacheService {
5341
6279
  });
5342
6280
  client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
5343
6281
  }
6282
+ const pendingClient = client;
5344
6283
  await new Promise((resolve, reject) => {
5345
- client.once("ready", resolve);
5346
- client.once("error", (e) => {
6284
+ let settled = false;
6285
+ const cleanupListeners = () => {
6286
+ pendingClient.removeListener?.("ready", onReady);
6287
+ pendingClient.removeListener?.("error", onError);
6288
+ };
6289
+ const onReady = () => {
6290
+ if (settled) return;
6291
+ settled = true;
6292
+ clearTimeout(timer);
6293
+ cleanupListeners();
6294
+ resolve();
6295
+ };
6296
+ const onError = (e) => {
6297
+ if (settled) return;
6298
+ settled = true;
6299
+ clearTimeout(timer);
6300
+ cleanupListeners();
5347
6301
  this._checkAndLogResp3Hint(e);
5348
6302
  reject(e);
5349
- });
5350
- setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
6303
+ };
6304
+ const timer = setTimeout(() => {
6305
+ if (settled) return;
6306
+ settled = true;
6307
+ cleanupListeners();
6308
+ reject(new Error("Redis connection timeout"));
6309
+ }, 15e3);
6310
+ if (timer.unref) timer.unref();
6311
+ pendingClient.once("ready", onReady);
6312
+ pendingClient.once("error", onError);
5351
6313
  });
6314
+ if (this._destroyed) {
6315
+ try {
6316
+ client.disconnect();
6317
+ } catch {
6318
+ }
6319
+ this._assertActive("getRedis");
6320
+ }
5352
6321
  this.cb.onSuccess();
5353
6322
  this.redis = client;
5354
6323
  this.pipeliner = new AutoPipeliner(client, {
@@ -5358,6 +6327,10 @@ var CacheService = class _CacheService {
5358
6327
  this.redisConnecting = null;
5359
6328
  return client;
5360
6329
  } catch (err) {
6330
+ try {
6331
+ client?.disconnect();
6332
+ } catch {
6333
+ }
5361
6334
  this.cb.onFailure();
5362
6335
  this.redisConnecting = null;
5363
6336
  this._checkAndLogResp3Hint(err);
@@ -5377,7 +6350,12 @@ var CacheService = class _CacheService {
5377
6350
  try {
5378
6351
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
5379
6352
  if (entries.length === 0) return;
5380
- const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
6353
+ const payload = {
6354
+ version: SNAPSHOT_VERSION,
6355
+ writtenAt: Date.now(),
6356
+ entries,
6357
+ streamId: this.opts.backplaneMode === "stream" && this._lastStreamId !== "$" ? this._lastStreamId : void 0
6358
+ };
5381
6359
  const packed = this.codec.encode(payload);
5382
6360
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
5383
6361
  const dest = altPath ?? this.opts.snapshotPath;
@@ -5445,6 +6423,9 @@ var CacheService = class _CacheService {
5445
6423
  return;
5446
6424
  }
5447
6425
  const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
6426
+ this._restoredSnapshot ||= loaded > 0;
6427
+ if (typeof snapshot.streamId === "string" && /^\d{1,20}-\d{1,20}$/.test(snapshot.streamId)) this._lastStreamId = snapshot.streamId;
6428
+ for (const { key, entry } of snapshot.entries) if (this.l1.has(key)) this._restoreEntryMetadata(key, entry);
5448
6429
  this.logger.info("Cache snapshot loaded (L1 is warm)", {
5449
6430
  loaded,
5450
6431
  total: snapshot.entries.length,
@@ -5469,7 +6450,12 @@ var CacheService = class _CacheService {
5469
6450
  try {
5470
6451
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
5471
6452
  if (entries.length === 0) return false;
5472
- const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
6453
+ const payload = {
6454
+ version: SNAPSHOT_VERSION,
6455
+ writtenAt: Date.now(),
6456
+ entries,
6457
+ streamId: this.opts.backplaneMode === "stream" && this._lastStreamId !== "$" ? this._lastStreamId : void 0
6458
+ };
5473
6459
  const packed = this.codec.encode(payload);
5474
6460
  let final;
5475
6461
  if (this.opts.remoteSnapshot.envelope) {
@@ -5500,13 +6486,16 @@ var CacheService = class _CacheService {
5500
6486
  async loadRemoteSnapshot() {
5501
6487
  if (!this.opts.remoteSnapshot) return 0;
5502
6488
  const maxAgeMs = this.opts.remoteSnapshot.maxAgeMs ?? this.opts.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE;
6489
+ const epoch = this._globalEpoch;
5503
6490
  try {
5504
6491
  const raw = await this.opts.remoteSnapshot.adapter.get();
6492
+ if (this._destroyed || this._globalEpoch !== epoch) return 0;
5505
6493
  if (!raw || raw.length === 0) {
5506
6494
  this.logger.debug("Remote snapshot not found or empty \u2014 starting cold");
5507
6495
  return 0;
5508
6496
  }
5509
6497
  const rawBuf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
6498
+ if (rawBuf.length > SNAPSHOT_MAX_FILE_BYTES) throw new Error("Remote snapshot exceeds size limit");
5510
6499
  let buf;
5511
6500
  try {
5512
6501
  if (EnvelopeEncryption.isEnvelope(rawBuf)) {
@@ -5552,7 +6541,12 @@ var CacheService = class _CacheService {
5552
6541
  this.logger.warn("Remote snapshot rejected: entries is not an array");
5553
6542
  return 0;
5554
6543
  }
5555
- const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
6544
+ if (this._destroyed || this._globalEpoch !== epoch) return 0;
6545
+ const eligible = snapshot.entries.filter((item) => item && !this._keyMutationEpochs.has(item.key));
6546
+ const loaded = this.l1.importEntries(eligible, this.opts.forbiddenSnapshotPrefixes);
6547
+ this._restoredSnapshot ||= loaded > 0;
6548
+ if (typeof snapshot.streamId === "string" && /^\d{1,20}-\d{1,20}$/.test(snapshot.streamId)) this._lastStreamId = snapshot.streamId;
6549
+ for (const { key, entry } of eligible) if (this.l1.has(key)) this._restoreEntryMetadata(key, entry);
5556
6550
  this.counters.remoteSnapshotDownloads++;
5557
6551
  this.counters.remoteSnapshotLastDownloadedAt = Date.now();
5558
6552
  this.logger.info("Remote cache snapshot loaded (L1 hydrated)", {
@@ -5601,20 +6595,10 @@ var CacheService = class _CacheService {
5601
6595
  const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
5602
6596
  const l1Hit = this.l1.get(k);
5603
6597
  if (l1Hit !== null) {
5604
- let isGenerationalStale = false;
5605
- if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
5606
- const tags = Object.keys(l1Hit.tagVersions);
5607
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5608
- for (let i = 0; i < tags.length; i++) {
5609
- if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
5610
- isGenerationalStale = true;
5611
- break;
5612
- }
5613
- }
5614
- }
6598
+ const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
5615
6599
  if (isGenerationalStale) {
5616
6600
  this._deleteIfStale(k, l1Hit.setAt ?? 0);
5617
- } else {
6601
+ } else if (!l1Hit.isStale || optSwr > 0) {
5618
6602
  if (l1Hit.isStale) {
5619
6603
  const swrGraceMs2 = optSwr * 1e3;
5620
6604
  if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
@@ -5677,115 +6661,58 @@ var CacheService = class _CacheService {
5677
6661
  this.counters.stampedes++;
5678
6662
  this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch/read", { cacheKey });
5679
6663
  span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
5680
- return existing;
6664
+ return this._prepareReadValue(await existing);
5681
6665
  }
5682
6666
  const mutationEpochAtStart = this._getKeyMutationEpoch(k);
5683
- const executionPromise = (async () => {
6667
+ const executionPromise = Promise.resolve().then(async () => {
5684
6668
  try {
5685
- if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
5686
- if (this._isTombstonedByPattern(k)) {
5687
- try {
5688
- this.disk.delete(k);
5689
- } catch {
5690
- }
5691
- } else {
5692
- const isDiskAllowed = this.watchdog.isDiskAllowed();
5693
- if (isDiskAllowed) {
5694
- const diskStart = performance.now();
5695
- const diskHit = this.disk.load(k);
5696
- const diskElapsed = performance.now() - diskStart;
5697
- this.watchdog.recordDisk(diskElapsed);
5698
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
5699
- if (diskHit !== null) {
5700
- let isDiskStale = false;
5701
- if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
5702
- const tags = Object.keys(diskHit.tagVersions);
5703
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5704
- for (let i = 0; i < tags.length; i++) {
5705
- if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
5706
- isDiskStale = true;
5707
- break;
5708
- }
5709
- }
5710
- }
5711
- if (isDiskStale) {
5712
- this.disk.delete(k);
5713
- } else {
5714
- const promoted = this.l1.importEntries(
5715
- [{ key: k, entry: diskHit }],
5716
- this.opts.forbiddenSnapshotPrefixes
5717
- );
5718
- if (promoted > 0) {
5719
- const l1Check = this.l1.get(k);
5720
- if (l1Check !== null) {
5721
- this.counters.diskHits++;
5722
- this.opts.onHit?.(cacheKey, "disk");
5723
- this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
5724
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
5725
- if (this.opts.frozen) deepFreeze(l1Check.value);
5726
- return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
5727
- }
5728
- }
5729
- }
5730
- }
5731
- }
6669
+ const diskHit = await this._readDiskEntry(k, mutationEpochAtStart);
6670
+ if (diskHit && (diskHit.entry.staleAt === void 0 || diskHit.entry.staleAt > Date.now() || optSwr > 0)) {
6671
+ this.counters.diskHits++;
6672
+ this.opts.onHit?.(cacheKey, "disk");
6673
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
6674
+ if (diskHit.entry.staleAt !== void 0 && diskHit.entry.staleAt <= Date.now() && optSwr > 0 && !this.revalidating.has(k)) {
6675
+ this.revalidating.add(k);
6676
+ this.counters.swrRevalidations++;
6677
+ void this._revalidate(
6678
+ k,
6679
+ fetchFn,
6680
+ ttlMs,
6681
+ swrGraceMs,
6682
+ priority,
6683
+ diskHit.entry.tagVersions ?? Object.fromEntries((diskHit.entry.tags ?? []).map((tag) => [tag, 0]))
6684
+ );
5732
6685
  }
6686
+ return diskHit.value;
5733
6687
  }
5734
6688
  if (!this._redisDisabled) {
5735
6689
  try {
5736
6690
  const client = await this.getRedis();
5737
6691
  const redisStart = performance.now();
5738
- if (this.opts.tagStrategy === "generational") {
5739
- const hashData = await client.hgetall(k);
5740
- const redisElapsed = performance.now() - redisStart;
5741
- this.watchdog.recordRedis(redisElapsed);
5742
- this.cb.onSuccess();
5743
- if (hashData && hashData.d) {
5744
- let isStale = false;
5745
- let storedTagVersions = {};
5746
- if (hashData.tv) {
5747
- try {
5748
- storedTagVersions = JSON.parse(hashData.tv);
5749
- } catch {
5750
- }
5751
- }
5752
- const tags = Object.keys(storedTagVersions);
5753
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5754
- for (let i = 0; i < tags.length; i++) {
5755
- if (currentVers[i] > storedTagVersions[tags[i]]) {
5756
- isStale = true;
5757
- break;
5758
- }
5759
- }
5760
- if (isStale) {
5761
- const setAtMs = parseInt(hashData.t, 10) || 0;
5762
- this._deleteIfStale(k, setAtMs);
5763
- } else {
5764
- const parsed = await this._decryptAndDeserialize(hashData.d);
5765
- this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
5766
- this.counters.l2Hits++;
5767
- this.opts.onHit?.(cacheKey, "l2");
5768
- this.logger.debug("L2 hit (Redis hash)", { cacheKey });
5769
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5770
- if (this.opts.frozen) deepFreeze(parsed);
5771
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
5772
- }
6692
+ const redisHit = await this._readRedisEntry(client, k, true);
6693
+ const redisElapsed = performance.now() - redisStart;
6694
+ this.watchdog.recordRedis(redisElapsed);
6695
+ this.cb.onSuccess();
6696
+ if (redisHit && !redisHit.stale && (redisHit.staleAt === void 0 || redisHit.staleAt > Date.now() || optSwr > 0)) {
6697
+ const parsed = redisHit.value;
6698
+ if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
6699
+ this.logger.debug("Aborting L2 promotion \u2014 key was mutated or deleted during Redis read", { cacheKey });
6700
+ span.setAttribute("cache.aborted_mutation_race", true);
6701
+ const current = this.l1.get(k);
6702
+ const liveVal = current && !current.isStale ? current.value : parsed;
6703
+ return liveVal;
5773
6704
  }
5774
- } else {
5775
- const raw = this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
5776
- const redisElapsed = performance.now() - redisStart;
5777
- this.watchdog.recordRedis(redisElapsed);
5778
- this.cb.onSuccess();
5779
- if (raw) {
5780
- const parsed = await this._decryptAndDeserialize(raw);
5781
- this.l1.set(k, parsed, ttlMs, priority);
5782
- this.counters.l2Hits++;
5783
- this.opts.onHit?.(cacheKey, "l2");
5784
- this.logger.debug("L2 hit (Redis)", { cacheKey });
5785
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5786
- if (this.opts.frozen) deepFreeze(parsed);
5787
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
6705
+ if (!this._promoteRedisEntry(k, redisHit, ttlMs, priority)) throw new Error("Redis entry expired during promotion");
6706
+ this.counters.l2Hits++;
6707
+ this.opts.onHit?.(cacheKey, "l2");
6708
+ this.logger.debug(redisHit.tagVersions ? "L2 hit (Redis hash)" : "L2 hit (Redis)", { cacheKey });
6709
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
6710
+ if (redisHit.staleAt !== void 0 && redisHit.staleAt <= Date.now() && optSwr > 0 && !this.revalidating.has(k)) {
6711
+ this.revalidating.add(k);
6712
+ this.counters.swrRevalidations++;
6713
+ void this._revalidate(k, fetchFn, ttlMs, swrGraceMs, priority, redisHit.tagVersions);
5788
6714
  }
6715
+ return parsed;
5789
6716
  }
5790
6717
  } catch (err) {
5791
6718
  this.cb.onFailure();
@@ -5795,6 +6722,7 @@ var CacheService = class _CacheService {
5795
6722
  span.setAttribute("cache.hit", false).setAttribute("cache.hit_tier", "miss");
5796
6723
  this.opts.onMiss?.(cacheKey);
5797
6724
  this.counters.fetches++;
6725
+ const tagSnapshot = this.opts.tagStrategy === "generational" && optTags?.length ? Object.fromEntries(await Promise.all(optTags.map(async (tag) => [tag, await this._getTagVersion(tag)]))) : void 0;
5798
6726
  const fetchStart = Date.now();
5799
6727
  let data;
5800
6728
  try {
@@ -5823,50 +6751,41 @@ var CacheService = class _CacheService {
5823
6751
  }
5824
6752
  const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
5825
6753
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
5826
- let activeTagVersions;
6754
+ const activeTagVersions = tagSnapshot;
5827
6755
  if (optTags?.length) {
5828
6756
  if (this.opts.tagStrategy === "generational") {
5829
- const vers = await Promise.all(optTags.map((tag) => this._getTagVersion(tag)));
5830
- activeTagVersions = {};
5831
- for (let i = 0; i < optTags.length; i++) {
5832
- activeTagVersions[optTags[i]] = vers[i];
5833
- }
6757
+ if (await this._isGenerationalEntryStale(tagSnapshot)) return data;
5834
6758
  } else {
5835
- await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
6759
+ await this._registerTags(k, optTags, Math.ceil(storeTtl / 1e3));
5836
6760
  }
5837
6761
  }
5838
6762
  if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
5839
6763
  this.logger.debug("Aborting in-flight cache commit \u2014 key was mutated or deleted during fetch", { cacheKey });
5840
6764
  span.setAttribute("cache.aborted_mutation_race", true);
5841
6765
  const current = this.l1.get(k);
5842
- if (current && !current.isStale && current.value !== void 0) {
6766
+ if (current && !current.isStale) {
5843
6767
  const freshVal = current.value;
5844
- if (this.opts.frozen) deepFreeze(freshVal);
5845
- return this.opts.cloneStrategy === "structuredClone" && freshVal != null && typeof freshVal === "object" ? structuredClone(freshVal) : freshVal;
6768
+ return freshVal;
5846
6769
  }
5847
- if (this.opts.frozen) deepFreeze(data);
5848
- return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
6770
+ return data;
5849
6771
  }
5850
- this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
5851
- if (!this._redisDisabled) {
6772
+ const writeTs = Date.now();
6773
+ this._invalidateDiskKey(k);
6774
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs, optTags, opts.dependsOn);
6775
+ this._restoreEntryMetadata(k, { tags: optTags, dependsOn: opts.dependsOn, expiresAt: writeTs + storeTtl });
6776
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
5852
6777
  try {
5853
- const client = await this.getRedis();
5854
- const serialized = JSON.stringify(data);
5855
- const toStore = await this._serializeAndEncrypt(serialized);
5856
- const ttlSec = Math.ceil(effectiveTtl / 1e3);
5857
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
5858
- const now = Date.now();
5859
- const tx = client.multi();
5860
- tx.hset(k, {
5861
- d: toStore,
5862
- t: String(now),
5863
- tv: JSON.stringify(activeTagVersions)
5864
- });
5865
- tx.expire(k, ttlSec);
5866
- await tx.exec();
5867
- } else {
5868
- await client.setex(k, ttlSec, toStore);
5869
- }
6778
+ await this._writeRedisEntry(
6779
+ k,
6780
+ data,
6781
+ writeTs + storeTtl,
6782
+ writeTs,
6783
+ activeTagVersions,
6784
+ staleAt,
6785
+ optTags,
6786
+ opts.dependsOn,
6787
+ () => this._getKeyMutationEpoch(k) === mutationEpochAtStart
6788
+ );
5870
6789
  this.cb.onSuccess();
5871
6790
  this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
5872
6791
  } catch {
@@ -5876,15 +6795,14 @@ var CacheService = class _CacheService {
5876
6795
  } else {
5877
6796
  this.logger.debug("Cached L1", { cacheKey });
5878
6797
  }
5879
- if (this.opts.frozen) deepFreeze(data);
5880
- return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
6798
+ return data;
5881
6799
  } finally {
5882
- this.inflight.delete(k);
6800
+ if (this.inflight.get(k) === executionPromise) this.inflight.delete(k);
5883
6801
  span.end();
5884
6802
  }
5885
- })();
6803
+ });
5886
6804
  this.inflight.set(k, executionPromise);
5887
- return executionPromise;
6805
+ return this._prepareReadValue(await executionPromise);
5888
6806
  }
5889
6807
  /**
5890
6808
  * Graceful shutdown flusher for Kubernetes preStop hooks, NestJS onApplicationShutdown,
@@ -5965,6 +6883,9 @@ var CacheService = class _CacheService {
5965
6883
  }
5966
6884
  async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority, knownTagVersions) {
5967
6885
  const startEpoch = this._getKeyMutationEpoch(cacheKey);
6886
+ const previous = this.l1.getEntry(cacheKey);
6887
+ const tags = previous?.tags ?? Object.keys(knownTagVersions ?? {});
6888
+ const dependencies = previous?.dependsOn;
5968
6889
  try {
5969
6890
  const fetchStart = Date.now();
5970
6891
  const data = await fetchFn();
@@ -5979,14 +6900,14 @@ var CacheService = class _CacheService {
5979
6900
  const l1Existing = this.l1.get(cacheKey);
5980
6901
  const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
5981
6902
  if (this.opts.tagStrategy === "generational" && tagVersionsSource) {
5982
- const tags = Object.keys(tagVersionsSource);
5983
- const vers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
6903
+ const tags2 = Object.keys(tagVersionsSource);
6904
+ const vers = await Promise.all(tags2.map((tag) => this._getTagVersion(tag)));
5984
6905
  activeTagVersions = {};
5985
- for (let i = 0; i < tags.length; i++) {
5986
- activeTagVersions[tags[i]] = vers[i];
6906
+ for (let i = 0; i < tags2.length; i++) {
6907
+ activeTagVersions[tags2[i]] = vers[i];
5987
6908
  }
5988
6909
  if (knownTagVersions) {
5989
- for (const t of tags) {
6910
+ for (const t of tags2) {
5990
6911
  if (knownTagVersions[t] !== void 0 && activeTagVersions[t] !== knownTagVersions[t]) {
5991
6912
  this.logger.debug("SWR: aborting revalidation commit \u2014 tag version bumped during revalidation", { cacheKey, tag: t });
5992
6913
  return;
@@ -5998,32 +6919,29 @@ var CacheService = class _CacheService {
5998
6919
  this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
5999
6920
  return;
6000
6921
  }
6001
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
6922
+ const writeTs = Date.now();
6923
+ this._invalidateDiskKey(cacheKey);
6924
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs, tags, dependencies);
6925
+ this._restoreEntryMetadata(cacheKey, { tags, dependsOn: dependencies, expiresAt: writeTs + ttlMs + swrGraceMs });
6002
6926
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6003
6927
  try {
6004
- const client = await this.getRedis();
6005
- const s = JSON.stringify(data);
6006
- const stored = await this._serializeAndEncrypt(s);
6007
- const ttlSec = Math.ceil(ttlMs / 1e3);
6008
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
6009
- const now = Date.now();
6010
- const tx = client.multi();
6011
- tx.hset(cacheKey, {
6012
- d: stored,
6013
- t: String(now),
6014
- tv: JSON.stringify(activeTagVersions)
6015
- });
6016
- tx.expire(cacheKey, ttlSec);
6017
- await tx.exec();
6018
- } else {
6019
- await client.setex(cacheKey, ttlSec, stored);
6020
- }
6928
+ await this._writeRedisEntry(
6929
+ cacheKey,
6930
+ data,
6931
+ writeTs + ttlMs + swrGraceMs,
6932
+ writeTs,
6933
+ activeTagVersions,
6934
+ staleAt,
6935
+ tags,
6936
+ dependencies,
6937
+ () => this._getKeyMutationEpoch(cacheKey) === startEpoch
6938
+ );
6021
6939
  } catch {
6022
6940
  }
6023
6941
  }
6024
6942
  this.logger.debug("SWR: revalidation complete", { cacheKey });
6025
6943
  } catch (err) {
6026
- if (this.opts.staleIfError > 0) {
6944
+ if (this.opts.staleIfError > 0 && this._getKeyMutationEpoch(cacheKey) === startEpoch) {
6027
6945
  const additionalMs = this.opts.staleIfError * 1e3;
6028
6946
  this.l1.bumpExpiry(cacheKey, additionalMs);
6029
6947
  this.logger.debug("SWR: revalidation failed, stale-if-error extending expiry", {
@@ -6051,12 +6969,16 @@ var CacheService = class _CacheService {
6051
6969
  const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
6052
6970
  const p = priority ?? inferPriority(cacheKey);
6053
6971
  const k = this.nk(cacheKey);
6972
+ const existingEntry = this.l1.getEntry(k);
6973
+ const requestedTags = opts?.tags ?? existingEntry?.tags ?? this.keyTags.get(k)?.tags;
6974
+ const requestedDependencies = opts?.dependsOn ?? existingEntry?.dependsOn;
6054
6975
  this._bumpKeyMutation(k);
6976
+ const epoch = this._getKeyMutationEpoch(k);
6055
6977
  this.inflight.delete(k);
6056
- this._pendingDiskDeletes.delete(k);
6978
+ this._invalidateDiskKey(k);
6057
6979
  this.counters.sets++;
6058
6980
  let activeTagVersions;
6059
- const tagsToRegister = opts?.tags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
6981
+ const tagsToRegister = requestedTags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(requestedTags, this.opts.tagHierarchyDelimiter) : requestedTags : void 0;
6060
6982
  if (tagsToRegister?.length) {
6061
6983
  if (this.opts.tagStrategy === "generational") {
6062
6984
  const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
@@ -6065,44 +6987,27 @@ var CacheService = class _CacheService {
6065
6987
  activeTagVersions[tagsToRegister[i]] = vers[i];
6066
6988
  }
6067
6989
  } else {
6068
- await this._registerTags(k, tagsToRegister, ttlSeconds);
6069
- }
6070
- }
6071
- this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
6072
- if (opts?.dependsOn?.length) {
6073
- for (const pattern of opts.dependsOn) {
6074
- const nsPattern = this.nk(pattern);
6075
- let deps = this.dependencyIndex.get(nsPattern);
6076
- if (!deps) {
6077
- deps = /* @__PURE__ */ new Set();
6078
- this.dependencyIndex.set(nsPattern, deps);
6079
- }
6080
- deps.add(k);
6990
+ await this._registerTags(k, tagsToRegister, effectiveTtlSeconds);
6081
6991
  }
6082
6992
  }
6993
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return;
6994
+ const writeTs = Date.now();
6995
+ this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions, writeTs, tagsToRegister, requestedDependencies);
6996
+ this._rememberTags(k, tagsToRegister ?? [], writeTs + ttlMs);
6997
+ this._registerDependencies(k, requestedDependencies);
6083
6998
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6084
6999
  try {
6085
- const client = await this.getRedis();
6086
- const s = JSON.stringify(data);
6087
- const stored = await this._serializeAndEncrypt(s);
6088
- const ttlSec = Math.ceil(ttlMs / 1e3);
6089
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
6090
- const now = Date.now();
6091
- const tx = client.multi();
6092
- tx.hset(k, {
6093
- d: stored,
6094
- t: String(now),
6095
- tv: JSON.stringify(activeTagVersions)
6096
- });
6097
- tx.expire(k, ttlSec);
6098
- await tx.exec();
6099
- } else {
6100
- if (this.opts.autoPipeline && this.pipeliner) {
6101
- await this.pipeliner.setex(k, ttlSec, stored);
6102
- } else {
6103
- await client.setex(k, ttlSec, stored);
6104
- }
6105
- }
7000
+ await this._writeRedisEntry(
7001
+ k,
7002
+ data,
7003
+ writeTs + ttlMs,
7004
+ writeTs,
7005
+ activeTagVersions,
7006
+ void 0,
7007
+ tagsToRegister,
7008
+ requestedDependencies,
7009
+ () => this._getKeyMutationEpoch(k) === epoch
7010
+ );
6106
7011
  this.cb.onSuccess();
6107
7012
  } catch (err) {
6108
7013
  this.cb.onFailure();
@@ -6127,23 +7032,18 @@ var CacheService = class _CacheService {
6127
7032
  * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
6128
7033
  */
6129
7034
  async _registerTags(k, tags, ttlSeconds) {
6130
- for (const tag of tags) {
6131
- const tagKey = this.nk(`_tag_:${tag}`);
6132
- let members = this.tagIndex.get(tagKey);
6133
- if (!members) {
6134
- members = /* @__PURE__ */ new Set();
6135
- this.tagIndex.set(tagKey, members);
6136
- }
6137
- members.add(k);
6138
- }
7035
+ const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
7036
+ const expiresAt = Date.now() + effectiveTtl * 1e3;
7037
+ const uniqueTags = Array.from(new Set(tags));
7038
+ this._rememberTags(k, uniqueTags, expiresAt);
6139
7039
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6140
7040
  try {
6141
7041
  const client = await this.getRedis();
6142
7042
  const pl = client.pipeline();
6143
- for (const tag of tags) {
7043
+ for (const tag of uniqueTags) {
6144
7044
  const tagKey = this.nk(`_tag_:${tag}`);
6145
7045
  pl.sadd(tagKey, k);
6146
- pl.expire(tagKey, ttlSeconds + 3600);
7046
+ pl.expire(tagKey, effectiveTtl + 3600);
6147
7047
  }
6148
7048
  await pl.exec();
6149
7049
  this.cb.onSuccess();
@@ -6168,6 +7068,7 @@ var CacheService = class _CacheService {
6168
7068
  const k = this.nk(cacheKey);
6169
7069
  this.counters.deletes++;
6170
7070
  if (isPattern) {
7071
+ this._fenceInvalidation();
6171
7072
  const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6172
7073
  for (const liveKey of this.l1.liveKeys()) {
6173
7074
  if (liveKey.startsWith(pfx)) {
@@ -6180,29 +7081,30 @@ var CacheService = class _CacheService {
6180
7081
  this.inflight.delete(inflightKey);
6181
7082
  }
6182
7083
  }
6183
- this._addPatternTombstone(pfx);
7084
+ this._addPatternTombstone(k);
6184
7085
  this.l1.deletePattern(k);
7086
+ this._removePatternFromIndices(k);
7087
+ for (const ktKey of Array.from(this.keyTags.keys())) {
7088
+ if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
7089
+ }
7090
+ for (const kdKey of Array.from(this.keyDependencies.keys())) {
7091
+ if (this._matchesGlob(kdKey, k)) this._removeKeyDependencies(kdKey);
7092
+ }
6185
7093
  } else {
6186
7094
  this._bumpKeyMutation(k);
6187
7095
  this.inflight.delete(k);
6188
7096
  this.l1.delete(k);
6189
- this._pendingDiskDeletes.add(k);
6190
- setImmediate(() => {
6191
- try {
6192
- if (!this._diskDisabled) this.disk.delete(k);
6193
- } finally {
6194
- this._pendingDiskDeletes.delete(k);
6195
- }
6196
- });
7097
+ this._invalidateDiskKey(k);
7098
+ this._removeKeyTags(k);
6197
7099
  this._cascadeDependencies(k);
6198
- for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
7100
+ this._removeKeyDependencies(k);
6199
7101
  }
6200
7102
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6201
7103
  try {
6202
7104
  const client = await this.getRedis();
6203
7105
  if (isPattern) {
6204
7106
  const keys = await this._scanKeys(client, k);
6205
- if (keys.length > 0) await client.del(...keys);
7107
+ await this._deleteRedisKeys(client, keys);
6206
7108
  } else {
6207
7109
  if (this.opts.autoPipeline && this.pipeliner) {
6208
7110
  await this.pipeliner.del(k);
@@ -6249,7 +7151,7 @@ var CacheService = class _CacheService {
6249
7151
  async increment(cacheKey, ttlSeconds) {
6250
7152
  this._assertActive("increment");
6251
7153
  const k = this.nk(cacheKey);
6252
- if (this._redisDisabled) {
7154
+ if (this._redisDisabled || this.opts.l2WriteMode === "read-only") {
6253
7155
  if (!this._incrementFallbackWarned) {
6254
7156
  this._incrementFallbackWarned = true;
6255
7157
  this.logger.warn(
@@ -6264,6 +7166,15 @@ var CacheService = class _CacheService {
6264
7166
  entry.value++;
6265
7167
  return entry.value;
6266
7168
  }
7169
+ if (this._l1Counters.size >= 5e4 && !this._l1Counters.has(k)) {
7170
+ for (const [ck, cv] of this._l1Counters) {
7171
+ if (cv.expiresAt <= now) this._l1Counters.delete(ck);
7172
+ }
7173
+ if (this._l1Counters.size >= 5e4) {
7174
+ const oldest = this._l1Counters.keys().next().value;
7175
+ if (oldest !== void 0) this._l1Counters.delete(oldest);
7176
+ }
7177
+ }
6267
7178
  this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
6268
7179
  return 1;
6269
7180
  }
@@ -6296,6 +7207,7 @@ var CacheService = class _CacheService {
6296
7207
  this.counters.deletes++;
6297
7208
  const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
6298
7209
  if (k) {
7210
+ this._fenceInvalidation();
6299
7211
  const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6300
7212
  for (const liveKey of this.l1.liveKeys()) {
6301
7213
  if (liveKey.startsWith(pfx)) {
@@ -6308,8 +7220,9 @@ var CacheService = class _CacheService {
6308
7220
  this.inflight.delete(inflightKey);
6309
7221
  }
6310
7222
  }
6311
- this._addPatternTombstone(pfx);
7223
+ this._addPatternTombstone(k);
6312
7224
  this.l1.deletePattern(k);
7225
+ this._removePatternFromIndices(k);
6313
7226
  } else {
6314
7227
  this._globalEpoch++;
6315
7228
  this.inflight.clear();
@@ -6318,7 +7231,10 @@ var CacheService = class _CacheService {
6318
7231
  if (!this._diskDisabled) this.disk.clear();
6319
7232
  this._l1Counters.clear();
6320
7233
  this.tagIndex.clear();
7234
+ this.keyTags.clear();
6321
7235
  this.tagVersions.clear();
7236
+ this.dependencyIndex.clear();
7237
+ this.keyDependencies.clear();
6322
7238
  this._pendingDiskDeletes.clear();
6323
7239
  this._keyMutationEpochs.clear();
6324
7240
  }
@@ -6327,7 +7243,7 @@ var CacheService = class _CacheService {
6327
7243
  const client = await this.getRedis();
6328
7244
  const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
6329
7245
  const keys = await this._scanKeys(client, pattern);
6330
- if (keys.length > 0) await client.del(...keys);
7246
+ await this._deleteRedisKeys(client, keys);
6331
7247
  } catch (err) {
6332
7248
  this.logger.debug("clear: Redis unavailable", { error: err.message });
6333
7249
  }
@@ -6456,24 +7372,34 @@ var CacheService = class _CacheService {
6456
7372
  this._assertActive("scan");
6457
7373
  const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
6458
7374
  this.l1.scan((key, entry, pfx) => {
6459
- const value = entry.value !== void 0 ? entry.value : entry.data;
6460
- fn(key, value, pfx);
7375
+ fn(key, this._prepareReadValue(this.l1.resolveValue(entry)), pfx);
6461
7376
  }, prefixLen);
6462
7377
  }
6463
7378
  /**
6464
- * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
7379
+ * Extend the TTL of a key in L1 and Redis without fetching.
6465
7380
  * Returns `false` if the key is absent or already expired.
6466
7381
  *
6467
7382
  * @param newTtlSeconds - The new TTL from now, in seconds.
6468
7383
  */
6469
7384
  async touch(cacheKey, newTtlSeconds) {
6470
7385
  this._assertActive("touch");
7386
+ if (!Number.isFinite(newTtlSeconds) || newTtlSeconds <= 0) throw new Error("touch TTL must be finite and positive");
6471
7387
  const k = this.nk(cacheKey);
7388
+ const epoch = this._getKeyMutationEpoch(k);
6472
7389
  const hit = this.l1.touch(k, newTtlSeconds * 1e3);
6473
- if (hit && !this._redisDisabled) {
7390
+ const entry = this.l1.getEntry(k);
7391
+ if (hit) {
7392
+ const kt = this.keyTags.get(k);
7393
+ if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1e3;
7394
+ }
7395
+ if (hit && !this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6474
7396
  try {
6475
7397
  const client = await this.getRedis();
6476
- void client.expire(k, newTtlSeconds);
7398
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return hit;
7399
+ if (entry && typeof client.pttl === "function" && typeof client.eval === "function") {
7400
+ await client.eval(LUA_TOUCH_CACHE_ENTRY, 1, k, String(entry.setAt ?? 0), String(entry.expiresAt), String(Math.ceil(newTtlSeconds * 1e3)));
7401
+ } else await client.expire(k, Math.ceil(newTtlSeconds));
7402
+ this.cb.onSuccess();
6477
7403
  } catch {
6478
7404
  }
6479
7405
  }
@@ -6495,7 +7421,12 @@ var CacheService = class _CacheService {
6495
7421
  const now = Date.now();
6496
7422
  if (entry.expiresAt <= now) return null;
6497
7423
  if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
6498
- return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
7424
+ if (entry.tagVersions && Object.entries(entry.tagVersions).some(([tag, version]) => (this.tagVersions.get(tag)?.version ?? 0) > version)) return null;
7425
+ return this._prepareReadValue(entry.value !== void 0 ? entry.value : this.codec.decode(entry.data));
7426
+ }
7427
+ _prepareReadValue(val) {
7428
+ if (this.opts.frozen) deepFreeze(val);
7429
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6499
7430
  }
6500
7431
  /**
6501
7432
  * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
@@ -6508,59 +7439,36 @@ var CacheService = class _CacheService {
6508
7439
  async peek(cacheKey) {
6509
7440
  this._assertActive("peek");
6510
7441
  const k = this.nk(cacheKey);
7442
+ const epoch = this._getKeyMutationEpoch(k);
7443
+ this.counters.gets++;
6511
7444
  const l1Hit = this.l1.get(k);
6512
7445
  if (l1Hit !== null) {
6513
- this.counters.gets++;
6514
- this.counters.l1Hits++;
6515
- const val = l1Hit.value;
6516
- if (this.opts.frozen) deepFreeze(val);
6517
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6518
- }
6519
- if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
6520
- if (this._isTombstonedByPattern(k)) {
6521
- try {
6522
- this.disk.delete(k);
6523
- } catch {
6524
- }
6525
- } else if (this.watchdog.isDiskAllowed()) {
6526
- const diskStart = performance.now();
6527
- const diskHit = this.disk.load(k);
6528
- const diskElapsed = performance.now() - diskStart;
6529
- this.watchdog.recordDisk(diskElapsed);
6530
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6531
- if (diskHit !== null) {
6532
- const promoted = this.l1.importEntries(
6533
- [{ key: k, entry: diskHit }],
6534
- this.opts.forbiddenSnapshotPrefixes
6535
- );
6536
- if (promoted > 0) {
6537
- const l1Check = this.l1.get(k);
6538
- if (l1Check !== null) {
6539
- this.counters.gets++;
6540
- this.counters.diskHits++;
6541
- const val = l1Check.value;
6542
- if (this.opts.frozen) deepFreeze(val);
6543
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6544
- }
6545
- }
6546
- }
7446
+ if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
7447
+ this._deleteIfStale(k, l1Hit.setAt ?? 0);
7448
+ } else {
7449
+ this.counters.l1Hits++;
7450
+ return this._prepareReadValue(l1Hit.value);
6547
7451
  }
6548
7452
  }
6549
- if (!this._redisDisabled && !this.cb.isOpen) {
7453
+ const diskHit = await this._readDiskEntry(k, epoch);
7454
+ if (diskHit) {
7455
+ this.counters.diskHits++;
7456
+ return this._prepareReadValue(diskHit.value);
7457
+ }
7458
+ if (!this._redisDisabled) {
6550
7459
  try {
6551
7460
  const client = await this.getRedis();
6552
7461
  const redisStart = performance.now();
6553
- const raw = await client.get(k);
7462
+ const redisHit = await this._readRedisEntry(client, k);
6554
7463
  const redisElapsed = performance.now() - redisStart;
6555
7464
  this.watchdog.recordRedis(redisElapsed);
6556
- if (raw !== null) {
6557
- const parsed = await this._decryptAndDeserialize(raw);
6558
- this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
6559
- this.counters.gets++;
7465
+ this.cb.onSuccess();
7466
+ if (redisHit && !redisHit.stale) {
7467
+ const parsed = redisHit.value;
7468
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return null;
7469
+ if (!this._promoteRedisEntry(k, redisHit, 6e4, inferPriority(cacheKey))) return null;
6560
7470
  this.counters.l2Hits++;
6561
- this.cb.onSuccess();
6562
- if (this.opts.frozen) deepFreeze(parsed);
6563
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
7471
+ return this._prepareReadValue(parsed);
6564
7472
  }
6565
7473
  } catch (err) {
6566
7474
  this.cb.onFailure();
@@ -6580,6 +7488,8 @@ var CacheService = class _CacheService {
6580
7488
  */
6581
7489
  async mget(keys, fetchFn, ttl = 300, priority) {
6582
7490
  this._assertActive("mget");
7491
+ this.counters.gets += keys.length;
7492
+ const epochs = new Map(keys.map((key) => [this.nk(key), this._getKeyMutationEpoch(this.nk(key))]));
6583
7493
  const span = this._startSpan("tricache.mget");
6584
7494
  if (this.opts.tracer) {
6585
7495
  span.setAttribute("cache.batch.size", keys.length);
@@ -6588,12 +7498,20 @@ var CacheService = class _CacheService {
6588
7498
  const result = Array.from({ length: keys.length });
6589
7499
  const missIndexes = [];
6590
7500
  const missKeys = [];
7501
+ const now = Date.now();
6591
7502
  for (let i = 0; i < keys.length; i++) {
6592
7503
  const k = this.nk(keys[i]);
6593
7504
  const entry = this.l1.getEntry(k);
6594
- if (entry && entry.expiresAt > Date.now()) {
6595
- result[i] = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
6596
- this.counters.l1Hits++;
7505
+ if (entry && entry.expiresAt > now && (entry.staleAt === void 0 || entry.staleAt > now)) {
7506
+ if (await this._isGenerationalEntryStale(entry.tagVersions)) {
7507
+ this._deleteIfStale(k, entry.setAt ?? 0);
7508
+ missIndexes.push(i);
7509
+ missKeys.push(keys[i]);
7510
+ } else {
7511
+ const val = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
7512
+ result[i] = this._prepareReadValue(val);
7513
+ this.counters.l1Hits++;
7514
+ }
6597
7515
  } else {
6598
7516
  missIndexes.push(i);
6599
7517
  missKeys.push(keys[i]);
@@ -6613,30 +7531,24 @@ var CacheService = class _CacheService {
6613
7531
  try {
6614
7532
  const client = await this.getRedis();
6615
7533
  const nsKeys = missKeys.map((k) => this.nk(k));
6616
- const pipeline = client.multi();
6617
- for (const nk of nsKeys) pipeline.get(nk);
6618
- const redisStart = performance.now();
6619
- const raws = await pipeline.exec();
6620
- const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
6621
- this.watchdog.recordRedis(redisElapsed);
6622
- this.cb.onSuccess();
7534
+ const remoteEntries = await this._readRedisBatch(client, nsKeys);
6623
7535
  for (let j = 0; j < missKeys.length; j++) {
6624
- const raw = raws[j] ? raws[j][1] : null;
6625
7536
  const idx = missIndexes[j];
6626
- if (raw) {
6627
- const parsed = await this._decryptAndDeserialize(raw);
6628
- const k = nsKeys[j];
7537
+ const k = nsKeys[j];
7538
+ const entry = remoteEntries.get(k);
7539
+ if (entry && (entry.staleAt === void 0 || entry.staleAt > Date.now()) && !this._destroyed && this._getKeyMutationEpoch(k) === epochs.get(k)) {
6629
7540
  const p = priority ?? inferPriority(missKeys[j]);
6630
- this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
7541
+ const ttlVal = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
7542
+ if (!this._promoteRedisEntry(k, entry, this._jitterTtl(ttlVal * 1e3), p)) continue;
6631
7543
  this.counters.l2Hits++;
6632
7544
  l2HitCount++;
6633
- result[idx] = parsed;
7545
+ result[idx] = this._prepareReadValue(entry.value);
6634
7546
  missIndexes[j] = -1;
6635
7547
  missKeys[j] = "";
6636
7548
  }
6637
7549
  }
6638
7550
  const remainingIdx = missIndexes.filter((i) => i >= 0);
6639
- const remainingKeys = missKeys.filter((k) => k !== "");
7551
+ const remainingKeys = missKeys.filter((_key, index) => missIndexes[index] >= 0);
6640
7552
  missIndexes.length = 0;
6641
7553
  missKeys.length = 0;
6642
7554
  missIndexes.push(...remainingIdx);
@@ -6649,58 +7561,64 @@ var CacheService = class _CacheService {
6649
7561
  if (!this._diskDisabled && missKeys.length > 0) {
6650
7562
  for (let j = missKeys.length - 1; j >= 0; j--) {
6651
7563
  const k = this.nk(missKeys[j]);
6652
- if (this._pendingDiskDeletes.has(k)) continue;
6653
- if (this._isTombstonedByPattern(k)) {
6654
- try {
6655
- this.disk.delete(k);
6656
- } catch {
6657
- }
6658
- continue;
6659
- }
6660
- if (!this.watchdog.isDiskAllowed()) continue;
6661
- const diskStart = performance.now();
6662
- const diskHit = this.disk.load(k);
6663
- const diskElapsed = performance.now() - diskStart;
6664
- this.watchdog.recordDisk(diskElapsed);
6665
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6666
- if (diskHit !== null) {
6667
- const promoted = this.l1.importEntries(
6668
- [{ key: k, entry: diskHit }],
6669
- this.opts.forbiddenSnapshotPrefixes
6670
- );
6671
- if (promoted > 0) {
6672
- const l1Check = this.l1.get(k);
6673
- if (l1Check !== null) {
6674
- this.counters.diskHits++;
6675
- result[missIndexes[j]] = l1Check.value;
6676
- missIndexes.splice(j, 1);
6677
- missKeys.splice(j, 1);
6678
- }
6679
- }
7564
+ const diskHit = await this._readDiskEntry(k, epochs.get(k));
7565
+ if (diskHit && (diskHit.entry.staleAt === void 0 || diskHit.entry.staleAt > Date.now())) {
7566
+ this.counters.diskHits++;
7567
+ result[missIndexes[j]] = this._prepareReadValue(diskHit.value);
7568
+ missIndexes.splice(j, 1);
7569
+ missKeys.splice(j, 1);
6680
7570
  }
6681
7571
  }
6682
7572
  }
6683
7573
  if (missKeys.length > 0 && fetchFn) {
6684
- this.counters.fetches++;
6685
- const fetched = await fetchFn(missKeys);
6686
- const isMap = fetched instanceof Map;
6687
- const setPromises = [];
7574
+ const owned = /* @__PURE__ */ new Map();
7575
+ const waiting = [];
6688
7576
  for (let j = 0; j < missKeys.length; j++) {
6689
- const k = missKeys[j];
6690
- const v = isMap ? fetched.get(k) : fetched[k];
6691
- result[missIndexes[j]] = v;
6692
- if (v !== void 0 && v !== null) {
6693
- const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
6694
- setPromises.push(this.set(k, v, resolvedTtl, priority));
6695
- } else if (v == null && this.opts.notFoundTtl > 0) {
6696
- setPromises.push(this.set(k, null, this.opts.notFoundTtl, priority));
6697
- } else if (v === null) {
6698
- const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
6699
- setPromises.push(this.set(k, null, resolvedTtl, priority));
7577
+ const key = missKeys[j];
7578
+ const namespaced = this.nk(key);
7579
+ let promise = this.inflight.get(namespaced);
7580
+ if (!promise) {
7581
+ let resolve;
7582
+ let reject;
7583
+ promise = new Promise((yes, no) => {
7584
+ resolve = yes;
7585
+ reject = no;
7586
+ });
7587
+ owned.set(key, { promise, resolve, reject });
7588
+ this.inflight.set(namespaced, promise);
7589
+ } else {
7590
+ this.counters.stampedes++;
6700
7591
  }
7592
+ const index = missIndexes[j];
7593
+ waiting.push(promise.then((value) => {
7594
+ result[index] = this._prepareReadValue(value);
7595
+ }));
6701
7596
  }
6702
- if (setPromises.length > 0) {
6703
- await Promise.all(setPromises);
7597
+ const settled = Promise.allSettled(waiting);
7598
+ try {
7599
+ if (owned.size > 0) {
7600
+ this.counters.fetches++;
7601
+ const fetched = await fetchFn([...owned.keys()]);
7602
+ await Promise.all([...owned].map(async ([key, entry]) => {
7603
+ const value = fetched instanceof Map ? fetched.get(key) : Object.hasOwn(fetched, key) ? fetched[key] : void 0;
7604
+ if (!this._destroyed && this._getKeyMutationEpoch(this.nk(key)) === epochs.get(this.nk(key))) {
7605
+ const resolvedTtl = value == null && this.opts.notFoundTtl > 0 ? this.opts.notFoundTtl : typeof ttl === "function" ? ttl(key) : ttl;
7606
+ if (value !== void 0 || this.opts.notFoundTtl > 0) await this.set(key, value === void 0 && this.opts.notFoundTtl > 0 ? null : value, resolvedTtl, priority);
7607
+ }
7608
+ entry.resolve(value);
7609
+ }));
7610
+ }
7611
+ const outcomes = await settled;
7612
+ const failed = outcomes.find((outcome) => outcome.status === "rejected");
7613
+ if (failed?.status === "rejected") throw failed.reason;
7614
+ } catch (error) {
7615
+ for (const entry of owned.values()) entry.reject(error);
7616
+ throw error;
7617
+ } finally {
7618
+ for (const [key, entry] of owned) {
7619
+ const namespaced = this.nk(key);
7620
+ if (this.inflight.get(namespaced) === entry.promise) this.inflight.delete(namespaced);
7621
+ }
6704
7622
  }
6705
7623
  }
6706
7624
  if (this.opts.tracer) {
@@ -6753,7 +7671,7 @@ var CacheService = class _CacheService {
6753
7671
  try {
6754
7672
  await Promise.all(keys.map((key) => {
6755
7673
  const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
6756
- const hasOpts = tags?.length || dependsOn?.length;
7674
+ const hasOpts = tags !== void 0 || dependsOn !== void 0;
6757
7675
  return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
6758
7676
  }));
6759
7677
  } catch (err) {
@@ -6805,26 +7723,21 @@ var CacheService = class _CacheService {
6805
7723
  try {
6806
7724
  const client = await this.getRedis();
6807
7725
  const nsPattern = this.nk(pattern);
6808
- const matchedKeys = await this._scanKeys(client, nsPattern);
7726
+ const matchedKeys = (await this._scanKeys(client, nsPattern)).filter((key) => {
7727
+ const raw = this.unnk(key);
7728
+ return !raw.startsWith("_tag_:") && !raw.startsWith("tag_ver:") && !raw.startsWith("lock:") && key !== this.backplaneStreamKey;
7729
+ });
6809
7730
  if (matchedKeys.length === 0) {
6810
7731
  this.cb.onSuccess();
6811
7732
  return 0;
6812
7733
  }
6813
- const pl = client.pipeline();
6814
- for (const k of matchedKeys) pl.get(k);
6815
- const results = await pl.exec();
6816
- this.cb.onSuccess();
7734
+ const epochs = new Map(matchedKeys.map((key) => [key, this._getKeyMutationEpoch(key)]));
7735
+ const results = await this._readRedisBatch(client, matchedKeys);
6817
7736
  let loaded = 0;
6818
- for (let i = 0; i < matchedKeys.length; i++) {
6819
- const [err, raw] = results[i];
6820
- if (err || raw == null) continue;
6821
- try {
6822
- const parsed = await this._decryptAndDeserialize(raw);
6823
- const remainingMs = 10 * 60 * 1e3;
6824
- this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
6825
- loaded++;
6826
- } catch {
6827
- }
7737
+ for (const key of matchedKeys) {
7738
+ const entry = results.get(key);
7739
+ if (!entry || this._destroyed || this._getKeyMutationEpoch(key) !== epochs.get(key)) continue;
7740
+ if (this._promoteRedisEntry(key, entry, 10 * 60 * 1e3, opts?.priority ?? inferPriority(this.unnk(key))) && this.l1.has(key)) loaded++;
6828
7741
  }
6829
7742
  this.logger.info("warmFromL2 complete", {
6830
7743
  pattern,
@@ -6897,6 +7810,139 @@ var CacheService = class _CacheService {
6897
7810
  }
6898
7811
  return matched;
6899
7812
  }
7813
+ async _publishTagInvalidation(op, key, tagVersion) {
7814
+ if (this.opts.awaitInvalidationBackplane) {
7815
+ await this.publishInvalidation(op, key, tagVersion, false, true);
7816
+ } else {
7817
+ void this.publishInvalidation(op, key, tagVersion, false, true);
7818
+ }
7819
+ }
7820
+ _removeTagMembersLocal(keys) {
7821
+ const keyList = Array.isArray(keys) ? keys : Array.from(keys);
7822
+ for (const k of keyList) {
7823
+ this.l1.delete(k);
7824
+ this._bumpKeyMutation(k);
7825
+ this._removeKeyTags(k);
7826
+ this._removeKeyDependencies(k);
7827
+ this._invalidateDiskKey(k);
7828
+ }
7829
+ }
7830
+ /**
7831
+ * Executes invalidation for a single already-resolved concrete tag without
7832
+ * wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
7833
+ */
7834
+ async _invalidateConcreteTag(tag) {
7835
+ this._fenceInvalidation();
7836
+ if (this.opts.tagStrategy === "generational") {
7837
+ let newVer = 1;
7838
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7839
+ try {
7840
+ const client = await this.getRedis();
7841
+ newVer = await client.incr(this.nk(`tag_ver:${tag}`));
7842
+ } catch (err) {
7843
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7844
+ const current = this.tagVersions.get(tag)?.version ?? 0;
7845
+ newVer = current + 1;
7846
+ }
7847
+ } else {
7848
+ const current = this.tagVersions.get(tag)?.version ?? 0;
7849
+ newVer = current + 1;
7850
+ }
7851
+ this._setLocalTagVersion(tag, newVer, performance.now());
7852
+ await this._publishTagInvalidation("tag_incr", tag, newVer);
7853
+ return;
7854
+ }
7855
+ const tagKey = this.nk(`_tag_:${tag}`);
7856
+ const members = new Set(this.tagIndex.get(tagKey) ?? []);
7857
+ this.tagIndex.delete(tagKey);
7858
+ this._removeTagMembersLocal(members);
7859
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7860
+ try {
7861
+ const client = await this.getRedis();
7862
+ const redisMembers = await client.smembers(tagKey);
7863
+ for (const key of redisMembers) members.add(key);
7864
+ this._removeTagMembersLocal(redisMembers);
7865
+ const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers, tagKey])];
7866
+ await this._deleteRedisKeys(client, toDelete);
7867
+ } catch (err) {
7868
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7869
+ }
7870
+ }
7871
+ await Promise.all([...members].map((key) => this._publishTagInvalidation("del", key)));
7872
+ await this._publishTagInvalidation("tag_pattern_del", tag);
7873
+ }
7874
+ /**
7875
+ * Executes invalidation for an array of already-resolved concrete tags
7876
+ * without re-entering wildcard/cascade resolution or invalidateTag().
7877
+ */
7878
+ async _invalidateConcreteTags(tags) {
7879
+ if (tags.length === 0) return;
7880
+ if (tags.length === 1) {
7881
+ await this._invalidateConcreteTag(tags[0]);
7882
+ return;
7883
+ }
7884
+ this._fenceInvalidation();
7885
+ if (this.opts.tagStrategy === "generational") {
7886
+ const now = performance.now();
7887
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7888
+ try {
7889
+ const client = await this.getRedis();
7890
+ const pl = client.pipeline();
7891
+ for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
7892
+ const results = await pl.exec();
7893
+ for (let i = 0; i < tags.length; i++) {
7894
+ const [err, newVer] = results[i] ?? [null, null];
7895
+ const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
7896
+ this._setLocalTagVersion(tags[i], ver, now);
7897
+ await this._publishTagInvalidation("tag_incr", tags[i], ver);
7898
+ }
7899
+ return;
7900
+ } catch (err) {
7901
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7902
+ }
7903
+ }
7904
+ for (const tag of tags) {
7905
+ const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
7906
+ this._setLocalTagVersion(tag, ver, now);
7907
+ await this._publishTagInvalidation("tag_incr", tag, ver);
7908
+ }
7909
+ return;
7910
+ }
7911
+ const tagKeys = [];
7912
+ const allMembers = /* @__PURE__ */ new Set();
7913
+ for (const tag of tags) {
7914
+ const tagKey = this.nk(`_tag_:${tag}`);
7915
+ tagKeys.push(tagKey);
7916
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
7917
+ for (const k of members) allMembers.add(k);
7918
+ this.tagIndex.delete(tagKey);
7919
+ }
7920
+ this._removeTagMembersLocal(allMembers);
7921
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7922
+ try {
7923
+ const client = await this.getRedis();
7924
+ const pl = client.pipeline();
7925
+ for (const tagKey of tagKeys) pl.smembers(tagKey);
7926
+ const smResults = await pl.exec();
7927
+ const toDelete = [...allMembers];
7928
+ for (const [err, redisMembers] of smResults) {
7929
+ if (!err && redisMembers) {
7930
+ for (const k of redisMembers) {
7931
+ if (!allMembers.has(k)) toDelete.push(k);
7932
+ allMembers.add(k);
7933
+ }
7934
+ }
7935
+ }
7936
+ const keysToRemove = [...toDelete, ...tagKeys];
7937
+ await this._deleteRedisKeys(client, keysToRemove);
7938
+ this._removeTagMembersLocal(allMembers);
7939
+ } catch (err) {
7940
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7941
+ }
7942
+ }
7943
+ await Promise.all([...allMembers].map((key) => this._publishTagInvalidation("del", key)));
7944
+ for (const tag of tags) await this._publishTagInvalidation("tag_pattern_del", tag);
7945
+ }
6900
7946
  /**
6901
7947
  * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
6902
7948
  * Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
@@ -6932,68 +7978,13 @@ var CacheService = class _CacheService {
6932
7978
  const delim = this.opts.tagHierarchyDelimiter;
6933
7979
  const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
6934
7980
  if (matchedTags.size > 0) {
6935
- await this.invalidateTags(Array.from(matchedTags));
7981
+ await this._invalidateConcreteTags(Array.from(matchedTags));
6936
7982
  }
6937
7983
  const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
6938
- if (this.opts.awaitInvalidationBackplane) {
6939
- await this.publishInvalidation(op, broadcastPattern, void 0, false, true);
6940
- } else {
6941
- void this.publishInvalidation(op, broadcastPattern, void 0, false, true);
6942
- }
7984
+ await this._publishTagInvalidation(op, broadcastPattern);
6943
7985
  return;
6944
7986
  }
6945
- if (this.opts.tagStrategy === "generational") {
6946
- let newVer = 1;
6947
- if (!this._redisDisabled) {
6948
- try {
6949
- const client = await this.getRedis();
6950
- newVer = await client.incr(this.nk(`tag_ver:${tag}`));
6951
- } catch (err) {
6952
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
6953
- const current = this.tagVersions.get(tag)?.version ?? 0;
6954
- newVer = current + 1;
6955
- }
6956
- } else {
6957
- const current = this.tagVersions.get(tag)?.version ?? 0;
6958
- newVer = current + 1;
6959
- }
6960
- this._setLocalTagVersion(tag, newVer, performance.now());
6961
- if (this.opts.awaitInvalidationBackplane) {
6962
- await this.publishInvalidation("tag_incr", tag, newVer, false, true);
6963
- } else {
6964
- void this.publishInvalidation("tag_incr", tag, newVer, false, true);
6965
- }
6966
- return;
6967
- }
6968
- const tagKey = this.nk(`_tag_:${tag}`);
6969
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
6970
- for (const k of members) {
6971
- this.l1.delete(k);
6972
- this._bumpKeyMutation(k);
6973
- this._pendingDiskDeletes.add(k);
6974
- setImmediate(() => {
6975
- try {
6976
- if (!this._diskDisabled) this.disk.delete(k);
6977
- } finally {
6978
- this._pendingDiskDeletes.delete(k);
6979
- }
6980
- });
6981
- }
6982
- this.tagIndex.delete(tagKey);
6983
- if (!this._redisDisabled) {
6984
- try {
6985
- const client = await this.getRedis();
6986
- const redisMembers = await client.smembers(tagKey);
6987
- const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
6988
- if (toDelete.length > 0) {
6989
- await client.del(...toDelete, tagKey);
6990
- } else {
6991
- await client.del(tagKey);
6992
- }
6993
- } catch (err) {
6994
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
6995
- }
6996
- }
7987
+ await this._invalidateConcreteTag(tag);
6997
7988
  } catch (err) {
6998
7989
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
6999
7990
  span.recordException?.(err);
@@ -7020,96 +8011,28 @@ var CacheService = class _CacheService {
7020
8011
  const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
7021
8012
  if (hasWildcards || shouldCascade) {
7022
8013
  const allResolvedTags = /* @__PURE__ */ new Set();
8014
+ const broadcastPatterns = /* @__PURE__ */ new Set();
8015
+ const delim = this.opts.tagHierarchyDelimiter;
7023
8016
  for (const t of tags) {
7024
- if (isWildcardTag(t) || shouldCascade) {
8017
+ const tIsPattern = isWildcardTag(t);
8018
+ if (tIsPattern || shouldCascade) {
8019
+ broadcastPatterns.add(tIsPattern ? t : `${t}${delim}*`);
7025
8020
  const resolved = await this._resolveMatchingTags(t, shouldCascade);
7026
8021
  for (const rt of resolved) allResolvedTags.add(rt);
7027
8022
  } else {
7028
8023
  allResolvedTags.add(t);
7029
8024
  }
7030
8025
  }
7031
- if (allResolvedTags.size === 0) return;
7032
- tags = Array.from(allResolvedTags);
7033
- }
7034
- if (tags.length === 1) {
7035
- await this.invalidateTag(tags[0], opts);
7036
- return;
7037
- }
7038
- if (this.opts.tagStrategy === "generational") {
7039
- const now = performance.now();
7040
- if (!this._redisDisabled) {
7041
- try {
7042
- const client = await this.getRedis();
7043
- const pl = client.pipeline();
7044
- for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
7045
- const results = await pl.exec();
7046
- for (let i = 0; i < tags.length; i++) {
7047
- const [err, newVer] = results[i] ?? [null, null];
7048
- const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
7049
- this._setLocalTagVersion(tags[i], ver, now);
7050
- if (this.opts.awaitInvalidationBackplane) {
7051
- await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7052
- } else {
7053
- void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7054
- }
7055
- }
7056
- return;
7057
- } catch (err) {
7058
- this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7059
- }
8026
+ if (allResolvedTags.size > 0) {
8027
+ await this._invalidateConcreteTags(Array.from(allResolvedTags));
7060
8028
  }
7061
- for (const tag of tags) {
7062
- const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
7063
- this._setLocalTagVersion(tag, ver, now);
7064
- if (this.opts.awaitInvalidationBackplane) {
7065
- await this.publishInvalidation("tag_incr", tag, ver, false, true);
7066
- } else {
7067
- void this.publishInvalidation("tag_incr", tag, ver, false, true);
7068
- }
8029
+ const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
8030
+ for (const pattern of broadcastPatterns) {
8031
+ await this._publishTagInvalidation(op, pattern);
7069
8032
  }
7070
8033
  return;
7071
8034
  }
7072
- const tagKeys = [];
7073
- const allMembers = /* @__PURE__ */ new Set();
7074
- for (const tag of tags) {
7075
- const tagKey = this.nk(`_tag_:${tag}`);
7076
- tagKeys.push(tagKey);
7077
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
7078
- for (const k of members) allMembers.add(k);
7079
- this.tagIndex.delete(tagKey);
7080
- }
7081
- for (const k of allMembers) {
7082
- this.l1.delete(k);
7083
- this._bumpKeyMutation(k);
7084
- this._pendingDiskDeletes.add(k);
7085
- setImmediate(() => {
7086
- try {
7087
- if (!this._diskDisabled) this.disk.delete(k);
7088
- } finally {
7089
- this._pendingDiskDeletes.delete(k);
7090
- }
7091
- });
7092
- }
7093
- if (!this._redisDisabled) {
7094
- try {
7095
- const client = await this.getRedis();
7096
- const pl = client.pipeline();
7097
- for (const tagKey of tagKeys) pl.smembers(tagKey);
7098
- const smResults = await pl.exec();
7099
- const toDelete = [...allMembers];
7100
- for (const [err, redisMembers] of smResults) {
7101
- if (!err && redisMembers) {
7102
- for (const k of redisMembers) {
7103
- if (!allMembers.has(k)) toDelete.push(k);
7104
- }
7105
- }
7106
- }
7107
- const keysToRemove = [...toDelete, ...tagKeys];
7108
- if (keysToRemove.length > 0) await client.del(...keysToRemove);
7109
- } catch (err) {
7110
- this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7111
- }
7112
- }
8035
+ await this._invalidateConcreteTags(Array.from(new Set(tags)));
7113
8036
  }
7114
8037
  /**
7115
8038
  * Get the current generational tag version for a tag (synced with Redis when due).
@@ -7172,19 +8095,23 @@ var CacheService = class _CacheService {
7172
8095
  const diskLowSpace = !this._diskDisabled && this.disk.hostVolumeLowSpace;
7173
8096
  const circuitOpen = this.cb.isOpen;
7174
8097
  const latencyBypass = watchdogTel.bypassActive;
7175
- const degraded = circuitOpen || latencyBypass || diskPruning || diskLowSpace;
7176
- const healthy = this.opts.failReadinessOnDegraded ? !degraded : true;
8098
+ const backplaneUnavailable = this.opts.invalidationBackplane && !this._redisDisabled && !this._backplaneAvailable;
8099
+ const degraded = this._destroyed || circuitOpen || latencyBypass || diskPruning || diskLowSpace || backplaneUnavailable;
8100
+ const healthy = !this._destroyed && (this.opts.failReadinessOnDegraded ? !degraded : true);
7177
8101
  const reasons = [];
7178
8102
  if (circuitOpen) reasons.push("redis_circuit_breaker_open");
7179
8103
  if (latencyBypass) reasons.push(`disk_latency_bypass_stage_${watchdogTel.bypassStage}`);
7180
8104
  if (diskPruning) reasons.push("disk_quota_watermark_pruning_active");
7181
8105
  if (diskLowSpace) reasons.push("disk_host_volume_low_space");
8106
+ if (backplaneUnavailable) reasons.push("invalidation_backplane_unavailable");
8107
+ if (this._destroyed) reasons.push("cache_destroyed");
7182
8108
  return {
7183
8109
  healthy,
7184
8110
  degraded,
7185
8111
  reasons,
7186
8112
  details: {
7187
- redisConnected: !circuitOpen && !this._redisDisabled,
8113
+ redisConnected: !this._destroyed && !circuitOpen && !!this.redis && (this.redis.status === "ready" || this.redis.isOpen === true),
8114
+ backplaneReady: this._backplaneAvailable,
7188
8115
  circuitBreakerState: this.cb.currentState,
7189
8116
  diskPruningActive: diskPruning,
7190
8117
  diskHostVolumeLowSpace: diskLowSpace,
@@ -7206,23 +8133,28 @@ var CacheService = class _CacheService {
7206
8133
  */
7207
8134
  async drainToL2() {
7208
8135
  this._assertActive("drainToL2");
7209
- if (this._redisDisabled) return 0;
8136
+ if (this._redisDisabled || this.opts.l2WriteMode === "read-only") return 0;
7210
8137
  try {
7211
- const client = await this.getRedis();
7212
8138
  const entries = this.l1.exportEntries([]);
7213
- const now = Date.now();
7214
8139
  if (entries.length === 0) return 0;
7215
- const pl = client.pipeline();
7216
- for (const { key, entry } of entries) {
7217
- const remainingMs = entry.expiresAt - now;
7218
- if (remainingMs <= 0) continue;
7219
- const ttlSecs = Math.max(1, Math.ceil(remainingMs / 1e3));
7220
- const s = JSON.stringify(entry.value);
7221
- const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
7222
- pl.setex(key, ttlSecs, stored);
7223
- }
7224
- await pl.exec();
7225
- return entries.length;
8140
+ let written = 0;
8141
+ await Promise.all(entries.map(async ({ key, entry }) => {
8142
+ const epoch = this._getKeyMutationEpoch(key);
8143
+ if (entry.expiresAt <= Date.now()) return;
8144
+ await this._writeRedisEntry(
8145
+ key,
8146
+ this.l1.resolveValue(entry),
8147
+ entry.expiresAt,
8148
+ entry.setAt ?? Date.now(),
8149
+ entry.tagVersions,
8150
+ entry.staleAt,
8151
+ entry.tags,
8152
+ entry.dependsOn,
8153
+ () => this._getKeyMutationEpoch(key) === epoch
8154
+ );
8155
+ written++;
8156
+ }));
8157
+ return written;
7226
8158
  } catch (err) {
7227
8159
  this.logger.debug("drainToL2: Redis unavailable", { error: err.message });
7228
8160
  return 0;
@@ -7252,7 +8184,7 @@ var CacheService = class _CacheService {
7252
8184
  this._assertActive("setIfAbsent");
7253
8185
  const k = this.nk(cacheKey);
7254
8186
  if (this.l1.has(k)) return false;
7255
- if (!this._redisDisabled) {
8187
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7256
8188
  try {
7257
8189
  const client = await this.getRedis();
7258
8190
  const serialized = JSON.stringify(value);
@@ -7269,7 +8201,7 @@ var CacheService = class _CacheService {
7269
8201
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
7270
8202
  const p = priority ?? inferPriority(cacheKey);
7271
8203
  this._bumpKeyMutation(k);
7272
- this._pendingDiskDeletes.delete(k);
8204
+ this._invalidateDiskKey(k);
7273
8205
  this.l1.set(k, value, ttlMs, p);
7274
8206
  this.counters.sets++;
7275
8207
  return true;
@@ -7296,7 +8228,7 @@ var CacheService = class _CacheService {
7296
8228
  const token = import_crypto3.default.randomUUID();
7297
8229
  const deadline = Date.now() + acquireTimeout;
7298
8230
  let acquired = false;
7299
- if (!this._redisDisabled) {
8231
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7300
8232
  let client = null;
7301
8233
  try {
7302
8234
  client = await this.getRedis();
@@ -7391,7 +8323,9 @@ var CacheService = class _CacheService {
7391
8323
  const gDiskFiles = meter.createObservableGauge("tricache.disk.files", { description: "Current L1.5 disk file count" });
7392
8324
  const gDiskBytes = meter.createObservableGauge("tricache.disk.bytes", { description: "Current L1.5 disk size in bytes" });
7393
8325
  const gBloomFpr = meter.createObservableGauge("tricache.bloom.fpr", { description: "Bloom filter false-positive rate" });
7394
- meter.addBatchObservableCallback((observableResult) => {
8326
+ const observables = [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr];
8327
+ const callback = (observableResult) => {
8328
+ if (this._destroyed) return;
7395
8329
  const stats = this.stats();
7396
8330
  const l1 = stats.l1;
7397
8331
  const disk = stats.disk;
@@ -7404,7 +8338,9 @@ var CacheService = class _CacheService {
7404
8338
  observableResult.observe(gDiskFiles, disk.files, attrs);
7405
8339
  observableResult.observe(gDiskBytes, disk.sizeKB * 1024, attrs);
7406
8340
  observableResult.observe(gBloomFpr, fpr, attrs);
7407
- }, [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr]);
8341
+ };
8342
+ meter.addBatchObservableCallback(callback, observables);
8343
+ this._otelCleanup = () => meter.removeBatchObservableCallback?.(callback, observables);
7408
8344
  } catch (err) {
7409
8345
  this.logger.warn("Failed to initialize OpenTelemetry metrics meter", { error: err.message });
7410
8346
  }
@@ -7674,8 +8610,25 @@ var CacheService = class _CacheService {
7674
8610
  /** Close Redis connections and stop all background timers. */
7675
8611
  async destroy() {
7676
8612
  this._destroyed = true;
8613
+ this._fenceInvalidation();
8614
+ this._backplaneAvailable = false;
8615
+ this.l1.clear();
8616
+ try {
8617
+ this._otelCleanup?.();
8618
+ } catch {
8619
+ }
8620
+ this._otelCleanup = null;
8621
+ this.tagVersions.clear();
8622
+ for (const dispose of this._backplaneDisposers.splice(0)) dispose();
7677
8623
  this._pendingDiskDeletes.clear();
7678
8624
  this._keyMutationEpochs.clear();
8625
+ this.inflight.clear();
8626
+ this.revalidating.clear();
8627
+ this._l1Counters.clear();
8628
+ this.tagIndex.clear();
8629
+ this.keyTags.clear();
8630
+ this.dependencyIndex.clear();
8631
+ this.keyDependencies.clear();
7679
8632
  const g = globalThis;
7680
8633
  const key = _CacheService.globalKey(this.opts);
7681
8634
  if (g[key] === this) {
@@ -7696,6 +8649,12 @@ var CacheService = class _CacheService {
7696
8649
  this._workerPool = null;
7697
8650
  }
7698
8651
  if (this.subClient) {
8652
+ if (this.opts.redisSubClient) {
8653
+ try {
8654
+ await this.subClient.unsubscribe?.(this.backplaneChannel);
8655
+ } catch {
8656
+ }
8657
+ }
7699
8658
  if (!this.opts.redisSubClient) {
7700
8659
  try {
7701
8660
  this.subClient.disconnect();
@@ -7705,7 +8664,7 @@ var CacheService = class _CacheService {
7705
8664
  this.subClient = null;
7706
8665
  }
7707
8666
  if (this.streamClient) {
7708
- try {
8667
+ if (!this.opts.redisSubClient) try {
7709
8668
  this.streamClient.disconnect();
7710
8669
  } catch {
7711
8670
  }
@@ -7773,18 +8732,31 @@ function resolveCacheLife(profileOrName) {
7773
8732
  }
7774
8733
  return null;
7775
8734
  }
7776
- async function drainStream(stream) {
8735
+ async function drainStream(stream, maxBytes) {
7777
8736
  const reader = stream.getReader();
7778
8737
  const chunks = [];
7779
- while (true) {
7780
- const { done, value } = await reader.read();
7781
- if (done) break;
7782
- if (value) chunks.push(value);
8738
+ let size = 0;
8739
+ try {
8740
+ while (true) {
8741
+ const { done, value } = await reader.read();
8742
+ if (done) break;
8743
+ if (value) {
8744
+ size += value.byteLength;
8745
+ if (size > maxBytes) throw new Error("RSC stream exceeds maxStreamBytes");
8746
+ chunks.push(Uint8Array.from(value));
8747
+ }
8748
+ }
8749
+ return Buffer.concat(chunks);
8750
+ } catch (error) {
8751
+ void reader.cancel(error).catch(() => {
8752
+ });
8753
+ throw error;
8754
+ } finally {
8755
+ reader.releaseLock();
7783
8756
  }
7784
- return Buffer.concat(chunks);
7785
8757
  }
7786
8758
  function createReadableStream(buffer) {
7787
- const uint8 = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
8759
+ const uint8 = Uint8Array.from(buffer);
7788
8760
  return new ReadableStream({
7789
8761
  start(controller) {
7790
8762
  controller.enqueue(uint8);
@@ -7795,8 +8767,14 @@ function createReadableStream(buffer) {
7795
8767
  var TriCacheHandler = class {
7796
8768
  cache;
7797
8769
  logger;
8770
+ maxStreamBytes;
8771
+ pendingSets = /* @__PURE__ */ new Map();
8772
+ observedTags = /* @__PURE__ */ new Map();
7798
8773
  constructor(options = {}) {
7799
8774
  this.logger = options.logger ?? consoleLogger;
8775
+ this.maxStreamBytes = options.maxStreamBytes ?? 16 * 1024 * 1024;
8776
+ if (!Number.isFinite(this.maxStreamBytes) || this.maxStreamBytes <= 0) throw new Error("maxStreamBytes must be finite and positive");
8777
+ if (options.tagStrategy && options.tagStrategy !== "generational") throw new Error("Next.js cache handlers require tagStrategy: generational");
7800
8778
  const isBuildPhase = options.isBuildPhase ?? (typeof process !== "undefined" && (process.env.NEXT_PHASE === "phase-production-build" || process.env.NEXT_PHASE === "phase-export"));
7801
8779
  this.cache = CacheService.create({
7802
8780
  ...options,
@@ -7806,37 +8784,62 @@ var TriCacheHandler = class {
7806
8784
  disableRedis: isBuildPhase ? true : options.disableRedis
7807
8785
  });
7808
8786
  }
7809
- /**
7810
- * Get an entry from cache. Checks softTags against generational tag versions
7811
- * and returns a fresh unlocked ReadableStream if the stored value was a stream.
7812
- */
7813
- async get(cacheKey, ctx) {
7814
- const stored = await this.cache.get(
7815
- cacheKey,
7816
- async () => null
7817
- );
8787
+ async get(cacheKey, context) {
8788
+ let pending = this.pendingSets.get(cacheKey);
8789
+ while (pending) {
8790
+ await pending.completion;
8791
+ pending = this.pendingSets.get(cacheKey);
8792
+ }
8793
+ const native = Array.isArray(context);
8794
+ const ctx = native ? { softTags: context } : context;
8795
+ const stored = await this.cache.peek(cacheKey);
7818
8796
  if (!stored || stored.data == null) {
7819
8797
  return void 0;
7820
8798
  }
7821
- if (ctx?.softTags && ctx.softTags.length > 0) {
7822
- const softTags = ctx.softTags;
7823
- const currentVers = await Promise.all(softTags.map((st) => this.cache.getTagVersion(st)));
7824
- for (let i = 0; i < softTags.length; i++) {
7825
- const storedSoftVer = stored.softTagVersions?.[softTags[i]] ?? 0;
7826
- if (currentVers[i] > storedSoftVer) {
7827
- return void 0;
8799
+ const expire = stored.expire ?? stored.ttl;
8800
+ if (!Number.isFinite(stored.timestamp) || !Number.isFinite(expire) || Date.now() >= stored.timestamp + expire * 1e3) return void 0;
8801
+ const tags = [.../* @__PURE__ */ new Set([...stored.tags, ...ctx?.softTags ?? []])];
8802
+ const versions = await Promise.all(tags.map((tag) => this.cache.getTagVersion(tag)));
8803
+ const states = await this.cache.mget(tags.map((tag) => `_next_tag_state_:${tag}`));
8804
+ let revalidate = stored.revalidate ?? stored.ttl;
8805
+ for (let index = 0; index < tags.length; index++) {
8806
+ const tag = tags[index];
8807
+ const state = states[index];
8808
+ const snapshot = stored.generations?.[tag] ?? stored.softTagVersions?.[tag];
8809
+ if (state && (state.revalidatedAt > stored.timestamp || state.revalidatedAt === stored.timestamp && snapshot !== versions[index])) {
8810
+ if (state.expiredAt !== void 0 && state.expiredAt <= Date.now()) return void 0;
8811
+ revalidate = -1;
8812
+ } else if (!state && versions[index] > 0) {
8813
+ if (snapshot !== void 0 && versions[index] > snapshot) return void 0;
8814
+ if (snapshot === void 0) {
8815
+ const observed = this.observeTag(tag, versions[index]);
8816
+ if (stored.timestamp <= observed) return void 0;
7828
8817
  }
7829
8818
  }
7830
8819
  }
7831
8820
  let val = stored.data;
7832
- if (stored.isStream && (Buffer.isBuffer(val) || val instanceof Uint8Array)) {
7833
- val = createReadableStream(val);
8821
+ if (stored.isStream) {
8822
+ let bytes;
8823
+ if (stored.streamEncoding === "base64" && typeof val === "string") {
8824
+ if (val.length > Math.ceil(this.maxStreamBytes / 3) * 4) return void 0;
8825
+ bytes = Buffer.from(val, "base64");
8826
+ } else if (Buffer.isBuffer(val) || val instanceof Uint8Array) bytes = val;
8827
+ else if (val && typeof val === "object" && val.type === "Buffer" && Array.isArray(val.data)) {
8828
+ bytes = Buffer.from(val.data);
8829
+ } else return void 0;
8830
+ if (bytes.length > this.maxStreamBytes) return void 0;
8831
+ val = createReadableStream(bytes);
8832
+ } else if (native) {
8833
+ return void 0;
7834
8834
  }
7835
8835
  return {
7836
8836
  value: val,
7837
8837
  tags: stored.tags,
7838
8838
  timestamp: stored.timestamp,
7839
- ttl: stored.ttl
8839
+ ttl: stored.ttl,
8840
+ stale: stored.stale ?? 300,
8841
+ revalidate,
8842
+ expire
7840
8843
  };
7841
8844
  }
7842
8845
  /**
@@ -7844,92 +8847,111 @@ var TriCacheHandler = class {
7844
8847
  * before storing. Catches mid-flight stream aborts to avoid crashing Next.js.
7845
8848
  */
7846
8849
  async set(cacheKey, pendingEntry, ctx) {
7847
- const entry = await pendingEntry;
7848
- if (!entry || entry.value == null) return;
7849
- let dataToStore = entry.value;
7850
- const isStream = Boolean(
7851
- dataToStore && typeof dataToStore.getReader === "function"
7852
- );
7853
- if (isStream) {
7854
- try {
7855
- dataToStore = await drainStream(dataToStore);
7856
- } catch (streamErr) {
7857
- this.logger.debug("Next.js cacheHandler: stream drain failed mid-flight, skipping cache", {
7858
- cacheKey,
7859
- error: streamErr.message
7860
- });
7861
- return;
8850
+ const token = Symbol(cacheKey);
8851
+ let finish;
8852
+ const completion = new Promise((resolve) => {
8853
+ finish = resolve;
8854
+ });
8855
+ this.pendingSets.set(cacheKey, { token, completion });
8856
+ try {
8857
+ const canCommit = this.cache.captureMutationFence(cacheKey);
8858
+ const entry = await pendingEntry;
8859
+ if (!entry || entry.value == null) return;
8860
+ const tags = Array.from(/* @__PURE__ */ new Set([...entry.tags ?? [], ...ctx?.tags ?? []]));
8861
+ const allTags = [.../* @__PURE__ */ new Set([...tags, ...ctx?.softTags ?? []])];
8862
+ const initialVersions = Object.fromEntries(await Promise.all(allTags.map(async (tag) => [tag, await this.cache.getTagVersion(tag)])));
8863
+ let dataToStore = entry.value;
8864
+ const isStream = Boolean(
8865
+ dataToStore && typeof dataToStore.getReader === "function"
8866
+ );
8867
+ if (isStream) {
8868
+ try {
8869
+ dataToStore = (await drainStream(dataToStore, this.maxStreamBytes)).toString("base64");
8870
+ } catch (streamErr) {
8871
+ this.logger.debug("Next.js cacheHandler: stream drain failed mid-flight, skipping cache", {
8872
+ cacheKey,
8873
+ error: streamErr.message
8874
+ });
8875
+ return;
8876
+ }
7862
8877
  }
7863
- }
7864
- let ttl;
7865
- const resolvedLife = resolveCacheLife(ctx?.cacheLife);
7866
- if (resolvedLife) {
7867
- ttl = resolvedLife.ttl;
7868
- } else if (typeof entry.ttl === "number") {
7869
- ttl = entry.ttl;
7870
- } else if (typeof ctx?.revalidate === "number") {
7871
- if (ctx.revalidate <= 0) return;
7872
- ttl = ctx.revalidate;
7873
- } else if (ctx?.revalidate === false) {
7874
- ttl = 31536e3;
7875
- } else {
7876
- ttl = 300;
7877
- }
7878
- const tags = Array.from(/* @__PURE__ */ new Set([...entry.tags ?? [], ...ctx?.tags ?? []]));
7879
- let softTagVersions;
7880
- if (ctx?.softTags && ctx.softTags.length > 0) {
7881
- const softTags = ctx.softTags;
7882
- const vers = await Promise.all(softTags.map((st) => this.cache.getTagVersion(st)));
7883
- softTagVersions = {};
7884
- for (let i = 0; i < softTags.length; i++) {
7885
- softTagVersions[softTags[i]] = vers[i];
8878
+ let ttl;
8879
+ const resolvedLife = resolveCacheLife(ctx?.cacheLife);
8880
+ if (resolvedLife) {
8881
+ ttl = resolvedLife.ttl;
8882
+ } else if (typeof entry.revalidate === "number") {
8883
+ ttl = entry.revalidate;
8884
+ } else if (typeof entry.ttl === "number") {
8885
+ ttl = entry.ttl;
8886
+ } else if (typeof ctx?.revalidate === "number") {
8887
+ if (ctx.revalidate <= 0) return;
8888
+ ttl = ctx.revalidate;
8889
+ } else if (ctx?.revalidate === false) {
8890
+ ttl = 31536e3;
8891
+ } else {
8892
+ ttl = 300;
8893
+ }
8894
+ const expire = entry.expire ?? (resolvedLife ? resolvedLife.ttl + resolvedLife.swr : ttl);
8895
+ const timestamp = entry.timestamp ?? Date.now();
8896
+ if (!Number.isFinite(expire) || expire <= 0 || !Number.isFinite(timestamp) || timestamp > Date.now() + (this.cache.options.clockSkewToleranceMs ?? 250)) return;
8897
+ const remaining = timestamp + expire * 1e3 - Date.now();
8898
+ if (remaining <= 0 || !canCommit() || this.pendingSets.get(cacheKey)?.token !== token) return;
8899
+ const finalVersions = await Promise.all(allTags.map((tag) => this.cache.getTagVersion(tag)));
8900
+ if (allTags.some((tag, index) => finalVersions[index] !== initialVersions[tag])) return;
8901
+ const tagStates = await this.cache.mget(allTags.map((tag) => `_next_tag_state_:${tag}`));
8902
+ if (tagStates.some((state) => state && state.revalidatedAt > timestamp)) return;
8903
+ let softTagVersions;
8904
+ if (ctx?.softTags && ctx.softTags.length > 0) {
8905
+ const softTags = ctx.softTags;
8906
+ const vers = await Promise.all(softTags.map((st) => this.cache.getTagVersion(st)));
8907
+ softTagVersions = {};
8908
+ for (let i = 0; i < softTags.length; i++) {
8909
+ softTagVersions[softTags[i]] = vers[i];
8910
+ }
7886
8911
  }
8912
+ const stored = {
8913
+ data: dataToStore,
8914
+ isStream,
8915
+ tags,
8916
+ timestamp,
8917
+ ttl,
8918
+ softTagVersions,
8919
+ generations: initialVersions,
8920
+ stale: entry.stale ?? (typeof ctx?.cacheLife === "string" ? PRESET_CACHE_LIFE_PROFILES[ctx.cacheLife]?.stale : typeof ctx?.cacheLife === "object" ? ctx.cacheLife.stale : void 0) ?? 300,
8921
+ revalidate: ttl,
8922
+ expire,
8923
+ streamEncoding: isStream ? "base64" : void 0
8924
+ };
8925
+ if (!canCommit() || this.pendingSets.get(cacheKey)?.token !== token) return;
8926
+ await this.cache.set(cacheKey, stored, remaining / 1e3, void 0, { tags: [] });
8927
+ } finally {
8928
+ finish();
8929
+ if (this.pendingSets.get(cacheKey)?.token === token) this.pendingSets.delete(cacheKey);
7887
8930
  }
7888
- const stored = {
7889
- data: dataToStore,
7890
- isStream,
7891
- tags,
7892
- timestamp: entry.timestamp ?? Date.now(),
7893
- ttl,
7894
- softTagVersions
7895
- };
7896
- await this.cache.set(cacheKey, stored, ttl, void 0, tags.length > 0 ? { tags } : void 0);
8931
+ }
8932
+ observeTag(tag, version) {
8933
+ const known = this.observedTags.get(tag);
8934
+ if (known?.version === version) return known.observedAt;
8935
+ if (this.observedTags.size >= 1e4) {
8936
+ const oldest = this.observedTags.keys().next().value;
8937
+ if (oldest !== void 0) this.observedTags.delete(oldest);
8938
+ }
8939
+ const observedAt = Date.now();
8940
+ this.observedTags.set(tag, { version, observedAt });
8941
+ return observedAt;
7897
8942
  }
7898
8943
  /**
7899
- * Returns the expiration timestamp (ms since epoch) of the most relevant
7900
- * cached entry for the given tags, or 0 when nothing is tracked. Next.js
7901
- * uses this to decide whether a revalidation is due — a hardcoded 0 means
7902
- * "always expired", so this reads the real stored entries instead.
8944
+ * Delegate soft-tag checking to get() using Next's Infinity sentinel.
7903
8945
  */
7904
8946
  async getExpiration(tags) {
7905
- try {
7906
- let maxExpiration = 0;
7907
- const tagSet = new Set(tags);
7908
- const l1 = this.cache.l1;
7909
- l1.scan((key, entry) => {
7910
- if (!entry.tagVersions) return;
7911
- for (const tag of Object.keys(entry.tagVersions)) {
7912
- if (!tagSet.has(tag)) continue;
7913
- const exp = entry.expiresAt ?? 0;
7914
- if (exp > maxExpiration) maxExpiration = exp;
7915
- return;
7916
- }
7917
- }, 0);
7918
- return maxExpiration;
7919
- } catch (err) {
7920
- this.logger.debug("Next.js cacheHandler getExpiration fail-soft", { error: err.message });
7921
- return 0;
7922
- }
8947
+ return tags.length ? Infinity : 0;
7923
8948
  }
7924
8949
  /**
7925
- * Reconcile local generational tag knowledge against shared state: drops the
7926
- * in-memory tag-version cache so every subsequent read re-syncs versions
7927
- * from Redis. The previous implementation was an empty try/catch.
8950
+ * Force subsequent tag reads to re-sync without forgetting monotonic versions.
7928
8951
  */
7929
8952
  async refreshTags() {
7930
8953
  try {
7931
- const cache = this.cache;
7932
- cache.tagVersions?.clear();
8954
+ this.cache.refreshTagVersions();
7933
8955
  } catch (err) {
7934
8956
  this.logger.debug("Next.js cacheHandler refreshTags fail-soft catch", {
7935
8957
  error: err.message
@@ -7939,8 +8961,15 @@ var TriCacheHandler = class {
7939
8961
  /**
7940
8962
  * Update or invalidate tags cluster-wide.
7941
8963
  */
7942
- async updateTags(tags) {
8964
+ async updateTags(tags, durations) {
7943
8965
  if (!tags || tags.length === 0) return;
8966
+ const now = Date.now();
8967
+ const delay = durations && durations.expire === void 0 ? void 0 : Math.max(0, durations?.expire ?? 0) * 1e3;
8968
+ if (delay !== void 0 && !Number.isFinite(delay)) throw new Error("Tag expiry duration must be finite");
8969
+ await Promise.all(tags.map((tag) => this.cache.set(`_next_tag_state_:${tag}`, {
8970
+ revalidatedAt: now,
8971
+ expiredAt: delay === void 0 ? void 0 : now + delay
8972
+ }, 0, 3 /* HIGH */)));
7944
8973
  await this.cache.invalidateTags(tags);
7945
8974
  }
7946
8975
  };
@@ -7967,10 +8996,7 @@ var TriCacheISRHandler = class {
7967
8996
  if (this.requestCache.has(key)) {
7968
8997
  return this.requestCache.get(key) ?? null;
7969
8998
  }
7970
- const stored = await this.cache.get(
7971
- key,
7972
- async () => null
7973
- );
8999
+ const stored = await this.cache.peek(key);
7974
9000
  if (stored) {
7975
9001
  this.requestCache.set(key, stored);
7976
9002
  return stored;