tricache 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +36 -28
  2. package/dist/{cache-service-CREOp7MM.d.ts → cache-service-B108FzER.d.ts} +36 -4
  3. package/dist/cache-service-CWI4jkS7.d.cts +963 -0
  4. package/dist/{cache-service-MG7PN6MX.js → cache-service-GYPZFB7O.js} +2 -2
  5. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  6. package/dist/{chunk-2AJKEQMZ.js → chunk-H4GFLQ26.js} +7 -4
  7. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  8. package/dist/chunk-OYDU3SMI.js +89 -0
  9. package/dist/{chunk-3I5L7K6I.js → chunk-VNRDL5RA.js} +102 -140
  10. package/dist/{chunk-JYQFQJNJ.js → chunk-WYF7NOAT.js} +1443 -609
  11. package/dist/cli.cjs +1367 -625
  12. package/dist/cli.d.cts +12 -0
  13. package/dist/cli.js +27 -6
  14. package/dist/dashboard/index.cjs +111 -29
  15. package/dist/dashboard/index.d.cts +185 -0
  16. package/dist/dashboard/index.d.ts +5 -3
  17. package/dist/dashboard/index.js +1 -1
  18. package/dist/drizzle/index.cjs +1370 -624
  19. package/dist/drizzle/index.d.cts +46 -0
  20. package/dist/drizzle/index.d.ts +2 -2
  21. package/dist/drizzle/index.js +1 -1
  22. package/dist/edge/index.cjs +227 -123
  23. package/dist/edge/index.d.cts +127 -0
  24. package/dist/edge/index.d.ts +3 -3
  25. package/dist/edge/index.js +201 -117
  26. package/dist/hono/index.cjs +1418 -644
  27. package/dist/hono/index.d.cts +93 -0
  28. package/dist/hono/index.d.ts +7 -5
  29. package/dist/hono/index.js +16 -9
  30. package/dist/{hono-DSV2ve66.d.ts → hono-3rDMYVtY.d.ts} +16 -3
  31. package/dist/hono-C886ok3X.d.cts +391 -0
  32. package/dist/http/index.cjs +1514 -679
  33. package/dist/http/index.d.cts +103 -0
  34. package/dist/http/index.d.ts +13 -5
  35. package/dist/http/index.js +92 -43
  36. package/dist/index.cjs +1671 -790
  37. package/dist/index.d.cts +1006 -0
  38. package/dist/index.d.ts +39 -8
  39. package/dist/index.js +8 -8
  40. package/dist/murmur3-CMGw9PbV.d.cts +98 -0
  41. package/dist/nestjs/index.cjs +1454 -649
  42. package/dist/nestjs/index.d.cts +285 -0
  43. package/dist/nestjs/index.d.ts +103 -30
  44. package/dist/nestjs/index.js +115 -32
  45. package/dist/next/index.cjs +1512 -718
  46. package/dist/next/index.d.cts +232 -0
  47. package/dist/next/index.d.ts +33 -11
  48. package/dist/next/index.js +172 -99
  49. package/dist/prisma/index.cjs +11 -1
  50. package/dist/prisma/index.d.cts +62 -0
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +11 -1
  53. package/dist/serialize-worker.d.cts +2 -0
  54. package/dist/{types-Dyip5wAl.d.ts → types-BA4pz1A0.d.cts} +24 -9
  55. package/dist/types-BA4pz1A0.d.ts +1519 -0
  56. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  57. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  58. package/package.json +96 -36
  59. package/src/adapters/auto-pipeliner.ts +107 -24
  60. package/src/adapters/node-redis.ts +106 -27
  61. package/src/cache-service.ts +802 -502
  62. package/src/cli.ts +24 -6
  63. package/src/cross-region.ts +21 -3
  64. package/src/dashboard/handler.ts +26 -6
  65. package/src/dashboard/html.ts +35 -10
  66. package/src/dashboard/index.ts +35 -13
  67. package/src/dashboard/types.ts +3 -1
  68. package/src/disk-tier.ts +171 -65
  69. package/src/edge/cache.ts +145 -97
  70. package/src/edge/hono.ts +23 -6
  71. package/src/edge/types.ts +2 -0
  72. package/src/hono/index.ts +19 -9
  73. package/src/http/express.ts +62 -17
  74. package/src/http/fastify.ts +35 -21
  75. package/src/http/utils.ts +54 -20
  76. package/src/ipc-telemetry.ts +35 -9
  77. package/src/nestjs/decorators.ts +1 -1
  78. package/src/nestjs/index.ts +2 -0
  79. package/src/nestjs/keyv-adapter.ts +68 -0
  80. package/src/nestjs/tricache.module.ts +13 -11
  81. package/src/nestjs/tricache.store.ts +51 -20
  82. package/src/nestjs/types.ts +29 -15
  83. package/src/next/cache-handler.ts +131 -53
  84. package/src/next/index.ts +1 -0
  85. package/src/next/types.ts +21 -0
  86. package/src/prisma/index.ts +12 -1
  87. package/src/smart-memory-cache.ts +63 -26
  88. package/src/types.ts +25 -2
  89. package/src/utils/cgroup.ts +12 -0
  90. package/src/utils/deadline.ts +14 -0
  91. package/src/utils/diagnostics.ts +27 -0
  92. package/src/utils/redis-slot.ts +13 -0
  93. package/src/wasm/bloom-filter-wasm.ts +9 -4
  94. package/src/worker-pool.ts +17 -8
  95. package/src/wtiny-lfu.ts +20 -6
  96. package/dist/chunk-BQRURGGD.js +0 -60
package/dist/index.cjs CHANGED
@@ -92,7 +92,7 @@ __export(index_exports, {
92
92
  module.exports = __toCommonJS(index_exports);
93
93
 
94
94
  // src/cache-service.ts
95
- var import_ioredis = require("ioredis");
95
+ var import_ioredis2 = require("ioredis");
96
96
 
97
97
  // src/codec.ts
98
98
  var import_msgpackr = require("msgpackr");
@@ -127,6 +127,127 @@ var defaultCodec = new CacheCodec({
127
127
  moreTypes: true
128
128
  });
129
129
 
130
+ // src/cross-region.ts
131
+ var import_node_crypto = require("crypto");
132
+ function isCrossRegionInvalidationEvent(value) {
133
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
134
+ const event = value;
135
+ const text = (key, max) => typeof event[key] === "string" && event[key].length > 0 && event[key].length <= max;
136
+ 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);
137
+ }
138
+ function createHttpMeshRelay(options) {
139
+ const peerUrls = options.peerUrls;
140
+ const timeoutMs = options.timeoutMs ?? 3e3;
141
+ const fetcher = options.fetchFn ?? globalThis.fetch;
142
+ const headers = {
143
+ "Content-Type": "application/json"
144
+ };
145
+ if (options.authSecret) {
146
+ headers["Authorization"] = `Bearer ${options.authSecret}`;
147
+ headers["X-TriCache-Auth"] = options.authSecret;
148
+ }
149
+ return {
150
+ async broadcast(event) {
151
+ if (!peerUrls.length) return;
152
+ const body = JSON.stringify(event);
153
+ const results = await Promise.allSettled(
154
+ peerUrls.map(async (url) => {
155
+ const res = await fetcher(url, {
156
+ method: "POST",
157
+ headers,
158
+ body,
159
+ signal: AbortSignal.timeout(timeoutMs)
160
+ });
161
+ if (!res.ok) {
162
+ throw new Error(`HttpMeshRelay: peer ${url} returned HTTP ${res.status} ${res.statusText}`);
163
+ }
164
+ })
165
+ );
166
+ const failures = results.filter((result) => result.status === "rejected");
167
+ if (failures.length) throw new AggregateError(failures.map((result) => result.reason), `Cross-region delivery failed for ${failures.length} peer(s)`);
168
+ }
169
+ };
170
+ }
171
+ function createCustomCrossRegionRelay(relay) {
172
+ return relay;
173
+ }
174
+ function createMemoryCrossRegionRelay() {
175
+ const handlers = /* @__PURE__ */ new Map();
176
+ let broadcastCount = 0;
177
+ return {
178
+ async broadcast(event) {
179
+ broadcastCount++;
180
+ const promises = [];
181
+ for (const [region, set] of handlers.entries()) {
182
+ if (region !== event.originRegion) {
183
+ for (const fn of set) {
184
+ promises.push(Promise.resolve(fn(event)));
185
+ }
186
+ }
187
+ }
188
+ const results = await Promise.allSettled(promises);
189
+ const failures = results.filter((result) => result.status === "rejected");
190
+ if (failures.length) throw new AggregateError(failures.map((result) => result.reason), "Cross-region handler failed");
191
+ },
192
+ register(region, handler) {
193
+ if (!handlers.has(region)) {
194
+ handlers.set(region, /* @__PURE__ */ new Set());
195
+ }
196
+ handlers.get(region).add(handler);
197
+ return () => {
198
+ handlers.get(region)?.delete(handler);
199
+ };
200
+ },
201
+ getBroadcastCount() {
202
+ return broadcastCount;
203
+ },
204
+ clear() {
205
+ handlers.clear();
206
+ broadcastCount = 0;
207
+ }
208
+ };
209
+ }
210
+ function createCrossRegionWebhookHandler(cache, options = {}) {
211
+ return async function handleCrossRegionWebhook(req) {
212
+ if (options.authSecret) {
213
+ const authHeader = req.headers["authorization"] ?? req.headers["Authorization"];
214
+ const customHeader = req.headers["x-tricache-auth"] ?? req.headers["X-TriCache-Auth"];
215
+ const bearer = typeof authHeader === "string" && authHeader.startsWith("Bearer ") ? authHeader.slice(7).trim() : authHeader;
216
+ const provided = typeof customHeader === "string" ? customHeader : bearer;
217
+ if (typeof provided !== "string" || !(0, import_node_crypto.timingSafeEqual)((0, import_node_crypto.createHash)("sha256").update(provided).digest(), (0, import_node_crypto.createHash)("sha256").update(options.authSecret).digest())) {
218
+ return {
219
+ status: 401,
220
+ body: { ok: false, message: "Unauthorized: invalid or missing auth secret" }
221
+ };
222
+ }
223
+ }
224
+ try {
225
+ let event;
226
+ if (typeof req.body === "string") {
227
+ event = JSON.parse(req.body);
228
+ } else if (req.body && typeof req.body === "object") {
229
+ event = req.body;
230
+ } else {
231
+ return {
232
+ status: 400,
233
+ body: { ok: false, message: "Invalid payload: body must be JSON object" }
234
+ };
235
+ }
236
+ if (!isCrossRegionInvalidationEvent(event)) return { status: 400, body: { ok: false, message: "Invalid invalidation event" } };
237
+ const accepted = await cache.receiveCrossRegionInvalidation(event);
238
+ return {
239
+ status: 200,
240
+ body: { ok: true, message: accepted ? "Invalidation applied" : "Invalidation ignored (deduplicated or self)" }
241
+ };
242
+ } catch (err) {
243
+ return {
244
+ status: 400,
245
+ body: { ok: false, message: err.message }
246
+ };
247
+ }
248
+ };
249
+ }
250
+
130
251
  // src/cache-service.ts
131
252
  var import_crypto3 = __toESM(require("crypto"), 1);
132
253
  var import_os3 = __toESM(require("os"), 1);
@@ -153,7 +274,8 @@ try {
153
274
  _workerFile = jsPath;
154
275
  }
155
276
  } catch {
156
- _workerFile = (0, import_path.join)(__dirname, "serialize-worker.js");
277
+ const sibling = (0, import_path.join)(__dirname, "serialize-worker.js");
278
+ _workerFile = (0, import_fs.existsSync)(sibling) ? sibling : (0, import_path.join)((0, import_path.dirname)(__dirname), "serialize-worker.js");
157
279
  }
158
280
  function getTransferableArrayBuffer(buf) {
159
281
  if (buf.buffer instanceof ArrayBuffer) {
@@ -186,6 +308,7 @@ var WorkerPool = class {
186
308
  }
187
309
  _spawnWorkers(opts) {
188
310
  const size = Math.max(1, opts.size ?? Math.min(4, availableCpus()));
311
+ if (!Number.isInteger(size) || size > 32 || !(0, import_fs.existsSync)(_workerFile)) throw new Error("Worker pool unavailable or invalid worker count");
189
312
  const workerData = {
190
313
  keyBase64: opts.keyBase64,
191
314
  mode: opts.mode,
@@ -199,7 +322,8 @@ var WorkerPool = class {
199
322
  const createWorker = (index) => {
200
323
  const worker = new import_worker_threads.Worker(_workerFile, {
201
324
  workerData,
202
- execArgv: _workerExecArgv.length > 0 ? _workerExecArgv : void 0
325
+ execArgv: _workerExecArgv
326
+ // Do not inherit --input-type/eval or application loader flags.
203
327
  });
204
328
  const pending = pendingList[index] ?? /* @__PURE__ */ new Map();
205
329
  if (!pendingList[index]) pendingList[index] = pending;
@@ -229,7 +353,7 @@ var WorkerPool = class {
229
353
  }
230
354
  pending.clear();
231
355
  worker.unref();
232
- if (this._available && exitCode !== 0 && workers[index] === worker) {
356
+ if (this._available && this.workers === workers && workers[index] === worker) {
233
357
  try {
234
358
  workers[index] = createWorker(index);
235
359
  } catch {
@@ -239,9 +363,12 @@ var WorkerPool = class {
239
363
  worker.unref();
240
364
  return worker;
241
365
  };
242
- for (let i = 0; i < size; i++) {
243
- const worker = createWorker(i);
244
- workers.push(worker);
366
+ try {
367
+ for (let i = 0; i < size; i++) workers.push(createWorker(i));
368
+ } catch (error) {
369
+ for (const worker of workers) void worker.terminate().catch(() => {
370
+ });
371
+ throw error;
245
372
  }
246
373
  return { workers, pending: pendingList };
247
374
  }
@@ -268,7 +395,7 @@ var WorkerPool = class {
268
395
  entry.reject(new Error("WorkerPool replaced during key rotation"));
269
396
  }
270
397
  oldPending[i]?.clear();
271
- oldWorkers[i]?.terminate().catch(() => {
398
+ await oldWorkers[i]?.terminate().catch(() => {
272
399
  });
273
400
  }
274
401
  }
@@ -310,7 +437,13 @@ var WorkerPool = class {
310
437
  return new Promise((resolve, reject) => {
311
438
  pending.set(id, { resolve, reject });
312
439
  worker.ref();
313
- worker.postMessage({ id, type, payload: dataToSend }, transferList);
440
+ try {
441
+ worker.postMessage({ id, type, payload: dataToSend }, transferList);
442
+ } catch (error) {
443
+ pending.delete(id);
444
+ if (pending.size === 0) worker.unref();
445
+ reject(error);
446
+ }
314
447
  });
315
448
  }
316
449
  /** Terminate all worker threads. In-flight promises are rejected. */
@@ -1112,8 +1245,9 @@ var WTinyLfuCache = class {
1112
1245
  }
1113
1246
  };
1114
1247
  var WTinyLfuPolicy = class {
1115
- constructor(capacity, sketch, windowPercent = 0.01, protectedPercent = 0.8) {
1248
+ constructor(capacity, sketch, windowPercent = 0.01, protectedPercent = 0.8, canEvict) {
1116
1249
  this.sketch = sketch;
1250
+ this.canEvict = canEvict;
1117
1251
  this.maxTotal = Math.max(2, capacity);
1118
1252
  this.maxWindow = Math.max(1, Math.floor(this.maxTotal * windowPercent));
1119
1253
  const mainCapacity = Math.max(1, this.maxTotal - this.maxWindow);
@@ -1121,6 +1255,7 @@ var WTinyLfuPolicy = class {
1121
1255
  this.maxProbation = Math.max(1, mainCapacity - this.maxProtected);
1122
1256
  }
1123
1257
  sketch;
1258
+ canEvict;
1124
1259
  maxTotal;
1125
1260
  maxWindow;
1126
1261
  maxProtected;
@@ -1200,15 +1335,33 @@ var WTinyLfuPolicy = class {
1200
1335
  }
1201
1336
  let victimKey;
1202
1337
  let victimIsProbation = true;
1203
- if (this.probation.size > 0) {
1204
- victimKey = this.probation.values().next().value;
1205
- } else {
1206
- victimKey = this.protected_.values().next().value;
1338
+ for (const candidate of this.probation) {
1339
+ if (!this.canEvict || this.canEvict(candidate)) {
1340
+ victimKey = candidate;
1341
+ break;
1342
+ }
1343
+ }
1344
+ if (victimKey === void 0) {
1345
+ for (const candidate of this.protected_) {
1346
+ if (!this.canEvict || this.canEvict(candidate)) {
1347
+ victimKey = candidate;
1348
+ break;
1349
+ }
1350
+ }
1207
1351
  victimIsProbation = false;
1208
1352
  }
1353
+ if (victimKey === void 0) {
1354
+ if (this.canEvict && !this.canEvict(candKey)) {
1355
+ this.window.delete(key);
1356
+ this.window.add(candKey);
1357
+ return { admit: false, candidateKey: key };
1358
+ }
1359
+ this.rejectionCount++;
1360
+ return { admit: false, candidateKey: candKey };
1361
+ }
1209
1362
  const candFreq = this.sketch.estimate(candKey);
1210
1363
  const victimFreq = this.sketch.estimate(victimKey);
1211
- if (candFreq > victimFreq) {
1364
+ if (this.canEvict && !this.canEvict(candKey) || candFreq > victimFreq) {
1212
1365
  if (victimIsProbation) {
1213
1366
  this.probation.delete(victimKey);
1214
1367
  } else {
@@ -1282,9 +1435,12 @@ function base64ToUint8Array(base64) {
1282
1435
  var BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
1283
1436
  var KEY_STAGING_OFFSET = 2e4;
1284
1437
  var MAX_KEY_BYTES = 512;
1285
- var BLOOM_WASM_MODULE = new WebAssembly.Module(
1286
- base64ToUint8Array(BLOOM_WASM_BASE64)
1287
- );
1438
+ var bloomWasmModule;
1439
+ function getBloomWasmModule() {
1440
+ return bloomWasmModule ??= new WebAssembly.Module(
1441
+ base64ToUint8Array(BLOOM_WASM_BASE64)
1442
+ );
1443
+ }
1288
1444
  var WasmBloomFilter = class {
1289
1445
  exports;
1290
1446
  mem;
@@ -1296,7 +1452,7 @@ var WasmBloomFilter = class {
1296
1452
  /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
1297
1453
  _insertionCount = 0;
1298
1454
  constructor() {
1299
- const instance = new WebAssembly.Instance(BLOOM_WASM_MODULE, {});
1455
+ const instance = new WebAssembly.Instance(getBloomWasmModule(), {});
1300
1456
  this.exports = instance.exports;
1301
1457
  this.mem = new Uint8Array(this.exports.memory.buffer);
1302
1458
  this.stagingTarget = new Uint8Array(this.exports.memory.buffer, KEY_STAGING_OFFSET, MAX_KEY_BYTES);
@@ -1428,8 +1584,9 @@ var JsBloomFilter = class {
1428
1584
  };
1429
1585
  function createBloomFilter(logger, maxEntries) {
1430
1586
  const LN2_SQ = Math.LN2 * Math.LN2;
1431
- const optimalBits = Math.ceil(-maxEntries * Math.log(0.01) / LN2_SQ);
1432
- const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / maxEntries)));
1587
+ const capacity = Math.max(1, maxEntries);
1588
+ const optimalBits = Math.ceil(-capacity * Math.log(0.01) / LN2_SQ);
1589
+ const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / capacity)));
1433
1590
  try {
1434
1591
  const wasm = new WasmBloomFilter();
1435
1592
  if (wasm.maxCapacity >= maxEntries) {
@@ -1553,7 +1710,10 @@ var SmartMemoryCache = class {
1553
1710
  this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
1554
1711
  this.categoryPrefixes = Object.keys(opts.categories).filter((k) => k !== "default");
1555
1712
  if (opts.admissionPolicy === "wtinylfu") {
1556
- this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch);
1713
+ this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch, 0.01, 0.8, (key) => {
1714
+ const entry = this.cache.get(key);
1715
+ return !entry || entry.priority !== 4 || entry.expiresAt <= Date.now();
1716
+ });
1557
1717
  }
1558
1718
  if (existing) {
1559
1719
  for (const [k, v] of existing) this.cache.set(k, v);
@@ -1632,6 +1792,7 @@ var SmartMemoryCache = class {
1632
1792
  const MAX_EVICT_PASSES = 64;
1633
1793
  let passes = 0;
1634
1794
  do {
1795
+ const before = this.cache.size;
1635
1796
  this.smartEvict(category, catOvf);
1636
1797
  const lim2 = this.getCategoryLimit(category);
1637
1798
  const catCnt2 = this.categoryCount.get(category) ?? 0;
@@ -1639,6 +1800,7 @@ var SmartMemoryCache = class {
1639
1800
  catOvf = catCnt2 >= lim2.maxEntries || catSz2 + neededSize > lim2.maxSizeBytes;
1640
1801
  glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
1641
1802
  passes++;
1803
+ if (this.cache.size === before) break;
1642
1804
  } while ((catOvf || glbOvf) && passes < MAX_EVICT_PASSES);
1643
1805
  }
1644
1806
  score(entry, catBonus, now, key) {
@@ -1769,20 +1931,26 @@ var SmartMemoryCache = class {
1769
1931
  delta: entry.delta,
1770
1932
  fetchedAt: now,
1771
1933
  tagVersions: entry.tagVersions,
1772
- setAt: entry.setAt
1934
+ setAt: entry.setAt,
1935
+ tags: entry.tags,
1936
+ dependsOn: entry.dependsOn
1773
1937
  };
1774
1938
  return hit;
1775
1939
  }
1776
- set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions, setAt) {
1940
+ set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions, setAt, tags, dependsOn) {
1777
1941
  const packed = this.codec.encode(data);
1942
+ return this.storePacked(key, packed, data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn);
1943
+ }
1944
+ storePacked(key, packed, data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn) {
1778
1945
  const size = packed.byteLength;
1779
1946
  this.compressions++;
1780
1947
  this.sketch.increment(key);
1781
1948
  const cat = this.getCategory(key);
1782
1949
  const lim = this.getCategoryLimit(cat);
1783
- if (size > lim.maxSizeBytes * 0.5) {
1950
+ if (!Number.isFinite(ttlMs) || ttlMs <= 0 || this.opts.maxEntries <= 0 || lim.maxEntries <= 0 || size > this.opts.maxBytes || size > lim.maxSizeBytes * 0.5) {
1951
+ this.delete(key);
1784
1952
  this.opts.logger.debug("SmartMemoryCache: entry too large, skipping", { key, sizeBytes: size });
1785
- return;
1953
+ return false;
1786
1954
  }
1787
1955
  const existingEntry = this.cache.get(key);
1788
1956
  if (existingEntry) {
@@ -1811,10 +1979,12 @@ var SmartMemoryCache = class {
1811
1979
  ttlMs,
1812
1980
  delta,
1813
1981
  setAt: setAt ?? now2,
1814
- tagVersions
1982
+ tagVersions,
1983
+ tags,
1984
+ dependsOn
1815
1985
  });
1816
1986
  }
1817
- return;
1987
+ return false;
1818
1988
  } else if (decision.candidateKey) {
1819
1989
  const candEntry = this.cache.get(decision.candidateKey);
1820
1990
  if (candEntry && this.opts.diskSpill) {
@@ -1830,15 +2000,19 @@ var SmartMemoryCache = class {
1830
2000
  this._delete(decision.evictKey, "capacity");
1831
2001
  }
1832
2002
  const catSz = this.categorySize.get(cat) ?? 0;
1833
- if (catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
2003
+ if ((this.categoryCount.get(cat) ?? 0) >= lim.maxEntries || this.cache.size >= this.opts.maxEntries || catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
1834
2004
  this.ensureCapacity(cat, size);
1835
2005
  }
1836
2006
  } else {
1837
2007
  this.ensureCapacity(cat, size);
1838
2008
  }
2009
+ 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) {
2010
+ this.wtinyPolicy?.onDelete(key);
2011
+ return false;
2012
+ }
1839
2013
  const now = Date.now();
1840
2014
  const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
1841
- 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 });
2015
+ 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 });
1842
2016
  if (!existingEntry) this.bloom.add(key);
1843
2017
  this.maybeRebuildBloom();
1844
2018
  this.totalSize += size;
@@ -1850,6 +2024,7 @@ var SmartMemoryCache = class {
1850
2024
  this.categoryKeys.set(cat, ks);
1851
2025
  }
1852
2026
  ks.add(key);
2027
+ return true;
1853
2028
  }
1854
2029
  delete(key) {
1855
2030
  const deleted = this._delete(key, "manual");
@@ -2051,25 +2226,48 @@ var SmartMemoryCache = class {
2051
2226
  if (entry.expiresAt <= now) continue;
2052
2227
  if (entry.priority === 4) continue;
2053
2228
  if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
2054
- out.push({ key, entry: { ...entry } });
2229
+ const { value: _value, ...stored } = entry;
2230
+ out.push({ key, entry: { ...stored } });
2055
2231
  }
2056
2232
  return out;
2057
2233
  }
2058
2234
  importEntries(entries, forbiddenPrefixes) {
2059
2235
  const now = Date.now();
2060
2236
  let loaded = 0;
2061
- for (const { key, entry } of entries) {
2062
- if (entry.expiresAt <= now) continue;
2237
+ for (const item of entries) {
2238
+ if (!item || typeof item.key !== "string" || !item.entry) continue;
2239
+ const { key, entry } = item;
2240
+ if (!Number.isFinite(entry.expiresAt) || entry.expiresAt <= now) continue;
2063
2241
  if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
2064
2242
  if (this.cache.has(key)) continue;
2065
- const rawData = entry.data;
2066
- const data = !entry.isCompressed ? this.codec.encode(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
2067
- const value = entry.size <= LARGE_VALUE_BYTES ? this.codec.decode(data) : void 0;
2068
- this.cache.set(key, { ...entry, data, value, isCompressed: true });
2069
- this.bloom.add(key);
2070
- loaded++;
2071
- }
2072
- this.recalculateStats();
2243
+ try {
2244
+ const rawData = entry.data;
2245
+ const data = !entry.isCompressed ? this.codec.encode(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : null;
2246
+ if (!data) continue;
2247
+ const value = data.length <= LARGE_VALUE_BYTES ? this.codec.decode(data) : void 0;
2248
+ if (this.storePacked(
2249
+ key,
2250
+ data,
2251
+ value,
2252
+ entry.expiresAt - now,
2253
+ entry.priority,
2254
+ entry.staleAt,
2255
+ entry.delta,
2256
+ entry.tagVersions,
2257
+ entry.setAt,
2258
+ entry.tags,
2259
+ entry.dependsOn
2260
+ )) {
2261
+ const restored = this.cache.get(key);
2262
+ restored.expiresAt = entry.expiresAt;
2263
+ restored.ttlMs = entry.ttlMs ?? entry.expiresAt - now;
2264
+ restored.hits = Number.isFinite(entry.hits) ? Math.max(1, entry.hits) : 1;
2265
+ restored.lastAccess = Number.isFinite(entry.lastAccess) ? entry.lastAccess : now;
2266
+ loaded++;
2267
+ }
2268
+ } catch {
2269
+ }
2270
+ }
2073
2271
  return loaded;
2074
2272
  }
2075
2273
  // ── Iterators ─────────────────────────────────────────────────────────────
@@ -2433,6 +2631,9 @@ var BoundedDiskQueue = class {
2433
2631
  this.writeTimeoutMs = writeTimeoutMs;
2434
2632
  this.failureThreshold = failureThreshold;
2435
2633
  this.cooldownMs = cooldownMs;
2634
+ 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) {
2635
+ throw new Error("Disk queue limits and timeout must be finite positive values (pending/cooldown may be zero)");
2636
+ }
2436
2637
  }
2437
2638
  maxConcurrent;
2438
2639
  maxPending;
@@ -2445,6 +2646,17 @@ var BoundedDiskQueue = class {
2445
2646
  consecutiveFailures = 0;
2446
2647
  circuitState = "closed";
2447
2648
  lastStateChangeMonotonic = performance.now();
2649
+ get isSaturated() {
2650
+ return this.active >= this.maxConcurrent && this.queue.length >= this.maxPending;
2651
+ }
2652
+ releaseSlot() {
2653
+ if (this.circuitState === "open") {
2654
+ for (const next2 of this.queue.splice(0)) next2(false);
2655
+ }
2656
+ const next = this.queue.shift();
2657
+ if (next) next(true);
2658
+ else this.active--;
2659
+ }
2448
2660
  async schedule(task) {
2449
2661
  const now = performance.now();
2450
2662
  if (this.circuitState === "open") {
@@ -2460,18 +2672,25 @@ var BoundedDiskQueue = class {
2460
2672
  this.spillsDropped++;
2461
2673
  return null;
2462
2674
  }
2463
- if (this.queue.length >= this.maxPending) {
2675
+ if (this.isSaturated) {
2464
2676
  this.spillsDropped++;
2465
2677
  return null;
2466
2678
  }
2467
2679
  if (this.active >= this.maxConcurrent) {
2468
- await new Promise((resolve) => this.queue.push(resolve));
2680
+ const admitted = await new Promise((resolve) => this.queue.push(resolve));
2681
+ if (!admitted) {
2682
+ this.spillsDropped++;
2683
+ return null;
2684
+ }
2685
+ } else {
2686
+ this.active++;
2469
2687
  }
2470
- this.active++;
2471
2688
  let timeoutId = null;
2689
+ const work = Promise.resolve().then(task);
2690
+ void work.then(() => this.releaseSlot(), () => this.releaseSlot());
2472
2691
  try {
2473
2692
  const result = await Promise.race([
2474
- task(),
2693
+ work,
2475
2694
  new Promise((_, reject) => {
2476
2695
  timeoutId = setTimeout(
2477
2696
  () => reject(new Error(`Disk write exceeded timeout of ${this.writeTimeoutMs}ms`)),
@@ -2490,14 +2709,12 @@ var BoundedDiskQueue = class {
2490
2709
  if (this.consecutiveFailures >= this.failureThreshold || this.circuitState === "half-open") {
2491
2710
  this.circuitState = "open";
2492
2711
  this.lastStateChangeMonotonic = performance.now();
2712
+ for (const next of this.queue.splice(0)) next(false);
2493
2713
  }
2494
2714
  this.spillsDropped++;
2495
2715
  return null;
2496
2716
  } finally {
2497
2717
  if (timeoutId) clearTimeout(timeoutId);
2498
- this.active--;
2499
- const next = this.queue.shift();
2500
- if (next) next();
2501
2718
  }
2502
2719
  }
2503
2720
  getStats() {
@@ -2571,6 +2788,13 @@ var DiskTier = class {
2571
2788
  usageCounted = false;
2572
2789
  fileCount = 0;
2573
2790
  // maintained in-memory; avoids walkCacheFiles() in stats
2791
+ reservedBytes = 0;
2792
+ reservedFiles = 0;
2793
+ saveSequence = 0;
2794
+ epoch = 0;
2795
+ pendingSaves = /* @__PURE__ */ new Map();
2796
+ closed = false;
2797
+ invalidatedKeys = /* @__PURE__ */ new Set();
2574
2798
  /** Next bucket index (0–255) for the staggered janitor wheel. */
2575
2799
  _nextJanitorBucket = 0;
2576
2800
  // ── High-watermark pruning & host volume health state ─────────────────────
@@ -2611,6 +2835,7 @@ var DiskTier = class {
2611
2835
  }
2612
2836
  // ── Helpers ───────────────────────────────────────────────────────────────
2613
2837
  ensureDir() {
2838
+ if (this.closed) return;
2614
2839
  if (this.dirReady) return;
2615
2840
  try {
2616
2841
  import_fs2.default.mkdirSync(this.opts.dir, { recursive: true, mode: 448 });
@@ -2732,8 +2957,24 @@ var DiskTier = class {
2732
2957
  *
2733
2958
  * 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
2734
2959
  */
2735
- hashToWritePath(hash, expiresAt) {
2736
- return import_path2.default.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiresAt.toString(16).padStart(12, "0")}`);
2960
+ hashToWritePath(hash, expiresAt, setAt) {
2961
+ const expiry = Math.floor(expiresAt).toString(16).padStart(12, "0");
2962
+ if (setAt === void 0) return import_path2.default.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}`);
2963
+ const written = Math.floor(setAt).toString(16).padStart(12, "0");
2964
+ const sequence = (++this.saveSequence).toString(16).padStart(12, "0");
2965
+ return import_path2.default.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}_${written}_${sequence}_${import_crypto2.default.randomBytes(6).toString("hex")}`);
2966
+ }
2967
+ findFilePaths(hash) {
2968
+ const bucket = import_path2.default.join(this.opts.dir, hash.slice(0, 2));
2969
+ try {
2970
+ return import_fs2.default.readdirSync(bucket).filter((file) => !file.endsWith(".tmp") && (file === hash || file.startsWith(hash + "_"))).map((file) => import_path2.default.join(bucket, file));
2971
+ } catch {
2972
+ return [];
2973
+ }
2974
+ }
2975
+ fileWrittenAt(file) {
2976
+ const parts = import_path2.default.basename(file).split("_");
2977
+ return parts.length >= 4 ? parseInt(parts[2], 16) : import_fs2.default.statSync(file).mtimeMs;
2737
2978
  }
2738
2979
  /**
2739
2980
  * Find the on-disk file for a key hash, handling all filename generations:
@@ -2742,19 +2983,31 @@ var DiskTier = class {
2742
2983
  * Returns null when the bucket dir does not exist or the key is absent.
2743
2984
  */
2744
2985
  findFilePath(hash) {
2745
- const bucketPath = import_path2.default.join(this.opts.dir, hash.slice(0, 2));
2746
- let files;
2986
+ let match = null;
2987
+ let newest = -Infinity;
2988
+ let sequence = -1;
2989
+ for (const file of this.findFilePaths(hash)) {
2990
+ try {
2991
+ const written = this.fileWrittenAt(file);
2992
+ const order = parseInt(import_path2.default.basename(file).split("_")[3] ?? "0", 16);
2993
+ if (written > newest || written === newest && order > sequence) {
2994
+ match = file;
2995
+ newest = written;
2996
+ sequence = order;
2997
+ }
2998
+ } catch {
2999
+ }
3000
+ }
3001
+ return match;
3002
+ }
3003
+ removeFile(filePath) {
2747
3004
  try {
2748
- files = import_fs2.default.readdirSync(bucketPath);
3005
+ const size = import_fs2.default.statSync(filePath).size;
3006
+ import_fs2.default.unlinkSync(filePath);
3007
+ this.diskUsageBytes = Math.max(0, this.diskUsageBytes - size);
3008
+ this.fileCount = Math.max(0, this.fileCount - 1);
2749
3009
  } catch {
2750
- return null;
2751
3010
  }
2752
- let match;
2753
- for (const f of files) {
2754
- if ((f === hash || f.startsWith(hash + "_")) && (!match || f > match)) match = f;
2755
- }
2756
- if (!match) return null;
2757
- return import_path2.default.join(bucketPath, match);
2758
3011
  }
2759
3012
  /**
2760
3013
  * Recursively list all cache file paths across the 2-level sharded subdirs.
@@ -2829,6 +3082,7 @@ var DiskTier = class {
2829
3082
  * so the Node.js event loop is never stalled waiting for disk I/O.
2830
3083
  */
2831
3084
  async save(key, entry) {
3085
+ if (this.closed || this.diskQueue.isSaturated) return;
2832
3086
  if (this.isForbidden(key)) return;
2833
3087
  if (entry.expiresAt <= Date.now()) return;
2834
3088
  this.ensureDir();
@@ -2837,7 +3091,7 @@ var DiskTier = class {
2837
3091
  if (++this._writeCounter % 2e3 === 0) {
2838
3092
  this.checkHostVolumeHealth();
2839
3093
  }
2840
- if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes >= this.opts.maxBytes) {
3094
+ if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes + this.reservedBytes >= this.opts.maxBytes) {
2841
3095
  this._spillsShedTotal++;
2842
3096
  return;
2843
3097
  }
@@ -2846,11 +3100,12 @@ var DiskTier = class {
2846
3100
  }
2847
3101
  let final;
2848
3102
  try {
3103
+ const { value: _value, ...storedEntry } = entry;
2849
3104
  const payload = {
2850
3105
  version: DISK_TIER_VERSION,
2851
3106
  key,
2852
3107
  entry: {
2853
- ...entry,
3108
+ ...storedEntry,
2854
3109
  data: entry.data instanceof Uint8Array ? Buffer.from(entry.data) : entry.data
2855
3110
  },
2856
3111
  writtenAt: Date.now()
@@ -2863,24 +3118,46 @@ var DiskTier = class {
2863
3118
  }
2864
3119
  const header = Buffer.allocUnsafe(V2_HEADER_LEN);
2865
3120
  DISK_MAGIC_V2.copy(header, 0);
2866
- header.writeBigUInt64LE(BigInt(entry.expiresAt), 8);
3121
+ header.writeBigUInt64LE(BigInt(Math.floor(entry.expiresAt)), 8);
2867
3122
  final = Buffer.concat([header, this.encryptV2(toEncrypt)]);
3123
+ if (final.length > this.opts.entryMaxBytes || this.diskUsageBytes + this.reservedBytes + final.length > this.opts.maxBytes) return;
2868
3124
  } catch (err) {
2869
3125
  this.opts.logger.debug("DiskTier: pack/encrypt failed", { key: key.slice(0, 50), error: err.message });
2870
3126
  return;
2871
3127
  }
2872
3128
  const hash = this.keyToHash(key);
2873
- const filePath = this.hashToWritePath(hash, entry.expiresAt);
3129
+ const setAt = entry.setAt ?? Date.now();
3130
+ if ((this.pendingSaves.get(key)?.setAt ?? 0) > setAt) return;
3131
+ const filePath = this.hashToWritePath(hash, entry.expiresAt, setAt);
2874
3132
  const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${import_crypto2.default.randomBytes(6).toString("hex")}.tmp`;
2875
- this.diskUsageBytes += final.length;
2876
- this.fileCount++;
3133
+ const token = Symbol(key);
3134
+ const epoch = this.epoch;
3135
+ this.pendingSaves.set(key, { token, setAt });
3136
+ const current = () => !this.closed && this.epoch === epoch && this.pendingSaves.get(key)?.token === token;
3137
+ let started = false;
3138
+ let released = false;
3139
+ let accounted = false;
3140
+ const releaseReservation = () => {
3141
+ if (released) return;
3142
+ released = true;
3143
+ this.reservedBytes = Math.max(0, this.reservedBytes - final.length);
3144
+ this.reservedFiles = Math.max(0, this.reservedFiles - 1);
3145
+ if (this.pendingSaves.get(key)?.token === token) this.pendingSaves.delete(key);
3146
+ };
3147
+ this.reservedBytes += final.length;
3148
+ this.reservedFiles++;
2877
3149
  if (this.diskUsageBytes >= this.opts.maxBytes * 0.8 && !this._isPruning) {
2878
3150
  void this.triggerChunkedPrune();
2879
3151
  }
2880
3152
  const result = await this.diskQueue.schedule(async () => {
3153
+ started = true;
2881
3154
  try {
3155
+ if (!current()) return false;
3156
+ const previous = this.findFilePath(hash);
3157
+ if (previous && this.fileWrittenAt(previous) > setAt) return false;
2882
3158
  await import_fs2.default.promises.mkdir(import_path2.default.dirname(filePath), { recursive: true });
2883
3159
  await import_fs2.default.promises.writeFile(tmpPath, final, { mode: 384 });
3160
+ if (!current()) return false;
2884
3161
  try {
2885
3162
  await import_fs2.default.promises.rename(tmpPath, filePath);
2886
3163
  } catch (renameErr) {
@@ -2892,6 +3169,20 @@ var DiskTier = class {
2892
3169
  throw renameErr;
2893
3170
  }
2894
3171
  }
3172
+ if (!current()) {
3173
+ try {
3174
+ await import_fs2.default.promises.unlink(filePath);
3175
+ } catch {
3176
+ }
3177
+ return false;
3178
+ }
3179
+ for (const previousPath of this.findFilePaths(hash)) {
3180
+ if (previousPath !== filePath) this.removeFile(previousPath);
3181
+ }
3182
+ this.diskUsageBytes += final.length;
3183
+ this.fileCount++;
3184
+ accounted = true;
3185
+ this.invalidatedKeys.delete(key);
2895
3186
  if (this._db) {
2896
3187
  const priority = typeof entry.priority === "number" ? entry.priority : 2;
2897
3188
  const lastAccess = typeof entry.lastAccess === "number" ? entry.lastAccess : Date.now();
@@ -2904,23 +3195,25 @@ var DiskTier = class {
2904
3195
  await import_fs2.default.promises.unlink(tmpPath);
2905
3196
  } catch {
2906
3197
  }
2907
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
2908
- this.fileCount = Math.max(0, this.fileCount - 1);
2909
- if (this._db) try {
2910
- this._stmtDelete.run(hash);
2911
- } catch {
2912
- }
3198
+ if (accounted) this.removeFile(filePath);
2913
3199
  this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
2914
3200
  throw err;
3201
+ } finally {
3202
+ try {
3203
+ await import_fs2.default.promises.unlink(tmpPath);
3204
+ } catch {
3205
+ }
3206
+ releaseReservation();
3207
+ if (this.invalidatedKeys.has(key) && !this.pendingSaves.has(key)) this.delete(key, true);
2915
3208
  }
2916
3209
  });
2917
- if (result === null) {
2918
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
2919
- this.fileCount = Math.max(0, this.fileCount - 1);
3210
+ if (result === null && !started) {
3211
+ releaseReservation();
2920
3212
  }
2921
3213
  }
2922
3214
  /** Load a key from disk, or return null on miss/expiry/corruption. */
2923
3215
  load(key) {
3216
+ if (this.invalidatedKeys.has(key) || this.closed) return null;
2924
3217
  if (this.isForbidden(key)) return null;
2925
3218
  this.ensureDir();
2926
3219
  if (!this.dirReady) return null;
@@ -2948,8 +3241,8 @@ var DiskTier = class {
2948
3241
  try {
2949
3242
  if (!this._db) {
2950
3243
  const filename = import_path2.default.basename(filePath);
2951
- if (filename.length === 77 && filename[64] === "_") {
2952
- const expiresAt = parseInt(filename.slice(65), 16);
3244
+ if (filename.length >= 77 && filename[64] === "_") {
3245
+ const expiresAt = parseInt(filename.slice(65, 77), 16);
2953
3246
  if (expiresAt <= Date.now()) {
2954
3247
  try {
2955
3248
  const sz = import_fs2.default.statSync(filePath).size;
@@ -2970,12 +3263,7 @@ var DiskTier = class {
2970
3263
  return null;
2971
3264
  }
2972
3265
  const raw = import_fs2.default.readFileSync(filePath);
2973
- try {
2974
- import_fs2.default.unlinkSync(filePath);
2975
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
2976
- this.fileCount = Math.max(0, this.fileCount - 1);
2977
- } catch {
2978
- }
3266
+ for (const storedPath of this.findFilePaths(hash)) this.removeFile(storedPath);
2979
3267
  if (this._db) this._stmtDelete.run(hash);
2980
3268
  let decrypted;
2981
3269
  if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
@@ -3010,25 +3298,24 @@ var DiskTier = class {
3010
3298
  return null;
3011
3299
  }
3012
3300
  }
3013
- /** Explicitly delete a key from disk (cache invalidation). */
3014
- delete(key) {
3301
+ /** Synchronously fence queued/running saves while leaving filesystem cleanup deferred. */
3302
+ invalidate(key) {
3303
+ this.pendingSaves.delete(key);
3304
+ this.invalidatedKeys.add(key);
3305
+ }
3306
+ /** Delete all versions; deferred cleanup must not cancel a newer save. */
3307
+ delete(key, invalidatedOnly = false) {
3308
+ if (invalidatedOnly && (!this.invalidatedKeys.has(key) || this.pendingSaves.has(key))) return;
3309
+ if (!invalidatedOnly) this.pendingSaves.delete(key);
3015
3310
  const hash = this.keyToHash(key);
3016
- let filePath;
3311
+ const files = new Set(this.findFilePaths(hash));
3017
3312
  if (this._db) {
3018
3313
  const row = this._stmtSelect.get(hash);
3019
- filePath = row?.file_path ?? null;
3314
+ if (row?.file_path) files.add(row.file_path);
3020
3315
  this._stmtDelete.run(hash);
3021
- } else {
3022
- filePath = this.findFilePath(hash);
3023
- }
3024
- if (!filePath) return;
3025
- try {
3026
- const stat = import_fs2.default.statSync(filePath);
3027
- import_fs2.default.unlinkSync(filePath);
3028
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
3029
- this.fileCount = Math.max(0, this.fileCount - 1);
3030
- } catch {
3031
3316
  }
3317
+ for (const file of files) this.removeFile(file);
3318
+ this.invalidatedKeys.delete(key);
3032
3319
  }
3033
3320
  /** Purge all expired entries. Returns number deleted. */
3034
3321
  purgeExpired() {
@@ -3064,8 +3351,8 @@ var DiskTier = class {
3064
3351
  }
3065
3352
  continue;
3066
3353
  }
3067
- if (filename.length === 77 && filename[64] === "_") {
3068
- const expiresAt = parseInt(filename.slice(65), 16);
3354
+ if (filename.length >= 77 && filename[64] === "_") {
3355
+ const expiresAt = parseInt(filename.slice(65, 77), 16);
3069
3356
  if (expiresAt <= now) {
3070
3357
  try {
3071
3358
  const sz = import_fs2.default.statSync(filePath).size;
@@ -3185,8 +3472,8 @@ var DiskTier = class {
3185
3472
  }
3186
3473
  continue;
3187
3474
  }
3188
- if (file.length === 77 && file[64] === "_") {
3189
- const expiresAt = parseInt(file.slice(65), 16);
3475
+ if (file.length >= 77 && file[64] === "_") {
3476
+ const expiresAt = parseInt(file.slice(65, 77), 16);
3190
3477
  if (expiresAt <= now2) {
3191
3478
  const fp = import_path2.default.join(orphanBucketP, file);
3192
3479
  try {
@@ -3226,8 +3513,8 @@ var DiskTier = class {
3226
3513
  }
3227
3514
  continue;
3228
3515
  }
3229
- if (file.length === 77 && file[64] === "_") {
3230
- const expiresAt = parseInt(file.slice(65), 16);
3516
+ if (file.length >= 77 && file[64] === "_") {
3517
+ const expiresAt = parseInt(file.slice(65, 77), 16);
3231
3518
  if (expiresAt <= now) {
3232
3519
  const filePath2 = import_path2.default.join(bucketPath, file);
3233
3520
  try {
@@ -3300,6 +3587,9 @@ var DiskTier = class {
3300
3587
  }
3301
3588
  /** Delete every file in the disk cache. Returns the count deleted. */
3302
3589
  clear() {
3590
+ this.epoch++;
3591
+ this.pendingSaves.clear();
3592
+ this.invalidatedKeys.clear();
3303
3593
  this.ensureDir();
3304
3594
  if (!this.dirReady) return 0;
3305
3595
  let cleared = 0;
@@ -3363,6 +3653,7 @@ var DiskTier = class {
3363
3653
  * yielding to the event loop via setImmediate between chunks.
3364
3654
  */
3365
3655
  async triggerChunkedPrune() {
3656
+ if (this.closed) return 0;
3366
3657
  if (this._isPruning) return 0;
3367
3658
  this._isPruning = true;
3368
3659
  this._pruneRounds++;
@@ -3371,7 +3662,7 @@ var DiskTier = class {
3371
3662
  this.ensureUsageCounted();
3372
3663
  const targetBytes = Math.floor(this.opts.maxBytes * 0.6);
3373
3664
  if (this._db && this._stmtPruneChunk) {
3374
- while (this.diskUsageBytes > targetBytes) {
3665
+ while (!this.closed && this.diskUsageBytes > targetBytes) {
3375
3666
  const rows = this._stmtPruneChunk.all();
3376
3667
  if (!rows || rows.length === 0) break;
3377
3668
  for (const row of rows) {
@@ -3394,7 +3685,7 @@ var DiskTier = class {
3394
3685
  }
3395
3686
  }
3396
3687
  } else {
3397
- while (this.diskUsageBytes > targetBytes) {
3688
+ while (!this.closed && this.diskUsageBytes > targetBytes) {
3398
3689
  const files = this.walkCacheFiles();
3399
3690
  if (files.length === 0) break;
3400
3691
  const chunk = files.slice(0, 500);
@@ -3462,6 +3753,10 @@ var DiskTier = class {
3462
3753
  }
3463
3754
  /** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
3464
3755
  close() {
3756
+ this.closed = true;
3757
+ this.epoch++;
3758
+ this.pendingSaves.clear();
3759
+ this.invalidatedKeys.clear();
3465
3760
  if (this._db) {
3466
3761
  try {
3467
3762
  this._db.close();
@@ -3704,6 +3999,17 @@ function readCgroupMemoryLimit() {
3704
3999
  }
3705
4000
  return Infinity;
3706
4001
  }
4002
+ function readCgroupMemoryUsage() {
4003
+ if (process.platform !== "linux") return null;
4004
+ for (const file of ["/sys/fs/cgroup/memory.current", "/sys/fs/cgroup/memory/memory.usage_in_bytes"]) {
4005
+ try {
4006
+ const value = Number(import_node_fs.default.readFileSync(file, "utf8").trim());
4007
+ if (Number.isFinite(value) && value >= 0) return value;
4008
+ } catch {
4009
+ }
4010
+ }
4011
+ return null;
4012
+ }
3707
4013
  function getV8HeapLimit() {
3708
4014
  try {
3709
4015
  const stats = import_node_v8.default.getHeapStatistics();
@@ -3727,7 +4033,81 @@ function resolveAutonomousL1MaxBytes(options) {
3727
4033
  return Math.max(MIN_AUTONOMOUS_L1_FLOOR_BYTES, Math.floor(resolved));
3728
4034
  }
3729
4035
 
4036
+ // src/utils/diagnostics.ts
4037
+ function redactDiagnostics(value, seen = /* @__PURE__ */ new WeakSet(), depth = 0) {
4038
+ if (typeof value === "string" && /^[a-z][a-z\d+.-]*:\/\//i.test(value)) {
4039
+ try {
4040
+ const url = new URL(value);
4041
+ if (url.username) url.username = "[REDACTED]";
4042
+ if (url.password) url.password = "[REDACTED]";
4043
+ for (const key of url.searchParams.keys()) {
4044
+ if (/key|token|secret|password|credential|authorization|cookie/i.test(key)) url.searchParams.set(key, "[REDACTED]");
4045
+ }
4046
+ return url.toString();
4047
+ } catch {
4048
+ return "[REDACTED URL]";
4049
+ }
4050
+ }
4051
+ if (value == null || typeof value !== "object") return typeof value === "function" ? void 0 : value;
4052
+ if (depth >= 8) return "[OMITTED]";
4053
+ if (seen.has(value)) return "[CIRCULAR]";
4054
+ seen.add(value);
4055
+ if (Array.isArray(value)) return value.map((item) => redactDiagnostics(item, seen, depth + 1));
4056
+ const result = {};
4057
+ for (const [key, item] of Object.entries(value)) {
4058
+ if (typeof item === "function") continue;
4059
+ result[key] = /key|token|secret|password|credential|authorization|cookie|headers/i.test(key) ? item == null ? item : "[REDACTED]" : redactDiagnostics(item, seen, depth + 1);
4060
+ }
4061
+ return result;
4062
+ }
4063
+
4064
+ // src/utils/redis-slot.ts
4065
+ function redisHashSlot(key) {
4066
+ const open = key.indexOf("{");
4067
+ const close = open < 0 ? -1 : key.indexOf("}", open + 1);
4068
+ const bytes = Buffer.from(close > open + 1 ? key.slice(open + 1, close) : key, "utf8");
4069
+ let crc = 0;
4070
+ for (const byte of bytes) {
4071
+ crc ^= byte << 8;
4072
+ for (let bit = 0; bit < 8; bit++) crc = crc << 1 ^ (crc & 32768 ? 4129 : 0);
4073
+ crc &= 65535;
4074
+ }
4075
+ return crc & 16383;
4076
+ }
4077
+
4078
+ // src/utils/deadline.ts
4079
+ async function withDeadline(operation, timeoutMs, label) {
4080
+ let timer;
4081
+ try {
4082
+ return await Promise.race([
4083
+ operation,
4084
+ new Promise((_resolve, reject) => {
4085
+ timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs);
4086
+ })
4087
+ ]);
4088
+ } finally {
4089
+ if (timer) clearTimeout(timer);
4090
+ }
4091
+ }
4092
+
3730
4093
  // src/adapters/auto-pipeliner.ts
4094
+ var import_ioredis = require("ioredis");
4095
+ async function readRedisValue(client, key, hash = false) {
4096
+ if (typeof client.pttl === "function" && typeof client.multi === "function") {
4097
+ const transaction = client.multi();
4098
+ if (typeof transaction.pttl === "function" && (!hash || typeof transaction.hgetall === "function")) {
4099
+ if (hash) transaction.hgetall(key);
4100
+ else transaction.get(key);
4101
+ transaction.pttl(key);
4102
+ const results = await transaction.exec();
4103
+ if (!results) throw new Error("Redis read transaction aborted");
4104
+ if (results[0]?.[0]) throw results[0][0];
4105
+ if (results[1]?.[0]) throw results[1][0];
4106
+ return { raw: results[0]?.[1] ?? null, ttlMs: Number(results[1]?.[1]) };
4107
+ }
4108
+ }
4109
+ return { raw: await (hash ? client.hgetall(key) : client.get(key)) };
4110
+ }
3731
4111
  var AutoPipeliner = class {
3732
4112
  constructor(client, options) {
3733
4113
  this.client = client;
@@ -3759,6 +4139,17 @@ var AutoPipeliner = class {
3759
4139
  this.enqueue({ type: "get", key, resolve, reject });
3760
4140
  });
3761
4141
  }
4142
+ async read(key, hash = false) {
4143
+ if (!hash && typeof this.client.pttl !== "function") return { raw: await this.get(key) };
4144
+ if (!this.enabled || !this.supportsPipelines() || typeof this.client.pttl !== "function") {
4145
+ return readRedisValue(this.client, key, hash);
4146
+ }
4147
+ const probe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
4148
+ if (typeof probe.pttl !== "function" || hash && typeof probe.hgetall !== "function") {
4149
+ return readRedisValue(this.client, key, hash);
4150
+ }
4151
+ return new Promise((resolve, reject) => this.enqueue({ type: "read", key, hash, resolve, reject }));
4152
+ }
3762
4153
  async setex(key, seconds, value) {
3763
4154
  if (!this.enabled || !this.supportsPipelines()) {
3764
4155
  if (typeof this.client.setex === "function") {
@@ -3772,8 +4163,18 @@ var AutoPipeliner = class {
3772
4163
  this.enqueue({ type: "setex", key, seconds, value, resolve, reject });
3773
4164
  });
3774
4165
  }
4166
+ async setpx(key, milliseconds, value) {
4167
+ if (!this.enabled || !this.supportsPipelines()) {
4168
+ await this.client.set(key, value, "PX", milliseconds);
4169
+ return;
4170
+ }
4171
+ return new Promise((resolve, reject) => this.enqueue({ type: "setpx", key, milliseconds, value, resolve, reject }));
4172
+ }
3775
4173
  async del(...keys) {
3776
4174
  if (keys.length === 0) return 0;
4175
+ if (this.client instanceof import_ioredis.Cluster && keys.length > 1) {
4176
+ return (await Promise.all(keys.map((key) => this.del(key)))).reduce((sum, value) => sum + value, 0);
4177
+ }
3777
4178
  if (!this.enabled || !this.supportsPipelines()) {
3778
4179
  return this.client.del(...keys);
3779
4180
  }
@@ -3807,44 +4208,72 @@ var AutoPipeliner = class {
3807
4208
  this.scheduled = false;
3808
4209
  this.statsInternal.batchesDispatched++;
3809
4210
  this.statsInternal.operationsBatched += batch.length;
3810
- const pipe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
3811
- for (const op of batch) {
3812
- switch (op.type) {
3813
- case "get":
3814
- pipe.get(op.key);
3815
- break;
3816
- case "setex":
3817
- pipe.setex(op.key, op.seconds, op.value);
3818
- break;
3819
- case "del":
3820
- pipe.del(...op.keys);
3821
- break;
3822
- }
4211
+ if (this.client instanceof import_ioredis.Cluster) {
4212
+ const groups = /* @__PURE__ */ new Map();
4213
+ for (const operation of batch) {
4214
+ const key = operation.type === "del" ? operation.keys[0] : operation.key;
4215
+ const slot = redisHashSlot(key);
4216
+ const master = this.client.slots[slot]?.[0] ?? String(slot);
4217
+ const members = groups.get(master) ?? [];
4218
+ members.push(operation);
4219
+ groups.set(master, members);
4220
+ }
4221
+ await Promise.all([...groups.values()].map((members) => this.dispatch(members)));
4222
+ return;
3823
4223
  }
4224
+ await this.dispatch(batch);
4225
+ }
4226
+ async dispatch(batch) {
3824
4227
  try {
4228
+ const pipe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
4229
+ const indexes = [];
4230
+ let commandCount = 0;
4231
+ for (const op of batch) {
4232
+ indexes.push(commandCount++);
4233
+ switch (op.type) {
4234
+ case "get":
4235
+ pipe.get(op.key);
4236
+ break;
4237
+ case "setex":
4238
+ pipe.setex(op.key, op.seconds, op.value);
4239
+ break;
4240
+ case "setpx":
4241
+ pipe.set(op.key, op.value, "PX", op.milliseconds);
4242
+ break;
4243
+ case "del":
4244
+ pipe.del(...op.keys);
4245
+ break;
4246
+ case "read":
4247
+ if (op.hash) pipe.hgetall(op.key);
4248
+ else pipe.get(op.key);
4249
+ pipe.pttl(op.key);
4250
+ commandCount++;
4251
+ break;
4252
+ }
4253
+ }
3825
4254
  const results = await pipe.exec();
3826
4255
  if (!results) {
3827
4256
  for (const op of batch) {
3828
- if (op.type === "get") op.resolve(null);
3829
- else if (op.type === "del") op.resolve(0);
3830
- else op.resolve();
4257
+ op.reject(new Error("Redis pipeline aborted"));
3831
4258
  }
3832
4259
  return;
3833
4260
  }
3834
4261
  for (let i = 0; i < batch.length; i++) {
3835
4262
  const op = batch[i];
3836
- const resTuple = results[i];
4263
+ const resTuple = results[indexes[i]];
3837
4264
  if (!resTuple) {
3838
- if (op.type === "get") op.resolve(null);
3839
- else if (op.type === "del") op.resolve(0);
3840
- else op.resolve();
4265
+ op.reject(new Error("Missing Redis pipeline result"));
3841
4266
  continue;
3842
4267
  }
3843
4268
  const [err, val] = resTuple;
3844
4269
  if (err) {
3845
4270
  op.reject(err instanceof Error ? err : new Error(String(err)));
3846
4271
  } else {
3847
- if (op.type === "get") {
4272
+ if (op.type === "read") {
4273
+ const ttlResult = results[indexes[i] + 1];
4274
+ if (!ttlResult || ttlResult[0]) op.reject(ttlResult?.[0] ?? new Error("Missing Redis PTTL result"));
4275
+ else op.resolve({ raw: val, ttlMs: Number(ttlResult[1]) });
4276
+ } else if (op.type === "get") {
3848
4277
  op.resolve(val != null ? String(val) : null);
3849
4278
  } else if (op.type === "del") {
3850
4279
  op.resolve(typeof val === "number" ? val : Number(val) || 0);
@@ -3881,6 +4310,8 @@ var IpcTelemetryServer = class {
3881
4310
  server = null;
3882
4311
  socketPath;
3883
4312
  _closed = false;
4313
+ _starting = null;
4314
+ sockets = /* @__PURE__ */ new Set();
3884
4315
  _exitHandler = null;
3885
4316
  _sigintHandler = null;
3886
4317
  _sigtermHandler = null;
@@ -3888,10 +4319,23 @@ var IpcTelemetryServer = class {
3888
4319
  * Start listening on the IPC socket / pipe.
3889
4320
  */
3890
4321
  async start() {
3891
- if (this.server && this.server.listening) return;
4322
+ if (this._closed || this.server?.listening) return;
4323
+ if (this._starting) return this._starting;
4324
+ this._starting = this.startInternal();
4325
+ try {
4326
+ await this._starting;
4327
+ } finally {
4328
+ this._starting = null;
4329
+ }
4330
+ }
4331
+ async startInternal() {
3892
4332
  if (process.platform !== "win32" && import_node_fs2.default.existsSync(this.socketPath)) {
3893
4333
  await new Promise((resolve) => {
3894
4334
  const testSocket = import_node_net.default.createConnection(this.socketPath);
4335
+ testSocket.setTimeout(1e3, () => {
4336
+ testSocket.destroy();
4337
+ resolve();
4338
+ });
3895
4339
  testSocket.once("connect", () => {
3896
4340
  testSocket.destroy();
3897
4341
  resolve();
@@ -3906,17 +4350,37 @@ var IpcTelemetryServer = class {
3906
4350
  });
3907
4351
  });
3908
4352
  }
4353
+ if (this._closed) return;
3909
4354
  this.server = import_node_net.default.createServer((socket) => {
4355
+ if (this._closed) {
4356
+ socket.destroy();
4357
+ return;
4358
+ }
4359
+ this.sockets.add(socket);
4360
+ socket.once("close", () => this.sockets.delete(socket));
4361
+ socket.setTimeout(5e3, () => socket.destroy());
3910
4362
  let buffer = "";
4363
+ let pending = 0;
3911
4364
  socket.on("data", (chunk) => {
4365
+ if (Buffer.byteLength(buffer) + chunk.length > 4096 || socket.writableLength > 65536) {
4366
+ socket.destroy();
4367
+ return;
4368
+ }
3912
4369
  buffer += chunk.toString("utf8");
3913
4370
  let newlineIndex;
3914
4371
  while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
3915
4372
  const line = buffer.slice(0, newlineIndex).trim();
3916
4373
  buffer = buffer.slice(newlineIndex + 1);
3917
4374
  if (!line) continue;
4375
+ if (++pending > 8) {
4376
+ socket.destroy();
4377
+ return;
4378
+ }
3918
4379
  setImmediate(() => {
3919
- if (socket.destroyed) return;
4380
+ if (socket.destroyed) {
4381
+ pending--;
4382
+ return;
4383
+ }
3920
4384
  try {
3921
4385
  let cmd = line;
3922
4386
  try {
@@ -3941,6 +4405,8 @@ var IpcTelemetryServer = class {
3941
4405
  if (!socket.destroyed) {
3942
4406
  socket.write(JSON.stringify({ error: err.message }) + "\n");
3943
4407
  }
4408
+ } finally {
4409
+ pending--;
3944
4410
  }
3945
4411
  });
3946
4412
  }
@@ -3948,21 +4414,38 @@ var IpcTelemetryServer = class {
3948
4414
  socket.on("error", () => {
3949
4415
  });
3950
4416
  });
4417
+ this.server.maxConnections = 128;
3951
4418
  await new Promise((resolve, reject) => {
3952
- this.server.once("error", reject);
3953
- this.server.listen(this.socketPath, () => {
3954
- this.server.removeListener("error", reject);
4419
+ const server = this.server;
4420
+ const cleanup = () => {
4421
+ server.off("error", failed);
4422
+ server.off("close", closed);
4423
+ };
4424
+ const failed = (error) => {
4425
+ cleanup();
4426
+ reject(error);
4427
+ };
4428
+ const closed = () => {
4429
+ cleanup();
4430
+ resolve();
4431
+ };
4432
+ server.once("error", failed);
4433
+ server.once("close", closed);
4434
+ server.listen(this.socketPath, () => {
4435
+ cleanup();
3955
4436
  resolve();
3956
4437
  });
3957
4438
  });
4439
+ if (this._closed) {
4440
+ if (this.server.listening) this.server.close();
4441
+ return;
4442
+ }
3958
4443
  this._exitHandler = () => this._unlinkSocket();
3959
4444
  this._sigintHandler = () => {
3960
4445
  this._unlinkSocket();
3961
- process.exit(0);
3962
4446
  };
3963
4447
  this._sigtermHandler = () => {
3964
4448
  this._unlinkSocket();
3965
- process.exit(0);
3966
4449
  };
3967
4450
  process.once("exit", this._exitHandler);
3968
4451
  process.once("SIGINT", this._sigintHandler);
@@ -3992,6 +4475,7 @@ var IpcTelemetryServer = class {
3992
4475
  _unlinkSocket() {
3993
4476
  if (this._closed) return;
3994
4477
  this._closed = true;
4478
+ for (const socket of this.sockets) socket.destroy();
3995
4479
  try {
3996
4480
  this.server?.close();
3997
4481
  } catch {
@@ -4009,6 +4493,9 @@ var IpcTelemetryServer = class {
4009
4493
  * Gracefully close the IPC telemetry server and clean up handlers and sockets.
4010
4494
  */
4011
4495
  async close() {
4496
+ this._unlinkSocket();
4497
+ await this._starting?.catch(() => {
4498
+ });
4012
4499
  if (this._exitHandler) {
4013
4500
  process.removeListener("exit", this._exitHandler);
4014
4501
  this._exitHandler = null;
@@ -4021,7 +4508,6 @@ var IpcTelemetryServer = class {
4021
4508
  process.removeListener("SIGTERM", this._sigtermHandler);
4022
4509
  this._sigtermHandler = null;
4023
4510
  }
4024
- this._unlinkSocket();
4025
4511
  return new Promise((resolve) => {
4026
4512
  if (!this.server || !this.server.listening) {
4027
4513
  resolve();
@@ -4307,6 +4793,37 @@ if currentTs and currentTs == ARGV[1] then
4307
4793
  end
4308
4794
  return 0
4309
4795
  `;
4796
+ var LUA_READ_CACHE_ENTRY = `
4797
+ local kind = redis.call('TYPE', KEYS[1]).ok
4798
+ if kind == 'string' then
4799
+ return { kind, redis.call('GET', KEYS[1]), redis.call('PTTL', KEYS[1]) }
4800
+ elseif kind == 'hash' then
4801
+ return { kind, redis.call('HGETALL', KEYS[1]), redis.call('PTTL', KEYS[1]) }
4802
+ end
4803
+ return { 'none', false, -2 }
4804
+ `;
4805
+ var LUA_MAX_TAG_VERSION = `
4806
+ local current = tonumber(redis.call('GET', KEYS[1]) or '0')
4807
+ local floor = tonumber(ARGV[1])
4808
+ if current < floor then redis.call('SET', KEYS[1], floor) return floor end
4809
+ return current
4810
+ `;
4811
+ var LUA_RECEIVE_TAG_VERSION = `
4812
+ local current = tonumber(redis.call('GET', KEYS[1]) or '0')
4813
+ local next = math.max(current + 1, tonumber(ARGV[1]))
4814
+ redis.call('SET', KEYS[1], next)
4815
+ return next
4816
+ `;
4817
+ var LUA_TOUCH_CACHE_ENTRY = `
4818
+ local kind = redis.call('TYPE', KEYS[1]).ok
4819
+ if kind == 'hash' then
4820
+ if redis.call('HGET', KEYS[1], 't') ~= ARGV[1] then return 0 end
4821
+ redis.call('HSET', KEYS[1], 'e', ARGV[2])
4822
+ elseif kind ~= 'string' then
4823
+ return 0
4824
+ end
4825
+ return redis.call('PEXPIRE', KEYS[1], ARGV[3])
4826
+ `;
4310
4827
  var SNAPSHOT_VERSION = 1;
4311
4828
  var DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
4312
4829
  var INDEFINITE_TTL_SECONDS = 31536e3;
@@ -4599,6 +5116,7 @@ var CacheService = class _CacheService {
4599
5116
  keyTags = /* @__PURE__ */ new Map();
4600
5117
  /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
4601
5118
  tagVersions = /* @__PURE__ */ new Map();
5119
+ _tagRefreshEpoch = 0;
4602
5120
  /**
4603
5121
  * Dependency index: source glob pattern → Set of namespaced dependent keys.
4604
5122
  * When an exact-key delete matches a registered pattern, all dependents are cascaded.
@@ -4629,9 +5147,17 @@ var CacheService = class _CacheService {
4629
5147
  subClient = null;
4630
5148
  streamClient = null;
4631
5149
  _lastStreamId = "$";
5150
+ _restoredSnapshot = false;
5151
+ _backplaneAvailable = false;
5152
+ _otelCleanup = null;
5153
+ _streamRecovering = false;
5154
+ _backplaneDisposers = [];
4632
5155
  _destroyed = false;
4633
5156
  _pendingDiskDeletes = /* @__PURE__ */ new Set();
4634
5157
  _globalEpoch = 0;
5158
+ _pendingSpillCount = 0;
5159
+ _suppressSpills = false;
5160
+ _diskCleanupScheduled = false;
4635
5161
  _keyMutationEpochs = /* @__PURE__ */ new Map();
4636
5162
  /**
4637
5163
  * Pattern tombstones for disk tier.
@@ -4640,20 +5166,24 @@ var CacheService = class _CacheService {
4640
5166
  * pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
4641
5167
  */
4642
5168
  _patternTombstones = [];
4643
- _addPatternTombstone(prefix) {
5169
+ _diskInvalidatedBefore = 0;
5170
+ _addPatternTombstone(pattern) {
4644
5171
  const now = Date.now();
4645
5172
  while (this._patternTombstones.length > 0 && now - this._patternTombstones[0].createdAt > 36e5) {
4646
- this._patternTombstones.shift();
5173
+ const forgotten = this._patternTombstones.shift();
5174
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
4647
5175
  }
4648
5176
  if (this._patternTombstones.length >= 2e3) {
4649
- this._patternTombstones.shift();
5177
+ const forgotten = this._patternTombstones.shift();
5178
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
4650
5179
  }
4651
- this._patternTombstones.push({ prefix, createdAt: now });
5180
+ this._patternTombstones.push({ pattern, createdAt: now });
4652
5181
  }
4653
- _isTombstonedByPattern(namespacedKey) {
5182
+ _isTombstonedByPattern(namespacedKey, setAt = 0) {
5183
+ if (this._diskInvalidatedBefore > 0 && setAt <= this._diskInvalidatedBefore) return true;
4654
5184
  if (this._patternTombstones.length === 0) return false;
4655
5185
  for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
4656
- if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
5186
+ if (setAt <= this._patternTombstones[i].createdAt && this._matchesGlob(namespacedKey, this._patternTombstones[i].pattern)) {
4657
5187
  return true;
4658
5188
  }
4659
5189
  }
@@ -4668,13 +5198,86 @@ var CacheService = class _CacheService {
4668
5198
  const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
4669
5199
  this._keyMutationEpochs.set(namespacedKey, next);
4670
5200
  if (this._keyMutationEpochs.size > 5e4) {
4671
- const oldest = this._keyMutationEpochs.keys().next().value;
4672
- if (oldest !== void 0) this._keyMutationEpochs.delete(oldest);
5201
+ this._globalEpoch++;
5202
+ this._keyMutationEpochs.clear();
5203
+ this._keyMutationEpochs.set(namespacedKey, next);
4673
5204
  }
4674
5205
  return next;
4675
5206
  }
4676
5207
  _getKeyMutationEpoch(namespacedKey) {
4677
- return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
5208
+ return `${this._globalEpoch}:${this._keyMutationEpochs.get(namespacedKey) ?? 0}`;
5209
+ }
5210
+ /** Capture a commit fence before asynchronous computation outside the cache. */
5211
+ captureMutationFence(cacheKey) {
5212
+ this._assertActive("captureMutationFence");
5213
+ const key = this.nk(cacheKey);
5214
+ const epoch = this._getKeyMutationEpoch(key);
5215
+ return () => !this._destroyed && this._getKeyMutationEpoch(key) === epoch;
5216
+ }
5217
+ /** Force tag re-sync without forgetting locally observed monotonic generations. */
5218
+ refreshTagVersions() {
5219
+ this._assertActive("refreshTagVersions");
5220
+ this._tagRefreshEpoch++;
5221
+ }
5222
+ _fenceInvalidation() {
5223
+ this._globalEpoch++;
5224
+ this.inflight.clear();
5225
+ }
5226
+ _invalidateDiskKey(key) {
5227
+ if (this._diskDisabled) return;
5228
+ this.disk.invalidate(key);
5229
+ this._pendingDiskDeletes.add(key);
5230
+ this._scheduleDiskCleanup();
5231
+ }
5232
+ _scheduleDiskCleanup() {
5233
+ if (this._diskCleanupScheduled || this._pendingDiskDeletes.size === 0) return;
5234
+ this._diskCleanupScheduled = true;
5235
+ setImmediate(() => {
5236
+ this._diskCleanupScheduled = false;
5237
+ if (this._destroyed) return;
5238
+ let processed = 0;
5239
+ for (const key of this._pendingDiskDeletes) {
5240
+ try {
5241
+ this.disk.delete(key, true);
5242
+ } finally {
5243
+ this._pendingDiskDeletes.delete(key);
5244
+ }
5245
+ if (++processed >= 16) break;
5246
+ }
5247
+ this._scheduleDiskCleanup();
5248
+ });
5249
+ }
5250
+ _registerDependencies(key, patterns) {
5251
+ this._removeKeyDependencies(key);
5252
+ if (!patterns?.length) return;
5253
+ const namespaced = [...new Set(patterns.map((pattern) => this.nk(pattern)))];
5254
+ for (const pattern of namespaced) {
5255
+ const dependents = this.dependencyIndex.get(pattern) ?? /* @__PURE__ */ new Set();
5256
+ dependents.add(key);
5257
+ this.dependencyIndex.set(pattern, dependents);
5258
+ }
5259
+ this.keyDependencies.set(key, namespaced);
5260
+ }
5261
+ _rememberTags(key, tags, expiresAt) {
5262
+ this._removeKeyTags(key);
5263
+ if (!tags.length) return;
5264
+ if (this.keyTags.size >= 1e5) {
5265
+ this._sweepExpiredMetadata();
5266
+ const oldest = this.keyTags.keys().next().value;
5267
+ if (this.keyTags.size >= 1e5 && oldest !== void 0) this._removeKeyTags(oldest);
5268
+ }
5269
+ const unique = [...new Set(tags)];
5270
+ for (const tag of unique) {
5271
+ const tagKey = this.nk(`_tag_:${tag}`);
5272
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
5273
+ members.add(key);
5274
+ this.tagIndex.set(tagKey, members);
5275
+ }
5276
+ this.keyTags.set(key, { tags: unique, expiresAt });
5277
+ }
5278
+ _restoreEntryMetadata(key, entry) {
5279
+ if (entry.tags?.length) this._rememberTags(key, entry.tags, entry.expiresAt);
5280
+ if (entry.dependsOn?.length) this._registerDependencies(key, entry.dependsOn);
4678
5281
  }
4679
5282
  _removeKeyTags(namespacedKey) {
4680
5283
  const entry = this.keyTags.get(namespacedKey);
@@ -4708,21 +5311,21 @@ var CacheService = class _CacheService {
4708
5311
  }
4709
5312
  }
4710
5313
  _handleL1Eviction(namespacedKey, reason) {
4711
- const spilledToDisk = !this._diskDisabled && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
5314
+ const spilledToDisk = !this._diskDisabled && !this._suppressSpills && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
4712
5315
  if (!spilledToDisk) {
4713
5316
  this._removeKeyTags(namespacedKey);
4714
5317
  this._removeKeyDependencies(namespacedKey);
4715
5318
  }
4716
5319
  }
4717
- _removePrefixFromIndices(prefix) {
5320
+ _removePatternFromIndices(pattern) {
4718
5321
  for (const k of Array.from(this.keyTags.keys())) {
4719
- if (k.startsWith(prefix)) this._removeKeyTags(k);
5322
+ if (this._matchesGlob(k, pattern)) this._removeKeyTags(k);
4720
5323
  }
4721
5324
  for (const k of Array.from(this.keyDependencies.keys())) {
4722
- if (k.startsWith(prefix)) this._removeKeyDependencies(k);
5325
+ if (this._matchesGlob(k, pattern)) this._removeKeyDependencies(k);
4723
5326
  }
4724
5327
  for (const k of Array.from(this._l1Counters.keys())) {
4725
- if (k.startsWith(prefix)) this._l1Counters.delete(k);
5328
+ if (this._matchesGlob(k, pattern)) this._l1Counters.delete(k);
4726
5329
  }
4727
5330
  }
4728
5331
  _sweepExpiredMetadata() {
@@ -4740,10 +5343,16 @@ var CacheService = class _CacheService {
4740
5343
  _runOomCheck() {
4741
5344
  const heap = import_node_v82.default.getHeapStatistics();
4742
5345
  const heapUsed = heap.used_heap_size / heap.heap_size_limit;
4743
- const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? process.memoryUsage().rss / this._cgroupMemoryLimit : 0;
5346
+ const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? (readCgroupMemoryUsage() ?? process.memoryUsage().rss) / this._cgroupMemoryLimit : 0;
4744
5347
  const used = Math.max(heapUsed, cgroupUsed);
4745
5348
  if (used >= this.opts.oomHeapThreshold) {
4746
- const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
5349
+ this._suppressSpills = cgroupUsed >= this.opts.oomHeapThreshold;
5350
+ let evicted;
5351
+ try {
5352
+ evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
5353
+ } finally {
5354
+ this._suppressSpills = false;
5355
+ }
4747
5356
  this.counters.oomEvictions++;
4748
5357
  this.counters.oomLastAt = Date.now();
4749
5358
  this.logger.warn("tricache OOM guard: emergency L1 eviction", {
@@ -4979,9 +5588,13 @@ var CacheService = class _CacheService {
4979
5588
  admissionPolicy: this.opts.l1AdmissionPolicy,
4980
5589
  codec: this.codec,
4981
5590
  diskSpill: (key, entry) => {
4982
- if (this._diskDisabled) return;
5591
+ if (this._diskDisabled || this._suppressSpills) return;
5592
+ if (this._pendingSpillCount >= (this.opts.diskMaxPendingWrites ?? 512)) return;
5593
+ const epoch = this._getKeyMutationEpoch(key);
5594
+ this._pendingSpillCount++;
4983
5595
  setImmediate(() => {
4984
- void this.disk.save(key, entry);
5596
+ this._pendingSpillCount--;
5597
+ if (!this._destroyed && this._getKeyMutationEpoch(key) === epoch) void this.disk.save(key, entry);
4985
5598
  });
4986
5599
  },
4987
5600
  onEviction: (key, reason) => {
@@ -5060,7 +5673,7 @@ var CacheService = class _CacheService {
5060
5673
  this.instanceId = import_crypto3.default.randomBytes(8).toString("hex");
5061
5674
  this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
5062
5675
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
5063
- this.initBackplane();
5676
+ 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 }));
5064
5677
  const startupPromises = [];
5065
5678
  if (this.opts.compression === "zstd") {
5066
5679
  startupPromises.push(initZstd().then(() => void 0));
@@ -5071,9 +5684,8 @@ var CacheService = class _CacheService {
5071
5684
  if (this.opts.warmKeys) {
5072
5685
  startupPromises.push(this.warmFromL2(this.opts.warmKeys).then(() => void 0));
5073
5686
  }
5074
- if (startupPromises.length > 0) {
5075
- this._readyPromise = Promise.all(startupPromises).then(() => void 0);
5076
- }
5687
+ const backplaneReady = this.opts.remoteSnapshot || this.opts.warmKeys ? Promise.all(startupPromises).then(startBackplane) : startBackplane();
5688
+ this._readyPromise = Promise.all([...startupPromises, backplaneReady]).then(() => void 0);
5077
5689
  if (this.opts.meter) {
5078
5690
  this._initOtelMetrics(this.opts.meter);
5079
5691
  const otel = this._otelMetrics;
@@ -5086,7 +5698,10 @@ var CacheService = class _CacheService {
5086
5698
  if (typeof prop === "string" && typeof value === "number" && typeof oldVal === "number") {
5087
5699
  const diff = value - oldVal;
5088
5700
  if (diff > 0 && otel[prop]) {
5089
- otel[prop].add(diff, nsAttr);
5701
+ try {
5702
+ otel[prop].add(diff, nsAttr);
5703
+ } catch {
5704
+ }
5090
5705
  }
5091
5706
  }
5092
5707
  return ok;
@@ -5178,7 +5793,7 @@ var CacheService = class _CacheService {
5178
5793
  return g[key];
5179
5794
  }
5180
5795
  const existing = g[key];
5181
- const diff = _CacheService.optionsDiff(options ?? {}, existing.options);
5796
+ const diff = _CacheService.optionsDiff(options ?? {}, existing.opts);
5182
5797
  if (diff.length > 0) {
5183
5798
  existing.bumpSingletonDivergence();
5184
5799
  const msg = `tricache: singleton already initialised for namespace '${existing.options.namespace || "(default)"}' \u2014 ignoring divergent options: ${diff.join(", ")}`;
@@ -5212,7 +5827,13 @@ var CacheService = class _CacheService {
5212
5827
  "instanceName",
5213
5828
  "invalidationBackplane",
5214
5829
  "awaitInvalidationBackplane",
5215
- "lockFailClosed"
5830
+ "lockFailClosed",
5831
+ "tagStrategy",
5832
+ "cloneStrategy",
5833
+ "compression",
5834
+ "backplaneMode",
5835
+ "redisProtocol",
5836
+ "failClosed"
5216
5837
  ];
5217
5838
  /** Returns the names of options that differ between `a` and the live `b`. */
5218
5839
  static optionsDiff(a, b) {
@@ -5230,12 +5851,12 @@ var CacheService = class _CacheService {
5230
5851
  bumpSingletonDivergence() {
5231
5852
  this.counters.singletonDivergences++;
5232
5853
  }
5233
- /** Read-only view of the options the singleton was constructed with. */
5854
+ /** Sanitized diagnostic view; retain the original options/adapters to reuse configuration. */
5234
5855
  get options() {
5235
5856
  const o = this.opts;
5236
5857
  return {
5237
5858
  namespace: o.namespace,
5238
- logger: o.logger,
5859
+ 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) },
5239
5860
  l1MaxBytes: o.l1MaxBytes,
5240
5861
  l1MaxEntries: o.l1MaxEntries,
5241
5862
  redisHost: o.redisHost,
@@ -5256,8 +5877,8 @@ var CacheService = class _CacheService {
5256
5877
  awaitInvalidationBackplane: o.awaitInvalidationBackplane,
5257
5878
  lockFailClosed: o.lockFailClosed,
5258
5879
  strictSingleton: o.strictSingleton,
5259
- remoteSnapshot: o.remoteSnapshot,
5260
- crossRegion: o.crossRegion
5880
+ remoteSnapshot: redactDiagnostics(o.remoteSnapshot),
5881
+ crossRegion: redactDiagnostics(o.crossRegion)
5261
5882
  };
5262
5883
  }
5263
5884
  /**
@@ -5340,21 +5961,26 @@ var CacheService = class _CacheService {
5340
5961
  if (this.opts.redisClient && typeof this.opts.redisClient.duplicate === "function") {
5341
5962
  return this.opts.redisClient.duplicate();
5342
5963
  }
5964
+ if (this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel) {
5965
+ throw new Error("Invalidation backplane requires redisSubClient or a driver supporting duplicate()");
5966
+ }
5343
5967
  if (this.opts.redisClusterNodes?.length) {
5344
- return new import_ioredis.Cluster(this.opts.redisClusterNodes, {
5968
+ return new import_ioredis2.Cluster(this.opts.redisClusterNodes, {
5345
5969
  redisOptions: {
5346
5970
  tls: this.opts.redisTls ? {} : void 0,
5347
5971
  connectTimeout: 1e4,
5972
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
5348
5973
  maxRetriesPerRequest: null,
5349
5974
  ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
5350
5975
  }
5351
5976
  });
5352
5977
  } else if (this.opts.redisSentinel) {
5353
- return new import_ioredis.Redis({
5978
+ return new import_ioredis2.Redis({
5354
5979
  sentinels: this.opts.redisSentinel.sentinels,
5355
5980
  name: this.opts.redisSentinel.name,
5356
5981
  tls: this.opts.redisTls ? {} : void 0,
5357
5982
  connectTimeout: 1e4,
5983
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
5358
5984
  lazyConnect: true,
5359
5985
  maxRetriesPerRequest: null,
5360
5986
  enableAutoPipelining: false,
@@ -5362,11 +5988,12 @@ var CacheService = class _CacheService {
5362
5988
  ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
5363
5989
  });
5364
5990
  } else {
5365
- return new import_ioredis.Redis({
5991
+ return new import_ioredis2.Redis({
5366
5992
  host: this.opts.redisHost,
5367
5993
  port: this.opts.redisPort,
5368
5994
  tls: this.opts.redisTls ? {} : void 0,
5369
5995
  connectTimeout: 1e4,
5996
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
5370
5997
  lazyConnect: true,
5371
5998
  maxRetriesPerRequest: null,
5372
5999
  enableAutoPipelining: false,
@@ -5376,26 +6003,32 @@ var CacheService = class _CacheService {
5376
6003
  });
5377
6004
  }
5378
6005
  }
5379
- initBackplane() {
6006
+ _listenBackplane(client, event, listener) {
6007
+ client.on?.(event, listener);
6008
+ this._backplaneDisposers.push(() => client.removeListener?.(event, listener));
6009
+ }
6010
+ async initBackplane() {
5380
6011
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
5381
6012
  if (this.opts.backplaneMode === "stream") {
5382
6013
  if (this.streamClient) return;
5383
- void this._startStreamConsumer();
6014
+ await this._startStreamConsumer();
5384
6015
  return;
5385
6016
  }
5386
6017
  if (this.subClient) return;
5387
6018
  const sub = this.createDedicatedRedisClient();
5388
- sub.on("error", (e) => {
6019
+ this.subClient = sub;
6020
+ this._listenBackplane(sub, "error", (e) => {
5389
6021
  this._checkAndLogResp3Hint(e);
5390
6022
  this.logger.debug("Backplane subscriber error", { error: e.message });
5391
6023
  });
5392
- sub.on("close", () => {
6024
+ this._listenBackplane(sub, "close", () => {
6025
+ this._backplaneAvailable = false;
5393
6026
  if (this._subDisconnectedAt === null) {
5394
6027
  this._subDisconnectedAt = Date.now();
5395
6028
  this.logger.debug("Backplane: subscriber disconnected", { at: this._subDisconnectedAt });
5396
6029
  }
5397
6030
  });
5398
- sub.on("ready", () => {
6031
+ this._listenBackplane(sub, "ready", () => {
5399
6032
  if (this._subDisconnectedAt !== null && this.opts.backplaneMaxStalenessMs > 0) {
5400
6033
  const gapMs = Date.now() - this._subDisconnectedAt;
5401
6034
  if (gapMs > this.opts.backplaneMaxStalenessMs) {
@@ -5408,52 +6041,119 @@ var CacheService = class _CacheService {
5408
6041
  }
5409
6042
  this._subDisconnectedAt = null;
5410
6043
  }
6044
+ if (!this._destroyed) this._backplaneAvailable = true;
5411
6045
  });
5412
6046
  const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
5413
6047
  if (isClusterSharded) {
5414
- sub.on("smessage", (_channel, message) => {
6048
+ this._listenBackplane(sub, "smessage", (_channel, message) => {
5415
6049
  this._handleBackplaneMessage(message);
5416
6050
  });
5417
- sub.ssubscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: sharded subscribed", {
6051
+ if (typeof sub.connect === "function" && (sub.isOpen === false || sub.status === "wait")) await sub.connect();
6052
+ await sub.ssubscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: sharded subscribed", {
5418
6053
  channel: this.backplaneChannel,
5419
6054
  instanceId: this.instanceId
5420
- })).catch((err) => this.logger.warn("Backplane: sharded subscribe failed", {
5421
- error: err.message
5422
6055
  }));
5423
6056
  } else {
5424
- sub.on("message", (_channel, message) => {
6057
+ this._listenBackplane(sub, "message", (_channel, message) => {
5425
6058
  this._handleBackplaneMessage(message);
5426
6059
  });
5427
- sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
6060
+ if (typeof sub.connect === "function" && (sub.isOpen === false || sub.status === "wait")) await sub.connect();
6061
+ if (this._destroyed) return;
6062
+ await sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
5428
6063
  channel: this.backplaneChannel,
5429
6064
  instanceId: this.instanceId
5430
- })).catch((err) => this.logger.warn("Backplane: subscribe failed", {
5431
- error: err.message
5432
6065
  }));
5433
6066
  }
5434
- this.subClient = sub;
6067
+ if (!this._destroyed) this._backplaneAvailable = true;
6068
+ }
6069
+ _resetAfterStreamGap() {
6070
+ this.counters.streamGaps++;
6071
+ this._fenceInvalidation();
6072
+ this.l1.clear();
6073
+ this.tagIndex.clear();
6074
+ this.keyTags.clear();
6075
+ this.tagVersions.clear();
6076
+ this.dependencyIndex.clear();
6077
+ this.keyDependencies.clear();
6078
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, Date.now());
6079
+ this._addPatternTombstone(this.nk("*"));
6080
+ this._lastStreamId = "0-0";
5435
6081
  }
5436
6082
  async _startStreamConsumer() {
6083
+ this._streamRecovering ||= this._lastStreamId !== "$" && this._lastStreamId !== "0-0";
5437
6084
  const sub = this.streamClient ?? this.createDedicatedRedisClient();
5438
6085
  this.streamClient = sub;
6086
+ if (typeof sub.xread !== "function") throw new Error("backplaneMode: stream requires a driver supporting XREAD");
5439
6087
  if (typeof sub.on === "function") {
5440
- sub.on("error", (e) => this.logger.debug("Backplane stream consumer error", { error: e.message }));
5441
- sub.on("close", () => {
6088
+ this._listenBackplane(sub, "error", (e) => this.logger.debug("Backplane stream consumer error", { error: e.message }));
6089
+ this._listenBackplane(sub, "close", () => {
6090
+ this._streamRecovering = true;
6091
+ this._backplaneAvailable = false;
5442
6092
  if (this._subDisconnectedAt === null) {
5443
6093
  this._subDisconnectedAt = Date.now();
5444
6094
  this.logger.debug("Backplane stream: consumer disconnected", { at: this._subDisconnectedAt });
5445
6095
  }
5446
6096
  });
5447
- sub.on("ready", () => {
6097
+ this._listenBackplane(sub, "ready", () => {
5448
6098
  if (this._subDisconnectedAt !== null) {
5449
6099
  this.logger.debug("Backplane stream: consumer reconnected, resuming stream read", { lastId: this._lastStreamId });
5450
6100
  this._subDisconnectedAt = null;
5451
6101
  }
5452
6102
  });
5453
6103
  }
6104
+ const checkGap = async () => {
6105
+ if (this._lastStreamId === "$" || this._lastStreamId === "0-0" || typeof sub.xrange !== "function") return;
6106
+ const first = await sub.xrange(this.backplaneStreamKey, "-", "+", "COUNT", 1);
6107
+ const firstId = first?.[0]?.[0];
6108
+ if (!firstId) return;
6109
+ const [firstMs, firstSequence] = firstId.split("-").map(BigInt);
6110
+ const [lastMs, lastSequence] = this._lastStreamId.split("-").map(BigInt);
6111
+ if (firstMs > lastMs || firstMs === lastMs && firstSequence > lastSequence) this._resetAfterStreamGap();
6112
+ };
6113
+ const apply = (response) => {
6114
+ if (this._destroyed || !response) return;
6115
+ if (this._streamRecovering && response.some(([, entries]) => entries.length > 0)) {
6116
+ this.counters.streamReplays++;
6117
+ this._streamRecovering = false;
6118
+ }
6119
+ for (const [, entries] of response) {
6120
+ for (const [id, fields] of entries) {
6121
+ this._lastStreamId = id;
6122
+ this.counters.streamEntriesReceived++;
6123
+ this._processStreamEntry(fields);
6124
+ }
6125
+ }
6126
+ };
6127
+ let initialized = false;
6128
+ const initialize = async () => {
6129
+ if (typeof sub.connect === "function" && (sub.isOpen === false || sub.status === "wait")) await sub.connect();
6130
+ if (this._destroyed) return;
6131
+ if (this._lastStreamId === "$") {
6132
+ if (this._restoredSnapshot) this._resetAfterStreamGap();
6133
+ else if (typeof sub.xrevrange === "function") {
6134
+ const latest = await sub.xrevrange(this.backplaneStreamKey, "+", "-", "COUNT", 1);
6135
+ this._lastStreamId = latest?.[0]?.[0] ?? "0-0";
6136
+ } else this._lastStreamId = "0-0";
6137
+ }
6138
+ if (typeof sub.xrange === "function") {
6139
+ await checkGap();
6140
+ apply(await sub.xread("STREAMS", this.backplaneStreamKey, this._lastStreamId));
6141
+ }
6142
+ initialized = true;
6143
+ this._backplaneAvailable = true;
6144
+ };
6145
+ try {
6146
+ await initialize();
6147
+ } catch (error) {
6148
+ this._backplaneAvailable = false;
6149
+ this.logger.warn("Backplane stream initialization failed; retrying in consumer loop", { error: error.message });
6150
+ }
5454
6151
  const runLoop = async () => {
5455
6152
  while (!this._destroyed && !this._redisDisabled) {
5456
6153
  try {
6154
+ if (!initialized) await initialize();
6155
+ if (this._destroyed) break;
6156
+ await checkGap();
5457
6157
  const res = await sub.xread(
5458
6158
  "BLOCK",
5459
6159
  this.opts.backplaneStreamBlockMs,
@@ -5462,19 +6162,10 @@ var CacheService = class _CacheService {
5462
6162
  this._lastStreamId
5463
6163
  );
5464
6164
  if (this._destroyed) break;
6165
+ this._backplaneAvailable = true;
5465
6166
  if (res && res.length > 0) {
5466
- for (const [, entries] of res) {
5467
- if (entries.length > 0) {
5468
- if (this._lastStreamId !== "$") {
5469
- this.counters.streamReplays++;
5470
- }
5471
- for (const [id, fields] of entries) {
5472
- this._lastStreamId = id;
5473
- this.counters.streamEntriesReceived++;
5474
- this._processStreamEntry(fields);
5475
- }
5476
- }
5477
- }
6167
+ apply(res);
6168
+ this._backplaneAvailable = true;
5478
6169
  } else {
5479
6170
  await new Promise((resolve) => setTimeout(resolve, 10));
5480
6171
  }
@@ -5482,10 +6173,9 @@ var CacheService = class _CacheService {
5482
6173
  if (this._destroyed) break;
5483
6174
  const msg = err.message ?? "";
5484
6175
  if (msg.includes("NOGROUP") || msg.includes("smaller than") || msg.includes("trimmed")) {
5485
- this.counters.streamGaps++;
5486
- this.l1.clear();
5487
- this._lastStreamId = "$";
6176
+ this._resetAfterStreamGap();
5488
6177
  }
6178
+ this._backplaneAvailable = false;
5489
6179
  await new Promise((resolve) => setTimeout(resolve, 200));
5490
6180
  }
5491
6181
  }
@@ -5514,7 +6204,7 @@ var CacheService = class _CacheService {
5514
6204
  else if (f === "tagVersion") tagVersionRaw = v;
5515
6205
  }
5516
6206
  const validOp = op === "del" || op === "del-glob" || op === "tag_incr" || op === "tag_pattern_incr" || op === "tag_pattern_del";
5517
- if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
6207
+ if (!validOp || typeof key !== "string" || !key || typeof src !== "string" || !src || (op === "del" || op === "del-glob") && this._namespace && !key.startsWith(`${this._namespace}:`)) {
5518
6208
  this.logger.warn("Backplane: rejected invalid stream entry", {
5519
6209
  op: String(op).slice(0, 40),
5520
6210
  key: typeof key === "string" ? key.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(key)
@@ -5523,8 +6213,8 @@ var CacheService = class _CacheService {
5523
6213
  }
5524
6214
  let tagVersion;
5525
6215
  if (tagVersionRaw !== void 0) {
5526
- const parsed = parseInt(tagVersionRaw, 10);
5527
- if (!Number.isFinite(parsed)) {
6216
+ const parsed = Number(tagVersionRaw);
6217
+ if (!Number.isSafeInteger(parsed) || parsed < 0) {
5528
6218
  this.logger.warn("Backplane: rejected stream entry with non-numeric tagVersion", { key });
5529
6219
  return;
5530
6220
  }
@@ -5542,16 +6232,10 @@ var CacheService = class _CacheService {
5542
6232
  this.l1.delete(key);
5543
6233
  this._bumpKeyMutation(key);
5544
6234
  this.inflight.delete(key);
5545
- this._pendingDiskDeletes.add(key);
5546
- setImmediate(() => {
5547
- try {
5548
- if (!this._diskDisabled) this.disk.delete(key);
5549
- } finally {
5550
- this._pendingDiskDeletes.delete(key);
5551
- }
5552
- });
6235
+ this._invalidateDiskKey(key);
5553
6236
  this._cascadeDependencies(key);
5554
6237
  } else if (op === "del-glob") {
6238
+ this._fenceInvalidation();
5555
6239
  this.l1.deletePattern(key);
5556
6240
  const pfx = key.endsWith("*") ? key.slice(0, -1) : key;
5557
6241
  for (const liveKey of this.l1.liveKeys()) {
@@ -5565,12 +6249,22 @@ var CacheService = class _CacheService {
5565
6249
  this.inflight.delete(inflightKey);
5566
6250
  }
5567
6251
  }
5568
- this._addPatternTombstone(pfx);
6252
+ this._addPatternTombstone(key);
6253
+ this._removePatternFromIndices(key);
6254
+ if (key === this.nk("*")) {
6255
+ this.tagIndex.clear();
6256
+ this.keyTags.clear();
6257
+ this.tagVersions.clear();
6258
+ this.dependencyIndex.clear();
6259
+ this.keyDependencies.clear();
6260
+ }
5569
6261
  } else if (op === "tag_incr") {
6262
+ this._fenceInvalidation();
5570
6263
  const tag = key;
5571
6264
  const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
5572
6265
  this._setLocalTagVersion(tag, ver, performance.now());
5573
6266
  } else if (op === "tag_pattern_incr") {
6267
+ this._fenceInvalidation();
5574
6268
  const pattern = key;
5575
6269
  const now = performance.now();
5576
6270
  for (const [tag, info] of this.tagVersions) {
@@ -5590,6 +6284,7 @@ var CacheService = class _CacheService {
5590
6284
  }
5591
6285
  }, 0);
5592
6286
  } else if (op === "tag_pattern_del") {
6287
+ this._fenceInvalidation();
5593
6288
  const pattern = key;
5594
6289
  const matchedTagKeys = [];
5595
6290
  const prefix = this.nk("_tag_:");
@@ -5600,14 +6295,7 @@ var CacheService = class _CacheService {
5600
6295
  for (const k of members) {
5601
6296
  this.l1.delete(k);
5602
6297
  this._bumpKeyMutation(k);
5603
- this._pendingDiskDeletes.add(k);
5604
- setImmediate(() => {
5605
- try {
5606
- if (!this._diskDisabled) this.disk.delete(k);
5607
- } finally {
5608
- this._pendingDiskDeletes.delete(k);
5609
- }
5610
- });
6298
+ this._invalidateDiskKey(k);
5611
6299
  }
5612
6300
  }
5613
6301
  }
@@ -5638,6 +6326,7 @@ var CacheService = class _CacheService {
5638
6326
  }
5639
6327
  }
5640
6328
  async publishInvalidation(op, key, tagVersion, isCrossRegionRelay = false, isExplicitInvalidation = false) {
6329
+ if (this.opts.l2WriteMode === "read-only") return;
5641
6330
  if (!isCrossRegionRelay && this.opts.crossRegion) {
5642
6331
  const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
5643
6332
  if (shouldBroadcast) {
@@ -5720,13 +6409,13 @@ var CacheService = class _CacheService {
5720
6409
  timestamp: Date.now(),
5721
6410
  namespace: this._namespace || void 0
5722
6411
  };
5723
- this.counters.crossRegionSent++;
5724
6412
  await cr.relay.broadcast(event);
6413
+ this.counters.crossRegionSent++;
5725
6414
  this.logger.debug("Cross-region invalidation broadcast", { op, key, region: cr.currentRegion });
5726
6415
  } catch (err) {
5727
- this.counters.crossRegionSent = Math.max(0, this.counters.crossRegionSent - 1);
5728
6416
  this.counters.crossRegionErrors++;
5729
6417
  this.logger.warn("Cross-region invalidation broadcast failed", { error: err.message });
6418
+ if (this.opts.awaitInvalidationBackplane) throw err;
5730
6419
  }
5731
6420
  }
5732
6421
  /**
@@ -5737,11 +6426,12 @@ var CacheService = class _CacheService {
5737
6426
  * Returns true if the event was accepted and applied, or false if ignored/deduplicated.
5738
6427
  */
5739
6428
  async receiveCrossRegionInvalidation(event) {
6429
+ this._assertActive("receiveCrossRegionInvalidation");
5740
6430
  const cr = this.opts.crossRegion;
5741
6431
  if (!cr) return false;
5742
- if (!event || typeof event !== "object" || !event.id || !event.originRegion || !event.op || !event.key) {
6432
+ if (!isCrossRegionInvalidationEvent(event)) {
5743
6433
  this.counters.crossRegionErrors++;
5744
- this.logger.warn("Cross-region: rejected invalid event payload", { event });
6434
+ this.logger.warn("Cross-region: rejected invalid event payload");
5745
6435
  return false;
5746
6436
  }
5747
6437
  if (event.originRegion === cr.currentRegion) {
@@ -5752,13 +6442,52 @@ var CacheService = class _CacheService {
5752
6442
  this.counters.crossRegionDeduplicated++;
5753
6443
  return false;
5754
6444
  }
5755
- this._markCrossRegionEventSeen(event.id);
5756
6445
  if (event.namespace !== void 0 && event.namespace !== (this._namespace || void 0)) {
5757
6446
  return false;
5758
6447
  }
6448
+ if ((event.op === "del" || event.op === "del-glob") && this._namespace && !event.key.startsWith(`${this._namespace}:`)) return false;
6449
+ this._markCrossRegionEventSeen(event.id);
5759
6450
  this.counters.crossRegionReceived++;
5760
- this._applyInvalidationEvent(event.op, event.key, event.tagVersion);
5761
- void this.publishInvalidation(event.op, event.key, event.tagVersion, true);
6451
+ const localTags = /* @__PURE__ */ new Set([...this.tagVersions.keys(), ...[...this.tagIndex.keys()].map((key) => this.unnk(key).replace(/^_tag_:/, ""))]);
6452
+ let version = event.tagVersion;
6453
+ if (event.op === "tag_incr") version = Math.max((this.tagVersions.get(event.key)?.version ?? 0) + 1, version ?? 0);
6454
+ this._applyInvalidationEvent(event.op, event.key, version);
6455
+ try {
6456
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6457
+ const client = await this.getRedis();
6458
+ if (event.op === "del" || event.op === "del-glob") {
6459
+ await this._deleteRedisKeys(client, event.op === "del" ? [event.key] : await this._scanKeys(client, event.key));
6460
+ } else if (event.op === "tag_incr") {
6461
+ version = Number(await client.eval(LUA_RECEIVE_TAG_VERSION, 1, this.nk(`tag_ver:${event.key}`), String(version)));
6462
+ this._setLocalTagVersion(event.key, version);
6463
+ } else {
6464
+ const matched = await this._resolveMatchingTags(event.key, false);
6465
+ for (const tag of localTags) if (matchesTagPattern(event.key, tag)) matched.add(tag);
6466
+ for (const tag of matched) {
6467
+ if (event.op === "tag_pattern_incr") {
6468
+ const floor = this.tagVersions.get(tag)?.version ?? 1;
6469
+ const next = Number(await client.eval(LUA_RECEIVE_TAG_VERSION, 1, this.nk(`tag_ver:${tag}`), String(floor)));
6470
+ this._setLocalTagVersion(tag, next);
6471
+ await this.publishInvalidation("tag_incr", tag, next, true);
6472
+ } else {
6473
+ const tagKey = this.nk(`_tag_:${tag}`);
6474
+ const members = await client.smembers(tagKey);
6475
+ this._removeTagMembersLocal(members);
6476
+ await this._deleteRedisKeys(client, [...members, tagKey]);
6477
+ await Promise.all(members.map((key) => this.publishInvalidation("del", key, void 0, true)));
6478
+ }
6479
+ }
6480
+ }
6481
+ this.cb.onSuccess();
6482
+ }
6483
+ await this.publishInvalidation(event.op, event.key, version, true);
6484
+ } catch (error) {
6485
+ this._seenCrossRegionEvents.delete(event.id);
6486
+ this.counters.crossRegionErrors++;
6487
+ this.logger.warn("Cross-region regional invalidation failed", { error: error.message });
6488
+ if (this.opts.awaitInvalidationBackplane) throw error;
6489
+ return false;
6490
+ }
5762
6491
  this.logger.info("Cross-region invalidation applied", {
5763
6492
  op: event.op,
5764
6493
  key: event.key,
@@ -5773,10 +6502,10 @@ var CacheService = class _CacheService {
5773
6502
  const oldestKey = this.tagVersions.keys().next().value;
5774
6503
  if (oldestKey !== void 0) this.tagVersions.delete(oldestKey);
5775
6504
  }
5776
- this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
6505
+ this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now, refreshEpoch: this._tagRefreshEpoch });
5777
6506
  }
5778
6507
  async _isGenerationalEntryStale(tagVersions) {
5779
- if (this.opts.tagStrategy !== "generational" || !tagVersions) return false;
6508
+ if (!tagVersions) return false;
5780
6509
  const tags = Object.keys(tagVersions);
5781
6510
  if (tags.length === 0) return false;
5782
6511
  const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
@@ -5788,13 +6517,23 @@ var CacheService = class _CacheService {
5788
6517
  async _deleteRedisKeys(client, keys) {
5789
6518
  if (keys.length === 0) return;
5790
6519
  const CHUNK_SIZE = 1e3;
5791
- if (client instanceof import_ioredis.Cluster) {
5792
- for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
5793
- const chunk = keys.slice(i, i + CHUNK_SIZE);
5794
- const pl = client.pipeline();
5795
- for (const k of chunk) pl.del(k);
5796
- await pl.exec();
5797
- }
6520
+ if (client instanceof import_ioredis2.Cluster) {
6521
+ const groups = /* @__PURE__ */ new Map();
6522
+ for (const key of keys) {
6523
+ const slot = redisHashSlot(key);
6524
+ const master = client.slots?.[slot]?.[0] ?? String(slot);
6525
+ const members = groups.get(master) ?? [];
6526
+ members.push(key);
6527
+ groups.set(master, members);
6528
+ }
6529
+ await Promise.all([...groups.values()].map(async (members) => {
6530
+ for (let offset = 0; offset < members.length; offset += CHUNK_SIZE) {
6531
+ const pipeline = client.pipeline();
6532
+ for (const key of members.slice(offset, offset + CHUNK_SIZE)) pipeline.del(key);
6533
+ const result = await pipeline.exec();
6534
+ if (!result || result.some(([error]) => error)) throw new Error("Redis Cluster delete failed");
6535
+ }
6536
+ }));
5798
6537
  return;
5799
6538
  }
5800
6539
  for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
@@ -5807,8 +6546,11 @@ var CacheService = class _CacheService {
5807
6546
  let storedTagVersions = {};
5808
6547
  if (hashData.tv) {
5809
6548
  try {
5810
- storedTagVersions = JSON.parse(hashData.tv);
6549
+ const parsed = JSON.parse(hashData.tv);
6550
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || Object.values(parsed).some((version) => !Number.isSafeInteger(version) || Number(version) < 0)) return null;
6551
+ storedTagVersions = parsed;
5811
6552
  } catch {
6553
+ return null;
5812
6554
  }
5813
6555
  }
5814
6556
  if (await this._isGenerationalEntryStale(storedTagVersions)) {
@@ -5817,18 +6559,48 @@ var CacheService = class _CacheService {
5817
6559
  return { stale: true };
5818
6560
  }
5819
6561
  const value = await this._decryptAndDeserialize(hashData.d);
5820
- return { value, tagVersions: storedTagVersions, stale: false };
6562
+ const expiresAt = Number(hashData.e);
6563
+ const staleAt = Number(hashData.s);
6564
+ let tags;
6565
+ let dependsOn;
6566
+ try {
6567
+ const parsedTags = hashData.tags ? JSON.parse(hashData.tags) : Object.keys(storedTagVersions);
6568
+ const parsedDependencies = hashData.deps ? JSON.parse(hashData.deps) : void 0;
6569
+ if (Array.isArray(parsedTags) && parsedTags.every((tag) => typeof tag === "string")) tags = parsedTags;
6570
+ if (Array.isArray(parsedDependencies) && parsedDependencies.every((pattern) => typeof pattern === "string")) dependsOn = parsedDependencies;
6571
+ } catch {
6572
+ return null;
6573
+ }
6574
+ return {
6575
+ value,
6576
+ tagVersions: storedTagVersions,
6577
+ stale: false,
6578
+ tags,
6579
+ dependsOn,
6580
+ setAt: Number(hashData.t) || void 0,
6581
+ expiresAt: Number.isFinite(expiresAt) && expiresAt > 0 ? expiresAt : void 0,
6582
+ staleAt: Number.isFinite(staleAt) && staleAt > 0 ? staleAt : void 0
6583
+ };
5821
6584
  }
5822
6585
  async _readRedisEntry(client, k, allowAutoPipeline = false) {
6586
+ const readStartedAt = Date.now();
6587
+ const read = async (hash) => allowAutoPipeline && this.opts.autoPipeline && this.pipeliner ? this.pipeliner.read(k, hash) : readRedisValue(client, k, hash);
6588
+ const withExpiry = (entry, ttlMs2) => {
6589
+ if (!entry || ttlMs2 === -2 || ttlMs2 === 0) return null;
6590
+ if (ttlMs2 !== void 0 && Number.isFinite(ttlMs2) && ttlMs2 > 0) {
6591
+ entry.expiresAt = Math.min(entry.expiresAt ?? Infinity, readStartedAt + ttlMs2);
6592
+ }
6593
+ return entry.expiresAt !== void 0 && entry.expiresAt <= Date.now() ? null : entry;
6594
+ };
5823
6595
  if (this.opts.tagStrategy === "generational" && typeof client.hgetall === "function") {
5824
6596
  try {
5825
- const hashData = await client.hgetall(k);
6597
+ const { raw: hashData, ttlMs: ttlMs2 } = await read(true);
5826
6598
  if (typeof hashData === "string") {
5827
6599
  const value2 = await this._decryptAndDeserialize(hashData);
5828
- return { value: value2, stale: false };
6600
+ return withExpiry({ value: value2, stale: false }, ttlMs2);
5829
6601
  }
5830
6602
  if (hashData && hashData.d) {
5831
- return await this._parseGenerationalRedisHash(k, hashData);
6603
+ return withExpiry(await this._parseGenerationalRedisHash(k, hashData), ttlMs2);
5832
6604
  }
5833
6605
  return null;
5834
6606
  } catch (err) {
@@ -5836,28 +6608,163 @@ var CacheService = class _CacheService {
5836
6608
  if (!msg.includes("WRONGTYPE")) throw err;
5837
6609
  }
5838
6610
  }
5839
- const raw = allowAutoPipeline && this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
6611
+ const { raw, ttlMs } = await read(false);
5840
6612
  if (raw == null) return null;
6613
+ if (typeof raw !== "string") return null;
5841
6614
  const value = await this._decryptAndDeserialize(raw);
5842
- return { value, stale: false };
6615
+ return withExpiry({ value, stale: false }, ttlMs);
5843
6616
  }
5844
6617
  async _getTagVersion(tag) {
5845
6618
  const now = performance.now();
5846
6619
  const local = this.tagVersions.get(tag);
5847
- if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
6620
+ if (local && (local.refreshEpoch ?? 0) === this._tagRefreshEpoch && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
5848
6621
  return local.version;
5849
6622
  }
5850
6623
  if (!this._redisDisabled) {
5851
6624
  try {
5852
6625
  const client = await this.getRedis();
5853
6626
  const raw = await client.get(this.nk(`tag_ver:${tag}`));
5854
- const version = raw ? parseInt(raw, 10) : 0;
5855
- this._setLocalTagVersion(tag, version, now);
5856
- return version;
6627
+ const parsed = raw ? Number(raw) : 0;
6628
+ if (!Number.isSafeInteger(parsed) || parsed < 0) throw new Error("Invalid Redis tag generation");
6629
+ const version2 = Math.max(this.tagVersions.get(tag)?.version ?? 0, parsed);
6630
+ if (this.opts.l2WriteMode === "read-write") {
6631
+ if (raw === null) await client.set(this.nk(`tag_ver:${tag}`), String(version2), "NX");
6632
+ else if (version2 > parsed) await client.eval(LUA_MAX_TAG_VERSION, 1, this.nk(`tag_ver:${tag}`), String(version2));
6633
+ }
6634
+ this._setLocalTagVersion(tag, version2, now);
6635
+ this.cb.onSuccess();
6636
+ return version2;
5857
6637
  } catch {
5858
6638
  }
5859
6639
  }
5860
- return local?.version ?? 0;
6640
+ const version = this.tagVersions.get(tag)?.version ?? local?.version ?? 0;
6641
+ if (this._redisDisabled) this._setLocalTagVersion(tag, version, now);
6642
+ return version;
6643
+ }
6644
+ async _readRedisBatch(client, keys) {
6645
+ const entries = /* @__PURE__ */ new Map();
6646
+ const groups = /* @__PURE__ */ new Map();
6647
+ for (const key of new Set(keys)) {
6648
+ const group = client instanceof import_ioredis2.Cluster ? client.slots[redisHashSlot(key)]?.[0] ?? String(redisHashSlot(key)) : "single";
6649
+ const members = groups.get(group) ?? [];
6650
+ members.push(key);
6651
+ groups.set(group, members);
6652
+ }
6653
+ await Promise.all([...groups.values()].map(async (members) => {
6654
+ for (let offset = 0; offset < members.length; offset += 1e3) {
6655
+ const chunk = members.slice(offset, offset + 1e3);
6656
+ const pipeline = typeof client.pipeline === "function" ? client.pipeline() : client.multi();
6657
+ const timedScripts = typeof pipeline.eval === "function";
6658
+ const hashes = this.opts.tagStrategy === "generational" && typeof pipeline.hgetall === "function";
6659
+ for (const key of chunk) {
6660
+ if (timedScripts) pipeline.eval(LUA_READ_CACHE_ENTRY, 1, key);
6661
+ else if (hashes) pipeline.hgetall(key);
6662
+ else pipeline.get(key);
6663
+ }
6664
+ const startedAt = Date.now();
6665
+ const start = performance.now();
6666
+ const results = await pipeline.exec();
6667
+ this.watchdog.recordRedis(performance.now() - start);
6668
+ if (!results) throw new Error("Redis batch read aborted");
6669
+ for (let index = 0; index < chunk.length; index++) {
6670
+ try {
6671
+ const tuple = results[index];
6672
+ if (!tuple) continue;
6673
+ let [error, raw] = tuple;
6674
+ let ttl;
6675
+ if (error?.message?.includes("WRONGTYPE")) {
6676
+ const fallback = await this._readRedisEntry(client, chunk[index]);
6677
+ if (fallback && !fallback.stale) entries.set(chunk[index], fallback);
6678
+ continue;
6679
+ }
6680
+ if (error) continue;
6681
+ if (timedScripts) {
6682
+ if (!Array.isArray(raw) || raw[0] === "none") continue;
6683
+ const kind = raw[0];
6684
+ ttl = Number(raw[2]);
6685
+ const payload = raw[1];
6686
+ if (kind === "hash") {
6687
+ if (!Array.isArray(payload) || payload.length % 2 !== 0) continue;
6688
+ raw = Object.fromEntries(Array.from({ length: payload.length / 2 }, (_unused, i) => [String(payload[i * 2]), String(payload[i * 2 + 1])]));
6689
+ } else if (kind === "string") raw = payload;
6690
+ else continue;
6691
+ if (ttl === -2 || ttl === 0) continue;
6692
+ }
6693
+ 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;
6694
+ if (!entry || entry.stale) continue;
6695
+ if (ttl !== void 0 && ttl > 0) entry.expiresAt = Math.min(entry.expiresAt ?? Infinity, startedAt + ttl);
6696
+ if (entry.expiresAt !== void 0 && entry.expiresAt <= Date.now()) continue;
6697
+ entries.set(chunk[index], entry);
6698
+ } catch (error) {
6699
+ this.logger.debug("mget: skipping invalid remote entry", { key: chunk[index], error: error.message });
6700
+ }
6701
+ }
6702
+ }
6703
+ }));
6704
+ this.cb.onSuccess();
6705
+ return entries;
6706
+ }
6707
+ _promoteRedisEntry(key, entry, fallbackTtlMs, priority) {
6708
+ const expiresAt = entry.expiresAt ?? Date.now() + fallbackTtlMs;
6709
+ if (expiresAt <= Date.now()) return false;
6710
+ const admitted = this.l1.set(
6711
+ key,
6712
+ entry.value,
6713
+ expiresAt - Date.now(),
6714
+ priority,
6715
+ entry.staleAt,
6716
+ void 0,
6717
+ entry.tagVersions,
6718
+ entry.setAt,
6719
+ entry.tags,
6720
+ entry.dependsOn
6721
+ );
6722
+ if (admitted) this._restoreEntryMetadata(key, { ...entry, expiresAt });
6723
+ return true;
6724
+ }
6725
+ async _readDiskEntry(key, epoch) {
6726
+ if (this._diskDisabled || this._pendingDiskDeletes.has(key) || !this.watchdog.isDiskAllowed()) return null;
6727
+ const start = performance.now();
6728
+ const entry = this.disk.load(key);
6729
+ const elapsed = performance.now() - start;
6730
+ this.watchdog.recordDisk(elapsed);
6731
+ this.watchdog.onCanaryResult(entry !== null, elapsed);
6732
+ 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;
6733
+ this.l1.importEntries([{ key, entry }], this.opts.forbiddenSnapshotPrefixes);
6734
+ const hit = this.l1.get(key);
6735
+ const value = hit ? hit.value : entry.isCompressed ? this.codec.decode(entry.data) : JSON.parse(entry.data);
6736
+ this._restoreEntryMetadata(key, entry);
6737
+ return { value, entry };
6738
+ }
6739
+ /** Common write policy and metadata across get/set/revalidation/draining. */
6740
+ async _writeRedisEntry(key, data, expiresAt, setAt, tagVersions, staleAt, tags, dependsOn, canCommit = () => true) {
6741
+ if (this._redisDisabled || this.opts.l2WriteMode !== "read-write" || !canCommit() || this._destroyed) return;
6742
+ const client = await this.getRedis();
6743
+ const stored = await this._serializeAndEncrypt(JSON.stringify(data) ?? "undefined");
6744
+ if (!canCommit() || this._destroyed) return;
6745
+ const useHash = this.opts.tagStrategy === "generational" && (tagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function");
6746
+ const remaining = (useHash ? expiresAt : staleAt ?? expiresAt) - Date.now();
6747
+ if (remaining <= 0) return;
6748
+ const ttl = Math.max(1, Math.ceil(remaining / 1e3));
6749
+ if (useHash) {
6750
+ const transaction = client.multi();
6751
+ transaction.del(key);
6752
+ const hash = { d: stored, t: String(setAt), tv: JSON.stringify(tagVersions ?? {}), e: String(expiresAt) };
6753
+ if (staleAt !== void 0) hash.s = String(staleAt);
6754
+ if (tags?.length) hash.tags = JSON.stringify(tags);
6755
+ if (dependsOn?.length) hash.deps = JSON.stringify(dependsOn);
6756
+ transaction.hset(key, hash);
6757
+ transaction.expire(key, ttl);
6758
+ const result = await transaction.exec();
6759
+ if (!result || result.some(([error]) => error)) throw new Error("Redis cache write transaction failed");
6760
+ } else if (this.opts.autoPipeline && this.pipeliner) {
6761
+ if (typeof client.pttl === "function" && typeof client.set === "function") await this.pipeliner.setpx(key, Math.ceil(remaining), stored);
6762
+ else await this.pipeliner.setex(key, ttl, stored);
6763
+ } else {
6764
+ if (typeof client.pttl === "function" && typeof client.set === "function") await client.set(key, stored, "PX", Math.ceil(remaining));
6765
+ else await client.setex(key, ttl, stored);
6766
+ }
6767
+ this.cb.onSuccess();
5861
6768
  }
5862
6769
  _deleteIfStale(k, setAtMs) {
5863
6770
  this.l1.deleteIfSetBefore(k, setAtMs);
@@ -5910,7 +6817,7 @@ var CacheService = class _CacheService {
5910
6817
  } else {
5911
6818
  plain = raw;
5912
6819
  }
5913
- return JSON.parse(plain);
6820
+ return plain === "undefined" ? void 0 : JSON.parse(plain);
5914
6821
  }
5915
6822
  /**
5916
6823
  * Scan all keys matching `pattern` across single-node or Cluster clients.
@@ -5918,7 +6825,7 @@ var CacheService = class _CacheService {
5918
6825
  */
5919
6826
  async _scanKeys(client, pattern) {
5920
6827
  const keys = [];
5921
- if (client instanceof import_ioredis.Cluster) {
6828
+ if (client instanceof import_ioredis2.Cluster) {
5922
6829
  const masters = client.nodes("master");
5923
6830
  await Promise.all(masters.map(
5924
6831
  (node) => new Promise((resolve, reject) => {
@@ -5981,7 +6888,7 @@ var CacheService = class _CacheService {
5981
6888
  let client = null;
5982
6889
  try {
5983
6890
  if (this.opts.redisClusterNodes?.length) {
5984
- client = new import_ioredis.Cluster(this.opts.redisClusterNodes, {
6891
+ client = new import_ioredis2.Cluster(this.opts.redisClusterNodes, {
5985
6892
  redisOptions: {
5986
6893
  tls: this.opts.redisTls ? {} : void 0,
5987
6894
  connectTimeout: 1e4,
@@ -6001,7 +6908,7 @@ var CacheService = class _CacheService {
6001
6908
  });
6002
6909
  client.on("reconnecting", () => this.logger.debug("Redis Cluster reconnecting"));
6003
6910
  } else if (this.opts.redisSentinel) {
6004
- client = new import_ioredis.Redis({
6911
+ client = new import_ioredis2.Redis({
6005
6912
  sentinels: this.opts.redisSentinel.sentinels,
6006
6913
  name: this.opts.redisSentinel.name,
6007
6914
  tls: this.opts.redisTls ? {} : void 0,
@@ -6021,7 +6928,7 @@ var CacheService = class _CacheService {
6021
6928
  });
6022
6929
  client.on("reconnecting", () => this.logger.debug("Redis Sentinel reconnecting"));
6023
6930
  } else {
6024
- client = new import_ioredis.Redis({
6931
+ client = new import_ioredis2.Redis({
6025
6932
  host: this.opts.redisHost,
6026
6933
  port: this.opts.redisPort,
6027
6934
  tls: this.opts.redisTls ? {} : void 0,
@@ -6113,7 +7020,12 @@ var CacheService = class _CacheService {
6113
7020
  try {
6114
7021
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
6115
7022
  if (entries.length === 0) return;
6116
- const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
7023
+ const payload = {
7024
+ version: SNAPSHOT_VERSION,
7025
+ writtenAt: Date.now(),
7026
+ entries,
7027
+ streamId: this.opts.backplaneMode === "stream" && this._lastStreamId !== "$" ? this._lastStreamId : void 0
7028
+ };
6117
7029
  const packed = this.codec.encode(payload);
6118
7030
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
6119
7031
  const dest = altPath ?? this.opts.snapshotPath;
@@ -6181,6 +7093,9 @@ var CacheService = class _CacheService {
6181
7093
  return;
6182
7094
  }
6183
7095
  const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
7096
+ this._restoredSnapshot ||= loaded > 0;
7097
+ if (typeof snapshot.streamId === "string" && /^\d{1,20}-\d{1,20}$/.test(snapshot.streamId)) this._lastStreamId = snapshot.streamId;
7098
+ for (const { key, entry } of snapshot.entries) if (this.l1.has(key)) this._restoreEntryMetadata(key, entry);
6184
7099
  this.logger.info("Cache snapshot loaded (L1 is warm)", {
6185
7100
  loaded,
6186
7101
  total: snapshot.entries.length,
@@ -6205,7 +7120,12 @@ var CacheService = class _CacheService {
6205
7120
  try {
6206
7121
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
6207
7122
  if (entries.length === 0) return false;
6208
- const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
7123
+ const payload = {
7124
+ version: SNAPSHOT_VERSION,
7125
+ writtenAt: Date.now(),
7126
+ entries,
7127
+ streamId: this.opts.backplaneMode === "stream" && this._lastStreamId !== "$" ? this._lastStreamId : void 0
7128
+ };
6209
7129
  const packed = this.codec.encode(payload);
6210
7130
  let final;
6211
7131
  if (this.opts.remoteSnapshot.envelope) {
@@ -6236,13 +7156,16 @@ var CacheService = class _CacheService {
6236
7156
  async loadRemoteSnapshot() {
6237
7157
  if (!this.opts.remoteSnapshot) return 0;
6238
7158
  const maxAgeMs = this.opts.remoteSnapshot.maxAgeMs ?? this.opts.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE;
7159
+ const epoch = this._globalEpoch;
6239
7160
  try {
6240
7161
  const raw = await this.opts.remoteSnapshot.adapter.get();
7162
+ if (this._destroyed || this._globalEpoch !== epoch) return 0;
6241
7163
  if (!raw || raw.length === 0) {
6242
7164
  this.logger.debug("Remote snapshot not found or empty \u2014 starting cold");
6243
7165
  return 0;
6244
7166
  }
6245
7167
  const rawBuf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
7168
+ if (rawBuf.length > SNAPSHOT_MAX_FILE_BYTES) throw new Error("Remote snapshot exceeds size limit");
6246
7169
  let buf;
6247
7170
  try {
6248
7171
  if (EnvelopeEncryption.isEnvelope(rawBuf)) {
@@ -6288,7 +7211,12 @@ var CacheService = class _CacheService {
6288
7211
  this.logger.warn("Remote snapshot rejected: entries is not an array");
6289
7212
  return 0;
6290
7213
  }
6291
- const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
7214
+ if (this._destroyed || this._globalEpoch !== epoch) return 0;
7215
+ const eligible = snapshot.entries.filter((item) => item && !this._keyMutationEpochs.has(item.key));
7216
+ const loaded = this.l1.importEntries(eligible, this.opts.forbiddenSnapshotPrefixes);
7217
+ this._restoredSnapshot ||= loaded > 0;
7218
+ if (typeof snapshot.streamId === "string" && /^\d{1,20}-\d{1,20}$/.test(snapshot.streamId)) this._lastStreamId = snapshot.streamId;
7219
+ for (const { key, entry } of eligible) if (this.l1.has(key)) this._restoreEntryMetadata(key, entry);
6292
7220
  this.counters.remoteSnapshotDownloads++;
6293
7221
  this.counters.remoteSnapshotLastDownloadedAt = Date.now();
6294
7222
  this.logger.info("Remote cache snapshot loaded (L1 hydrated)", {
@@ -6340,7 +7268,7 @@ var CacheService = class _CacheService {
6340
7268
  const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
6341
7269
  if (isGenerationalStale) {
6342
7270
  this._deleteIfStale(k, l1Hit.setAt ?? 0);
6343
- } else {
7271
+ } else if (!l1Hit.isStale || optSwr > 0) {
6344
7272
  if (l1Hit.isStale) {
6345
7273
  const swrGraceMs2 = optSwr * 1e3;
6346
7274
  if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
@@ -6403,49 +7331,29 @@ var CacheService = class _CacheService {
6403
7331
  this.counters.stampedes++;
6404
7332
  this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch/read", { cacheKey });
6405
7333
  span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
6406
- return existing;
7334
+ return this._prepareReadValue(await existing);
6407
7335
  }
6408
7336
  const mutationEpochAtStart = this._getKeyMutationEpoch(k);
6409
- const executionPromise = (async () => {
7337
+ const executionPromise = Promise.resolve().then(async () => {
6410
7338
  try {
6411
- if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
6412
- if (this._isTombstonedByPattern(k)) {
6413
- try {
6414
- this.disk.delete(k);
6415
- } catch {
6416
- }
6417
- } else {
6418
- const isDiskAllowed = this.watchdog.isDiskAllowed();
6419
- if (isDiskAllowed) {
6420
- const diskStart = performance.now();
6421
- const diskHit = this.disk.load(k);
6422
- const diskElapsed = performance.now() - diskStart;
6423
- this.watchdog.recordDisk(diskElapsed);
6424
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6425
- if (diskHit !== null) {
6426
- const isDiskStale = await this._isGenerationalEntryStale(diskHit.tagVersions);
6427
- if (isDiskStale) {
6428
- this.disk.delete(k);
6429
- } else {
6430
- const promoted = this.l1.importEntries(
6431
- [{ key: k, entry: diskHit }],
6432
- this.opts.forbiddenSnapshotPrefixes
6433
- );
6434
- if (promoted > 0) {
6435
- const l1Check = this.l1.get(k);
6436
- if (l1Check !== null) {
6437
- this.counters.diskHits++;
6438
- this.opts.onHit?.(cacheKey, "disk");
6439
- this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
6440
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
6441
- if (this.opts.frozen) deepFreeze(l1Check.value);
6442
- return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
6443
- }
6444
- }
6445
- }
6446
- }
6447
- }
7339
+ const diskHit = await this._readDiskEntry(k, mutationEpochAtStart);
7340
+ if (diskHit && (diskHit.entry.staleAt === void 0 || diskHit.entry.staleAt > Date.now() || optSwr > 0)) {
7341
+ this.counters.diskHits++;
7342
+ this.opts.onHit?.(cacheKey, "disk");
7343
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
7344
+ if (diskHit.entry.staleAt !== void 0 && diskHit.entry.staleAt <= Date.now() && optSwr > 0 && !this.revalidating.has(k)) {
7345
+ this.revalidating.add(k);
7346
+ this.counters.swrRevalidations++;
7347
+ void this._revalidate(
7348
+ k,
7349
+ fetchFn,
7350
+ ttlMs,
7351
+ swrGraceMs,
7352
+ priority,
7353
+ diskHit.entry.tagVersions ?? Object.fromEntries((diskHit.entry.tags ?? []).map((tag) => [tag, 0]))
7354
+ );
6448
7355
  }
7356
+ return diskHit.value;
6449
7357
  }
6450
7358
  if (!this._redisDisabled) {
6451
7359
  try {
@@ -6455,23 +7363,26 @@ var CacheService = class _CacheService {
6455
7363
  const redisElapsed = performance.now() - redisStart;
6456
7364
  this.watchdog.recordRedis(redisElapsed);
6457
7365
  this.cb.onSuccess();
6458
- if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
7366
+ if (redisHit && !redisHit.stale && (redisHit.staleAt === void 0 || redisHit.staleAt > Date.now() || optSwr > 0)) {
6459
7367
  const parsed = redisHit.value;
6460
7368
  if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
6461
7369
  this.logger.debug("Aborting L2 promotion \u2014 key was mutated or deleted during Redis read", { cacheKey });
6462
7370
  span.setAttribute("cache.aborted_mutation_race", true);
6463
7371
  const current = this.l1.get(k);
6464
- const liveVal = current && !current.isStale && current.value !== void 0 ? current.value : parsed;
6465
- if (this.opts.frozen) deepFreeze(liveVal);
6466
- return this.opts.cloneStrategy === "structuredClone" && liveVal != null && typeof liveVal === "object" ? structuredClone(liveVal) : liveVal;
7372
+ const liveVal = current && !current.isStale ? current.value : parsed;
7373
+ return liveVal;
6467
7374
  }
6468
- this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, redisHit.tagVersions);
7375
+ if (!this._promoteRedisEntry(k, redisHit, ttlMs, priority)) throw new Error("Redis entry expired during promotion");
6469
7376
  this.counters.l2Hits++;
6470
7377
  this.opts.onHit?.(cacheKey, "l2");
6471
7378
  this.logger.debug(redisHit.tagVersions ? "L2 hit (Redis hash)" : "L2 hit (Redis)", { cacheKey });
6472
7379
  span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
6473
- if (this.opts.frozen) deepFreeze(parsed);
6474
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
7380
+ if (redisHit.staleAt !== void 0 && redisHit.staleAt <= Date.now() && optSwr > 0 && !this.revalidating.has(k)) {
7381
+ this.revalidating.add(k);
7382
+ this.counters.swrRevalidations++;
7383
+ void this._revalidate(k, fetchFn, ttlMs, swrGraceMs, priority, redisHit.tagVersions);
7384
+ }
7385
+ return parsed;
6475
7386
  }
6476
7387
  } catch (err) {
6477
7388
  this.cb.onFailure();
@@ -6481,6 +7392,7 @@ var CacheService = class _CacheService {
6481
7392
  span.setAttribute("cache.hit", false).setAttribute("cache.hit_tier", "miss");
6482
7393
  this.opts.onMiss?.(cacheKey);
6483
7394
  this.counters.fetches++;
7395
+ const tagSnapshot = this.opts.tagStrategy === "generational" && optTags?.length ? Object.fromEntries(await Promise.all(optTags.map(async (tag) => [tag, await this._getTagVersion(tag)]))) : void 0;
6484
7396
  const fetchStart = Date.now();
6485
7397
  let data;
6486
7398
  try {
@@ -6509,50 +7421,41 @@ var CacheService = class _CacheService {
6509
7421
  }
6510
7422
  const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
6511
7423
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
6512
- let activeTagVersions;
7424
+ const activeTagVersions = tagSnapshot;
6513
7425
  if (optTags?.length) {
6514
7426
  if (this.opts.tagStrategy === "generational") {
6515
- const vers = await Promise.all(optTags.map((tag) => this._getTagVersion(tag)));
6516
- activeTagVersions = {};
6517
- for (let i = 0; i < optTags.length; i++) {
6518
- activeTagVersions[optTags[i]] = vers[i];
6519
- }
7427
+ if (await this._isGenerationalEntryStale(tagSnapshot)) return data;
6520
7428
  } else {
6521
- await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
7429
+ await this._registerTags(k, optTags, Math.ceil(storeTtl / 1e3));
6522
7430
  }
6523
7431
  }
6524
7432
  if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
6525
7433
  this.logger.debug("Aborting in-flight cache commit \u2014 key was mutated or deleted during fetch", { cacheKey });
6526
7434
  span.setAttribute("cache.aborted_mutation_race", true);
6527
7435
  const current = this.l1.get(k);
6528
- if (current && !current.isStale && current.value !== void 0) {
7436
+ if (current && !current.isStale) {
6529
7437
  const freshVal = current.value;
6530
- if (this.opts.frozen) deepFreeze(freshVal);
6531
- return this.opts.cloneStrategy === "structuredClone" && freshVal != null && typeof freshVal === "object" ? structuredClone(freshVal) : freshVal;
7438
+ return freshVal;
6532
7439
  }
6533
- if (this.opts.frozen) deepFreeze(data);
6534
- return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
7440
+ return data;
6535
7441
  }
6536
7442
  const writeTs = Date.now();
6537
- this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs);
6538
- if (!this._redisDisabled) {
7443
+ this._invalidateDiskKey(k);
7444
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs, optTags, opts.dependsOn);
7445
+ this._restoreEntryMetadata(k, { tags: optTags, dependsOn: opts.dependsOn, expiresAt: writeTs + storeTtl });
7446
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6539
7447
  try {
6540
- const client = await this.getRedis();
6541
- const serialized = JSON.stringify(data);
6542
- const toStore = await this._serializeAndEncrypt(serialized);
6543
- const ttlSec = Math.ceil(effectiveTtl / 1e3);
6544
- if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
6545
- const tx = client.multi();
6546
- tx.hset(k, {
6547
- d: toStore,
6548
- t: String(writeTs),
6549
- tv: JSON.stringify(activeTagVersions ?? {})
6550
- });
6551
- tx.expire(k, ttlSec);
6552
- await tx.exec();
6553
- } else {
6554
- await client.setex(k, ttlSec, toStore);
6555
- }
7448
+ await this._writeRedisEntry(
7449
+ k,
7450
+ data,
7451
+ writeTs + storeTtl,
7452
+ writeTs,
7453
+ activeTagVersions,
7454
+ staleAt,
7455
+ optTags,
7456
+ opts.dependsOn,
7457
+ () => this._getKeyMutationEpoch(k) === mutationEpochAtStart
7458
+ );
6556
7459
  this.cb.onSuccess();
6557
7460
  this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
6558
7461
  } catch {
@@ -6562,15 +7465,14 @@ var CacheService = class _CacheService {
6562
7465
  } else {
6563
7466
  this.logger.debug("Cached L1", { cacheKey });
6564
7467
  }
6565
- if (this.opts.frozen) deepFreeze(data);
6566
- return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
7468
+ return data;
6567
7469
  } finally {
6568
- this.inflight.delete(k);
7470
+ if (this.inflight.get(k) === executionPromise) this.inflight.delete(k);
6569
7471
  span.end();
6570
7472
  }
6571
- })();
7473
+ });
6572
7474
  this.inflight.set(k, executionPromise);
6573
- return executionPromise;
7475
+ return this._prepareReadValue(await executionPromise);
6574
7476
  }
6575
7477
  /**
6576
7478
  * Graceful shutdown flusher for Kubernetes preStop hooks, NestJS onApplicationShutdown,
@@ -6651,6 +7553,9 @@ var CacheService = class _CacheService {
6651
7553
  }
6652
7554
  async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority, knownTagVersions) {
6653
7555
  const startEpoch = this._getKeyMutationEpoch(cacheKey);
7556
+ const previous = this.l1.getEntry(cacheKey);
7557
+ const tags = previous?.tags ?? Object.keys(knownTagVersions ?? {});
7558
+ const dependencies = previous?.dependsOn;
6654
7559
  try {
6655
7560
  const fetchStart = Date.now();
6656
7561
  const data = await fetchFn();
@@ -6665,14 +7570,14 @@ var CacheService = class _CacheService {
6665
7570
  const l1Existing = this.l1.get(cacheKey);
6666
7571
  const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
6667
7572
  if (this.opts.tagStrategy === "generational" && tagVersionsSource) {
6668
- const tags = Object.keys(tagVersionsSource);
6669
- const vers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
7573
+ const tags2 = Object.keys(tagVersionsSource);
7574
+ const vers = await Promise.all(tags2.map((tag) => this._getTagVersion(tag)));
6670
7575
  activeTagVersions = {};
6671
- for (let i = 0; i < tags.length; i++) {
6672
- activeTagVersions[tags[i]] = vers[i];
7576
+ for (let i = 0; i < tags2.length; i++) {
7577
+ activeTagVersions[tags2[i]] = vers[i];
6673
7578
  }
6674
7579
  if (knownTagVersions) {
6675
- for (const t of tags) {
7580
+ for (const t of tags2) {
6676
7581
  if (knownTagVersions[t] !== void 0 && activeTagVersions[t] !== knownTagVersions[t]) {
6677
7582
  this.logger.debug("SWR: aborting revalidation commit \u2014 tag version bumped during revalidation", { cacheKey, tag: t });
6678
7583
  return;
@@ -6685,31 +7590,28 @@ var CacheService = class _CacheService {
6685
7590
  return;
6686
7591
  }
6687
7592
  const writeTs = Date.now();
6688
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs);
7593
+ this._invalidateDiskKey(cacheKey);
7594
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs, tags, dependencies);
7595
+ this._restoreEntryMetadata(cacheKey, { tags, dependsOn: dependencies, expiresAt: writeTs + ttlMs + swrGraceMs });
6689
7596
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6690
7597
  try {
6691
- const client = await this.getRedis();
6692
- const s = JSON.stringify(data);
6693
- const stored = await this._serializeAndEncrypt(s);
6694
- const ttlSec = Math.ceil(ttlMs / 1e3);
6695
- if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
6696
- const tx = client.multi();
6697
- tx.hset(cacheKey, {
6698
- d: stored,
6699
- t: String(writeTs),
6700
- tv: JSON.stringify(activeTagVersions ?? {})
6701
- });
6702
- tx.expire(cacheKey, ttlSec);
6703
- await tx.exec();
6704
- } else {
6705
- await client.setex(cacheKey, ttlSec, stored);
6706
- }
7598
+ await this._writeRedisEntry(
7599
+ cacheKey,
7600
+ data,
7601
+ writeTs + ttlMs + swrGraceMs,
7602
+ writeTs,
7603
+ activeTagVersions,
7604
+ staleAt,
7605
+ tags,
7606
+ dependencies,
7607
+ () => this._getKeyMutationEpoch(cacheKey) === startEpoch
7608
+ );
6707
7609
  } catch {
6708
7610
  }
6709
7611
  }
6710
7612
  this.logger.debug("SWR: revalidation complete", { cacheKey });
6711
7613
  } catch (err) {
6712
- if (this.opts.staleIfError > 0) {
7614
+ if (this.opts.staleIfError > 0 && this._getKeyMutationEpoch(cacheKey) === startEpoch) {
6713
7615
  const additionalMs = this.opts.staleIfError * 1e3;
6714
7616
  this.l1.bumpExpiry(cacheKey, additionalMs);
6715
7617
  this.logger.debug("SWR: revalidation failed, stale-if-error extending expiry", {
@@ -6737,12 +7639,16 @@ var CacheService = class _CacheService {
6737
7639
  const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
6738
7640
  const p = priority ?? inferPriority(cacheKey);
6739
7641
  const k = this.nk(cacheKey);
7642
+ const existingEntry = this.l1.getEntry(k);
7643
+ const requestedTags = opts?.tags ?? existingEntry?.tags ?? this.keyTags.get(k)?.tags;
7644
+ const requestedDependencies = opts?.dependsOn ?? existingEntry?.dependsOn;
6740
7645
  this._bumpKeyMutation(k);
7646
+ const epoch = this._getKeyMutationEpoch(k);
6741
7647
  this.inflight.delete(k);
6742
- this._pendingDiskDeletes.delete(k);
7648
+ this._invalidateDiskKey(k);
6743
7649
  this.counters.sets++;
6744
7650
  let activeTagVersions;
6745
- const tagsToRegister = opts?.tags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
7651
+ const tagsToRegister = requestedTags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(requestedTags, this.opts.tagHierarchyDelimiter) : requestedTags : void 0;
6746
7652
  if (tagsToRegister?.length) {
6747
7653
  if (this.opts.tagStrategy === "generational") {
6748
7654
  const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
@@ -6751,50 +7657,27 @@ var CacheService = class _CacheService {
6751
7657
  activeTagVersions[tagsToRegister[i]] = vers[i];
6752
7658
  }
6753
7659
  } else {
6754
- await this._registerTags(k, tagsToRegister, ttlSeconds);
7660
+ await this._registerTags(k, tagsToRegister, effectiveTtlSeconds);
6755
7661
  }
6756
7662
  }
7663
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return;
6757
7664
  const writeTs = Date.now();
6758
- this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions, writeTs);
6759
- if (opts?.dependsOn !== void 0) {
6760
- this._removeKeyDependencies(k);
6761
- if (opts.dependsOn.length > 0) {
6762
- const nsPatterns = [];
6763
- for (const pattern of opts.dependsOn) {
6764
- const nsPattern = this.nk(pattern);
6765
- nsPatterns.push(nsPattern);
6766
- let deps = this.dependencyIndex.get(nsPattern);
6767
- if (!deps) {
6768
- deps = /* @__PURE__ */ new Set();
6769
- this.dependencyIndex.set(nsPattern, deps);
6770
- }
6771
- deps.add(k);
6772
- }
6773
- this.keyDependencies.set(k, nsPatterns);
6774
- }
6775
- }
7665
+ this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions, writeTs, tagsToRegister, requestedDependencies);
7666
+ this._rememberTags(k, tagsToRegister ?? [], writeTs + ttlMs);
7667
+ this._registerDependencies(k, requestedDependencies);
6776
7668
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6777
7669
  try {
6778
- const client = await this.getRedis();
6779
- const s = JSON.stringify(data);
6780
- const stored = await this._serializeAndEncrypt(s);
6781
- const ttlSec = Math.ceil(ttlMs / 1e3);
6782
- if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
6783
- const tx = client.multi();
6784
- tx.hset(k, {
6785
- d: stored,
6786
- t: String(writeTs),
6787
- tv: JSON.stringify(activeTagVersions ?? {})
6788
- });
6789
- tx.expire(k, ttlSec);
6790
- await tx.exec();
6791
- } else {
6792
- if (this.opts.autoPipeline && this.pipeliner) {
6793
- await this.pipeliner.setex(k, ttlSec, stored);
6794
- } else {
6795
- await client.setex(k, ttlSec, stored);
6796
- }
6797
- }
7670
+ await this._writeRedisEntry(
7671
+ k,
7672
+ data,
7673
+ writeTs + ttlMs,
7674
+ writeTs,
7675
+ activeTagVersions,
7676
+ void 0,
7677
+ tagsToRegister,
7678
+ requestedDependencies,
7679
+ () => this._getKeyMutationEpoch(k) === epoch
7680
+ );
6798
7681
  this.cb.onSuccess();
6799
7682
  } catch (err) {
6800
7683
  this.cb.onFailure();
@@ -6819,27 +7702,10 @@ var CacheService = class _CacheService {
6819
7702
  * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
6820
7703
  */
6821
7704
  async _registerTags(k, tags, ttlSeconds) {
6822
- this._removeKeyTags(k);
6823
7705
  const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
6824
7706
  const expiresAt = Date.now() + effectiveTtl * 1e3;
6825
- if (this.keyTags.size >= 1e5 && !this.keyTags.has(k)) {
6826
- this._sweepExpiredMetadata();
6827
- if (this.keyTags.size >= 1e5) {
6828
- const oldestKey = this.keyTags.keys().next().value;
6829
- if (oldestKey !== void 0) this._removeKeyTags(oldestKey);
6830
- }
6831
- }
6832
7707
  const uniqueTags = Array.from(new Set(tags));
6833
- for (const tag of uniqueTags) {
6834
- const tagKey = this.nk(`_tag_:${tag}`);
6835
- let members = this.tagIndex.get(tagKey);
6836
- if (!members) {
6837
- members = /* @__PURE__ */ new Set();
6838
- this.tagIndex.set(tagKey, members);
6839
- }
6840
- members.add(k);
6841
- }
6842
- this.keyTags.set(k, { tags: uniqueTags, expiresAt });
7708
+ this._rememberTags(k, uniqueTags, expiresAt);
6843
7709
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6844
7710
  try {
6845
7711
  const client = await this.getRedis();
@@ -6872,6 +7738,7 @@ var CacheService = class _CacheService {
6872
7738
  const k = this.nk(cacheKey);
6873
7739
  this.counters.deletes++;
6874
7740
  if (isPattern) {
7741
+ this._fenceInvalidation();
6875
7742
  const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6876
7743
  for (const liveKey of this.l1.liveKeys()) {
6877
7744
  if (liveKey.startsWith(pfx)) {
@@ -6884,9 +7751,9 @@ var CacheService = class _CacheService {
6884
7751
  this.inflight.delete(inflightKey);
6885
7752
  }
6886
7753
  }
6887
- this._addPatternTombstone(pfx);
7754
+ this._addPatternTombstone(k);
6888
7755
  this.l1.deletePattern(k);
6889
- this._removePrefixFromIndices(pfx);
7756
+ this._removePatternFromIndices(k);
6890
7757
  for (const ktKey of Array.from(this.keyTags.keys())) {
6891
7758
  if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
6892
7759
  }
@@ -6897,14 +7764,7 @@ var CacheService = class _CacheService {
6897
7764
  this._bumpKeyMutation(k);
6898
7765
  this.inflight.delete(k);
6899
7766
  this.l1.delete(k);
6900
- this._pendingDiskDeletes.add(k);
6901
- setImmediate(() => {
6902
- try {
6903
- if (!this._diskDisabled) this.disk.delete(k);
6904
- } finally {
6905
- this._pendingDiskDeletes.delete(k);
6906
- }
6907
- });
7767
+ this._invalidateDiskKey(k);
6908
7768
  this._removeKeyTags(k);
6909
7769
  this._cascadeDependencies(k);
6910
7770
  this._removeKeyDependencies(k);
@@ -6961,7 +7821,7 @@ var CacheService = class _CacheService {
6961
7821
  async increment(cacheKey, ttlSeconds) {
6962
7822
  this._assertActive("increment");
6963
7823
  const k = this.nk(cacheKey);
6964
- if (this._redisDisabled) {
7824
+ if (this._redisDisabled || this.opts.l2WriteMode === "read-only") {
6965
7825
  if (!this._incrementFallbackWarned) {
6966
7826
  this._incrementFallbackWarned = true;
6967
7827
  this.logger.warn(
@@ -7017,6 +7877,7 @@ var CacheService = class _CacheService {
7017
7877
  this.counters.deletes++;
7018
7878
  const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
7019
7879
  if (k) {
7880
+ this._fenceInvalidation();
7020
7881
  const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
7021
7882
  for (const liveKey of this.l1.liveKeys()) {
7022
7883
  if (liveKey.startsWith(pfx)) {
@@ -7029,9 +7890,9 @@ var CacheService = class _CacheService {
7029
7890
  this.inflight.delete(inflightKey);
7030
7891
  }
7031
7892
  }
7032
- this._addPatternTombstone(pfx);
7893
+ this._addPatternTombstone(k);
7033
7894
  this.l1.deletePattern(k);
7034
- this._removePrefixFromIndices(pfx);
7895
+ this._removePatternFromIndices(k);
7035
7896
  } else {
7036
7897
  this._globalEpoch++;
7037
7898
  this.inflight.clear();
@@ -7181,28 +8042,34 @@ var CacheService = class _CacheService {
7181
8042
  this._assertActive("scan");
7182
8043
  const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
7183
8044
  this.l1.scan((key, entry, pfx) => {
7184
- const value = entry.value !== void 0 ? entry.value : entry.data;
7185
- fn(key, value, pfx);
8045
+ fn(key, this._prepareReadValue(this.l1.resolveValue(entry)), pfx);
7186
8046
  }, prefixLen);
7187
8047
  }
7188
8048
  /**
7189
- * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
8049
+ * Extend the TTL of a key in L1 and Redis without fetching.
7190
8050
  * Returns `false` if the key is absent or already expired.
7191
8051
  *
7192
8052
  * @param newTtlSeconds - The new TTL from now, in seconds.
7193
8053
  */
7194
8054
  async touch(cacheKey, newTtlSeconds) {
7195
8055
  this._assertActive("touch");
8056
+ if (!Number.isFinite(newTtlSeconds) || newTtlSeconds <= 0) throw new Error("touch TTL must be finite and positive");
7196
8057
  const k = this.nk(cacheKey);
8058
+ const epoch = this._getKeyMutationEpoch(k);
7197
8059
  const hit = this.l1.touch(k, newTtlSeconds * 1e3);
8060
+ const entry = this.l1.getEntry(k);
7198
8061
  if (hit) {
7199
8062
  const kt = this.keyTags.get(k);
7200
8063
  if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1e3;
7201
8064
  }
7202
- if (hit && !this._redisDisabled) {
8065
+ if (hit && !this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7203
8066
  try {
7204
8067
  const client = await this.getRedis();
7205
- void client.expire(k, newTtlSeconds);
8068
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return hit;
8069
+ if (entry && typeof client.pttl === "function" && typeof client.eval === "function") {
8070
+ await client.eval(LUA_TOUCH_CACHE_ENTRY, 1, k, String(entry.setAt ?? 0), String(entry.expiresAt), String(Math.ceil(newTtlSeconds * 1e3)));
8071
+ } else await client.expire(k, Math.ceil(newTtlSeconds));
8072
+ this.cb.onSuccess();
7206
8073
  } catch {
7207
8074
  }
7208
8075
  }
@@ -7224,7 +8091,8 @@ var CacheService = class _CacheService {
7224
8091
  const now = Date.now();
7225
8092
  if (entry.expiresAt <= now) return null;
7226
8093
  if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
7227
- return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
8094
+ if (entry.tagVersions && Object.entries(entry.tagVersions).some(([tag, version]) => (this.tagVersions.get(tag)?.version ?? 0) > version)) return null;
8095
+ return this._prepareReadValue(entry.value !== void 0 ? entry.value : this.codec.decode(entry.data));
7228
8096
  }
7229
8097
  _prepareReadValue(val) {
7230
8098
  if (this.opts.frozen) deepFreeze(val);
@@ -7241,49 +8109,23 @@ var CacheService = class _CacheService {
7241
8109
  async peek(cacheKey) {
7242
8110
  this._assertActive("peek");
7243
8111
  const k = this.nk(cacheKey);
8112
+ const epoch = this._getKeyMutationEpoch(k);
8113
+ this.counters.gets++;
7244
8114
  const l1Hit = this.l1.get(k);
7245
8115
  if (l1Hit !== null) {
7246
8116
  if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
7247
8117
  this._deleteIfStale(k, l1Hit.setAt ?? 0);
7248
8118
  } else {
7249
- this.counters.gets++;
7250
8119
  this.counters.l1Hits++;
7251
8120
  return this._prepareReadValue(l1Hit.value);
7252
8121
  }
7253
8122
  }
7254
- if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
7255
- if (this._isTombstonedByPattern(k)) {
7256
- try {
7257
- this.disk.delete(k);
7258
- } catch {
7259
- }
7260
- } else if (this.watchdog.isDiskAllowed()) {
7261
- const diskStart = performance.now();
7262
- const diskHit = this.disk.load(k);
7263
- const diskElapsed = performance.now() - diskStart;
7264
- this.watchdog.recordDisk(diskElapsed);
7265
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
7266
- if (diskHit !== null) {
7267
- if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
7268
- this.disk.delete(k);
7269
- } else {
7270
- const promoted = this.l1.importEntries(
7271
- [{ key: k, entry: diskHit }],
7272
- this.opts.forbiddenSnapshotPrefixes
7273
- );
7274
- if (promoted > 0) {
7275
- const l1Check = this.l1.get(k);
7276
- if (l1Check !== null) {
7277
- this.counters.gets++;
7278
- this.counters.diskHits++;
7279
- return this._prepareReadValue(l1Check.value);
7280
- }
7281
- }
7282
- }
7283
- }
7284
- }
8123
+ const diskHit = await this._readDiskEntry(k, epoch);
8124
+ if (diskHit) {
8125
+ this.counters.diskHits++;
8126
+ return this._prepareReadValue(diskHit.value);
7285
8127
  }
7286
- if (!this._redisDisabled && !this.cb.isOpen) {
8128
+ if (!this._redisDisabled) {
7287
8129
  try {
7288
8130
  const client = await this.getRedis();
7289
8131
  const redisStart = performance.now();
@@ -7291,10 +8133,10 @@ var CacheService = class _CacheService {
7291
8133
  const redisElapsed = performance.now() - redisStart;
7292
8134
  this.watchdog.recordRedis(redisElapsed);
7293
8135
  this.cb.onSuccess();
7294
- if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
8136
+ if (redisHit && !redisHit.stale) {
7295
8137
  const parsed = redisHit.value;
7296
- this.l1.set(k, parsed, 6e4, inferPriority(cacheKey), void 0, void 0, redisHit.tagVersions);
7297
- this.counters.gets++;
8138
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return null;
8139
+ if (!this._promoteRedisEntry(k, redisHit, 6e4, inferPriority(cacheKey))) return null;
7298
8140
  this.counters.l2Hits++;
7299
8141
  return this._prepareReadValue(parsed);
7300
8142
  }
@@ -7316,6 +8158,8 @@ var CacheService = class _CacheService {
7316
8158
  */
7317
8159
  async mget(keys, fetchFn, ttl = 300, priority) {
7318
8160
  this._assertActive("mget");
8161
+ this.counters.gets += keys.length;
8162
+ const epochs = new Map(keys.map((key) => [this.nk(key), this._getKeyMutationEpoch(this.nk(key))]));
7319
8163
  const span = this._startSpan("tricache.mget");
7320
8164
  if (this.opts.tracer) {
7321
8165
  span.setAttribute("cache.batch.size", keys.length);
@@ -7328,7 +8172,7 @@ var CacheService = class _CacheService {
7328
8172
  for (let i = 0; i < keys.length; i++) {
7329
8173
  const k = this.nk(keys[i]);
7330
8174
  const entry = this.l1.getEntry(k);
7331
- if (entry && entry.expiresAt > now) {
8175
+ if (entry && entry.expiresAt > now && (entry.staleAt === void 0 || entry.staleAt > now)) {
7332
8176
  if (await this._isGenerationalEntryStale(entry.tagVersions)) {
7333
8177
  this._deleteIfStale(k, entry.setAt ?? 0);
7334
8178
  missIndexes.push(i);
@@ -7357,64 +8201,24 @@ var CacheService = class _CacheService {
7357
8201
  try {
7358
8202
  const client = await this.getRedis();
7359
8203
  const nsKeys = missKeys.map((k) => this.nk(k));
7360
- const pipeline = client.multi();
7361
- const useHashPipeline = this.opts.tagStrategy === "generational" && typeof pipeline.hgetall === "function";
7362
- for (const nk of nsKeys) {
7363
- if (useHashPipeline) {
7364
- pipeline.hgetall(nk);
7365
- } else {
7366
- pipeline.get(nk);
7367
- }
7368
- }
7369
- const redisStart = performance.now();
7370
- const raws = await pipeline.exec();
7371
- const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
7372
- this.watchdog.recordRedis(redisElapsed);
7373
- this.cb.onSuccess();
8204
+ const remoteEntries = await this._readRedisBatch(client, nsKeys);
7374
8205
  for (let j = 0; j < missKeys.length; j++) {
7375
- const tuple = raws[j];
7376
- const err = tuple ? tuple[0] : null;
7377
- const rawVal = tuple ? tuple[1] : null;
7378
8206
  const idx = missIndexes[j];
7379
8207
  const k = nsKeys[j];
7380
- let parsed;
7381
- let tagVersions;
7382
- let hit = false;
7383
- if (useHashPipeline) {
7384
- if (err && err.message?.includes("WRONGTYPE")) {
7385
- const fallbackRaw = await client.get(k);
7386
- if (fallbackRaw) {
7387
- parsed = await this._decryptAndDeserialize(fallbackRaw);
7388
- hit = true;
7389
- }
7390
- } else if (!err && typeof rawVal === "string") {
7391
- parsed = await this._decryptAndDeserialize(rawVal);
7392
- hit = true;
7393
- } else if (!err && rawVal && typeof rawVal === "object" && rawVal.d) {
7394
- const hashHit = await this._parseGenerationalRedisHash(k, rawVal);
7395
- if (hashHit && !hashHit.stale && hashHit.value !== void 0) {
7396
- parsed = hashHit.value;
7397
- tagVersions = hashHit.tagVersions;
7398
- hit = true;
7399
- }
7400
- }
7401
- } else if (!err && rawVal) {
7402
- parsed = await this._decryptAndDeserialize(rawVal);
7403
- hit = true;
7404
- }
7405
- if (hit && parsed !== void 0) {
8208
+ const entry = remoteEntries.get(k);
8209
+ if (entry && (entry.staleAt === void 0 || entry.staleAt > Date.now()) && !this._destroyed && this._getKeyMutationEpoch(k) === epochs.get(k)) {
7406
8210
  const p = priority ?? inferPriority(missKeys[j]);
7407
8211
  const ttlVal = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
7408
- this.l1.set(k, parsed, this._jitterTtl(ttlVal * 1e3), p, void 0, void 0, tagVersions);
8212
+ if (!this._promoteRedisEntry(k, entry, this._jitterTtl(ttlVal * 1e3), p)) continue;
7409
8213
  this.counters.l2Hits++;
7410
8214
  l2HitCount++;
7411
- result[idx] = this._prepareReadValue(parsed);
8215
+ result[idx] = this._prepareReadValue(entry.value);
7412
8216
  missIndexes[j] = -1;
7413
8217
  missKeys[j] = "";
7414
8218
  }
7415
8219
  }
7416
8220
  const remainingIdx = missIndexes.filter((i) => i >= 0);
7417
- const remainingKeys = missKeys.filter((k) => k !== "");
8221
+ const remainingKeys = missKeys.filter((_key, index) => missIndexes[index] >= 0);
7418
8222
  missIndexes.length = 0;
7419
8223
  missKeys.length = 0;
7420
8224
  missIndexes.push(...remainingIdx);
@@ -7427,62 +8231,64 @@ var CacheService = class _CacheService {
7427
8231
  if (!this._diskDisabled && missKeys.length > 0) {
7428
8232
  for (let j = missKeys.length - 1; j >= 0; j--) {
7429
8233
  const k = this.nk(missKeys[j]);
7430
- if (this._pendingDiskDeletes.has(k)) continue;
7431
- if (this._isTombstonedByPattern(k)) {
7432
- try {
7433
- this.disk.delete(k);
7434
- } catch {
7435
- }
7436
- continue;
7437
- }
7438
- if (!this.watchdog.isDiskAllowed()) continue;
7439
- const diskStart = performance.now();
7440
- const diskHit = this.disk.load(k);
7441
- const diskElapsed = performance.now() - diskStart;
7442
- this.watchdog.recordDisk(diskElapsed);
7443
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
7444
- if (diskHit !== null) {
7445
- if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
7446
- this.disk.delete(k);
7447
- continue;
7448
- }
7449
- const promoted = this.l1.importEntries(
7450
- [{ key: k, entry: diskHit }],
7451
- this.opts.forbiddenSnapshotPrefixes
7452
- );
7453
- if (promoted > 0) {
7454
- const l1Check = this.l1.get(k);
7455
- if (l1Check !== null) {
7456
- this.counters.diskHits++;
7457
- result[missIndexes[j]] = this._prepareReadValue(l1Check.value);
7458
- missIndexes.splice(j, 1);
7459
- missKeys.splice(j, 1);
7460
- }
7461
- }
8234
+ const diskHit = await this._readDiskEntry(k, epochs.get(k));
8235
+ if (diskHit && (diskHit.entry.staleAt === void 0 || diskHit.entry.staleAt > Date.now())) {
8236
+ this.counters.diskHits++;
8237
+ result[missIndexes[j]] = this._prepareReadValue(diskHit.value);
8238
+ missIndexes.splice(j, 1);
8239
+ missKeys.splice(j, 1);
7462
8240
  }
7463
8241
  }
7464
8242
  }
7465
8243
  if (missKeys.length > 0 && fetchFn) {
7466
- this.counters.fetches++;
7467
- const fetched = await fetchFn(missKeys);
7468
- const isMap = fetched instanceof Map;
7469
- const setPromises = [];
8244
+ const owned = /* @__PURE__ */ new Map();
8245
+ const waiting = [];
7470
8246
  for (let j = 0; j < missKeys.length; j++) {
7471
- const k = missKeys[j];
7472
- const v = isMap ? fetched.get(k) : fetched[k];
7473
- result[missIndexes[j]] = v;
7474
- if (v !== void 0 && v !== null) {
7475
- const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
7476
- setPromises.push(this.set(k, v, resolvedTtl, priority));
7477
- } else if (v == null && this.opts.notFoundTtl > 0) {
7478
- setPromises.push(this.set(k, null, this.opts.notFoundTtl, priority));
7479
- } else if (v === null) {
7480
- const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
7481
- setPromises.push(this.set(k, null, resolvedTtl, priority));
8247
+ const key = missKeys[j];
8248
+ const namespaced = this.nk(key);
8249
+ let promise = this.inflight.get(namespaced);
8250
+ if (!promise) {
8251
+ let resolve;
8252
+ let reject;
8253
+ promise = new Promise((yes, no) => {
8254
+ resolve = yes;
8255
+ reject = no;
8256
+ });
8257
+ owned.set(key, { promise, resolve, reject });
8258
+ this.inflight.set(namespaced, promise);
8259
+ } else {
8260
+ this.counters.stampedes++;
7482
8261
  }
8262
+ const index = missIndexes[j];
8263
+ waiting.push(promise.then((value) => {
8264
+ result[index] = this._prepareReadValue(value);
8265
+ }));
7483
8266
  }
7484
- if (setPromises.length > 0) {
7485
- await Promise.all(setPromises);
8267
+ const settled = Promise.allSettled(waiting);
8268
+ try {
8269
+ if (owned.size > 0) {
8270
+ this.counters.fetches++;
8271
+ const fetched = await fetchFn([...owned.keys()]);
8272
+ await Promise.all([...owned].map(async ([key, entry]) => {
8273
+ const value = fetched instanceof Map ? fetched.get(key) : Object.hasOwn(fetched, key) ? fetched[key] : void 0;
8274
+ if (!this._destroyed && this._getKeyMutationEpoch(this.nk(key)) === epochs.get(this.nk(key))) {
8275
+ const resolvedTtl = value == null && this.opts.notFoundTtl > 0 ? this.opts.notFoundTtl : typeof ttl === "function" ? ttl(key) : ttl;
8276
+ if (value !== void 0 || this.opts.notFoundTtl > 0) await this.set(key, value === void 0 && this.opts.notFoundTtl > 0 ? null : value, resolvedTtl, priority);
8277
+ }
8278
+ entry.resolve(value);
8279
+ }));
8280
+ }
8281
+ const outcomes = await settled;
8282
+ const failed = outcomes.find((outcome) => outcome.status === "rejected");
8283
+ if (failed?.status === "rejected") throw failed.reason;
8284
+ } catch (error) {
8285
+ for (const entry of owned.values()) entry.reject(error);
8286
+ throw error;
8287
+ } finally {
8288
+ for (const [key, entry] of owned) {
8289
+ const namespaced = this.nk(key);
8290
+ if (this.inflight.get(namespaced) === entry.promise) this.inflight.delete(namespaced);
8291
+ }
7486
8292
  }
7487
8293
  }
7488
8294
  if (this.opts.tracer) {
@@ -7535,7 +8341,7 @@ var CacheService = class _CacheService {
7535
8341
  try {
7536
8342
  await Promise.all(keys.map((key) => {
7537
8343
  const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
7538
- const hasOpts = tags?.length || dependsOn?.length;
8344
+ const hasOpts = tags !== void 0 || dependsOn !== void 0;
7539
8345
  return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
7540
8346
  }));
7541
8347
  } catch (err) {
@@ -7587,26 +8393,21 @@ var CacheService = class _CacheService {
7587
8393
  try {
7588
8394
  const client = await this.getRedis();
7589
8395
  const nsPattern = this.nk(pattern);
7590
- const matchedKeys = await this._scanKeys(client, nsPattern);
8396
+ const matchedKeys = (await this._scanKeys(client, nsPattern)).filter((key) => {
8397
+ const raw = this.unnk(key);
8398
+ return !raw.startsWith("_tag_:") && !raw.startsWith("tag_ver:") && !raw.startsWith("lock:") && key !== this.backplaneStreamKey;
8399
+ });
7591
8400
  if (matchedKeys.length === 0) {
7592
8401
  this.cb.onSuccess();
7593
8402
  return 0;
7594
8403
  }
7595
- const pl = client.pipeline();
7596
- for (const k of matchedKeys) pl.get(k);
7597
- const results = await pl.exec();
7598
- this.cb.onSuccess();
8404
+ const epochs = new Map(matchedKeys.map((key) => [key, this._getKeyMutationEpoch(key)]));
8405
+ const results = await this._readRedisBatch(client, matchedKeys);
7599
8406
  let loaded = 0;
7600
- for (let i = 0; i < matchedKeys.length; i++) {
7601
- const [err, raw] = results[i];
7602
- if (err || raw == null) continue;
7603
- try {
7604
- const parsed = await this._decryptAndDeserialize(raw);
7605
- const remainingMs = 10 * 60 * 1e3;
7606
- this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
7607
- loaded++;
7608
- } catch {
7609
- }
8407
+ for (const key of matchedKeys) {
8408
+ const entry = results.get(key);
8409
+ if (!entry || this._destroyed || this._getKeyMutationEpoch(key) !== epochs.get(key)) continue;
8410
+ if (this._promoteRedisEntry(key, entry, 10 * 60 * 1e3, opts?.priority ?? inferPriority(this.unnk(key))) && this.l1.has(key)) loaded++;
7610
8411
  }
7611
8412
  this.logger.info("warmFromL2 complete", {
7612
8413
  pattern,
@@ -7693,14 +8494,7 @@ var CacheService = class _CacheService {
7693
8494
  this._bumpKeyMutation(k);
7694
8495
  this._removeKeyTags(k);
7695
8496
  this._removeKeyDependencies(k);
7696
- this._pendingDiskDeletes.add(k);
7697
- setImmediate(() => {
7698
- try {
7699
- if (!this._diskDisabled) this.disk.delete(k);
7700
- } finally {
7701
- this._pendingDiskDeletes.delete(k);
7702
- }
7703
- });
8497
+ this._invalidateDiskKey(k);
7704
8498
  }
7705
8499
  }
7706
8500
  /**
@@ -7708,9 +8502,10 @@ var CacheService = class _CacheService {
7708
8502
  * wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
7709
8503
  */
7710
8504
  async _invalidateConcreteTag(tag) {
8505
+ this._fenceInvalidation();
7711
8506
  if (this.opts.tagStrategy === "generational") {
7712
8507
  let newVer = 1;
7713
- if (!this._redisDisabled) {
8508
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7714
8509
  try {
7715
8510
  const client = await this.getRedis();
7716
8511
  newVer = await client.incr(this.nk(`tag_ver:${tag}`));
@@ -7728,19 +8523,23 @@ var CacheService = class _CacheService {
7728
8523
  return;
7729
8524
  }
7730
8525
  const tagKey = this.nk(`_tag_:${tag}`);
7731
- const members = Array.from(this.tagIndex.get(tagKey) ?? []);
8526
+ const members = new Set(this.tagIndex.get(tagKey) ?? []);
7732
8527
  this.tagIndex.delete(tagKey);
7733
8528
  this._removeTagMembersLocal(members);
7734
- if (!this._redisDisabled) {
8529
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7735
8530
  try {
7736
8531
  const client = await this.getRedis();
7737
8532
  const redisMembers = await client.smembers(tagKey);
8533
+ for (const key of redisMembers) members.add(key);
8534
+ this._removeTagMembersLocal(redisMembers);
7738
8535
  const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers, tagKey])];
7739
8536
  await this._deleteRedisKeys(client, toDelete);
7740
8537
  } catch (err) {
7741
8538
  this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7742
8539
  }
7743
8540
  }
8541
+ await Promise.all([...members].map((key) => this._publishTagInvalidation("del", key)));
8542
+ await this._publishTagInvalidation("tag_pattern_del", tag);
7744
8543
  }
7745
8544
  /**
7746
8545
  * Executes invalidation for an array of already-resolved concrete tags
@@ -7752,9 +8551,10 @@ var CacheService = class _CacheService {
7752
8551
  await this._invalidateConcreteTag(tags[0]);
7753
8552
  return;
7754
8553
  }
8554
+ this._fenceInvalidation();
7755
8555
  if (this.opts.tagStrategy === "generational") {
7756
8556
  const now = performance.now();
7757
- if (!this._redisDisabled) {
8557
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7758
8558
  try {
7759
8559
  const client = await this.getRedis();
7760
8560
  const pl = client.pipeline();
@@ -7788,7 +8588,7 @@ var CacheService = class _CacheService {
7788
8588
  this.tagIndex.delete(tagKey);
7789
8589
  }
7790
8590
  this._removeTagMembersLocal(allMembers);
7791
- if (!this._redisDisabled) {
8591
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7792
8592
  try {
7793
8593
  const client = await this.getRedis();
7794
8594
  const pl = client.pipeline();
@@ -7799,15 +8599,19 @@ var CacheService = class _CacheService {
7799
8599
  if (!err && redisMembers) {
7800
8600
  for (const k of redisMembers) {
7801
8601
  if (!allMembers.has(k)) toDelete.push(k);
8602
+ allMembers.add(k);
7802
8603
  }
7803
8604
  }
7804
8605
  }
7805
8606
  const keysToRemove = [...toDelete, ...tagKeys];
7806
8607
  await this._deleteRedisKeys(client, keysToRemove);
8608
+ this._removeTagMembersLocal(allMembers);
7807
8609
  } catch (err) {
7808
8610
  this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7809
8611
  }
7810
8612
  }
8613
+ await Promise.all([...allMembers].map((key) => this._publishTagInvalidation("del", key)));
8614
+ for (const tag of tags) await this._publishTagInvalidation("tag_pattern_del", tag);
7811
8615
  }
7812
8616
  /**
7813
8617
  * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
@@ -7961,19 +8765,23 @@ var CacheService = class _CacheService {
7961
8765
  const diskLowSpace = !this._diskDisabled && this.disk.hostVolumeLowSpace;
7962
8766
  const circuitOpen = this.cb.isOpen;
7963
8767
  const latencyBypass = watchdogTel.bypassActive;
7964
- const degraded = circuitOpen || latencyBypass || diskPruning || diskLowSpace;
7965
- const healthy = this.opts.failReadinessOnDegraded ? !degraded : true;
8768
+ const backplaneUnavailable = this.opts.invalidationBackplane && !this._redisDisabled && !this._backplaneAvailable;
8769
+ const degraded = this._destroyed || circuitOpen || latencyBypass || diskPruning || diskLowSpace || backplaneUnavailable;
8770
+ const healthy = !this._destroyed && (this.opts.failReadinessOnDegraded ? !degraded : true);
7966
8771
  const reasons = [];
7967
8772
  if (circuitOpen) reasons.push("redis_circuit_breaker_open");
7968
8773
  if (latencyBypass) reasons.push(`disk_latency_bypass_stage_${watchdogTel.bypassStage}`);
7969
8774
  if (diskPruning) reasons.push("disk_quota_watermark_pruning_active");
7970
8775
  if (diskLowSpace) reasons.push("disk_host_volume_low_space");
8776
+ if (backplaneUnavailable) reasons.push("invalidation_backplane_unavailable");
8777
+ if (this._destroyed) reasons.push("cache_destroyed");
7971
8778
  return {
7972
8779
  healthy,
7973
8780
  degraded,
7974
8781
  reasons,
7975
8782
  details: {
7976
- redisConnected: !circuitOpen && !this._redisDisabled,
8783
+ redisConnected: !this._destroyed && !circuitOpen && !!this.redis && (this.redis.status === "ready" || this.redis.isOpen === true),
8784
+ backplaneReady: this._backplaneAvailable,
7977
8785
  circuitBreakerState: this.cb.currentState,
7978
8786
  diskPruningActive: diskPruning,
7979
8787
  diskHostVolumeLowSpace: diskLowSpace,
@@ -7995,23 +8803,28 @@ var CacheService = class _CacheService {
7995
8803
  */
7996
8804
  async drainToL2() {
7997
8805
  this._assertActive("drainToL2");
7998
- if (this._redisDisabled) return 0;
8806
+ if (this._redisDisabled || this.opts.l2WriteMode === "read-only") return 0;
7999
8807
  try {
8000
- const client = await this.getRedis();
8001
8808
  const entries = this.l1.exportEntries([]);
8002
- const now = Date.now();
8003
8809
  if (entries.length === 0) return 0;
8004
- const pl = client.pipeline();
8005
- for (const { key, entry } of entries) {
8006
- const remainingMs = entry.expiresAt - now;
8007
- if (remainingMs <= 0) continue;
8008
- const ttlSecs = Math.max(1, Math.ceil(remainingMs / 1e3));
8009
- const s = JSON.stringify(entry.value);
8010
- const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
8011
- pl.setex(key, ttlSecs, stored);
8012
- }
8013
- await pl.exec();
8014
- return entries.length;
8810
+ let written = 0;
8811
+ await Promise.all(entries.map(async ({ key, entry }) => {
8812
+ const epoch = this._getKeyMutationEpoch(key);
8813
+ if (entry.expiresAt <= Date.now()) return;
8814
+ await this._writeRedisEntry(
8815
+ key,
8816
+ this.l1.resolveValue(entry),
8817
+ entry.expiresAt,
8818
+ entry.setAt ?? Date.now(),
8819
+ entry.tagVersions,
8820
+ entry.staleAt,
8821
+ entry.tags,
8822
+ entry.dependsOn,
8823
+ () => this._getKeyMutationEpoch(key) === epoch
8824
+ );
8825
+ written++;
8826
+ }));
8827
+ return written;
8015
8828
  } catch (err) {
8016
8829
  this.logger.debug("drainToL2: Redis unavailable", { error: err.message });
8017
8830
  return 0;
@@ -8041,7 +8854,7 @@ var CacheService = class _CacheService {
8041
8854
  this._assertActive("setIfAbsent");
8042
8855
  const k = this.nk(cacheKey);
8043
8856
  if (this.l1.has(k)) return false;
8044
- if (!this._redisDisabled) {
8857
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
8045
8858
  try {
8046
8859
  const client = await this.getRedis();
8047
8860
  const serialized = JSON.stringify(value);
@@ -8058,7 +8871,7 @@ var CacheService = class _CacheService {
8058
8871
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
8059
8872
  const p = priority ?? inferPriority(cacheKey);
8060
8873
  this._bumpKeyMutation(k);
8061
- this._pendingDiskDeletes.delete(k);
8874
+ this._invalidateDiskKey(k);
8062
8875
  this.l1.set(k, value, ttlMs, p);
8063
8876
  this.counters.sets++;
8064
8877
  return true;
@@ -8085,7 +8898,7 @@ var CacheService = class _CacheService {
8085
8898
  const token = import_crypto3.default.randomUUID();
8086
8899
  const deadline = Date.now() + acquireTimeout;
8087
8900
  let acquired = false;
8088
- if (!this._redisDisabled) {
8901
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
8089
8902
  let client = null;
8090
8903
  try {
8091
8904
  client = await this.getRedis();
@@ -8180,7 +8993,9 @@ var CacheService = class _CacheService {
8180
8993
  const gDiskFiles = meter.createObservableGauge("tricache.disk.files", { description: "Current L1.5 disk file count" });
8181
8994
  const gDiskBytes = meter.createObservableGauge("tricache.disk.bytes", { description: "Current L1.5 disk size in bytes" });
8182
8995
  const gBloomFpr = meter.createObservableGauge("tricache.bloom.fpr", { description: "Bloom filter false-positive rate" });
8183
- meter.addBatchObservableCallback((observableResult) => {
8996
+ const observables = [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr];
8997
+ const callback = (observableResult) => {
8998
+ if (this._destroyed) return;
8184
8999
  const stats = this.stats();
8185
9000
  const l1 = stats.l1;
8186
9001
  const disk = stats.disk;
@@ -8193,7 +9008,9 @@ var CacheService = class _CacheService {
8193
9008
  observableResult.observe(gDiskFiles, disk.files, attrs);
8194
9009
  observableResult.observe(gDiskBytes, disk.sizeKB * 1024, attrs);
8195
9010
  observableResult.observe(gBloomFpr, fpr, attrs);
8196
- }, [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr]);
9011
+ };
9012
+ meter.addBatchObservableCallback(callback, observables);
9013
+ this._otelCleanup = () => meter.removeBatchObservableCallback?.(callback, observables);
8197
9014
  } catch (err) {
8198
9015
  this.logger.warn("Failed to initialize OpenTelemetry metrics meter", { error: err.message });
8199
9016
  }
@@ -8463,6 +9280,16 @@ var CacheService = class _CacheService {
8463
9280
  /** Close Redis connections and stop all background timers. */
8464
9281
  async destroy() {
8465
9282
  this._destroyed = true;
9283
+ this._fenceInvalidation();
9284
+ this._backplaneAvailable = false;
9285
+ this.l1.clear();
9286
+ try {
9287
+ this._otelCleanup?.();
9288
+ } catch {
9289
+ }
9290
+ this._otelCleanup = null;
9291
+ this.tagVersions.clear();
9292
+ for (const dispose of this._backplaneDisposers.splice(0)) dispose();
8466
9293
  this._pendingDiskDeletes.clear();
8467
9294
  this._keyMutationEpochs.clear();
8468
9295
  this.inflight.clear();
@@ -8492,6 +9319,12 @@ var CacheService = class _CacheService {
8492
9319
  this._workerPool = null;
8493
9320
  }
8494
9321
  if (this.subClient) {
9322
+ if (this.opts.redisSubClient) {
9323
+ try {
9324
+ await this.subClient.unsubscribe?.(this.backplaneChannel);
9325
+ } catch {
9326
+ }
9327
+ }
8495
9328
  if (!this.opts.redisSubClient) {
8496
9329
  try {
8497
9330
  this.subClient.disconnect();
@@ -8501,7 +9334,7 @@ var CacheService = class _CacheService {
8501
9334
  this.subClient = null;
8502
9335
  }
8503
9336
  if (this.streamClient) {
8504
- try {
9337
+ if (!this.opts.redisSubClient) try {
8505
9338
  this.streamClient.disconnect();
8506
9339
  } catch {
8507
9340
  }
@@ -8769,193 +9602,118 @@ function createMemorySnapshotAdapter() {
8769
9602
  };
8770
9603
  }
8771
9604
 
8772
- // src/cross-region.ts
8773
- function createHttpMeshRelay(options) {
8774
- const peerUrls = options.peerUrls;
8775
- const timeoutMs = options.timeoutMs ?? 3e3;
8776
- const fetcher = options.fetchFn ?? globalThis.fetch;
8777
- const headers = {
8778
- "Content-Type": "application/json"
8779
- };
8780
- if (options.authSecret) {
8781
- headers["Authorization"] = `Bearer ${options.authSecret}`;
8782
- headers["X-TriCache-Auth"] = options.authSecret;
8783
- }
8784
- return {
8785
- async broadcast(event) {
8786
- if (!peerUrls.length) return;
8787
- const body = JSON.stringify(event);
8788
- await Promise.allSettled(
8789
- peerUrls.map(async (url) => {
8790
- const res = await fetcher(url, {
8791
- method: "POST",
8792
- headers,
8793
- body,
8794
- signal: AbortSignal.timeout(timeoutMs)
8795
- });
8796
- if (!res.ok) {
8797
- throw new Error(`HttpMeshRelay: peer ${url} returned HTTP ${res.status} ${res.statusText}`);
8798
- }
8799
- })
8800
- );
8801
- }
8802
- };
8803
- }
8804
- function createCustomCrossRegionRelay(relay) {
8805
- return relay;
8806
- }
8807
- function createMemoryCrossRegionRelay() {
8808
- const handlers = /* @__PURE__ */ new Map();
8809
- let broadcastCount = 0;
8810
- return {
8811
- async broadcast(event) {
8812
- broadcastCount++;
8813
- const promises = [];
8814
- for (const [region, set] of handlers.entries()) {
8815
- if (region !== event.originRegion) {
8816
- for (const fn of set) {
8817
- promises.push(Promise.resolve(fn(event)));
8818
- }
8819
- }
8820
- }
8821
- await Promise.allSettled(promises);
8822
- },
8823
- register(region, handler) {
8824
- if (!handlers.has(region)) {
8825
- handlers.set(region, /* @__PURE__ */ new Set());
8826
- }
8827
- handlers.get(region).add(handler);
8828
- return () => {
8829
- handlers.get(region)?.delete(handler);
9605
+ // src/adapters/node-redis.ts
9606
+ var import_node_events = require("events");
9607
+ var NodeRedisPipelineAdapter = class {
9608
+ constructor(multiInstance, transactional = true) {
9609
+ this.transactional = transactional;
9610
+ this.multiInstance = multiInstance;
9611
+ if (typeof multiInstance.pTTL === "function" || typeof multiInstance.pttl === "function") {
9612
+ this.pttl = (key) => {
9613
+ this.queueCommand(typeof multiInstance.pTTL === "function" ? "pTTL" : "pttl", [key]);
9614
+ return this;
8830
9615
  };
8831
- },
8832
- getBroadcastCount() {
8833
- return broadcastCount;
8834
- },
8835
- clear() {
8836
- handlers.clear();
8837
- broadcastCount = 0;
8838
- }
8839
- };
8840
- }
8841
- function createCrossRegionWebhookHandler(cache, options = {}) {
8842
- return async function handleCrossRegionWebhook(req) {
8843
- if (options.authSecret) {
8844
- const authHeader = req.headers["authorization"] ?? req.headers["Authorization"];
8845
- const customHeader = req.headers["x-tricache-auth"] ?? req.headers["X-TriCache-Auth"];
8846
- const bearer = typeof authHeader === "string" && authHeader.startsWith("Bearer ") ? authHeader.slice(7).trim() : authHeader;
8847
- const provided = typeof customHeader === "string" ? customHeader : bearer;
8848
- if (!provided || provided !== options.authSecret) {
8849
- return {
8850
- status: 401,
8851
- body: { ok: false, message: "Unauthorized: invalid or missing auth secret" }
8852
- };
8853
- }
8854
9616
  }
8855
- try {
8856
- let event;
8857
- if (typeof req.body === "string") {
8858
- event = JSON.parse(req.body);
8859
- } else if (req.body && typeof req.body === "object") {
8860
- event = req.body;
8861
- } else {
8862
- return {
8863
- status: 400,
8864
- body: { ok: false, message: "Invalid payload: body must be JSON object" }
8865
- };
8866
- }
8867
- const accepted = await cache.receiveCrossRegionInvalidation(event);
8868
- return {
8869
- status: 200,
8870
- body: { ok: true, message: accepted ? "Invalidation applied" : "Invalidation ignored (deduplicated or self)" }
8871
- };
8872
- } catch (err) {
8873
- return {
8874
- status: 400,
8875
- body: { ok: false, message: err.message }
9617
+ if (typeof multiInstance.eval === "function" || typeof multiInstance.addCommand === "function") {
9618
+ this.eval = (script, numkeys, ...args) => {
9619
+ if (typeof multiInstance.eval === "function") {
9620
+ this.queueCommand("eval", [script, { keys: args.slice(0, numkeys).map(String), arguments: args.slice(numkeys).map(String) }]);
9621
+ } else this.queueCommand("addCommand", [["EVAL", script, String(numkeys), ...args.map(String)]]);
9622
+ return this;
8876
9623
  };
8877
9624
  }
8878
- };
8879
- }
8880
-
8881
- // src/adapters/node-redis.ts
8882
- var import_node_events = require("events");
8883
- var NodeRedisPipelineAdapter = class {
9625
+ }
9626
+ transactional;
8884
9627
  multiInstance;
8885
- constructor(multiInstance) {
8886
- this.multiInstance = multiInstance;
9628
+ operations = [];
9629
+ pttl;
9630
+ eval;
9631
+ queueCommand(method, args) {
9632
+ if (this.transactional) this.multiInstance[method](...args);
9633
+ else this.operations.push(() => this.multiInstance[method](...args));
8887
9634
  }
8888
9635
  get(key) {
8889
- this.multiInstance.get(key);
9636
+ this.queueCommand("get", [key]);
8890
9637
  return this;
8891
9638
  }
8892
9639
  set(key, value, ...args) {
8893
9640
  const opts = parseSetArgs(args);
8894
9641
  if (opts) {
8895
- this.multiInstance.set(key, value, opts);
9642
+ this.queueCommand("set", [key, value, opts]);
8896
9643
  } else {
8897
- this.multiInstance.set(key, value);
9644
+ this.queueCommand("set", [key, value]);
8898
9645
  }
8899
9646
  return this;
8900
9647
  }
8901
9648
  setex(key, seconds, value) {
8902
9649
  if (typeof this.multiInstance.setEx === "function") {
8903
- this.multiInstance.setEx(key, seconds, value);
9650
+ this.queueCommand("setEx", [key, seconds, value]);
8904
9651
  } else if (typeof this.multiInstance.setex === "function") {
8905
- this.multiInstance.setex(key, seconds, value);
9652
+ this.queueCommand("setex", [key, seconds, value]);
8906
9653
  } else {
8907
- this.multiInstance.set(key, value, { EX: seconds });
9654
+ this.queueCommand("set", [key, value, { EX: seconds }]);
8908
9655
  }
8909
9656
  return this;
8910
9657
  }
8911
9658
  del(...keys) {
8912
9659
  if (keys.length === 0) return this;
8913
- this.multiInstance.del(keys.length === 1 ? keys[0] : keys);
9660
+ this.queueCommand("del", [keys.length === 1 ? keys[0] : keys]);
8914
9661
  return this;
8915
9662
  }
8916
9663
  expire(key, seconds) {
8917
- this.multiInstance.expire(key, seconds);
9664
+ this.queueCommand("expire", [key, seconds]);
8918
9665
  return this;
8919
9666
  }
8920
9667
  incr(key) {
8921
- this.multiInstance.incr(key);
9668
+ this.queueCommand("incr", [key]);
8922
9669
  return this;
8923
9670
  }
8924
9671
  sadd(key, ...members) {
8925
9672
  if (members.length === 0) return this;
8926
9673
  if (typeof this.multiInstance.sAdd === "function") {
8927
- this.multiInstance.sAdd(key, members.length === 1 ? members[0] : members);
9674
+ this.queueCommand("sAdd", [key, members.length === 1 ? members[0] : members]);
8928
9675
  } else {
8929
- this.multiInstance.sadd(key, ...members);
9676
+ this.queueCommand("sadd", [key, ...members]);
8930
9677
  }
8931
9678
  return this;
8932
9679
  }
8933
9680
  smembers(key) {
8934
9681
  if (typeof this.multiInstance.sMembers === "function") {
8935
- this.multiInstance.sMembers(key);
9682
+ this.queueCommand("sMembers", [key]);
8936
9683
  } else {
8937
- this.multiInstance.smembers(key);
9684
+ this.queueCommand("smembers", [key]);
8938
9685
  }
8939
9686
  return this;
8940
9687
  }
8941
9688
  hset(key, value) {
8942
9689
  if (typeof this.multiInstance.hSet === "function") {
8943
- this.multiInstance.hSet(key, value);
9690
+ this.queueCommand("hSet", [key, value]);
8944
9691
  } else {
8945
- this.multiInstance.hset(key, value);
9692
+ this.queueCommand("hset", [key, value]);
8946
9693
  }
8947
9694
  return this;
8948
9695
  }
8949
9696
  hgetall(key) {
8950
9697
  if (typeof this.multiInstance.hGetAll === "function") {
8951
- this.multiInstance.hGetAll(key);
9698
+ this.queueCommand("hGetAll", [key]);
8952
9699
  } else {
8953
- this.multiInstance.hgetall(key);
9700
+ this.queueCommand("hgetall", [key]);
8954
9701
  }
8955
9702
  return this;
8956
9703
  }
8957
9704
  async exec() {
8958
- const raw = await this.multiInstance.exec();
9705
+ let raw;
9706
+ if (!this.transactional) {
9707
+ const results = await Promise.allSettled(this.operations.splice(0).map((operation) => Promise.resolve().then(operation)));
9708
+ return results.map((result) => result.status === "fulfilled" ? [null, result.value] : [result.reason instanceof Error ? result.reason : new Error(String(result.reason)), null]);
9709
+ }
9710
+ try {
9711
+ raw = await this.multiInstance.exec();
9712
+ } catch (error) {
9713
+ const replies = error.replies;
9714
+ if (!Array.isArray(replies)) throw error;
9715
+ raw = replies;
9716
+ }
8959
9717
  if (!raw) return null;
8960
9718
  return raw.map((item) => {
8961
9719
  if (item instanceof Error) {
@@ -8965,20 +9723,32 @@ var NodeRedisPipelineAdapter = class {
8965
9723
  });
8966
9724
  }
8967
9725
  };
8968
- var NodeRedisAdapter = class _NodeRedisAdapter {
9726
+ var NodeRedisAdapter = class _NodeRedisAdapter extends import_node_events.EventEmitter {
8969
9727
  client;
9728
+ connecting = null;
9729
+ pttl;
8970
9730
  constructor(client) {
9731
+ super();
8971
9732
  if (!client) {
8972
9733
  throw new Error("NodeRedisAdapter requires an active @redis/client instance");
8973
9734
  }
8974
9735
  this.client = client;
9736
+ if (typeof client.pTTL === "function" || typeof client.pttl === "function") {
9737
+ this.pttl = (key) => (client.pTTL ?? client.pttl).call(client, key);
9738
+ }
8975
9739
  }
8976
9740
  get isOpen() {
8977
9741
  return this.client.isOpen !== false;
8978
9742
  }
8979
9743
  async connect() {
9744
+ if (this.connecting) return this.connecting;
8980
9745
  if (typeof this.client.connect === "function" && !this.client.isOpen) {
8981
- return await this.client.connect();
9746
+ this.connecting = Promise.resolve(this.client.connect());
9747
+ try {
9748
+ return await this.connecting;
9749
+ } finally {
9750
+ this.connecting = null;
9751
+ }
8982
9752
  }
8983
9753
  return void 0;
8984
9754
  }
@@ -9055,7 +9825,7 @@ var NodeRedisAdapter = class _NodeRedisAdapter {
9055
9825
  return new NodeRedisPipelineAdapter(multiInstance);
9056
9826
  }
9057
9827
  pipeline() {
9058
- return this.multi();
9828
+ return new NodeRedisPipelineAdapter(this.client, false);
9059
9829
  }
9060
9830
  async smembers(key) {
9061
9831
  if (typeof this.client.sMembers === "function") {
@@ -9109,7 +9879,29 @@ var NodeRedisAdapter = class _NodeRedisAdapter {
9109
9879
  }
9110
9880
  async subscribe(...channels) {
9111
9881
  if (channels.length === 0) return void 0;
9112
- return await this.client.subscribe(channels);
9882
+ await this.connect();
9883
+ return await this.client.subscribe(channels, (message, channel) => this.emit("message", channel, message));
9884
+ }
9885
+ async unsubscribe(...channels) {
9886
+ if (!channels.length || !this.isOpen) return void 0;
9887
+ return this.client.unsubscribe(channels);
9888
+ }
9889
+ async xread(...args) {
9890
+ await this.connect();
9891
+ const raw = await this.client.sendCommand(["XREAD", ...args.map(String)]);
9892
+ if (raw == null) return null;
9893
+ if (raw instanceof Map) return [...raw.entries()];
9894
+ if (!Array.isArray(raw) && typeof raw === "object") return Object.entries(raw);
9895
+ return raw;
9896
+ }
9897
+ async xadd(...args) {
9898
+ return this.client.sendCommand(["XADD", ...args.map(String)]);
9899
+ }
9900
+ async xrange(...args) {
9901
+ return this.client.sendCommand(["XRANGE", ...args.map(String)]);
9902
+ }
9903
+ async xrevrange(...args) {
9904
+ return this.client.sendCommand(["XREVRANGE", ...args.map(String)]);
9113
9905
  }
9114
9906
  scanStream(options) {
9115
9907
  const ee = new import_node_events.EventEmitter();
@@ -9119,8 +9911,8 @@ var NodeRedisAdapter = class _NodeRedisAdapter {
9119
9911
  try {
9120
9912
  if (typeof this.client.scanIterator === "function") {
9121
9913
  const batch = [];
9122
- for await (const key of this.client.scanIterator({ MATCH: pattern, COUNT: count })) {
9123
- batch.push(key);
9914
+ for await (const keys of this.client.scanIterator({ MATCH: pattern, COUNT: count })) {
9915
+ batch.push(...Array.isArray(keys) ? keys : [keys]);
9124
9916
  if (batch.length >= count) {
9125
9917
  ee.emit("data", [...batch]);
9126
9918
  batch.length = 0;
@@ -9164,17 +9956,24 @@ var NodeRedisAdapter = class _NodeRedisAdapter {
9164
9956
  return this;
9165
9957
  }
9166
9958
  on(event, listener) {
9959
+ if (event === "message" || event === "smessage") return super.on(event, listener);
9167
9960
  if (typeof this.client.on === "function") {
9168
- this.client.on(event, listener);
9961
+ this.client.on(event === "close" ? "end" : event, listener);
9169
9962
  }
9170
9963
  return this;
9171
9964
  }
9172
9965
  once(event, listener) {
9966
+ if (event === "message" || event === "smessage") return super.once(event, listener);
9173
9967
  if (typeof this.client.once === "function") {
9174
- this.client.once(event, listener);
9968
+ this.client.once(event === "close" ? "end" : event, listener);
9175
9969
  }
9176
9970
  return this;
9177
9971
  }
9972
+ removeListener(event, listener) {
9973
+ super.removeListener(event, listener);
9974
+ this.client.removeListener?.(event === "close" ? "end" : event, listener);
9975
+ return this;
9976
+ }
9178
9977
  };
9179
9978
  function createNodeRedisAdapter(client) {
9180
9979
  if (client instanceof NodeRedisAdapter) return client;
@@ -9362,7 +10161,7 @@ function formatTraceParent(traceId, spanId, traceFlags = 1) {
9362
10161
  var import_node_http = __toESM(require("http"), 1);
9363
10162
 
9364
10163
  // src/dashboard/handler.ts
9365
- var import_node_crypto = require("crypto");
10164
+ var import_node_crypto2 = require("crypto");
9366
10165
  var import_node_os = __toESM(require("os"), 1);
9367
10166
 
9368
10167
  // src/dashboard/html.ts
@@ -9647,7 +10446,7 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
9647
10446
  <span class="pulse-dot"></span>
9648
10447
  <span id="stream-text">SSE Live</span>
9649
10448
  </div>
9650
- <select id="peer-select" class="peer-select" style="display:none;" onchange="if(this.value) window.location.href=this.value;">
10449
+ <select id="peer-select" aria-label="Switch cache instance" class="peer-select" style="display:none;" onchange="if(this.value) window.location.href=this.value;">
9651
10450
  <option value="">Switch Pod...</option>
9652
10451
  </select>
9653
10452
  </div>
@@ -9707,9 +10506,10 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
9707
10506
 
9708
10507
  <!-- Invalidate Modal -->
9709
10508
  <div class="dialog-overlay" id="invalidate-modal">
9710
- <div class="dialog">
9711
- <h3>Invalidate Tag</h3>
10509
+ <div class="dialog" role="dialog" aria-modal="true" aria-labelledby="invalidate-title">
10510
+ <h3 id="invalidate-title">Invalidate Tag</h3>
9712
10511
  <p>Increments generational tag version across local tiers and broadcast backplane.</p>
10512
+ <label for="tag-input">Tag name or pattern</label>
9713
10513
  <input type="text" id="tag-input" placeholder="e.g. products, tenant-123" />
9714
10514
  <div class="dialog-actions">
9715
10515
  <button class="btn" onclick="closeModals()">Cancel</button>
@@ -9720,8 +10520,8 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
9720
10520
 
9721
10521
  <!-- Clear Modal -->
9722
10522
  <div class="dialog-overlay" id="clear-modal">
9723
- <div class="dialog">
9724
- <h3>Clear Cache</h3>
10523
+ <div class="dialog" role="dialog" aria-modal="true" aria-labelledby="clear-title">
10524
+ <h3 id="clear-title">Clear Cache</h3>
9725
10525
  <p>Evict all cached keys from the local L1 memory and NVMe disk tiers.</p>
9726
10526
  <div class="dialog-actions">
9727
10527
  <button class="btn" onclick="closeModals()">Cancel</button>
@@ -9730,12 +10530,20 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
9730
10530
  </div>
9731
10531
  </div>
9732
10532
 
9733
- <div id="toast"></div>
10533
+ <div id="toast" role="status" aria-live="polite"></div>
9734
10534
 
9735
10535
  <script>
9736
10536
  (function() {
9737
10537
  let isReadOnly = false;
9738
10538
  let sseFailed = false;
10539
+ let previousFocus = null;
10540
+ const token = new URLSearchParams(window.location.search).get('token');
10541
+ const basePath = window.location.pathname.replace(/\\/index\\.html$/, '').replace(/\\/+$/, '');
10542
+ function apiURL(path) {
10543
+ const url = new URL(basePath + '/' + path, window.location.origin);
10544
+ if (token) url.searchParams.set('token', token);
10545
+ return url.toString();
10546
+ }
9739
10547
 
9740
10548
  function showToast(msg, duration = 3000) {
9741
10549
  const t = document.getElementById('toast');
@@ -9842,7 +10650,8 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
9842
10650
  }
9843
10651
 
9844
10652
  window.fetchMetricsSnapshot = function() {
9845
- fetch('api/metrics')
10653
+ fetch(apiURL('api/metrics'))
10654
+ .then(r => { if (!r.ok) throw new Error('HTTP ' + r.status); return r; })
9846
10655
  .then(r => r.json())
9847
10656
  .then(data => updateUI(data))
9848
10657
  .catch(err => showToast('Failed to fetch snapshot: ' + err.message));
@@ -9853,7 +10662,7 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
9853
10662
  fallbackPolling();
9854
10663
  return;
9855
10664
  }
9856
- const sse = new EventSource('api/stream');
10665
+ const sse = new EventSource(apiURL('api/stream'));
9857
10666
  sse.onmessage = function(e) {
9858
10667
  try {
9859
10668
  const data = JSON.parse(e.data);
@@ -9878,22 +10687,37 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
9878
10687
 
9879
10688
  window.openInvalidateModal = function() {
9880
10689
  if (isReadOnly) return;
10690
+ previousFocus = document.activeElement;
9881
10691
  document.getElementById('invalidate-modal').classList.add('active');
9882
10692
  document.getElementById('tag-input').focus();
9883
10693
  };
9884
10694
  window.openClearModal = function() {
9885
10695
  if (isReadOnly) return;
10696
+ previousFocus = document.activeElement;
9886
10697
  document.getElementById('clear-modal').classList.add('active');
10698
+ document.querySelector('#clear-modal button').focus();
9887
10699
  };
9888
10700
  window.closeModals = function() {
9889
10701
  document.getElementById('invalidate-modal').classList.remove('active');
9890
10702
  document.getElementById('clear-modal').classList.remove('active');
10703
+ if (previousFocus) previousFocus.focus();
9891
10704
  };
10705
+ document.addEventListener('keydown', function(event) {
10706
+ const modal = document.querySelector('.dialog-overlay.active');
10707
+ if (!modal) return;
10708
+ if (event.key === 'Escape') { event.preventDefault(); closeModals(); }
10709
+ if (event.key === 'Tab') {
10710
+ const controls = modal.querySelectorAll('button, input, select, [tabindex="0"]');
10711
+ const first = controls[0], last = controls[controls.length - 1];
10712
+ if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
10713
+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
10714
+ }
10715
+ });
9892
10716
 
9893
10717
  window.submitTagInvalidation = function() {
9894
10718
  const tag = document.getElementById('tag-input').value.trim();
9895
10719
  if (!tag) return;
9896
- fetch('api/actions/invalidate-tag', {
10720
+ fetch(apiURL('api/actions/invalidate-tag'), {
9897
10721
  method: 'POST',
9898
10722
  headers: {
9899
10723
  'Content-Type': 'application/json',
@@ -9916,7 +10740,7 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
9916
10740
  };
9917
10741
 
9918
10742
  window.submitClear = function() {
9919
- fetch('api/actions/clear', {
10743
+ fetch(apiURL('api/actions/clear'), {
9920
10744
  method: 'POST',
9921
10745
  headers: {
9922
10746
  'Content-Type': 'application/json',
@@ -9948,15 +10772,15 @@ var DASHBOARD_GZIP_BUFFER = (0, import_node_zlib.gzipSync)(Buffer.from(DASHBOARD
9948
10772
  // src/dashboard/handler.ts
9949
10773
  function safeCompare(a, b) {
9950
10774
  if (typeof a !== "string" || typeof b !== "string") return false;
9951
- const hashA = (0, import_node_crypto.createHash)("sha256").update(a).digest();
9952
- const hashB = (0, import_node_crypto.createHash)("sha256").update(b).digest();
9953
- return (0, import_node_crypto.timingSafeEqual)(hashA, hashB);
10775
+ const hashA = (0, import_node_crypto2.createHash)("sha256").update(a).digest();
10776
+ const hashB = (0, import_node_crypto2.createHash)("sha256").update(b).digest();
10777
+ return (0, import_node_crypto2.timingSafeEqual)(hashA, hashB);
9954
10778
  }
9955
10779
  var SECURITY_HEADERS = {
9956
10780
  "Content-Security-Policy": "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'",
9957
10781
  "X-Frame-Options": "DENY",
9958
10782
  "X-Content-Type-Options": "nosniff",
9959
- "Referrer-Policy": "same-origin",
10783
+ "Referrer-Policy": "no-referrer",
9960
10784
  "Cache-Control": "no-store, no-cache, must-revalidate"
9961
10785
  };
9962
10786
  function resolveInstanceId(custom) {
@@ -9975,7 +10799,7 @@ function buildMetricsPayload(options) {
9975
10799
  title: options.title || "TriCache Observability",
9976
10800
  instanceId: resolveInstanceId(options.instanceId),
9977
10801
  nodeVersion: process.version,
9978
- readOnly: !!options.readOnly,
10802
+ readOnly: options.readOnly ?? true,
9979
10803
  peerInstances: options.peerInstances || [],
9980
10804
  metrics: {
9981
10805
  ...metrics,
@@ -10081,6 +10905,7 @@ async function handleDashboardRequest(req, options) {
10081
10905
  }
10082
10906
  ticker = setInterval(() => {
10083
10907
  try {
10908
+ if ((controller.desiredSize ?? 0) <= 0) return;
10084
10909
  const data = buildMetricsPayload(options);
10085
10910
  controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}
10086
10911
 
@@ -10103,7 +10928,7 @@ async function handleDashboardRequest(req, options) {
10103
10928
  controller.close();
10104
10929
  } catch {
10105
10930
  }
10106
- });
10931
+ }, { once: true });
10107
10932
  }
10108
10933
  },
10109
10934
  cancel() {
@@ -10135,7 +10960,7 @@ async function handleDashboardRequest(req, options) {
10135
10960
  }
10136
10961
  if (pathname === "/api/actions/invalidate-tag" && req.method === "POST") {
10137
10962
  const clientIp = req.headers.get("x-forwarded-for") || void 0;
10138
- if (options.readOnly) {
10963
+ if (options.readOnly ?? true) {
10139
10964
  return new Response(JSON.stringify({ ok: false, error: "Dashboard is in read-only mode" }), {
10140
10965
  status: 403,
10141
10966
  headers: { "Content-Type": "application/json" }
@@ -10148,7 +10973,28 @@ async function handleDashboardRequest(req, options) {
10148
10973
  });
10149
10974
  }
10150
10975
  try {
10151
- const body = await req.json();
10976
+ const maxBytes = options.maxRequestBytes ?? 65536;
10977
+ if (Number(req.headers.get("content-length")) > maxBytes) return new Response(JSON.stringify({ error: "Request body too large" }), { status: 413 });
10978
+ const reader = req.body?.getReader();
10979
+ const chunks = [];
10980
+ let bytes = 0;
10981
+ if (reader) {
10982
+ try {
10983
+ while (true) {
10984
+ const chunk = await reader.read();
10985
+ if (chunk.done) break;
10986
+ bytes += chunk.value.length;
10987
+ if (bytes > maxBytes) {
10988
+ await reader.cancel();
10989
+ return new Response(JSON.stringify({ error: "Request body too large" }), { status: 413 });
10990
+ }
10991
+ chunks.push(chunk.value);
10992
+ }
10993
+ } finally {
10994
+ reader.releaseLock();
10995
+ }
10996
+ }
10997
+ const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
10152
10998
  const tag = body?.tag?.trim();
10153
10999
  if (!tag) {
10154
11000
  return new Response(JSON.stringify({ ok: false, error: "Tag parameter is required" }), {
@@ -10187,7 +11033,7 @@ async function handleDashboardRequest(req, options) {
10187
11033
  }
10188
11034
  if (pathname === "/api/actions/clear" && req.method === "POST") {
10189
11035
  const clientIp = req.headers.get("x-forwarded-for") || void 0;
10190
- if (options.readOnly) {
11036
+ if (options.readOnly ?? true) {
10191
11037
  return new Response(JSON.stringify({ ok: false, error: "Dashboard is in read-only mode" }), {
10192
11038
  status: 403,
10193
11039
  headers: { "Content-Type": "application/json" }
@@ -10256,7 +11102,7 @@ async function handleDashboardRequest(req, options) {
10256
11102
  }
10257
11103
 
10258
11104
  // src/dashboard/index.ts
10259
- async function nodeToWebRequest(req) {
11105
+ async function nodeToWebRequest(req, res, maxBytes) {
10260
11106
  const protocol = req.socket.encrypted ? "https" : "http";
10261
11107
  const host = req.headers.host || "localhost";
10262
11108
  const url = new URL(req.url || "/", `${protocol}://${host}`);
@@ -10272,19 +11118,23 @@ async function nodeToWebRequest(req) {
10272
11118
  let body = null;
10273
11119
  if (req.method !== "GET" && req.method !== "HEAD") {
10274
11120
  const chunks = [];
10275
- for await (const chunk of req) {
10276
- chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
11121
+ let size = 0;
11122
+ const parsed = req.body;
11123
+ if (req.readableEnded && parsed !== void 0) chunks.push(Buffer.from(JSON.stringify(parsed)));
11124
+ else for await (const chunk of req) {
11125
+ const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
11126
+ size += bytes.length;
11127
+ if (size > maxBytes) throw Object.assign(new Error("Request body exceeds dashboard limit"), { status: 413 });
11128
+ chunks.push(bytes);
10277
11129
  }
10278
11130
  if (chunks.length > 0) {
10279
11131
  body = Buffer.concat(chunks);
11132
+ if (body.length > maxBytes) throw Object.assign(new Error("Request body exceeds dashboard limit"), { status: 413 });
10280
11133
  }
10281
11134
  }
10282
11135
  const controller = new AbortController();
10283
- req.on("close", () => {
10284
- if (req.destroyed || !req.complete) {
10285
- controller.abort();
10286
- }
10287
- });
11136
+ req.once("aborted", () => controller.abort());
11137
+ res.once("close", () => controller.abort());
10288
11138
  const init = {
10289
11139
  method: req.method,
10290
11140
  headers,
@@ -10306,24 +11156,54 @@ async function pipeWebResponseToNode(webRes, nodeRes) {
10306
11156
  return;
10307
11157
  }
10308
11158
  const reader = webRes.body.getReader();
11159
+ const cancel = () => {
11160
+ void reader.cancel().catch(() => {
11161
+ });
11162
+ };
11163
+ nodeRes.once("close", cancel);
10309
11164
  try {
10310
11165
  while (true) {
10311
11166
  const { done, value } = await reader.read();
10312
11167
  if (done) break;
10313
- nodeRes.write(value);
11168
+ if (nodeRes.destroyed) break;
11169
+ if (!nodeRes.write(value)) await new Promise((resolve, reject) => {
11170
+ const cleanup = () => {
11171
+ nodeRes.off("drain", onDrain);
11172
+ nodeRes.off("close", onClose);
11173
+ };
11174
+ const onDrain = () => {
11175
+ cleanup();
11176
+ resolve();
11177
+ };
11178
+ const onClose = () => {
11179
+ cleanup();
11180
+ reject(new Error("Dashboard response closed"));
11181
+ };
11182
+ nodeRes.once("drain", onDrain);
11183
+ nodeRes.once("close", onClose);
11184
+ });
10314
11185
  }
10315
11186
  } finally {
10316
- nodeRes.end();
11187
+ nodeRes.off("close", cancel);
11188
+ await reader.cancel().catch(() => {
11189
+ });
11190
+ reader.releaseLock();
11191
+ if (!nodeRes.destroyed) nodeRes.end();
10317
11192
  }
10318
11193
  }
10319
11194
  function tricacheDashboard(options) {
10320
11195
  return async (req, res, next) => {
10321
11196
  try {
10322
- const webReq = await nodeToWebRequest(req);
11197
+ const webReq = await nodeToWebRequest(req, res, options.maxRequestBytes ?? 65536);
10323
11198
  const webRes = await handleDashboardRequest(webReq, options);
10324
11199
  await pipeWebResponseToNode(webRes, res);
10325
11200
  } catch (err) {
10326
- if (typeof next === "function") {
11201
+ if (res.destroyed) return;
11202
+ if (err.status === 413) {
11203
+ res.statusCode = 413;
11204
+ res.setHeader("Connection", "close");
11205
+ res.end(JSON.stringify({ error: "Request body too large" }));
11206
+ } else if (typeof next === "function") {
10327
11207
  next(err);
10328
11208
  } else {
10329
11209
  res.statusCode = 500;
@@ -10342,7 +11222,7 @@ function createNextDashboardHandlers(options) {
10342
11222
  };
10343
11223
  }
10344
11224
  async function startDashboardServer(options) {
10345
- const port = options.port || 9090;
11225
+ const port = options.port ?? 9090;
10346
11226
  const host = options.host || "127.0.0.1";
10347
11227
  const middleware = tricacheDashboard(options);
10348
11228
  const server = import_node_http.default.createServer((req, res) => {
@@ -10366,6 +11246,7 @@ async function startDashboardServer(options) {
10366
11246
  host,
10367
11247
  close: () => new Promise((resolve, reject) => {
10368
11248
  server.close((err) => err ? reject(err) : resolve());
11249
+ server.closeAllConnections();
10369
11250
  })
10370
11251
  };
10371
11252
  }