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
@@ -16,7 +16,7 @@ import {
16
16
  isChildTag,
17
17
  isWildcardTag,
18
18
  matchesTagPattern
19
- } from "./chunk-2AJKEQMZ.js";
19
+ } from "./chunk-H4GFLQ26.js";
20
20
 
21
21
  // src/cache-service.ts
22
22
  import { Redis as RedisClient, Cluster as RedisCluster } from "ioredis";
@@ -54,6 +54,127 @@ var defaultCodec = new CacheCodec({
54
54
  moreTypes: true
55
55
  });
56
56
 
57
+ // src/cross-region.ts
58
+ import { createHash, timingSafeEqual } from "crypto";
59
+ function isCrossRegionInvalidationEvent(value) {
60
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
61
+ const event = value;
62
+ const text = (key, max) => typeof event[key] === "string" && event[key].length > 0 && event[key].length <= max;
63
+ 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);
64
+ }
65
+ function createHttpMeshRelay(options) {
66
+ const peerUrls = options.peerUrls;
67
+ const timeoutMs = options.timeoutMs ?? 3e3;
68
+ const fetcher = options.fetchFn ?? globalThis.fetch;
69
+ const headers = {
70
+ "Content-Type": "application/json"
71
+ };
72
+ if (options.authSecret) {
73
+ headers["Authorization"] = `Bearer ${options.authSecret}`;
74
+ headers["X-TriCache-Auth"] = options.authSecret;
75
+ }
76
+ return {
77
+ async broadcast(event) {
78
+ if (!peerUrls.length) return;
79
+ const body = JSON.stringify(event);
80
+ const results = await Promise.allSettled(
81
+ peerUrls.map(async (url) => {
82
+ const res = await fetcher(url, {
83
+ method: "POST",
84
+ headers,
85
+ body,
86
+ signal: AbortSignal.timeout(timeoutMs)
87
+ });
88
+ if (!res.ok) {
89
+ throw new Error(`HttpMeshRelay: peer ${url} returned HTTP ${res.status} ${res.statusText}`);
90
+ }
91
+ })
92
+ );
93
+ const failures = results.filter((result) => result.status === "rejected");
94
+ if (failures.length) throw new AggregateError(failures.map((result) => result.reason), `Cross-region delivery failed for ${failures.length} peer(s)`);
95
+ }
96
+ };
97
+ }
98
+ function createCustomCrossRegionRelay(relay) {
99
+ return relay;
100
+ }
101
+ function createMemoryCrossRegionRelay() {
102
+ const handlers = /* @__PURE__ */ new Map();
103
+ let broadcastCount = 0;
104
+ return {
105
+ async broadcast(event) {
106
+ broadcastCount++;
107
+ const promises = [];
108
+ for (const [region, set] of handlers.entries()) {
109
+ if (region !== event.originRegion) {
110
+ for (const fn of set) {
111
+ promises.push(Promise.resolve(fn(event)));
112
+ }
113
+ }
114
+ }
115
+ const results = await Promise.allSettled(promises);
116
+ const failures = results.filter((result) => result.status === "rejected");
117
+ if (failures.length) throw new AggregateError(failures.map((result) => result.reason), "Cross-region handler failed");
118
+ },
119
+ register(region, handler) {
120
+ if (!handlers.has(region)) {
121
+ handlers.set(region, /* @__PURE__ */ new Set());
122
+ }
123
+ handlers.get(region).add(handler);
124
+ return () => {
125
+ handlers.get(region)?.delete(handler);
126
+ };
127
+ },
128
+ getBroadcastCount() {
129
+ return broadcastCount;
130
+ },
131
+ clear() {
132
+ handlers.clear();
133
+ broadcastCount = 0;
134
+ }
135
+ };
136
+ }
137
+ function createCrossRegionWebhookHandler(cache, options = {}) {
138
+ return async function handleCrossRegionWebhook(req) {
139
+ if (options.authSecret) {
140
+ const authHeader = req.headers["authorization"] ?? req.headers["Authorization"];
141
+ const customHeader = req.headers["x-tricache-auth"] ?? req.headers["X-TriCache-Auth"];
142
+ const bearer = typeof authHeader === "string" && authHeader.startsWith("Bearer ") ? authHeader.slice(7).trim() : authHeader;
143
+ const provided = typeof customHeader === "string" ? customHeader : bearer;
144
+ if (typeof provided !== "string" || !timingSafeEqual(createHash("sha256").update(provided).digest(), createHash("sha256").update(options.authSecret).digest())) {
145
+ return {
146
+ status: 401,
147
+ body: { ok: false, message: "Unauthorized: invalid or missing auth secret" }
148
+ };
149
+ }
150
+ }
151
+ try {
152
+ let event;
153
+ if (typeof req.body === "string") {
154
+ event = JSON.parse(req.body);
155
+ } else if (req.body && typeof req.body === "object") {
156
+ event = req.body;
157
+ } else {
158
+ return {
159
+ status: 400,
160
+ body: { ok: false, message: "Invalid payload: body must be JSON object" }
161
+ };
162
+ }
163
+ if (!isCrossRegionInvalidationEvent(event)) return { status: 400, body: { ok: false, message: "Invalid invalidation event" } };
164
+ const accepted = await cache.receiveCrossRegionInvalidation(event);
165
+ return {
166
+ status: 200,
167
+ body: { ok: true, message: accepted ? "Invalidation applied" : "Invalidation ignored (deduplicated or self)" }
168
+ };
169
+ } catch (err) {
170
+ return {
171
+ status: 400,
172
+ body: { ok: false, message: err.message }
173
+ };
174
+ }
175
+ };
176
+ }
177
+
57
178
  // src/cache-service.ts
58
179
  import crypto2 from "crypto";
59
180
  import os3 from "os";
@@ -79,7 +200,8 @@ try {
79
200
  _workerFile = jsPath;
80
201
  }
81
202
  } catch {
82
- _workerFile = join(__dirname, "serialize-worker.js");
203
+ const sibling = join(__dirname, "serialize-worker.js");
204
+ _workerFile = existsSync(sibling) ? sibling : join(dirname(__dirname), "serialize-worker.js");
83
205
  }
84
206
  function getTransferableArrayBuffer(buf) {
85
207
  if (buf.buffer instanceof ArrayBuffer) {
@@ -112,6 +234,7 @@ var WorkerPool = class {
112
234
  }
113
235
  _spawnWorkers(opts) {
114
236
  const size = Math.max(1, opts.size ?? Math.min(4, availableCpus()));
237
+ if (!Number.isInteger(size) || size > 32 || !existsSync(_workerFile)) throw new Error("Worker pool unavailable or invalid worker count");
115
238
  const workerData = {
116
239
  keyBase64: opts.keyBase64,
117
240
  mode: opts.mode,
@@ -125,7 +248,8 @@ var WorkerPool = class {
125
248
  const createWorker = (index) => {
126
249
  const worker = new Worker(_workerFile, {
127
250
  workerData,
128
- execArgv: _workerExecArgv.length > 0 ? _workerExecArgv : void 0
251
+ execArgv: _workerExecArgv
252
+ // Do not inherit --input-type/eval or application loader flags.
129
253
  });
130
254
  const pending = pendingList[index] ?? /* @__PURE__ */ new Map();
131
255
  if (!pendingList[index]) pendingList[index] = pending;
@@ -155,7 +279,7 @@ var WorkerPool = class {
155
279
  }
156
280
  pending.clear();
157
281
  worker.unref();
158
- if (this._available && exitCode !== 0 && workers[index] === worker) {
282
+ if (this._available && this.workers === workers && workers[index] === worker) {
159
283
  try {
160
284
  workers[index] = createWorker(index);
161
285
  } catch {
@@ -165,9 +289,12 @@ var WorkerPool = class {
165
289
  worker.unref();
166
290
  return worker;
167
291
  };
168
- for (let i = 0; i < size; i++) {
169
- const worker = createWorker(i);
170
- workers.push(worker);
292
+ try {
293
+ for (let i = 0; i < size; i++) workers.push(createWorker(i));
294
+ } catch (error) {
295
+ for (const worker of workers) void worker.terminate().catch(() => {
296
+ });
297
+ throw error;
171
298
  }
172
299
  return { workers, pending: pendingList };
173
300
  }
@@ -194,7 +321,7 @@ var WorkerPool = class {
194
321
  entry.reject(new Error("WorkerPool replaced during key rotation"));
195
322
  }
196
323
  oldPending[i]?.clear();
197
- oldWorkers[i]?.terminate().catch(() => {
324
+ await oldWorkers[i]?.terminate().catch(() => {
198
325
  });
199
326
  }
200
327
  }
@@ -236,7 +363,13 @@ var WorkerPool = class {
236
363
  return new Promise((resolve, reject) => {
237
364
  pending.set(id, { resolve, reject });
238
365
  worker.ref();
239
- worker.postMessage({ id, type, payload: dataToSend }, transferList);
366
+ try {
367
+ worker.postMessage({ id, type, payload: dataToSend }, transferList);
368
+ } catch (error) {
369
+ pending.delete(id);
370
+ if (pending.size === 0) worker.unref();
371
+ reject(error);
372
+ }
240
373
  });
241
374
  }
242
375
  /** Terminate all worker threads. In-flight promises are rejected. */
@@ -550,8 +683,9 @@ var WTinyLfuCache = class {
550
683
  }
551
684
  };
552
685
  var WTinyLfuPolicy = class {
553
- constructor(capacity, sketch, windowPercent = 0.01, protectedPercent = 0.8) {
686
+ constructor(capacity, sketch, windowPercent = 0.01, protectedPercent = 0.8, canEvict) {
554
687
  this.sketch = sketch;
688
+ this.canEvict = canEvict;
555
689
  this.maxTotal = Math.max(2, capacity);
556
690
  this.maxWindow = Math.max(1, Math.floor(this.maxTotal * windowPercent));
557
691
  const mainCapacity = Math.max(1, this.maxTotal - this.maxWindow);
@@ -559,6 +693,7 @@ var WTinyLfuPolicy = class {
559
693
  this.maxProbation = Math.max(1, mainCapacity - this.maxProtected);
560
694
  }
561
695
  sketch;
696
+ canEvict;
562
697
  maxTotal;
563
698
  maxWindow;
564
699
  maxProtected;
@@ -638,15 +773,33 @@ var WTinyLfuPolicy = class {
638
773
  }
639
774
  let victimKey;
640
775
  let victimIsProbation = true;
641
- if (this.probation.size > 0) {
642
- victimKey = this.probation.values().next().value;
643
- } else {
644
- victimKey = this.protected_.values().next().value;
776
+ for (const candidate of this.probation) {
777
+ if (!this.canEvict || this.canEvict(candidate)) {
778
+ victimKey = candidate;
779
+ break;
780
+ }
781
+ }
782
+ if (victimKey === void 0) {
783
+ for (const candidate of this.protected_) {
784
+ if (!this.canEvict || this.canEvict(candidate)) {
785
+ victimKey = candidate;
786
+ break;
787
+ }
788
+ }
645
789
  victimIsProbation = false;
646
790
  }
791
+ if (victimKey === void 0) {
792
+ if (this.canEvict && !this.canEvict(candKey)) {
793
+ this.window.delete(key);
794
+ this.window.add(candKey);
795
+ return { admit: false, candidateKey: key };
796
+ }
797
+ this.rejectionCount++;
798
+ return { admit: false, candidateKey: candKey };
799
+ }
647
800
  const candFreq = this.sketch.estimate(candKey);
648
801
  const victimFreq = this.sketch.estimate(victimKey);
649
- if (candFreq > victimFreq) {
802
+ if (this.canEvict && !this.canEvict(candKey) || candFreq > victimFreq) {
650
803
  if (victimIsProbation) {
651
804
  this.probation.delete(victimKey);
652
805
  } else {
@@ -785,8 +938,9 @@ var JsBloomFilter = class {
785
938
  };
786
939
  function createBloomFilter(logger, maxEntries) {
787
940
  const LN2_SQ = Math.LN2 * Math.LN2;
788
- const optimalBits = Math.ceil(-maxEntries * Math.log(0.01) / LN2_SQ);
789
- const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / maxEntries)));
941
+ const capacity = Math.max(1, maxEntries);
942
+ const optimalBits = Math.ceil(-capacity * Math.log(0.01) / LN2_SQ);
943
+ const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / capacity)));
790
944
  try {
791
945
  const wasm = new WasmBloomFilter();
792
946
  if (wasm.maxCapacity >= maxEntries) {
@@ -910,7 +1064,10 @@ var SmartMemoryCache = class {
910
1064
  this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
911
1065
  this.categoryPrefixes = Object.keys(opts.categories).filter((k) => k !== "default");
912
1066
  if (opts.admissionPolicy === "wtinylfu") {
913
- this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch);
1067
+ this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch, 0.01, 0.8, (key) => {
1068
+ const entry = this.cache.get(key);
1069
+ return !entry || entry.priority !== 4 || entry.expiresAt <= Date.now();
1070
+ });
914
1071
  }
915
1072
  if (existing) {
916
1073
  for (const [k, v] of existing) this.cache.set(k, v);
@@ -989,6 +1146,7 @@ var SmartMemoryCache = class {
989
1146
  const MAX_EVICT_PASSES = 64;
990
1147
  let passes = 0;
991
1148
  do {
1149
+ const before = this.cache.size;
992
1150
  this.smartEvict(category, catOvf);
993
1151
  const lim2 = this.getCategoryLimit(category);
994
1152
  const catCnt2 = this.categoryCount.get(category) ?? 0;
@@ -996,6 +1154,7 @@ var SmartMemoryCache = class {
996
1154
  catOvf = catCnt2 >= lim2.maxEntries || catSz2 + neededSize > lim2.maxSizeBytes;
997
1155
  glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
998
1156
  passes++;
1157
+ if (this.cache.size === before) break;
999
1158
  } while ((catOvf || glbOvf) && passes < MAX_EVICT_PASSES);
1000
1159
  }
1001
1160
  score(entry, catBonus, now, key) {
@@ -1126,20 +1285,26 @@ var SmartMemoryCache = class {
1126
1285
  delta: entry.delta,
1127
1286
  fetchedAt: now,
1128
1287
  tagVersions: entry.tagVersions,
1129
- setAt: entry.setAt
1288
+ setAt: entry.setAt,
1289
+ tags: entry.tags,
1290
+ dependsOn: entry.dependsOn
1130
1291
  };
1131
1292
  return hit;
1132
1293
  }
1133
- set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
1294
+ set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions, setAt, tags, dependsOn) {
1134
1295
  const packed = this.codec.encode(data);
1296
+ return this.storePacked(key, packed, data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn);
1297
+ }
1298
+ storePacked(key, packed, data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn) {
1135
1299
  const size = packed.byteLength;
1136
1300
  this.compressions++;
1137
1301
  this.sketch.increment(key);
1138
1302
  const cat = this.getCategory(key);
1139
1303
  const lim = this.getCategoryLimit(cat);
1140
- if (size > lim.maxSizeBytes * 0.5) {
1304
+ if (!Number.isFinite(ttlMs) || ttlMs <= 0 || this.opts.maxEntries <= 0 || lim.maxEntries <= 0 || size > this.opts.maxBytes || size > lim.maxSizeBytes * 0.5) {
1305
+ this.delete(key);
1141
1306
  this.opts.logger.debug("SmartMemoryCache: entry too large, skipping", { key, sizeBytes: size });
1142
- return;
1307
+ return false;
1143
1308
  }
1144
1309
  const existingEntry = this.cache.get(key);
1145
1310
  if (existingEntry) {
@@ -1167,11 +1332,13 @@ var SmartMemoryCache = class {
1167
1332
  priority,
1168
1333
  ttlMs,
1169
1334
  delta,
1170
- setAt: now2,
1171
- tagVersions
1335
+ setAt: setAt ?? now2,
1336
+ tagVersions,
1337
+ tags,
1338
+ dependsOn
1172
1339
  });
1173
1340
  }
1174
- return;
1341
+ return false;
1175
1342
  } else if (decision.candidateKey) {
1176
1343
  const candEntry = this.cache.get(decision.candidateKey);
1177
1344
  if (candEntry && this.opts.diskSpill) {
@@ -1187,15 +1354,19 @@ var SmartMemoryCache = class {
1187
1354
  this._delete(decision.evictKey, "capacity");
1188
1355
  }
1189
1356
  const catSz = this.categorySize.get(cat) ?? 0;
1190
- if (catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
1357
+ if ((this.categoryCount.get(cat) ?? 0) >= lim.maxEntries || this.cache.size >= this.opts.maxEntries || catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
1191
1358
  this.ensureCapacity(cat, size);
1192
1359
  }
1193
1360
  } else {
1194
1361
  this.ensureCapacity(cat, size);
1195
1362
  }
1363
+ 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) {
1364
+ this.wtinyPolicy?.onDelete(key);
1365
+ return false;
1366
+ }
1196
1367
  const now = Date.now();
1197
1368
  const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
1198
- 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 });
1369
+ 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 });
1199
1370
  if (!existingEntry) this.bloom.add(key);
1200
1371
  this.maybeRebuildBloom();
1201
1372
  this.totalSize += size;
@@ -1207,6 +1378,7 @@ var SmartMemoryCache = class {
1207
1378
  this.categoryKeys.set(cat, ks);
1208
1379
  }
1209
1380
  ks.add(key);
1381
+ return true;
1210
1382
  }
1211
1383
  delete(key) {
1212
1384
  const deleted = this._delete(key, "manual");
@@ -1408,25 +1580,48 @@ var SmartMemoryCache = class {
1408
1580
  if (entry.expiresAt <= now) continue;
1409
1581
  if (entry.priority === 4) continue;
1410
1582
  if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
1411
- out.push({ key, entry: { ...entry } });
1583
+ const { value: _value, ...stored } = entry;
1584
+ out.push({ key, entry: { ...stored } });
1412
1585
  }
1413
1586
  return out;
1414
1587
  }
1415
1588
  importEntries(entries, forbiddenPrefixes) {
1416
1589
  const now = Date.now();
1417
1590
  let loaded = 0;
1418
- for (const { key, entry } of entries) {
1419
- if (entry.expiresAt <= now) continue;
1591
+ for (const item of entries) {
1592
+ if (!item || typeof item.key !== "string" || !item.entry) continue;
1593
+ const { key, entry } = item;
1594
+ if (!Number.isFinite(entry.expiresAt) || entry.expiresAt <= now) continue;
1420
1595
  if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
1421
1596
  if (this.cache.has(key)) continue;
1422
- const rawData = entry.data;
1423
- const data = !entry.isCompressed ? this.codec.encode(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
1424
- const value = entry.size <= LARGE_VALUE_BYTES ? this.codec.decode(data) : void 0;
1425
- this.cache.set(key, { ...entry, data, value, isCompressed: true });
1426
- this.bloom.add(key);
1427
- loaded++;
1428
- }
1429
- this.recalculateStats();
1597
+ try {
1598
+ const rawData = entry.data;
1599
+ const data = !entry.isCompressed ? this.codec.encode(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : null;
1600
+ if (!data) continue;
1601
+ const value = data.length <= LARGE_VALUE_BYTES ? this.codec.decode(data) : void 0;
1602
+ if (this.storePacked(
1603
+ key,
1604
+ data,
1605
+ value,
1606
+ entry.expiresAt - now,
1607
+ entry.priority,
1608
+ entry.staleAt,
1609
+ entry.delta,
1610
+ entry.tagVersions,
1611
+ entry.setAt,
1612
+ entry.tags,
1613
+ entry.dependsOn
1614
+ )) {
1615
+ const restored = this.cache.get(key);
1616
+ restored.expiresAt = entry.expiresAt;
1617
+ restored.ttlMs = entry.ttlMs ?? entry.expiresAt - now;
1618
+ restored.hits = Number.isFinite(entry.hits) ? Math.max(1, entry.hits) : 1;
1619
+ restored.lastAccess = Number.isFinite(entry.lastAccess) ? entry.lastAccess : now;
1620
+ loaded++;
1621
+ }
1622
+ } catch {
1623
+ }
1624
+ }
1430
1625
  return loaded;
1431
1626
  }
1432
1627
  // ── Iterators ─────────────────────────────────────────────────────────────
@@ -1618,6 +1813,9 @@ var BoundedDiskQueue = class {
1618
1813
  this.writeTimeoutMs = writeTimeoutMs;
1619
1814
  this.failureThreshold = failureThreshold;
1620
1815
  this.cooldownMs = cooldownMs;
1816
+ 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) {
1817
+ throw new Error("Disk queue limits and timeout must be finite positive values (pending/cooldown may be zero)");
1818
+ }
1621
1819
  }
1622
1820
  maxConcurrent;
1623
1821
  maxPending;
@@ -1630,6 +1828,17 @@ var BoundedDiskQueue = class {
1630
1828
  consecutiveFailures = 0;
1631
1829
  circuitState = "closed";
1632
1830
  lastStateChangeMonotonic = performance.now();
1831
+ get isSaturated() {
1832
+ return this.active >= this.maxConcurrent && this.queue.length >= this.maxPending;
1833
+ }
1834
+ releaseSlot() {
1835
+ if (this.circuitState === "open") {
1836
+ for (const next2 of this.queue.splice(0)) next2(false);
1837
+ }
1838
+ const next = this.queue.shift();
1839
+ if (next) next(true);
1840
+ else this.active--;
1841
+ }
1633
1842
  async schedule(task) {
1634
1843
  const now = performance.now();
1635
1844
  if (this.circuitState === "open") {
@@ -1645,18 +1854,25 @@ var BoundedDiskQueue = class {
1645
1854
  this.spillsDropped++;
1646
1855
  return null;
1647
1856
  }
1648
- if (this.queue.length >= this.maxPending) {
1857
+ if (this.isSaturated) {
1649
1858
  this.spillsDropped++;
1650
1859
  return null;
1651
1860
  }
1652
1861
  if (this.active >= this.maxConcurrent) {
1653
- await new Promise((resolve) => this.queue.push(resolve));
1862
+ const admitted = await new Promise((resolve) => this.queue.push(resolve));
1863
+ if (!admitted) {
1864
+ this.spillsDropped++;
1865
+ return null;
1866
+ }
1867
+ } else {
1868
+ this.active++;
1654
1869
  }
1655
- this.active++;
1656
1870
  let timeoutId = null;
1871
+ const work = Promise.resolve().then(task);
1872
+ void work.then(() => this.releaseSlot(), () => this.releaseSlot());
1657
1873
  try {
1658
1874
  const result = await Promise.race([
1659
- task(),
1875
+ work,
1660
1876
  new Promise((_, reject) => {
1661
1877
  timeoutId = setTimeout(
1662
1878
  () => reject(new Error(`Disk write exceeded timeout of ${this.writeTimeoutMs}ms`)),
@@ -1675,14 +1891,12 @@ var BoundedDiskQueue = class {
1675
1891
  if (this.consecutiveFailures >= this.failureThreshold || this.circuitState === "half-open") {
1676
1892
  this.circuitState = "open";
1677
1893
  this.lastStateChangeMonotonic = performance.now();
1894
+ for (const next of this.queue.splice(0)) next(false);
1678
1895
  }
1679
1896
  this.spillsDropped++;
1680
1897
  return null;
1681
1898
  } finally {
1682
1899
  if (timeoutId) clearTimeout(timeoutId);
1683
- this.active--;
1684
- const next = this.queue.shift();
1685
- if (next) next();
1686
1900
  }
1687
1901
  }
1688
1902
  getStats() {
@@ -1756,6 +1970,13 @@ var DiskTier = class {
1756
1970
  usageCounted = false;
1757
1971
  fileCount = 0;
1758
1972
  // maintained in-memory; avoids walkCacheFiles() in stats
1973
+ reservedBytes = 0;
1974
+ reservedFiles = 0;
1975
+ saveSequence = 0;
1976
+ epoch = 0;
1977
+ pendingSaves = /* @__PURE__ */ new Map();
1978
+ closed = false;
1979
+ invalidatedKeys = /* @__PURE__ */ new Set();
1759
1980
  /** Next bucket index (0–255) for the staggered janitor wheel. */
1760
1981
  _nextJanitorBucket = 0;
1761
1982
  // ── High-watermark pruning & host volume health state ─────────────────────
@@ -1796,6 +2017,7 @@ var DiskTier = class {
1796
2017
  }
1797
2018
  // ── Helpers ───────────────────────────────────────────────────────────────
1798
2019
  ensureDir() {
2020
+ if (this.closed) return;
1799
2021
  if (this.dirReady) return;
1800
2022
  try {
1801
2023
  fs.mkdirSync(this.opts.dir, { recursive: true, mode: 448 });
@@ -1917,8 +2139,24 @@ var DiskTier = class {
1917
2139
  *
1918
2140
  * 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
1919
2141
  */
1920
- hashToWritePath(hash, expiresAt) {
1921
- return path.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiresAt.toString(16).padStart(12, "0")}`);
2142
+ hashToWritePath(hash, expiresAt, setAt) {
2143
+ const expiry = Math.floor(expiresAt).toString(16).padStart(12, "0");
2144
+ if (setAt === void 0) return path.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}`);
2145
+ const written = Math.floor(setAt).toString(16).padStart(12, "0");
2146
+ const sequence = (++this.saveSequence).toString(16).padStart(12, "0");
2147
+ return path.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}_${written}_${sequence}_${crypto.randomBytes(6).toString("hex")}`);
2148
+ }
2149
+ findFilePaths(hash) {
2150
+ const bucket = path.join(this.opts.dir, hash.slice(0, 2));
2151
+ try {
2152
+ return fs.readdirSync(bucket).filter((file) => !file.endsWith(".tmp") && (file === hash || file.startsWith(hash + "_"))).map((file) => path.join(bucket, file));
2153
+ } catch {
2154
+ return [];
2155
+ }
2156
+ }
2157
+ fileWrittenAt(file) {
2158
+ const parts = path.basename(file).split("_");
2159
+ return parts.length >= 4 ? parseInt(parts[2], 16) : fs.statSync(file).mtimeMs;
1922
2160
  }
1923
2161
  /**
1924
2162
  * Find the on-disk file for a key hash, handling all filename generations:
@@ -1927,19 +2165,31 @@ var DiskTier = class {
1927
2165
  * Returns null when the bucket dir does not exist or the key is absent.
1928
2166
  */
1929
2167
  findFilePath(hash) {
1930
- const bucketPath = path.join(this.opts.dir, hash.slice(0, 2));
1931
- let files;
2168
+ let match = null;
2169
+ let newest = -Infinity;
2170
+ let sequence = -1;
2171
+ for (const file of this.findFilePaths(hash)) {
2172
+ try {
2173
+ const written = this.fileWrittenAt(file);
2174
+ const order = parseInt(path.basename(file).split("_")[3] ?? "0", 16);
2175
+ if (written > newest || written === newest && order > sequence) {
2176
+ match = file;
2177
+ newest = written;
2178
+ sequence = order;
2179
+ }
2180
+ } catch {
2181
+ }
2182
+ }
2183
+ return match;
2184
+ }
2185
+ removeFile(filePath) {
1932
2186
  try {
1933
- files = fs.readdirSync(bucketPath);
2187
+ const size = fs.statSync(filePath).size;
2188
+ fs.unlinkSync(filePath);
2189
+ this.diskUsageBytes = Math.max(0, this.diskUsageBytes - size);
2190
+ this.fileCount = Math.max(0, this.fileCount - 1);
1934
2191
  } catch {
1935
- return null;
1936
- }
1937
- let match;
1938
- for (const f of files) {
1939
- if ((f === hash || f.startsWith(hash + "_")) && (!match || f > match)) match = f;
1940
2192
  }
1941
- if (!match) return null;
1942
- return path.join(bucketPath, match);
1943
2193
  }
1944
2194
  /**
1945
2195
  * Recursively list all cache file paths across the 2-level sharded subdirs.
@@ -2014,6 +2264,7 @@ var DiskTier = class {
2014
2264
  * so the Node.js event loop is never stalled waiting for disk I/O.
2015
2265
  */
2016
2266
  async save(key, entry) {
2267
+ if (this.closed || this.diskQueue.isSaturated) return;
2017
2268
  if (this.isForbidden(key)) return;
2018
2269
  if (entry.expiresAt <= Date.now()) return;
2019
2270
  this.ensureDir();
@@ -2022,7 +2273,7 @@ var DiskTier = class {
2022
2273
  if (++this._writeCounter % 2e3 === 0) {
2023
2274
  this.checkHostVolumeHealth();
2024
2275
  }
2025
- if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes >= this.opts.maxBytes) {
2276
+ if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes + this.reservedBytes >= this.opts.maxBytes) {
2026
2277
  this._spillsShedTotal++;
2027
2278
  return;
2028
2279
  }
@@ -2031,11 +2282,12 @@ var DiskTier = class {
2031
2282
  }
2032
2283
  let final;
2033
2284
  try {
2285
+ const { value: _value, ...storedEntry } = entry;
2034
2286
  const payload = {
2035
2287
  version: DISK_TIER_VERSION,
2036
2288
  key,
2037
2289
  entry: {
2038
- ...entry,
2290
+ ...storedEntry,
2039
2291
  data: entry.data instanceof Uint8Array ? Buffer.from(entry.data) : entry.data
2040
2292
  },
2041
2293
  writtenAt: Date.now()
@@ -2048,24 +2300,46 @@ var DiskTier = class {
2048
2300
  }
2049
2301
  const header = Buffer.allocUnsafe(V2_HEADER_LEN);
2050
2302
  DISK_MAGIC_V2.copy(header, 0);
2051
- header.writeBigUInt64LE(BigInt(entry.expiresAt), 8);
2303
+ header.writeBigUInt64LE(BigInt(Math.floor(entry.expiresAt)), 8);
2052
2304
  final = Buffer.concat([header, this.encryptV2(toEncrypt)]);
2305
+ if (final.length > this.opts.entryMaxBytes || this.diskUsageBytes + this.reservedBytes + final.length > this.opts.maxBytes) return;
2053
2306
  } catch (err) {
2054
2307
  this.opts.logger.debug("DiskTier: pack/encrypt failed", { key: key.slice(0, 50), error: err.message });
2055
2308
  return;
2056
2309
  }
2057
2310
  const hash = this.keyToHash(key);
2058
- const filePath = this.hashToWritePath(hash, entry.expiresAt);
2311
+ const setAt = entry.setAt ?? Date.now();
2312
+ if ((this.pendingSaves.get(key)?.setAt ?? 0) > setAt) return;
2313
+ const filePath = this.hashToWritePath(hash, entry.expiresAt, setAt);
2059
2314
  const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${crypto.randomBytes(6).toString("hex")}.tmp`;
2060
- this.diskUsageBytes += final.length;
2061
- this.fileCount++;
2315
+ const token = Symbol(key);
2316
+ const epoch = this.epoch;
2317
+ this.pendingSaves.set(key, { token, setAt });
2318
+ const current = () => !this.closed && this.epoch === epoch && this.pendingSaves.get(key)?.token === token;
2319
+ let started = false;
2320
+ let released = false;
2321
+ let accounted = false;
2322
+ const releaseReservation = () => {
2323
+ if (released) return;
2324
+ released = true;
2325
+ this.reservedBytes = Math.max(0, this.reservedBytes - final.length);
2326
+ this.reservedFiles = Math.max(0, this.reservedFiles - 1);
2327
+ if (this.pendingSaves.get(key)?.token === token) this.pendingSaves.delete(key);
2328
+ };
2329
+ this.reservedBytes += final.length;
2330
+ this.reservedFiles++;
2062
2331
  if (this.diskUsageBytes >= this.opts.maxBytes * 0.8 && !this._isPruning) {
2063
2332
  void this.triggerChunkedPrune();
2064
2333
  }
2065
2334
  const result = await this.diskQueue.schedule(async () => {
2335
+ started = true;
2066
2336
  try {
2337
+ if (!current()) return false;
2338
+ const previous = this.findFilePath(hash);
2339
+ if (previous && this.fileWrittenAt(previous) > setAt) return false;
2067
2340
  await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
2068
2341
  await fs.promises.writeFile(tmpPath, final, { mode: 384 });
2342
+ if (!current()) return false;
2069
2343
  try {
2070
2344
  await fs.promises.rename(tmpPath, filePath);
2071
2345
  } catch (renameErr) {
@@ -2077,6 +2351,20 @@ var DiskTier = class {
2077
2351
  throw renameErr;
2078
2352
  }
2079
2353
  }
2354
+ if (!current()) {
2355
+ try {
2356
+ await fs.promises.unlink(filePath);
2357
+ } catch {
2358
+ }
2359
+ return false;
2360
+ }
2361
+ for (const previousPath of this.findFilePaths(hash)) {
2362
+ if (previousPath !== filePath) this.removeFile(previousPath);
2363
+ }
2364
+ this.diskUsageBytes += final.length;
2365
+ this.fileCount++;
2366
+ accounted = true;
2367
+ this.invalidatedKeys.delete(key);
2080
2368
  if (this._db) {
2081
2369
  const priority = typeof entry.priority === "number" ? entry.priority : 2;
2082
2370
  const lastAccess = typeof entry.lastAccess === "number" ? entry.lastAccess : Date.now();
@@ -2089,23 +2377,25 @@ var DiskTier = class {
2089
2377
  await fs.promises.unlink(tmpPath);
2090
2378
  } catch {
2091
2379
  }
2092
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
2093
- this.fileCount = Math.max(0, this.fileCount - 1);
2094
- if (this._db) try {
2095
- this._stmtDelete.run(hash);
2096
- } catch {
2097
- }
2380
+ if (accounted) this.removeFile(filePath);
2098
2381
  this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
2099
2382
  throw err;
2383
+ } finally {
2384
+ try {
2385
+ await fs.promises.unlink(tmpPath);
2386
+ } catch {
2387
+ }
2388
+ releaseReservation();
2389
+ if (this.invalidatedKeys.has(key) && !this.pendingSaves.has(key)) this.delete(key, true);
2100
2390
  }
2101
2391
  });
2102
- if (result === null) {
2103
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
2104
- this.fileCount = Math.max(0, this.fileCount - 1);
2392
+ if (result === null && !started) {
2393
+ releaseReservation();
2105
2394
  }
2106
2395
  }
2107
2396
  /** Load a key from disk, or return null on miss/expiry/corruption. */
2108
2397
  load(key) {
2398
+ if (this.invalidatedKeys.has(key) || this.closed) return null;
2109
2399
  if (this.isForbidden(key)) return null;
2110
2400
  this.ensureDir();
2111
2401
  if (!this.dirReady) return null;
@@ -2133,8 +2423,8 @@ var DiskTier = class {
2133
2423
  try {
2134
2424
  if (!this._db) {
2135
2425
  const filename = path.basename(filePath);
2136
- if (filename.length === 77 && filename[64] === "_") {
2137
- const expiresAt = parseInt(filename.slice(65), 16);
2426
+ if (filename.length >= 77 && filename[64] === "_") {
2427
+ const expiresAt = parseInt(filename.slice(65, 77), 16);
2138
2428
  if (expiresAt <= Date.now()) {
2139
2429
  try {
2140
2430
  const sz = fs.statSync(filePath).size;
@@ -2155,12 +2445,7 @@ var DiskTier = class {
2155
2445
  return null;
2156
2446
  }
2157
2447
  const raw = fs.readFileSync(filePath);
2158
- try {
2159
- fs.unlinkSync(filePath);
2160
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
2161
- this.fileCount = Math.max(0, this.fileCount - 1);
2162
- } catch {
2163
- }
2448
+ for (const storedPath of this.findFilePaths(hash)) this.removeFile(storedPath);
2164
2449
  if (this._db) this._stmtDelete.run(hash);
2165
2450
  let decrypted;
2166
2451
  if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
@@ -2195,25 +2480,24 @@ var DiskTier = class {
2195
2480
  return null;
2196
2481
  }
2197
2482
  }
2198
- /** Explicitly delete a key from disk (cache invalidation). */
2199
- delete(key) {
2483
+ /** Synchronously fence queued/running saves while leaving filesystem cleanup deferred. */
2484
+ invalidate(key) {
2485
+ this.pendingSaves.delete(key);
2486
+ this.invalidatedKeys.add(key);
2487
+ }
2488
+ /** Delete all versions; deferred cleanup must not cancel a newer save. */
2489
+ delete(key, invalidatedOnly = false) {
2490
+ if (invalidatedOnly && (!this.invalidatedKeys.has(key) || this.pendingSaves.has(key))) return;
2491
+ if (!invalidatedOnly) this.pendingSaves.delete(key);
2200
2492
  const hash = this.keyToHash(key);
2201
- let filePath;
2493
+ const files = new Set(this.findFilePaths(hash));
2202
2494
  if (this._db) {
2203
2495
  const row = this._stmtSelect.get(hash);
2204
- filePath = row?.file_path ?? null;
2496
+ if (row?.file_path) files.add(row.file_path);
2205
2497
  this._stmtDelete.run(hash);
2206
- } else {
2207
- filePath = this.findFilePath(hash);
2208
- }
2209
- if (!filePath) return;
2210
- try {
2211
- const stat = fs.statSync(filePath);
2212
- fs.unlinkSync(filePath);
2213
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
2214
- this.fileCount = Math.max(0, this.fileCount - 1);
2215
- } catch {
2216
2498
  }
2499
+ for (const file of files) this.removeFile(file);
2500
+ this.invalidatedKeys.delete(key);
2217
2501
  }
2218
2502
  /** Purge all expired entries. Returns number deleted. */
2219
2503
  purgeExpired() {
@@ -2249,8 +2533,8 @@ var DiskTier = class {
2249
2533
  }
2250
2534
  continue;
2251
2535
  }
2252
- if (filename.length === 77 && filename[64] === "_") {
2253
- const expiresAt = parseInt(filename.slice(65), 16);
2536
+ if (filename.length >= 77 && filename[64] === "_") {
2537
+ const expiresAt = parseInt(filename.slice(65, 77), 16);
2254
2538
  if (expiresAt <= now) {
2255
2539
  try {
2256
2540
  const sz = fs.statSync(filePath).size;
@@ -2370,8 +2654,8 @@ var DiskTier = class {
2370
2654
  }
2371
2655
  continue;
2372
2656
  }
2373
- if (file.length === 77 && file[64] === "_") {
2374
- const expiresAt = parseInt(file.slice(65), 16);
2657
+ if (file.length >= 77 && file[64] === "_") {
2658
+ const expiresAt = parseInt(file.slice(65, 77), 16);
2375
2659
  if (expiresAt <= now2) {
2376
2660
  const fp = path.join(orphanBucketP, file);
2377
2661
  try {
@@ -2411,8 +2695,8 @@ var DiskTier = class {
2411
2695
  }
2412
2696
  continue;
2413
2697
  }
2414
- if (file.length === 77 && file[64] === "_") {
2415
- const expiresAt = parseInt(file.slice(65), 16);
2698
+ if (file.length >= 77 && file[64] === "_") {
2699
+ const expiresAt = parseInt(file.slice(65, 77), 16);
2416
2700
  if (expiresAt <= now) {
2417
2701
  const filePath2 = path.join(bucketPath, file);
2418
2702
  try {
@@ -2485,6 +2769,9 @@ var DiskTier = class {
2485
2769
  }
2486
2770
  /** Delete every file in the disk cache. Returns the count deleted. */
2487
2771
  clear() {
2772
+ this.epoch++;
2773
+ this.pendingSaves.clear();
2774
+ this.invalidatedKeys.clear();
2488
2775
  this.ensureDir();
2489
2776
  if (!this.dirReady) return 0;
2490
2777
  let cleared = 0;
@@ -2548,6 +2835,7 @@ var DiskTier = class {
2548
2835
  * yielding to the event loop via setImmediate between chunks.
2549
2836
  */
2550
2837
  async triggerChunkedPrune() {
2838
+ if (this.closed) return 0;
2551
2839
  if (this._isPruning) return 0;
2552
2840
  this._isPruning = true;
2553
2841
  this._pruneRounds++;
@@ -2556,7 +2844,7 @@ var DiskTier = class {
2556
2844
  this.ensureUsageCounted();
2557
2845
  const targetBytes = Math.floor(this.opts.maxBytes * 0.6);
2558
2846
  if (this._db && this._stmtPruneChunk) {
2559
- while (this.diskUsageBytes > targetBytes) {
2847
+ while (!this.closed && this.diskUsageBytes > targetBytes) {
2560
2848
  const rows = this._stmtPruneChunk.all();
2561
2849
  if (!rows || rows.length === 0) break;
2562
2850
  for (const row of rows) {
@@ -2579,7 +2867,7 @@ var DiskTier = class {
2579
2867
  }
2580
2868
  }
2581
2869
  } else {
2582
- while (this.diskUsageBytes > targetBytes) {
2870
+ while (!this.closed && this.diskUsageBytes > targetBytes) {
2583
2871
  const files = this.walkCacheFiles();
2584
2872
  if (files.length === 0) break;
2585
2873
  const chunk = files.slice(0, 500);
@@ -2647,6 +2935,10 @@ var DiskTier = class {
2647
2935
  }
2648
2936
  /** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
2649
2937
  close() {
2938
+ this.closed = true;
2939
+ this.epoch++;
2940
+ this.pendingSaves.clear();
2941
+ this.invalidatedKeys.clear();
2650
2942
  if (this._db) {
2651
2943
  try {
2652
2944
  this._db.close();
@@ -2889,6 +3181,17 @@ function readCgroupMemoryLimit() {
2889
3181
  }
2890
3182
  return Infinity;
2891
3183
  }
3184
+ function readCgroupMemoryUsage() {
3185
+ if (process.platform !== "linux") return null;
3186
+ for (const file of ["/sys/fs/cgroup/memory.current", "/sys/fs/cgroup/memory/memory.usage_in_bytes"]) {
3187
+ try {
3188
+ const value = Number(fs2.readFileSync(file, "utf8").trim());
3189
+ if (Number.isFinite(value) && value >= 0) return value;
3190
+ } catch {
3191
+ }
3192
+ }
3193
+ return null;
3194
+ }
2892
3195
  function getV8HeapLimit() {
2893
3196
  try {
2894
3197
  const stats = v8.getHeapStatistics();
@@ -2912,7 +3215,81 @@ function resolveAutonomousL1MaxBytes(options) {
2912
3215
  return Math.max(MIN_AUTONOMOUS_L1_FLOOR_BYTES, Math.floor(resolved));
2913
3216
  }
2914
3217
 
3218
+ // src/utils/diagnostics.ts
3219
+ function redactDiagnostics(value, seen = /* @__PURE__ */ new WeakSet(), depth = 0) {
3220
+ if (typeof value === "string" && /^[a-z][a-z\d+.-]*:\/\//i.test(value)) {
3221
+ try {
3222
+ const url = new URL(value);
3223
+ if (url.username) url.username = "[REDACTED]";
3224
+ if (url.password) url.password = "[REDACTED]";
3225
+ for (const key of url.searchParams.keys()) {
3226
+ if (/key|token|secret|password|credential|authorization|cookie/i.test(key)) url.searchParams.set(key, "[REDACTED]");
3227
+ }
3228
+ return url.toString();
3229
+ } catch {
3230
+ return "[REDACTED URL]";
3231
+ }
3232
+ }
3233
+ if (value == null || typeof value !== "object") return typeof value === "function" ? void 0 : value;
3234
+ if (depth >= 8) return "[OMITTED]";
3235
+ if (seen.has(value)) return "[CIRCULAR]";
3236
+ seen.add(value);
3237
+ if (Array.isArray(value)) return value.map((item) => redactDiagnostics(item, seen, depth + 1));
3238
+ const result = {};
3239
+ for (const [key, item] of Object.entries(value)) {
3240
+ if (typeof item === "function") continue;
3241
+ result[key] = /key|token|secret|password|credential|authorization|cookie|headers/i.test(key) ? item == null ? item : "[REDACTED]" : redactDiagnostics(item, seen, depth + 1);
3242
+ }
3243
+ return result;
3244
+ }
3245
+
3246
+ // src/utils/redis-slot.ts
3247
+ function redisHashSlot(key) {
3248
+ const open = key.indexOf("{");
3249
+ const close = open < 0 ? -1 : key.indexOf("}", open + 1);
3250
+ const bytes = Buffer.from(close > open + 1 ? key.slice(open + 1, close) : key, "utf8");
3251
+ let crc = 0;
3252
+ for (const byte of bytes) {
3253
+ crc ^= byte << 8;
3254
+ for (let bit = 0; bit < 8; bit++) crc = crc << 1 ^ (crc & 32768 ? 4129 : 0);
3255
+ crc &= 65535;
3256
+ }
3257
+ return crc & 16383;
3258
+ }
3259
+
3260
+ // src/utils/deadline.ts
3261
+ async function withDeadline(operation, timeoutMs, label) {
3262
+ let timer;
3263
+ try {
3264
+ return await Promise.race([
3265
+ operation,
3266
+ new Promise((_resolve, reject) => {
3267
+ timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs);
3268
+ })
3269
+ ]);
3270
+ } finally {
3271
+ if (timer) clearTimeout(timer);
3272
+ }
3273
+ }
3274
+
2915
3275
  // src/adapters/auto-pipeliner.ts
3276
+ import { Cluster } from "ioredis";
3277
+ async function readRedisValue(client, key, hash = false) {
3278
+ if (typeof client.pttl === "function" && typeof client.multi === "function") {
3279
+ const transaction = client.multi();
3280
+ if (typeof transaction.pttl === "function" && (!hash || typeof transaction.hgetall === "function")) {
3281
+ if (hash) transaction.hgetall(key);
3282
+ else transaction.get(key);
3283
+ transaction.pttl(key);
3284
+ const results = await transaction.exec();
3285
+ if (!results) throw new Error("Redis read transaction aborted");
3286
+ if (results[0]?.[0]) throw results[0][0];
3287
+ if (results[1]?.[0]) throw results[1][0];
3288
+ return { raw: results[0]?.[1] ?? null, ttlMs: Number(results[1]?.[1]) };
3289
+ }
3290
+ }
3291
+ return { raw: await (hash ? client.hgetall(key) : client.get(key)) };
3292
+ }
2916
3293
  var AutoPipeliner = class {
2917
3294
  constructor(client, options) {
2918
3295
  this.client = client;
@@ -2944,6 +3321,17 @@ var AutoPipeliner = class {
2944
3321
  this.enqueue({ type: "get", key, resolve, reject });
2945
3322
  });
2946
3323
  }
3324
+ async read(key, hash = false) {
3325
+ if (!hash && typeof this.client.pttl !== "function") return { raw: await this.get(key) };
3326
+ if (!this.enabled || !this.supportsPipelines() || typeof this.client.pttl !== "function") {
3327
+ return readRedisValue(this.client, key, hash);
3328
+ }
3329
+ const probe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
3330
+ if (typeof probe.pttl !== "function" || hash && typeof probe.hgetall !== "function") {
3331
+ return readRedisValue(this.client, key, hash);
3332
+ }
3333
+ return new Promise((resolve, reject) => this.enqueue({ type: "read", key, hash, resolve, reject }));
3334
+ }
2947
3335
  async setex(key, seconds, value) {
2948
3336
  if (!this.enabled || !this.supportsPipelines()) {
2949
3337
  if (typeof this.client.setex === "function") {
@@ -2957,8 +3345,18 @@ var AutoPipeliner = class {
2957
3345
  this.enqueue({ type: "setex", key, seconds, value, resolve, reject });
2958
3346
  });
2959
3347
  }
3348
+ async setpx(key, milliseconds, value) {
3349
+ if (!this.enabled || !this.supportsPipelines()) {
3350
+ await this.client.set(key, value, "PX", milliseconds);
3351
+ return;
3352
+ }
3353
+ return new Promise((resolve, reject) => this.enqueue({ type: "setpx", key, milliseconds, value, resolve, reject }));
3354
+ }
2960
3355
  async del(...keys) {
2961
3356
  if (keys.length === 0) return 0;
3357
+ if (this.client instanceof Cluster && keys.length > 1) {
3358
+ return (await Promise.all(keys.map((key) => this.del(key)))).reduce((sum, value) => sum + value, 0);
3359
+ }
2962
3360
  if (!this.enabled || !this.supportsPipelines()) {
2963
3361
  return this.client.del(...keys);
2964
3362
  }
@@ -2992,44 +3390,72 @@ var AutoPipeliner = class {
2992
3390
  this.scheduled = false;
2993
3391
  this.statsInternal.batchesDispatched++;
2994
3392
  this.statsInternal.operationsBatched += batch.length;
2995
- const pipe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
2996
- for (const op of batch) {
2997
- switch (op.type) {
2998
- case "get":
2999
- pipe.get(op.key);
3000
- break;
3001
- case "setex":
3002
- pipe.setex(op.key, op.seconds, op.value);
3003
- break;
3004
- case "del":
3005
- pipe.del(...op.keys);
3006
- break;
3007
- }
3393
+ if (this.client instanceof Cluster) {
3394
+ const groups = /* @__PURE__ */ new Map();
3395
+ for (const operation of batch) {
3396
+ const key = operation.type === "del" ? operation.keys[0] : operation.key;
3397
+ const slot = redisHashSlot(key);
3398
+ const master = this.client.slots[slot]?.[0] ?? String(slot);
3399
+ const members = groups.get(master) ?? [];
3400
+ members.push(operation);
3401
+ groups.set(master, members);
3402
+ }
3403
+ await Promise.all([...groups.values()].map((members) => this.dispatch(members)));
3404
+ return;
3008
3405
  }
3406
+ await this.dispatch(batch);
3407
+ }
3408
+ async dispatch(batch) {
3009
3409
  try {
3410
+ const pipe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
3411
+ const indexes = [];
3412
+ let commandCount = 0;
3413
+ for (const op of batch) {
3414
+ indexes.push(commandCount++);
3415
+ switch (op.type) {
3416
+ case "get":
3417
+ pipe.get(op.key);
3418
+ break;
3419
+ case "setex":
3420
+ pipe.setex(op.key, op.seconds, op.value);
3421
+ break;
3422
+ case "setpx":
3423
+ pipe.set(op.key, op.value, "PX", op.milliseconds);
3424
+ break;
3425
+ case "del":
3426
+ pipe.del(...op.keys);
3427
+ break;
3428
+ case "read":
3429
+ if (op.hash) pipe.hgetall(op.key);
3430
+ else pipe.get(op.key);
3431
+ pipe.pttl(op.key);
3432
+ commandCount++;
3433
+ break;
3434
+ }
3435
+ }
3010
3436
  const results = await pipe.exec();
3011
3437
  if (!results) {
3012
3438
  for (const op of batch) {
3013
- if (op.type === "get") op.resolve(null);
3014
- else if (op.type === "del") op.resolve(0);
3015
- else op.resolve();
3439
+ op.reject(new Error("Redis pipeline aborted"));
3016
3440
  }
3017
3441
  return;
3018
3442
  }
3019
3443
  for (let i = 0; i < batch.length; i++) {
3020
3444
  const op = batch[i];
3021
- const resTuple = results[i];
3445
+ const resTuple = results[indexes[i]];
3022
3446
  if (!resTuple) {
3023
- if (op.type === "get") op.resolve(null);
3024
- else if (op.type === "del") op.resolve(0);
3025
- else op.resolve();
3447
+ op.reject(new Error("Missing Redis pipeline result"));
3026
3448
  continue;
3027
3449
  }
3028
3450
  const [err, val] = resTuple;
3029
3451
  if (err) {
3030
3452
  op.reject(err instanceof Error ? err : new Error(String(err)));
3031
3453
  } else {
3032
- if (op.type === "get") {
3454
+ if (op.type === "read") {
3455
+ const ttlResult = results[indexes[i] + 1];
3456
+ if (!ttlResult || ttlResult[0]) op.reject(ttlResult?.[0] ?? new Error("Missing Redis PTTL result"));
3457
+ else op.resolve({ raw: val, ttlMs: Number(ttlResult[1]) });
3458
+ } else if (op.type === "get") {
3033
3459
  op.resolve(val != null ? String(val) : null);
3034
3460
  } else if (op.type === "del") {
3035
3461
  op.resolve(typeof val === "number" ? val : Number(val) || 0);
@@ -3066,6 +3492,8 @@ var IpcTelemetryServer = class {
3066
3492
  server = null;
3067
3493
  socketPath;
3068
3494
  _closed = false;
3495
+ _starting = null;
3496
+ sockets = /* @__PURE__ */ new Set();
3069
3497
  _exitHandler = null;
3070
3498
  _sigintHandler = null;
3071
3499
  _sigtermHandler = null;
@@ -3073,10 +3501,23 @@ var IpcTelemetryServer = class {
3073
3501
  * Start listening on the IPC socket / pipe.
3074
3502
  */
3075
3503
  async start() {
3076
- if (this.server && this.server.listening) return;
3504
+ if (this._closed || this.server?.listening) return;
3505
+ if (this._starting) return this._starting;
3506
+ this._starting = this.startInternal();
3507
+ try {
3508
+ await this._starting;
3509
+ } finally {
3510
+ this._starting = null;
3511
+ }
3512
+ }
3513
+ async startInternal() {
3077
3514
  if (process.platform !== "win32" && fs3.existsSync(this.socketPath)) {
3078
3515
  await new Promise((resolve) => {
3079
3516
  const testSocket = net.createConnection(this.socketPath);
3517
+ testSocket.setTimeout(1e3, () => {
3518
+ testSocket.destroy();
3519
+ resolve();
3520
+ });
3080
3521
  testSocket.once("connect", () => {
3081
3522
  testSocket.destroy();
3082
3523
  resolve();
@@ -3091,17 +3532,37 @@ var IpcTelemetryServer = class {
3091
3532
  });
3092
3533
  });
3093
3534
  }
3535
+ if (this._closed) return;
3094
3536
  this.server = net.createServer((socket) => {
3537
+ if (this._closed) {
3538
+ socket.destroy();
3539
+ return;
3540
+ }
3541
+ this.sockets.add(socket);
3542
+ socket.once("close", () => this.sockets.delete(socket));
3543
+ socket.setTimeout(5e3, () => socket.destroy());
3095
3544
  let buffer = "";
3545
+ let pending = 0;
3096
3546
  socket.on("data", (chunk) => {
3547
+ if (Buffer.byteLength(buffer) + chunk.length > 4096 || socket.writableLength > 65536) {
3548
+ socket.destroy();
3549
+ return;
3550
+ }
3097
3551
  buffer += chunk.toString("utf8");
3098
3552
  let newlineIndex;
3099
3553
  while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
3100
3554
  const line = buffer.slice(0, newlineIndex).trim();
3101
3555
  buffer = buffer.slice(newlineIndex + 1);
3102
3556
  if (!line) continue;
3557
+ if (++pending > 8) {
3558
+ socket.destroy();
3559
+ return;
3560
+ }
3103
3561
  setImmediate(() => {
3104
- if (socket.destroyed) return;
3562
+ if (socket.destroyed) {
3563
+ pending--;
3564
+ return;
3565
+ }
3105
3566
  try {
3106
3567
  let cmd = line;
3107
3568
  try {
@@ -3126,6 +3587,8 @@ var IpcTelemetryServer = class {
3126
3587
  if (!socket.destroyed) {
3127
3588
  socket.write(JSON.stringify({ error: err.message }) + "\n");
3128
3589
  }
3590
+ } finally {
3591
+ pending--;
3129
3592
  }
3130
3593
  });
3131
3594
  }
@@ -3133,21 +3596,38 @@ var IpcTelemetryServer = class {
3133
3596
  socket.on("error", () => {
3134
3597
  });
3135
3598
  });
3599
+ this.server.maxConnections = 128;
3136
3600
  await new Promise((resolve, reject) => {
3137
- this.server.once("error", reject);
3138
- this.server.listen(this.socketPath, () => {
3139
- this.server.removeListener("error", reject);
3601
+ const server = this.server;
3602
+ const cleanup = () => {
3603
+ server.off("error", failed);
3604
+ server.off("close", closed);
3605
+ };
3606
+ const failed = (error) => {
3607
+ cleanup();
3608
+ reject(error);
3609
+ };
3610
+ const closed = () => {
3611
+ cleanup();
3612
+ resolve();
3613
+ };
3614
+ server.once("error", failed);
3615
+ server.once("close", closed);
3616
+ server.listen(this.socketPath, () => {
3617
+ cleanup();
3140
3618
  resolve();
3141
3619
  });
3142
3620
  });
3621
+ if (this._closed) {
3622
+ if (this.server.listening) this.server.close();
3623
+ return;
3624
+ }
3143
3625
  this._exitHandler = () => this._unlinkSocket();
3144
3626
  this._sigintHandler = () => {
3145
3627
  this._unlinkSocket();
3146
- process.exit(0);
3147
3628
  };
3148
3629
  this._sigtermHandler = () => {
3149
3630
  this._unlinkSocket();
3150
- process.exit(0);
3151
3631
  };
3152
3632
  process.once("exit", this._exitHandler);
3153
3633
  process.once("SIGINT", this._sigintHandler);
@@ -3177,6 +3657,7 @@ var IpcTelemetryServer = class {
3177
3657
  _unlinkSocket() {
3178
3658
  if (this._closed) return;
3179
3659
  this._closed = true;
3660
+ for (const socket of this.sockets) socket.destroy();
3180
3661
  try {
3181
3662
  this.server?.close();
3182
3663
  } catch {
@@ -3194,6 +3675,9 @@ var IpcTelemetryServer = class {
3194
3675
  * Gracefully close the IPC telemetry server and clean up handlers and sockets.
3195
3676
  */
3196
3677
  async close() {
3678
+ this._unlinkSocket();
3679
+ await this._starting?.catch(() => {
3680
+ });
3197
3681
  if (this._exitHandler) {
3198
3682
  process.removeListener("exit", this._exitHandler);
3199
3683
  this._exitHandler = null;
@@ -3206,7 +3690,6 @@ var IpcTelemetryServer = class {
3206
3690
  process.removeListener("SIGTERM", this._sigtermHandler);
3207
3691
  this._sigtermHandler = null;
3208
3692
  }
3209
- this._unlinkSocket();
3210
3693
  return new Promise((resolve) => {
3211
3694
  if (!this.server || !this.server.listening) {
3212
3695
  resolve();
@@ -3443,6 +3926,37 @@ if currentTs and currentTs == ARGV[1] then
3443
3926
  end
3444
3927
  return 0
3445
3928
  `;
3929
+ var LUA_READ_CACHE_ENTRY = `
3930
+ local kind = redis.call('TYPE', KEYS[1]).ok
3931
+ if kind == 'string' then
3932
+ return { kind, redis.call('GET', KEYS[1]), redis.call('PTTL', KEYS[1]) }
3933
+ elseif kind == 'hash' then
3934
+ return { kind, redis.call('HGETALL', KEYS[1]), redis.call('PTTL', KEYS[1]) }
3935
+ end
3936
+ return { 'none', false, -2 }
3937
+ `;
3938
+ var LUA_MAX_TAG_VERSION = `
3939
+ local current = tonumber(redis.call('GET', KEYS[1]) or '0')
3940
+ local floor = tonumber(ARGV[1])
3941
+ if current < floor then redis.call('SET', KEYS[1], floor) return floor end
3942
+ return current
3943
+ `;
3944
+ var LUA_RECEIVE_TAG_VERSION = `
3945
+ local current = tonumber(redis.call('GET', KEYS[1]) or '0')
3946
+ local next = math.max(current + 1, tonumber(ARGV[1]))
3947
+ redis.call('SET', KEYS[1], next)
3948
+ return next
3949
+ `;
3950
+ var LUA_TOUCH_CACHE_ENTRY = `
3951
+ local kind = redis.call('TYPE', KEYS[1]).ok
3952
+ if kind == 'hash' then
3953
+ if redis.call('HGET', KEYS[1], 't') ~= ARGV[1] then return 0 end
3954
+ redis.call('HSET', KEYS[1], 'e', ARGV[2])
3955
+ elseif kind ~= 'string' then
3956
+ return 0
3957
+ end
3958
+ return redis.call('PEXPIRE', KEYS[1], ARGV[3])
3959
+ `;
3446
3960
  var SNAPSHOT_VERSION = 1;
3447
3961
  var DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
3448
3962
  var INDEFINITE_TTL_SECONDS = 31536e3;
@@ -3731,13 +4245,19 @@ var CacheService = class _CacheService {
3731
4245
  _l1Counters = /* @__PURE__ */ new Map();
3732
4246
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
3733
4247
  tagIndex = /* @__PURE__ */ new Map();
4248
+ /** Reverse index of namespaced key → { tags, expiresAt } for bounded cleanup on eviction/delete */
4249
+ keyTags = /* @__PURE__ */ new Map();
3734
4250
  /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
3735
4251
  tagVersions = /* @__PURE__ */ new Map();
4252
+ _tagRefreshEpoch = 0;
3736
4253
  /**
3737
4254
  * Dependency index: source glob pattern → Set of namespaced dependent keys.
3738
4255
  * When an exact-key delete matches a registered pattern, all dependents are cascaded.
3739
4256
  */
3740
4257
  dependencyIndex = /* @__PURE__ */ new Map();
4258
+ /** Reverse index of namespaced dependent key → source glob patterns */
4259
+ keyDependencies = /* @__PURE__ */ new Map();
4260
+ _cgroupMemoryLimit;
3741
4261
  redis = null;
3742
4262
  redisConnecting = null;
3743
4263
  cb;
@@ -3760,9 +4280,17 @@ var CacheService = class _CacheService {
3760
4280
  subClient = null;
3761
4281
  streamClient = null;
3762
4282
  _lastStreamId = "$";
4283
+ _restoredSnapshot = false;
4284
+ _backplaneAvailable = false;
4285
+ _otelCleanup = null;
4286
+ _streamRecovering = false;
4287
+ _backplaneDisposers = [];
3763
4288
  _destroyed = false;
3764
4289
  _pendingDiskDeletes = /* @__PURE__ */ new Set();
3765
4290
  _globalEpoch = 0;
4291
+ _pendingSpillCount = 0;
4292
+ _suppressSpills = false;
4293
+ _diskCleanupScheduled = false;
3766
4294
  _keyMutationEpochs = /* @__PURE__ */ new Map();
3767
4295
  /**
3768
4296
  * Pattern tombstones for disk tier.
@@ -3771,20 +4299,24 @@ var CacheService = class _CacheService {
3771
4299
  * pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
3772
4300
  */
3773
4301
  _patternTombstones = [];
3774
- _addPatternTombstone(prefix) {
4302
+ _diskInvalidatedBefore = 0;
4303
+ _addPatternTombstone(pattern) {
3775
4304
  const now = Date.now();
3776
4305
  while (this._patternTombstones.length > 0 && now - this._patternTombstones[0].createdAt > 36e5) {
3777
- this._patternTombstones.shift();
4306
+ const forgotten = this._patternTombstones.shift();
4307
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
3778
4308
  }
3779
4309
  if (this._patternTombstones.length >= 2e3) {
3780
- this._patternTombstones.shift();
4310
+ const forgotten = this._patternTombstones.shift();
4311
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
3781
4312
  }
3782
- this._patternTombstones.push({ prefix, createdAt: now });
4313
+ this._patternTombstones.push({ pattern, createdAt: now });
3783
4314
  }
3784
- _isTombstonedByPattern(namespacedKey) {
4315
+ _isTombstonedByPattern(namespacedKey, setAt = 0) {
4316
+ if (this._diskInvalidatedBefore > 0 && setAt <= this._diskInvalidatedBefore) return true;
3785
4317
  if (this._patternTombstones.length === 0) return false;
3786
4318
  for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
3787
- if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
4319
+ if (setAt <= this._patternTombstones[i].createdAt && this._matchesGlob(namespacedKey, this._patternTombstones[i].pattern)) {
3788
4320
  return true;
3789
4321
  }
3790
4322
  }
@@ -3799,13 +4331,170 @@ var CacheService = class _CacheService {
3799
4331
  const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
3800
4332
  this._keyMutationEpochs.set(namespacedKey, next);
3801
4333
  if (this._keyMutationEpochs.size > 5e4) {
3802
- const oldest = this._keyMutationEpochs.keys().next().value;
3803
- if (oldest !== void 0) this._keyMutationEpochs.delete(oldest);
4334
+ this._globalEpoch++;
4335
+ this._keyMutationEpochs.clear();
4336
+ this._keyMutationEpochs.set(namespacedKey, next);
3804
4337
  }
3805
4338
  return next;
3806
4339
  }
3807
4340
  _getKeyMutationEpoch(namespacedKey) {
3808
- return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
4341
+ return `${this._globalEpoch}:${this._keyMutationEpochs.get(namespacedKey) ?? 0}`;
4342
+ }
4343
+ /** Capture a commit fence before asynchronous computation outside the cache. */
4344
+ captureMutationFence(cacheKey) {
4345
+ this._assertActive("captureMutationFence");
4346
+ const key = this.nk(cacheKey);
4347
+ const epoch = this._getKeyMutationEpoch(key);
4348
+ return () => !this._destroyed && this._getKeyMutationEpoch(key) === epoch;
4349
+ }
4350
+ /** Force tag re-sync without forgetting locally observed monotonic generations. */
4351
+ refreshTagVersions() {
4352
+ this._assertActive("refreshTagVersions");
4353
+ this._tagRefreshEpoch++;
4354
+ }
4355
+ _fenceInvalidation() {
4356
+ this._globalEpoch++;
4357
+ this.inflight.clear();
4358
+ }
4359
+ _invalidateDiskKey(key) {
4360
+ if (this._diskDisabled) return;
4361
+ this.disk.invalidate(key);
4362
+ this._pendingDiskDeletes.add(key);
4363
+ this._scheduleDiskCleanup();
4364
+ }
4365
+ _scheduleDiskCleanup() {
4366
+ if (this._diskCleanupScheduled || this._pendingDiskDeletes.size === 0) return;
4367
+ this._diskCleanupScheduled = true;
4368
+ setImmediate(() => {
4369
+ this._diskCleanupScheduled = false;
4370
+ if (this._destroyed) return;
4371
+ let processed = 0;
4372
+ for (const key of this._pendingDiskDeletes) {
4373
+ try {
4374
+ this.disk.delete(key, true);
4375
+ } finally {
4376
+ this._pendingDiskDeletes.delete(key);
4377
+ }
4378
+ if (++processed >= 16) break;
4379
+ }
4380
+ this._scheduleDiskCleanup();
4381
+ });
4382
+ }
4383
+ _registerDependencies(key, patterns) {
4384
+ this._removeKeyDependencies(key);
4385
+ if (!patterns?.length) return;
4386
+ const namespaced = [...new Set(patterns.map((pattern) => this.nk(pattern)))];
4387
+ for (const pattern of namespaced) {
4388
+ const dependents = this.dependencyIndex.get(pattern) ?? /* @__PURE__ */ new Set();
4389
+ dependents.add(key);
4390
+ this.dependencyIndex.set(pattern, dependents);
4391
+ }
4392
+ this.keyDependencies.set(key, namespaced);
4393
+ }
4394
+ _rememberTags(key, tags, expiresAt) {
4395
+ this._removeKeyTags(key);
4396
+ if (!tags.length) return;
4397
+ if (this.keyTags.size >= 1e5) {
4398
+ this._sweepExpiredMetadata();
4399
+ const oldest = this.keyTags.keys().next().value;
4400
+ if (this.keyTags.size >= 1e5 && oldest !== void 0) this._removeKeyTags(oldest);
4401
+ }
4402
+ const unique = [...new Set(tags)];
4403
+ for (const tag of unique) {
4404
+ const tagKey = this.nk(`_tag_:${tag}`);
4405
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
4406
+ members.add(key);
4407
+ this.tagIndex.set(tagKey, members);
4408
+ }
4409
+ this.keyTags.set(key, { tags: unique, expiresAt });
4410
+ }
4411
+ _restoreEntryMetadata(key, entry) {
4412
+ if (entry.tags?.length) this._rememberTags(key, entry.tags, entry.expiresAt);
4413
+ if (entry.dependsOn?.length) this._registerDependencies(key, entry.dependsOn);
4414
+ }
4415
+ _removeKeyTags(namespacedKey) {
4416
+ const entry = this.keyTags.get(namespacedKey);
4417
+ if (!entry) return;
4418
+ for (const tag of entry.tags) {
4419
+ const tagKey = this.nk(`_tag_:${tag}`);
4420
+ const members = this.tagIndex.get(tagKey);
4421
+ if (members) {
4422
+ members.delete(namespacedKey);
4423
+ if (members.size === 0) this.tagIndex.delete(tagKey);
4424
+ }
4425
+ }
4426
+ this.keyTags.delete(namespacedKey);
4427
+ }
4428
+ _removeKeyDependencies(namespacedKey) {
4429
+ const patterns = this.keyDependencies.get(namespacedKey);
4430
+ if (patterns) {
4431
+ for (const pat of patterns) {
4432
+ const deps = this.dependencyIndex.get(pat);
4433
+ if (deps) {
4434
+ deps.delete(namespacedKey);
4435
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
4436
+ }
4437
+ }
4438
+ this.keyDependencies.delete(namespacedKey);
4439
+ } else if (this.dependencyIndex.size > 0) {
4440
+ for (const [pat, deps] of this.dependencyIndex) {
4441
+ deps.delete(namespacedKey);
4442
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
4443
+ }
4444
+ }
4445
+ }
4446
+ _handleL1Eviction(namespacedKey, reason) {
4447
+ const spilledToDisk = !this._diskDisabled && !this._suppressSpills && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
4448
+ if (!spilledToDisk) {
4449
+ this._removeKeyTags(namespacedKey);
4450
+ this._removeKeyDependencies(namespacedKey);
4451
+ }
4452
+ }
4453
+ _removePatternFromIndices(pattern) {
4454
+ for (const k of Array.from(this.keyTags.keys())) {
4455
+ if (this._matchesGlob(k, pattern)) this._removeKeyTags(k);
4456
+ }
4457
+ for (const k of Array.from(this.keyDependencies.keys())) {
4458
+ if (this._matchesGlob(k, pattern)) this._removeKeyDependencies(k);
4459
+ }
4460
+ for (const k of Array.from(this._l1Counters.keys())) {
4461
+ if (this._matchesGlob(k, pattern)) this._l1Counters.delete(k);
4462
+ }
4463
+ }
4464
+ _sweepExpiredMetadata() {
4465
+ const now = Date.now();
4466
+ for (const [k, c] of this._l1Counters) {
4467
+ if (c.expiresAt <= now) this._l1Counters.delete(k);
4468
+ }
4469
+ for (const [k, meta] of this.keyTags) {
4470
+ if (meta.expiresAt <= now && !this.l1.has(k)) {
4471
+ this._removeKeyTags(k);
4472
+ this._removeKeyDependencies(k);
4473
+ }
4474
+ }
4475
+ }
4476
+ _runOomCheck() {
4477
+ const heap = v82.getHeapStatistics();
4478
+ const heapUsed = heap.used_heap_size / heap.heap_size_limit;
4479
+ const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? (readCgroupMemoryUsage() ?? process.memoryUsage().rss) / this._cgroupMemoryLimit : 0;
4480
+ const used = Math.max(heapUsed, cgroupUsed);
4481
+ if (used >= this.opts.oomHeapThreshold) {
4482
+ this._suppressSpills = cgroupUsed >= this.opts.oomHeapThreshold;
4483
+ let evicted;
4484
+ try {
4485
+ evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
4486
+ } finally {
4487
+ this._suppressSpills = false;
4488
+ }
4489
+ this.counters.oomEvictions++;
4490
+ this.counters.oomLastAt = Date.now();
4491
+ this.logger.warn("tricache OOM guard: emergency L1 eviction", {
4492
+ heapUsedPct: Math.round(heapUsed * 100),
4493
+ cgroupUsedPct: cgroupUsed > 0 ? Math.round(cgroupUsed * 100) : void 0,
4494
+ threshold: Math.round(this.opts.oomHeapThreshold * 100),
4495
+ evicted
4496
+ });
4497
+ }
3809
4498
  }
3810
4499
  _ipcServer;
3811
4500
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
@@ -3853,6 +4542,7 @@ var CacheService = class _CacheService {
3853
4542
  constructor(options = {}) {
3854
4543
  const logger = options.logger ?? consoleLogger;
3855
4544
  this.logger = logger;
4545
+ this._cgroupMemoryLimit = readCgroupMemoryLimit();
3856
4546
  const ns = options.namespace?.trim() ?? "";
3857
4547
  const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
3858
4548
  this.enc = new CacheEncryption(
@@ -4031,12 +4721,19 @@ var CacheService = class _CacheService {
4031
4721
  admissionPolicy: this.opts.l1AdmissionPolicy,
4032
4722
  codec: this.codec,
4033
4723
  diskSpill: (key, entry) => {
4034
- if (this._diskDisabled) return;
4724
+ if (this._diskDisabled || this._suppressSpills) return;
4725
+ if (this._pendingSpillCount >= (this.opts.diskMaxPendingWrites ?? 512)) return;
4726
+ const epoch = this._getKeyMutationEpoch(key);
4727
+ this._pendingSpillCount++;
4035
4728
  setImmediate(() => {
4036
- void this.disk.save(key, entry);
4729
+ this._pendingSpillCount--;
4730
+ if (!this._destroyed && this._getKeyMutationEpoch(key) === epoch) void this.disk.save(key, entry);
4037
4731
  });
4038
4732
  },
4039
- onEviction: options.onEviction,
4733
+ onEviction: (key, reason) => {
4734
+ this._handleL1Eviction(key, reason);
4735
+ options.onEviction?.(key, reason);
4736
+ },
4040
4737
  logger
4041
4738
  });
4042
4739
  if (!this.snapshotLoaded) {
@@ -4074,6 +4771,7 @@ var CacheService = class _CacheService {
4074
4771
  }
4075
4772
  this.cleanupInterval = setInterval(() => {
4076
4773
  const cleaned = this.l1.cleanup();
4774
+ this._sweepExpiredMetadata();
4077
4775
  if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
4078
4776
  }, 5 * 60 * 1e3);
4079
4777
  if (this.cleanupInterval.unref) this.cleanupInterval.unref();
@@ -4086,18 +4784,7 @@ var CacheService = class _CacheService {
4086
4784
  }
4087
4785
  if (this.opts.oomProtection) {
4088
4786
  this.oomInterval = setInterval(() => {
4089
- const heap = v82.getHeapStatistics();
4090
- const used = heap.used_heap_size / heap.heap_size_limit;
4091
- if (used >= this.opts.oomHeapThreshold) {
4092
- const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
4093
- this.counters.oomEvictions++;
4094
- this.counters.oomLastAt = Date.now();
4095
- this.logger.warn("tricache OOM guard: emergency L1 eviction", {
4096
- heapUsedPct: Math.round(used * 100),
4097
- threshold: Math.round(this.opts.oomHeapThreshold * 100),
4098
- evicted
4099
- });
4100
- }
4787
+ this._runOomCheck();
4101
4788
  }, this.opts.oomCheckIntervalMs);
4102
4789
  if (this.oomInterval.unref) this.oomInterval.unref();
4103
4790
  }
@@ -4119,7 +4806,7 @@ var CacheService = class _CacheService {
4119
4806
  this.instanceId = crypto2.randomBytes(8).toString("hex");
4120
4807
  this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
4121
4808
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
4122
- this.initBackplane();
4809
+ 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 }));
4123
4810
  const startupPromises = [];
4124
4811
  if (this.opts.compression === "zstd") {
4125
4812
  startupPromises.push(initZstd().then(() => void 0));
@@ -4130,9 +4817,8 @@ var CacheService = class _CacheService {
4130
4817
  if (this.opts.warmKeys) {
4131
4818
  startupPromises.push(this.warmFromL2(this.opts.warmKeys).then(() => void 0));
4132
4819
  }
4133
- if (startupPromises.length > 0) {
4134
- this._readyPromise = Promise.all(startupPromises).then(() => void 0);
4135
- }
4820
+ const backplaneReady = this.opts.remoteSnapshot || this.opts.warmKeys ? Promise.all(startupPromises).then(startBackplane) : startBackplane();
4821
+ this._readyPromise = Promise.all([...startupPromises, backplaneReady]).then(() => void 0);
4136
4822
  if (this.opts.meter) {
4137
4823
  this._initOtelMetrics(this.opts.meter);
4138
4824
  const otel = this._otelMetrics;
@@ -4145,7 +4831,10 @@ var CacheService = class _CacheService {
4145
4831
  if (typeof prop === "string" && typeof value === "number" && typeof oldVal === "number") {
4146
4832
  const diff = value - oldVal;
4147
4833
  if (diff > 0 && otel[prop]) {
4148
- otel[prop].add(diff, nsAttr);
4834
+ try {
4835
+ otel[prop].add(diff, nsAttr);
4836
+ } catch {
4837
+ }
4149
4838
  }
4150
4839
  }
4151
4840
  return ok;
@@ -4237,7 +4926,7 @@ var CacheService = class _CacheService {
4237
4926
  return g[key];
4238
4927
  }
4239
4928
  const existing = g[key];
4240
- const diff = _CacheService.optionsDiff(options ?? {}, existing.options);
4929
+ const diff = _CacheService.optionsDiff(options ?? {}, existing.opts);
4241
4930
  if (diff.length > 0) {
4242
4931
  existing.bumpSingletonDivergence();
4243
4932
  const msg = `tricache: singleton already initialised for namespace '${existing.options.namespace || "(default)"}' \u2014 ignoring divergent options: ${diff.join(", ")}`;
@@ -4271,7 +4960,13 @@ var CacheService = class _CacheService {
4271
4960
  "instanceName",
4272
4961
  "invalidationBackplane",
4273
4962
  "awaitInvalidationBackplane",
4274
- "lockFailClosed"
4963
+ "lockFailClosed",
4964
+ "tagStrategy",
4965
+ "cloneStrategy",
4966
+ "compression",
4967
+ "backplaneMode",
4968
+ "redisProtocol",
4969
+ "failClosed"
4275
4970
  ];
4276
4971
  /** Returns the names of options that differ between `a` and the live `b`. */
4277
4972
  static optionsDiff(a, b) {
@@ -4289,12 +4984,12 @@ var CacheService = class _CacheService {
4289
4984
  bumpSingletonDivergence() {
4290
4985
  this.counters.singletonDivergences++;
4291
4986
  }
4292
- /** Read-only view of the options the singleton was constructed with. */
4987
+ /** Sanitized diagnostic view; retain the original options/adapters to reuse configuration. */
4293
4988
  get options() {
4294
4989
  const o = this.opts;
4295
4990
  return {
4296
4991
  namespace: o.namespace,
4297
- logger: o.logger,
4992
+ 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) },
4298
4993
  l1MaxBytes: o.l1MaxBytes,
4299
4994
  l1MaxEntries: o.l1MaxEntries,
4300
4995
  redisHost: o.redisHost,
@@ -4315,8 +5010,8 @@ var CacheService = class _CacheService {
4315
5010
  awaitInvalidationBackplane: o.awaitInvalidationBackplane,
4316
5011
  lockFailClosed: o.lockFailClosed,
4317
5012
  strictSingleton: o.strictSingleton,
4318
- remoteSnapshot: o.remoteSnapshot,
4319
- crossRegion: o.crossRegion
5013
+ remoteSnapshot: redactDiagnostics(o.remoteSnapshot),
5014
+ crossRegion: redactDiagnostics(o.crossRegion)
4320
5015
  };
4321
5016
  }
4322
5017
  /**
@@ -4399,11 +5094,15 @@ var CacheService = class _CacheService {
4399
5094
  if (this.opts.redisClient && typeof this.opts.redisClient.duplicate === "function") {
4400
5095
  return this.opts.redisClient.duplicate();
4401
5096
  }
5097
+ if (this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel) {
5098
+ throw new Error("Invalidation backplane requires redisSubClient or a driver supporting duplicate()");
5099
+ }
4402
5100
  if (this.opts.redisClusterNodes?.length) {
4403
5101
  return new RedisCluster(this.opts.redisClusterNodes, {
4404
5102
  redisOptions: {
4405
5103
  tls: this.opts.redisTls ? {} : void 0,
4406
5104
  connectTimeout: 1e4,
5105
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
4407
5106
  maxRetriesPerRequest: null,
4408
5107
  ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
4409
5108
  }
@@ -4414,6 +5113,7 @@ var CacheService = class _CacheService {
4414
5113
  name: this.opts.redisSentinel.name,
4415
5114
  tls: this.opts.redisTls ? {} : void 0,
4416
5115
  connectTimeout: 1e4,
5116
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
4417
5117
  lazyConnect: true,
4418
5118
  maxRetriesPerRequest: null,
4419
5119
  enableAutoPipelining: false,
@@ -4426,6 +5126,7 @@ var CacheService = class _CacheService {
4426
5126
  port: this.opts.redisPort,
4427
5127
  tls: this.opts.redisTls ? {} : void 0,
4428
5128
  connectTimeout: 1e4,
5129
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
4429
5130
  lazyConnect: true,
4430
5131
  maxRetriesPerRequest: null,
4431
5132
  enableAutoPipelining: false,
@@ -4435,26 +5136,32 @@ var CacheService = class _CacheService {
4435
5136
  });
4436
5137
  }
4437
5138
  }
4438
- initBackplane() {
5139
+ _listenBackplane(client, event, listener) {
5140
+ client.on?.(event, listener);
5141
+ this._backplaneDisposers.push(() => client.removeListener?.(event, listener));
5142
+ }
5143
+ async initBackplane() {
4439
5144
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
4440
5145
  if (this.opts.backplaneMode === "stream") {
4441
5146
  if (this.streamClient) return;
4442
- void this._startStreamConsumer();
5147
+ await this._startStreamConsumer();
4443
5148
  return;
4444
5149
  }
4445
5150
  if (this.subClient) return;
4446
5151
  const sub = this.createDedicatedRedisClient();
4447
- sub.on("error", (e) => {
5152
+ this.subClient = sub;
5153
+ this._listenBackplane(sub, "error", (e) => {
4448
5154
  this._checkAndLogResp3Hint(e);
4449
5155
  this.logger.debug("Backplane subscriber error", { error: e.message });
4450
5156
  });
4451
- sub.on("close", () => {
5157
+ this._listenBackplane(sub, "close", () => {
5158
+ this._backplaneAvailable = false;
4452
5159
  if (this._subDisconnectedAt === null) {
4453
5160
  this._subDisconnectedAt = Date.now();
4454
5161
  this.logger.debug("Backplane: subscriber disconnected", { at: this._subDisconnectedAt });
4455
5162
  }
4456
5163
  });
4457
- sub.on("ready", () => {
5164
+ this._listenBackplane(sub, "ready", () => {
4458
5165
  if (this._subDisconnectedAt !== null && this.opts.backplaneMaxStalenessMs > 0) {
4459
5166
  const gapMs = Date.now() - this._subDisconnectedAt;
4460
5167
  if (gapMs > this.opts.backplaneMaxStalenessMs) {
@@ -4467,52 +5174,119 @@ var CacheService = class _CacheService {
4467
5174
  }
4468
5175
  this._subDisconnectedAt = null;
4469
5176
  }
5177
+ if (!this._destroyed) this._backplaneAvailable = true;
4470
5178
  });
4471
5179
  const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
4472
5180
  if (isClusterSharded) {
4473
- sub.on("smessage", (_channel, message) => {
5181
+ this._listenBackplane(sub, "smessage", (_channel, message) => {
4474
5182
  this._handleBackplaneMessage(message);
4475
5183
  });
4476
- sub.ssubscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: sharded subscribed", {
5184
+ if (typeof sub.connect === "function" && (sub.isOpen === false || sub.status === "wait")) await sub.connect();
5185
+ await sub.ssubscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: sharded subscribed", {
4477
5186
  channel: this.backplaneChannel,
4478
5187
  instanceId: this.instanceId
4479
- })).catch((err) => this.logger.warn("Backplane: sharded subscribe failed", {
4480
- error: err.message
4481
5188
  }));
4482
5189
  } else {
4483
- sub.on("message", (_channel, message) => {
5190
+ this._listenBackplane(sub, "message", (_channel, message) => {
4484
5191
  this._handleBackplaneMessage(message);
4485
5192
  });
4486
- sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
5193
+ if (typeof sub.connect === "function" && (sub.isOpen === false || sub.status === "wait")) await sub.connect();
5194
+ if (this._destroyed) return;
5195
+ await sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
4487
5196
  channel: this.backplaneChannel,
4488
5197
  instanceId: this.instanceId
4489
- })).catch((err) => this.logger.warn("Backplane: subscribe failed", {
4490
- error: err.message
4491
5198
  }));
4492
5199
  }
4493
- this.subClient = sub;
5200
+ if (!this._destroyed) this._backplaneAvailable = true;
5201
+ }
5202
+ _resetAfterStreamGap() {
5203
+ this.counters.streamGaps++;
5204
+ this._fenceInvalidation();
5205
+ this.l1.clear();
5206
+ this.tagIndex.clear();
5207
+ this.keyTags.clear();
5208
+ this.tagVersions.clear();
5209
+ this.dependencyIndex.clear();
5210
+ this.keyDependencies.clear();
5211
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, Date.now());
5212
+ this._addPatternTombstone(this.nk("*"));
5213
+ this._lastStreamId = "0-0";
4494
5214
  }
4495
5215
  async _startStreamConsumer() {
5216
+ this._streamRecovering ||= this._lastStreamId !== "$" && this._lastStreamId !== "0-0";
4496
5217
  const sub = this.streamClient ?? this.createDedicatedRedisClient();
4497
5218
  this.streamClient = sub;
5219
+ if (typeof sub.xread !== "function") throw new Error("backplaneMode: stream requires a driver supporting XREAD");
4498
5220
  if (typeof sub.on === "function") {
4499
- sub.on("error", (e) => this.logger.debug("Backplane stream consumer error", { error: e.message }));
4500
- sub.on("close", () => {
5221
+ this._listenBackplane(sub, "error", (e) => this.logger.debug("Backplane stream consumer error", { error: e.message }));
5222
+ this._listenBackplane(sub, "close", () => {
5223
+ this._streamRecovering = true;
5224
+ this._backplaneAvailable = false;
4501
5225
  if (this._subDisconnectedAt === null) {
4502
5226
  this._subDisconnectedAt = Date.now();
4503
5227
  this.logger.debug("Backplane stream: consumer disconnected", { at: this._subDisconnectedAt });
4504
5228
  }
4505
5229
  });
4506
- sub.on("ready", () => {
5230
+ this._listenBackplane(sub, "ready", () => {
4507
5231
  if (this._subDisconnectedAt !== null) {
4508
5232
  this.logger.debug("Backplane stream: consumer reconnected, resuming stream read", { lastId: this._lastStreamId });
4509
5233
  this._subDisconnectedAt = null;
4510
5234
  }
4511
5235
  });
4512
5236
  }
5237
+ const checkGap = async () => {
5238
+ if (this._lastStreamId === "$" || this._lastStreamId === "0-0" || typeof sub.xrange !== "function") return;
5239
+ const first = await sub.xrange(this.backplaneStreamKey, "-", "+", "COUNT", 1);
5240
+ const firstId = first?.[0]?.[0];
5241
+ if (!firstId) return;
5242
+ const [firstMs, firstSequence] = firstId.split("-").map(BigInt);
5243
+ const [lastMs, lastSequence] = this._lastStreamId.split("-").map(BigInt);
5244
+ if (firstMs > lastMs || firstMs === lastMs && firstSequence > lastSequence) this._resetAfterStreamGap();
5245
+ };
5246
+ const apply = (response) => {
5247
+ if (this._destroyed || !response) return;
5248
+ if (this._streamRecovering && response.some(([, entries]) => entries.length > 0)) {
5249
+ this.counters.streamReplays++;
5250
+ this._streamRecovering = false;
5251
+ }
5252
+ for (const [, entries] of response) {
5253
+ for (const [id, fields] of entries) {
5254
+ this._lastStreamId = id;
5255
+ this.counters.streamEntriesReceived++;
5256
+ this._processStreamEntry(fields);
5257
+ }
5258
+ }
5259
+ };
5260
+ let initialized = false;
5261
+ const initialize = async () => {
5262
+ if (typeof sub.connect === "function" && (sub.isOpen === false || sub.status === "wait")) await sub.connect();
5263
+ if (this._destroyed) return;
5264
+ if (this._lastStreamId === "$") {
5265
+ if (this._restoredSnapshot) this._resetAfterStreamGap();
5266
+ else if (typeof sub.xrevrange === "function") {
5267
+ const latest = await sub.xrevrange(this.backplaneStreamKey, "+", "-", "COUNT", 1);
5268
+ this._lastStreamId = latest?.[0]?.[0] ?? "0-0";
5269
+ } else this._lastStreamId = "0-0";
5270
+ }
5271
+ if (typeof sub.xrange === "function") {
5272
+ await checkGap();
5273
+ apply(await sub.xread("STREAMS", this.backplaneStreamKey, this._lastStreamId));
5274
+ }
5275
+ initialized = true;
5276
+ this._backplaneAvailable = true;
5277
+ };
5278
+ try {
5279
+ await initialize();
5280
+ } catch (error) {
5281
+ this._backplaneAvailable = false;
5282
+ this.logger.warn("Backplane stream initialization failed; retrying in consumer loop", { error: error.message });
5283
+ }
4513
5284
  const runLoop = async () => {
4514
5285
  while (!this._destroyed && !this._redisDisabled) {
4515
5286
  try {
5287
+ if (!initialized) await initialize();
5288
+ if (this._destroyed) break;
5289
+ await checkGap();
4516
5290
  const res = await sub.xread(
4517
5291
  "BLOCK",
4518
5292
  this.opts.backplaneStreamBlockMs,
@@ -4521,19 +5295,10 @@ var CacheService = class _CacheService {
4521
5295
  this._lastStreamId
4522
5296
  );
4523
5297
  if (this._destroyed) break;
5298
+ this._backplaneAvailable = true;
4524
5299
  if (res && res.length > 0) {
4525
- for (const [, entries] of res) {
4526
- if (entries.length > 0) {
4527
- if (this._lastStreamId !== "$") {
4528
- this.counters.streamReplays++;
4529
- }
4530
- for (const [id, fields] of entries) {
4531
- this._lastStreamId = id;
4532
- this.counters.streamEntriesReceived++;
4533
- this._processStreamEntry(fields);
4534
- }
4535
- }
4536
- }
5300
+ apply(res);
5301
+ this._backplaneAvailable = true;
4537
5302
  } else {
4538
5303
  await new Promise((resolve) => setTimeout(resolve, 10));
4539
5304
  }
@@ -4541,10 +5306,9 @@ var CacheService = class _CacheService {
4541
5306
  if (this._destroyed) break;
4542
5307
  const msg = err.message ?? "";
4543
5308
  if (msg.includes("NOGROUP") || msg.includes("smaller than") || msg.includes("trimmed")) {
4544
- this.counters.streamGaps++;
4545
- this.l1.clear();
4546
- this._lastStreamId = "$";
5309
+ this._resetAfterStreamGap();
4547
5310
  }
5311
+ this._backplaneAvailable = false;
4548
5312
  await new Promise((resolve) => setTimeout(resolve, 200));
4549
5313
  }
4550
5314
  }
@@ -4572,8 +5336,8 @@ var CacheService = class _CacheService {
4572
5336
  else if (f === "src") src = v;
4573
5337
  else if (f === "tagVersion") tagVersionRaw = v;
4574
5338
  }
4575
- const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
4576
- if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
5339
+ const validOp = op === "del" || op === "del-glob" || op === "tag_incr" || op === "tag_pattern_incr" || op === "tag_pattern_del";
5340
+ if (!validOp || typeof key !== "string" || !key || typeof src !== "string" || !src || (op === "del" || op === "del-glob") && this._namespace && !key.startsWith(`${this._namespace}:`)) {
4577
5341
  this.logger.warn("Backplane: rejected invalid stream entry", {
4578
5342
  op: String(op).slice(0, 40),
4579
5343
  key: typeof key === "string" ? key.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(key)
@@ -4582,8 +5346,8 @@ var CacheService = class _CacheService {
4582
5346
  }
4583
5347
  let tagVersion;
4584
5348
  if (tagVersionRaw !== void 0) {
4585
- const parsed = parseInt(tagVersionRaw, 10);
4586
- if (!Number.isFinite(parsed)) {
5349
+ const parsed = Number(tagVersionRaw);
5350
+ if (!Number.isSafeInteger(parsed) || parsed < 0) {
4587
5351
  this.logger.warn("Backplane: rejected stream entry with non-numeric tagVersion", { key });
4588
5352
  return;
4589
5353
  }
@@ -4601,16 +5365,10 @@ var CacheService = class _CacheService {
4601
5365
  this.l1.delete(key);
4602
5366
  this._bumpKeyMutation(key);
4603
5367
  this.inflight.delete(key);
4604
- this._pendingDiskDeletes.add(key);
4605
- setImmediate(() => {
4606
- try {
4607
- if (!this._diskDisabled) this.disk.delete(key);
4608
- } finally {
4609
- this._pendingDiskDeletes.delete(key);
4610
- }
4611
- });
5368
+ this._invalidateDiskKey(key);
4612
5369
  this._cascadeDependencies(key);
4613
5370
  } else if (op === "del-glob") {
5371
+ this._fenceInvalidation();
4614
5372
  this.l1.deletePattern(key);
4615
5373
  const pfx = key.endsWith("*") ? key.slice(0, -1) : key;
4616
5374
  for (const liveKey of this.l1.liveKeys()) {
@@ -4624,12 +5382,22 @@ var CacheService = class _CacheService {
4624
5382
  this.inflight.delete(inflightKey);
4625
5383
  }
4626
5384
  }
4627
- this._addPatternTombstone(pfx);
5385
+ this._addPatternTombstone(key);
5386
+ this._removePatternFromIndices(key);
5387
+ if (key === this.nk("*")) {
5388
+ this.tagIndex.clear();
5389
+ this.keyTags.clear();
5390
+ this.tagVersions.clear();
5391
+ this.dependencyIndex.clear();
5392
+ this.keyDependencies.clear();
5393
+ }
4628
5394
  } else if (op === "tag_incr") {
5395
+ this._fenceInvalidation();
4629
5396
  const tag = key;
4630
5397
  const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
4631
5398
  this._setLocalTagVersion(tag, ver, performance.now());
4632
5399
  } else if (op === "tag_pattern_incr") {
5400
+ this._fenceInvalidation();
4633
5401
  const pattern = key;
4634
5402
  const now = performance.now();
4635
5403
  for (const [tag, info] of this.tagVersions) {
@@ -4649,6 +5417,7 @@ var CacheService = class _CacheService {
4649
5417
  }
4650
5418
  }, 0);
4651
5419
  } else if (op === "tag_pattern_del") {
5420
+ this._fenceInvalidation();
4652
5421
  const pattern = key;
4653
5422
  const matchedTagKeys = [];
4654
5423
  const prefix = this.nk("_tag_:");
@@ -4659,14 +5428,7 @@ var CacheService = class _CacheService {
4659
5428
  for (const k of members) {
4660
5429
  this.l1.delete(k);
4661
5430
  this._bumpKeyMutation(k);
4662
- this._pendingDiskDeletes.add(k);
4663
- setImmediate(() => {
4664
- try {
4665
- if (!this._diskDisabled) this.disk.delete(k);
4666
- } finally {
4667
- this._pendingDiskDeletes.delete(k);
4668
- }
4669
- });
5431
+ this._invalidateDiskKey(k);
4670
5432
  }
4671
5433
  }
4672
5434
  }
@@ -4697,6 +5459,7 @@ var CacheService = class _CacheService {
4697
5459
  }
4698
5460
  }
4699
5461
  async publishInvalidation(op, key, tagVersion, isCrossRegionRelay = false, isExplicitInvalidation = false) {
5462
+ if (this.opts.l2WriteMode === "read-only") return;
4700
5463
  if (!isCrossRegionRelay && this.opts.crossRegion) {
4701
5464
  const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
4702
5465
  if (shouldBroadcast) {
@@ -4779,13 +5542,13 @@ var CacheService = class _CacheService {
4779
5542
  timestamp: Date.now(),
4780
5543
  namespace: this._namespace || void 0
4781
5544
  };
4782
- this.counters.crossRegionSent++;
4783
5545
  await cr.relay.broadcast(event);
5546
+ this.counters.crossRegionSent++;
4784
5547
  this.logger.debug("Cross-region invalidation broadcast", { op, key, region: cr.currentRegion });
4785
5548
  } catch (err) {
4786
- this.counters.crossRegionSent = Math.max(0, this.counters.crossRegionSent - 1);
4787
5549
  this.counters.crossRegionErrors++;
4788
5550
  this.logger.warn("Cross-region invalidation broadcast failed", { error: err.message });
5551
+ if (this.opts.awaitInvalidationBackplane) throw err;
4789
5552
  }
4790
5553
  }
4791
5554
  /**
@@ -4796,11 +5559,12 @@ var CacheService = class _CacheService {
4796
5559
  * Returns true if the event was accepted and applied, or false if ignored/deduplicated.
4797
5560
  */
4798
5561
  async receiveCrossRegionInvalidation(event) {
5562
+ this._assertActive("receiveCrossRegionInvalidation");
4799
5563
  const cr = this.opts.crossRegion;
4800
5564
  if (!cr) return false;
4801
- if (!event || typeof event !== "object" || !event.id || !event.originRegion || !event.op || !event.key) {
5565
+ if (!isCrossRegionInvalidationEvent(event)) {
4802
5566
  this.counters.crossRegionErrors++;
4803
- this.logger.warn("Cross-region: rejected invalid event payload", { event });
5567
+ this.logger.warn("Cross-region: rejected invalid event payload");
4804
5568
  return false;
4805
5569
  }
4806
5570
  if (event.originRegion === cr.currentRegion) {
@@ -4811,13 +5575,52 @@ var CacheService = class _CacheService {
4811
5575
  this.counters.crossRegionDeduplicated++;
4812
5576
  return false;
4813
5577
  }
4814
- this._markCrossRegionEventSeen(event.id);
4815
5578
  if (event.namespace !== void 0 && event.namespace !== (this._namespace || void 0)) {
4816
5579
  return false;
4817
5580
  }
5581
+ if ((event.op === "del" || event.op === "del-glob") && this._namespace && !event.key.startsWith(`${this._namespace}:`)) return false;
5582
+ this._markCrossRegionEventSeen(event.id);
4818
5583
  this.counters.crossRegionReceived++;
4819
- this._applyInvalidationEvent(event.op, event.key, event.tagVersion);
4820
- void this.publishInvalidation(event.op, event.key, event.tagVersion, true);
5584
+ const localTags = /* @__PURE__ */ new Set([...this.tagVersions.keys(), ...[...this.tagIndex.keys()].map((key) => this.unnk(key).replace(/^_tag_:/, ""))]);
5585
+ let version = event.tagVersion;
5586
+ if (event.op === "tag_incr") version = Math.max((this.tagVersions.get(event.key)?.version ?? 0) + 1, version ?? 0);
5587
+ this._applyInvalidationEvent(event.op, event.key, version);
5588
+ try {
5589
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
5590
+ const client = await this.getRedis();
5591
+ if (event.op === "del" || event.op === "del-glob") {
5592
+ await this._deleteRedisKeys(client, event.op === "del" ? [event.key] : await this._scanKeys(client, event.key));
5593
+ } else if (event.op === "tag_incr") {
5594
+ version = Number(await client.eval(LUA_RECEIVE_TAG_VERSION, 1, this.nk(`tag_ver:${event.key}`), String(version)));
5595
+ this._setLocalTagVersion(event.key, version);
5596
+ } else {
5597
+ const matched = await this._resolveMatchingTags(event.key, false);
5598
+ for (const tag of localTags) if (matchesTagPattern(event.key, tag)) matched.add(tag);
5599
+ for (const tag of matched) {
5600
+ if (event.op === "tag_pattern_incr") {
5601
+ const floor = this.tagVersions.get(tag)?.version ?? 1;
5602
+ const next = Number(await client.eval(LUA_RECEIVE_TAG_VERSION, 1, this.nk(`tag_ver:${tag}`), String(floor)));
5603
+ this._setLocalTagVersion(tag, next);
5604
+ await this.publishInvalidation("tag_incr", tag, next, true);
5605
+ } else {
5606
+ const tagKey = this.nk(`_tag_:${tag}`);
5607
+ const members = await client.smembers(tagKey);
5608
+ this._removeTagMembersLocal(members);
5609
+ await this._deleteRedisKeys(client, [...members, tagKey]);
5610
+ await Promise.all(members.map((key) => this.publishInvalidation("del", key, void 0, true)));
5611
+ }
5612
+ }
5613
+ }
5614
+ this.cb.onSuccess();
5615
+ }
5616
+ await this.publishInvalidation(event.op, event.key, version, true);
5617
+ } catch (error) {
5618
+ this._seenCrossRegionEvents.delete(event.id);
5619
+ this.counters.crossRegionErrors++;
5620
+ this.logger.warn("Cross-region regional invalidation failed", { error: error.message });
5621
+ if (this.opts.awaitInvalidationBackplane) throw error;
5622
+ return false;
5623
+ }
4821
5624
  this.logger.info("Cross-region invalidation applied", {
4822
5625
  op: event.op,
4823
5626
  key: event.key,
@@ -4832,25 +5635,269 @@ var CacheService = class _CacheService {
4832
5635
  const oldestKey = this.tagVersions.keys().next().value;
4833
5636
  if (oldestKey !== void 0) this.tagVersions.delete(oldestKey);
4834
5637
  }
4835
- this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
5638
+ this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now, refreshEpoch: this._tagRefreshEpoch });
5639
+ }
5640
+ async _isGenerationalEntryStale(tagVersions) {
5641
+ if (!tagVersions) return false;
5642
+ const tags = Object.keys(tagVersions);
5643
+ if (tags.length === 0) return false;
5644
+ const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5645
+ for (let i = 0; i < tags.length; i++) {
5646
+ if (currentVers[i] > tagVersions[tags[i]]) return true;
5647
+ }
5648
+ return false;
5649
+ }
5650
+ async _deleteRedisKeys(client, keys) {
5651
+ if (keys.length === 0) return;
5652
+ const CHUNK_SIZE = 1e3;
5653
+ if (client instanceof RedisCluster) {
5654
+ const groups = /* @__PURE__ */ new Map();
5655
+ for (const key of keys) {
5656
+ const slot = redisHashSlot(key);
5657
+ const master = client.slots?.[slot]?.[0] ?? String(slot);
5658
+ const members = groups.get(master) ?? [];
5659
+ members.push(key);
5660
+ groups.set(master, members);
5661
+ }
5662
+ await Promise.all([...groups.values()].map(async (members) => {
5663
+ for (let offset = 0; offset < members.length; offset += CHUNK_SIZE) {
5664
+ const pipeline = client.pipeline();
5665
+ for (const key of members.slice(offset, offset + CHUNK_SIZE)) pipeline.del(key);
5666
+ const result = await pipeline.exec();
5667
+ if (!result || result.some(([error]) => error)) throw new Error("Redis Cluster delete failed");
5668
+ }
5669
+ }));
5670
+ return;
5671
+ }
5672
+ for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
5673
+ const chunk = keys.slice(i, i + CHUNK_SIZE);
5674
+ await client.del(...chunk);
5675
+ }
5676
+ }
5677
+ async _parseGenerationalRedisHash(k, hashData) {
5678
+ if (!hashData || !hashData.d) return null;
5679
+ let storedTagVersions = {};
5680
+ if (hashData.tv) {
5681
+ try {
5682
+ const parsed = JSON.parse(hashData.tv);
5683
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || Object.values(parsed).some((version) => !Number.isSafeInteger(version) || Number(version) < 0)) return null;
5684
+ storedTagVersions = parsed;
5685
+ } catch {
5686
+ return null;
5687
+ }
5688
+ }
5689
+ if (await this._isGenerationalEntryStale(storedTagVersions)) {
5690
+ const setAtMs = parseInt(hashData.t, 10) || 0;
5691
+ this._deleteIfStale(k, setAtMs);
5692
+ return { stale: true };
5693
+ }
5694
+ const value = await this._decryptAndDeserialize(hashData.d);
5695
+ const expiresAt = Number(hashData.e);
5696
+ const staleAt = Number(hashData.s);
5697
+ let tags;
5698
+ let dependsOn;
5699
+ try {
5700
+ const parsedTags = hashData.tags ? JSON.parse(hashData.tags) : Object.keys(storedTagVersions);
5701
+ const parsedDependencies = hashData.deps ? JSON.parse(hashData.deps) : void 0;
5702
+ if (Array.isArray(parsedTags) && parsedTags.every((tag) => typeof tag === "string")) tags = parsedTags;
5703
+ if (Array.isArray(parsedDependencies) && parsedDependencies.every((pattern) => typeof pattern === "string")) dependsOn = parsedDependencies;
5704
+ } catch {
5705
+ return null;
5706
+ }
5707
+ return {
5708
+ value,
5709
+ tagVersions: storedTagVersions,
5710
+ stale: false,
5711
+ tags,
5712
+ dependsOn,
5713
+ setAt: Number(hashData.t) || void 0,
5714
+ expiresAt: Number.isFinite(expiresAt) && expiresAt > 0 ? expiresAt : void 0,
5715
+ staleAt: Number.isFinite(staleAt) && staleAt > 0 ? staleAt : void 0
5716
+ };
5717
+ }
5718
+ async _readRedisEntry(client, k, allowAutoPipeline = false) {
5719
+ const readStartedAt = Date.now();
5720
+ const read = async (hash) => allowAutoPipeline && this.opts.autoPipeline && this.pipeliner ? this.pipeliner.read(k, hash) : readRedisValue(client, k, hash);
5721
+ const withExpiry = (entry, ttlMs2) => {
5722
+ if (!entry || ttlMs2 === -2 || ttlMs2 === 0) return null;
5723
+ if (ttlMs2 !== void 0 && Number.isFinite(ttlMs2) && ttlMs2 > 0) {
5724
+ entry.expiresAt = Math.min(entry.expiresAt ?? Infinity, readStartedAt + ttlMs2);
5725
+ }
5726
+ return entry.expiresAt !== void 0 && entry.expiresAt <= Date.now() ? null : entry;
5727
+ };
5728
+ if (this.opts.tagStrategy === "generational" && typeof client.hgetall === "function") {
5729
+ try {
5730
+ const { raw: hashData, ttlMs: ttlMs2 } = await read(true);
5731
+ if (typeof hashData === "string") {
5732
+ const value2 = await this._decryptAndDeserialize(hashData);
5733
+ return withExpiry({ value: value2, stale: false }, ttlMs2);
5734
+ }
5735
+ if (hashData && hashData.d) {
5736
+ return withExpiry(await this._parseGenerationalRedisHash(k, hashData), ttlMs2);
5737
+ }
5738
+ return null;
5739
+ } catch (err) {
5740
+ const msg = err instanceof Error ? err.message : String(err);
5741
+ if (!msg.includes("WRONGTYPE")) throw err;
5742
+ }
5743
+ }
5744
+ const { raw, ttlMs } = await read(false);
5745
+ if (raw == null) return null;
5746
+ if (typeof raw !== "string") return null;
5747
+ const value = await this._decryptAndDeserialize(raw);
5748
+ return withExpiry({ value, stale: false }, ttlMs);
4836
5749
  }
4837
5750
  async _getTagVersion(tag) {
4838
5751
  const now = performance.now();
4839
5752
  const local = this.tagVersions.get(tag);
4840
- if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
5753
+ if (local && (local.refreshEpoch ?? 0) === this._tagRefreshEpoch && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
4841
5754
  return local.version;
4842
5755
  }
4843
5756
  if (!this._redisDisabled) {
4844
5757
  try {
4845
5758
  const client = await this.getRedis();
4846
5759
  const raw = await client.get(this.nk(`tag_ver:${tag}`));
4847
- const version = raw ? parseInt(raw, 10) : 0;
4848
- this._setLocalTagVersion(tag, version, now);
4849
- return version;
5760
+ const parsed = raw ? Number(raw) : 0;
5761
+ if (!Number.isSafeInteger(parsed) || parsed < 0) throw new Error("Invalid Redis tag generation");
5762
+ const version2 = Math.max(this.tagVersions.get(tag)?.version ?? 0, parsed);
5763
+ if (this.opts.l2WriteMode === "read-write") {
5764
+ if (raw === null) await client.set(this.nk(`tag_ver:${tag}`), String(version2), "NX");
5765
+ else if (version2 > parsed) await client.eval(LUA_MAX_TAG_VERSION, 1, this.nk(`tag_ver:${tag}`), String(version2));
5766
+ }
5767
+ this._setLocalTagVersion(tag, version2, now);
5768
+ this.cb.onSuccess();
5769
+ return version2;
4850
5770
  } catch {
4851
5771
  }
4852
5772
  }
4853
- return local?.version ?? 0;
5773
+ const version = this.tagVersions.get(tag)?.version ?? local?.version ?? 0;
5774
+ if (this._redisDisabled) this._setLocalTagVersion(tag, version, now);
5775
+ return version;
5776
+ }
5777
+ async _readRedisBatch(client, keys) {
5778
+ const entries = /* @__PURE__ */ new Map();
5779
+ const groups = /* @__PURE__ */ new Map();
5780
+ for (const key of new Set(keys)) {
5781
+ const group = client instanceof RedisCluster ? client.slots[redisHashSlot(key)]?.[0] ?? String(redisHashSlot(key)) : "single";
5782
+ const members = groups.get(group) ?? [];
5783
+ members.push(key);
5784
+ groups.set(group, members);
5785
+ }
5786
+ await Promise.all([...groups.values()].map(async (members) => {
5787
+ for (let offset = 0; offset < members.length; offset += 1e3) {
5788
+ const chunk = members.slice(offset, offset + 1e3);
5789
+ const pipeline = typeof client.pipeline === "function" ? client.pipeline() : client.multi();
5790
+ const timedScripts = typeof pipeline.eval === "function";
5791
+ const hashes = this.opts.tagStrategy === "generational" && typeof pipeline.hgetall === "function";
5792
+ for (const key of chunk) {
5793
+ if (timedScripts) pipeline.eval(LUA_READ_CACHE_ENTRY, 1, key);
5794
+ else if (hashes) pipeline.hgetall(key);
5795
+ else pipeline.get(key);
5796
+ }
5797
+ const startedAt = Date.now();
5798
+ const start = performance.now();
5799
+ const results = await pipeline.exec();
5800
+ this.watchdog.recordRedis(performance.now() - start);
5801
+ if (!results) throw new Error("Redis batch read aborted");
5802
+ for (let index = 0; index < chunk.length; index++) {
5803
+ try {
5804
+ const tuple = results[index];
5805
+ if (!tuple) continue;
5806
+ let [error, raw] = tuple;
5807
+ let ttl;
5808
+ if (error?.message?.includes("WRONGTYPE")) {
5809
+ const fallback = await this._readRedisEntry(client, chunk[index]);
5810
+ if (fallback && !fallback.stale) entries.set(chunk[index], fallback);
5811
+ continue;
5812
+ }
5813
+ if (error) continue;
5814
+ if (timedScripts) {
5815
+ if (!Array.isArray(raw) || raw[0] === "none") continue;
5816
+ const kind = raw[0];
5817
+ ttl = Number(raw[2]);
5818
+ const payload = raw[1];
5819
+ if (kind === "hash") {
5820
+ if (!Array.isArray(payload) || payload.length % 2 !== 0) continue;
5821
+ raw = Object.fromEntries(Array.from({ length: payload.length / 2 }, (_unused, i) => [String(payload[i * 2]), String(payload[i * 2 + 1])]));
5822
+ } else if (kind === "string") raw = payload;
5823
+ else continue;
5824
+ if (ttl === -2 || ttl === 0) continue;
5825
+ }
5826
+ 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;
5827
+ if (!entry || entry.stale) continue;
5828
+ if (ttl !== void 0 && ttl > 0) entry.expiresAt = Math.min(entry.expiresAt ?? Infinity, startedAt + ttl);
5829
+ if (entry.expiresAt !== void 0 && entry.expiresAt <= Date.now()) continue;
5830
+ entries.set(chunk[index], entry);
5831
+ } catch (error) {
5832
+ this.logger.debug("mget: skipping invalid remote entry", { key: chunk[index], error: error.message });
5833
+ }
5834
+ }
5835
+ }
5836
+ }));
5837
+ this.cb.onSuccess();
5838
+ return entries;
5839
+ }
5840
+ _promoteRedisEntry(key, entry, fallbackTtlMs, priority) {
5841
+ const expiresAt = entry.expiresAt ?? Date.now() + fallbackTtlMs;
5842
+ if (expiresAt <= Date.now()) return false;
5843
+ const admitted = this.l1.set(
5844
+ key,
5845
+ entry.value,
5846
+ expiresAt - Date.now(),
5847
+ priority,
5848
+ entry.staleAt,
5849
+ void 0,
5850
+ entry.tagVersions,
5851
+ entry.setAt,
5852
+ entry.tags,
5853
+ entry.dependsOn
5854
+ );
5855
+ if (admitted) this._restoreEntryMetadata(key, { ...entry, expiresAt });
5856
+ return true;
5857
+ }
5858
+ async _readDiskEntry(key, epoch) {
5859
+ if (this._diskDisabled || this._pendingDiskDeletes.has(key) || !this.watchdog.isDiskAllowed()) return null;
5860
+ const start = performance.now();
5861
+ const entry = this.disk.load(key);
5862
+ const elapsed = performance.now() - start;
5863
+ this.watchdog.recordDisk(elapsed);
5864
+ this.watchdog.onCanaryResult(entry !== null, elapsed);
5865
+ 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;
5866
+ this.l1.importEntries([{ key, entry }], this.opts.forbiddenSnapshotPrefixes);
5867
+ const hit = this.l1.get(key);
5868
+ const value = hit ? hit.value : entry.isCompressed ? this.codec.decode(entry.data) : JSON.parse(entry.data);
5869
+ this._restoreEntryMetadata(key, entry);
5870
+ return { value, entry };
5871
+ }
5872
+ /** Common write policy and metadata across get/set/revalidation/draining. */
5873
+ async _writeRedisEntry(key, data, expiresAt, setAt, tagVersions, staleAt, tags, dependsOn, canCommit = () => true) {
5874
+ if (this._redisDisabled || this.opts.l2WriteMode !== "read-write" || !canCommit() || this._destroyed) return;
5875
+ const client = await this.getRedis();
5876
+ const stored = await this._serializeAndEncrypt(JSON.stringify(data) ?? "undefined");
5877
+ if (!canCommit() || this._destroyed) return;
5878
+ const useHash = this.opts.tagStrategy === "generational" && (tagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function");
5879
+ const remaining = (useHash ? expiresAt : staleAt ?? expiresAt) - Date.now();
5880
+ if (remaining <= 0) return;
5881
+ const ttl = Math.max(1, Math.ceil(remaining / 1e3));
5882
+ if (useHash) {
5883
+ const transaction = client.multi();
5884
+ transaction.del(key);
5885
+ const hash = { d: stored, t: String(setAt), tv: JSON.stringify(tagVersions ?? {}), e: String(expiresAt) };
5886
+ if (staleAt !== void 0) hash.s = String(staleAt);
5887
+ if (tags?.length) hash.tags = JSON.stringify(tags);
5888
+ if (dependsOn?.length) hash.deps = JSON.stringify(dependsOn);
5889
+ transaction.hset(key, hash);
5890
+ transaction.expire(key, ttl);
5891
+ const result = await transaction.exec();
5892
+ if (!result || result.some(([error]) => error)) throw new Error("Redis cache write transaction failed");
5893
+ } else if (this.opts.autoPipeline && this.pipeliner) {
5894
+ if (typeof client.pttl === "function" && typeof client.set === "function") await this.pipeliner.setpx(key, Math.ceil(remaining), stored);
5895
+ else await this.pipeliner.setex(key, ttl, stored);
5896
+ } else {
5897
+ if (typeof client.pttl === "function" && typeof client.set === "function") await client.set(key, stored, "PX", Math.ceil(remaining));
5898
+ else await client.setex(key, ttl, stored);
5899
+ }
5900
+ this.cb.onSuccess();
4854
5901
  }
4855
5902
  _deleteIfStale(k, setAtMs) {
4856
5903
  this.l1.deleteIfSetBefore(k, setAtMs);
@@ -4903,7 +5950,7 @@ var CacheService = class _CacheService {
4903
5950
  } else {
4904
5951
  plain = raw;
4905
5952
  }
4906
- return JSON.parse(plain);
5953
+ return plain === "undefined" ? void 0 : JSON.parse(plain);
4907
5954
  }
4908
5955
  /**
4909
5956
  * Scan all keys matching `pattern` across single-node or Cluster clients.
@@ -4971,8 +6018,8 @@ var CacheService = class _CacheService {
4971
6018
  return client;
4972
6019
  }
4973
6020
  this.redisConnecting = (async () => {
6021
+ let client = null;
4974
6022
  try {
4975
- let client;
4976
6023
  if (this.opts.redisClusterNodes?.length) {
4977
6024
  client = new RedisCluster(this.opts.redisClusterNodes, {
4978
6025
  redisOptions: {
@@ -5035,14 +6082,45 @@ var CacheService = class _CacheService {
5035
6082
  });
5036
6083
  client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
5037
6084
  }
6085
+ const pendingClient = client;
5038
6086
  await new Promise((resolve, reject) => {
5039
- client.once("ready", resolve);
5040
- client.once("error", (e) => {
6087
+ let settled = false;
6088
+ const cleanupListeners = () => {
6089
+ pendingClient.removeListener?.("ready", onReady);
6090
+ pendingClient.removeListener?.("error", onError);
6091
+ };
6092
+ const onReady = () => {
6093
+ if (settled) return;
6094
+ settled = true;
6095
+ clearTimeout(timer);
6096
+ cleanupListeners();
6097
+ resolve();
6098
+ };
6099
+ const onError = (e) => {
6100
+ if (settled) return;
6101
+ settled = true;
6102
+ clearTimeout(timer);
6103
+ cleanupListeners();
5041
6104
  this._checkAndLogResp3Hint(e);
5042
6105
  reject(e);
5043
- });
5044
- setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
6106
+ };
6107
+ const timer = setTimeout(() => {
6108
+ if (settled) return;
6109
+ settled = true;
6110
+ cleanupListeners();
6111
+ reject(new Error("Redis connection timeout"));
6112
+ }, 15e3);
6113
+ if (timer.unref) timer.unref();
6114
+ pendingClient.once("ready", onReady);
6115
+ pendingClient.once("error", onError);
5045
6116
  });
6117
+ if (this._destroyed) {
6118
+ try {
6119
+ client.disconnect();
6120
+ } catch {
6121
+ }
6122
+ this._assertActive("getRedis");
6123
+ }
5046
6124
  this.cb.onSuccess();
5047
6125
  this.redis = client;
5048
6126
  this.pipeliner = new AutoPipeliner(client, {
@@ -5052,6 +6130,10 @@ var CacheService = class _CacheService {
5052
6130
  this.redisConnecting = null;
5053
6131
  return client;
5054
6132
  } catch (err) {
6133
+ try {
6134
+ client?.disconnect();
6135
+ } catch {
6136
+ }
5055
6137
  this.cb.onFailure();
5056
6138
  this.redisConnecting = null;
5057
6139
  this._checkAndLogResp3Hint(err);
@@ -5071,7 +6153,12 @@ var CacheService = class _CacheService {
5071
6153
  try {
5072
6154
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
5073
6155
  if (entries.length === 0) return;
5074
- const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
6156
+ const payload = {
6157
+ version: SNAPSHOT_VERSION,
6158
+ writtenAt: Date.now(),
6159
+ entries,
6160
+ streamId: this.opts.backplaneMode === "stream" && this._lastStreamId !== "$" ? this._lastStreamId : void 0
6161
+ };
5075
6162
  const packed = this.codec.encode(payload);
5076
6163
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
5077
6164
  const dest = altPath ?? this.opts.snapshotPath;
@@ -5139,6 +6226,9 @@ var CacheService = class _CacheService {
5139
6226
  return;
5140
6227
  }
5141
6228
  const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
6229
+ this._restoredSnapshot ||= loaded > 0;
6230
+ if (typeof snapshot.streamId === "string" && /^\d{1,20}-\d{1,20}$/.test(snapshot.streamId)) this._lastStreamId = snapshot.streamId;
6231
+ for (const { key, entry } of snapshot.entries) if (this.l1.has(key)) this._restoreEntryMetadata(key, entry);
5142
6232
  this.logger.info("Cache snapshot loaded (L1 is warm)", {
5143
6233
  loaded,
5144
6234
  total: snapshot.entries.length,
@@ -5163,7 +6253,12 @@ var CacheService = class _CacheService {
5163
6253
  try {
5164
6254
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
5165
6255
  if (entries.length === 0) return false;
5166
- const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
6256
+ const payload = {
6257
+ version: SNAPSHOT_VERSION,
6258
+ writtenAt: Date.now(),
6259
+ entries,
6260
+ streamId: this.opts.backplaneMode === "stream" && this._lastStreamId !== "$" ? this._lastStreamId : void 0
6261
+ };
5167
6262
  const packed = this.codec.encode(payload);
5168
6263
  let final;
5169
6264
  if (this.opts.remoteSnapshot.envelope) {
@@ -5194,13 +6289,16 @@ var CacheService = class _CacheService {
5194
6289
  async loadRemoteSnapshot() {
5195
6290
  if (!this.opts.remoteSnapshot) return 0;
5196
6291
  const maxAgeMs = this.opts.remoteSnapshot.maxAgeMs ?? this.opts.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE;
6292
+ const epoch = this._globalEpoch;
5197
6293
  try {
5198
6294
  const raw = await this.opts.remoteSnapshot.adapter.get();
6295
+ if (this._destroyed || this._globalEpoch !== epoch) return 0;
5199
6296
  if (!raw || raw.length === 0) {
5200
6297
  this.logger.debug("Remote snapshot not found or empty \u2014 starting cold");
5201
6298
  return 0;
5202
6299
  }
5203
6300
  const rawBuf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
6301
+ if (rawBuf.length > SNAPSHOT_MAX_FILE_BYTES) throw new Error("Remote snapshot exceeds size limit");
5204
6302
  let buf;
5205
6303
  try {
5206
6304
  if (EnvelopeEncryption.isEnvelope(rawBuf)) {
@@ -5246,7 +6344,12 @@ var CacheService = class _CacheService {
5246
6344
  this.logger.warn("Remote snapshot rejected: entries is not an array");
5247
6345
  return 0;
5248
6346
  }
5249
- const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
6347
+ if (this._destroyed || this._globalEpoch !== epoch) return 0;
6348
+ const eligible = snapshot.entries.filter((item) => item && !this._keyMutationEpochs.has(item.key));
6349
+ const loaded = this.l1.importEntries(eligible, this.opts.forbiddenSnapshotPrefixes);
6350
+ this._restoredSnapshot ||= loaded > 0;
6351
+ if (typeof snapshot.streamId === "string" && /^\d{1,20}-\d{1,20}$/.test(snapshot.streamId)) this._lastStreamId = snapshot.streamId;
6352
+ for (const { key, entry } of eligible) if (this.l1.has(key)) this._restoreEntryMetadata(key, entry);
5250
6353
  this.counters.remoteSnapshotDownloads++;
5251
6354
  this.counters.remoteSnapshotLastDownloadedAt = Date.now();
5252
6355
  this.logger.info("Remote cache snapshot loaded (L1 hydrated)", {
@@ -5295,20 +6398,10 @@ var CacheService = class _CacheService {
5295
6398
  const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
5296
6399
  const l1Hit = this.l1.get(k);
5297
6400
  if (l1Hit !== null) {
5298
- let isGenerationalStale = false;
5299
- if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
5300
- const tags = Object.keys(l1Hit.tagVersions);
5301
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5302
- for (let i = 0; i < tags.length; i++) {
5303
- if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
5304
- isGenerationalStale = true;
5305
- break;
5306
- }
5307
- }
5308
- }
6401
+ const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
5309
6402
  if (isGenerationalStale) {
5310
6403
  this._deleteIfStale(k, l1Hit.setAt ?? 0);
5311
- } else {
6404
+ } else if (!l1Hit.isStale || optSwr > 0) {
5312
6405
  if (l1Hit.isStale) {
5313
6406
  const swrGraceMs2 = optSwr * 1e3;
5314
6407
  if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
@@ -5371,115 +6464,58 @@ var CacheService = class _CacheService {
5371
6464
  this.counters.stampedes++;
5372
6465
  this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch/read", { cacheKey });
5373
6466
  span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
5374
- return existing;
6467
+ return this._prepareReadValue(await existing);
5375
6468
  }
5376
6469
  const mutationEpochAtStart = this._getKeyMutationEpoch(k);
5377
- const executionPromise = (async () => {
6470
+ const executionPromise = Promise.resolve().then(async () => {
5378
6471
  try {
5379
- if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
5380
- if (this._isTombstonedByPattern(k)) {
5381
- try {
5382
- this.disk.delete(k);
5383
- } catch {
5384
- }
5385
- } else {
5386
- const isDiskAllowed = this.watchdog.isDiskAllowed();
5387
- if (isDiskAllowed) {
5388
- const diskStart = performance.now();
5389
- const diskHit = this.disk.load(k);
5390
- const diskElapsed = performance.now() - diskStart;
5391
- this.watchdog.recordDisk(diskElapsed);
5392
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
5393
- if (diskHit !== null) {
5394
- let isDiskStale = false;
5395
- if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
5396
- const tags = Object.keys(diskHit.tagVersions);
5397
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5398
- for (let i = 0; i < tags.length; i++) {
5399
- if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
5400
- isDiskStale = true;
5401
- break;
5402
- }
5403
- }
5404
- }
5405
- if (isDiskStale) {
5406
- this.disk.delete(k);
5407
- } else {
5408
- const promoted = this.l1.importEntries(
5409
- [{ key: k, entry: diskHit }],
5410
- this.opts.forbiddenSnapshotPrefixes
5411
- );
5412
- if (promoted > 0) {
5413
- const l1Check = this.l1.get(k);
5414
- if (l1Check !== null) {
5415
- this.counters.diskHits++;
5416
- this.opts.onHit?.(cacheKey, "disk");
5417
- this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
5418
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
5419
- if (this.opts.frozen) deepFreeze(l1Check.value);
5420
- return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
5421
- }
5422
- }
5423
- }
5424
- }
5425
- }
6472
+ const diskHit = await this._readDiskEntry(k, mutationEpochAtStart);
6473
+ if (diskHit && (diskHit.entry.staleAt === void 0 || diskHit.entry.staleAt > Date.now() || optSwr > 0)) {
6474
+ this.counters.diskHits++;
6475
+ this.opts.onHit?.(cacheKey, "disk");
6476
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
6477
+ if (diskHit.entry.staleAt !== void 0 && diskHit.entry.staleAt <= Date.now() && optSwr > 0 && !this.revalidating.has(k)) {
6478
+ this.revalidating.add(k);
6479
+ this.counters.swrRevalidations++;
6480
+ void this._revalidate(
6481
+ k,
6482
+ fetchFn,
6483
+ ttlMs,
6484
+ swrGraceMs,
6485
+ priority,
6486
+ diskHit.entry.tagVersions ?? Object.fromEntries((diskHit.entry.tags ?? []).map((tag) => [tag, 0]))
6487
+ );
5426
6488
  }
6489
+ return diskHit.value;
5427
6490
  }
5428
6491
  if (!this._redisDisabled) {
5429
6492
  try {
5430
6493
  const client = await this.getRedis();
5431
6494
  const redisStart = performance.now();
5432
- if (this.opts.tagStrategy === "generational") {
5433
- const hashData = await client.hgetall(k);
5434
- const redisElapsed = performance.now() - redisStart;
5435
- this.watchdog.recordRedis(redisElapsed);
5436
- this.cb.onSuccess();
5437
- if (hashData && hashData.d) {
5438
- let isStale = false;
5439
- let storedTagVersions = {};
5440
- if (hashData.tv) {
5441
- try {
5442
- storedTagVersions = JSON.parse(hashData.tv);
5443
- } catch {
5444
- }
5445
- }
5446
- const tags = Object.keys(storedTagVersions);
5447
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5448
- for (let i = 0; i < tags.length; i++) {
5449
- if (currentVers[i] > storedTagVersions[tags[i]]) {
5450
- isStale = true;
5451
- break;
5452
- }
5453
- }
5454
- if (isStale) {
5455
- const setAtMs = parseInt(hashData.t, 10) || 0;
5456
- this._deleteIfStale(k, setAtMs);
5457
- } else {
5458
- const parsed = await this._decryptAndDeserialize(hashData.d);
5459
- this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
5460
- this.counters.l2Hits++;
5461
- this.opts.onHit?.(cacheKey, "l2");
5462
- this.logger.debug("L2 hit (Redis hash)", { cacheKey });
5463
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5464
- if (this.opts.frozen) deepFreeze(parsed);
5465
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
5466
- }
6495
+ const redisHit = await this._readRedisEntry(client, k, true);
6496
+ const redisElapsed = performance.now() - redisStart;
6497
+ this.watchdog.recordRedis(redisElapsed);
6498
+ this.cb.onSuccess();
6499
+ if (redisHit && !redisHit.stale && (redisHit.staleAt === void 0 || redisHit.staleAt > Date.now() || optSwr > 0)) {
6500
+ const parsed = redisHit.value;
6501
+ if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
6502
+ this.logger.debug("Aborting L2 promotion \u2014 key was mutated or deleted during Redis read", { cacheKey });
6503
+ span.setAttribute("cache.aborted_mutation_race", true);
6504
+ const current = this.l1.get(k);
6505
+ const liveVal = current && !current.isStale ? current.value : parsed;
6506
+ return liveVal;
5467
6507
  }
5468
- } else {
5469
- const raw = this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
5470
- const redisElapsed = performance.now() - redisStart;
5471
- this.watchdog.recordRedis(redisElapsed);
5472
- this.cb.onSuccess();
5473
- if (raw) {
5474
- const parsed = await this._decryptAndDeserialize(raw);
5475
- this.l1.set(k, parsed, ttlMs, priority);
5476
- this.counters.l2Hits++;
5477
- this.opts.onHit?.(cacheKey, "l2");
5478
- this.logger.debug("L2 hit (Redis)", { cacheKey });
5479
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5480
- if (this.opts.frozen) deepFreeze(parsed);
5481
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
6508
+ if (!this._promoteRedisEntry(k, redisHit, ttlMs, priority)) throw new Error("Redis entry expired during promotion");
6509
+ this.counters.l2Hits++;
6510
+ this.opts.onHit?.(cacheKey, "l2");
6511
+ this.logger.debug(redisHit.tagVersions ? "L2 hit (Redis hash)" : "L2 hit (Redis)", { cacheKey });
6512
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
6513
+ if (redisHit.staleAt !== void 0 && redisHit.staleAt <= Date.now() && optSwr > 0 && !this.revalidating.has(k)) {
6514
+ this.revalidating.add(k);
6515
+ this.counters.swrRevalidations++;
6516
+ void this._revalidate(k, fetchFn, ttlMs, swrGraceMs, priority, redisHit.tagVersions);
5482
6517
  }
6518
+ return parsed;
5483
6519
  }
5484
6520
  } catch (err) {
5485
6521
  this.cb.onFailure();
@@ -5489,6 +6525,7 @@ var CacheService = class _CacheService {
5489
6525
  span.setAttribute("cache.hit", false).setAttribute("cache.hit_tier", "miss");
5490
6526
  this.opts.onMiss?.(cacheKey);
5491
6527
  this.counters.fetches++;
6528
+ const tagSnapshot = this.opts.tagStrategy === "generational" && optTags?.length ? Object.fromEntries(await Promise.all(optTags.map(async (tag) => [tag, await this._getTagVersion(tag)]))) : void 0;
5492
6529
  const fetchStart = Date.now();
5493
6530
  let data;
5494
6531
  try {
@@ -5517,50 +6554,41 @@ var CacheService = class _CacheService {
5517
6554
  }
5518
6555
  const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
5519
6556
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
5520
- let activeTagVersions;
6557
+ const activeTagVersions = tagSnapshot;
5521
6558
  if (optTags?.length) {
5522
6559
  if (this.opts.tagStrategy === "generational") {
5523
- const vers = await Promise.all(optTags.map((tag) => this._getTagVersion(tag)));
5524
- activeTagVersions = {};
5525
- for (let i = 0; i < optTags.length; i++) {
5526
- activeTagVersions[optTags[i]] = vers[i];
5527
- }
6560
+ if (await this._isGenerationalEntryStale(tagSnapshot)) return data;
5528
6561
  } else {
5529
- await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
6562
+ await this._registerTags(k, optTags, Math.ceil(storeTtl / 1e3));
5530
6563
  }
5531
6564
  }
5532
6565
  if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
5533
6566
  this.logger.debug("Aborting in-flight cache commit \u2014 key was mutated or deleted during fetch", { cacheKey });
5534
6567
  span.setAttribute("cache.aborted_mutation_race", true);
5535
6568
  const current = this.l1.get(k);
5536
- if (current && !current.isStale && current.value !== void 0) {
6569
+ if (current && !current.isStale) {
5537
6570
  const freshVal = current.value;
5538
- if (this.opts.frozen) deepFreeze(freshVal);
5539
- return this.opts.cloneStrategy === "structuredClone" && freshVal != null && typeof freshVal === "object" ? structuredClone(freshVal) : freshVal;
6571
+ return freshVal;
5540
6572
  }
5541
- if (this.opts.frozen) deepFreeze(data);
5542
- return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
6573
+ return data;
5543
6574
  }
5544
- this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
5545
- if (!this._redisDisabled) {
6575
+ const writeTs = Date.now();
6576
+ this._invalidateDiskKey(k);
6577
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs, optTags, opts.dependsOn);
6578
+ this._restoreEntryMetadata(k, { tags: optTags, dependsOn: opts.dependsOn, expiresAt: writeTs + storeTtl });
6579
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
5546
6580
  try {
5547
- const client = await this.getRedis();
5548
- const serialized = JSON.stringify(data);
5549
- const toStore = await this._serializeAndEncrypt(serialized);
5550
- const ttlSec = Math.ceil(effectiveTtl / 1e3);
5551
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
5552
- const now = Date.now();
5553
- const tx = client.multi();
5554
- tx.hset(k, {
5555
- d: toStore,
5556
- t: String(now),
5557
- tv: JSON.stringify(activeTagVersions)
5558
- });
5559
- tx.expire(k, ttlSec);
5560
- await tx.exec();
5561
- } else {
5562
- await client.setex(k, ttlSec, toStore);
5563
- }
6581
+ await this._writeRedisEntry(
6582
+ k,
6583
+ data,
6584
+ writeTs + storeTtl,
6585
+ writeTs,
6586
+ activeTagVersions,
6587
+ staleAt,
6588
+ optTags,
6589
+ opts.dependsOn,
6590
+ () => this._getKeyMutationEpoch(k) === mutationEpochAtStart
6591
+ );
5564
6592
  this.cb.onSuccess();
5565
6593
  this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
5566
6594
  } catch {
@@ -5570,15 +6598,14 @@ var CacheService = class _CacheService {
5570
6598
  } else {
5571
6599
  this.logger.debug("Cached L1", { cacheKey });
5572
6600
  }
5573
- if (this.opts.frozen) deepFreeze(data);
5574
- return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
6601
+ return data;
5575
6602
  } finally {
5576
- this.inflight.delete(k);
6603
+ if (this.inflight.get(k) === executionPromise) this.inflight.delete(k);
5577
6604
  span.end();
5578
6605
  }
5579
- })();
6606
+ });
5580
6607
  this.inflight.set(k, executionPromise);
5581
- return executionPromise;
6608
+ return this._prepareReadValue(await executionPromise);
5582
6609
  }
5583
6610
  /**
5584
6611
  * Graceful shutdown flusher for Kubernetes preStop hooks, NestJS onApplicationShutdown,
@@ -5659,6 +6686,9 @@ var CacheService = class _CacheService {
5659
6686
  }
5660
6687
  async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority, knownTagVersions) {
5661
6688
  const startEpoch = this._getKeyMutationEpoch(cacheKey);
6689
+ const previous = this.l1.getEntry(cacheKey);
6690
+ const tags = previous?.tags ?? Object.keys(knownTagVersions ?? {});
6691
+ const dependencies = previous?.dependsOn;
5662
6692
  try {
5663
6693
  const fetchStart = Date.now();
5664
6694
  const data = await fetchFn();
@@ -5673,14 +6703,14 @@ var CacheService = class _CacheService {
5673
6703
  const l1Existing = this.l1.get(cacheKey);
5674
6704
  const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
5675
6705
  if (this.opts.tagStrategy === "generational" && tagVersionsSource) {
5676
- const tags = Object.keys(tagVersionsSource);
5677
- const vers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
6706
+ const tags2 = Object.keys(tagVersionsSource);
6707
+ const vers = await Promise.all(tags2.map((tag) => this._getTagVersion(tag)));
5678
6708
  activeTagVersions = {};
5679
- for (let i = 0; i < tags.length; i++) {
5680
- activeTagVersions[tags[i]] = vers[i];
6709
+ for (let i = 0; i < tags2.length; i++) {
6710
+ activeTagVersions[tags2[i]] = vers[i];
5681
6711
  }
5682
6712
  if (knownTagVersions) {
5683
- for (const t of tags) {
6713
+ for (const t of tags2) {
5684
6714
  if (knownTagVersions[t] !== void 0 && activeTagVersions[t] !== knownTagVersions[t]) {
5685
6715
  this.logger.debug("SWR: aborting revalidation commit \u2014 tag version bumped during revalidation", { cacheKey, tag: t });
5686
6716
  return;
@@ -5692,32 +6722,29 @@ var CacheService = class _CacheService {
5692
6722
  this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
5693
6723
  return;
5694
6724
  }
5695
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
6725
+ const writeTs = Date.now();
6726
+ this._invalidateDiskKey(cacheKey);
6727
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs, tags, dependencies);
6728
+ this._restoreEntryMetadata(cacheKey, { tags, dependsOn: dependencies, expiresAt: writeTs + ttlMs + swrGraceMs });
5696
6729
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
5697
6730
  try {
5698
- const client = await this.getRedis();
5699
- const s = JSON.stringify(data);
5700
- const stored = await this._serializeAndEncrypt(s);
5701
- const ttlSec = Math.ceil(ttlMs / 1e3);
5702
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
5703
- const now = Date.now();
5704
- const tx = client.multi();
5705
- tx.hset(cacheKey, {
5706
- d: stored,
5707
- t: String(now),
5708
- tv: JSON.stringify(activeTagVersions)
5709
- });
5710
- tx.expire(cacheKey, ttlSec);
5711
- await tx.exec();
5712
- } else {
5713
- await client.setex(cacheKey, ttlSec, stored);
5714
- }
6731
+ await this._writeRedisEntry(
6732
+ cacheKey,
6733
+ data,
6734
+ writeTs + ttlMs + swrGraceMs,
6735
+ writeTs,
6736
+ activeTagVersions,
6737
+ staleAt,
6738
+ tags,
6739
+ dependencies,
6740
+ () => this._getKeyMutationEpoch(cacheKey) === startEpoch
6741
+ );
5715
6742
  } catch {
5716
6743
  }
5717
6744
  }
5718
6745
  this.logger.debug("SWR: revalidation complete", { cacheKey });
5719
6746
  } catch (err) {
5720
- if (this.opts.staleIfError > 0) {
6747
+ if (this.opts.staleIfError > 0 && this._getKeyMutationEpoch(cacheKey) === startEpoch) {
5721
6748
  const additionalMs = this.opts.staleIfError * 1e3;
5722
6749
  this.l1.bumpExpiry(cacheKey, additionalMs);
5723
6750
  this.logger.debug("SWR: revalidation failed, stale-if-error extending expiry", {
@@ -5745,12 +6772,16 @@ var CacheService = class _CacheService {
5745
6772
  const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
5746
6773
  const p = priority ?? inferPriority(cacheKey);
5747
6774
  const k = this.nk(cacheKey);
6775
+ const existingEntry = this.l1.getEntry(k);
6776
+ const requestedTags = opts?.tags ?? existingEntry?.tags ?? this.keyTags.get(k)?.tags;
6777
+ const requestedDependencies = opts?.dependsOn ?? existingEntry?.dependsOn;
5748
6778
  this._bumpKeyMutation(k);
6779
+ const epoch = this._getKeyMutationEpoch(k);
5749
6780
  this.inflight.delete(k);
5750
- this._pendingDiskDeletes.delete(k);
6781
+ this._invalidateDiskKey(k);
5751
6782
  this.counters.sets++;
5752
6783
  let activeTagVersions;
5753
- const tagsToRegister = opts?.tags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
6784
+ const tagsToRegister = requestedTags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(requestedTags, this.opts.tagHierarchyDelimiter) : requestedTags : void 0;
5754
6785
  if (tagsToRegister?.length) {
5755
6786
  if (this.opts.tagStrategy === "generational") {
5756
6787
  const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
@@ -5759,44 +6790,27 @@ var CacheService = class _CacheService {
5759
6790
  activeTagVersions[tagsToRegister[i]] = vers[i];
5760
6791
  }
5761
6792
  } else {
5762
- await this._registerTags(k, tagsToRegister, ttlSeconds);
5763
- }
5764
- }
5765
- this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
5766
- if (opts?.dependsOn?.length) {
5767
- for (const pattern of opts.dependsOn) {
5768
- const nsPattern = this.nk(pattern);
5769
- let deps = this.dependencyIndex.get(nsPattern);
5770
- if (!deps) {
5771
- deps = /* @__PURE__ */ new Set();
5772
- this.dependencyIndex.set(nsPattern, deps);
5773
- }
5774
- deps.add(k);
6793
+ await this._registerTags(k, tagsToRegister, effectiveTtlSeconds);
5775
6794
  }
5776
6795
  }
6796
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return;
6797
+ const writeTs = Date.now();
6798
+ this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions, writeTs, tagsToRegister, requestedDependencies);
6799
+ this._rememberTags(k, tagsToRegister ?? [], writeTs + ttlMs);
6800
+ this._registerDependencies(k, requestedDependencies);
5777
6801
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
5778
6802
  try {
5779
- const client = await this.getRedis();
5780
- const s = JSON.stringify(data);
5781
- const stored = await this._serializeAndEncrypt(s);
5782
- const ttlSec = Math.ceil(ttlMs / 1e3);
5783
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
5784
- const now = Date.now();
5785
- const tx = client.multi();
5786
- tx.hset(k, {
5787
- d: stored,
5788
- t: String(now),
5789
- tv: JSON.stringify(activeTagVersions)
5790
- });
5791
- tx.expire(k, ttlSec);
5792
- await tx.exec();
5793
- } else {
5794
- if (this.opts.autoPipeline && this.pipeliner) {
5795
- await this.pipeliner.setex(k, ttlSec, stored);
5796
- } else {
5797
- await client.setex(k, ttlSec, stored);
5798
- }
5799
- }
6803
+ await this._writeRedisEntry(
6804
+ k,
6805
+ data,
6806
+ writeTs + ttlMs,
6807
+ writeTs,
6808
+ activeTagVersions,
6809
+ void 0,
6810
+ tagsToRegister,
6811
+ requestedDependencies,
6812
+ () => this._getKeyMutationEpoch(k) === epoch
6813
+ );
5800
6814
  this.cb.onSuccess();
5801
6815
  } catch (err) {
5802
6816
  this.cb.onFailure();
@@ -5821,23 +6835,18 @@ var CacheService = class _CacheService {
5821
6835
  * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
5822
6836
  */
5823
6837
  async _registerTags(k, tags, ttlSeconds) {
5824
- for (const tag of tags) {
5825
- const tagKey = this.nk(`_tag_:${tag}`);
5826
- let members = this.tagIndex.get(tagKey);
5827
- if (!members) {
5828
- members = /* @__PURE__ */ new Set();
5829
- this.tagIndex.set(tagKey, members);
5830
- }
5831
- members.add(k);
5832
- }
6838
+ const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
6839
+ const expiresAt = Date.now() + effectiveTtl * 1e3;
6840
+ const uniqueTags = Array.from(new Set(tags));
6841
+ this._rememberTags(k, uniqueTags, expiresAt);
5833
6842
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
5834
6843
  try {
5835
6844
  const client = await this.getRedis();
5836
6845
  const pl = client.pipeline();
5837
- for (const tag of tags) {
6846
+ for (const tag of uniqueTags) {
5838
6847
  const tagKey = this.nk(`_tag_:${tag}`);
5839
6848
  pl.sadd(tagKey, k);
5840
- pl.expire(tagKey, ttlSeconds + 3600);
6849
+ pl.expire(tagKey, effectiveTtl + 3600);
5841
6850
  }
5842
6851
  await pl.exec();
5843
6852
  this.cb.onSuccess();
@@ -5862,6 +6871,7 @@ var CacheService = class _CacheService {
5862
6871
  const k = this.nk(cacheKey);
5863
6872
  this.counters.deletes++;
5864
6873
  if (isPattern) {
6874
+ this._fenceInvalidation();
5865
6875
  const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
5866
6876
  for (const liveKey of this.l1.liveKeys()) {
5867
6877
  if (liveKey.startsWith(pfx)) {
@@ -5874,29 +6884,30 @@ var CacheService = class _CacheService {
5874
6884
  this.inflight.delete(inflightKey);
5875
6885
  }
5876
6886
  }
5877
- this._addPatternTombstone(pfx);
6887
+ this._addPatternTombstone(k);
5878
6888
  this.l1.deletePattern(k);
6889
+ this._removePatternFromIndices(k);
6890
+ for (const ktKey of Array.from(this.keyTags.keys())) {
6891
+ if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
6892
+ }
6893
+ for (const kdKey of Array.from(this.keyDependencies.keys())) {
6894
+ if (this._matchesGlob(kdKey, k)) this._removeKeyDependencies(kdKey);
6895
+ }
5879
6896
  } else {
5880
6897
  this._bumpKeyMutation(k);
5881
6898
  this.inflight.delete(k);
5882
6899
  this.l1.delete(k);
5883
- this._pendingDiskDeletes.add(k);
5884
- setImmediate(() => {
5885
- try {
5886
- if (!this._diskDisabled) this.disk.delete(k);
5887
- } finally {
5888
- this._pendingDiskDeletes.delete(k);
5889
- }
5890
- });
6900
+ this._invalidateDiskKey(k);
6901
+ this._removeKeyTags(k);
5891
6902
  this._cascadeDependencies(k);
5892
- for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
6903
+ this._removeKeyDependencies(k);
5893
6904
  }
5894
6905
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
5895
6906
  try {
5896
6907
  const client = await this.getRedis();
5897
6908
  if (isPattern) {
5898
6909
  const keys = await this._scanKeys(client, k);
5899
- if (keys.length > 0) await client.del(...keys);
6910
+ await this._deleteRedisKeys(client, keys);
5900
6911
  } else {
5901
6912
  if (this.opts.autoPipeline && this.pipeliner) {
5902
6913
  await this.pipeliner.del(k);
@@ -5943,7 +6954,7 @@ var CacheService = class _CacheService {
5943
6954
  async increment(cacheKey, ttlSeconds) {
5944
6955
  this._assertActive("increment");
5945
6956
  const k = this.nk(cacheKey);
5946
- if (this._redisDisabled) {
6957
+ if (this._redisDisabled || this.opts.l2WriteMode === "read-only") {
5947
6958
  if (!this._incrementFallbackWarned) {
5948
6959
  this._incrementFallbackWarned = true;
5949
6960
  this.logger.warn(
@@ -5958,6 +6969,15 @@ var CacheService = class _CacheService {
5958
6969
  entry.value++;
5959
6970
  return entry.value;
5960
6971
  }
6972
+ if (this._l1Counters.size >= 5e4 && !this._l1Counters.has(k)) {
6973
+ for (const [ck, cv] of this._l1Counters) {
6974
+ if (cv.expiresAt <= now) this._l1Counters.delete(ck);
6975
+ }
6976
+ if (this._l1Counters.size >= 5e4) {
6977
+ const oldest = this._l1Counters.keys().next().value;
6978
+ if (oldest !== void 0) this._l1Counters.delete(oldest);
6979
+ }
6980
+ }
5961
6981
  this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
5962
6982
  return 1;
5963
6983
  }
@@ -5990,6 +7010,7 @@ var CacheService = class _CacheService {
5990
7010
  this.counters.deletes++;
5991
7011
  const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
5992
7012
  if (k) {
7013
+ this._fenceInvalidation();
5993
7014
  const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
5994
7015
  for (const liveKey of this.l1.liveKeys()) {
5995
7016
  if (liveKey.startsWith(pfx)) {
@@ -6002,8 +7023,9 @@ var CacheService = class _CacheService {
6002
7023
  this.inflight.delete(inflightKey);
6003
7024
  }
6004
7025
  }
6005
- this._addPatternTombstone(pfx);
7026
+ this._addPatternTombstone(k);
6006
7027
  this.l1.deletePattern(k);
7028
+ this._removePatternFromIndices(k);
6007
7029
  } else {
6008
7030
  this._globalEpoch++;
6009
7031
  this.inflight.clear();
@@ -6012,7 +7034,10 @@ var CacheService = class _CacheService {
6012
7034
  if (!this._diskDisabled) this.disk.clear();
6013
7035
  this._l1Counters.clear();
6014
7036
  this.tagIndex.clear();
7037
+ this.keyTags.clear();
6015
7038
  this.tagVersions.clear();
7039
+ this.dependencyIndex.clear();
7040
+ this.keyDependencies.clear();
6016
7041
  this._pendingDiskDeletes.clear();
6017
7042
  this._keyMutationEpochs.clear();
6018
7043
  }
@@ -6021,7 +7046,7 @@ var CacheService = class _CacheService {
6021
7046
  const client = await this.getRedis();
6022
7047
  const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
6023
7048
  const keys = await this._scanKeys(client, pattern);
6024
- if (keys.length > 0) await client.del(...keys);
7049
+ await this._deleteRedisKeys(client, keys);
6025
7050
  } catch (err) {
6026
7051
  this.logger.debug("clear: Redis unavailable", { error: err.message });
6027
7052
  }
@@ -6150,24 +7175,34 @@ var CacheService = class _CacheService {
6150
7175
  this._assertActive("scan");
6151
7176
  const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
6152
7177
  this.l1.scan((key, entry, pfx) => {
6153
- const value = entry.value !== void 0 ? entry.value : entry.data;
6154
- fn(key, value, pfx);
7178
+ fn(key, this._prepareReadValue(this.l1.resolveValue(entry)), pfx);
6155
7179
  }, prefixLen);
6156
7180
  }
6157
7181
  /**
6158
- * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
7182
+ * Extend the TTL of a key in L1 and Redis without fetching.
6159
7183
  * Returns `false` if the key is absent or already expired.
6160
7184
  *
6161
7185
  * @param newTtlSeconds - The new TTL from now, in seconds.
6162
7186
  */
6163
7187
  async touch(cacheKey, newTtlSeconds) {
6164
7188
  this._assertActive("touch");
7189
+ if (!Number.isFinite(newTtlSeconds) || newTtlSeconds <= 0) throw new Error("touch TTL must be finite and positive");
6165
7190
  const k = this.nk(cacheKey);
7191
+ const epoch = this._getKeyMutationEpoch(k);
6166
7192
  const hit = this.l1.touch(k, newTtlSeconds * 1e3);
6167
- if (hit && !this._redisDisabled) {
7193
+ const entry = this.l1.getEntry(k);
7194
+ if (hit) {
7195
+ const kt = this.keyTags.get(k);
7196
+ if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1e3;
7197
+ }
7198
+ if (hit && !this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6168
7199
  try {
6169
7200
  const client = await this.getRedis();
6170
- void client.expire(k, newTtlSeconds);
7201
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return hit;
7202
+ if (entry && typeof client.pttl === "function" && typeof client.eval === "function") {
7203
+ await client.eval(LUA_TOUCH_CACHE_ENTRY, 1, k, String(entry.setAt ?? 0), String(entry.expiresAt), String(Math.ceil(newTtlSeconds * 1e3)));
7204
+ } else await client.expire(k, Math.ceil(newTtlSeconds));
7205
+ this.cb.onSuccess();
6171
7206
  } catch {
6172
7207
  }
6173
7208
  }
@@ -6189,7 +7224,12 @@ var CacheService = class _CacheService {
6189
7224
  const now = Date.now();
6190
7225
  if (entry.expiresAt <= now) return null;
6191
7226
  if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
6192
- return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
7227
+ if (entry.tagVersions && Object.entries(entry.tagVersions).some(([tag, version]) => (this.tagVersions.get(tag)?.version ?? 0) > version)) return null;
7228
+ return this._prepareReadValue(entry.value !== void 0 ? entry.value : this.codec.decode(entry.data));
7229
+ }
7230
+ _prepareReadValue(val) {
7231
+ if (this.opts.frozen) deepFreeze(val);
7232
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6193
7233
  }
6194
7234
  /**
6195
7235
  * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
@@ -6202,59 +7242,36 @@ var CacheService = class _CacheService {
6202
7242
  async peek(cacheKey) {
6203
7243
  this._assertActive("peek");
6204
7244
  const k = this.nk(cacheKey);
7245
+ const epoch = this._getKeyMutationEpoch(k);
7246
+ this.counters.gets++;
6205
7247
  const l1Hit = this.l1.get(k);
6206
7248
  if (l1Hit !== null) {
6207
- this.counters.gets++;
6208
- this.counters.l1Hits++;
6209
- const val = l1Hit.value;
6210
- if (this.opts.frozen) deepFreeze(val);
6211
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6212
- }
6213
- if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
6214
- if (this._isTombstonedByPattern(k)) {
6215
- try {
6216
- this.disk.delete(k);
6217
- } catch {
6218
- }
6219
- } else if (this.watchdog.isDiskAllowed()) {
6220
- const diskStart = performance.now();
6221
- const diskHit = this.disk.load(k);
6222
- const diskElapsed = performance.now() - diskStart;
6223
- this.watchdog.recordDisk(diskElapsed);
6224
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6225
- if (diskHit !== null) {
6226
- const promoted = this.l1.importEntries(
6227
- [{ key: k, entry: diskHit }],
6228
- this.opts.forbiddenSnapshotPrefixes
6229
- );
6230
- if (promoted > 0) {
6231
- const l1Check = this.l1.get(k);
6232
- if (l1Check !== null) {
6233
- this.counters.gets++;
6234
- this.counters.diskHits++;
6235
- const val = l1Check.value;
6236
- if (this.opts.frozen) deepFreeze(val);
6237
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6238
- }
6239
- }
6240
- }
7249
+ if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
7250
+ this._deleteIfStale(k, l1Hit.setAt ?? 0);
7251
+ } else {
7252
+ this.counters.l1Hits++;
7253
+ return this._prepareReadValue(l1Hit.value);
6241
7254
  }
6242
7255
  }
6243
- if (!this._redisDisabled && !this.cb.isOpen) {
7256
+ const diskHit = await this._readDiskEntry(k, epoch);
7257
+ if (diskHit) {
7258
+ this.counters.diskHits++;
7259
+ return this._prepareReadValue(diskHit.value);
7260
+ }
7261
+ if (!this._redisDisabled) {
6244
7262
  try {
6245
7263
  const client = await this.getRedis();
6246
7264
  const redisStart = performance.now();
6247
- const raw = await client.get(k);
7265
+ const redisHit = await this._readRedisEntry(client, k);
6248
7266
  const redisElapsed = performance.now() - redisStart;
6249
7267
  this.watchdog.recordRedis(redisElapsed);
6250
- if (raw !== null) {
6251
- const parsed = await this._decryptAndDeserialize(raw);
6252
- this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
6253
- this.counters.gets++;
7268
+ this.cb.onSuccess();
7269
+ if (redisHit && !redisHit.stale) {
7270
+ const parsed = redisHit.value;
7271
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return null;
7272
+ if (!this._promoteRedisEntry(k, redisHit, 6e4, inferPriority(cacheKey))) return null;
6254
7273
  this.counters.l2Hits++;
6255
- this.cb.onSuccess();
6256
- if (this.opts.frozen) deepFreeze(parsed);
6257
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
7274
+ return this._prepareReadValue(parsed);
6258
7275
  }
6259
7276
  } catch (err) {
6260
7277
  this.cb.onFailure();
@@ -6274,6 +7291,8 @@ var CacheService = class _CacheService {
6274
7291
  */
6275
7292
  async mget(keys, fetchFn, ttl = 300, priority) {
6276
7293
  this._assertActive("mget");
7294
+ this.counters.gets += keys.length;
7295
+ const epochs = new Map(keys.map((key) => [this.nk(key), this._getKeyMutationEpoch(this.nk(key))]));
6277
7296
  const span = this._startSpan("tricache.mget");
6278
7297
  if (this.opts.tracer) {
6279
7298
  span.setAttribute("cache.batch.size", keys.length);
@@ -6282,12 +7301,20 @@ var CacheService = class _CacheService {
6282
7301
  const result = Array.from({ length: keys.length });
6283
7302
  const missIndexes = [];
6284
7303
  const missKeys = [];
7304
+ const now = Date.now();
6285
7305
  for (let i = 0; i < keys.length; i++) {
6286
7306
  const k = this.nk(keys[i]);
6287
7307
  const entry = this.l1.getEntry(k);
6288
- if (entry && entry.expiresAt > Date.now()) {
6289
- result[i] = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
6290
- this.counters.l1Hits++;
7308
+ if (entry && entry.expiresAt > now && (entry.staleAt === void 0 || entry.staleAt > now)) {
7309
+ if (await this._isGenerationalEntryStale(entry.tagVersions)) {
7310
+ this._deleteIfStale(k, entry.setAt ?? 0);
7311
+ missIndexes.push(i);
7312
+ missKeys.push(keys[i]);
7313
+ } else {
7314
+ const val = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
7315
+ result[i] = this._prepareReadValue(val);
7316
+ this.counters.l1Hits++;
7317
+ }
6291
7318
  } else {
6292
7319
  missIndexes.push(i);
6293
7320
  missKeys.push(keys[i]);
@@ -6307,30 +7334,24 @@ var CacheService = class _CacheService {
6307
7334
  try {
6308
7335
  const client = await this.getRedis();
6309
7336
  const nsKeys = missKeys.map((k) => this.nk(k));
6310
- const pipeline = client.multi();
6311
- for (const nk of nsKeys) pipeline.get(nk);
6312
- const redisStart = performance.now();
6313
- const raws = await pipeline.exec();
6314
- const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
6315
- this.watchdog.recordRedis(redisElapsed);
6316
- this.cb.onSuccess();
7337
+ const remoteEntries = await this._readRedisBatch(client, nsKeys);
6317
7338
  for (let j = 0; j < missKeys.length; j++) {
6318
- const raw = raws[j] ? raws[j][1] : null;
6319
7339
  const idx = missIndexes[j];
6320
- if (raw) {
6321
- const parsed = await this._decryptAndDeserialize(raw);
6322
- const k = nsKeys[j];
7340
+ const k = nsKeys[j];
7341
+ const entry = remoteEntries.get(k);
7342
+ if (entry && (entry.staleAt === void 0 || entry.staleAt > Date.now()) && !this._destroyed && this._getKeyMutationEpoch(k) === epochs.get(k)) {
6323
7343
  const p = priority ?? inferPriority(missKeys[j]);
6324
- this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
7344
+ const ttlVal = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
7345
+ if (!this._promoteRedisEntry(k, entry, this._jitterTtl(ttlVal * 1e3), p)) continue;
6325
7346
  this.counters.l2Hits++;
6326
7347
  l2HitCount++;
6327
- result[idx] = parsed;
7348
+ result[idx] = this._prepareReadValue(entry.value);
6328
7349
  missIndexes[j] = -1;
6329
7350
  missKeys[j] = "";
6330
7351
  }
6331
7352
  }
6332
7353
  const remainingIdx = missIndexes.filter((i) => i >= 0);
6333
- const remainingKeys = missKeys.filter((k) => k !== "");
7354
+ const remainingKeys = missKeys.filter((_key, index) => missIndexes[index] >= 0);
6334
7355
  missIndexes.length = 0;
6335
7356
  missKeys.length = 0;
6336
7357
  missIndexes.push(...remainingIdx);
@@ -6343,58 +7364,64 @@ var CacheService = class _CacheService {
6343
7364
  if (!this._diskDisabled && missKeys.length > 0) {
6344
7365
  for (let j = missKeys.length - 1; j >= 0; j--) {
6345
7366
  const k = this.nk(missKeys[j]);
6346
- if (this._pendingDiskDeletes.has(k)) continue;
6347
- if (this._isTombstonedByPattern(k)) {
6348
- try {
6349
- this.disk.delete(k);
6350
- } catch {
6351
- }
6352
- continue;
6353
- }
6354
- if (!this.watchdog.isDiskAllowed()) continue;
6355
- const diskStart = performance.now();
6356
- const diskHit = this.disk.load(k);
6357
- const diskElapsed = performance.now() - diskStart;
6358
- this.watchdog.recordDisk(diskElapsed);
6359
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6360
- if (diskHit !== null) {
6361
- const promoted = this.l1.importEntries(
6362
- [{ key: k, entry: diskHit }],
6363
- this.opts.forbiddenSnapshotPrefixes
6364
- );
6365
- if (promoted > 0) {
6366
- const l1Check = this.l1.get(k);
6367
- if (l1Check !== null) {
6368
- this.counters.diskHits++;
6369
- result[missIndexes[j]] = l1Check.value;
6370
- missIndexes.splice(j, 1);
6371
- missKeys.splice(j, 1);
6372
- }
6373
- }
7367
+ const diskHit = await this._readDiskEntry(k, epochs.get(k));
7368
+ if (diskHit && (diskHit.entry.staleAt === void 0 || diskHit.entry.staleAt > Date.now())) {
7369
+ this.counters.diskHits++;
7370
+ result[missIndexes[j]] = this._prepareReadValue(diskHit.value);
7371
+ missIndexes.splice(j, 1);
7372
+ missKeys.splice(j, 1);
6374
7373
  }
6375
7374
  }
6376
7375
  }
6377
7376
  if (missKeys.length > 0 && fetchFn) {
6378
- this.counters.fetches++;
6379
- const fetched = await fetchFn(missKeys);
6380
- const isMap = fetched instanceof Map;
6381
- const setPromises = [];
7377
+ const owned = /* @__PURE__ */ new Map();
7378
+ const waiting = [];
6382
7379
  for (let j = 0; j < missKeys.length; j++) {
6383
- const k = missKeys[j];
6384
- const v = isMap ? fetched.get(k) : fetched[k];
6385
- result[missIndexes[j]] = v;
6386
- if (v !== void 0 && v !== null) {
6387
- const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
6388
- setPromises.push(this.set(k, v, resolvedTtl, priority));
6389
- } else if (v == null && this.opts.notFoundTtl > 0) {
6390
- setPromises.push(this.set(k, null, this.opts.notFoundTtl, priority));
6391
- } else if (v === null) {
6392
- const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
6393
- setPromises.push(this.set(k, null, resolvedTtl, priority));
7380
+ const key = missKeys[j];
7381
+ const namespaced = this.nk(key);
7382
+ let promise = this.inflight.get(namespaced);
7383
+ if (!promise) {
7384
+ let resolve;
7385
+ let reject;
7386
+ promise = new Promise((yes, no) => {
7387
+ resolve = yes;
7388
+ reject = no;
7389
+ });
7390
+ owned.set(key, { promise, resolve, reject });
7391
+ this.inflight.set(namespaced, promise);
7392
+ } else {
7393
+ this.counters.stampedes++;
6394
7394
  }
7395
+ const index = missIndexes[j];
7396
+ waiting.push(promise.then((value) => {
7397
+ result[index] = this._prepareReadValue(value);
7398
+ }));
6395
7399
  }
6396
- if (setPromises.length > 0) {
6397
- await Promise.all(setPromises);
7400
+ const settled = Promise.allSettled(waiting);
7401
+ try {
7402
+ if (owned.size > 0) {
7403
+ this.counters.fetches++;
7404
+ const fetched = await fetchFn([...owned.keys()]);
7405
+ await Promise.all([...owned].map(async ([key, entry]) => {
7406
+ const value = fetched instanceof Map ? fetched.get(key) : Object.hasOwn(fetched, key) ? fetched[key] : void 0;
7407
+ if (!this._destroyed && this._getKeyMutationEpoch(this.nk(key)) === epochs.get(this.nk(key))) {
7408
+ const resolvedTtl = value == null && this.opts.notFoundTtl > 0 ? this.opts.notFoundTtl : typeof ttl === "function" ? ttl(key) : ttl;
7409
+ if (value !== void 0 || this.opts.notFoundTtl > 0) await this.set(key, value === void 0 && this.opts.notFoundTtl > 0 ? null : value, resolvedTtl, priority);
7410
+ }
7411
+ entry.resolve(value);
7412
+ }));
7413
+ }
7414
+ const outcomes = await settled;
7415
+ const failed = outcomes.find((outcome) => outcome.status === "rejected");
7416
+ if (failed?.status === "rejected") throw failed.reason;
7417
+ } catch (error) {
7418
+ for (const entry of owned.values()) entry.reject(error);
7419
+ throw error;
7420
+ } finally {
7421
+ for (const [key, entry] of owned) {
7422
+ const namespaced = this.nk(key);
7423
+ if (this.inflight.get(namespaced) === entry.promise) this.inflight.delete(namespaced);
7424
+ }
6398
7425
  }
6399
7426
  }
6400
7427
  if (this.opts.tracer) {
@@ -6447,7 +7474,7 @@ var CacheService = class _CacheService {
6447
7474
  try {
6448
7475
  await Promise.all(keys.map((key) => {
6449
7476
  const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
6450
- const hasOpts = tags?.length || dependsOn?.length;
7477
+ const hasOpts = tags !== void 0 || dependsOn !== void 0;
6451
7478
  return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
6452
7479
  }));
6453
7480
  } catch (err) {
@@ -6499,26 +7526,21 @@ var CacheService = class _CacheService {
6499
7526
  try {
6500
7527
  const client = await this.getRedis();
6501
7528
  const nsPattern = this.nk(pattern);
6502
- const matchedKeys = await this._scanKeys(client, nsPattern);
7529
+ const matchedKeys = (await this._scanKeys(client, nsPattern)).filter((key) => {
7530
+ const raw = this.unnk(key);
7531
+ return !raw.startsWith("_tag_:") && !raw.startsWith("tag_ver:") && !raw.startsWith("lock:") && key !== this.backplaneStreamKey;
7532
+ });
6503
7533
  if (matchedKeys.length === 0) {
6504
7534
  this.cb.onSuccess();
6505
7535
  return 0;
6506
7536
  }
6507
- const pl = client.pipeline();
6508
- for (const k of matchedKeys) pl.get(k);
6509
- const results = await pl.exec();
6510
- this.cb.onSuccess();
7537
+ const epochs = new Map(matchedKeys.map((key) => [key, this._getKeyMutationEpoch(key)]));
7538
+ const results = await this._readRedisBatch(client, matchedKeys);
6511
7539
  let loaded = 0;
6512
- for (let i = 0; i < matchedKeys.length; i++) {
6513
- const [err, raw] = results[i];
6514
- if (err || raw == null) continue;
6515
- try {
6516
- const parsed = await this._decryptAndDeserialize(raw);
6517
- const remainingMs = 10 * 60 * 1e3;
6518
- this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
6519
- loaded++;
6520
- } catch {
6521
- }
7540
+ for (const key of matchedKeys) {
7541
+ const entry = results.get(key);
7542
+ if (!entry || this._destroyed || this._getKeyMutationEpoch(key) !== epochs.get(key)) continue;
7543
+ if (this._promoteRedisEntry(key, entry, 10 * 60 * 1e3, opts?.priority ?? inferPriority(this.unnk(key))) && this.l1.has(key)) loaded++;
6522
7544
  }
6523
7545
  this.logger.info("warmFromL2 complete", {
6524
7546
  pattern,
@@ -6591,6 +7613,139 @@ var CacheService = class _CacheService {
6591
7613
  }
6592
7614
  return matched;
6593
7615
  }
7616
+ async _publishTagInvalidation(op, key, tagVersion) {
7617
+ if (this.opts.awaitInvalidationBackplane) {
7618
+ await this.publishInvalidation(op, key, tagVersion, false, true);
7619
+ } else {
7620
+ void this.publishInvalidation(op, key, tagVersion, false, true);
7621
+ }
7622
+ }
7623
+ _removeTagMembersLocal(keys) {
7624
+ const keyList = Array.isArray(keys) ? keys : Array.from(keys);
7625
+ for (const k of keyList) {
7626
+ this.l1.delete(k);
7627
+ this._bumpKeyMutation(k);
7628
+ this._removeKeyTags(k);
7629
+ this._removeKeyDependencies(k);
7630
+ this._invalidateDiskKey(k);
7631
+ }
7632
+ }
7633
+ /**
7634
+ * Executes invalidation for a single already-resolved concrete tag without
7635
+ * wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
7636
+ */
7637
+ async _invalidateConcreteTag(tag) {
7638
+ this._fenceInvalidation();
7639
+ if (this.opts.tagStrategy === "generational") {
7640
+ let newVer = 1;
7641
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7642
+ try {
7643
+ const client = await this.getRedis();
7644
+ newVer = await client.incr(this.nk(`tag_ver:${tag}`));
7645
+ } catch (err) {
7646
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7647
+ const current = this.tagVersions.get(tag)?.version ?? 0;
7648
+ newVer = current + 1;
7649
+ }
7650
+ } else {
7651
+ const current = this.tagVersions.get(tag)?.version ?? 0;
7652
+ newVer = current + 1;
7653
+ }
7654
+ this._setLocalTagVersion(tag, newVer, performance.now());
7655
+ await this._publishTagInvalidation("tag_incr", tag, newVer);
7656
+ return;
7657
+ }
7658
+ const tagKey = this.nk(`_tag_:${tag}`);
7659
+ const members = new Set(this.tagIndex.get(tagKey) ?? []);
7660
+ this.tagIndex.delete(tagKey);
7661
+ this._removeTagMembersLocal(members);
7662
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7663
+ try {
7664
+ const client = await this.getRedis();
7665
+ const redisMembers = await client.smembers(tagKey);
7666
+ for (const key of redisMembers) members.add(key);
7667
+ this._removeTagMembersLocal(redisMembers);
7668
+ const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers, tagKey])];
7669
+ await this._deleteRedisKeys(client, toDelete);
7670
+ } catch (err) {
7671
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7672
+ }
7673
+ }
7674
+ await Promise.all([...members].map((key) => this._publishTagInvalidation("del", key)));
7675
+ await this._publishTagInvalidation("tag_pattern_del", tag);
7676
+ }
7677
+ /**
7678
+ * Executes invalidation for an array of already-resolved concrete tags
7679
+ * without re-entering wildcard/cascade resolution or invalidateTag().
7680
+ */
7681
+ async _invalidateConcreteTags(tags) {
7682
+ if (tags.length === 0) return;
7683
+ if (tags.length === 1) {
7684
+ await this._invalidateConcreteTag(tags[0]);
7685
+ return;
7686
+ }
7687
+ this._fenceInvalidation();
7688
+ if (this.opts.tagStrategy === "generational") {
7689
+ const now = performance.now();
7690
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7691
+ try {
7692
+ const client = await this.getRedis();
7693
+ const pl = client.pipeline();
7694
+ for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
7695
+ const results = await pl.exec();
7696
+ for (let i = 0; i < tags.length; i++) {
7697
+ const [err, newVer] = results[i] ?? [null, null];
7698
+ const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
7699
+ this._setLocalTagVersion(tags[i], ver, now);
7700
+ await this._publishTagInvalidation("tag_incr", tags[i], ver);
7701
+ }
7702
+ return;
7703
+ } catch (err) {
7704
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7705
+ }
7706
+ }
7707
+ for (const tag of tags) {
7708
+ const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
7709
+ this._setLocalTagVersion(tag, ver, now);
7710
+ await this._publishTagInvalidation("tag_incr", tag, ver);
7711
+ }
7712
+ return;
7713
+ }
7714
+ const tagKeys = [];
7715
+ const allMembers = /* @__PURE__ */ new Set();
7716
+ for (const tag of tags) {
7717
+ const tagKey = this.nk(`_tag_:${tag}`);
7718
+ tagKeys.push(tagKey);
7719
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
7720
+ for (const k of members) allMembers.add(k);
7721
+ this.tagIndex.delete(tagKey);
7722
+ }
7723
+ this._removeTagMembersLocal(allMembers);
7724
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7725
+ try {
7726
+ const client = await this.getRedis();
7727
+ const pl = client.pipeline();
7728
+ for (const tagKey of tagKeys) pl.smembers(tagKey);
7729
+ const smResults = await pl.exec();
7730
+ const toDelete = [...allMembers];
7731
+ for (const [err, redisMembers] of smResults) {
7732
+ if (!err && redisMembers) {
7733
+ for (const k of redisMembers) {
7734
+ if (!allMembers.has(k)) toDelete.push(k);
7735
+ allMembers.add(k);
7736
+ }
7737
+ }
7738
+ }
7739
+ const keysToRemove = [...toDelete, ...tagKeys];
7740
+ await this._deleteRedisKeys(client, keysToRemove);
7741
+ this._removeTagMembersLocal(allMembers);
7742
+ } catch (err) {
7743
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7744
+ }
7745
+ }
7746
+ await Promise.all([...allMembers].map((key) => this._publishTagInvalidation("del", key)));
7747
+ for (const tag of tags) await this._publishTagInvalidation("tag_pattern_del", tag);
7748
+ }
6594
7749
  /**
6595
7750
  * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
6596
7751
  * Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
@@ -6626,68 +7781,13 @@ var CacheService = class _CacheService {
6626
7781
  const delim = this.opts.tagHierarchyDelimiter;
6627
7782
  const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
6628
7783
  if (matchedTags.size > 0) {
6629
- await this.invalidateTags(Array.from(matchedTags));
7784
+ await this._invalidateConcreteTags(Array.from(matchedTags));
6630
7785
  }
6631
7786
  const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
6632
- if (this.opts.awaitInvalidationBackplane) {
6633
- await this.publishInvalidation(op, broadcastPattern, void 0, false, true);
6634
- } else {
6635
- void this.publishInvalidation(op, broadcastPattern, void 0, false, true);
6636
- }
6637
- return;
6638
- }
6639
- if (this.opts.tagStrategy === "generational") {
6640
- let newVer = 1;
6641
- if (!this._redisDisabled) {
6642
- try {
6643
- const client = await this.getRedis();
6644
- newVer = await client.incr(this.nk(`tag_ver:${tag}`));
6645
- } catch (err) {
6646
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
6647
- const current = this.tagVersions.get(tag)?.version ?? 0;
6648
- newVer = current + 1;
6649
- }
6650
- } else {
6651
- const current = this.tagVersions.get(tag)?.version ?? 0;
6652
- newVer = current + 1;
6653
- }
6654
- this._setLocalTagVersion(tag, newVer, performance.now());
6655
- if (this.opts.awaitInvalidationBackplane) {
6656
- await this.publishInvalidation("tag_incr", tag, newVer, false, true);
6657
- } else {
6658
- void this.publishInvalidation("tag_incr", tag, newVer, false, true);
6659
- }
7787
+ await this._publishTagInvalidation(op, broadcastPattern);
6660
7788
  return;
6661
7789
  }
6662
- const tagKey = this.nk(`_tag_:${tag}`);
6663
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
6664
- for (const k of members) {
6665
- this.l1.delete(k);
6666
- this._bumpKeyMutation(k);
6667
- this._pendingDiskDeletes.add(k);
6668
- setImmediate(() => {
6669
- try {
6670
- if (!this._diskDisabled) this.disk.delete(k);
6671
- } finally {
6672
- this._pendingDiskDeletes.delete(k);
6673
- }
6674
- });
6675
- }
6676
- this.tagIndex.delete(tagKey);
6677
- if (!this._redisDisabled) {
6678
- try {
6679
- const client = await this.getRedis();
6680
- const redisMembers = await client.smembers(tagKey);
6681
- const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
6682
- if (toDelete.length > 0) {
6683
- await client.del(...toDelete, tagKey);
6684
- } else {
6685
- await client.del(tagKey);
6686
- }
6687
- } catch (err) {
6688
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
6689
- }
6690
- }
7790
+ await this._invalidateConcreteTag(tag);
6691
7791
  } catch (err) {
6692
7792
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
6693
7793
  span.recordException?.(err);
@@ -6714,96 +7814,28 @@ var CacheService = class _CacheService {
6714
7814
  const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
6715
7815
  if (hasWildcards || shouldCascade) {
6716
7816
  const allResolvedTags = /* @__PURE__ */ new Set();
7817
+ const broadcastPatterns = /* @__PURE__ */ new Set();
7818
+ const delim = this.opts.tagHierarchyDelimiter;
6717
7819
  for (const t of tags) {
6718
- if (isWildcardTag(t) || shouldCascade) {
7820
+ const tIsPattern = isWildcardTag(t);
7821
+ if (tIsPattern || shouldCascade) {
7822
+ broadcastPatterns.add(tIsPattern ? t : `${t}${delim}*`);
6719
7823
  const resolved = await this._resolveMatchingTags(t, shouldCascade);
6720
7824
  for (const rt of resolved) allResolvedTags.add(rt);
6721
7825
  } else {
6722
7826
  allResolvedTags.add(t);
6723
7827
  }
6724
7828
  }
6725
- if (allResolvedTags.size === 0) return;
6726
- tags = Array.from(allResolvedTags);
6727
- }
6728
- if (tags.length === 1) {
6729
- await this.invalidateTag(tags[0], opts);
6730
- return;
6731
- }
6732
- if (this.opts.tagStrategy === "generational") {
6733
- const now = performance.now();
6734
- if (!this._redisDisabled) {
6735
- try {
6736
- const client = await this.getRedis();
6737
- const pl = client.pipeline();
6738
- for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
6739
- const results = await pl.exec();
6740
- for (let i = 0; i < tags.length; i++) {
6741
- const [err, newVer] = results[i] ?? [null, null];
6742
- const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
6743
- this._setLocalTagVersion(tags[i], ver, now);
6744
- if (this.opts.awaitInvalidationBackplane) {
6745
- await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
6746
- } else {
6747
- void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
6748
- }
6749
- }
6750
- return;
6751
- } catch (err) {
6752
- this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
6753
- }
7829
+ if (allResolvedTags.size > 0) {
7830
+ await this._invalidateConcreteTags(Array.from(allResolvedTags));
6754
7831
  }
6755
- for (const tag of tags) {
6756
- const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
6757
- this._setLocalTagVersion(tag, ver, now);
6758
- if (this.opts.awaitInvalidationBackplane) {
6759
- await this.publishInvalidation("tag_incr", tag, ver, false, true);
6760
- } else {
6761
- void this.publishInvalidation("tag_incr", tag, ver, false, true);
6762
- }
7832
+ const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
7833
+ for (const pattern of broadcastPatterns) {
7834
+ await this._publishTagInvalidation(op, pattern);
6763
7835
  }
6764
7836
  return;
6765
7837
  }
6766
- const tagKeys = [];
6767
- const allMembers = /* @__PURE__ */ new Set();
6768
- for (const tag of tags) {
6769
- const tagKey = this.nk(`_tag_:${tag}`);
6770
- tagKeys.push(tagKey);
6771
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
6772
- for (const k of members) allMembers.add(k);
6773
- this.tagIndex.delete(tagKey);
6774
- }
6775
- for (const k of allMembers) {
6776
- this.l1.delete(k);
6777
- this._bumpKeyMutation(k);
6778
- this._pendingDiskDeletes.add(k);
6779
- setImmediate(() => {
6780
- try {
6781
- if (!this._diskDisabled) this.disk.delete(k);
6782
- } finally {
6783
- this._pendingDiskDeletes.delete(k);
6784
- }
6785
- });
6786
- }
6787
- if (!this._redisDisabled) {
6788
- try {
6789
- const client = await this.getRedis();
6790
- const pl = client.pipeline();
6791
- for (const tagKey of tagKeys) pl.smembers(tagKey);
6792
- const smResults = await pl.exec();
6793
- const toDelete = [...allMembers];
6794
- for (const [err, redisMembers] of smResults) {
6795
- if (!err && redisMembers) {
6796
- for (const k of redisMembers) {
6797
- if (!allMembers.has(k)) toDelete.push(k);
6798
- }
6799
- }
6800
- }
6801
- const keysToRemove = [...toDelete, ...tagKeys];
6802
- if (keysToRemove.length > 0) await client.del(...keysToRemove);
6803
- } catch (err) {
6804
- this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
6805
- }
6806
- }
7838
+ await this._invalidateConcreteTags(Array.from(new Set(tags)));
6807
7839
  }
6808
7840
  /**
6809
7841
  * Get the current generational tag version for a tag (synced with Redis when due).
@@ -6866,19 +7898,23 @@ var CacheService = class _CacheService {
6866
7898
  const diskLowSpace = !this._diskDisabled && this.disk.hostVolumeLowSpace;
6867
7899
  const circuitOpen = this.cb.isOpen;
6868
7900
  const latencyBypass = watchdogTel.bypassActive;
6869
- const degraded = circuitOpen || latencyBypass || diskPruning || diskLowSpace;
6870
- const healthy = this.opts.failReadinessOnDegraded ? !degraded : true;
7901
+ const backplaneUnavailable = this.opts.invalidationBackplane && !this._redisDisabled && !this._backplaneAvailable;
7902
+ const degraded = this._destroyed || circuitOpen || latencyBypass || diskPruning || diskLowSpace || backplaneUnavailable;
7903
+ const healthy = !this._destroyed && (this.opts.failReadinessOnDegraded ? !degraded : true);
6871
7904
  const reasons = [];
6872
7905
  if (circuitOpen) reasons.push("redis_circuit_breaker_open");
6873
7906
  if (latencyBypass) reasons.push(`disk_latency_bypass_stage_${watchdogTel.bypassStage}`);
6874
7907
  if (diskPruning) reasons.push("disk_quota_watermark_pruning_active");
6875
7908
  if (diskLowSpace) reasons.push("disk_host_volume_low_space");
7909
+ if (backplaneUnavailable) reasons.push("invalidation_backplane_unavailable");
7910
+ if (this._destroyed) reasons.push("cache_destroyed");
6876
7911
  return {
6877
7912
  healthy,
6878
7913
  degraded,
6879
7914
  reasons,
6880
7915
  details: {
6881
- redisConnected: !circuitOpen && !this._redisDisabled,
7916
+ redisConnected: !this._destroyed && !circuitOpen && !!this.redis && (this.redis.status === "ready" || this.redis.isOpen === true),
7917
+ backplaneReady: this._backplaneAvailable,
6882
7918
  circuitBreakerState: this.cb.currentState,
6883
7919
  diskPruningActive: diskPruning,
6884
7920
  diskHostVolumeLowSpace: diskLowSpace,
@@ -6900,23 +7936,28 @@ var CacheService = class _CacheService {
6900
7936
  */
6901
7937
  async drainToL2() {
6902
7938
  this._assertActive("drainToL2");
6903
- if (this._redisDisabled) return 0;
7939
+ if (this._redisDisabled || this.opts.l2WriteMode === "read-only") return 0;
6904
7940
  try {
6905
- const client = await this.getRedis();
6906
7941
  const entries = this.l1.exportEntries([]);
6907
- const now = Date.now();
6908
7942
  if (entries.length === 0) return 0;
6909
- const pl = client.pipeline();
6910
- for (const { key, entry } of entries) {
6911
- const remainingMs = entry.expiresAt - now;
6912
- if (remainingMs <= 0) continue;
6913
- const ttlSecs = Math.max(1, Math.ceil(remainingMs / 1e3));
6914
- const s = JSON.stringify(entry.value);
6915
- const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
6916
- pl.setex(key, ttlSecs, stored);
6917
- }
6918
- await pl.exec();
6919
- return entries.length;
7943
+ let written = 0;
7944
+ await Promise.all(entries.map(async ({ key, entry }) => {
7945
+ const epoch = this._getKeyMutationEpoch(key);
7946
+ if (entry.expiresAt <= Date.now()) return;
7947
+ await this._writeRedisEntry(
7948
+ key,
7949
+ this.l1.resolveValue(entry),
7950
+ entry.expiresAt,
7951
+ entry.setAt ?? Date.now(),
7952
+ entry.tagVersions,
7953
+ entry.staleAt,
7954
+ entry.tags,
7955
+ entry.dependsOn,
7956
+ () => this._getKeyMutationEpoch(key) === epoch
7957
+ );
7958
+ written++;
7959
+ }));
7960
+ return written;
6920
7961
  } catch (err) {
6921
7962
  this.logger.debug("drainToL2: Redis unavailable", { error: err.message });
6922
7963
  return 0;
@@ -6946,7 +7987,7 @@ var CacheService = class _CacheService {
6946
7987
  this._assertActive("setIfAbsent");
6947
7988
  const k = this.nk(cacheKey);
6948
7989
  if (this.l1.has(k)) return false;
6949
- if (!this._redisDisabled) {
7990
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6950
7991
  try {
6951
7992
  const client = await this.getRedis();
6952
7993
  const serialized = JSON.stringify(value);
@@ -6963,7 +8004,7 @@ var CacheService = class _CacheService {
6963
8004
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
6964
8005
  const p = priority ?? inferPriority(cacheKey);
6965
8006
  this._bumpKeyMutation(k);
6966
- this._pendingDiskDeletes.delete(k);
8007
+ this._invalidateDiskKey(k);
6967
8008
  this.l1.set(k, value, ttlMs, p);
6968
8009
  this.counters.sets++;
6969
8010
  return true;
@@ -6990,7 +8031,7 @@ var CacheService = class _CacheService {
6990
8031
  const token = crypto2.randomUUID();
6991
8032
  const deadline = Date.now() + acquireTimeout;
6992
8033
  let acquired = false;
6993
- if (!this._redisDisabled) {
8034
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6994
8035
  let client = null;
6995
8036
  try {
6996
8037
  client = await this.getRedis();
@@ -7085,7 +8126,9 @@ var CacheService = class _CacheService {
7085
8126
  const gDiskFiles = meter.createObservableGauge("tricache.disk.files", { description: "Current L1.5 disk file count" });
7086
8127
  const gDiskBytes = meter.createObservableGauge("tricache.disk.bytes", { description: "Current L1.5 disk size in bytes" });
7087
8128
  const gBloomFpr = meter.createObservableGauge("tricache.bloom.fpr", { description: "Bloom filter false-positive rate" });
7088
- meter.addBatchObservableCallback((observableResult) => {
8129
+ const observables = [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr];
8130
+ const callback = (observableResult) => {
8131
+ if (this._destroyed) return;
7089
8132
  const stats = this.stats();
7090
8133
  const l1 = stats.l1;
7091
8134
  const disk = stats.disk;
@@ -7098,7 +8141,9 @@ var CacheService = class _CacheService {
7098
8141
  observableResult.observe(gDiskFiles, disk.files, attrs);
7099
8142
  observableResult.observe(gDiskBytes, disk.sizeKB * 1024, attrs);
7100
8143
  observableResult.observe(gBloomFpr, fpr, attrs);
7101
- }, [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr]);
8144
+ };
8145
+ meter.addBatchObservableCallback(callback, observables);
8146
+ this._otelCleanup = () => meter.removeBatchObservableCallback?.(callback, observables);
7102
8147
  } catch (err) {
7103
8148
  this.logger.warn("Failed to initialize OpenTelemetry metrics meter", { error: err.message });
7104
8149
  }
@@ -7368,8 +8413,25 @@ var CacheService = class _CacheService {
7368
8413
  /** Close Redis connections and stop all background timers. */
7369
8414
  async destroy() {
7370
8415
  this._destroyed = true;
8416
+ this._fenceInvalidation();
8417
+ this._backplaneAvailable = false;
8418
+ this.l1.clear();
8419
+ try {
8420
+ this._otelCleanup?.();
8421
+ } catch {
8422
+ }
8423
+ this._otelCleanup = null;
8424
+ this.tagVersions.clear();
8425
+ for (const dispose of this._backplaneDisposers.splice(0)) dispose();
7371
8426
  this._pendingDiskDeletes.clear();
7372
8427
  this._keyMutationEpochs.clear();
8428
+ this.inflight.clear();
8429
+ this.revalidating.clear();
8430
+ this._l1Counters.clear();
8431
+ this.tagIndex.clear();
8432
+ this.keyTags.clear();
8433
+ this.dependencyIndex.clear();
8434
+ this.keyDependencies.clear();
7373
8435
  const g = globalThis;
7374
8436
  const key = _CacheService.globalKey(this.opts);
7375
8437
  if (g[key] === this) {
@@ -7390,6 +8452,12 @@ var CacheService = class _CacheService {
7390
8452
  this._workerPool = null;
7391
8453
  }
7392
8454
  if (this.subClient) {
8455
+ if (this.opts.redisSubClient) {
8456
+ try {
8457
+ await this.subClient.unsubscribe?.(this.backplaneChannel);
8458
+ } catch {
8459
+ }
8460
+ }
7393
8461
  if (!this.opts.redisSubClient) {
7394
8462
  try {
7395
8463
  this.subClient.disconnect();
@@ -7399,7 +8467,7 @@ var CacheService = class _CacheService {
7399
8467
  this.subClient = null;
7400
8468
  }
7401
8469
  if (this.streamClient) {
7402
- try {
8470
+ if (!this.opts.redisSubClient) try {
7403
8471
  this.streamClient.disconnect();
7404
8472
  } catch {
7405
8473
  }
@@ -7438,6 +8506,10 @@ var CacheService = class _CacheService {
7438
8506
  export {
7439
8507
  CacheCodec,
7440
8508
  defaultCodec,
8509
+ createHttpMeshRelay,
8510
+ createCustomCrossRegionRelay,
8511
+ createMemoryCrossRegionRelay,
8512
+ createCrossRegionWebhookHandler,
7441
8513
  TinyLfuSketch,
7442
8514
  WTinyLfuCache,
7443
8515
  WTinyLfuPolicy,