tricache 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +36 -28
  2. package/dist/{cache-service-pJ-nFcVj.d.ts → cache-service-B108FzER.d.ts} +63 -3
  3. package/dist/cache-service-CWI4jkS7.d.cts +963 -0
  4. package/dist/{cache-service-26GCO3UU.js → cache-service-GYPZFB7O.js} +2 -2
  5. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  6. package/dist/{chunk-2AJKEQMZ.js → chunk-H4GFLQ26.js} +7 -4
  7. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  8. package/dist/chunk-OYDU3SMI.js +89 -0
  9. package/dist/{chunk-VXFTFZ5N.js → chunk-VNRDL5RA.js} +117 -138
  10. package/dist/{chunk-7SZSQS55.js → chunk-WYF7NOAT.js} +1831 -759
  11. package/dist/cli.cjs +1757 -777
  12. package/dist/cli.d.cts +12 -0
  13. package/dist/cli.js +27 -6
  14. package/dist/dashboard/index.cjs +111 -29
  15. package/dist/dashboard/index.d.cts +185 -0
  16. package/dist/dashboard/index.d.ts +5 -3
  17. package/dist/dashboard/index.js +1 -1
  18. package/dist/drizzle/index.cjs +1757 -773
  19. package/dist/drizzle/index.d.cts +46 -0
  20. package/dist/drizzle/index.d.ts +2 -2
  21. package/dist/drizzle/index.js +1 -1
  22. package/dist/edge/index.cjs +280 -153
  23. package/dist/edge/index.d.cts +127 -0
  24. package/dist/edge/index.d.ts +3 -3
  25. package/dist/edge/index.js +254 -147
  26. package/dist/hono/index.cjs +1805 -793
  27. package/dist/hono/index.d.cts +93 -0
  28. package/dist/hono/index.d.ts +7 -5
  29. package/dist/hono/index.js +16 -9
  30. package/dist/{hono-DuNvciyq.d.ts → hono-3rDMYVtY.d.ts} +23 -3
  31. package/dist/hono-C886ok3X.d.cts +391 -0
  32. package/dist/http/index.cjs +1946 -842
  33. package/dist/http/index.d.cts +103 -0
  34. package/dist/http/index.d.ts +13 -5
  35. package/dist/http/index.js +137 -57
  36. package/dist/index.cjs +2073 -937
  37. package/dist/index.d.cts +1006 -0
  38. package/dist/index.d.ts +40 -8
  39. package/dist/index.js +8 -8
  40. package/dist/murmur3-CMGw9PbV.d.cts +98 -0
  41. package/dist/nestjs/index.cjs +1849 -806
  42. package/dist/nestjs/index.d.cts +285 -0
  43. package/dist/nestjs/index.d.ts +103 -30
  44. package/dist/nestjs/index.js +115 -32
  45. package/dist/next/index.cjs +1913 -887
  46. package/dist/next/index.d.cts +232 -0
  47. package/dist/next/index.d.ts +33 -11
  48. package/dist/next/index.js +174 -107
  49. package/dist/prisma/index.cjs +11 -1
  50. package/dist/prisma/index.d.cts +62 -0
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +11 -1
  53. package/dist/serialize-worker.d.cts +2 -0
  54. package/dist/{types-5HXqBfAf.d.ts → types-BA4pz1A0.d.cts} +26 -9
  55. package/dist/types-BA4pz1A0.d.ts +1519 -0
  56. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  57. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  58. package/package.json +96 -36
  59. package/src/adapters/auto-pipeliner.ts +107 -24
  60. package/src/adapters/node-redis.ts +123 -25
  61. package/src/cache-service.ts +1238 -659
  62. package/src/cli.ts +24 -6
  63. package/src/cross-region.ts +21 -3
  64. package/src/dashboard/handler.ts +26 -6
  65. package/src/dashboard/html.ts +35 -10
  66. package/src/dashboard/index.ts +35 -13
  67. package/src/dashboard/types.ts +3 -1
  68. package/src/disk-tier.ts +171 -65
  69. package/src/edge/cache.ts +202 -129
  70. package/src/edge/hono.ts +23 -6
  71. package/src/edge/types.ts +2 -0
  72. package/src/hono/index.ts +19 -9
  73. package/src/http/express.ts +110 -26
  74. package/src/http/fastify.ts +38 -28
  75. package/src/http/utils.ts +54 -20
  76. package/src/ipc-telemetry.ts +35 -9
  77. package/src/nestjs/decorators.ts +1 -1
  78. package/src/nestjs/index.ts +2 -0
  79. package/src/nestjs/keyv-adapter.ts +68 -0
  80. package/src/nestjs/tricache.module.ts +13 -11
  81. package/src/nestjs/tricache.store.ts +51 -20
  82. package/src/nestjs/types.ts +29 -15
  83. package/src/next/cache-handler.ts +132 -57
  84. package/src/next/index.ts +1 -0
  85. package/src/next/isr-handler.ts +1 -4
  86. package/src/next/types.ts +21 -0
  87. package/src/prisma/index.ts +12 -1
  88. package/src/smart-memory-cache.ts +65 -27
  89. package/src/types.ts +27 -2
  90. package/src/utils/cgroup.ts +12 -0
  91. package/src/utils/deadline.ts +14 -0
  92. package/src/utils/diagnostics.ts +27 -0
  93. package/src/utils/redis-slot.ts +13 -0
  94. package/src/wasm/bloom-filter-wasm.ts +9 -4
  95. package/src/worker-pool.ts +17 -8
  96. package/src/wtiny-lfu.ts +20 -6
  97. package/dist/chunk-BQRURGGD.js +0 -60
package/dist/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) {
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) {
@@ -1810,11 +1978,13 @@ var SmartMemoryCache = class {
1810
1978
  priority,
1811
1979
  ttlMs,
1812
1980
  delta,
1813
- setAt: now2,
1814
- tagVersions
1981
+ setAt: setAt ?? now2,
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: 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;
@@ -4595,13 +5112,19 @@ var CacheService = class _CacheService {
4595
5112
  _l1Counters = /* @__PURE__ */ new Map();
4596
5113
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
4597
5114
  tagIndex = /* @__PURE__ */ new Map();
5115
+ /** Reverse index of namespaced key → { tags, expiresAt } for bounded cleanup on eviction/delete */
5116
+ keyTags = /* @__PURE__ */ new Map();
4598
5117
  /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
4599
5118
  tagVersions = /* @__PURE__ */ new Map();
5119
+ _tagRefreshEpoch = 0;
4600
5120
  /**
4601
5121
  * Dependency index: source glob pattern → Set of namespaced dependent keys.
4602
5122
  * When an exact-key delete matches a registered pattern, all dependents are cascaded.
4603
5123
  */
4604
5124
  dependencyIndex = /* @__PURE__ */ new Map();
5125
+ /** Reverse index of namespaced dependent key → source glob patterns */
5126
+ keyDependencies = /* @__PURE__ */ new Map();
5127
+ _cgroupMemoryLimit;
4605
5128
  redis = null;
4606
5129
  redisConnecting = null;
4607
5130
  cb;
@@ -4624,9 +5147,17 @@ var CacheService = class _CacheService {
4624
5147
  subClient = null;
4625
5148
  streamClient = null;
4626
5149
  _lastStreamId = "$";
5150
+ _restoredSnapshot = false;
5151
+ _backplaneAvailable = false;
5152
+ _otelCleanup = null;
5153
+ _streamRecovering = false;
5154
+ _backplaneDisposers = [];
4627
5155
  _destroyed = false;
4628
5156
  _pendingDiskDeletes = /* @__PURE__ */ new Set();
4629
5157
  _globalEpoch = 0;
5158
+ _pendingSpillCount = 0;
5159
+ _suppressSpills = false;
5160
+ _diskCleanupScheduled = false;
4630
5161
  _keyMutationEpochs = /* @__PURE__ */ new Map();
4631
5162
  /**
4632
5163
  * Pattern tombstones for disk tier.
@@ -4635,20 +5166,24 @@ var CacheService = class _CacheService {
4635
5166
  * pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
4636
5167
  */
4637
5168
  _patternTombstones = [];
4638
- _addPatternTombstone(prefix) {
5169
+ _diskInvalidatedBefore = 0;
5170
+ _addPatternTombstone(pattern) {
4639
5171
  const now = Date.now();
4640
5172
  while (this._patternTombstones.length > 0 && now - this._patternTombstones[0].createdAt > 36e5) {
4641
- this._patternTombstones.shift();
5173
+ const forgotten = this._patternTombstones.shift();
5174
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
4642
5175
  }
4643
5176
  if (this._patternTombstones.length >= 2e3) {
4644
- this._patternTombstones.shift();
5177
+ const forgotten = this._patternTombstones.shift();
5178
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
4645
5179
  }
4646
- this._patternTombstones.push({ prefix, createdAt: now });
5180
+ this._patternTombstones.push({ pattern, createdAt: now });
4647
5181
  }
4648
- _isTombstonedByPattern(namespacedKey) {
5182
+ _isTombstonedByPattern(namespacedKey, setAt = 0) {
5183
+ if (this._diskInvalidatedBefore > 0 && setAt <= this._diskInvalidatedBefore) return true;
4649
5184
  if (this._patternTombstones.length === 0) return false;
4650
5185
  for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
4651
- if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
5186
+ if (setAt <= this._patternTombstones[i].createdAt && this._matchesGlob(namespacedKey, this._patternTombstones[i].pattern)) {
4652
5187
  return true;
4653
5188
  }
4654
5189
  }
@@ -4663,13 +5198,170 @@ var CacheService = class _CacheService {
4663
5198
  const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
4664
5199
  this._keyMutationEpochs.set(namespacedKey, next);
4665
5200
  if (this._keyMutationEpochs.size > 5e4) {
4666
- const oldest = this._keyMutationEpochs.keys().next().value;
4667
- if (oldest !== void 0) this._keyMutationEpochs.delete(oldest);
5201
+ this._globalEpoch++;
5202
+ this._keyMutationEpochs.clear();
5203
+ this._keyMutationEpochs.set(namespacedKey, next);
4668
5204
  }
4669
5205
  return next;
4670
5206
  }
4671
5207
  _getKeyMutationEpoch(namespacedKey) {
4672
- 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);
5281
+ }
5282
+ _removeKeyTags(namespacedKey) {
5283
+ const entry = this.keyTags.get(namespacedKey);
5284
+ if (!entry) return;
5285
+ for (const tag of entry.tags) {
5286
+ const tagKey = this.nk(`_tag_:${tag}`);
5287
+ const members = this.tagIndex.get(tagKey);
5288
+ if (members) {
5289
+ members.delete(namespacedKey);
5290
+ if (members.size === 0) this.tagIndex.delete(tagKey);
5291
+ }
5292
+ }
5293
+ this.keyTags.delete(namespacedKey);
5294
+ }
5295
+ _removeKeyDependencies(namespacedKey) {
5296
+ const patterns = this.keyDependencies.get(namespacedKey);
5297
+ if (patterns) {
5298
+ for (const pat of patterns) {
5299
+ const deps = this.dependencyIndex.get(pat);
5300
+ if (deps) {
5301
+ deps.delete(namespacedKey);
5302
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
5303
+ }
5304
+ }
5305
+ this.keyDependencies.delete(namespacedKey);
5306
+ } else if (this.dependencyIndex.size > 0) {
5307
+ for (const [pat, deps] of this.dependencyIndex) {
5308
+ deps.delete(namespacedKey);
5309
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
5310
+ }
5311
+ }
5312
+ }
5313
+ _handleL1Eviction(namespacedKey, reason) {
5314
+ const spilledToDisk = !this._diskDisabled && !this._suppressSpills && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
5315
+ if (!spilledToDisk) {
5316
+ this._removeKeyTags(namespacedKey);
5317
+ this._removeKeyDependencies(namespacedKey);
5318
+ }
5319
+ }
5320
+ _removePatternFromIndices(pattern) {
5321
+ for (const k of Array.from(this.keyTags.keys())) {
5322
+ if (this._matchesGlob(k, pattern)) this._removeKeyTags(k);
5323
+ }
5324
+ for (const k of Array.from(this.keyDependencies.keys())) {
5325
+ if (this._matchesGlob(k, pattern)) this._removeKeyDependencies(k);
5326
+ }
5327
+ for (const k of Array.from(this._l1Counters.keys())) {
5328
+ if (this._matchesGlob(k, pattern)) this._l1Counters.delete(k);
5329
+ }
5330
+ }
5331
+ _sweepExpiredMetadata() {
5332
+ const now = Date.now();
5333
+ for (const [k, c] of this._l1Counters) {
5334
+ if (c.expiresAt <= now) this._l1Counters.delete(k);
5335
+ }
5336
+ for (const [k, meta] of this.keyTags) {
5337
+ if (meta.expiresAt <= now && !this.l1.has(k)) {
5338
+ this._removeKeyTags(k);
5339
+ this._removeKeyDependencies(k);
5340
+ }
5341
+ }
5342
+ }
5343
+ _runOomCheck() {
5344
+ const heap = import_node_v82.default.getHeapStatistics();
5345
+ const heapUsed = heap.used_heap_size / heap.heap_size_limit;
5346
+ const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? (readCgroupMemoryUsage() ?? process.memoryUsage().rss) / this._cgroupMemoryLimit : 0;
5347
+ const used = Math.max(heapUsed, cgroupUsed);
5348
+ if (used >= this.opts.oomHeapThreshold) {
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
+ }
5356
+ this.counters.oomEvictions++;
5357
+ this.counters.oomLastAt = Date.now();
5358
+ this.logger.warn("tricache OOM guard: emergency L1 eviction", {
5359
+ heapUsedPct: Math.round(heapUsed * 100),
5360
+ cgroupUsedPct: cgroupUsed > 0 ? Math.round(cgroupUsed * 100) : void 0,
5361
+ threshold: Math.round(this.opts.oomHeapThreshold * 100),
5362
+ evicted
5363
+ });
5364
+ }
4673
5365
  }
4674
5366
  _ipcServer;
4675
5367
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
@@ -4717,6 +5409,7 @@ var CacheService = class _CacheService {
4717
5409
  constructor(options = {}) {
4718
5410
  const logger = options.logger ?? consoleLogger;
4719
5411
  this.logger = logger;
5412
+ this._cgroupMemoryLimit = readCgroupMemoryLimit();
4720
5413
  const ns = options.namespace?.trim() ?? "";
4721
5414
  const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
4722
5415
  this.enc = new CacheEncryption(
@@ -4895,12 +5588,19 @@ var CacheService = class _CacheService {
4895
5588
  admissionPolicy: this.opts.l1AdmissionPolicy,
4896
5589
  codec: this.codec,
4897
5590
  diskSpill: (key, entry) => {
4898
- 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++;
4899
5595
  setImmediate(() => {
4900
- void this.disk.save(key, entry);
5596
+ this._pendingSpillCount--;
5597
+ if (!this._destroyed && this._getKeyMutationEpoch(key) === epoch) void this.disk.save(key, entry);
4901
5598
  });
4902
5599
  },
4903
- onEviction: options.onEviction,
5600
+ onEviction: (key, reason) => {
5601
+ this._handleL1Eviction(key, reason);
5602
+ options.onEviction?.(key, reason);
5603
+ },
4904
5604
  logger
4905
5605
  });
4906
5606
  if (!this.snapshotLoaded) {
@@ -4938,6 +5638,7 @@ var CacheService = class _CacheService {
4938
5638
  }
4939
5639
  this.cleanupInterval = setInterval(() => {
4940
5640
  const cleaned = this.l1.cleanup();
5641
+ this._sweepExpiredMetadata();
4941
5642
  if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
4942
5643
  }, 5 * 60 * 1e3);
4943
5644
  if (this.cleanupInterval.unref) this.cleanupInterval.unref();
@@ -4950,18 +5651,7 @@ var CacheService = class _CacheService {
4950
5651
  }
4951
5652
  if (this.opts.oomProtection) {
4952
5653
  this.oomInterval = setInterval(() => {
4953
- const heap = import_node_v82.default.getHeapStatistics();
4954
- const used = heap.used_heap_size / heap.heap_size_limit;
4955
- if (used >= this.opts.oomHeapThreshold) {
4956
- const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
4957
- this.counters.oomEvictions++;
4958
- this.counters.oomLastAt = Date.now();
4959
- this.logger.warn("tricache OOM guard: emergency L1 eviction", {
4960
- heapUsedPct: Math.round(used * 100),
4961
- threshold: Math.round(this.opts.oomHeapThreshold * 100),
4962
- evicted
4963
- });
4964
- }
5654
+ this._runOomCheck();
4965
5655
  }, this.opts.oomCheckIntervalMs);
4966
5656
  if (this.oomInterval.unref) this.oomInterval.unref();
4967
5657
  }
@@ -4983,7 +5673,7 @@ var CacheService = class _CacheService {
4983
5673
  this.instanceId = import_crypto3.default.randomBytes(8).toString("hex");
4984
5674
  this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
4985
5675
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
4986
- 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 }));
4987
5677
  const startupPromises = [];
4988
5678
  if (this.opts.compression === "zstd") {
4989
5679
  startupPromises.push(initZstd().then(() => void 0));
@@ -4994,9 +5684,8 @@ var CacheService = class _CacheService {
4994
5684
  if (this.opts.warmKeys) {
4995
5685
  startupPromises.push(this.warmFromL2(this.opts.warmKeys).then(() => void 0));
4996
5686
  }
4997
- if (startupPromises.length > 0) {
4998
- this._readyPromise = Promise.all(startupPromises).then(() => void 0);
4999
- }
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);
5000
5689
  if (this.opts.meter) {
5001
5690
  this._initOtelMetrics(this.opts.meter);
5002
5691
  const otel = this._otelMetrics;
@@ -5009,7 +5698,10 @@ var CacheService = class _CacheService {
5009
5698
  if (typeof prop === "string" && typeof value === "number" && typeof oldVal === "number") {
5010
5699
  const diff = value - oldVal;
5011
5700
  if (diff > 0 && otel[prop]) {
5012
- otel[prop].add(diff, nsAttr);
5701
+ try {
5702
+ otel[prop].add(diff, nsAttr);
5703
+ } catch {
5704
+ }
5013
5705
  }
5014
5706
  }
5015
5707
  return ok;
@@ -5101,7 +5793,7 @@ var CacheService = class _CacheService {
5101
5793
  return g[key];
5102
5794
  }
5103
5795
  const existing = g[key];
5104
- const diff = _CacheService.optionsDiff(options ?? {}, existing.options);
5796
+ const diff = _CacheService.optionsDiff(options ?? {}, existing.opts);
5105
5797
  if (diff.length > 0) {
5106
5798
  existing.bumpSingletonDivergence();
5107
5799
  const msg = `tricache: singleton already initialised for namespace '${existing.options.namespace || "(default)"}' \u2014 ignoring divergent options: ${diff.join(", ")}`;
@@ -5135,7 +5827,13 @@ var CacheService = class _CacheService {
5135
5827
  "instanceName",
5136
5828
  "invalidationBackplane",
5137
5829
  "awaitInvalidationBackplane",
5138
- "lockFailClosed"
5830
+ "lockFailClosed",
5831
+ "tagStrategy",
5832
+ "cloneStrategy",
5833
+ "compression",
5834
+ "backplaneMode",
5835
+ "redisProtocol",
5836
+ "failClosed"
5139
5837
  ];
5140
5838
  /** Returns the names of options that differ between `a` and the live `b`. */
5141
5839
  static optionsDiff(a, b) {
@@ -5153,12 +5851,12 @@ var CacheService = class _CacheService {
5153
5851
  bumpSingletonDivergence() {
5154
5852
  this.counters.singletonDivergences++;
5155
5853
  }
5156
- /** Read-only view of the options the singleton was constructed with. */
5854
+ /** Sanitized diagnostic view; retain the original options/adapters to reuse configuration. */
5157
5855
  get options() {
5158
5856
  const o = this.opts;
5159
5857
  return {
5160
5858
  namespace: o.namespace,
5161
- 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) },
5162
5860
  l1MaxBytes: o.l1MaxBytes,
5163
5861
  l1MaxEntries: o.l1MaxEntries,
5164
5862
  redisHost: o.redisHost,
@@ -5179,8 +5877,8 @@ var CacheService = class _CacheService {
5179
5877
  awaitInvalidationBackplane: o.awaitInvalidationBackplane,
5180
5878
  lockFailClosed: o.lockFailClosed,
5181
5879
  strictSingleton: o.strictSingleton,
5182
- remoteSnapshot: o.remoteSnapshot,
5183
- crossRegion: o.crossRegion
5880
+ remoteSnapshot: redactDiagnostics(o.remoteSnapshot),
5881
+ crossRegion: redactDiagnostics(o.crossRegion)
5184
5882
  };
5185
5883
  }
5186
5884
  /**
@@ -5263,21 +5961,26 @@ var CacheService = class _CacheService {
5263
5961
  if (this.opts.redisClient && typeof this.opts.redisClient.duplicate === "function") {
5264
5962
  return this.opts.redisClient.duplicate();
5265
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
+ }
5266
5967
  if (this.opts.redisClusterNodes?.length) {
5267
- return new import_ioredis.Cluster(this.opts.redisClusterNodes, {
5968
+ return new import_ioredis2.Cluster(this.opts.redisClusterNodes, {
5268
5969
  redisOptions: {
5269
5970
  tls: this.opts.redisTls ? {} : void 0,
5270
5971
  connectTimeout: 1e4,
5972
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
5271
5973
  maxRetriesPerRequest: null,
5272
5974
  ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
5273
5975
  }
5274
5976
  });
5275
5977
  } else if (this.opts.redisSentinel) {
5276
- return new import_ioredis.Redis({
5978
+ return new import_ioredis2.Redis({
5277
5979
  sentinels: this.opts.redisSentinel.sentinels,
5278
5980
  name: this.opts.redisSentinel.name,
5279
5981
  tls: this.opts.redisTls ? {} : void 0,
5280
5982
  connectTimeout: 1e4,
5983
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
5281
5984
  lazyConnect: true,
5282
5985
  maxRetriesPerRequest: null,
5283
5986
  enableAutoPipelining: false,
@@ -5285,11 +5988,12 @@ var CacheService = class _CacheService {
5285
5988
  ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
5286
5989
  });
5287
5990
  } else {
5288
- return new import_ioredis.Redis({
5991
+ return new import_ioredis2.Redis({
5289
5992
  host: this.opts.redisHost,
5290
5993
  port: this.opts.redisPort,
5291
5994
  tls: this.opts.redisTls ? {} : void 0,
5292
5995
  connectTimeout: 1e4,
5996
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
5293
5997
  lazyConnect: true,
5294
5998
  maxRetriesPerRequest: null,
5295
5999
  enableAutoPipelining: false,
@@ -5299,26 +6003,32 @@ var CacheService = class _CacheService {
5299
6003
  });
5300
6004
  }
5301
6005
  }
5302
- initBackplane() {
6006
+ _listenBackplane(client, event, listener) {
6007
+ client.on?.(event, listener);
6008
+ this._backplaneDisposers.push(() => client.removeListener?.(event, listener));
6009
+ }
6010
+ async initBackplane() {
5303
6011
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
5304
6012
  if (this.opts.backplaneMode === "stream") {
5305
6013
  if (this.streamClient) return;
5306
- void this._startStreamConsumer();
6014
+ await this._startStreamConsumer();
5307
6015
  return;
5308
6016
  }
5309
6017
  if (this.subClient) return;
5310
6018
  const sub = this.createDedicatedRedisClient();
5311
- sub.on("error", (e) => {
6019
+ this.subClient = sub;
6020
+ this._listenBackplane(sub, "error", (e) => {
5312
6021
  this._checkAndLogResp3Hint(e);
5313
6022
  this.logger.debug("Backplane subscriber error", { error: e.message });
5314
6023
  });
5315
- sub.on("close", () => {
6024
+ this._listenBackplane(sub, "close", () => {
6025
+ this._backplaneAvailable = false;
5316
6026
  if (this._subDisconnectedAt === null) {
5317
6027
  this._subDisconnectedAt = Date.now();
5318
6028
  this.logger.debug("Backplane: subscriber disconnected", { at: this._subDisconnectedAt });
5319
6029
  }
5320
6030
  });
5321
- sub.on("ready", () => {
6031
+ this._listenBackplane(sub, "ready", () => {
5322
6032
  if (this._subDisconnectedAt !== null && this.opts.backplaneMaxStalenessMs > 0) {
5323
6033
  const gapMs = Date.now() - this._subDisconnectedAt;
5324
6034
  if (gapMs > this.opts.backplaneMaxStalenessMs) {
@@ -5331,52 +6041,119 @@ var CacheService = class _CacheService {
5331
6041
  }
5332
6042
  this._subDisconnectedAt = null;
5333
6043
  }
6044
+ if (!this._destroyed) this._backplaneAvailable = true;
5334
6045
  });
5335
6046
  const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
5336
6047
  if (isClusterSharded) {
5337
- sub.on("smessage", (_channel, message) => {
6048
+ this._listenBackplane(sub, "smessage", (_channel, message) => {
5338
6049
  this._handleBackplaneMessage(message);
5339
6050
  });
5340
- 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", {
5341
6053
  channel: this.backplaneChannel,
5342
6054
  instanceId: this.instanceId
5343
- })).catch((err) => this.logger.warn("Backplane: sharded subscribe failed", {
5344
- error: err.message
5345
6055
  }));
5346
6056
  } else {
5347
- sub.on("message", (_channel, message) => {
6057
+ this._listenBackplane(sub, "message", (_channel, message) => {
5348
6058
  this._handleBackplaneMessage(message);
5349
6059
  });
5350
- 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", {
5351
6063
  channel: this.backplaneChannel,
5352
6064
  instanceId: this.instanceId
5353
- })).catch((err) => this.logger.warn("Backplane: subscribe failed", {
5354
- error: err.message
5355
6065
  }));
5356
6066
  }
5357
- 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";
5358
6081
  }
5359
6082
  async _startStreamConsumer() {
6083
+ this._streamRecovering ||= this._lastStreamId !== "$" && this._lastStreamId !== "0-0";
5360
6084
  const sub = this.streamClient ?? this.createDedicatedRedisClient();
5361
6085
  this.streamClient = sub;
6086
+ if (typeof sub.xread !== "function") throw new Error("backplaneMode: stream requires a driver supporting XREAD");
5362
6087
  if (typeof sub.on === "function") {
5363
- sub.on("error", (e) => this.logger.debug("Backplane stream consumer error", { error: e.message }));
5364
- 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;
5365
6092
  if (this._subDisconnectedAt === null) {
5366
6093
  this._subDisconnectedAt = Date.now();
5367
6094
  this.logger.debug("Backplane stream: consumer disconnected", { at: this._subDisconnectedAt });
5368
6095
  }
5369
6096
  });
5370
- sub.on("ready", () => {
6097
+ this._listenBackplane(sub, "ready", () => {
5371
6098
  if (this._subDisconnectedAt !== null) {
5372
6099
  this.logger.debug("Backplane stream: consumer reconnected, resuming stream read", { lastId: this._lastStreamId });
5373
6100
  this._subDisconnectedAt = null;
5374
6101
  }
5375
6102
  });
5376
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
+ }
5377
6151
  const runLoop = async () => {
5378
6152
  while (!this._destroyed && !this._redisDisabled) {
5379
6153
  try {
6154
+ if (!initialized) await initialize();
6155
+ if (this._destroyed) break;
6156
+ await checkGap();
5380
6157
  const res = await sub.xread(
5381
6158
  "BLOCK",
5382
6159
  this.opts.backplaneStreamBlockMs,
@@ -5385,19 +6162,10 @@ var CacheService = class _CacheService {
5385
6162
  this._lastStreamId
5386
6163
  );
5387
6164
  if (this._destroyed) break;
6165
+ this._backplaneAvailable = true;
5388
6166
  if (res && res.length > 0) {
5389
- for (const [, entries] of res) {
5390
- if (entries.length > 0) {
5391
- if (this._lastStreamId !== "$") {
5392
- this.counters.streamReplays++;
5393
- }
5394
- for (const [id, fields] of entries) {
5395
- this._lastStreamId = id;
5396
- this.counters.streamEntriesReceived++;
5397
- this._processStreamEntry(fields);
5398
- }
5399
- }
5400
- }
6167
+ apply(res);
6168
+ this._backplaneAvailable = true;
5401
6169
  } else {
5402
6170
  await new Promise((resolve) => setTimeout(resolve, 10));
5403
6171
  }
@@ -5405,10 +6173,9 @@ var CacheService = class _CacheService {
5405
6173
  if (this._destroyed) break;
5406
6174
  const msg = err.message ?? "";
5407
6175
  if (msg.includes("NOGROUP") || msg.includes("smaller than") || msg.includes("trimmed")) {
5408
- this.counters.streamGaps++;
5409
- this.l1.clear();
5410
- this._lastStreamId = "$";
6176
+ this._resetAfterStreamGap();
5411
6177
  }
6178
+ this._backplaneAvailable = false;
5412
6179
  await new Promise((resolve) => setTimeout(resolve, 200));
5413
6180
  }
5414
6181
  }
@@ -5436,8 +6203,8 @@ var CacheService = class _CacheService {
5436
6203
  else if (f === "src") src = v;
5437
6204
  else if (f === "tagVersion") tagVersionRaw = v;
5438
6205
  }
5439
- const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
5440
- if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
6206
+ const validOp = op === "del" || op === "del-glob" || op === "tag_incr" || op === "tag_pattern_incr" || op === "tag_pattern_del";
6207
+ if (!validOp || typeof key !== "string" || !key || typeof src !== "string" || !src || (op === "del" || op === "del-glob") && this._namespace && !key.startsWith(`${this._namespace}:`)) {
5441
6208
  this.logger.warn("Backplane: rejected invalid stream entry", {
5442
6209
  op: String(op).slice(0, 40),
5443
6210
  key: typeof key === "string" ? key.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(key)
@@ -5446,8 +6213,8 @@ var CacheService = class _CacheService {
5446
6213
  }
5447
6214
  let tagVersion;
5448
6215
  if (tagVersionRaw !== void 0) {
5449
- const parsed = parseInt(tagVersionRaw, 10);
5450
- if (!Number.isFinite(parsed)) {
6216
+ const parsed = Number(tagVersionRaw);
6217
+ if (!Number.isSafeInteger(parsed) || parsed < 0) {
5451
6218
  this.logger.warn("Backplane: rejected stream entry with non-numeric tagVersion", { key });
5452
6219
  return;
5453
6220
  }
@@ -5465,16 +6232,10 @@ var CacheService = class _CacheService {
5465
6232
  this.l1.delete(key);
5466
6233
  this._bumpKeyMutation(key);
5467
6234
  this.inflight.delete(key);
5468
- this._pendingDiskDeletes.add(key);
5469
- setImmediate(() => {
5470
- try {
5471
- if (!this._diskDisabled) this.disk.delete(key);
5472
- } finally {
5473
- this._pendingDiskDeletes.delete(key);
5474
- }
5475
- });
6235
+ this._invalidateDiskKey(key);
5476
6236
  this._cascadeDependencies(key);
5477
6237
  } else if (op === "del-glob") {
6238
+ this._fenceInvalidation();
5478
6239
  this.l1.deletePattern(key);
5479
6240
  const pfx = key.endsWith("*") ? key.slice(0, -1) : key;
5480
6241
  for (const liveKey of this.l1.liveKeys()) {
@@ -5488,12 +6249,22 @@ var CacheService = class _CacheService {
5488
6249
  this.inflight.delete(inflightKey);
5489
6250
  }
5490
6251
  }
5491
- 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
+ }
5492
6261
  } else if (op === "tag_incr") {
6262
+ this._fenceInvalidation();
5493
6263
  const tag = key;
5494
6264
  const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
5495
6265
  this._setLocalTagVersion(tag, ver, performance.now());
5496
6266
  } else if (op === "tag_pattern_incr") {
6267
+ this._fenceInvalidation();
5497
6268
  const pattern = key;
5498
6269
  const now = performance.now();
5499
6270
  for (const [tag, info] of this.tagVersions) {
@@ -5513,6 +6284,7 @@ var CacheService = class _CacheService {
5513
6284
  }
5514
6285
  }, 0);
5515
6286
  } else if (op === "tag_pattern_del") {
6287
+ this._fenceInvalidation();
5516
6288
  const pattern = key;
5517
6289
  const matchedTagKeys = [];
5518
6290
  const prefix = this.nk("_tag_:");
@@ -5523,14 +6295,7 @@ var CacheService = class _CacheService {
5523
6295
  for (const k of members) {
5524
6296
  this.l1.delete(k);
5525
6297
  this._bumpKeyMutation(k);
5526
- this._pendingDiskDeletes.add(k);
5527
- setImmediate(() => {
5528
- try {
5529
- if (!this._diskDisabled) this.disk.delete(k);
5530
- } finally {
5531
- this._pendingDiskDeletes.delete(k);
5532
- }
5533
- });
6298
+ this._invalidateDiskKey(k);
5534
6299
  }
5535
6300
  }
5536
6301
  }
@@ -5561,6 +6326,7 @@ var CacheService = class _CacheService {
5561
6326
  }
5562
6327
  }
5563
6328
  async publishInvalidation(op, key, tagVersion, isCrossRegionRelay = false, isExplicitInvalidation = false) {
6329
+ if (this.opts.l2WriteMode === "read-only") return;
5564
6330
  if (!isCrossRegionRelay && this.opts.crossRegion) {
5565
6331
  const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
5566
6332
  if (shouldBroadcast) {
@@ -5643,13 +6409,13 @@ var CacheService = class _CacheService {
5643
6409
  timestamp: Date.now(),
5644
6410
  namespace: this._namespace || void 0
5645
6411
  };
5646
- this.counters.crossRegionSent++;
5647
6412
  await cr.relay.broadcast(event);
6413
+ this.counters.crossRegionSent++;
5648
6414
  this.logger.debug("Cross-region invalidation broadcast", { op, key, region: cr.currentRegion });
5649
6415
  } catch (err) {
5650
- this.counters.crossRegionSent = Math.max(0, this.counters.crossRegionSent - 1);
5651
6416
  this.counters.crossRegionErrors++;
5652
6417
  this.logger.warn("Cross-region invalidation broadcast failed", { error: err.message });
6418
+ if (this.opts.awaitInvalidationBackplane) throw err;
5653
6419
  }
5654
6420
  }
5655
6421
  /**
@@ -5660,11 +6426,12 @@ var CacheService = class _CacheService {
5660
6426
  * Returns true if the event was accepted and applied, or false if ignored/deduplicated.
5661
6427
  */
5662
6428
  async receiveCrossRegionInvalidation(event) {
6429
+ this._assertActive("receiveCrossRegionInvalidation");
5663
6430
  const cr = this.opts.crossRegion;
5664
6431
  if (!cr) return false;
5665
- if (!event || typeof event !== "object" || !event.id || !event.originRegion || !event.op || !event.key) {
6432
+ if (!isCrossRegionInvalidationEvent(event)) {
5666
6433
  this.counters.crossRegionErrors++;
5667
- this.logger.warn("Cross-region: rejected invalid event payload", { event });
6434
+ this.logger.warn("Cross-region: rejected invalid event payload");
5668
6435
  return false;
5669
6436
  }
5670
6437
  if (event.originRegion === cr.currentRegion) {
@@ -5675,13 +6442,52 @@ var CacheService = class _CacheService {
5675
6442
  this.counters.crossRegionDeduplicated++;
5676
6443
  return false;
5677
6444
  }
5678
- this._markCrossRegionEventSeen(event.id);
5679
6445
  if (event.namespace !== void 0 && event.namespace !== (this._namespace || void 0)) {
5680
6446
  return false;
5681
6447
  }
6448
+ if ((event.op === "del" || event.op === "del-glob") && this._namespace && !event.key.startsWith(`${this._namespace}:`)) return false;
6449
+ this._markCrossRegionEventSeen(event.id);
5682
6450
  this.counters.crossRegionReceived++;
5683
- this._applyInvalidationEvent(event.op, event.key, event.tagVersion);
5684
- 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
+ }
5685
6491
  this.logger.info("Cross-region invalidation applied", {
5686
6492
  op: event.op,
5687
6493
  key: event.key,
@@ -5696,25 +6502,269 @@ var CacheService = class _CacheService {
5696
6502
  const oldestKey = this.tagVersions.keys().next().value;
5697
6503
  if (oldestKey !== void 0) this.tagVersions.delete(oldestKey);
5698
6504
  }
5699
- this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
6505
+ this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now, refreshEpoch: this._tagRefreshEpoch });
6506
+ }
6507
+ async _isGenerationalEntryStale(tagVersions) {
6508
+ if (!tagVersions) return false;
6509
+ const tags = Object.keys(tagVersions);
6510
+ if (tags.length === 0) return false;
6511
+ const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
6512
+ for (let i = 0; i < tags.length; i++) {
6513
+ if (currentVers[i] > tagVersions[tags[i]]) return true;
6514
+ }
6515
+ return false;
6516
+ }
6517
+ async _deleteRedisKeys(client, keys) {
6518
+ if (keys.length === 0) return;
6519
+ const CHUNK_SIZE = 1e3;
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
+ }));
6537
+ return;
6538
+ }
6539
+ for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
6540
+ const chunk = keys.slice(i, i + CHUNK_SIZE);
6541
+ await client.del(...chunk);
6542
+ }
6543
+ }
6544
+ async _parseGenerationalRedisHash(k, hashData) {
6545
+ if (!hashData || !hashData.d) return null;
6546
+ let storedTagVersions = {};
6547
+ if (hashData.tv) {
6548
+ try {
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;
6552
+ } catch {
6553
+ return null;
6554
+ }
6555
+ }
6556
+ if (await this._isGenerationalEntryStale(storedTagVersions)) {
6557
+ const setAtMs = parseInt(hashData.t, 10) || 0;
6558
+ this._deleteIfStale(k, setAtMs);
6559
+ return { stale: true };
6560
+ }
6561
+ const value = await this._decryptAndDeserialize(hashData.d);
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
+ };
6584
+ }
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
+ };
6595
+ if (this.opts.tagStrategy === "generational" && typeof client.hgetall === "function") {
6596
+ try {
6597
+ const { raw: hashData, ttlMs: ttlMs2 } = await read(true);
6598
+ if (typeof hashData === "string") {
6599
+ const value2 = await this._decryptAndDeserialize(hashData);
6600
+ return withExpiry({ value: value2, stale: false }, ttlMs2);
6601
+ }
6602
+ if (hashData && hashData.d) {
6603
+ return withExpiry(await this._parseGenerationalRedisHash(k, hashData), ttlMs2);
6604
+ }
6605
+ return null;
6606
+ } catch (err) {
6607
+ const msg = err instanceof Error ? err.message : String(err);
6608
+ if (!msg.includes("WRONGTYPE")) throw err;
6609
+ }
6610
+ }
6611
+ const { raw, ttlMs } = await read(false);
6612
+ if (raw == null) return null;
6613
+ if (typeof raw !== "string") return null;
6614
+ const value = await this._decryptAndDeserialize(raw);
6615
+ return withExpiry({ value, stale: false }, ttlMs);
5700
6616
  }
5701
6617
  async _getTagVersion(tag) {
5702
6618
  const now = performance.now();
5703
6619
  const local = this.tagVersions.get(tag);
5704
- if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
6620
+ if (local && (local.refreshEpoch ?? 0) === this._tagRefreshEpoch && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
5705
6621
  return local.version;
5706
6622
  }
5707
6623
  if (!this._redisDisabled) {
5708
6624
  try {
5709
6625
  const client = await this.getRedis();
5710
6626
  const raw = await client.get(this.nk(`tag_ver:${tag}`));
5711
- const version = raw ? parseInt(raw, 10) : 0;
5712
- this._setLocalTagVersion(tag, version, now);
5713
- 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;
5714
6637
  } catch {
5715
6638
  }
5716
6639
  }
5717
- 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();
5718
6768
  }
5719
6769
  _deleteIfStale(k, setAtMs) {
5720
6770
  this.l1.deleteIfSetBefore(k, setAtMs);
@@ -5767,7 +6817,7 @@ var CacheService = class _CacheService {
5767
6817
  } else {
5768
6818
  plain = raw;
5769
6819
  }
5770
- return JSON.parse(plain);
6820
+ return plain === "undefined" ? void 0 : JSON.parse(plain);
5771
6821
  }
5772
6822
  /**
5773
6823
  * Scan all keys matching `pattern` across single-node or Cluster clients.
@@ -5775,7 +6825,7 @@ var CacheService = class _CacheService {
5775
6825
  */
5776
6826
  async _scanKeys(client, pattern) {
5777
6827
  const keys = [];
5778
- if (client instanceof import_ioredis.Cluster) {
6828
+ if (client instanceof import_ioredis2.Cluster) {
5779
6829
  const masters = client.nodes("master");
5780
6830
  await Promise.all(masters.map(
5781
6831
  (node) => new Promise((resolve, reject) => {
@@ -5835,10 +6885,10 @@ var CacheService = class _CacheService {
5835
6885
  return client;
5836
6886
  }
5837
6887
  this.redisConnecting = (async () => {
6888
+ let client = null;
5838
6889
  try {
5839
- let client;
5840
6890
  if (this.opts.redisClusterNodes?.length) {
5841
- client = new import_ioredis.Cluster(this.opts.redisClusterNodes, {
6891
+ client = new import_ioredis2.Cluster(this.opts.redisClusterNodes, {
5842
6892
  redisOptions: {
5843
6893
  tls: this.opts.redisTls ? {} : void 0,
5844
6894
  connectTimeout: 1e4,
@@ -5858,7 +6908,7 @@ var CacheService = class _CacheService {
5858
6908
  });
5859
6909
  client.on("reconnecting", () => this.logger.debug("Redis Cluster reconnecting"));
5860
6910
  } else if (this.opts.redisSentinel) {
5861
- client = new import_ioredis.Redis({
6911
+ client = new import_ioredis2.Redis({
5862
6912
  sentinels: this.opts.redisSentinel.sentinels,
5863
6913
  name: this.opts.redisSentinel.name,
5864
6914
  tls: this.opts.redisTls ? {} : void 0,
@@ -5878,7 +6928,7 @@ var CacheService = class _CacheService {
5878
6928
  });
5879
6929
  client.on("reconnecting", () => this.logger.debug("Redis Sentinel reconnecting"));
5880
6930
  } else {
5881
- client = new import_ioredis.Redis({
6931
+ client = new import_ioredis2.Redis({
5882
6932
  host: this.opts.redisHost,
5883
6933
  port: this.opts.redisPort,
5884
6934
  tls: this.opts.redisTls ? {} : void 0,
@@ -5899,14 +6949,45 @@ var CacheService = class _CacheService {
5899
6949
  });
5900
6950
  client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
5901
6951
  }
6952
+ const pendingClient = client;
5902
6953
  await new Promise((resolve, reject) => {
5903
- client.once("ready", resolve);
5904
- client.once("error", (e) => {
6954
+ let settled = false;
6955
+ const cleanupListeners = () => {
6956
+ pendingClient.removeListener?.("ready", onReady);
6957
+ pendingClient.removeListener?.("error", onError);
6958
+ };
6959
+ const onReady = () => {
6960
+ if (settled) return;
6961
+ settled = true;
6962
+ clearTimeout(timer);
6963
+ cleanupListeners();
6964
+ resolve();
6965
+ };
6966
+ const onError = (e) => {
6967
+ if (settled) return;
6968
+ settled = true;
6969
+ clearTimeout(timer);
6970
+ cleanupListeners();
5905
6971
  this._checkAndLogResp3Hint(e);
5906
6972
  reject(e);
5907
- });
5908
- setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
6973
+ };
6974
+ const timer = setTimeout(() => {
6975
+ if (settled) return;
6976
+ settled = true;
6977
+ cleanupListeners();
6978
+ reject(new Error("Redis connection timeout"));
6979
+ }, 15e3);
6980
+ if (timer.unref) timer.unref();
6981
+ pendingClient.once("ready", onReady);
6982
+ pendingClient.once("error", onError);
5909
6983
  });
6984
+ if (this._destroyed) {
6985
+ try {
6986
+ client.disconnect();
6987
+ } catch {
6988
+ }
6989
+ this._assertActive("getRedis");
6990
+ }
5910
6991
  this.cb.onSuccess();
5911
6992
  this.redis = client;
5912
6993
  this.pipeliner = new AutoPipeliner(client, {
@@ -5916,6 +6997,10 @@ var CacheService = class _CacheService {
5916
6997
  this.redisConnecting = null;
5917
6998
  return client;
5918
6999
  } catch (err) {
7000
+ try {
7001
+ client?.disconnect();
7002
+ } catch {
7003
+ }
5919
7004
  this.cb.onFailure();
5920
7005
  this.redisConnecting = null;
5921
7006
  this._checkAndLogResp3Hint(err);
@@ -5935,7 +7020,12 @@ var CacheService = class _CacheService {
5935
7020
  try {
5936
7021
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
5937
7022
  if (entries.length === 0) return;
5938
- 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
+ };
5939
7029
  const packed = this.codec.encode(payload);
5940
7030
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
5941
7031
  const dest = altPath ?? this.opts.snapshotPath;
@@ -6003,6 +7093,9 @@ var CacheService = class _CacheService {
6003
7093
  return;
6004
7094
  }
6005
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);
6006
7099
  this.logger.info("Cache snapshot loaded (L1 is warm)", {
6007
7100
  loaded,
6008
7101
  total: snapshot.entries.length,
@@ -6027,7 +7120,12 @@ var CacheService = class _CacheService {
6027
7120
  try {
6028
7121
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
6029
7122
  if (entries.length === 0) return false;
6030
- 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
+ };
6031
7129
  const packed = this.codec.encode(payload);
6032
7130
  let final;
6033
7131
  if (this.opts.remoteSnapshot.envelope) {
@@ -6058,13 +7156,16 @@ var CacheService = class _CacheService {
6058
7156
  async loadRemoteSnapshot() {
6059
7157
  if (!this.opts.remoteSnapshot) return 0;
6060
7158
  const maxAgeMs = this.opts.remoteSnapshot.maxAgeMs ?? this.opts.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE;
7159
+ const epoch = this._globalEpoch;
6061
7160
  try {
6062
7161
  const raw = await this.opts.remoteSnapshot.adapter.get();
7162
+ if (this._destroyed || this._globalEpoch !== epoch) return 0;
6063
7163
  if (!raw || raw.length === 0) {
6064
7164
  this.logger.debug("Remote snapshot not found or empty \u2014 starting cold");
6065
7165
  return 0;
6066
7166
  }
6067
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");
6068
7169
  let buf;
6069
7170
  try {
6070
7171
  if (EnvelopeEncryption.isEnvelope(rawBuf)) {
@@ -6110,7 +7211,12 @@ var CacheService = class _CacheService {
6110
7211
  this.logger.warn("Remote snapshot rejected: entries is not an array");
6111
7212
  return 0;
6112
7213
  }
6113
- 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);
6114
7220
  this.counters.remoteSnapshotDownloads++;
6115
7221
  this.counters.remoteSnapshotLastDownloadedAt = Date.now();
6116
7222
  this.logger.info("Remote cache snapshot loaded (L1 hydrated)", {
@@ -6159,20 +7265,10 @@ var CacheService = class _CacheService {
6159
7265
  const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
6160
7266
  const l1Hit = this.l1.get(k);
6161
7267
  if (l1Hit !== null) {
6162
- let isGenerationalStale = false;
6163
- if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
6164
- const tags = Object.keys(l1Hit.tagVersions);
6165
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
6166
- for (let i = 0; i < tags.length; i++) {
6167
- if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
6168
- isGenerationalStale = true;
6169
- break;
6170
- }
6171
- }
6172
- }
7268
+ const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
6173
7269
  if (isGenerationalStale) {
6174
7270
  this._deleteIfStale(k, l1Hit.setAt ?? 0);
6175
- } else {
7271
+ } else if (!l1Hit.isStale || optSwr > 0) {
6176
7272
  if (l1Hit.isStale) {
6177
7273
  const swrGraceMs2 = optSwr * 1e3;
6178
7274
  if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
@@ -6235,115 +7331,58 @@ var CacheService = class _CacheService {
6235
7331
  this.counters.stampedes++;
6236
7332
  this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch/read", { cacheKey });
6237
7333
  span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
6238
- return existing;
7334
+ return this._prepareReadValue(await existing);
6239
7335
  }
6240
7336
  const mutationEpochAtStart = this._getKeyMutationEpoch(k);
6241
- const executionPromise = (async () => {
7337
+ const executionPromise = Promise.resolve().then(async () => {
6242
7338
  try {
6243
- if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
6244
- if (this._isTombstonedByPattern(k)) {
6245
- try {
6246
- this.disk.delete(k);
6247
- } catch {
6248
- }
6249
- } else {
6250
- const isDiskAllowed = this.watchdog.isDiskAllowed();
6251
- if (isDiskAllowed) {
6252
- const diskStart = performance.now();
6253
- const diskHit = this.disk.load(k);
6254
- const diskElapsed = performance.now() - diskStart;
6255
- this.watchdog.recordDisk(diskElapsed);
6256
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6257
- if (diskHit !== null) {
6258
- let isDiskStale = false;
6259
- if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
6260
- const tags = Object.keys(diskHit.tagVersions);
6261
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
6262
- for (let i = 0; i < tags.length; i++) {
6263
- if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
6264
- isDiskStale = true;
6265
- break;
6266
- }
6267
- }
6268
- }
6269
- if (isDiskStale) {
6270
- this.disk.delete(k);
6271
- } else {
6272
- const promoted = this.l1.importEntries(
6273
- [{ key: k, entry: diskHit }],
6274
- this.opts.forbiddenSnapshotPrefixes
6275
- );
6276
- if (promoted > 0) {
6277
- const l1Check = this.l1.get(k);
6278
- if (l1Check !== null) {
6279
- this.counters.diskHits++;
6280
- this.opts.onHit?.(cacheKey, "disk");
6281
- this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
6282
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
6283
- if (this.opts.frozen) deepFreeze(l1Check.value);
6284
- return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
6285
- }
6286
- }
6287
- }
6288
- }
6289
- }
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
+ );
6290
7355
  }
7356
+ return diskHit.value;
6291
7357
  }
6292
7358
  if (!this._redisDisabled) {
6293
7359
  try {
6294
7360
  const client = await this.getRedis();
6295
7361
  const redisStart = performance.now();
6296
- if (this.opts.tagStrategy === "generational") {
6297
- const hashData = await client.hgetall(k);
6298
- const redisElapsed = performance.now() - redisStart;
6299
- this.watchdog.recordRedis(redisElapsed);
6300
- this.cb.onSuccess();
6301
- if (hashData && hashData.d) {
6302
- let isStale = false;
6303
- let storedTagVersions = {};
6304
- if (hashData.tv) {
6305
- try {
6306
- storedTagVersions = JSON.parse(hashData.tv);
6307
- } catch {
6308
- }
6309
- }
6310
- const tags = Object.keys(storedTagVersions);
6311
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
6312
- for (let i = 0; i < tags.length; i++) {
6313
- if (currentVers[i] > storedTagVersions[tags[i]]) {
6314
- isStale = true;
6315
- break;
6316
- }
6317
- }
6318
- if (isStale) {
6319
- const setAtMs = parseInt(hashData.t, 10) || 0;
6320
- this._deleteIfStale(k, setAtMs);
6321
- } else {
6322
- const parsed = await this._decryptAndDeserialize(hashData.d);
6323
- this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
6324
- this.counters.l2Hits++;
6325
- this.opts.onHit?.(cacheKey, "l2");
6326
- this.logger.debug("L2 hit (Redis hash)", { cacheKey });
6327
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
6328
- if (this.opts.frozen) deepFreeze(parsed);
6329
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
6330
- }
7362
+ const redisHit = await this._readRedisEntry(client, k, true);
7363
+ const redisElapsed = performance.now() - redisStart;
7364
+ this.watchdog.recordRedis(redisElapsed);
7365
+ this.cb.onSuccess();
7366
+ if (redisHit && !redisHit.stale && (redisHit.staleAt === void 0 || redisHit.staleAt > Date.now() || optSwr > 0)) {
7367
+ const parsed = redisHit.value;
7368
+ if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
7369
+ this.logger.debug("Aborting L2 promotion \u2014 key was mutated or deleted during Redis read", { cacheKey });
7370
+ span.setAttribute("cache.aborted_mutation_race", true);
7371
+ const current = this.l1.get(k);
7372
+ const liveVal = current && !current.isStale ? current.value : parsed;
7373
+ return liveVal;
6331
7374
  }
6332
- } else {
6333
- const raw = this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
6334
- const redisElapsed = performance.now() - redisStart;
6335
- this.watchdog.recordRedis(redisElapsed);
6336
- this.cb.onSuccess();
6337
- if (raw) {
6338
- const parsed = await this._decryptAndDeserialize(raw);
6339
- this.l1.set(k, parsed, ttlMs, priority);
6340
- this.counters.l2Hits++;
6341
- this.opts.onHit?.(cacheKey, "l2");
6342
- this.logger.debug("L2 hit (Redis)", { cacheKey });
6343
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
6344
- if (this.opts.frozen) deepFreeze(parsed);
6345
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
7375
+ if (!this._promoteRedisEntry(k, redisHit, ttlMs, priority)) throw new Error("Redis entry expired during promotion");
7376
+ this.counters.l2Hits++;
7377
+ this.opts.onHit?.(cacheKey, "l2");
7378
+ this.logger.debug(redisHit.tagVersions ? "L2 hit (Redis hash)" : "L2 hit (Redis)", { cacheKey });
7379
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
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);
6346
7384
  }
7385
+ return parsed;
6347
7386
  }
6348
7387
  } catch (err) {
6349
7388
  this.cb.onFailure();
@@ -6353,6 +7392,7 @@ var CacheService = class _CacheService {
6353
7392
  span.setAttribute("cache.hit", false).setAttribute("cache.hit_tier", "miss");
6354
7393
  this.opts.onMiss?.(cacheKey);
6355
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;
6356
7396
  const fetchStart = Date.now();
6357
7397
  let data;
6358
7398
  try {
@@ -6381,50 +7421,41 @@ var CacheService = class _CacheService {
6381
7421
  }
6382
7422
  const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
6383
7423
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
6384
- let activeTagVersions;
7424
+ const activeTagVersions = tagSnapshot;
6385
7425
  if (optTags?.length) {
6386
7426
  if (this.opts.tagStrategy === "generational") {
6387
- const vers = await Promise.all(optTags.map((tag) => this._getTagVersion(tag)));
6388
- activeTagVersions = {};
6389
- for (let i = 0; i < optTags.length; i++) {
6390
- activeTagVersions[optTags[i]] = vers[i];
6391
- }
7427
+ if (await this._isGenerationalEntryStale(tagSnapshot)) return data;
6392
7428
  } else {
6393
- await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
7429
+ await this._registerTags(k, optTags, Math.ceil(storeTtl / 1e3));
6394
7430
  }
6395
7431
  }
6396
7432
  if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
6397
7433
  this.logger.debug("Aborting in-flight cache commit \u2014 key was mutated or deleted during fetch", { cacheKey });
6398
7434
  span.setAttribute("cache.aborted_mutation_race", true);
6399
7435
  const current = this.l1.get(k);
6400
- if (current && !current.isStale && current.value !== void 0) {
7436
+ if (current && !current.isStale) {
6401
7437
  const freshVal = current.value;
6402
- if (this.opts.frozen) deepFreeze(freshVal);
6403
- return this.opts.cloneStrategy === "structuredClone" && freshVal != null && typeof freshVal === "object" ? structuredClone(freshVal) : freshVal;
7438
+ return freshVal;
6404
7439
  }
6405
- if (this.opts.frozen) deepFreeze(data);
6406
- return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
7440
+ return data;
6407
7441
  }
6408
- this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
6409
- if (!this._redisDisabled) {
7442
+ const writeTs = Date.now();
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") {
6410
7447
  try {
6411
- const client = await this.getRedis();
6412
- const serialized = JSON.stringify(data);
6413
- const toStore = await this._serializeAndEncrypt(serialized);
6414
- const ttlSec = Math.ceil(effectiveTtl / 1e3);
6415
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
6416
- const now = Date.now();
6417
- const tx = client.multi();
6418
- tx.hset(k, {
6419
- d: toStore,
6420
- t: String(now),
6421
- tv: JSON.stringify(activeTagVersions)
6422
- });
6423
- tx.expire(k, ttlSec);
6424
- await tx.exec();
6425
- } else {
6426
- await client.setex(k, ttlSec, toStore);
6427
- }
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
+ );
6428
7459
  this.cb.onSuccess();
6429
7460
  this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
6430
7461
  } catch {
@@ -6434,15 +7465,14 @@ var CacheService = class _CacheService {
6434
7465
  } else {
6435
7466
  this.logger.debug("Cached L1", { cacheKey });
6436
7467
  }
6437
- if (this.opts.frozen) deepFreeze(data);
6438
- return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
7468
+ return data;
6439
7469
  } finally {
6440
- this.inflight.delete(k);
7470
+ if (this.inflight.get(k) === executionPromise) this.inflight.delete(k);
6441
7471
  span.end();
6442
7472
  }
6443
- })();
7473
+ });
6444
7474
  this.inflight.set(k, executionPromise);
6445
- return executionPromise;
7475
+ return this._prepareReadValue(await executionPromise);
6446
7476
  }
6447
7477
  /**
6448
7478
  * Graceful shutdown flusher for Kubernetes preStop hooks, NestJS onApplicationShutdown,
@@ -6523,6 +7553,9 @@ var CacheService = class _CacheService {
6523
7553
  }
6524
7554
  async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority, knownTagVersions) {
6525
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;
6526
7559
  try {
6527
7560
  const fetchStart = Date.now();
6528
7561
  const data = await fetchFn();
@@ -6537,14 +7570,14 @@ var CacheService = class _CacheService {
6537
7570
  const l1Existing = this.l1.get(cacheKey);
6538
7571
  const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
6539
7572
  if (this.opts.tagStrategy === "generational" && tagVersionsSource) {
6540
- const tags = Object.keys(tagVersionsSource);
6541
- 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)));
6542
7575
  activeTagVersions = {};
6543
- for (let i = 0; i < tags.length; i++) {
6544
- activeTagVersions[tags[i]] = vers[i];
7576
+ for (let i = 0; i < tags2.length; i++) {
7577
+ activeTagVersions[tags2[i]] = vers[i];
6545
7578
  }
6546
7579
  if (knownTagVersions) {
6547
- for (const t of tags) {
7580
+ for (const t of tags2) {
6548
7581
  if (knownTagVersions[t] !== void 0 && activeTagVersions[t] !== knownTagVersions[t]) {
6549
7582
  this.logger.debug("SWR: aborting revalidation commit \u2014 tag version bumped during revalidation", { cacheKey, tag: t });
6550
7583
  return;
@@ -6556,32 +7589,29 @@ var CacheService = class _CacheService {
6556
7589
  this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
6557
7590
  return;
6558
7591
  }
6559
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
7592
+ const writeTs = Date.now();
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 });
6560
7596
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6561
7597
  try {
6562
- const client = await this.getRedis();
6563
- const s = JSON.stringify(data);
6564
- const stored = await this._serializeAndEncrypt(s);
6565
- const ttlSec = Math.ceil(ttlMs / 1e3);
6566
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
6567
- const now = Date.now();
6568
- const tx = client.multi();
6569
- tx.hset(cacheKey, {
6570
- d: stored,
6571
- t: String(now),
6572
- tv: JSON.stringify(activeTagVersions)
6573
- });
6574
- tx.expire(cacheKey, ttlSec);
6575
- await tx.exec();
6576
- } else {
6577
- await client.setex(cacheKey, ttlSec, stored);
6578
- }
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
+ );
6579
7609
  } catch {
6580
7610
  }
6581
7611
  }
6582
7612
  this.logger.debug("SWR: revalidation complete", { cacheKey });
6583
7613
  } catch (err) {
6584
- if (this.opts.staleIfError > 0) {
7614
+ if (this.opts.staleIfError > 0 && this._getKeyMutationEpoch(cacheKey) === startEpoch) {
6585
7615
  const additionalMs = this.opts.staleIfError * 1e3;
6586
7616
  this.l1.bumpExpiry(cacheKey, additionalMs);
6587
7617
  this.logger.debug("SWR: revalidation failed, stale-if-error extending expiry", {
@@ -6609,12 +7639,16 @@ var CacheService = class _CacheService {
6609
7639
  const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
6610
7640
  const p = priority ?? inferPriority(cacheKey);
6611
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;
6612
7645
  this._bumpKeyMutation(k);
7646
+ const epoch = this._getKeyMutationEpoch(k);
6613
7647
  this.inflight.delete(k);
6614
- this._pendingDiskDeletes.delete(k);
7648
+ this._invalidateDiskKey(k);
6615
7649
  this.counters.sets++;
6616
7650
  let activeTagVersions;
6617
- 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;
6618
7652
  if (tagsToRegister?.length) {
6619
7653
  if (this.opts.tagStrategy === "generational") {
6620
7654
  const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
@@ -6623,44 +7657,27 @@ var CacheService = class _CacheService {
6623
7657
  activeTagVersions[tagsToRegister[i]] = vers[i];
6624
7658
  }
6625
7659
  } else {
6626
- await this._registerTags(k, tagsToRegister, ttlSeconds);
6627
- }
6628
- }
6629
- this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
6630
- if (opts?.dependsOn?.length) {
6631
- for (const pattern of opts.dependsOn) {
6632
- const nsPattern = this.nk(pattern);
6633
- let deps = this.dependencyIndex.get(nsPattern);
6634
- if (!deps) {
6635
- deps = /* @__PURE__ */ new Set();
6636
- this.dependencyIndex.set(nsPattern, deps);
6637
- }
6638
- deps.add(k);
7660
+ await this._registerTags(k, tagsToRegister, effectiveTtlSeconds);
6639
7661
  }
6640
7662
  }
7663
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return;
7664
+ const writeTs = Date.now();
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);
6641
7668
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6642
7669
  try {
6643
- const client = await this.getRedis();
6644
- const s = JSON.stringify(data);
6645
- const stored = await this._serializeAndEncrypt(s);
6646
- const ttlSec = Math.ceil(ttlMs / 1e3);
6647
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
6648
- const now = Date.now();
6649
- const tx = client.multi();
6650
- tx.hset(k, {
6651
- d: stored,
6652
- t: String(now),
6653
- tv: JSON.stringify(activeTagVersions)
6654
- });
6655
- tx.expire(k, ttlSec);
6656
- await tx.exec();
6657
- } else {
6658
- if (this.opts.autoPipeline && this.pipeliner) {
6659
- await this.pipeliner.setex(k, ttlSec, stored);
6660
- } else {
6661
- await client.setex(k, ttlSec, stored);
6662
- }
6663
- }
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
+ );
6664
7681
  this.cb.onSuccess();
6665
7682
  } catch (err) {
6666
7683
  this.cb.onFailure();
@@ -6685,23 +7702,18 @@ var CacheService = class _CacheService {
6685
7702
  * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
6686
7703
  */
6687
7704
  async _registerTags(k, tags, ttlSeconds) {
6688
- for (const tag of tags) {
6689
- const tagKey = this.nk(`_tag_:${tag}`);
6690
- let members = this.tagIndex.get(tagKey);
6691
- if (!members) {
6692
- members = /* @__PURE__ */ new Set();
6693
- this.tagIndex.set(tagKey, members);
6694
- }
6695
- members.add(k);
6696
- }
7705
+ const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
7706
+ const expiresAt = Date.now() + effectiveTtl * 1e3;
7707
+ const uniqueTags = Array.from(new Set(tags));
7708
+ this._rememberTags(k, uniqueTags, expiresAt);
6697
7709
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6698
7710
  try {
6699
7711
  const client = await this.getRedis();
6700
7712
  const pl = client.pipeline();
6701
- for (const tag of tags) {
7713
+ for (const tag of uniqueTags) {
6702
7714
  const tagKey = this.nk(`_tag_:${tag}`);
6703
7715
  pl.sadd(tagKey, k);
6704
- pl.expire(tagKey, ttlSeconds + 3600);
7716
+ pl.expire(tagKey, effectiveTtl + 3600);
6705
7717
  }
6706
7718
  await pl.exec();
6707
7719
  this.cb.onSuccess();
@@ -6726,6 +7738,7 @@ var CacheService = class _CacheService {
6726
7738
  const k = this.nk(cacheKey);
6727
7739
  this.counters.deletes++;
6728
7740
  if (isPattern) {
7741
+ this._fenceInvalidation();
6729
7742
  const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6730
7743
  for (const liveKey of this.l1.liveKeys()) {
6731
7744
  if (liveKey.startsWith(pfx)) {
@@ -6738,29 +7751,30 @@ var CacheService = class _CacheService {
6738
7751
  this.inflight.delete(inflightKey);
6739
7752
  }
6740
7753
  }
6741
- this._addPatternTombstone(pfx);
7754
+ this._addPatternTombstone(k);
6742
7755
  this.l1.deletePattern(k);
7756
+ this._removePatternFromIndices(k);
7757
+ for (const ktKey of Array.from(this.keyTags.keys())) {
7758
+ if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
7759
+ }
7760
+ for (const kdKey of Array.from(this.keyDependencies.keys())) {
7761
+ if (this._matchesGlob(kdKey, k)) this._removeKeyDependencies(kdKey);
7762
+ }
6743
7763
  } else {
6744
7764
  this._bumpKeyMutation(k);
6745
7765
  this.inflight.delete(k);
6746
7766
  this.l1.delete(k);
6747
- this._pendingDiskDeletes.add(k);
6748
- setImmediate(() => {
6749
- try {
6750
- if (!this._diskDisabled) this.disk.delete(k);
6751
- } finally {
6752
- this._pendingDiskDeletes.delete(k);
6753
- }
6754
- });
7767
+ this._invalidateDiskKey(k);
7768
+ this._removeKeyTags(k);
6755
7769
  this._cascadeDependencies(k);
6756
- for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
7770
+ this._removeKeyDependencies(k);
6757
7771
  }
6758
7772
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6759
7773
  try {
6760
7774
  const client = await this.getRedis();
6761
7775
  if (isPattern) {
6762
7776
  const keys = await this._scanKeys(client, k);
6763
- if (keys.length > 0) await client.del(...keys);
7777
+ await this._deleteRedisKeys(client, keys);
6764
7778
  } else {
6765
7779
  if (this.opts.autoPipeline && this.pipeliner) {
6766
7780
  await this.pipeliner.del(k);
@@ -6807,7 +7821,7 @@ var CacheService = class _CacheService {
6807
7821
  async increment(cacheKey, ttlSeconds) {
6808
7822
  this._assertActive("increment");
6809
7823
  const k = this.nk(cacheKey);
6810
- if (this._redisDisabled) {
7824
+ if (this._redisDisabled || this.opts.l2WriteMode === "read-only") {
6811
7825
  if (!this._incrementFallbackWarned) {
6812
7826
  this._incrementFallbackWarned = true;
6813
7827
  this.logger.warn(
@@ -6822,6 +7836,15 @@ var CacheService = class _CacheService {
6822
7836
  entry.value++;
6823
7837
  return entry.value;
6824
7838
  }
7839
+ if (this._l1Counters.size >= 5e4 && !this._l1Counters.has(k)) {
7840
+ for (const [ck, cv] of this._l1Counters) {
7841
+ if (cv.expiresAt <= now) this._l1Counters.delete(ck);
7842
+ }
7843
+ if (this._l1Counters.size >= 5e4) {
7844
+ const oldest = this._l1Counters.keys().next().value;
7845
+ if (oldest !== void 0) this._l1Counters.delete(oldest);
7846
+ }
7847
+ }
6825
7848
  this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
6826
7849
  return 1;
6827
7850
  }
@@ -6854,6 +7877,7 @@ var CacheService = class _CacheService {
6854
7877
  this.counters.deletes++;
6855
7878
  const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
6856
7879
  if (k) {
7880
+ this._fenceInvalidation();
6857
7881
  const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6858
7882
  for (const liveKey of this.l1.liveKeys()) {
6859
7883
  if (liveKey.startsWith(pfx)) {
@@ -6866,8 +7890,9 @@ var CacheService = class _CacheService {
6866
7890
  this.inflight.delete(inflightKey);
6867
7891
  }
6868
7892
  }
6869
- this._addPatternTombstone(pfx);
7893
+ this._addPatternTombstone(k);
6870
7894
  this.l1.deletePattern(k);
7895
+ this._removePatternFromIndices(k);
6871
7896
  } else {
6872
7897
  this._globalEpoch++;
6873
7898
  this.inflight.clear();
@@ -6876,7 +7901,10 @@ var CacheService = class _CacheService {
6876
7901
  if (!this._diskDisabled) this.disk.clear();
6877
7902
  this._l1Counters.clear();
6878
7903
  this.tagIndex.clear();
7904
+ this.keyTags.clear();
6879
7905
  this.tagVersions.clear();
7906
+ this.dependencyIndex.clear();
7907
+ this.keyDependencies.clear();
6880
7908
  this._pendingDiskDeletes.clear();
6881
7909
  this._keyMutationEpochs.clear();
6882
7910
  }
@@ -6885,7 +7913,7 @@ var CacheService = class _CacheService {
6885
7913
  const client = await this.getRedis();
6886
7914
  const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
6887
7915
  const keys = await this._scanKeys(client, pattern);
6888
- if (keys.length > 0) await client.del(...keys);
7916
+ await this._deleteRedisKeys(client, keys);
6889
7917
  } catch (err) {
6890
7918
  this.logger.debug("clear: Redis unavailable", { error: err.message });
6891
7919
  }
@@ -7014,24 +8042,34 @@ var CacheService = class _CacheService {
7014
8042
  this._assertActive("scan");
7015
8043
  const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
7016
8044
  this.l1.scan((key, entry, pfx) => {
7017
- const value = entry.value !== void 0 ? entry.value : entry.data;
7018
- fn(key, value, pfx);
8045
+ fn(key, this._prepareReadValue(this.l1.resolveValue(entry)), pfx);
7019
8046
  }, prefixLen);
7020
8047
  }
7021
8048
  /**
7022
- * 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.
7023
8050
  * Returns `false` if the key is absent or already expired.
7024
8051
  *
7025
8052
  * @param newTtlSeconds - The new TTL from now, in seconds.
7026
8053
  */
7027
8054
  async touch(cacheKey, newTtlSeconds) {
7028
8055
  this._assertActive("touch");
8056
+ if (!Number.isFinite(newTtlSeconds) || newTtlSeconds <= 0) throw new Error("touch TTL must be finite and positive");
7029
8057
  const k = this.nk(cacheKey);
8058
+ const epoch = this._getKeyMutationEpoch(k);
7030
8059
  const hit = this.l1.touch(k, newTtlSeconds * 1e3);
7031
- if (hit && !this._redisDisabled) {
8060
+ const entry = this.l1.getEntry(k);
8061
+ if (hit) {
8062
+ const kt = this.keyTags.get(k);
8063
+ if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1e3;
8064
+ }
8065
+ if (hit && !this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7032
8066
  try {
7033
8067
  const client = await this.getRedis();
7034
- 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();
7035
8073
  } catch {
7036
8074
  }
7037
8075
  }
@@ -7053,7 +8091,12 @@ var CacheService = class _CacheService {
7053
8091
  const now = Date.now();
7054
8092
  if (entry.expiresAt <= now) return null;
7055
8093
  if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
7056
- 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));
8096
+ }
8097
+ _prepareReadValue(val) {
8098
+ if (this.opts.frozen) deepFreeze(val);
8099
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
7057
8100
  }
7058
8101
  /**
7059
8102
  * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
@@ -7066,59 +8109,36 @@ var CacheService = class _CacheService {
7066
8109
  async peek(cacheKey) {
7067
8110
  this._assertActive("peek");
7068
8111
  const k = this.nk(cacheKey);
8112
+ const epoch = this._getKeyMutationEpoch(k);
8113
+ this.counters.gets++;
7069
8114
  const l1Hit = this.l1.get(k);
7070
8115
  if (l1Hit !== null) {
7071
- this.counters.gets++;
7072
- this.counters.l1Hits++;
7073
- const val = l1Hit.value;
7074
- if (this.opts.frozen) deepFreeze(val);
7075
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
7076
- }
7077
- if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
7078
- if (this._isTombstonedByPattern(k)) {
7079
- try {
7080
- this.disk.delete(k);
7081
- } catch {
7082
- }
7083
- } else if (this.watchdog.isDiskAllowed()) {
7084
- const diskStart = performance.now();
7085
- const diskHit = this.disk.load(k);
7086
- const diskElapsed = performance.now() - diskStart;
7087
- this.watchdog.recordDisk(diskElapsed);
7088
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
7089
- if (diskHit !== null) {
7090
- const promoted = this.l1.importEntries(
7091
- [{ key: k, entry: diskHit }],
7092
- this.opts.forbiddenSnapshotPrefixes
7093
- );
7094
- if (promoted > 0) {
7095
- const l1Check = this.l1.get(k);
7096
- if (l1Check !== null) {
7097
- this.counters.gets++;
7098
- this.counters.diskHits++;
7099
- const val = l1Check.value;
7100
- if (this.opts.frozen) deepFreeze(val);
7101
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
7102
- }
7103
- }
7104
- }
8116
+ if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
8117
+ this._deleteIfStale(k, l1Hit.setAt ?? 0);
8118
+ } else {
8119
+ this.counters.l1Hits++;
8120
+ return this._prepareReadValue(l1Hit.value);
7105
8121
  }
7106
8122
  }
7107
- if (!this._redisDisabled && !this.cb.isOpen) {
8123
+ const diskHit = await this._readDiskEntry(k, epoch);
8124
+ if (diskHit) {
8125
+ this.counters.diskHits++;
8126
+ return this._prepareReadValue(diskHit.value);
8127
+ }
8128
+ if (!this._redisDisabled) {
7108
8129
  try {
7109
8130
  const client = await this.getRedis();
7110
8131
  const redisStart = performance.now();
7111
- const raw = await client.get(k);
8132
+ const redisHit = await this._readRedisEntry(client, k);
7112
8133
  const redisElapsed = performance.now() - redisStart;
7113
8134
  this.watchdog.recordRedis(redisElapsed);
7114
- if (raw !== null) {
7115
- const parsed = await this._decryptAndDeserialize(raw);
7116
- this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
7117
- this.counters.gets++;
8135
+ this.cb.onSuccess();
8136
+ if (redisHit && !redisHit.stale) {
8137
+ const parsed = redisHit.value;
8138
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return null;
8139
+ if (!this._promoteRedisEntry(k, redisHit, 6e4, inferPriority(cacheKey))) return null;
7118
8140
  this.counters.l2Hits++;
7119
- this.cb.onSuccess();
7120
- if (this.opts.frozen) deepFreeze(parsed);
7121
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
8141
+ return this._prepareReadValue(parsed);
7122
8142
  }
7123
8143
  } catch (err) {
7124
8144
  this.cb.onFailure();
@@ -7138,6 +8158,8 @@ var CacheService = class _CacheService {
7138
8158
  */
7139
8159
  async mget(keys, fetchFn, ttl = 300, priority) {
7140
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))]));
7141
8163
  const span = this._startSpan("tricache.mget");
7142
8164
  if (this.opts.tracer) {
7143
8165
  span.setAttribute("cache.batch.size", keys.length);
@@ -7146,12 +8168,20 @@ var CacheService = class _CacheService {
7146
8168
  const result = Array.from({ length: keys.length });
7147
8169
  const missIndexes = [];
7148
8170
  const missKeys = [];
8171
+ const now = Date.now();
7149
8172
  for (let i = 0; i < keys.length; i++) {
7150
8173
  const k = this.nk(keys[i]);
7151
8174
  const entry = this.l1.getEntry(k);
7152
- if (entry && entry.expiresAt > Date.now()) {
7153
- result[i] = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
7154
- this.counters.l1Hits++;
8175
+ if (entry && entry.expiresAt > now && (entry.staleAt === void 0 || entry.staleAt > now)) {
8176
+ if (await this._isGenerationalEntryStale(entry.tagVersions)) {
8177
+ this._deleteIfStale(k, entry.setAt ?? 0);
8178
+ missIndexes.push(i);
8179
+ missKeys.push(keys[i]);
8180
+ } else {
8181
+ const val = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
8182
+ result[i] = this._prepareReadValue(val);
8183
+ this.counters.l1Hits++;
8184
+ }
7155
8185
  } else {
7156
8186
  missIndexes.push(i);
7157
8187
  missKeys.push(keys[i]);
@@ -7171,30 +8201,24 @@ var CacheService = class _CacheService {
7171
8201
  try {
7172
8202
  const client = await this.getRedis();
7173
8203
  const nsKeys = missKeys.map((k) => this.nk(k));
7174
- const pipeline = client.multi();
7175
- for (const nk of nsKeys) pipeline.get(nk);
7176
- const redisStart = performance.now();
7177
- const raws = await pipeline.exec();
7178
- const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
7179
- this.watchdog.recordRedis(redisElapsed);
7180
- this.cb.onSuccess();
8204
+ const remoteEntries = await this._readRedisBatch(client, nsKeys);
7181
8205
  for (let j = 0; j < missKeys.length; j++) {
7182
- const raw = raws[j] ? raws[j][1] : null;
7183
8206
  const idx = missIndexes[j];
7184
- if (raw) {
7185
- const parsed = await this._decryptAndDeserialize(raw);
7186
- const k = nsKeys[j];
8207
+ const k = nsKeys[j];
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)) {
7187
8210
  const p = priority ?? inferPriority(missKeys[j]);
7188
- this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
8211
+ const ttlVal = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
8212
+ if (!this._promoteRedisEntry(k, entry, this._jitterTtl(ttlVal * 1e3), p)) continue;
7189
8213
  this.counters.l2Hits++;
7190
8214
  l2HitCount++;
7191
- result[idx] = parsed;
8215
+ result[idx] = this._prepareReadValue(entry.value);
7192
8216
  missIndexes[j] = -1;
7193
8217
  missKeys[j] = "";
7194
8218
  }
7195
8219
  }
7196
8220
  const remainingIdx = missIndexes.filter((i) => i >= 0);
7197
- const remainingKeys = missKeys.filter((k) => k !== "");
8221
+ const remainingKeys = missKeys.filter((_key, index) => missIndexes[index] >= 0);
7198
8222
  missIndexes.length = 0;
7199
8223
  missKeys.length = 0;
7200
8224
  missIndexes.push(...remainingIdx);
@@ -7207,58 +8231,64 @@ var CacheService = class _CacheService {
7207
8231
  if (!this._diskDisabled && missKeys.length > 0) {
7208
8232
  for (let j = missKeys.length - 1; j >= 0; j--) {
7209
8233
  const k = this.nk(missKeys[j]);
7210
- if (this._pendingDiskDeletes.has(k)) continue;
7211
- if (this._isTombstonedByPattern(k)) {
7212
- try {
7213
- this.disk.delete(k);
7214
- } catch {
7215
- }
7216
- continue;
7217
- }
7218
- if (!this.watchdog.isDiskAllowed()) continue;
7219
- const diskStart = performance.now();
7220
- const diskHit = this.disk.load(k);
7221
- const diskElapsed = performance.now() - diskStart;
7222
- this.watchdog.recordDisk(diskElapsed);
7223
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
7224
- if (diskHit !== null) {
7225
- const promoted = this.l1.importEntries(
7226
- [{ key: k, entry: diskHit }],
7227
- this.opts.forbiddenSnapshotPrefixes
7228
- );
7229
- if (promoted > 0) {
7230
- const l1Check = this.l1.get(k);
7231
- if (l1Check !== null) {
7232
- this.counters.diskHits++;
7233
- result[missIndexes[j]] = l1Check.value;
7234
- missIndexes.splice(j, 1);
7235
- missKeys.splice(j, 1);
7236
- }
7237
- }
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);
7238
8240
  }
7239
8241
  }
7240
8242
  }
7241
8243
  if (missKeys.length > 0 && fetchFn) {
7242
- this.counters.fetches++;
7243
- const fetched = await fetchFn(missKeys);
7244
- const isMap = fetched instanceof Map;
7245
- const setPromises = [];
8244
+ const owned = /* @__PURE__ */ new Map();
8245
+ const waiting = [];
7246
8246
  for (let j = 0; j < missKeys.length; j++) {
7247
- const k = missKeys[j];
7248
- const v = isMap ? fetched.get(k) : fetched[k];
7249
- result[missIndexes[j]] = v;
7250
- if (v !== void 0 && v !== null) {
7251
- const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
7252
- setPromises.push(this.set(k, v, resolvedTtl, priority));
7253
- } else if (v == null && this.opts.notFoundTtl > 0) {
7254
- setPromises.push(this.set(k, null, this.opts.notFoundTtl, priority));
7255
- } else if (v === null) {
7256
- const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
7257
- 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++;
7258
8261
  }
8262
+ const index = missIndexes[j];
8263
+ waiting.push(promise.then((value) => {
8264
+ result[index] = this._prepareReadValue(value);
8265
+ }));
7259
8266
  }
7260
- if (setPromises.length > 0) {
7261
- 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
+ }
7262
8292
  }
7263
8293
  }
7264
8294
  if (this.opts.tracer) {
@@ -7311,7 +8341,7 @@ var CacheService = class _CacheService {
7311
8341
  try {
7312
8342
  await Promise.all(keys.map((key) => {
7313
8343
  const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
7314
- const hasOpts = tags?.length || dependsOn?.length;
8344
+ const hasOpts = tags !== void 0 || dependsOn !== void 0;
7315
8345
  return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
7316
8346
  }));
7317
8347
  } catch (err) {
@@ -7363,26 +8393,21 @@ var CacheService = class _CacheService {
7363
8393
  try {
7364
8394
  const client = await this.getRedis();
7365
8395
  const nsPattern = this.nk(pattern);
7366
- 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
+ });
7367
8400
  if (matchedKeys.length === 0) {
7368
8401
  this.cb.onSuccess();
7369
8402
  return 0;
7370
8403
  }
7371
- const pl = client.pipeline();
7372
- for (const k of matchedKeys) pl.get(k);
7373
- const results = await pl.exec();
7374
- this.cb.onSuccess();
8404
+ const epochs = new Map(matchedKeys.map((key) => [key, this._getKeyMutationEpoch(key)]));
8405
+ const results = await this._readRedisBatch(client, matchedKeys);
7375
8406
  let loaded = 0;
7376
- for (let i = 0; i < matchedKeys.length; i++) {
7377
- const [err, raw] = results[i];
7378
- if (err || raw == null) continue;
7379
- try {
7380
- const parsed = await this._decryptAndDeserialize(raw);
7381
- const remainingMs = 10 * 60 * 1e3;
7382
- this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
7383
- loaded++;
7384
- } catch {
7385
- }
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++;
7386
8411
  }
7387
8412
  this.logger.info("warmFromL2 complete", {
7388
8413
  pattern,
@@ -7455,6 +8480,139 @@ var CacheService = class _CacheService {
7455
8480
  }
7456
8481
  return matched;
7457
8482
  }
8483
+ async _publishTagInvalidation(op, key, tagVersion) {
8484
+ if (this.opts.awaitInvalidationBackplane) {
8485
+ await this.publishInvalidation(op, key, tagVersion, false, true);
8486
+ } else {
8487
+ void this.publishInvalidation(op, key, tagVersion, false, true);
8488
+ }
8489
+ }
8490
+ _removeTagMembersLocal(keys) {
8491
+ const keyList = Array.isArray(keys) ? keys : Array.from(keys);
8492
+ for (const k of keyList) {
8493
+ this.l1.delete(k);
8494
+ this._bumpKeyMutation(k);
8495
+ this._removeKeyTags(k);
8496
+ this._removeKeyDependencies(k);
8497
+ this._invalidateDiskKey(k);
8498
+ }
8499
+ }
8500
+ /**
8501
+ * Executes invalidation for a single already-resolved concrete tag without
8502
+ * wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
8503
+ */
8504
+ async _invalidateConcreteTag(tag) {
8505
+ this._fenceInvalidation();
8506
+ if (this.opts.tagStrategy === "generational") {
8507
+ let newVer = 1;
8508
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
8509
+ try {
8510
+ const client = await this.getRedis();
8511
+ newVer = await client.incr(this.nk(`tag_ver:${tag}`));
8512
+ } catch (err) {
8513
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
8514
+ const current = this.tagVersions.get(tag)?.version ?? 0;
8515
+ newVer = current + 1;
8516
+ }
8517
+ } else {
8518
+ const current = this.tagVersions.get(tag)?.version ?? 0;
8519
+ newVer = current + 1;
8520
+ }
8521
+ this._setLocalTagVersion(tag, newVer, performance.now());
8522
+ await this._publishTagInvalidation("tag_incr", tag, newVer);
8523
+ return;
8524
+ }
8525
+ const tagKey = this.nk(`_tag_:${tag}`);
8526
+ const members = new Set(this.tagIndex.get(tagKey) ?? []);
8527
+ this.tagIndex.delete(tagKey);
8528
+ this._removeTagMembersLocal(members);
8529
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
8530
+ try {
8531
+ const client = await this.getRedis();
8532
+ const redisMembers = await client.smembers(tagKey);
8533
+ for (const key of redisMembers) members.add(key);
8534
+ this._removeTagMembersLocal(redisMembers);
8535
+ const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers, tagKey])];
8536
+ await this._deleteRedisKeys(client, toDelete);
8537
+ } catch (err) {
8538
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
8539
+ }
8540
+ }
8541
+ await Promise.all([...members].map((key) => this._publishTagInvalidation("del", key)));
8542
+ await this._publishTagInvalidation("tag_pattern_del", tag);
8543
+ }
8544
+ /**
8545
+ * Executes invalidation for an array of already-resolved concrete tags
8546
+ * without re-entering wildcard/cascade resolution or invalidateTag().
8547
+ */
8548
+ async _invalidateConcreteTags(tags) {
8549
+ if (tags.length === 0) return;
8550
+ if (tags.length === 1) {
8551
+ await this._invalidateConcreteTag(tags[0]);
8552
+ return;
8553
+ }
8554
+ this._fenceInvalidation();
8555
+ if (this.opts.tagStrategy === "generational") {
8556
+ const now = performance.now();
8557
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
8558
+ try {
8559
+ const client = await this.getRedis();
8560
+ const pl = client.pipeline();
8561
+ for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
8562
+ const results = await pl.exec();
8563
+ for (let i = 0; i < tags.length; i++) {
8564
+ const [err, newVer] = results[i] ?? [null, null];
8565
+ const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
8566
+ this._setLocalTagVersion(tags[i], ver, now);
8567
+ await this._publishTagInvalidation("tag_incr", tags[i], ver);
8568
+ }
8569
+ return;
8570
+ } catch (err) {
8571
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
8572
+ }
8573
+ }
8574
+ for (const tag of tags) {
8575
+ const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
8576
+ this._setLocalTagVersion(tag, ver, now);
8577
+ await this._publishTagInvalidation("tag_incr", tag, ver);
8578
+ }
8579
+ return;
8580
+ }
8581
+ const tagKeys = [];
8582
+ const allMembers = /* @__PURE__ */ new Set();
8583
+ for (const tag of tags) {
8584
+ const tagKey = this.nk(`_tag_:${tag}`);
8585
+ tagKeys.push(tagKey);
8586
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
8587
+ for (const k of members) allMembers.add(k);
8588
+ this.tagIndex.delete(tagKey);
8589
+ }
8590
+ this._removeTagMembersLocal(allMembers);
8591
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
8592
+ try {
8593
+ const client = await this.getRedis();
8594
+ const pl = client.pipeline();
8595
+ for (const tagKey of tagKeys) pl.smembers(tagKey);
8596
+ const smResults = await pl.exec();
8597
+ const toDelete = [...allMembers];
8598
+ for (const [err, redisMembers] of smResults) {
8599
+ if (!err && redisMembers) {
8600
+ for (const k of redisMembers) {
8601
+ if (!allMembers.has(k)) toDelete.push(k);
8602
+ allMembers.add(k);
8603
+ }
8604
+ }
8605
+ }
8606
+ const keysToRemove = [...toDelete, ...tagKeys];
8607
+ await this._deleteRedisKeys(client, keysToRemove);
8608
+ this._removeTagMembersLocal(allMembers);
8609
+ } catch (err) {
8610
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
8611
+ }
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);
8615
+ }
7458
8616
  /**
7459
8617
  * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
7460
8618
  * Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
@@ -7490,68 +8648,13 @@ var CacheService = class _CacheService {
7490
8648
  const delim = this.opts.tagHierarchyDelimiter;
7491
8649
  const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
7492
8650
  if (matchedTags.size > 0) {
7493
- await this.invalidateTags(Array.from(matchedTags));
8651
+ await this._invalidateConcreteTags(Array.from(matchedTags));
7494
8652
  }
7495
8653
  const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
7496
- if (this.opts.awaitInvalidationBackplane) {
7497
- await this.publishInvalidation(op, broadcastPattern, void 0, false, true);
7498
- } else {
7499
- void this.publishInvalidation(op, broadcastPattern, void 0, false, true);
7500
- }
8654
+ await this._publishTagInvalidation(op, broadcastPattern);
7501
8655
  return;
7502
8656
  }
7503
- if (this.opts.tagStrategy === "generational") {
7504
- let newVer = 1;
7505
- if (!this._redisDisabled) {
7506
- try {
7507
- const client = await this.getRedis();
7508
- newVer = await client.incr(this.nk(`tag_ver:${tag}`));
7509
- } catch (err) {
7510
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7511
- const current = this.tagVersions.get(tag)?.version ?? 0;
7512
- newVer = current + 1;
7513
- }
7514
- } else {
7515
- const current = this.tagVersions.get(tag)?.version ?? 0;
7516
- newVer = current + 1;
7517
- }
7518
- this._setLocalTagVersion(tag, newVer, performance.now());
7519
- if (this.opts.awaitInvalidationBackplane) {
7520
- await this.publishInvalidation("tag_incr", tag, newVer, false, true);
7521
- } else {
7522
- void this.publishInvalidation("tag_incr", tag, newVer, false, true);
7523
- }
7524
- return;
7525
- }
7526
- const tagKey = this.nk(`_tag_:${tag}`);
7527
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
7528
- for (const k of members) {
7529
- this.l1.delete(k);
7530
- this._bumpKeyMutation(k);
7531
- this._pendingDiskDeletes.add(k);
7532
- setImmediate(() => {
7533
- try {
7534
- if (!this._diskDisabled) this.disk.delete(k);
7535
- } finally {
7536
- this._pendingDiskDeletes.delete(k);
7537
- }
7538
- });
7539
- }
7540
- this.tagIndex.delete(tagKey);
7541
- if (!this._redisDisabled) {
7542
- try {
7543
- const client = await this.getRedis();
7544
- const redisMembers = await client.smembers(tagKey);
7545
- const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
7546
- if (toDelete.length > 0) {
7547
- await client.del(...toDelete, tagKey);
7548
- } else {
7549
- await client.del(tagKey);
7550
- }
7551
- } catch (err) {
7552
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7553
- }
7554
- }
8657
+ await this._invalidateConcreteTag(tag);
7555
8658
  } catch (err) {
7556
8659
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
7557
8660
  span.recordException?.(err);
@@ -7578,96 +8681,28 @@ var CacheService = class _CacheService {
7578
8681
  const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
7579
8682
  if (hasWildcards || shouldCascade) {
7580
8683
  const allResolvedTags = /* @__PURE__ */ new Set();
8684
+ const broadcastPatterns = /* @__PURE__ */ new Set();
8685
+ const delim = this.opts.tagHierarchyDelimiter;
7581
8686
  for (const t of tags) {
7582
- if (isWildcardTag(t) || shouldCascade) {
8687
+ const tIsPattern = isWildcardTag(t);
8688
+ if (tIsPattern || shouldCascade) {
8689
+ broadcastPatterns.add(tIsPattern ? t : `${t}${delim}*`);
7583
8690
  const resolved = await this._resolveMatchingTags(t, shouldCascade);
7584
8691
  for (const rt of resolved) allResolvedTags.add(rt);
7585
8692
  } else {
7586
8693
  allResolvedTags.add(t);
7587
8694
  }
7588
8695
  }
7589
- if (allResolvedTags.size === 0) return;
7590
- tags = Array.from(allResolvedTags);
7591
- }
7592
- if (tags.length === 1) {
7593
- await this.invalidateTag(tags[0], opts);
7594
- return;
7595
- }
7596
- if (this.opts.tagStrategy === "generational") {
7597
- const now = performance.now();
7598
- if (!this._redisDisabled) {
7599
- try {
7600
- const client = await this.getRedis();
7601
- const pl = client.pipeline();
7602
- for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
7603
- const results = await pl.exec();
7604
- for (let i = 0; i < tags.length; i++) {
7605
- const [err, newVer] = results[i] ?? [null, null];
7606
- const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
7607
- this._setLocalTagVersion(tags[i], ver, now);
7608
- if (this.opts.awaitInvalidationBackplane) {
7609
- await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7610
- } else {
7611
- void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7612
- }
7613
- }
7614
- return;
7615
- } catch (err) {
7616
- this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7617
- }
8696
+ if (allResolvedTags.size > 0) {
8697
+ await this._invalidateConcreteTags(Array.from(allResolvedTags));
7618
8698
  }
7619
- for (const tag of tags) {
7620
- const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
7621
- this._setLocalTagVersion(tag, ver, now);
7622
- if (this.opts.awaitInvalidationBackplane) {
7623
- await this.publishInvalidation("tag_incr", tag, ver, false, true);
7624
- } else {
7625
- void this.publishInvalidation("tag_incr", tag, ver, false, true);
7626
- }
8699
+ const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
8700
+ for (const pattern of broadcastPatterns) {
8701
+ await this._publishTagInvalidation(op, pattern);
7627
8702
  }
7628
8703
  return;
7629
8704
  }
7630
- const tagKeys = [];
7631
- const allMembers = /* @__PURE__ */ new Set();
7632
- for (const tag of tags) {
7633
- const tagKey = this.nk(`_tag_:${tag}`);
7634
- tagKeys.push(tagKey);
7635
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
7636
- for (const k of members) allMembers.add(k);
7637
- this.tagIndex.delete(tagKey);
7638
- }
7639
- for (const k of allMembers) {
7640
- this.l1.delete(k);
7641
- this._bumpKeyMutation(k);
7642
- this._pendingDiskDeletes.add(k);
7643
- setImmediate(() => {
7644
- try {
7645
- if (!this._diskDisabled) this.disk.delete(k);
7646
- } finally {
7647
- this._pendingDiskDeletes.delete(k);
7648
- }
7649
- });
7650
- }
7651
- if (!this._redisDisabled) {
7652
- try {
7653
- const client = await this.getRedis();
7654
- const pl = client.pipeline();
7655
- for (const tagKey of tagKeys) pl.smembers(tagKey);
7656
- const smResults = await pl.exec();
7657
- const toDelete = [...allMembers];
7658
- for (const [err, redisMembers] of smResults) {
7659
- if (!err && redisMembers) {
7660
- for (const k of redisMembers) {
7661
- if (!allMembers.has(k)) toDelete.push(k);
7662
- }
7663
- }
7664
- }
7665
- const keysToRemove = [...toDelete, ...tagKeys];
7666
- if (keysToRemove.length > 0) await client.del(...keysToRemove);
7667
- } catch (err) {
7668
- this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7669
- }
7670
- }
8705
+ await this._invalidateConcreteTags(Array.from(new Set(tags)));
7671
8706
  }
7672
8707
  /**
7673
8708
  * Get the current generational tag version for a tag (synced with Redis when due).
@@ -7730,19 +8765,23 @@ var CacheService = class _CacheService {
7730
8765
  const diskLowSpace = !this._diskDisabled && this.disk.hostVolumeLowSpace;
7731
8766
  const circuitOpen = this.cb.isOpen;
7732
8767
  const latencyBypass = watchdogTel.bypassActive;
7733
- const degraded = circuitOpen || latencyBypass || diskPruning || diskLowSpace;
7734
- 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);
7735
8771
  const reasons = [];
7736
8772
  if (circuitOpen) reasons.push("redis_circuit_breaker_open");
7737
8773
  if (latencyBypass) reasons.push(`disk_latency_bypass_stage_${watchdogTel.bypassStage}`);
7738
8774
  if (diskPruning) reasons.push("disk_quota_watermark_pruning_active");
7739
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");
7740
8778
  return {
7741
8779
  healthy,
7742
8780
  degraded,
7743
8781
  reasons,
7744
8782
  details: {
7745
- redisConnected: !circuitOpen && !this._redisDisabled,
8783
+ redisConnected: !this._destroyed && !circuitOpen && !!this.redis && (this.redis.status === "ready" || this.redis.isOpen === true),
8784
+ backplaneReady: this._backplaneAvailable,
7746
8785
  circuitBreakerState: this.cb.currentState,
7747
8786
  diskPruningActive: diskPruning,
7748
8787
  diskHostVolumeLowSpace: diskLowSpace,
@@ -7764,23 +8803,28 @@ var CacheService = class _CacheService {
7764
8803
  */
7765
8804
  async drainToL2() {
7766
8805
  this._assertActive("drainToL2");
7767
- if (this._redisDisabled) return 0;
8806
+ if (this._redisDisabled || this.opts.l2WriteMode === "read-only") return 0;
7768
8807
  try {
7769
- const client = await this.getRedis();
7770
8808
  const entries = this.l1.exportEntries([]);
7771
- const now = Date.now();
7772
8809
  if (entries.length === 0) return 0;
7773
- const pl = client.pipeline();
7774
- for (const { key, entry } of entries) {
7775
- const remainingMs = entry.expiresAt - now;
7776
- if (remainingMs <= 0) continue;
7777
- const ttlSecs = Math.max(1, Math.ceil(remainingMs / 1e3));
7778
- const s = JSON.stringify(entry.value);
7779
- const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
7780
- pl.setex(key, ttlSecs, stored);
7781
- }
7782
- await pl.exec();
7783
- 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;
7784
8828
  } catch (err) {
7785
8829
  this.logger.debug("drainToL2: Redis unavailable", { error: err.message });
7786
8830
  return 0;
@@ -7810,7 +8854,7 @@ var CacheService = class _CacheService {
7810
8854
  this._assertActive("setIfAbsent");
7811
8855
  const k = this.nk(cacheKey);
7812
8856
  if (this.l1.has(k)) return false;
7813
- if (!this._redisDisabled) {
8857
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7814
8858
  try {
7815
8859
  const client = await this.getRedis();
7816
8860
  const serialized = JSON.stringify(value);
@@ -7827,7 +8871,7 @@ var CacheService = class _CacheService {
7827
8871
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
7828
8872
  const p = priority ?? inferPriority(cacheKey);
7829
8873
  this._bumpKeyMutation(k);
7830
- this._pendingDiskDeletes.delete(k);
8874
+ this._invalidateDiskKey(k);
7831
8875
  this.l1.set(k, value, ttlMs, p);
7832
8876
  this.counters.sets++;
7833
8877
  return true;
@@ -7854,7 +8898,7 @@ var CacheService = class _CacheService {
7854
8898
  const token = import_crypto3.default.randomUUID();
7855
8899
  const deadline = Date.now() + acquireTimeout;
7856
8900
  let acquired = false;
7857
- if (!this._redisDisabled) {
8901
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7858
8902
  let client = null;
7859
8903
  try {
7860
8904
  client = await this.getRedis();
@@ -7949,7 +8993,9 @@ var CacheService = class _CacheService {
7949
8993
  const gDiskFiles = meter.createObservableGauge("tricache.disk.files", { description: "Current L1.5 disk file count" });
7950
8994
  const gDiskBytes = meter.createObservableGauge("tricache.disk.bytes", { description: "Current L1.5 disk size in bytes" });
7951
8995
  const gBloomFpr = meter.createObservableGauge("tricache.bloom.fpr", { description: "Bloom filter false-positive rate" });
7952
- meter.addBatchObservableCallback((observableResult) => {
8996
+ const observables = [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr];
8997
+ const callback = (observableResult) => {
8998
+ if (this._destroyed) return;
7953
8999
  const stats = this.stats();
7954
9000
  const l1 = stats.l1;
7955
9001
  const disk = stats.disk;
@@ -7962,7 +9008,9 @@ var CacheService = class _CacheService {
7962
9008
  observableResult.observe(gDiskFiles, disk.files, attrs);
7963
9009
  observableResult.observe(gDiskBytes, disk.sizeKB * 1024, attrs);
7964
9010
  observableResult.observe(gBloomFpr, fpr, attrs);
7965
- }, [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr]);
9011
+ };
9012
+ meter.addBatchObservableCallback(callback, observables);
9013
+ this._otelCleanup = () => meter.removeBatchObservableCallback?.(callback, observables);
7966
9014
  } catch (err) {
7967
9015
  this.logger.warn("Failed to initialize OpenTelemetry metrics meter", { error: err.message });
7968
9016
  }
@@ -8232,8 +9280,25 @@ var CacheService = class _CacheService {
8232
9280
  /** Close Redis connections and stop all background timers. */
8233
9281
  async destroy() {
8234
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();
8235
9293
  this._pendingDiskDeletes.clear();
8236
9294
  this._keyMutationEpochs.clear();
9295
+ this.inflight.clear();
9296
+ this.revalidating.clear();
9297
+ this._l1Counters.clear();
9298
+ this.tagIndex.clear();
9299
+ this.keyTags.clear();
9300
+ this.dependencyIndex.clear();
9301
+ this.keyDependencies.clear();
8237
9302
  const g = globalThis;
8238
9303
  const key = _CacheService.globalKey(this.opts);
8239
9304
  if (g[key] === this) {
@@ -8254,6 +9319,12 @@ var CacheService = class _CacheService {
8254
9319
  this._workerPool = null;
8255
9320
  }
8256
9321
  if (this.subClient) {
9322
+ if (this.opts.redisSubClient) {
9323
+ try {
9324
+ await this.subClient.unsubscribe?.(this.backplaneChannel);
9325
+ } catch {
9326
+ }
9327
+ }
8257
9328
  if (!this.opts.redisSubClient) {
8258
9329
  try {
8259
9330
  this.subClient.disconnect();
@@ -8263,7 +9334,7 @@ var CacheService = class _CacheService {
8263
9334
  this.subClient = null;
8264
9335
  }
8265
9336
  if (this.streamClient) {
8266
- try {
9337
+ if (!this.opts.redisSubClient) try {
8267
9338
  this.streamClient.disconnect();
8268
9339
  } catch {
8269
9340
  }
@@ -8531,185 +9602,118 @@ function createMemorySnapshotAdapter() {
8531
9602
  };
8532
9603
  }
8533
9604
 
8534
- // src/cross-region.ts
8535
- function createHttpMeshRelay(options) {
8536
- const peerUrls = options.peerUrls;
8537
- const timeoutMs = options.timeoutMs ?? 3e3;
8538
- const fetcher = options.fetchFn ?? globalThis.fetch;
8539
- const headers = {
8540
- "Content-Type": "application/json"
8541
- };
8542
- if (options.authSecret) {
8543
- headers["Authorization"] = `Bearer ${options.authSecret}`;
8544
- headers["X-TriCache-Auth"] = options.authSecret;
8545
- }
8546
- return {
8547
- async broadcast(event) {
8548
- if (!peerUrls.length) return;
8549
- const body = JSON.stringify(event);
8550
- await Promise.allSettled(
8551
- peerUrls.map(async (url) => {
8552
- const res = await fetcher(url, {
8553
- method: "POST",
8554
- headers,
8555
- body,
8556
- signal: AbortSignal.timeout(timeoutMs)
8557
- });
8558
- if (!res.ok) {
8559
- throw new Error(`HttpMeshRelay: peer ${url} returned HTTP ${res.status} ${res.statusText}`);
8560
- }
8561
- })
8562
- );
8563
- }
8564
- };
8565
- }
8566
- function createCustomCrossRegionRelay(relay) {
8567
- return relay;
8568
- }
8569
- function createMemoryCrossRegionRelay() {
8570
- const handlers = /* @__PURE__ */ new Map();
8571
- let broadcastCount = 0;
8572
- return {
8573
- async broadcast(event) {
8574
- broadcastCount++;
8575
- const promises = [];
8576
- for (const [region, set] of handlers.entries()) {
8577
- if (region !== event.originRegion) {
8578
- for (const fn of set) {
8579
- promises.push(Promise.resolve(fn(event)));
8580
- }
8581
- }
8582
- }
8583
- await Promise.allSettled(promises);
8584
- },
8585
- register(region, handler) {
8586
- if (!handlers.has(region)) {
8587
- handlers.set(region, /* @__PURE__ */ new Set());
8588
- }
8589
- handlers.get(region).add(handler);
8590
- return () => {
8591
- 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;
8592
9615
  };
8593
- },
8594
- getBroadcastCount() {
8595
- return broadcastCount;
8596
- },
8597
- clear() {
8598
- handlers.clear();
8599
- broadcastCount = 0;
8600
- }
8601
- };
8602
- }
8603
- function createCrossRegionWebhookHandler(cache, options = {}) {
8604
- return async function handleCrossRegionWebhook(req) {
8605
- if (options.authSecret) {
8606
- const authHeader = req.headers["authorization"] ?? req.headers["Authorization"];
8607
- const customHeader = req.headers["x-tricache-auth"] ?? req.headers["X-TriCache-Auth"];
8608
- const bearer = typeof authHeader === "string" && authHeader.startsWith("Bearer ") ? authHeader.slice(7).trim() : authHeader;
8609
- const provided = typeof customHeader === "string" ? customHeader : bearer;
8610
- if (!provided || provided !== options.authSecret) {
8611
- return {
8612
- status: 401,
8613
- body: { ok: false, message: "Unauthorized: invalid or missing auth secret" }
8614
- };
8615
- }
8616
9616
  }
8617
- try {
8618
- let event;
8619
- if (typeof req.body === "string") {
8620
- event = JSON.parse(req.body);
8621
- } else if (req.body && typeof req.body === "object") {
8622
- event = req.body;
8623
- } else {
8624
- return {
8625
- status: 400,
8626
- body: { ok: false, message: "Invalid payload: body must be JSON object" }
8627
- };
8628
- }
8629
- const accepted = await cache.receiveCrossRegionInvalidation(event);
8630
- return {
8631
- status: 200,
8632
- body: { ok: true, message: accepted ? "Invalidation applied" : "Invalidation ignored (deduplicated or self)" }
8633
- };
8634
- } catch (err) {
8635
- return {
8636
- status: 400,
8637
- 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;
8638
9623
  };
8639
9624
  }
8640
- };
8641
- }
8642
-
8643
- // src/adapters/node-redis.ts
8644
- var import_node_events = require("events");
8645
- var NodeRedisPipelineAdapter = class {
9625
+ }
9626
+ transactional;
8646
9627
  multiInstance;
8647
- constructor(multiInstance) {
8648
- 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));
8649
9634
  }
8650
9635
  get(key) {
8651
- this.multiInstance.get(key);
9636
+ this.queueCommand("get", [key]);
8652
9637
  return this;
8653
9638
  }
8654
9639
  set(key, value, ...args) {
8655
9640
  const opts = parseSetArgs(args);
8656
9641
  if (opts) {
8657
- this.multiInstance.set(key, value, opts);
9642
+ this.queueCommand("set", [key, value, opts]);
8658
9643
  } else {
8659
- this.multiInstance.set(key, value);
9644
+ this.queueCommand("set", [key, value]);
8660
9645
  }
8661
9646
  return this;
8662
9647
  }
8663
9648
  setex(key, seconds, value) {
8664
9649
  if (typeof this.multiInstance.setEx === "function") {
8665
- this.multiInstance.setEx(key, seconds, value);
9650
+ this.queueCommand("setEx", [key, seconds, value]);
8666
9651
  } else if (typeof this.multiInstance.setex === "function") {
8667
- this.multiInstance.setex(key, seconds, value);
9652
+ this.queueCommand("setex", [key, seconds, value]);
8668
9653
  } else {
8669
- this.multiInstance.set(key, value, { EX: seconds });
9654
+ this.queueCommand("set", [key, value, { EX: seconds }]);
8670
9655
  }
8671
9656
  return this;
8672
9657
  }
8673
9658
  del(...keys) {
8674
9659
  if (keys.length === 0) return this;
8675
- this.multiInstance.del(keys.length === 1 ? keys[0] : keys);
9660
+ this.queueCommand("del", [keys.length === 1 ? keys[0] : keys]);
8676
9661
  return this;
8677
9662
  }
8678
9663
  expire(key, seconds) {
8679
- this.multiInstance.expire(key, seconds);
9664
+ this.queueCommand("expire", [key, seconds]);
8680
9665
  return this;
8681
9666
  }
8682
9667
  incr(key) {
8683
- this.multiInstance.incr(key);
9668
+ this.queueCommand("incr", [key]);
8684
9669
  return this;
8685
9670
  }
8686
9671
  sadd(key, ...members) {
8687
9672
  if (members.length === 0) return this;
8688
9673
  if (typeof this.multiInstance.sAdd === "function") {
8689
- this.multiInstance.sAdd(key, members.length === 1 ? members[0] : members);
9674
+ this.queueCommand("sAdd", [key, members.length === 1 ? members[0] : members]);
8690
9675
  } else {
8691
- this.multiInstance.sadd(key, ...members);
9676
+ this.queueCommand("sadd", [key, ...members]);
8692
9677
  }
8693
9678
  return this;
8694
9679
  }
8695
9680
  smembers(key) {
8696
9681
  if (typeof this.multiInstance.sMembers === "function") {
8697
- this.multiInstance.sMembers(key);
9682
+ this.queueCommand("sMembers", [key]);
8698
9683
  } else {
8699
- this.multiInstance.smembers(key);
9684
+ this.queueCommand("smembers", [key]);
8700
9685
  }
8701
9686
  return this;
8702
9687
  }
8703
9688
  hset(key, value) {
8704
9689
  if (typeof this.multiInstance.hSet === "function") {
8705
- this.multiInstance.hSet(key, value);
9690
+ this.queueCommand("hSet", [key, value]);
8706
9691
  } else {
8707
- this.multiInstance.hset(key, value);
9692
+ this.queueCommand("hset", [key, value]);
9693
+ }
9694
+ return this;
9695
+ }
9696
+ hgetall(key) {
9697
+ if (typeof this.multiInstance.hGetAll === "function") {
9698
+ this.queueCommand("hGetAll", [key]);
9699
+ } else {
9700
+ this.queueCommand("hgetall", [key]);
8708
9701
  }
8709
9702
  return this;
8710
9703
  }
8711
9704
  async exec() {
8712
- 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
+ }
8713
9717
  if (!raw) return null;
8714
9718
  return raw.map((item) => {
8715
9719
  if (item instanceof Error) {
@@ -8719,20 +9723,32 @@ var NodeRedisPipelineAdapter = class {
8719
9723
  });
8720
9724
  }
8721
9725
  };
8722
- var NodeRedisAdapter = class _NodeRedisAdapter {
9726
+ var NodeRedisAdapter = class _NodeRedisAdapter extends import_node_events.EventEmitter {
8723
9727
  client;
9728
+ connecting = null;
9729
+ pttl;
8724
9730
  constructor(client) {
9731
+ super();
8725
9732
  if (!client) {
8726
9733
  throw new Error("NodeRedisAdapter requires an active @redis/client instance");
8727
9734
  }
8728
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
+ }
8729
9739
  }
8730
9740
  get isOpen() {
8731
9741
  return this.client.isOpen !== false;
8732
9742
  }
8733
9743
  async connect() {
9744
+ if (this.connecting) return this.connecting;
8734
9745
  if (typeof this.client.connect === "function" && !this.client.isOpen) {
8735
- 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
+ }
8736
9752
  }
8737
9753
  return void 0;
8738
9754
  }
@@ -8809,7 +9825,7 @@ var NodeRedisAdapter = class _NodeRedisAdapter {
8809
9825
  return new NodeRedisPipelineAdapter(multiInstance);
8810
9826
  }
8811
9827
  pipeline() {
8812
- return this.multi();
9828
+ return new NodeRedisPipelineAdapter(this.client, false);
8813
9829
  }
8814
9830
  async smembers(key) {
8815
9831
  if (typeof this.client.sMembers === "function") {
@@ -8849,12 +9865,43 @@ var NodeRedisAdapter = class _NodeRedisAdapter {
8849
9865
  }
8850
9866
  return void 0;
8851
9867
  }
9868
+ async hgetall(key) {
9869
+ if (typeof this.client.hGetAll === "function") {
9870
+ return await this.client.hGetAll(key) ?? {};
9871
+ }
9872
+ if (typeof this.client.hgetall === "function") {
9873
+ return await this.client.hgetall(key) ?? {};
9874
+ }
9875
+ return {};
9876
+ }
8852
9877
  async publish(channel, message) {
8853
9878
  return await this.client.publish(channel, message);
8854
9879
  }
8855
9880
  async subscribe(...channels) {
8856
9881
  if (channels.length === 0) return void 0;
8857
- 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)]);
8858
9905
  }
8859
9906
  scanStream(options) {
8860
9907
  const ee = new import_node_events.EventEmitter();
@@ -8864,8 +9911,8 @@ var NodeRedisAdapter = class _NodeRedisAdapter {
8864
9911
  try {
8865
9912
  if (typeof this.client.scanIterator === "function") {
8866
9913
  const batch = [];
8867
- for await (const key of this.client.scanIterator({ MATCH: pattern, COUNT: count })) {
8868
- batch.push(key);
9914
+ for await (const keys of this.client.scanIterator({ MATCH: pattern, COUNT: count })) {
9915
+ batch.push(...Array.isArray(keys) ? keys : [keys]);
8869
9916
  if (batch.length >= count) {
8870
9917
  ee.emit("data", [...batch]);
8871
9918
  batch.length = 0;
@@ -8909,17 +9956,24 @@ var NodeRedisAdapter = class _NodeRedisAdapter {
8909
9956
  return this;
8910
9957
  }
8911
9958
  on(event, listener) {
9959
+ if (event === "message" || event === "smessage") return super.on(event, listener);
8912
9960
  if (typeof this.client.on === "function") {
8913
- this.client.on(event, listener);
9961
+ this.client.on(event === "close" ? "end" : event, listener);
8914
9962
  }
8915
9963
  return this;
8916
9964
  }
8917
9965
  once(event, listener) {
9966
+ if (event === "message" || event === "smessage") return super.once(event, listener);
8918
9967
  if (typeof this.client.once === "function") {
8919
- this.client.once(event, listener);
9968
+ this.client.once(event === "close" ? "end" : event, listener);
8920
9969
  }
8921
9970
  return this;
8922
9971
  }
9972
+ removeListener(event, listener) {
9973
+ super.removeListener(event, listener);
9974
+ this.client.removeListener?.(event === "close" ? "end" : event, listener);
9975
+ return this;
9976
+ }
8923
9977
  };
8924
9978
  function createNodeRedisAdapter(client) {
8925
9979
  if (client instanceof NodeRedisAdapter) return client;
@@ -9107,7 +10161,7 @@ function formatTraceParent(traceId, spanId, traceFlags = 1) {
9107
10161
  var import_node_http = __toESM(require("http"), 1);
9108
10162
 
9109
10163
  // src/dashboard/handler.ts
9110
- var import_node_crypto = require("crypto");
10164
+ var import_node_crypto2 = require("crypto");
9111
10165
  var import_node_os = __toESM(require("os"), 1);
9112
10166
 
9113
10167
  // src/dashboard/html.ts
@@ -9392,7 +10446,7 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
9392
10446
  <span class="pulse-dot"></span>
9393
10447
  <span id="stream-text">SSE Live</span>
9394
10448
  </div>
9395
- <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;">
9396
10450
  <option value="">Switch Pod...</option>
9397
10451
  </select>
9398
10452
  </div>
@@ -9452,9 +10506,10 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
9452
10506
 
9453
10507
  <!-- Invalidate Modal -->
9454
10508
  <div class="dialog-overlay" id="invalidate-modal">
9455
- <div class="dialog">
9456
- <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>
9457
10511
  <p>Increments generational tag version across local tiers and broadcast backplane.</p>
10512
+ <label for="tag-input">Tag name or pattern</label>
9458
10513
  <input type="text" id="tag-input" placeholder="e.g. products, tenant-123" />
9459
10514
  <div class="dialog-actions">
9460
10515
  <button class="btn" onclick="closeModals()">Cancel</button>
@@ -9465,8 +10520,8 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
9465
10520
 
9466
10521
  <!-- Clear Modal -->
9467
10522
  <div class="dialog-overlay" id="clear-modal">
9468
- <div class="dialog">
9469
- <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>
9470
10525
  <p>Evict all cached keys from the local L1 memory and NVMe disk tiers.</p>
9471
10526
  <div class="dialog-actions">
9472
10527
  <button class="btn" onclick="closeModals()">Cancel</button>
@@ -9475,12 +10530,20 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
9475
10530
  </div>
9476
10531
  </div>
9477
10532
 
9478
- <div id="toast"></div>
10533
+ <div id="toast" role="status" aria-live="polite"></div>
9479
10534
 
9480
10535
  <script>
9481
10536
  (function() {
9482
10537
  let isReadOnly = false;
9483
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
+ }
9484
10547
 
9485
10548
  function showToast(msg, duration = 3000) {
9486
10549
  const t = document.getElementById('toast');
@@ -9587,7 +10650,8 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
9587
10650
  }
9588
10651
 
9589
10652
  window.fetchMetricsSnapshot = function() {
9590
- fetch('api/metrics')
10653
+ fetch(apiURL('api/metrics'))
10654
+ .then(r => { if (!r.ok) throw new Error('HTTP ' + r.status); return r; })
9591
10655
  .then(r => r.json())
9592
10656
  .then(data => updateUI(data))
9593
10657
  .catch(err => showToast('Failed to fetch snapshot: ' + err.message));
@@ -9598,7 +10662,7 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
9598
10662
  fallbackPolling();
9599
10663
  return;
9600
10664
  }
9601
- const sse = new EventSource('api/stream');
10665
+ const sse = new EventSource(apiURL('api/stream'));
9602
10666
  sse.onmessage = function(e) {
9603
10667
  try {
9604
10668
  const data = JSON.parse(e.data);
@@ -9623,22 +10687,37 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
9623
10687
 
9624
10688
  window.openInvalidateModal = function() {
9625
10689
  if (isReadOnly) return;
10690
+ previousFocus = document.activeElement;
9626
10691
  document.getElementById('invalidate-modal').classList.add('active');
9627
10692
  document.getElementById('tag-input').focus();
9628
10693
  };
9629
10694
  window.openClearModal = function() {
9630
10695
  if (isReadOnly) return;
10696
+ previousFocus = document.activeElement;
9631
10697
  document.getElementById('clear-modal').classList.add('active');
10698
+ document.querySelector('#clear-modal button').focus();
9632
10699
  };
9633
10700
  window.closeModals = function() {
9634
10701
  document.getElementById('invalidate-modal').classList.remove('active');
9635
10702
  document.getElementById('clear-modal').classList.remove('active');
10703
+ if (previousFocus) previousFocus.focus();
9636
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
+ });
9637
10716
 
9638
10717
  window.submitTagInvalidation = function() {
9639
10718
  const tag = document.getElementById('tag-input').value.trim();
9640
10719
  if (!tag) return;
9641
- fetch('api/actions/invalidate-tag', {
10720
+ fetch(apiURL('api/actions/invalidate-tag'), {
9642
10721
  method: 'POST',
9643
10722
  headers: {
9644
10723
  'Content-Type': 'application/json',
@@ -9661,7 +10740,7 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
9661
10740
  };
9662
10741
 
9663
10742
  window.submitClear = function() {
9664
- fetch('api/actions/clear', {
10743
+ fetch(apiURL('api/actions/clear'), {
9665
10744
  method: 'POST',
9666
10745
  headers: {
9667
10746
  'Content-Type': 'application/json',
@@ -9693,15 +10772,15 @@ var DASHBOARD_GZIP_BUFFER = (0, import_node_zlib.gzipSync)(Buffer.from(DASHBOARD
9693
10772
  // src/dashboard/handler.ts
9694
10773
  function safeCompare(a, b) {
9695
10774
  if (typeof a !== "string" || typeof b !== "string") return false;
9696
- const hashA = (0, import_node_crypto.createHash)("sha256").update(a).digest();
9697
- const hashB = (0, import_node_crypto.createHash)("sha256").update(b).digest();
9698
- 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);
9699
10778
  }
9700
10779
  var SECURITY_HEADERS = {
9701
10780
  "Content-Security-Policy": "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'",
9702
10781
  "X-Frame-Options": "DENY",
9703
10782
  "X-Content-Type-Options": "nosniff",
9704
- "Referrer-Policy": "same-origin",
10783
+ "Referrer-Policy": "no-referrer",
9705
10784
  "Cache-Control": "no-store, no-cache, must-revalidate"
9706
10785
  };
9707
10786
  function resolveInstanceId(custom) {
@@ -9720,7 +10799,7 @@ function buildMetricsPayload(options) {
9720
10799
  title: options.title || "TriCache Observability",
9721
10800
  instanceId: resolveInstanceId(options.instanceId),
9722
10801
  nodeVersion: process.version,
9723
- readOnly: !!options.readOnly,
10802
+ readOnly: options.readOnly ?? true,
9724
10803
  peerInstances: options.peerInstances || [],
9725
10804
  metrics: {
9726
10805
  ...metrics,
@@ -9826,6 +10905,7 @@ async function handleDashboardRequest(req, options) {
9826
10905
  }
9827
10906
  ticker = setInterval(() => {
9828
10907
  try {
10908
+ if ((controller.desiredSize ?? 0) <= 0) return;
9829
10909
  const data = buildMetricsPayload(options);
9830
10910
  controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}
9831
10911
 
@@ -9848,7 +10928,7 @@ async function handleDashboardRequest(req, options) {
9848
10928
  controller.close();
9849
10929
  } catch {
9850
10930
  }
9851
- });
10931
+ }, { once: true });
9852
10932
  }
9853
10933
  },
9854
10934
  cancel() {
@@ -9880,7 +10960,7 @@ async function handleDashboardRequest(req, options) {
9880
10960
  }
9881
10961
  if (pathname === "/api/actions/invalidate-tag" && req.method === "POST") {
9882
10962
  const clientIp = req.headers.get("x-forwarded-for") || void 0;
9883
- if (options.readOnly) {
10963
+ if (options.readOnly ?? true) {
9884
10964
  return new Response(JSON.stringify({ ok: false, error: "Dashboard is in read-only mode" }), {
9885
10965
  status: 403,
9886
10966
  headers: { "Content-Type": "application/json" }
@@ -9893,7 +10973,28 @@ async function handleDashboardRequest(req, options) {
9893
10973
  });
9894
10974
  }
9895
10975
  try {
9896
- 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"));
9897
10998
  const tag = body?.tag?.trim();
9898
10999
  if (!tag) {
9899
11000
  return new Response(JSON.stringify({ ok: false, error: "Tag parameter is required" }), {
@@ -9932,7 +11033,7 @@ async function handleDashboardRequest(req, options) {
9932
11033
  }
9933
11034
  if (pathname === "/api/actions/clear" && req.method === "POST") {
9934
11035
  const clientIp = req.headers.get("x-forwarded-for") || void 0;
9935
- if (options.readOnly) {
11036
+ if (options.readOnly ?? true) {
9936
11037
  return new Response(JSON.stringify({ ok: false, error: "Dashboard is in read-only mode" }), {
9937
11038
  status: 403,
9938
11039
  headers: { "Content-Type": "application/json" }
@@ -10001,7 +11102,7 @@ async function handleDashboardRequest(req, options) {
10001
11102
  }
10002
11103
 
10003
11104
  // src/dashboard/index.ts
10004
- async function nodeToWebRequest(req) {
11105
+ async function nodeToWebRequest(req, res, maxBytes) {
10005
11106
  const protocol = req.socket.encrypted ? "https" : "http";
10006
11107
  const host = req.headers.host || "localhost";
10007
11108
  const url = new URL(req.url || "/", `${protocol}://${host}`);
@@ -10017,19 +11118,23 @@ async function nodeToWebRequest(req) {
10017
11118
  let body = null;
10018
11119
  if (req.method !== "GET" && req.method !== "HEAD") {
10019
11120
  const chunks = [];
10020
- for await (const chunk of req) {
10021
- 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);
10022
11129
  }
10023
11130
  if (chunks.length > 0) {
10024
11131
  body = Buffer.concat(chunks);
11132
+ if (body.length > maxBytes) throw Object.assign(new Error("Request body exceeds dashboard limit"), { status: 413 });
10025
11133
  }
10026
11134
  }
10027
11135
  const controller = new AbortController();
10028
- req.on("close", () => {
10029
- if (req.destroyed || !req.complete) {
10030
- controller.abort();
10031
- }
10032
- });
11136
+ req.once("aborted", () => controller.abort());
11137
+ res.once("close", () => controller.abort());
10033
11138
  const init = {
10034
11139
  method: req.method,
10035
11140
  headers,
@@ -10051,24 +11156,54 @@ async function pipeWebResponseToNode(webRes, nodeRes) {
10051
11156
  return;
10052
11157
  }
10053
11158
  const reader = webRes.body.getReader();
11159
+ const cancel = () => {
11160
+ void reader.cancel().catch(() => {
11161
+ });
11162
+ };
11163
+ nodeRes.once("close", cancel);
10054
11164
  try {
10055
11165
  while (true) {
10056
11166
  const { done, value } = await reader.read();
10057
11167
  if (done) break;
10058
- 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
+ });
10059
11185
  }
10060
11186
  } finally {
10061
- nodeRes.end();
11187
+ nodeRes.off("close", cancel);
11188
+ await reader.cancel().catch(() => {
11189
+ });
11190
+ reader.releaseLock();
11191
+ if (!nodeRes.destroyed) nodeRes.end();
10062
11192
  }
10063
11193
  }
10064
11194
  function tricacheDashboard(options) {
10065
11195
  return async (req, res, next) => {
10066
11196
  try {
10067
- const webReq = await nodeToWebRequest(req);
11197
+ const webReq = await nodeToWebRequest(req, res, options.maxRequestBytes ?? 65536);
10068
11198
  const webRes = await handleDashboardRequest(webReq, options);
10069
11199
  await pipeWebResponseToNode(webRes, res);
10070
11200
  } catch (err) {
10071
- 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") {
10072
11207
  next(err);
10073
11208
  } else {
10074
11209
  res.statusCode = 500;
@@ -10087,7 +11222,7 @@ function createNextDashboardHandlers(options) {
10087
11222
  };
10088
11223
  }
10089
11224
  async function startDashboardServer(options) {
10090
- const port = options.port || 9090;
11225
+ const port = options.port ?? 9090;
10091
11226
  const host = options.host || "127.0.0.1";
10092
11227
  const middleware = tricacheDashboard(options);
10093
11228
  const server = import_node_http.default.createServer((req, res) => {
@@ -10111,6 +11246,7 @@ async function startDashboardServer(options) {
10111
11246
  host,
10112
11247
  close: () => new Promise((resolve, reject) => {
10113
11248
  server.close((err) => err ? reject(err) : resolve());
11249
+ server.closeAllConnections();
10114
11250
  })
10115
11251
  };
10116
11252
  }