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
@@ -74,6 +74,21 @@ var init_codec = __esm({
74
74
  }
75
75
  });
76
76
 
77
+ // src/cross-region.ts
78
+ function isCrossRegionInvalidationEvent(value) {
79
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
80
+ const event = value;
81
+ const text = (key, max) => typeof event[key] === "string" && event[key].length > 0 && event[key].length <= max;
82
+ 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);
83
+ }
84
+ var import_node_crypto;
85
+ var init_cross_region = __esm({
86
+ "src/cross-region.ts"() {
87
+ "use strict";
88
+ import_node_crypto = require("crypto");
89
+ }
90
+ });
91
+
77
92
  // src/worker-pool.ts
78
93
  function getTransferableArrayBuffer(buf) {
79
94
  if (buf.buffer instanceof ArrayBuffer) {
@@ -115,7 +130,8 @@ var init_worker_pool = __esm({
115
130
  _workerFile = jsPath;
116
131
  }
117
132
  } catch {
118
- _workerFile = (0, import_path.join)(__dirname, "serialize-worker.js");
133
+ const sibling = (0, import_path.join)(__dirname, "serialize-worker.js");
134
+ _workerFile = (0, import_fs.existsSync)(sibling) ? sibling : (0, import_path.join)((0, import_path.dirname)(__dirname), "serialize-worker.js");
119
135
  }
120
136
  WorkerPool = class {
121
137
  workers = [];
@@ -135,6 +151,7 @@ var init_worker_pool = __esm({
135
151
  }
136
152
  _spawnWorkers(opts) {
137
153
  const size = Math.max(1, opts.size ?? Math.min(4, availableCpus()));
154
+ if (!Number.isInteger(size) || size > 32 || !(0, import_fs.existsSync)(_workerFile)) throw new Error("Worker pool unavailable or invalid worker count");
138
155
  const workerData = {
139
156
  keyBase64: opts.keyBase64,
140
157
  mode: opts.mode,
@@ -148,7 +165,8 @@ var init_worker_pool = __esm({
148
165
  const createWorker = (index) => {
149
166
  const worker = new import_worker_threads.Worker(_workerFile, {
150
167
  workerData,
151
- execArgv: _workerExecArgv.length > 0 ? _workerExecArgv : void 0
168
+ execArgv: _workerExecArgv
169
+ // Do not inherit --input-type/eval or application loader flags.
152
170
  });
153
171
  const pending = pendingList[index] ?? /* @__PURE__ */ new Map();
154
172
  if (!pendingList[index]) pendingList[index] = pending;
@@ -178,7 +196,7 @@ var init_worker_pool = __esm({
178
196
  }
179
197
  pending.clear();
180
198
  worker.unref();
181
- if (this._available && exitCode !== 0 && workers[index] === worker) {
199
+ if (this._available && this.workers === workers && workers[index] === worker) {
182
200
  try {
183
201
  workers[index] = createWorker(index);
184
202
  } catch {
@@ -188,9 +206,12 @@ var init_worker_pool = __esm({
188
206
  worker.unref();
189
207
  return worker;
190
208
  };
191
- for (let i = 0; i < size; i++) {
192
- const worker = createWorker(i);
193
- workers.push(worker);
209
+ try {
210
+ for (let i = 0; i < size; i++) workers.push(createWorker(i));
211
+ } catch (error) {
212
+ for (const worker of workers) void worker.terminate().catch(() => {
213
+ });
214
+ throw error;
194
215
  }
195
216
  return { workers, pending: pendingList };
196
217
  }
@@ -217,7 +238,7 @@ var init_worker_pool = __esm({
217
238
  entry.reject(new Error("WorkerPool replaced during key rotation"));
218
239
  }
219
240
  oldPending[i]?.clear();
220
- oldWorkers[i]?.terminate().catch(() => {
241
+ await oldWorkers[i]?.terminate().catch(() => {
221
242
  });
222
243
  }
223
244
  }
@@ -259,7 +280,13 @@ var init_worker_pool = __esm({
259
280
  return new Promise((resolve, reject) => {
260
281
  pending.set(id, { resolve, reject });
261
282
  worker.ref();
262
- worker.postMessage({ id, type, payload: dataToSend }, transferList);
283
+ try {
284
+ worker.postMessage({ id, type, payload: dataToSend }, transferList);
285
+ } catch (error) {
286
+ pending.delete(id);
287
+ if (pending.size === 0) worker.unref();
288
+ reject(error);
289
+ }
263
290
  });
264
291
  }
265
292
  /** Terminate all worker threads. In-flight promises are rejected. */
@@ -781,8 +808,9 @@ var init_wtiny_lfu = __esm({
781
808
  "src/wtiny-lfu.ts"() {
782
809
  "use strict";
783
810
  WTinyLfuPolicy = class {
784
- constructor(capacity, sketch, windowPercent = 0.01, protectedPercent = 0.8) {
811
+ constructor(capacity, sketch, windowPercent = 0.01, protectedPercent = 0.8, canEvict) {
785
812
  this.sketch = sketch;
813
+ this.canEvict = canEvict;
786
814
  this.maxTotal = Math.max(2, capacity);
787
815
  this.maxWindow = Math.max(1, Math.floor(this.maxTotal * windowPercent));
788
816
  const mainCapacity = Math.max(1, this.maxTotal - this.maxWindow);
@@ -790,6 +818,7 @@ var init_wtiny_lfu = __esm({
790
818
  this.maxProbation = Math.max(1, mainCapacity - this.maxProtected);
791
819
  }
792
820
  sketch;
821
+ canEvict;
793
822
  maxTotal;
794
823
  maxWindow;
795
824
  maxProtected;
@@ -869,15 +898,33 @@ var init_wtiny_lfu = __esm({
869
898
  }
870
899
  let victimKey;
871
900
  let victimIsProbation = true;
872
- if (this.probation.size > 0) {
873
- victimKey = this.probation.values().next().value;
874
- } else {
875
- victimKey = this.protected_.values().next().value;
901
+ for (const candidate of this.probation) {
902
+ if (!this.canEvict || this.canEvict(candidate)) {
903
+ victimKey = candidate;
904
+ break;
905
+ }
906
+ }
907
+ if (victimKey === void 0) {
908
+ for (const candidate of this.protected_) {
909
+ if (!this.canEvict || this.canEvict(candidate)) {
910
+ victimKey = candidate;
911
+ break;
912
+ }
913
+ }
876
914
  victimIsProbation = false;
877
915
  }
916
+ if (victimKey === void 0) {
917
+ if (this.canEvict && !this.canEvict(candKey)) {
918
+ this.window.delete(key);
919
+ this.window.add(candKey);
920
+ return { admit: false, candidateKey: key };
921
+ }
922
+ this.rejectionCount++;
923
+ return { admit: false, candidateKey: candKey };
924
+ }
878
925
  const candFreq = this.sketch.estimate(candKey);
879
926
  const victimFreq = this.sketch.estimate(victimKey);
880
- if (candFreq > victimFreq) {
927
+ if (this.canEvict && !this.canEvict(candKey) || candFreq > victimFreq) {
881
928
  if (victimIsProbation) {
882
929
  this.probation.delete(victimKey);
883
930
  } else {
@@ -955,7 +1002,12 @@ var init_base64 = __esm({
955
1002
  });
956
1003
 
957
1004
  // src/wasm/bloom-filter-wasm.ts
958
- var BLOOM_WASM_BASE64, KEY_STAGING_OFFSET, MAX_KEY_BYTES, BLOOM_WASM_MODULE, WasmBloomFilter;
1005
+ function getBloomWasmModule() {
1006
+ return bloomWasmModule ??= new WebAssembly.Module(
1007
+ base64ToUint8Array(BLOOM_WASM_BASE64)
1008
+ );
1009
+ }
1010
+ var BLOOM_WASM_BASE64, KEY_STAGING_OFFSET, MAX_KEY_BYTES, bloomWasmModule, WasmBloomFilter;
959
1011
  var init_bloom_filter_wasm = __esm({
960
1012
  "src/wasm/bloom-filter-wasm.ts"() {
961
1013
  "use strict";
@@ -963,9 +1015,6 @@ var init_bloom_filter_wasm = __esm({
963
1015
  BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
964
1016
  KEY_STAGING_OFFSET = 2e4;
965
1017
  MAX_KEY_BYTES = 512;
966
- BLOOM_WASM_MODULE = new WebAssembly.Module(
967
- base64ToUint8Array(BLOOM_WASM_BASE64)
968
- );
969
1018
  WasmBloomFilter = class {
970
1019
  exports;
971
1020
  mem;
@@ -977,7 +1026,7 @@ var init_bloom_filter_wasm = __esm({
977
1026
  /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
978
1027
  _insertionCount = 0;
979
1028
  constructor() {
980
- const instance = new WebAssembly.Instance(BLOOM_WASM_MODULE, {});
1029
+ const instance = new WebAssembly.Instance(getBloomWasmModule(), {});
981
1030
  this.exports = instance.exports;
982
1031
  this.mem = new Uint8Array(this.exports.memory.buffer);
983
1032
  this.stagingTarget = new Uint8Array(this.exports.memory.buffer, KEY_STAGING_OFFSET, MAX_KEY_BYTES);
@@ -1030,8 +1079,9 @@ var init_bloom_filter_wasm = __esm({
1030
1079
  // src/smart-memory-cache.ts
1031
1080
  function createBloomFilter(logger, maxEntries) {
1032
1081
  const LN2_SQ = Math.LN2 * Math.LN2;
1033
- const optimalBits = Math.ceil(-maxEntries * Math.log(0.01) / LN2_SQ);
1034
- const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / maxEntries)));
1082
+ const capacity = Math.max(1, maxEntries);
1083
+ const optimalBits = Math.ceil(-capacity * Math.log(0.01) / LN2_SQ);
1084
+ const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / capacity)));
1035
1085
  try {
1036
1086
  const wasm = new WasmBloomFilter();
1037
1087
  if (wasm.maxCapacity >= maxEntries) {
@@ -1243,7 +1293,10 @@ var init_smart_memory_cache = __esm({
1243
1293
  this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
1244
1294
  this.categoryPrefixes = Object.keys(opts.categories).filter((k) => k !== "default");
1245
1295
  if (opts.admissionPolicy === "wtinylfu") {
1246
- this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch);
1296
+ this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch, 0.01, 0.8, (key) => {
1297
+ const entry = this.cache.get(key);
1298
+ return !entry || entry.priority !== 4 || entry.expiresAt <= Date.now();
1299
+ });
1247
1300
  }
1248
1301
  if (existing) {
1249
1302
  for (const [k, v] of existing) this.cache.set(k, v);
@@ -1322,6 +1375,7 @@ var init_smart_memory_cache = __esm({
1322
1375
  const MAX_EVICT_PASSES = 64;
1323
1376
  let passes = 0;
1324
1377
  do {
1378
+ const before = this.cache.size;
1325
1379
  this.smartEvict(category, catOvf);
1326
1380
  const lim2 = this.getCategoryLimit(category);
1327
1381
  const catCnt2 = this.categoryCount.get(category) ?? 0;
@@ -1329,6 +1383,7 @@ var init_smart_memory_cache = __esm({
1329
1383
  catOvf = catCnt2 >= lim2.maxEntries || catSz2 + neededSize > lim2.maxSizeBytes;
1330
1384
  glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
1331
1385
  passes++;
1386
+ if (this.cache.size === before) break;
1332
1387
  } while ((catOvf || glbOvf) && passes < MAX_EVICT_PASSES);
1333
1388
  }
1334
1389
  score(entry, catBonus, now, key) {
@@ -1459,20 +1514,26 @@ var init_smart_memory_cache = __esm({
1459
1514
  delta: entry.delta,
1460
1515
  fetchedAt: now,
1461
1516
  tagVersions: entry.tagVersions,
1462
- setAt: entry.setAt
1517
+ setAt: entry.setAt,
1518
+ tags: entry.tags,
1519
+ dependsOn: entry.dependsOn
1463
1520
  };
1464
1521
  return hit;
1465
1522
  }
1466
- set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
1523
+ set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions, setAt, tags, dependsOn) {
1467
1524
  const packed = this.codec.encode(data);
1525
+ return this.storePacked(key, packed, data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn);
1526
+ }
1527
+ storePacked(key, packed, data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn) {
1468
1528
  const size = packed.byteLength;
1469
1529
  this.compressions++;
1470
1530
  this.sketch.increment(key);
1471
1531
  const cat = this.getCategory(key);
1472
1532
  const lim = this.getCategoryLimit(cat);
1473
- if (size > lim.maxSizeBytes * 0.5) {
1533
+ if (!Number.isFinite(ttlMs) || ttlMs <= 0 || this.opts.maxEntries <= 0 || lim.maxEntries <= 0 || size > this.opts.maxBytes || size > lim.maxSizeBytes * 0.5) {
1534
+ this.delete(key);
1474
1535
  this.opts.logger.debug("SmartMemoryCache: entry too large, skipping", { key, sizeBytes: size });
1475
- return;
1536
+ return false;
1476
1537
  }
1477
1538
  const existingEntry = this.cache.get(key);
1478
1539
  if (existingEntry) {
@@ -1500,11 +1561,13 @@ var init_smart_memory_cache = __esm({
1500
1561
  priority,
1501
1562
  ttlMs,
1502
1563
  delta,
1503
- setAt: now2,
1504
- tagVersions
1564
+ setAt: setAt ?? now2,
1565
+ tagVersions,
1566
+ tags,
1567
+ dependsOn
1505
1568
  });
1506
1569
  }
1507
- return;
1570
+ return false;
1508
1571
  } else if (decision.candidateKey) {
1509
1572
  const candEntry = this.cache.get(decision.candidateKey);
1510
1573
  if (candEntry && this.opts.diskSpill) {
@@ -1520,15 +1583,19 @@ var init_smart_memory_cache = __esm({
1520
1583
  this._delete(decision.evictKey, "capacity");
1521
1584
  }
1522
1585
  const catSz = this.categorySize.get(cat) ?? 0;
1523
- if (catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
1586
+ if ((this.categoryCount.get(cat) ?? 0) >= lim.maxEntries || this.cache.size >= this.opts.maxEntries || catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
1524
1587
  this.ensureCapacity(cat, size);
1525
1588
  }
1526
1589
  } else {
1527
1590
  this.ensureCapacity(cat, size);
1528
1591
  }
1592
+ 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) {
1593
+ this.wtinyPolicy?.onDelete(key);
1594
+ return false;
1595
+ }
1529
1596
  const now = Date.now();
1530
1597
  const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
1531
- 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 });
1598
+ 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 });
1532
1599
  if (!existingEntry) this.bloom.add(key);
1533
1600
  this.maybeRebuildBloom();
1534
1601
  this.totalSize += size;
@@ -1540,6 +1607,7 @@ var init_smart_memory_cache = __esm({
1540
1607
  this.categoryKeys.set(cat, ks);
1541
1608
  }
1542
1609
  ks.add(key);
1610
+ return true;
1543
1611
  }
1544
1612
  delete(key) {
1545
1613
  const deleted = this._delete(key, "manual");
@@ -1741,25 +1809,48 @@ var init_smart_memory_cache = __esm({
1741
1809
  if (entry.expiresAt <= now) continue;
1742
1810
  if (entry.priority === 4) continue;
1743
1811
  if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
1744
- out.push({ key, entry: { ...entry } });
1812
+ const { value: _value, ...stored } = entry;
1813
+ out.push({ key, entry: { ...stored } });
1745
1814
  }
1746
1815
  return out;
1747
1816
  }
1748
1817
  importEntries(entries, forbiddenPrefixes) {
1749
1818
  const now = Date.now();
1750
1819
  let loaded = 0;
1751
- for (const { key, entry } of entries) {
1752
- if (entry.expiresAt <= now) continue;
1820
+ for (const item of entries) {
1821
+ if (!item || typeof item.key !== "string" || !item.entry) continue;
1822
+ const { key, entry } = item;
1823
+ if (!Number.isFinite(entry.expiresAt) || entry.expiresAt <= now) continue;
1753
1824
  if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
1754
1825
  if (this.cache.has(key)) continue;
1755
- const rawData = entry.data;
1756
- const data = !entry.isCompressed ? this.codec.encode(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
1757
- const value = entry.size <= LARGE_VALUE_BYTES ? this.codec.decode(data) : void 0;
1758
- this.cache.set(key, { ...entry, data, value, isCompressed: true });
1759
- this.bloom.add(key);
1760
- loaded++;
1761
- }
1762
- this.recalculateStats();
1826
+ try {
1827
+ const rawData = entry.data;
1828
+ const data = !entry.isCompressed ? this.codec.encode(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : null;
1829
+ if (!data) continue;
1830
+ const value = data.length <= LARGE_VALUE_BYTES ? this.codec.decode(data) : void 0;
1831
+ if (this.storePacked(
1832
+ key,
1833
+ data,
1834
+ value,
1835
+ entry.expiresAt - now,
1836
+ entry.priority,
1837
+ entry.staleAt,
1838
+ entry.delta,
1839
+ entry.tagVersions,
1840
+ entry.setAt,
1841
+ entry.tags,
1842
+ entry.dependsOn
1843
+ )) {
1844
+ const restored = this.cache.get(key);
1845
+ restored.expiresAt = entry.expiresAt;
1846
+ restored.ttlMs = entry.ttlMs ?? entry.expiresAt - now;
1847
+ restored.hits = Number.isFinite(entry.hits) ? Math.max(1, entry.hits) : 1;
1848
+ restored.lastAccess = Number.isFinite(entry.lastAccess) ? entry.lastAccess : now;
1849
+ loaded++;
1850
+ }
1851
+ } catch {
1852
+ }
1853
+ }
1763
1854
  return loaded;
1764
1855
  }
1765
1856
  // ── Iterators ─────────────────────────────────────────────────────────────
@@ -2169,6 +2260,9 @@ var init_disk_tier = __esm({
2169
2260
  this.writeTimeoutMs = writeTimeoutMs;
2170
2261
  this.failureThreshold = failureThreshold;
2171
2262
  this.cooldownMs = cooldownMs;
2263
+ 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) {
2264
+ throw new Error("Disk queue limits and timeout must be finite positive values (pending/cooldown may be zero)");
2265
+ }
2172
2266
  }
2173
2267
  maxConcurrent;
2174
2268
  maxPending;
@@ -2181,6 +2275,17 @@ var init_disk_tier = __esm({
2181
2275
  consecutiveFailures = 0;
2182
2276
  circuitState = "closed";
2183
2277
  lastStateChangeMonotonic = performance.now();
2278
+ get isSaturated() {
2279
+ return this.active >= this.maxConcurrent && this.queue.length >= this.maxPending;
2280
+ }
2281
+ releaseSlot() {
2282
+ if (this.circuitState === "open") {
2283
+ for (const next2 of this.queue.splice(0)) next2(false);
2284
+ }
2285
+ const next = this.queue.shift();
2286
+ if (next) next(true);
2287
+ else this.active--;
2288
+ }
2184
2289
  async schedule(task) {
2185
2290
  const now = performance.now();
2186
2291
  if (this.circuitState === "open") {
@@ -2196,18 +2301,25 @@ var init_disk_tier = __esm({
2196
2301
  this.spillsDropped++;
2197
2302
  return null;
2198
2303
  }
2199
- if (this.queue.length >= this.maxPending) {
2304
+ if (this.isSaturated) {
2200
2305
  this.spillsDropped++;
2201
2306
  return null;
2202
2307
  }
2203
2308
  if (this.active >= this.maxConcurrent) {
2204
- await new Promise((resolve) => this.queue.push(resolve));
2309
+ const admitted = await new Promise((resolve) => this.queue.push(resolve));
2310
+ if (!admitted) {
2311
+ this.spillsDropped++;
2312
+ return null;
2313
+ }
2314
+ } else {
2315
+ this.active++;
2205
2316
  }
2206
- this.active++;
2207
2317
  let timeoutId = null;
2318
+ const work = Promise.resolve().then(task);
2319
+ void work.then(() => this.releaseSlot(), () => this.releaseSlot());
2208
2320
  try {
2209
2321
  const result = await Promise.race([
2210
- task(),
2322
+ work,
2211
2323
  new Promise((_, reject) => {
2212
2324
  timeoutId = setTimeout(
2213
2325
  () => reject(new Error(`Disk write exceeded timeout of ${this.writeTimeoutMs}ms`)),
@@ -2226,14 +2338,12 @@ var init_disk_tier = __esm({
2226
2338
  if (this.consecutiveFailures >= this.failureThreshold || this.circuitState === "half-open") {
2227
2339
  this.circuitState = "open";
2228
2340
  this.lastStateChangeMonotonic = performance.now();
2341
+ for (const next of this.queue.splice(0)) next(false);
2229
2342
  }
2230
2343
  this.spillsDropped++;
2231
2344
  return null;
2232
2345
  } finally {
2233
2346
  if (timeoutId) clearTimeout(timeoutId);
2234
- this.active--;
2235
- const next = this.queue.shift();
2236
- if (next) next();
2237
2347
  }
2238
2348
  }
2239
2349
  getStats() {
@@ -2273,6 +2383,13 @@ var init_disk_tier = __esm({
2273
2383
  usageCounted = false;
2274
2384
  fileCount = 0;
2275
2385
  // maintained in-memory; avoids walkCacheFiles() in stats
2386
+ reservedBytes = 0;
2387
+ reservedFiles = 0;
2388
+ saveSequence = 0;
2389
+ epoch = 0;
2390
+ pendingSaves = /* @__PURE__ */ new Map();
2391
+ closed = false;
2392
+ invalidatedKeys = /* @__PURE__ */ new Set();
2276
2393
  /** Next bucket index (0–255) for the staggered janitor wheel. */
2277
2394
  _nextJanitorBucket = 0;
2278
2395
  // ── High-watermark pruning & host volume health state ─────────────────────
@@ -2313,6 +2430,7 @@ var init_disk_tier = __esm({
2313
2430
  }
2314
2431
  // ── Helpers ───────────────────────────────────────────────────────────────
2315
2432
  ensureDir() {
2433
+ if (this.closed) return;
2316
2434
  if (this.dirReady) return;
2317
2435
  try {
2318
2436
  import_fs2.default.mkdirSync(this.opts.dir, { recursive: true, mode: 448 });
@@ -2434,8 +2552,24 @@ var init_disk_tier = __esm({
2434
2552
  *
2435
2553
  * 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
2436
2554
  */
2437
- hashToWritePath(hash, expiresAt) {
2438
- return import_path2.default.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiresAt.toString(16).padStart(12, "0")}`);
2555
+ hashToWritePath(hash, expiresAt, setAt) {
2556
+ const expiry = Math.floor(expiresAt).toString(16).padStart(12, "0");
2557
+ if (setAt === void 0) return import_path2.default.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}`);
2558
+ const written = Math.floor(setAt).toString(16).padStart(12, "0");
2559
+ const sequence = (++this.saveSequence).toString(16).padStart(12, "0");
2560
+ return import_path2.default.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}_${written}_${sequence}_${import_crypto2.default.randomBytes(6).toString("hex")}`);
2561
+ }
2562
+ findFilePaths(hash) {
2563
+ const bucket = import_path2.default.join(this.opts.dir, hash.slice(0, 2));
2564
+ try {
2565
+ return import_fs2.default.readdirSync(bucket).filter((file) => !file.endsWith(".tmp") && (file === hash || file.startsWith(hash + "_"))).map((file) => import_path2.default.join(bucket, file));
2566
+ } catch {
2567
+ return [];
2568
+ }
2569
+ }
2570
+ fileWrittenAt(file) {
2571
+ const parts = import_path2.default.basename(file).split("_");
2572
+ return parts.length >= 4 ? parseInt(parts[2], 16) : import_fs2.default.statSync(file).mtimeMs;
2439
2573
  }
2440
2574
  /**
2441
2575
  * Find the on-disk file for a key hash, handling all filename generations:
@@ -2444,19 +2578,31 @@ var init_disk_tier = __esm({
2444
2578
  * Returns null when the bucket dir does not exist or the key is absent.
2445
2579
  */
2446
2580
  findFilePath(hash) {
2447
- const bucketPath = import_path2.default.join(this.opts.dir, hash.slice(0, 2));
2448
- let files;
2581
+ let match = null;
2582
+ let newest = -Infinity;
2583
+ let sequence = -1;
2584
+ for (const file of this.findFilePaths(hash)) {
2585
+ try {
2586
+ const written = this.fileWrittenAt(file);
2587
+ const order = parseInt(import_path2.default.basename(file).split("_")[3] ?? "0", 16);
2588
+ if (written > newest || written === newest && order > sequence) {
2589
+ match = file;
2590
+ newest = written;
2591
+ sequence = order;
2592
+ }
2593
+ } catch {
2594
+ }
2595
+ }
2596
+ return match;
2597
+ }
2598
+ removeFile(filePath) {
2449
2599
  try {
2450
- files = import_fs2.default.readdirSync(bucketPath);
2600
+ const size = import_fs2.default.statSync(filePath).size;
2601
+ import_fs2.default.unlinkSync(filePath);
2602
+ this.diskUsageBytes = Math.max(0, this.diskUsageBytes - size);
2603
+ this.fileCount = Math.max(0, this.fileCount - 1);
2451
2604
  } catch {
2452
- return null;
2453
- }
2454
- let match;
2455
- for (const f of files) {
2456
- if ((f === hash || f.startsWith(hash + "_")) && (!match || f > match)) match = f;
2457
2605
  }
2458
- if (!match) return null;
2459
- return import_path2.default.join(bucketPath, match);
2460
2606
  }
2461
2607
  /**
2462
2608
  * Recursively list all cache file paths across the 2-level sharded subdirs.
@@ -2531,6 +2677,7 @@ var init_disk_tier = __esm({
2531
2677
  * so the Node.js event loop is never stalled waiting for disk I/O.
2532
2678
  */
2533
2679
  async save(key, entry) {
2680
+ if (this.closed || this.diskQueue.isSaturated) return;
2534
2681
  if (this.isForbidden(key)) return;
2535
2682
  if (entry.expiresAt <= Date.now()) return;
2536
2683
  this.ensureDir();
@@ -2539,7 +2686,7 @@ var init_disk_tier = __esm({
2539
2686
  if (++this._writeCounter % 2e3 === 0) {
2540
2687
  this.checkHostVolumeHealth();
2541
2688
  }
2542
- if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes >= this.opts.maxBytes) {
2689
+ if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes + this.reservedBytes >= this.opts.maxBytes) {
2543
2690
  this._spillsShedTotal++;
2544
2691
  return;
2545
2692
  }
@@ -2548,11 +2695,12 @@ var init_disk_tier = __esm({
2548
2695
  }
2549
2696
  let final;
2550
2697
  try {
2698
+ const { value: _value, ...storedEntry } = entry;
2551
2699
  const payload = {
2552
2700
  version: DISK_TIER_VERSION,
2553
2701
  key,
2554
2702
  entry: {
2555
- ...entry,
2703
+ ...storedEntry,
2556
2704
  data: entry.data instanceof Uint8Array ? Buffer.from(entry.data) : entry.data
2557
2705
  },
2558
2706
  writtenAt: Date.now()
@@ -2565,24 +2713,46 @@ var init_disk_tier = __esm({
2565
2713
  }
2566
2714
  const header = Buffer.allocUnsafe(V2_HEADER_LEN);
2567
2715
  DISK_MAGIC_V2.copy(header, 0);
2568
- header.writeBigUInt64LE(BigInt(entry.expiresAt), 8);
2716
+ header.writeBigUInt64LE(BigInt(Math.floor(entry.expiresAt)), 8);
2569
2717
  final = Buffer.concat([header, this.encryptV2(toEncrypt)]);
2718
+ if (final.length > this.opts.entryMaxBytes || this.diskUsageBytes + this.reservedBytes + final.length > this.opts.maxBytes) return;
2570
2719
  } catch (err) {
2571
2720
  this.opts.logger.debug("DiskTier: pack/encrypt failed", { key: key.slice(0, 50), error: err.message });
2572
2721
  return;
2573
2722
  }
2574
2723
  const hash = this.keyToHash(key);
2575
- const filePath = this.hashToWritePath(hash, entry.expiresAt);
2724
+ const setAt = entry.setAt ?? Date.now();
2725
+ if ((this.pendingSaves.get(key)?.setAt ?? 0) > setAt) return;
2726
+ const filePath = this.hashToWritePath(hash, entry.expiresAt, setAt);
2576
2727
  const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${import_crypto2.default.randomBytes(6).toString("hex")}.tmp`;
2577
- this.diskUsageBytes += final.length;
2578
- this.fileCount++;
2728
+ const token = Symbol(key);
2729
+ const epoch = this.epoch;
2730
+ this.pendingSaves.set(key, { token, setAt });
2731
+ const current = () => !this.closed && this.epoch === epoch && this.pendingSaves.get(key)?.token === token;
2732
+ let started = false;
2733
+ let released = false;
2734
+ let accounted = false;
2735
+ const releaseReservation = () => {
2736
+ if (released) return;
2737
+ released = true;
2738
+ this.reservedBytes = Math.max(0, this.reservedBytes - final.length);
2739
+ this.reservedFiles = Math.max(0, this.reservedFiles - 1);
2740
+ if (this.pendingSaves.get(key)?.token === token) this.pendingSaves.delete(key);
2741
+ };
2742
+ this.reservedBytes += final.length;
2743
+ this.reservedFiles++;
2579
2744
  if (this.diskUsageBytes >= this.opts.maxBytes * 0.8 && !this._isPruning) {
2580
2745
  void this.triggerChunkedPrune();
2581
2746
  }
2582
2747
  const result = await this.diskQueue.schedule(async () => {
2748
+ started = true;
2583
2749
  try {
2750
+ if (!current()) return false;
2751
+ const previous = this.findFilePath(hash);
2752
+ if (previous && this.fileWrittenAt(previous) > setAt) return false;
2584
2753
  await import_fs2.default.promises.mkdir(import_path2.default.dirname(filePath), { recursive: true });
2585
2754
  await import_fs2.default.promises.writeFile(tmpPath, final, { mode: 384 });
2755
+ if (!current()) return false;
2586
2756
  try {
2587
2757
  await import_fs2.default.promises.rename(tmpPath, filePath);
2588
2758
  } catch (renameErr) {
@@ -2594,6 +2764,20 @@ var init_disk_tier = __esm({
2594
2764
  throw renameErr;
2595
2765
  }
2596
2766
  }
2767
+ if (!current()) {
2768
+ try {
2769
+ await import_fs2.default.promises.unlink(filePath);
2770
+ } catch {
2771
+ }
2772
+ return false;
2773
+ }
2774
+ for (const previousPath of this.findFilePaths(hash)) {
2775
+ if (previousPath !== filePath) this.removeFile(previousPath);
2776
+ }
2777
+ this.diskUsageBytes += final.length;
2778
+ this.fileCount++;
2779
+ accounted = true;
2780
+ this.invalidatedKeys.delete(key);
2597
2781
  if (this._db) {
2598
2782
  const priority = typeof entry.priority === "number" ? entry.priority : 2;
2599
2783
  const lastAccess = typeof entry.lastAccess === "number" ? entry.lastAccess : Date.now();
@@ -2606,23 +2790,25 @@ var init_disk_tier = __esm({
2606
2790
  await import_fs2.default.promises.unlink(tmpPath);
2607
2791
  } catch {
2608
2792
  }
2609
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
2610
- this.fileCount = Math.max(0, this.fileCount - 1);
2611
- if (this._db) try {
2612
- this._stmtDelete.run(hash);
2613
- } catch {
2614
- }
2793
+ if (accounted) this.removeFile(filePath);
2615
2794
  this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
2616
2795
  throw err;
2796
+ } finally {
2797
+ try {
2798
+ await import_fs2.default.promises.unlink(tmpPath);
2799
+ } catch {
2800
+ }
2801
+ releaseReservation();
2802
+ if (this.invalidatedKeys.has(key) && !this.pendingSaves.has(key)) this.delete(key, true);
2617
2803
  }
2618
2804
  });
2619
- if (result === null) {
2620
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
2621
- this.fileCount = Math.max(0, this.fileCount - 1);
2805
+ if (result === null && !started) {
2806
+ releaseReservation();
2622
2807
  }
2623
2808
  }
2624
2809
  /** Load a key from disk, or return null on miss/expiry/corruption. */
2625
2810
  load(key) {
2811
+ if (this.invalidatedKeys.has(key) || this.closed) return null;
2626
2812
  if (this.isForbidden(key)) return null;
2627
2813
  this.ensureDir();
2628
2814
  if (!this.dirReady) return null;
@@ -2650,8 +2836,8 @@ var init_disk_tier = __esm({
2650
2836
  try {
2651
2837
  if (!this._db) {
2652
2838
  const filename = import_path2.default.basename(filePath);
2653
- if (filename.length === 77 && filename[64] === "_") {
2654
- const expiresAt = parseInt(filename.slice(65), 16);
2839
+ if (filename.length >= 77 && filename[64] === "_") {
2840
+ const expiresAt = parseInt(filename.slice(65, 77), 16);
2655
2841
  if (expiresAt <= Date.now()) {
2656
2842
  try {
2657
2843
  const sz = import_fs2.default.statSync(filePath).size;
@@ -2672,12 +2858,7 @@ var init_disk_tier = __esm({
2672
2858
  return null;
2673
2859
  }
2674
2860
  const raw = import_fs2.default.readFileSync(filePath);
2675
- try {
2676
- import_fs2.default.unlinkSync(filePath);
2677
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
2678
- this.fileCount = Math.max(0, this.fileCount - 1);
2679
- } catch {
2680
- }
2861
+ for (const storedPath of this.findFilePaths(hash)) this.removeFile(storedPath);
2681
2862
  if (this._db) this._stmtDelete.run(hash);
2682
2863
  let decrypted;
2683
2864
  if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
@@ -2712,25 +2893,24 @@ var init_disk_tier = __esm({
2712
2893
  return null;
2713
2894
  }
2714
2895
  }
2715
- /** Explicitly delete a key from disk (cache invalidation). */
2716
- delete(key) {
2896
+ /** Synchronously fence queued/running saves while leaving filesystem cleanup deferred. */
2897
+ invalidate(key) {
2898
+ this.pendingSaves.delete(key);
2899
+ this.invalidatedKeys.add(key);
2900
+ }
2901
+ /** Delete all versions; deferred cleanup must not cancel a newer save. */
2902
+ delete(key, invalidatedOnly = false) {
2903
+ if (invalidatedOnly && (!this.invalidatedKeys.has(key) || this.pendingSaves.has(key))) return;
2904
+ if (!invalidatedOnly) this.pendingSaves.delete(key);
2717
2905
  const hash = this.keyToHash(key);
2718
- let filePath;
2906
+ const files = new Set(this.findFilePaths(hash));
2719
2907
  if (this._db) {
2720
2908
  const row = this._stmtSelect.get(hash);
2721
- filePath = row?.file_path ?? null;
2909
+ if (row?.file_path) files.add(row.file_path);
2722
2910
  this._stmtDelete.run(hash);
2723
- } else {
2724
- filePath = this.findFilePath(hash);
2725
- }
2726
- if (!filePath) return;
2727
- try {
2728
- const stat = import_fs2.default.statSync(filePath);
2729
- import_fs2.default.unlinkSync(filePath);
2730
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
2731
- this.fileCount = Math.max(0, this.fileCount - 1);
2732
- } catch {
2733
2911
  }
2912
+ for (const file of files) this.removeFile(file);
2913
+ this.invalidatedKeys.delete(key);
2734
2914
  }
2735
2915
  /** Purge all expired entries. Returns number deleted. */
2736
2916
  purgeExpired() {
@@ -2766,8 +2946,8 @@ var init_disk_tier = __esm({
2766
2946
  }
2767
2947
  continue;
2768
2948
  }
2769
- if (filename.length === 77 && filename[64] === "_") {
2770
- const expiresAt = parseInt(filename.slice(65), 16);
2949
+ if (filename.length >= 77 && filename[64] === "_") {
2950
+ const expiresAt = parseInt(filename.slice(65, 77), 16);
2771
2951
  if (expiresAt <= now) {
2772
2952
  try {
2773
2953
  const sz = import_fs2.default.statSync(filePath).size;
@@ -2887,8 +3067,8 @@ var init_disk_tier = __esm({
2887
3067
  }
2888
3068
  continue;
2889
3069
  }
2890
- if (file.length === 77 && file[64] === "_") {
2891
- const expiresAt = parseInt(file.slice(65), 16);
3070
+ if (file.length >= 77 && file[64] === "_") {
3071
+ const expiresAt = parseInt(file.slice(65, 77), 16);
2892
3072
  if (expiresAt <= now2) {
2893
3073
  const fp = import_path2.default.join(orphanBucketP, file);
2894
3074
  try {
@@ -2928,8 +3108,8 @@ var init_disk_tier = __esm({
2928
3108
  }
2929
3109
  continue;
2930
3110
  }
2931
- if (file.length === 77 && file[64] === "_") {
2932
- const expiresAt = parseInt(file.slice(65), 16);
3111
+ if (file.length >= 77 && file[64] === "_") {
3112
+ const expiresAt = parseInt(file.slice(65, 77), 16);
2933
3113
  if (expiresAt <= now) {
2934
3114
  const filePath2 = import_path2.default.join(bucketPath, file);
2935
3115
  try {
@@ -3002,6 +3182,9 @@ var init_disk_tier = __esm({
3002
3182
  }
3003
3183
  /** Delete every file in the disk cache. Returns the count deleted. */
3004
3184
  clear() {
3185
+ this.epoch++;
3186
+ this.pendingSaves.clear();
3187
+ this.invalidatedKeys.clear();
3005
3188
  this.ensureDir();
3006
3189
  if (!this.dirReady) return 0;
3007
3190
  let cleared = 0;
@@ -3065,6 +3248,7 @@ var init_disk_tier = __esm({
3065
3248
  * yielding to the event loop via setImmediate between chunks.
3066
3249
  */
3067
3250
  async triggerChunkedPrune() {
3251
+ if (this.closed) return 0;
3068
3252
  if (this._isPruning) return 0;
3069
3253
  this._isPruning = true;
3070
3254
  this._pruneRounds++;
@@ -3073,7 +3257,7 @@ var init_disk_tier = __esm({
3073
3257
  this.ensureUsageCounted();
3074
3258
  const targetBytes = Math.floor(this.opts.maxBytes * 0.6);
3075
3259
  if (this._db && this._stmtPruneChunk) {
3076
- while (this.diskUsageBytes > targetBytes) {
3260
+ while (!this.closed && this.diskUsageBytes > targetBytes) {
3077
3261
  const rows = this._stmtPruneChunk.all();
3078
3262
  if (!rows || rows.length === 0) break;
3079
3263
  for (const row of rows) {
@@ -3096,7 +3280,7 @@ var init_disk_tier = __esm({
3096
3280
  }
3097
3281
  }
3098
3282
  } else {
3099
- while (this.diskUsageBytes > targetBytes) {
3283
+ while (!this.closed && this.diskUsageBytes > targetBytes) {
3100
3284
  const files = this.walkCacheFiles();
3101
3285
  if (files.length === 0) break;
3102
3286
  const chunk = files.slice(0, 500);
@@ -3164,6 +3348,10 @@ var init_disk_tier = __esm({
3164
3348
  }
3165
3349
  /** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
3166
3350
  close() {
3351
+ this.closed = true;
3352
+ this.epoch++;
3353
+ this.pendingSaves.clear();
3354
+ this.invalidatedKeys.clear();
3167
3355
  if (this._db) {
3168
3356
  try {
3169
3357
  this._db.close();
@@ -3409,6 +3597,17 @@ function readCgroupMemoryLimit() {
3409
3597
  }
3410
3598
  return Infinity;
3411
3599
  }
3600
+ function readCgroupMemoryUsage() {
3601
+ if (process.platform !== "linux") return null;
3602
+ for (const file of ["/sys/fs/cgroup/memory.current", "/sys/fs/cgroup/memory/memory.usage_in_bytes"]) {
3603
+ try {
3604
+ const value = Number(import_node_fs.default.readFileSync(file, "utf8").trim());
3605
+ if (Number.isFinite(value) && value >= 0) return value;
3606
+ } catch {
3607
+ }
3608
+ }
3609
+ return null;
3610
+ }
3412
3611
  function getV8HeapLimit() {
3413
3612
  try {
3414
3613
  const stats = import_node_v8.default.getHeapStatistics();
@@ -3443,11 +3642,101 @@ var init_cgroup = __esm({
3443
3642
  }
3444
3643
  });
3445
3644
 
3645
+ // src/utils/diagnostics.ts
3646
+ function redactDiagnostics(value, seen = /* @__PURE__ */ new WeakSet(), depth = 0) {
3647
+ if (typeof value === "string" && /^[a-z][a-z\d+.-]*:\/\//i.test(value)) {
3648
+ try {
3649
+ const url = new URL(value);
3650
+ if (url.username) url.username = "[REDACTED]";
3651
+ if (url.password) url.password = "[REDACTED]";
3652
+ for (const key of url.searchParams.keys()) {
3653
+ if (/key|token|secret|password|credential|authorization|cookie/i.test(key)) url.searchParams.set(key, "[REDACTED]");
3654
+ }
3655
+ return url.toString();
3656
+ } catch {
3657
+ return "[REDACTED URL]";
3658
+ }
3659
+ }
3660
+ if (value == null || typeof value !== "object") return typeof value === "function" ? void 0 : value;
3661
+ if (depth >= 8) return "[OMITTED]";
3662
+ if (seen.has(value)) return "[CIRCULAR]";
3663
+ seen.add(value);
3664
+ if (Array.isArray(value)) return value.map((item) => redactDiagnostics(item, seen, depth + 1));
3665
+ const result = {};
3666
+ for (const [key, item] of Object.entries(value)) {
3667
+ if (typeof item === "function") continue;
3668
+ result[key] = /key|token|secret|password|credential|authorization|cookie|headers/i.test(key) ? item == null ? item : "[REDACTED]" : redactDiagnostics(item, seen, depth + 1);
3669
+ }
3670
+ return result;
3671
+ }
3672
+ var init_diagnostics = __esm({
3673
+ "src/utils/diagnostics.ts"() {
3674
+ "use strict";
3675
+ }
3676
+ });
3677
+
3678
+ // src/utils/redis-slot.ts
3679
+ function redisHashSlot(key) {
3680
+ const open = key.indexOf("{");
3681
+ const close = open < 0 ? -1 : key.indexOf("}", open + 1);
3682
+ const bytes = Buffer.from(close > open + 1 ? key.slice(open + 1, close) : key, "utf8");
3683
+ let crc = 0;
3684
+ for (const byte of bytes) {
3685
+ crc ^= byte << 8;
3686
+ for (let bit = 0; bit < 8; bit++) crc = crc << 1 ^ (crc & 32768 ? 4129 : 0);
3687
+ crc &= 65535;
3688
+ }
3689
+ return crc & 16383;
3690
+ }
3691
+ var init_redis_slot = __esm({
3692
+ "src/utils/redis-slot.ts"() {
3693
+ "use strict";
3694
+ }
3695
+ });
3696
+
3697
+ // src/utils/deadline.ts
3698
+ async function withDeadline(operation, timeoutMs, label) {
3699
+ let timer;
3700
+ try {
3701
+ return await Promise.race([
3702
+ operation,
3703
+ new Promise((_resolve, reject) => {
3704
+ timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs);
3705
+ })
3706
+ ]);
3707
+ } finally {
3708
+ if (timer) clearTimeout(timer);
3709
+ }
3710
+ }
3711
+ var init_deadline = __esm({
3712
+ "src/utils/deadline.ts"() {
3713
+ "use strict";
3714
+ }
3715
+ });
3716
+
3446
3717
  // src/adapters/auto-pipeliner.ts
3447
- var AutoPipeliner;
3718
+ async function readRedisValue(client, key, hash = false) {
3719
+ if (typeof client.pttl === "function" && typeof client.multi === "function") {
3720
+ const transaction = client.multi();
3721
+ if (typeof transaction.pttl === "function" && (!hash || typeof transaction.hgetall === "function")) {
3722
+ if (hash) transaction.hgetall(key);
3723
+ else transaction.get(key);
3724
+ transaction.pttl(key);
3725
+ const results = await transaction.exec();
3726
+ if (!results) throw new Error("Redis read transaction aborted");
3727
+ if (results[0]?.[0]) throw results[0][0];
3728
+ if (results[1]?.[0]) throw results[1][0];
3729
+ return { raw: results[0]?.[1] ?? null, ttlMs: Number(results[1]?.[1]) };
3730
+ }
3731
+ }
3732
+ return { raw: await (hash ? client.hgetall(key) : client.get(key)) };
3733
+ }
3734
+ var import_ioredis, AutoPipeliner;
3448
3735
  var init_auto_pipeliner = __esm({
3449
3736
  "src/adapters/auto-pipeliner.ts"() {
3450
3737
  "use strict";
3738
+ import_ioredis = require("ioredis");
3739
+ init_redis_slot();
3451
3740
  AutoPipeliner = class {
3452
3741
  constructor(client, options) {
3453
3742
  this.client = client;
@@ -3479,6 +3768,17 @@ var init_auto_pipeliner = __esm({
3479
3768
  this.enqueue({ type: "get", key, resolve, reject });
3480
3769
  });
3481
3770
  }
3771
+ async read(key, hash = false) {
3772
+ if (!hash && typeof this.client.pttl !== "function") return { raw: await this.get(key) };
3773
+ if (!this.enabled || !this.supportsPipelines() || typeof this.client.pttl !== "function") {
3774
+ return readRedisValue(this.client, key, hash);
3775
+ }
3776
+ const probe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
3777
+ if (typeof probe.pttl !== "function" || hash && typeof probe.hgetall !== "function") {
3778
+ return readRedisValue(this.client, key, hash);
3779
+ }
3780
+ return new Promise((resolve, reject) => this.enqueue({ type: "read", key, hash, resolve, reject }));
3781
+ }
3482
3782
  async setex(key, seconds, value) {
3483
3783
  if (!this.enabled || !this.supportsPipelines()) {
3484
3784
  if (typeof this.client.setex === "function") {
@@ -3492,8 +3792,18 @@ var init_auto_pipeliner = __esm({
3492
3792
  this.enqueue({ type: "setex", key, seconds, value, resolve, reject });
3493
3793
  });
3494
3794
  }
3795
+ async setpx(key, milliseconds, value) {
3796
+ if (!this.enabled || !this.supportsPipelines()) {
3797
+ await this.client.set(key, value, "PX", milliseconds);
3798
+ return;
3799
+ }
3800
+ return new Promise((resolve, reject) => this.enqueue({ type: "setpx", key, milliseconds, value, resolve, reject }));
3801
+ }
3495
3802
  async del(...keys) {
3496
3803
  if (keys.length === 0) return 0;
3804
+ if (this.client instanceof import_ioredis.Cluster && keys.length > 1) {
3805
+ return (await Promise.all(keys.map((key) => this.del(key)))).reduce((sum, value) => sum + value, 0);
3806
+ }
3497
3807
  if (!this.enabled || !this.supportsPipelines()) {
3498
3808
  return this.client.del(...keys);
3499
3809
  }
@@ -3527,44 +3837,72 @@ var init_auto_pipeliner = __esm({
3527
3837
  this.scheduled = false;
3528
3838
  this.statsInternal.batchesDispatched++;
3529
3839
  this.statsInternal.operationsBatched += batch.length;
3530
- const pipe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
3531
- for (const op of batch) {
3532
- switch (op.type) {
3533
- case "get":
3534
- pipe.get(op.key);
3535
- break;
3536
- case "setex":
3537
- pipe.setex(op.key, op.seconds, op.value);
3538
- break;
3539
- case "del":
3540
- pipe.del(...op.keys);
3541
- break;
3542
- }
3840
+ if (this.client instanceof import_ioredis.Cluster) {
3841
+ const groups = /* @__PURE__ */ new Map();
3842
+ for (const operation of batch) {
3843
+ const key = operation.type === "del" ? operation.keys[0] : operation.key;
3844
+ const slot = redisHashSlot(key);
3845
+ const master = this.client.slots[slot]?.[0] ?? String(slot);
3846
+ const members = groups.get(master) ?? [];
3847
+ members.push(operation);
3848
+ groups.set(master, members);
3849
+ }
3850
+ await Promise.all([...groups.values()].map((members) => this.dispatch(members)));
3851
+ return;
3543
3852
  }
3853
+ await this.dispatch(batch);
3854
+ }
3855
+ async dispatch(batch) {
3544
3856
  try {
3857
+ const pipe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
3858
+ const indexes = [];
3859
+ let commandCount = 0;
3860
+ for (const op of batch) {
3861
+ indexes.push(commandCount++);
3862
+ switch (op.type) {
3863
+ case "get":
3864
+ pipe.get(op.key);
3865
+ break;
3866
+ case "setex":
3867
+ pipe.setex(op.key, op.seconds, op.value);
3868
+ break;
3869
+ case "setpx":
3870
+ pipe.set(op.key, op.value, "PX", op.milliseconds);
3871
+ break;
3872
+ case "del":
3873
+ pipe.del(...op.keys);
3874
+ break;
3875
+ case "read":
3876
+ if (op.hash) pipe.hgetall(op.key);
3877
+ else pipe.get(op.key);
3878
+ pipe.pttl(op.key);
3879
+ commandCount++;
3880
+ break;
3881
+ }
3882
+ }
3545
3883
  const results = await pipe.exec();
3546
3884
  if (!results) {
3547
3885
  for (const op of batch) {
3548
- if (op.type === "get") op.resolve(null);
3549
- else if (op.type === "del") op.resolve(0);
3550
- else op.resolve();
3886
+ op.reject(new Error("Redis pipeline aborted"));
3551
3887
  }
3552
3888
  return;
3553
3889
  }
3554
3890
  for (let i = 0; i < batch.length; i++) {
3555
3891
  const op = batch[i];
3556
- const resTuple = results[i];
3892
+ const resTuple = results[indexes[i]];
3557
3893
  if (!resTuple) {
3558
- if (op.type === "get") op.resolve(null);
3559
- else if (op.type === "del") op.resolve(0);
3560
- else op.resolve();
3894
+ op.reject(new Error("Missing Redis pipeline result"));
3561
3895
  continue;
3562
3896
  }
3563
3897
  const [err, val] = resTuple;
3564
3898
  if (err) {
3565
3899
  op.reject(err instanceof Error ? err : new Error(String(err)));
3566
3900
  } else {
3567
- if (op.type === "get") {
3901
+ if (op.type === "read") {
3902
+ const ttlResult = results[indexes[i] + 1];
3903
+ if (!ttlResult || ttlResult[0]) op.reject(ttlResult?.[0] ?? new Error("Missing Redis PTTL result"));
3904
+ else op.resolve({ raw: val, ttlMs: Number(ttlResult[1]) });
3905
+ } else if (op.type === "get") {
3568
3906
  op.resolve(val != null ? String(val) : null);
3569
3907
  } else if (op.type === "del") {
3570
3908
  op.resolve(typeof val === "number" ? val : Number(val) || 0);
@@ -3607,6 +3945,8 @@ var init_ipc_telemetry = __esm({
3607
3945
  server = null;
3608
3946
  socketPath;
3609
3947
  _closed = false;
3948
+ _starting = null;
3949
+ sockets = /* @__PURE__ */ new Set();
3610
3950
  _exitHandler = null;
3611
3951
  _sigintHandler = null;
3612
3952
  _sigtermHandler = null;
@@ -3614,10 +3954,23 @@ var init_ipc_telemetry = __esm({
3614
3954
  * Start listening on the IPC socket / pipe.
3615
3955
  */
3616
3956
  async start() {
3617
- if (this.server && this.server.listening) return;
3957
+ if (this._closed || this.server?.listening) return;
3958
+ if (this._starting) return this._starting;
3959
+ this._starting = this.startInternal();
3960
+ try {
3961
+ await this._starting;
3962
+ } finally {
3963
+ this._starting = null;
3964
+ }
3965
+ }
3966
+ async startInternal() {
3618
3967
  if (process.platform !== "win32" && import_node_fs2.default.existsSync(this.socketPath)) {
3619
3968
  await new Promise((resolve) => {
3620
3969
  const testSocket = import_node_net.default.createConnection(this.socketPath);
3970
+ testSocket.setTimeout(1e3, () => {
3971
+ testSocket.destroy();
3972
+ resolve();
3973
+ });
3621
3974
  testSocket.once("connect", () => {
3622
3975
  testSocket.destroy();
3623
3976
  resolve();
@@ -3632,17 +3985,37 @@ var init_ipc_telemetry = __esm({
3632
3985
  });
3633
3986
  });
3634
3987
  }
3988
+ if (this._closed) return;
3635
3989
  this.server = import_node_net.default.createServer((socket) => {
3990
+ if (this._closed) {
3991
+ socket.destroy();
3992
+ return;
3993
+ }
3994
+ this.sockets.add(socket);
3995
+ socket.once("close", () => this.sockets.delete(socket));
3996
+ socket.setTimeout(5e3, () => socket.destroy());
3636
3997
  let buffer = "";
3998
+ let pending = 0;
3637
3999
  socket.on("data", (chunk) => {
4000
+ if (Buffer.byteLength(buffer) + chunk.length > 4096 || socket.writableLength > 65536) {
4001
+ socket.destroy();
4002
+ return;
4003
+ }
3638
4004
  buffer += chunk.toString("utf8");
3639
4005
  let newlineIndex;
3640
4006
  while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
3641
4007
  const line = buffer.slice(0, newlineIndex).trim();
3642
4008
  buffer = buffer.slice(newlineIndex + 1);
3643
4009
  if (!line) continue;
4010
+ if (++pending > 8) {
4011
+ socket.destroy();
4012
+ return;
4013
+ }
3644
4014
  setImmediate(() => {
3645
- if (socket.destroyed) return;
4015
+ if (socket.destroyed) {
4016
+ pending--;
4017
+ return;
4018
+ }
3646
4019
  try {
3647
4020
  let cmd = line;
3648
4021
  try {
@@ -3667,6 +4040,8 @@ var init_ipc_telemetry = __esm({
3667
4040
  if (!socket.destroyed) {
3668
4041
  socket.write(JSON.stringify({ error: err.message }) + "\n");
3669
4042
  }
4043
+ } finally {
4044
+ pending--;
3670
4045
  }
3671
4046
  });
3672
4047
  }
@@ -3674,21 +4049,38 @@ var init_ipc_telemetry = __esm({
3674
4049
  socket.on("error", () => {
3675
4050
  });
3676
4051
  });
4052
+ this.server.maxConnections = 128;
3677
4053
  await new Promise((resolve, reject) => {
3678
- this.server.once("error", reject);
3679
- this.server.listen(this.socketPath, () => {
3680
- this.server.removeListener("error", reject);
4054
+ const server = this.server;
4055
+ const cleanup = () => {
4056
+ server.off("error", failed);
4057
+ server.off("close", closed);
4058
+ };
4059
+ const failed = (error) => {
4060
+ cleanup();
4061
+ reject(error);
4062
+ };
4063
+ const closed = () => {
4064
+ cleanup();
4065
+ resolve();
4066
+ };
4067
+ server.once("error", failed);
4068
+ server.once("close", closed);
4069
+ server.listen(this.socketPath, () => {
4070
+ cleanup();
3681
4071
  resolve();
3682
4072
  });
3683
4073
  });
4074
+ if (this._closed) {
4075
+ if (this.server.listening) this.server.close();
4076
+ return;
4077
+ }
3684
4078
  this._exitHandler = () => this._unlinkSocket();
3685
4079
  this._sigintHandler = () => {
3686
4080
  this._unlinkSocket();
3687
- process.exit(0);
3688
4081
  };
3689
4082
  this._sigtermHandler = () => {
3690
4083
  this._unlinkSocket();
3691
- process.exit(0);
3692
4084
  };
3693
4085
  process.once("exit", this._exitHandler);
3694
4086
  process.once("SIGINT", this._sigintHandler);
@@ -3718,6 +4110,7 @@ var init_ipc_telemetry = __esm({
3718
4110
  _unlinkSocket() {
3719
4111
  if (this._closed) return;
3720
4112
  this._closed = true;
4113
+ for (const socket of this.sockets) socket.destroy();
3721
4114
  try {
3722
4115
  this.server?.close();
3723
4116
  } catch {
@@ -3735,6 +4128,9 @@ var init_ipc_telemetry = __esm({
3735
4128
  * Gracefully close the IPC telemetry server and clean up handlers and sockets.
3736
4129
  */
3737
4130
  async close() {
4131
+ this._unlinkSocket();
4132
+ await this._starting?.catch(() => {
4133
+ });
3738
4134
  if (this._exitHandler) {
3739
4135
  process.removeListener("exit", this._exitHandler);
3740
4136
  this._exitHandler = null;
@@ -3747,7 +4143,6 @@ var init_ipc_telemetry = __esm({
3747
4143
  process.removeListener("SIGTERM", this._sigtermHandler);
3748
4144
  this._sigtermHandler = null;
3749
4145
  }
3750
- this._unlinkSocket();
3751
4146
  return new Promise((resolve) => {
3752
4147
  if (!this.server || !this.server.listening) {
3753
4148
  resolve();
@@ -3881,12 +4276,13 @@ function deepMergeOptions(base, overrides) {
3881
4276
  }
3882
4277
  return output;
3883
4278
  }
3884
- var import_ioredis, import_crypto3, import_os3, import_node_v82, import_fs3, import_path3, LUA_COMPARE_AND_DELETE, SNAPSHOT_VERSION, DEFAULT_SNAPSHOT_MAX_AGE, INDEFINITE_TTL_SECONDS, SNAPSHOT_MAX_FILE_BYTES, DEFAULT_CATEGORY_LIMITS, DEFAULT_FORBIDDEN_PREFIXES, DEFAULT_COUNTER_TTL_SECONDS, GLOB_REGEX_CACHE_MAX, globRegexCache2, L2CircuitBreaker, LatencyTracker, GLOBAL_KEY, ProcessTerminationBus, CacheService;
4279
+ var import_ioredis2, import_crypto3, import_os3, import_node_v82, import_fs3, import_path3, LUA_COMPARE_AND_DELETE, LUA_READ_CACHE_ENTRY, LUA_MAX_TAG_VERSION, LUA_RECEIVE_TAG_VERSION, LUA_TOUCH_CACHE_ENTRY, SNAPSHOT_VERSION, DEFAULT_SNAPSHOT_MAX_AGE, INDEFINITE_TTL_SECONDS, SNAPSHOT_MAX_FILE_BYTES, DEFAULT_CATEGORY_LIMITS, DEFAULT_FORBIDDEN_PREFIXES, DEFAULT_COUNTER_TTL_SECONDS, GLOB_REGEX_CACHE_MAX, globRegexCache2, L2CircuitBreaker, LatencyTracker, GLOBAL_KEY, ProcessTerminationBus, CacheService;
3885
4280
  var init_cache_service = __esm({
3886
4281
  "src/cache-service.ts"() {
3887
4282
  "use strict";
3888
- import_ioredis = require("ioredis");
4283
+ import_ioredis2 = require("ioredis");
3889
4284
  init_codec();
4285
+ init_cross_region();
3890
4286
  import_crypto3 = __toESM(require("crypto"), 1);
3891
4287
  import_os3 = __toESM(require("os"), 1);
3892
4288
  init_worker_pool();
@@ -3899,6 +4295,9 @@ var init_cache_service = __esm({
3899
4295
  init_disk_tier();
3900
4296
  init_latency_watchdog();
3901
4297
  init_cgroup();
4298
+ init_diagnostics();
4299
+ init_redis_slot();
4300
+ init_deadline();
3902
4301
  init_auto_pipeliner();
3903
4302
  init_ipc_telemetry();
3904
4303
  init_compression();
@@ -3909,6 +4308,37 @@ if currentTs and currentTs == ARGV[1] then
3909
4308
  return redis.call('DEL', KEYS[1])
3910
4309
  end
3911
4310
  return 0
4311
+ `;
4312
+ LUA_READ_CACHE_ENTRY = `
4313
+ local kind = redis.call('TYPE', KEYS[1]).ok
4314
+ if kind == 'string' then
4315
+ return { kind, redis.call('GET', KEYS[1]), redis.call('PTTL', KEYS[1]) }
4316
+ elseif kind == 'hash' then
4317
+ return { kind, redis.call('HGETALL', KEYS[1]), redis.call('PTTL', KEYS[1]) }
4318
+ end
4319
+ return { 'none', false, -2 }
4320
+ `;
4321
+ LUA_MAX_TAG_VERSION = `
4322
+ local current = tonumber(redis.call('GET', KEYS[1]) or '0')
4323
+ local floor = tonumber(ARGV[1])
4324
+ if current < floor then redis.call('SET', KEYS[1], floor) return floor end
4325
+ return current
4326
+ `;
4327
+ LUA_RECEIVE_TAG_VERSION = `
4328
+ local current = tonumber(redis.call('GET', KEYS[1]) or '0')
4329
+ local next = math.max(current + 1, tonumber(ARGV[1]))
4330
+ redis.call('SET', KEYS[1], next)
4331
+ return next
4332
+ `;
4333
+ LUA_TOUCH_CACHE_ENTRY = `
4334
+ local kind = redis.call('TYPE', KEYS[1]).ok
4335
+ if kind == 'hash' then
4336
+ if redis.call('HGET', KEYS[1], 't') ~= ARGV[1] then return 0 end
4337
+ redis.call('HSET', KEYS[1], 'e', ARGV[2])
4338
+ elseif kind ~= 'string' then
4339
+ return 0
4340
+ end
4341
+ return redis.call('PEXPIRE', KEYS[1], ARGV[3])
3912
4342
  `;
3913
4343
  SNAPSHOT_VERSION = 1;
3914
4344
  DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
@@ -4142,13 +4572,19 @@ return 0
4142
4572
  _l1Counters = /* @__PURE__ */ new Map();
4143
4573
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
4144
4574
  tagIndex = /* @__PURE__ */ new Map();
4575
+ /** Reverse index of namespaced key → { tags, expiresAt } for bounded cleanup on eviction/delete */
4576
+ keyTags = /* @__PURE__ */ new Map();
4145
4577
  /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
4146
4578
  tagVersions = /* @__PURE__ */ new Map();
4579
+ _tagRefreshEpoch = 0;
4147
4580
  /**
4148
4581
  * Dependency index: source glob pattern → Set of namespaced dependent keys.
4149
4582
  * When an exact-key delete matches a registered pattern, all dependents are cascaded.
4150
4583
  */
4151
4584
  dependencyIndex = /* @__PURE__ */ new Map();
4585
+ /** Reverse index of namespaced dependent key → source glob patterns */
4586
+ keyDependencies = /* @__PURE__ */ new Map();
4587
+ _cgroupMemoryLimit;
4152
4588
  redis = null;
4153
4589
  redisConnecting = null;
4154
4590
  cb;
@@ -4171,9 +4607,17 @@ return 0
4171
4607
  subClient = null;
4172
4608
  streamClient = null;
4173
4609
  _lastStreamId = "$";
4610
+ _restoredSnapshot = false;
4611
+ _backplaneAvailable = false;
4612
+ _otelCleanup = null;
4613
+ _streamRecovering = false;
4614
+ _backplaneDisposers = [];
4174
4615
  _destroyed = false;
4175
4616
  _pendingDiskDeletes = /* @__PURE__ */ new Set();
4176
4617
  _globalEpoch = 0;
4618
+ _pendingSpillCount = 0;
4619
+ _suppressSpills = false;
4620
+ _diskCleanupScheduled = false;
4177
4621
  _keyMutationEpochs = /* @__PURE__ */ new Map();
4178
4622
  /**
4179
4623
  * Pattern tombstones for disk tier.
@@ -4182,20 +4626,24 @@ return 0
4182
4626
  * pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
4183
4627
  */
4184
4628
  _patternTombstones = [];
4185
- _addPatternTombstone(prefix) {
4629
+ _diskInvalidatedBefore = 0;
4630
+ _addPatternTombstone(pattern) {
4186
4631
  const now = Date.now();
4187
4632
  while (this._patternTombstones.length > 0 && now - this._patternTombstones[0].createdAt > 36e5) {
4188
- this._patternTombstones.shift();
4633
+ const forgotten = this._patternTombstones.shift();
4634
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
4189
4635
  }
4190
4636
  if (this._patternTombstones.length >= 2e3) {
4191
- this._patternTombstones.shift();
4637
+ const forgotten = this._patternTombstones.shift();
4638
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
4192
4639
  }
4193
- this._patternTombstones.push({ prefix, createdAt: now });
4640
+ this._patternTombstones.push({ pattern, createdAt: now });
4194
4641
  }
4195
- _isTombstonedByPattern(namespacedKey) {
4642
+ _isTombstonedByPattern(namespacedKey, setAt = 0) {
4643
+ if (this._diskInvalidatedBefore > 0 && setAt <= this._diskInvalidatedBefore) return true;
4196
4644
  if (this._patternTombstones.length === 0) return false;
4197
4645
  for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
4198
- if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
4646
+ if (setAt <= this._patternTombstones[i].createdAt && this._matchesGlob(namespacedKey, this._patternTombstones[i].pattern)) {
4199
4647
  return true;
4200
4648
  }
4201
4649
  }
@@ -4210,13 +4658,170 @@ return 0
4210
4658
  const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
4211
4659
  this._keyMutationEpochs.set(namespacedKey, next);
4212
4660
  if (this._keyMutationEpochs.size > 5e4) {
4213
- const oldest = this._keyMutationEpochs.keys().next().value;
4214
- if (oldest !== void 0) this._keyMutationEpochs.delete(oldest);
4661
+ this._globalEpoch++;
4662
+ this._keyMutationEpochs.clear();
4663
+ this._keyMutationEpochs.set(namespacedKey, next);
4215
4664
  }
4216
4665
  return next;
4217
4666
  }
4218
4667
  _getKeyMutationEpoch(namespacedKey) {
4219
- return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
4668
+ return `${this._globalEpoch}:${this._keyMutationEpochs.get(namespacedKey) ?? 0}`;
4669
+ }
4670
+ /** Capture a commit fence before asynchronous computation outside the cache. */
4671
+ captureMutationFence(cacheKey) {
4672
+ this._assertActive("captureMutationFence");
4673
+ const key = this.nk(cacheKey);
4674
+ const epoch = this._getKeyMutationEpoch(key);
4675
+ return () => !this._destroyed && this._getKeyMutationEpoch(key) === epoch;
4676
+ }
4677
+ /** Force tag re-sync without forgetting locally observed monotonic generations. */
4678
+ refreshTagVersions() {
4679
+ this._assertActive("refreshTagVersions");
4680
+ this._tagRefreshEpoch++;
4681
+ }
4682
+ _fenceInvalidation() {
4683
+ this._globalEpoch++;
4684
+ this.inflight.clear();
4685
+ }
4686
+ _invalidateDiskKey(key) {
4687
+ if (this._diskDisabled) return;
4688
+ this.disk.invalidate(key);
4689
+ this._pendingDiskDeletes.add(key);
4690
+ this._scheduleDiskCleanup();
4691
+ }
4692
+ _scheduleDiskCleanup() {
4693
+ if (this._diskCleanupScheduled || this._pendingDiskDeletes.size === 0) return;
4694
+ this._diskCleanupScheduled = true;
4695
+ setImmediate(() => {
4696
+ this._diskCleanupScheduled = false;
4697
+ if (this._destroyed) return;
4698
+ let processed = 0;
4699
+ for (const key of this._pendingDiskDeletes) {
4700
+ try {
4701
+ this.disk.delete(key, true);
4702
+ } finally {
4703
+ this._pendingDiskDeletes.delete(key);
4704
+ }
4705
+ if (++processed >= 16) break;
4706
+ }
4707
+ this._scheduleDiskCleanup();
4708
+ });
4709
+ }
4710
+ _registerDependencies(key, patterns) {
4711
+ this._removeKeyDependencies(key);
4712
+ if (!patterns?.length) return;
4713
+ const namespaced = [...new Set(patterns.map((pattern) => this.nk(pattern)))];
4714
+ for (const pattern of namespaced) {
4715
+ const dependents = this.dependencyIndex.get(pattern) ?? /* @__PURE__ */ new Set();
4716
+ dependents.add(key);
4717
+ this.dependencyIndex.set(pattern, dependents);
4718
+ }
4719
+ this.keyDependencies.set(key, namespaced);
4720
+ }
4721
+ _rememberTags(key, tags, expiresAt) {
4722
+ this._removeKeyTags(key);
4723
+ if (!tags.length) return;
4724
+ if (this.keyTags.size >= 1e5) {
4725
+ this._sweepExpiredMetadata();
4726
+ const oldest = this.keyTags.keys().next().value;
4727
+ if (this.keyTags.size >= 1e5 && oldest !== void 0) this._removeKeyTags(oldest);
4728
+ }
4729
+ const unique = [...new Set(tags)];
4730
+ for (const tag of unique) {
4731
+ const tagKey = this.nk(`_tag_:${tag}`);
4732
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
4733
+ members.add(key);
4734
+ this.tagIndex.set(tagKey, members);
4735
+ }
4736
+ this.keyTags.set(key, { tags: unique, expiresAt });
4737
+ }
4738
+ _restoreEntryMetadata(key, entry) {
4739
+ if (entry.tags?.length) this._rememberTags(key, entry.tags, entry.expiresAt);
4740
+ if (entry.dependsOn?.length) this._registerDependencies(key, entry.dependsOn);
4741
+ }
4742
+ _removeKeyTags(namespacedKey) {
4743
+ const entry = this.keyTags.get(namespacedKey);
4744
+ if (!entry) return;
4745
+ for (const tag of entry.tags) {
4746
+ const tagKey = this.nk(`_tag_:${tag}`);
4747
+ const members = this.tagIndex.get(tagKey);
4748
+ if (members) {
4749
+ members.delete(namespacedKey);
4750
+ if (members.size === 0) this.tagIndex.delete(tagKey);
4751
+ }
4752
+ }
4753
+ this.keyTags.delete(namespacedKey);
4754
+ }
4755
+ _removeKeyDependencies(namespacedKey) {
4756
+ const patterns = this.keyDependencies.get(namespacedKey);
4757
+ if (patterns) {
4758
+ for (const pat of patterns) {
4759
+ const deps = this.dependencyIndex.get(pat);
4760
+ if (deps) {
4761
+ deps.delete(namespacedKey);
4762
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
4763
+ }
4764
+ }
4765
+ this.keyDependencies.delete(namespacedKey);
4766
+ } else if (this.dependencyIndex.size > 0) {
4767
+ for (const [pat, deps] of this.dependencyIndex) {
4768
+ deps.delete(namespacedKey);
4769
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
4770
+ }
4771
+ }
4772
+ }
4773
+ _handleL1Eviction(namespacedKey, reason) {
4774
+ const spilledToDisk = !this._diskDisabled && !this._suppressSpills && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
4775
+ if (!spilledToDisk) {
4776
+ this._removeKeyTags(namespacedKey);
4777
+ this._removeKeyDependencies(namespacedKey);
4778
+ }
4779
+ }
4780
+ _removePatternFromIndices(pattern) {
4781
+ for (const k of Array.from(this.keyTags.keys())) {
4782
+ if (this._matchesGlob(k, pattern)) this._removeKeyTags(k);
4783
+ }
4784
+ for (const k of Array.from(this.keyDependencies.keys())) {
4785
+ if (this._matchesGlob(k, pattern)) this._removeKeyDependencies(k);
4786
+ }
4787
+ for (const k of Array.from(this._l1Counters.keys())) {
4788
+ if (this._matchesGlob(k, pattern)) this._l1Counters.delete(k);
4789
+ }
4790
+ }
4791
+ _sweepExpiredMetadata() {
4792
+ const now = Date.now();
4793
+ for (const [k, c] of this._l1Counters) {
4794
+ if (c.expiresAt <= now) this._l1Counters.delete(k);
4795
+ }
4796
+ for (const [k, meta] of this.keyTags) {
4797
+ if (meta.expiresAt <= now && !this.l1.has(k)) {
4798
+ this._removeKeyTags(k);
4799
+ this._removeKeyDependencies(k);
4800
+ }
4801
+ }
4802
+ }
4803
+ _runOomCheck() {
4804
+ const heap = import_node_v82.default.getHeapStatistics();
4805
+ const heapUsed = heap.used_heap_size / heap.heap_size_limit;
4806
+ const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? (readCgroupMemoryUsage() ?? process.memoryUsage().rss) / this._cgroupMemoryLimit : 0;
4807
+ const used = Math.max(heapUsed, cgroupUsed);
4808
+ if (used >= this.opts.oomHeapThreshold) {
4809
+ this._suppressSpills = cgroupUsed >= this.opts.oomHeapThreshold;
4810
+ let evicted;
4811
+ try {
4812
+ evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
4813
+ } finally {
4814
+ this._suppressSpills = false;
4815
+ }
4816
+ this.counters.oomEvictions++;
4817
+ this.counters.oomLastAt = Date.now();
4818
+ this.logger.warn("tricache OOM guard: emergency L1 eviction", {
4819
+ heapUsedPct: Math.round(heapUsed * 100),
4820
+ cgroupUsedPct: cgroupUsed > 0 ? Math.round(cgroupUsed * 100) : void 0,
4821
+ threshold: Math.round(this.opts.oomHeapThreshold * 100),
4822
+ evicted
4823
+ });
4824
+ }
4220
4825
  }
4221
4826
  _ipcServer;
4222
4827
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
@@ -4264,6 +4869,7 @@ return 0
4264
4869
  constructor(options = {}) {
4265
4870
  const logger = options.logger ?? consoleLogger;
4266
4871
  this.logger = logger;
4872
+ this._cgroupMemoryLimit = readCgroupMemoryLimit();
4267
4873
  const ns = options.namespace?.trim() ?? "";
4268
4874
  const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
4269
4875
  this.enc = new CacheEncryption(
@@ -4442,12 +5048,19 @@ return 0
4442
5048
  admissionPolicy: this.opts.l1AdmissionPolicy,
4443
5049
  codec: this.codec,
4444
5050
  diskSpill: (key, entry) => {
4445
- if (this._diskDisabled) return;
5051
+ if (this._diskDisabled || this._suppressSpills) return;
5052
+ if (this._pendingSpillCount >= (this.opts.diskMaxPendingWrites ?? 512)) return;
5053
+ const epoch = this._getKeyMutationEpoch(key);
5054
+ this._pendingSpillCount++;
4446
5055
  setImmediate(() => {
4447
- void this.disk.save(key, entry);
5056
+ this._pendingSpillCount--;
5057
+ if (!this._destroyed && this._getKeyMutationEpoch(key) === epoch) void this.disk.save(key, entry);
4448
5058
  });
4449
5059
  },
4450
- onEviction: options.onEviction,
5060
+ onEviction: (key, reason) => {
5061
+ this._handleL1Eviction(key, reason);
5062
+ options.onEviction?.(key, reason);
5063
+ },
4451
5064
  logger
4452
5065
  });
4453
5066
  if (!this.snapshotLoaded) {
@@ -4485,6 +5098,7 @@ return 0
4485
5098
  }
4486
5099
  this.cleanupInterval = setInterval(() => {
4487
5100
  const cleaned = this.l1.cleanup();
5101
+ this._sweepExpiredMetadata();
4488
5102
  if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
4489
5103
  }, 5 * 60 * 1e3);
4490
5104
  if (this.cleanupInterval.unref) this.cleanupInterval.unref();
@@ -4497,18 +5111,7 @@ return 0
4497
5111
  }
4498
5112
  if (this.opts.oomProtection) {
4499
5113
  this.oomInterval = setInterval(() => {
4500
- const heap = import_node_v82.default.getHeapStatistics();
4501
- const used = heap.used_heap_size / heap.heap_size_limit;
4502
- if (used >= this.opts.oomHeapThreshold) {
4503
- const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
4504
- this.counters.oomEvictions++;
4505
- this.counters.oomLastAt = Date.now();
4506
- this.logger.warn("tricache OOM guard: emergency L1 eviction", {
4507
- heapUsedPct: Math.round(used * 100),
4508
- threshold: Math.round(this.opts.oomHeapThreshold * 100),
4509
- evicted
4510
- });
4511
- }
5114
+ this._runOomCheck();
4512
5115
  }, this.opts.oomCheckIntervalMs);
4513
5116
  if (this.oomInterval.unref) this.oomInterval.unref();
4514
5117
  }
@@ -4530,7 +5133,7 @@ return 0
4530
5133
  this.instanceId = import_crypto3.default.randomBytes(8).toString("hex");
4531
5134
  this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
4532
5135
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
4533
- this.initBackplane();
5136
+ 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 }));
4534
5137
  const startupPromises = [];
4535
5138
  if (this.opts.compression === "zstd") {
4536
5139
  startupPromises.push(initZstd().then(() => void 0));
@@ -4541,9 +5144,8 @@ return 0
4541
5144
  if (this.opts.warmKeys) {
4542
5145
  startupPromises.push(this.warmFromL2(this.opts.warmKeys).then(() => void 0));
4543
5146
  }
4544
- if (startupPromises.length > 0) {
4545
- this._readyPromise = Promise.all(startupPromises).then(() => void 0);
4546
- }
5147
+ const backplaneReady = this.opts.remoteSnapshot || this.opts.warmKeys ? Promise.all(startupPromises).then(startBackplane) : startBackplane();
5148
+ this._readyPromise = Promise.all([...startupPromises, backplaneReady]).then(() => void 0);
4547
5149
  if (this.opts.meter) {
4548
5150
  this._initOtelMetrics(this.opts.meter);
4549
5151
  const otel = this._otelMetrics;
@@ -4556,7 +5158,10 @@ return 0
4556
5158
  if (typeof prop === "string" && typeof value === "number" && typeof oldVal === "number") {
4557
5159
  const diff = value - oldVal;
4558
5160
  if (diff > 0 && otel[prop]) {
4559
- otel[prop].add(diff, nsAttr);
5161
+ try {
5162
+ otel[prop].add(diff, nsAttr);
5163
+ } catch {
5164
+ }
4560
5165
  }
4561
5166
  }
4562
5167
  return ok;
@@ -4648,7 +5253,7 @@ return 0
4648
5253
  return g[key];
4649
5254
  }
4650
5255
  const existing = g[key];
4651
- const diff = _CacheService.optionsDiff(options ?? {}, existing.options);
5256
+ const diff = _CacheService.optionsDiff(options ?? {}, existing.opts);
4652
5257
  if (diff.length > 0) {
4653
5258
  existing.bumpSingletonDivergence();
4654
5259
  const msg = `tricache: singleton already initialised for namespace '${existing.options.namespace || "(default)"}' \u2014 ignoring divergent options: ${diff.join(", ")}`;
@@ -4682,7 +5287,13 @@ return 0
4682
5287
  "instanceName",
4683
5288
  "invalidationBackplane",
4684
5289
  "awaitInvalidationBackplane",
4685
- "lockFailClosed"
5290
+ "lockFailClosed",
5291
+ "tagStrategy",
5292
+ "cloneStrategy",
5293
+ "compression",
5294
+ "backplaneMode",
5295
+ "redisProtocol",
5296
+ "failClosed"
4686
5297
  ];
4687
5298
  /** Returns the names of options that differ between `a` and the live `b`. */
4688
5299
  static optionsDiff(a, b) {
@@ -4700,12 +5311,12 @@ return 0
4700
5311
  bumpSingletonDivergence() {
4701
5312
  this.counters.singletonDivergences++;
4702
5313
  }
4703
- /** Read-only view of the options the singleton was constructed with. */
5314
+ /** Sanitized diagnostic view; retain the original options/adapters to reuse configuration. */
4704
5315
  get options() {
4705
5316
  const o = this.opts;
4706
5317
  return {
4707
5318
  namespace: o.namespace,
4708
- logger: o.logger,
5319
+ 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) },
4709
5320
  l1MaxBytes: o.l1MaxBytes,
4710
5321
  l1MaxEntries: o.l1MaxEntries,
4711
5322
  redisHost: o.redisHost,
@@ -4726,8 +5337,8 @@ return 0
4726
5337
  awaitInvalidationBackplane: o.awaitInvalidationBackplane,
4727
5338
  lockFailClosed: o.lockFailClosed,
4728
5339
  strictSingleton: o.strictSingleton,
4729
- remoteSnapshot: o.remoteSnapshot,
4730
- crossRegion: o.crossRegion
5340
+ remoteSnapshot: redactDiagnostics(o.remoteSnapshot),
5341
+ crossRegion: redactDiagnostics(o.crossRegion)
4731
5342
  };
4732
5343
  }
4733
5344
  /**
@@ -4810,21 +5421,26 @@ return 0
4810
5421
  if (this.opts.redisClient && typeof this.opts.redisClient.duplicate === "function") {
4811
5422
  return this.opts.redisClient.duplicate();
4812
5423
  }
5424
+ if (this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel) {
5425
+ throw new Error("Invalidation backplane requires redisSubClient or a driver supporting duplicate()");
5426
+ }
4813
5427
  if (this.opts.redisClusterNodes?.length) {
4814
- return new import_ioredis.Cluster(this.opts.redisClusterNodes, {
5428
+ return new import_ioredis2.Cluster(this.opts.redisClusterNodes, {
4815
5429
  redisOptions: {
4816
5430
  tls: this.opts.redisTls ? {} : void 0,
4817
5431
  connectTimeout: 1e4,
5432
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
4818
5433
  maxRetriesPerRequest: null,
4819
5434
  ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
4820
5435
  }
4821
5436
  });
4822
5437
  } else if (this.opts.redisSentinel) {
4823
- return new import_ioredis.Redis({
5438
+ return new import_ioredis2.Redis({
4824
5439
  sentinels: this.opts.redisSentinel.sentinels,
4825
5440
  name: this.opts.redisSentinel.name,
4826
5441
  tls: this.opts.redisTls ? {} : void 0,
4827
5442
  connectTimeout: 1e4,
5443
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
4828
5444
  lazyConnect: true,
4829
5445
  maxRetriesPerRequest: null,
4830
5446
  enableAutoPipelining: false,
@@ -4832,11 +5448,12 @@ return 0
4832
5448
  ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
4833
5449
  });
4834
5450
  } else {
4835
- return new import_ioredis.Redis({
5451
+ return new import_ioredis2.Redis({
4836
5452
  host: this.opts.redisHost,
4837
5453
  port: this.opts.redisPort,
4838
5454
  tls: this.opts.redisTls ? {} : void 0,
4839
5455
  connectTimeout: 1e4,
5456
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
4840
5457
  lazyConnect: true,
4841
5458
  maxRetriesPerRequest: null,
4842
5459
  enableAutoPipelining: false,
@@ -4846,26 +5463,32 @@ return 0
4846
5463
  });
4847
5464
  }
4848
5465
  }
4849
- initBackplane() {
5466
+ _listenBackplane(client, event, listener) {
5467
+ client.on?.(event, listener);
5468
+ this._backplaneDisposers.push(() => client.removeListener?.(event, listener));
5469
+ }
5470
+ async initBackplane() {
4850
5471
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
4851
5472
  if (this.opts.backplaneMode === "stream") {
4852
5473
  if (this.streamClient) return;
4853
- void this._startStreamConsumer();
5474
+ await this._startStreamConsumer();
4854
5475
  return;
4855
5476
  }
4856
5477
  if (this.subClient) return;
4857
5478
  const sub = this.createDedicatedRedisClient();
4858
- sub.on("error", (e) => {
5479
+ this.subClient = sub;
5480
+ this._listenBackplane(sub, "error", (e) => {
4859
5481
  this._checkAndLogResp3Hint(e);
4860
5482
  this.logger.debug("Backplane subscriber error", { error: e.message });
4861
5483
  });
4862
- sub.on("close", () => {
5484
+ this._listenBackplane(sub, "close", () => {
5485
+ this._backplaneAvailable = false;
4863
5486
  if (this._subDisconnectedAt === null) {
4864
5487
  this._subDisconnectedAt = Date.now();
4865
5488
  this.logger.debug("Backplane: subscriber disconnected", { at: this._subDisconnectedAt });
4866
5489
  }
4867
5490
  });
4868
- sub.on("ready", () => {
5491
+ this._listenBackplane(sub, "ready", () => {
4869
5492
  if (this._subDisconnectedAt !== null && this.opts.backplaneMaxStalenessMs > 0) {
4870
5493
  const gapMs = Date.now() - this._subDisconnectedAt;
4871
5494
  if (gapMs > this.opts.backplaneMaxStalenessMs) {
@@ -4878,52 +5501,119 @@ return 0
4878
5501
  }
4879
5502
  this._subDisconnectedAt = null;
4880
5503
  }
5504
+ if (!this._destroyed) this._backplaneAvailable = true;
4881
5505
  });
4882
5506
  const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
4883
5507
  if (isClusterSharded) {
4884
- sub.on("smessage", (_channel, message) => {
5508
+ this._listenBackplane(sub, "smessage", (_channel, message) => {
4885
5509
  this._handleBackplaneMessage(message);
4886
5510
  });
4887
- sub.ssubscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: sharded subscribed", {
5511
+ if (typeof sub.connect === "function" && (sub.isOpen === false || sub.status === "wait")) await sub.connect();
5512
+ await sub.ssubscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: sharded subscribed", {
4888
5513
  channel: this.backplaneChannel,
4889
5514
  instanceId: this.instanceId
4890
- })).catch((err) => this.logger.warn("Backplane: sharded subscribe failed", {
4891
- error: err.message
4892
5515
  }));
4893
5516
  } else {
4894
- sub.on("message", (_channel, message) => {
5517
+ this._listenBackplane(sub, "message", (_channel, message) => {
4895
5518
  this._handleBackplaneMessage(message);
4896
5519
  });
4897
- sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
5520
+ if (typeof sub.connect === "function" && (sub.isOpen === false || sub.status === "wait")) await sub.connect();
5521
+ if (this._destroyed) return;
5522
+ await sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
4898
5523
  channel: this.backplaneChannel,
4899
5524
  instanceId: this.instanceId
4900
- })).catch((err) => this.logger.warn("Backplane: subscribe failed", {
4901
- error: err.message
4902
5525
  }));
4903
5526
  }
4904
- this.subClient = sub;
5527
+ if (!this._destroyed) this._backplaneAvailable = true;
5528
+ }
5529
+ _resetAfterStreamGap() {
5530
+ this.counters.streamGaps++;
5531
+ this._fenceInvalidation();
5532
+ this.l1.clear();
5533
+ this.tagIndex.clear();
5534
+ this.keyTags.clear();
5535
+ this.tagVersions.clear();
5536
+ this.dependencyIndex.clear();
5537
+ this.keyDependencies.clear();
5538
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, Date.now());
5539
+ this._addPatternTombstone(this.nk("*"));
5540
+ this._lastStreamId = "0-0";
4905
5541
  }
4906
5542
  async _startStreamConsumer() {
5543
+ this._streamRecovering ||= this._lastStreamId !== "$" && this._lastStreamId !== "0-0";
4907
5544
  const sub = this.streamClient ?? this.createDedicatedRedisClient();
4908
5545
  this.streamClient = sub;
5546
+ if (typeof sub.xread !== "function") throw new Error("backplaneMode: stream requires a driver supporting XREAD");
4909
5547
  if (typeof sub.on === "function") {
4910
- sub.on("error", (e) => this.logger.debug("Backplane stream consumer error", { error: e.message }));
4911
- sub.on("close", () => {
5548
+ this._listenBackplane(sub, "error", (e) => this.logger.debug("Backplane stream consumer error", { error: e.message }));
5549
+ this._listenBackplane(sub, "close", () => {
5550
+ this._streamRecovering = true;
5551
+ this._backplaneAvailable = false;
4912
5552
  if (this._subDisconnectedAt === null) {
4913
5553
  this._subDisconnectedAt = Date.now();
4914
5554
  this.logger.debug("Backplane stream: consumer disconnected", { at: this._subDisconnectedAt });
4915
5555
  }
4916
5556
  });
4917
- sub.on("ready", () => {
5557
+ this._listenBackplane(sub, "ready", () => {
4918
5558
  if (this._subDisconnectedAt !== null) {
4919
5559
  this.logger.debug("Backplane stream: consumer reconnected, resuming stream read", { lastId: this._lastStreamId });
4920
5560
  this._subDisconnectedAt = null;
4921
5561
  }
4922
5562
  });
4923
5563
  }
5564
+ const checkGap = async () => {
5565
+ if (this._lastStreamId === "$" || this._lastStreamId === "0-0" || typeof sub.xrange !== "function") return;
5566
+ const first = await sub.xrange(this.backplaneStreamKey, "-", "+", "COUNT", 1);
5567
+ const firstId = first?.[0]?.[0];
5568
+ if (!firstId) return;
5569
+ const [firstMs, firstSequence] = firstId.split("-").map(BigInt);
5570
+ const [lastMs, lastSequence] = this._lastStreamId.split("-").map(BigInt);
5571
+ if (firstMs > lastMs || firstMs === lastMs && firstSequence > lastSequence) this._resetAfterStreamGap();
5572
+ };
5573
+ const apply = (response) => {
5574
+ if (this._destroyed || !response) return;
5575
+ if (this._streamRecovering && response.some(([, entries]) => entries.length > 0)) {
5576
+ this.counters.streamReplays++;
5577
+ this._streamRecovering = false;
5578
+ }
5579
+ for (const [, entries] of response) {
5580
+ for (const [id, fields] of entries) {
5581
+ this._lastStreamId = id;
5582
+ this.counters.streamEntriesReceived++;
5583
+ this._processStreamEntry(fields);
5584
+ }
5585
+ }
5586
+ };
5587
+ let initialized = false;
5588
+ const initialize = async () => {
5589
+ if (typeof sub.connect === "function" && (sub.isOpen === false || sub.status === "wait")) await sub.connect();
5590
+ if (this._destroyed) return;
5591
+ if (this._lastStreamId === "$") {
5592
+ if (this._restoredSnapshot) this._resetAfterStreamGap();
5593
+ else if (typeof sub.xrevrange === "function") {
5594
+ const latest = await sub.xrevrange(this.backplaneStreamKey, "+", "-", "COUNT", 1);
5595
+ this._lastStreamId = latest?.[0]?.[0] ?? "0-0";
5596
+ } else this._lastStreamId = "0-0";
5597
+ }
5598
+ if (typeof sub.xrange === "function") {
5599
+ await checkGap();
5600
+ apply(await sub.xread("STREAMS", this.backplaneStreamKey, this._lastStreamId));
5601
+ }
5602
+ initialized = true;
5603
+ this._backplaneAvailable = true;
5604
+ };
5605
+ try {
5606
+ await initialize();
5607
+ } catch (error) {
5608
+ this._backplaneAvailable = false;
5609
+ this.logger.warn("Backplane stream initialization failed; retrying in consumer loop", { error: error.message });
5610
+ }
4924
5611
  const runLoop = async () => {
4925
5612
  while (!this._destroyed && !this._redisDisabled) {
4926
5613
  try {
5614
+ if (!initialized) await initialize();
5615
+ if (this._destroyed) break;
5616
+ await checkGap();
4927
5617
  const res = await sub.xread(
4928
5618
  "BLOCK",
4929
5619
  this.opts.backplaneStreamBlockMs,
@@ -4932,19 +5622,10 @@ return 0
4932
5622
  this._lastStreamId
4933
5623
  );
4934
5624
  if (this._destroyed) break;
5625
+ this._backplaneAvailable = true;
4935
5626
  if (res && res.length > 0) {
4936
- for (const [, entries] of res) {
4937
- if (entries.length > 0) {
4938
- if (this._lastStreamId !== "$") {
4939
- this.counters.streamReplays++;
4940
- }
4941
- for (const [id, fields] of entries) {
4942
- this._lastStreamId = id;
4943
- this.counters.streamEntriesReceived++;
4944
- this._processStreamEntry(fields);
4945
- }
4946
- }
4947
- }
5627
+ apply(res);
5628
+ this._backplaneAvailable = true;
4948
5629
  } else {
4949
5630
  await new Promise((resolve) => setTimeout(resolve, 10));
4950
5631
  }
@@ -4952,10 +5633,9 @@ return 0
4952
5633
  if (this._destroyed) break;
4953
5634
  const msg = err.message ?? "";
4954
5635
  if (msg.includes("NOGROUP") || msg.includes("smaller than") || msg.includes("trimmed")) {
4955
- this.counters.streamGaps++;
4956
- this.l1.clear();
4957
- this._lastStreamId = "$";
5636
+ this._resetAfterStreamGap();
4958
5637
  }
5638
+ this._backplaneAvailable = false;
4959
5639
  await new Promise((resolve) => setTimeout(resolve, 200));
4960
5640
  }
4961
5641
  }
@@ -4983,8 +5663,8 @@ return 0
4983
5663
  else if (f === "src") src = v;
4984
5664
  else if (f === "tagVersion") tagVersionRaw = v;
4985
5665
  }
4986
- const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
4987
- if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
5666
+ const validOp = op === "del" || op === "del-glob" || op === "tag_incr" || op === "tag_pattern_incr" || op === "tag_pattern_del";
5667
+ if (!validOp || typeof key !== "string" || !key || typeof src !== "string" || !src || (op === "del" || op === "del-glob") && this._namespace && !key.startsWith(`${this._namespace}:`)) {
4988
5668
  this.logger.warn("Backplane: rejected invalid stream entry", {
4989
5669
  op: String(op).slice(0, 40),
4990
5670
  key: typeof key === "string" ? key.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(key)
@@ -4993,8 +5673,8 @@ return 0
4993
5673
  }
4994
5674
  let tagVersion;
4995
5675
  if (tagVersionRaw !== void 0) {
4996
- const parsed = parseInt(tagVersionRaw, 10);
4997
- if (!Number.isFinite(parsed)) {
5676
+ const parsed = Number(tagVersionRaw);
5677
+ if (!Number.isSafeInteger(parsed) || parsed < 0) {
4998
5678
  this.logger.warn("Backplane: rejected stream entry with non-numeric tagVersion", { key });
4999
5679
  return;
5000
5680
  }
@@ -5012,16 +5692,10 @@ return 0
5012
5692
  this.l1.delete(key);
5013
5693
  this._bumpKeyMutation(key);
5014
5694
  this.inflight.delete(key);
5015
- this._pendingDiskDeletes.add(key);
5016
- setImmediate(() => {
5017
- try {
5018
- if (!this._diskDisabled) this.disk.delete(key);
5019
- } finally {
5020
- this._pendingDiskDeletes.delete(key);
5021
- }
5022
- });
5695
+ this._invalidateDiskKey(key);
5023
5696
  this._cascadeDependencies(key);
5024
5697
  } else if (op === "del-glob") {
5698
+ this._fenceInvalidation();
5025
5699
  this.l1.deletePattern(key);
5026
5700
  const pfx = key.endsWith("*") ? key.slice(0, -1) : key;
5027
5701
  for (const liveKey of this.l1.liveKeys()) {
@@ -5035,12 +5709,22 @@ return 0
5035
5709
  this.inflight.delete(inflightKey);
5036
5710
  }
5037
5711
  }
5038
- this._addPatternTombstone(pfx);
5712
+ this._addPatternTombstone(key);
5713
+ this._removePatternFromIndices(key);
5714
+ if (key === this.nk("*")) {
5715
+ this.tagIndex.clear();
5716
+ this.keyTags.clear();
5717
+ this.tagVersions.clear();
5718
+ this.dependencyIndex.clear();
5719
+ this.keyDependencies.clear();
5720
+ }
5039
5721
  } else if (op === "tag_incr") {
5722
+ this._fenceInvalidation();
5040
5723
  const tag = key;
5041
5724
  const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
5042
5725
  this._setLocalTagVersion(tag, ver, performance.now());
5043
5726
  } else if (op === "tag_pattern_incr") {
5727
+ this._fenceInvalidation();
5044
5728
  const pattern = key;
5045
5729
  const now = performance.now();
5046
5730
  for (const [tag, info] of this.tagVersions) {
@@ -5060,6 +5744,7 @@ return 0
5060
5744
  }
5061
5745
  }, 0);
5062
5746
  } else if (op === "tag_pattern_del") {
5747
+ this._fenceInvalidation();
5063
5748
  const pattern = key;
5064
5749
  const matchedTagKeys = [];
5065
5750
  const prefix = this.nk("_tag_:");
@@ -5070,14 +5755,7 @@ return 0
5070
5755
  for (const k of members) {
5071
5756
  this.l1.delete(k);
5072
5757
  this._bumpKeyMutation(k);
5073
- this._pendingDiskDeletes.add(k);
5074
- setImmediate(() => {
5075
- try {
5076
- if (!this._diskDisabled) this.disk.delete(k);
5077
- } finally {
5078
- this._pendingDiskDeletes.delete(k);
5079
- }
5080
- });
5758
+ this._invalidateDiskKey(k);
5081
5759
  }
5082
5760
  }
5083
5761
  }
@@ -5108,6 +5786,7 @@ return 0
5108
5786
  }
5109
5787
  }
5110
5788
  async publishInvalidation(op, key, tagVersion, isCrossRegionRelay = false, isExplicitInvalidation = false) {
5789
+ if (this.opts.l2WriteMode === "read-only") return;
5111
5790
  if (!isCrossRegionRelay && this.opts.crossRegion) {
5112
5791
  const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
5113
5792
  if (shouldBroadcast) {
@@ -5190,13 +5869,13 @@ return 0
5190
5869
  timestamp: Date.now(),
5191
5870
  namespace: this._namespace || void 0
5192
5871
  };
5193
- this.counters.crossRegionSent++;
5194
5872
  await cr.relay.broadcast(event);
5873
+ this.counters.crossRegionSent++;
5195
5874
  this.logger.debug("Cross-region invalidation broadcast", { op, key, region: cr.currentRegion });
5196
5875
  } catch (err) {
5197
- this.counters.crossRegionSent = Math.max(0, this.counters.crossRegionSent - 1);
5198
5876
  this.counters.crossRegionErrors++;
5199
5877
  this.logger.warn("Cross-region invalidation broadcast failed", { error: err.message });
5878
+ if (this.opts.awaitInvalidationBackplane) throw err;
5200
5879
  }
5201
5880
  }
5202
5881
  /**
@@ -5207,11 +5886,12 @@ return 0
5207
5886
  * Returns true if the event was accepted and applied, or false if ignored/deduplicated.
5208
5887
  */
5209
5888
  async receiveCrossRegionInvalidation(event) {
5889
+ this._assertActive("receiveCrossRegionInvalidation");
5210
5890
  const cr = this.opts.crossRegion;
5211
5891
  if (!cr) return false;
5212
- if (!event || typeof event !== "object" || !event.id || !event.originRegion || !event.op || !event.key) {
5892
+ if (!isCrossRegionInvalidationEvent(event)) {
5213
5893
  this.counters.crossRegionErrors++;
5214
- this.logger.warn("Cross-region: rejected invalid event payload", { event });
5894
+ this.logger.warn("Cross-region: rejected invalid event payload");
5215
5895
  return false;
5216
5896
  }
5217
5897
  if (event.originRegion === cr.currentRegion) {
@@ -5222,13 +5902,52 @@ return 0
5222
5902
  this.counters.crossRegionDeduplicated++;
5223
5903
  return false;
5224
5904
  }
5225
- this._markCrossRegionEventSeen(event.id);
5226
5905
  if (event.namespace !== void 0 && event.namespace !== (this._namespace || void 0)) {
5227
5906
  return false;
5228
5907
  }
5908
+ if ((event.op === "del" || event.op === "del-glob") && this._namespace && !event.key.startsWith(`${this._namespace}:`)) return false;
5909
+ this._markCrossRegionEventSeen(event.id);
5229
5910
  this.counters.crossRegionReceived++;
5230
- this._applyInvalidationEvent(event.op, event.key, event.tagVersion);
5231
- void this.publishInvalidation(event.op, event.key, event.tagVersion, true);
5911
+ const localTags = /* @__PURE__ */ new Set([...this.tagVersions.keys(), ...[...this.tagIndex.keys()].map((key) => this.unnk(key).replace(/^_tag_:/, ""))]);
5912
+ let version = event.tagVersion;
5913
+ if (event.op === "tag_incr") version = Math.max((this.tagVersions.get(event.key)?.version ?? 0) + 1, version ?? 0);
5914
+ this._applyInvalidationEvent(event.op, event.key, version);
5915
+ try {
5916
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
5917
+ const client = await this.getRedis();
5918
+ if (event.op === "del" || event.op === "del-glob") {
5919
+ await this._deleteRedisKeys(client, event.op === "del" ? [event.key] : await this._scanKeys(client, event.key));
5920
+ } else if (event.op === "tag_incr") {
5921
+ version = Number(await client.eval(LUA_RECEIVE_TAG_VERSION, 1, this.nk(`tag_ver:${event.key}`), String(version)));
5922
+ this._setLocalTagVersion(event.key, version);
5923
+ } else {
5924
+ const matched = await this._resolveMatchingTags(event.key, false);
5925
+ for (const tag of localTags) if (matchesTagPattern(event.key, tag)) matched.add(tag);
5926
+ for (const tag of matched) {
5927
+ if (event.op === "tag_pattern_incr") {
5928
+ const floor = this.tagVersions.get(tag)?.version ?? 1;
5929
+ const next = Number(await client.eval(LUA_RECEIVE_TAG_VERSION, 1, this.nk(`tag_ver:${tag}`), String(floor)));
5930
+ this._setLocalTagVersion(tag, next);
5931
+ await this.publishInvalidation("tag_incr", tag, next, true);
5932
+ } else {
5933
+ const tagKey = this.nk(`_tag_:${tag}`);
5934
+ const members = await client.smembers(tagKey);
5935
+ this._removeTagMembersLocal(members);
5936
+ await this._deleteRedisKeys(client, [...members, tagKey]);
5937
+ await Promise.all(members.map((key) => this.publishInvalidation("del", key, void 0, true)));
5938
+ }
5939
+ }
5940
+ }
5941
+ this.cb.onSuccess();
5942
+ }
5943
+ await this.publishInvalidation(event.op, event.key, version, true);
5944
+ } catch (error) {
5945
+ this._seenCrossRegionEvents.delete(event.id);
5946
+ this.counters.crossRegionErrors++;
5947
+ this.logger.warn("Cross-region regional invalidation failed", { error: error.message });
5948
+ if (this.opts.awaitInvalidationBackplane) throw error;
5949
+ return false;
5950
+ }
5232
5951
  this.logger.info("Cross-region invalidation applied", {
5233
5952
  op: event.op,
5234
5953
  key: event.key,
@@ -5243,25 +5962,269 @@ return 0
5243
5962
  const oldestKey = this.tagVersions.keys().next().value;
5244
5963
  if (oldestKey !== void 0) this.tagVersions.delete(oldestKey);
5245
5964
  }
5246
- this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
5965
+ this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now, refreshEpoch: this._tagRefreshEpoch });
5966
+ }
5967
+ async _isGenerationalEntryStale(tagVersions) {
5968
+ if (!tagVersions) return false;
5969
+ const tags = Object.keys(tagVersions);
5970
+ if (tags.length === 0) return false;
5971
+ const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5972
+ for (let i = 0; i < tags.length; i++) {
5973
+ if (currentVers[i] > tagVersions[tags[i]]) return true;
5974
+ }
5975
+ return false;
5976
+ }
5977
+ async _deleteRedisKeys(client, keys) {
5978
+ if (keys.length === 0) return;
5979
+ const CHUNK_SIZE = 1e3;
5980
+ if (client instanceof import_ioredis2.Cluster) {
5981
+ const groups = /* @__PURE__ */ new Map();
5982
+ for (const key of keys) {
5983
+ const slot = redisHashSlot(key);
5984
+ const master = client.slots?.[slot]?.[0] ?? String(slot);
5985
+ const members = groups.get(master) ?? [];
5986
+ members.push(key);
5987
+ groups.set(master, members);
5988
+ }
5989
+ await Promise.all([...groups.values()].map(async (members) => {
5990
+ for (let offset = 0; offset < members.length; offset += CHUNK_SIZE) {
5991
+ const pipeline = client.pipeline();
5992
+ for (const key of members.slice(offset, offset + CHUNK_SIZE)) pipeline.del(key);
5993
+ const result = await pipeline.exec();
5994
+ if (!result || result.some(([error]) => error)) throw new Error("Redis Cluster delete failed");
5995
+ }
5996
+ }));
5997
+ return;
5998
+ }
5999
+ for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
6000
+ const chunk = keys.slice(i, i + CHUNK_SIZE);
6001
+ await client.del(...chunk);
6002
+ }
6003
+ }
6004
+ async _parseGenerationalRedisHash(k, hashData) {
6005
+ if (!hashData || !hashData.d) return null;
6006
+ let storedTagVersions = {};
6007
+ if (hashData.tv) {
6008
+ try {
6009
+ const parsed = JSON.parse(hashData.tv);
6010
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || Object.values(parsed).some((version) => !Number.isSafeInteger(version) || Number(version) < 0)) return null;
6011
+ storedTagVersions = parsed;
6012
+ } catch {
6013
+ return null;
6014
+ }
6015
+ }
6016
+ if (await this._isGenerationalEntryStale(storedTagVersions)) {
6017
+ const setAtMs = parseInt(hashData.t, 10) || 0;
6018
+ this._deleteIfStale(k, setAtMs);
6019
+ return { stale: true };
6020
+ }
6021
+ const value = await this._decryptAndDeserialize(hashData.d);
6022
+ const expiresAt = Number(hashData.e);
6023
+ const staleAt = Number(hashData.s);
6024
+ let tags;
6025
+ let dependsOn;
6026
+ try {
6027
+ const parsedTags = hashData.tags ? JSON.parse(hashData.tags) : Object.keys(storedTagVersions);
6028
+ const parsedDependencies = hashData.deps ? JSON.parse(hashData.deps) : void 0;
6029
+ if (Array.isArray(parsedTags) && parsedTags.every((tag) => typeof tag === "string")) tags = parsedTags;
6030
+ if (Array.isArray(parsedDependencies) && parsedDependencies.every((pattern) => typeof pattern === "string")) dependsOn = parsedDependencies;
6031
+ } catch {
6032
+ return null;
6033
+ }
6034
+ return {
6035
+ value,
6036
+ tagVersions: storedTagVersions,
6037
+ stale: false,
6038
+ tags,
6039
+ dependsOn,
6040
+ setAt: Number(hashData.t) || void 0,
6041
+ expiresAt: Number.isFinite(expiresAt) && expiresAt > 0 ? expiresAt : void 0,
6042
+ staleAt: Number.isFinite(staleAt) && staleAt > 0 ? staleAt : void 0
6043
+ };
6044
+ }
6045
+ async _readRedisEntry(client, k, allowAutoPipeline = false) {
6046
+ const readStartedAt = Date.now();
6047
+ const read = async (hash) => allowAutoPipeline && this.opts.autoPipeline && this.pipeliner ? this.pipeliner.read(k, hash) : readRedisValue(client, k, hash);
6048
+ const withExpiry = (entry, ttlMs2) => {
6049
+ if (!entry || ttlMs2 === -2 || ttlMs2 === 0) return null;
6050
+ if (ttlMs2 !== void 0 && Number.isFinite(ttlMs2) && ttlMs2 > 0) {
6051
+ entry.expiresAt = Math.min(entry.expiresAt ?? Infinity, readStartedAt + ttlMs2);
6052
+ }
6053
+ return entry.expiresAt !== void 0 && entry.expiresAt <= Date.now() ? null : entry;
6054
+ };
6055
+ if (this.opts.tagStrategy === "generational" && typeof client.hgetall === "function") {
6056
+ try {
6057
+ const { raw: hashData, ttlMs: ttlMs2 } = await read(true);
6058
+ if (typeof hashData === "string") {
6059
+ const value2 = await this._decryptAndDeserialize(hashData);
6060
+ return withExpiry({ value: value2, stale: false }, ttlMs2);
6061
+ }
6062
+ if (hashData && hashData.d) {
6063
+ return withExpiry(await this._parseGenerationalRedisHash(k, hashData), ttlMs2);
6064
+ }
6065
+ return null;
6066
+ } catch (err) {
6067
+ const msg = err instanceof Error ? err.message : String(err);
6068
+ if (!msg.includes("WRONGTYPE")) throw err;
6069
+ }
6070
+ }
6071
+ const { raw, ttlMs } = await read(false);
6072
+ if (raw == null) return null;
6073
+ if (typeof raw !== "string") return null;
6074
+ const value = await this._decryptAndDeserialize(raw);
6075
+ return withExpiry({ value, stale: false }, ttlMs);
5247
6076
  }
5248
6077
  async _getTagVersion(tag) {
5249
6078
  const now = performance.now();
5250
6079
  const local = this.tagVersions.get(tag);
5251
- if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
6080
+ if (local && (local.refreshEpoch ?? 0) === this._tagRefreshEpoch && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
5252
6081
  return local.version;
5253
6082
  }
5254
6083
  if (!this._redisDisabled) {
5255
6084
  try {
5256
6085
  const client = await this.getRedis();
5257
6086
  const raw = await client.get(this.nk(`tag_ver:${tag}`));
5258
- const version = raw ? parseInt(raw, 10) : 0;
5259
- this._setLocalTagVersion(tag, version, now);
5260
- return version;
6087
+ const parsed = raw ? Number(raw) : 0;
6088
+ if (!Number.isSafeInteger(parsed) || parsed < 0) throw new Error("Invalid Redis tag generation");
6089
+ const version2 = Math.max(this.tagVersions.get(tag)?.version ?? 0, parsed);
6090
+ if (this.opts.l2WriteMode === "read-write") {
6091
+ if (raw === null) await client.set(this.nk(`tag_ver:${tag}`), String(version2), "NX");
6092
+ else if (version2 > parsed) await client.eval(LUA_MAX_TAG_VERSION, 1, this.nk(`tag_ver:${tag}`), String(version2));
6093
+ }
6094
+ this._setLocalTagVersion(tag, version2, now);
6095
+ this.cb.onSuccess();
6096
+ return version2;
5261
6097
  } catch {
5262
6098
  }
5263
6099
  }
5264
- return local?.version ?? 0;
6100
+ const version = this.tagVersions.get(tag)?.version ?? local?.version ?? 0;
6101
+ if (this._redisDisabled) this._setLocalTagVersion(tag, version, now);
6102
+ return version;
6103
+ }
6104
+ async _readRedisBatch(client, keys) {
6105
+ const entries = /* @__PURE__ */ new Map();
6106
+ const groups = /* @__PURE__ */ new Map();
6107
+ for (const key of new Set(keys)) {
6108
+ const group = client instanceof import_ioredis2.Cluster ? client.slots[redisHashSlot(key)]?.[0] ?? String(redisHashSlot(key)) : "single";
6109
+ const members = groups.get(group) ?? [];
6110
+ members.push(key);
6111
+ groups.set(group, members);
6112
+ }
6113
+ await Promise.all([...groups.values()].map(async (members) => {
6114
+ for (let offset = 0; offset < members.length; offset += 1e3) {
6115
+ const chunk = members.slice(offset, offset + 1e3);
6116
+ const pipeline = typeof client.pipeline === "function" ? client.pipeline() : client.multi();
6117
+ const timedScripts = typeof pipeline.eval === "function";
6118
+ const hashes = this.opts.tagStrategy === "generational" && typeof pipeline.hgetall === "function";
6119
+ for (const key of chunk) {
6120
+ if (timedScripts) pipeline.eval(LUA_READ_CACHE_ENTRY, 1, key);
6121
+ else if (hashes) pipeline.hgetall(key);
6122
+ else pipeline.get(key);
6123
+ }
6124
+ const startedAt = Date.now();
6125
+ const start = performance.now();
6126
+ const results = await pipeline.exec();
6127
+ this.watchdog.recordRedis(performance.now() - start);
6128
+ if (!results) throw new Error("Redis batch read aborted");
6129
+ for (let index = 0; index < chunk.length; index++) {
6130
+ try {
6131
+ const tuple = results[index];
6132
+ if (!tuple) continue;
6133
+ let [error, raw] = tuple;
6134
+ let ttl;
6135
+ if (error?.message?.includes("WRONGTYPE")) {
6136
+ const fallback = await this._readRedisEntry(client, chunk[index]);
6137
+ if (fallback && !fallback.stale) entries.set(chunk[index], fallback);
6138
+ continue;
6139
+ }
6140
+ if (error) continue;
6141
+ if (timedScripts) {
6142
+ if (!Array.isArray(raw) || raw[0] === "none") continue;
6143
+ const kind = raw[0];
6144
+ ttl = Number(raw[2]);
6145
+ const payload = raw[1];
6146
+ if (kind === "hash") {
6147
+ if (!Array.isArray(payload) || payload.length % 2 !== 0) continue;
6148
+ raw = Object.fromEntries(Array.from({ length: payload.length / 2 }, (_unused, i) => [String(payload[i * 2]), String(payload[i * 2 + 1])]));
6149
+ } else if (kind === "string") raw = payload;
6150
+ else continue;
6151
+ if (ttl === -2 || ttl === 0) continue;
6152
+ }
6153
+ 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;
6154
+ if (!entry || entry.stale) continue;
6155
+ if (ttl !== void 0 && ttl > 0) entry.expiresAt = Math.min(entry.expiresAt ?? Infinity, startedAt + ttl);
6156
+ if (entry.expiresAt !== void 0 && entry.expiresAt <= Date.now()) continue;
6157
+ entries.set(chunk[index], entry);
6158
+ } catch (error) {
6159
+ this.logger.debug("mget: skipping invalid remote entry", { key: chunk[index], error: error.message });
6160
+ }
6161
+ }
6162
+ }
6163
+ }));
6164
+ this.cb.onSuccess();
6165
+ return entries;
6166
+ }
6167
+ _promoteRedisEntry(key, entry, fallbackTtlMs, priority) {
6168
+ const expiresAt = entry.expiresAt ?? Date.now() + fallbackTtlMs;
6169
+ if (expiresAt <= Date.now()) return false;
6170
+ const admitted = this.l1.set(
6171
+ key,
6172
+ entry.value,
6173
+ expiresAt - Date.now(),
6174
+ priority,
6175
+ entry.staleAt,
6176
+ void 0,
6177
+ entry.tagVersions,
6178
+ entry.setAt,
6179
+ entry.tags,
6180
+ entry.dependsOn
6181
+ );
6182
+ if (admitted) this._restoreEntryMetadata(key, { ...entry, expiresAt });
6183
+ return true;
6184
+ }
6185
+ async _readDiskEntry(key, epoch) {
6186
+ if (this._diskDisabled || this._pendingDiskDeletes.has(key) || !this.watchdog.isDiskAllowed()) return null;
6187
+ const start = performance.now();
6188
+ const entry = this.disk.load(key);
6189
+ const elapsed = performance.now() - start;
6190
+ this.watchdog.recordDisk(elapsed);
6191
+ this.watchdog.onCanaryResult(entry !== null, elapsed);
6192
+ 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;
6193
+ this.l1.importEntries([{ key, entry }], this.opts.forbiddenSnapshotPrefixes);
6194
+ const hit = this.l1.get(key);
6195
+ const value = hit ? hit.value : entry.isCompressed ? this.codec.decode(entry.data) : JSON.parse(entry.data);
6196
+ this._restoreEntryMetadata(key, entry);
6197
+ return { value, entry };
6198
+ }
6199
+ /** Common write policy and metadata across get/set/revalidation/draining. */
6200
+ async _writeRedisEntry(key, data, expiresAt, setAt, tagVersions, staleAt, tags, dependsOn, canCommit = () => true) {
6201
+ if (this._redisDisabled || this.opts.l2WriteMode !== "read-write" || !canCommit() || this._destroyed) return;
6202
+ const client = await this.getRedis();
6203
+ const stored = await this._serializeAndEncrypt(JSON.stringify(data) ?? "undefined");
6204
+ if (!canCommit() || this._destroyed) return;
6205
+ const useHash = this.opts.tagStrategy === "generational" && (tagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function");
6206
+ const remaining = (useHash ? expiresAt : staleAt ?? expiresAt) - Date.now();
6207
+ if (remaining <= 0) return;
6208
+ const ttl = Math.max(1, Math.ceil(remaining / 1e3));
6209
+ if (useHash) {
6210
+ const transaction = client.multi();
6211
+ transaction.del(key);
6212
+ const hash = { d: stored, t: String(setAt), tv: JSON.stringify(tagVersions ?? {}), e: String(expiresAt) };
6213
+ if (staleAt !== void 0) hash.s = String(staleAt);
6214
+ if (tags?.length) hash.tags = JSON.stringify(tags);
6215
+ if (dependsOn?.length) hash.deps = JSON.stringify(dependsOn);
6216
+ transaction.hset(key, hash);
6217
+ transaction.expire(key, ttl);
6218
+ const result = await transaction.exec();
6219
+ if (!result || result.some(([error]) => error)) throw new Error("Redis cache write transaction failed");
6220
+ } else if (this.opts.autoPipeline && this.pipeliner) {
6221
+ if (typeof client.pttl === "function" && typeof client.set === "function") await this.pipeliner.setpx(key, Math.ceil(remaining), stored);
6222
+ else await this.pipeliner.setex(key, ttl, stored);
6223
+ } else {
6224
+ if (typeof client.pttl === "function" && typeof client.set === "function") await client.set(key, stored, "PX", Math.ceil(remaining));
6225
+ else await client.setex(key, ttl, stored);
6226
+ }
6227
+ this.cb.onSuccess();
5265
6228
  }
5266
6229
  _deleteIfStale(k, setAtMs) {
5267
6230
  this.l1.deleteIfSetBefore(k, setAtMs);
@@ -5314,7 +6277,7 @@ return 0
5314
6277
  } else {
5315
6278
  plain = raw;
5316
6279
  }
5317
- return JSON.parse(plain);
6280
+ return plain === "undefined" ? void 0 : JSON.parse(plain);
5318
6281
  }
5319
6282
  /**
5320
6283
  * Scan all keys matching `pattern` across single-node or Cluster clients.
@@ -5322,7 +6285,7 @@ return 0
5322
6285
  */
5323
6286
  async _scanKeys(client, pattern) {
5324
6287
  const keys = [];
5325
- if (client instanceof import_ioredis.Cluster) {
6288
+ if (client instanceof import_ioredis2.Cluster) {
5326
6289
  const masters = client.nodes("master");
5327
6290
  await Promise.all(masters.map(
5328
6291
  (node) => new Promise((resolve, reject) => {
@@ -5382,10 +6345,10 @@ return 0
5382
6345
  return client;
5383
6346
  }
5384
6347
  this.redisConnecting = (async () => {
6348
+ let client = null;
5385
6349
  try {
5386
- let client;
5387
6350
  if (this.opts.redisClusterNodes?.length) {
5388
- client = new import_ioredis.Cluster(this.opts.redisClusterNodes, {
6351
+ client = new import_ioredis2.Cluster(this.opts.redisClusterNodes, {
5389
6352
  redisOptions: {
5390
6353
  tls: this.opts.redisTls ? {} : void 0,
5391
6354
  connectTimeout: 1e4,
@@ -5405,7 +6368,7 @@ return 0
5405
6368
  });
5406
6369
  client.on("reconnecting", () => this.logger.debug("Redis Cluster reconnecting"));
5407
6370
  } else if (this.opts.redisSentinel) {
5408
- client = new import_ioredis.Redis({
6371
+ client = new import_ioredis2.Redis({
5409
6372
  sentinels: this.opts.redisSentinel.sentinels,
5410
6373
  name: this.opts.redisSentinel.name,
5411
6374
  tls: this.opts.redisTls ? {} : void 0,
@@ -5425,7 +6388,7 @@ return 0
5425
6388
  });
5426
6389
  client.on("reconnecting", () => this.logger.debug("Redis Sentinel reconnecting"));
5427
6390
  } else {
5428
- client = new import_ioredis.Redis({
6391
+ client = new import_ioredis2.Redis({
5429
6392
  host: this.opts.redisHost,
5430
6393
  port: this.opts.redisPort,
5431
6394
  tls: this.opts.redisTls ? {} : void 0,
@@ -5446,14 +6409,45 @@ return 0
5446
6409
  });
5447
6410
  client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
5448
6411
  }
6412
+ const pendingClient = client;
5449
6413
  await new Promise((resolve, reject) => {
5450
- client.once("ready", resolve);
5451
- client.once("error", (e) => {
6414
+ let settled = false;
6415
+ const cleanupListeners = () => {
6416
+ pendingClient.removeListener?.("ready", onReady);
6417
+ pendingClient.removeListener?.("error", onError);
6418
+ };
6419
+ const onReady = () => {
6420
+ if (settled) return;
6421
+ settled = true;
6422
+ clearTimeout(timer);
6423
+ cleanupListeners();
6424
+ resolve();
6425
+ };
6426
+ const onError = (e) => {
6427
+ if (settled) return;
6428
+ settled = true;
6429
+ clearTimeout(timer);
6430
+ cleanupListeners();
5452
6431
  this._checkAndLogResp3Hint(e);
5453
6432
  reject(e);
5454
- });
5455
- setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
6433
+ };
6434
+ const timer = setTimeout(() => {
6435
+ if (settled) return;
6436
+ settled = true;
6437
+ cleanupListeners();
6438
+ reject(new Error("Redis connection timeout"));
6439
+ }, 15e3);
6440
+ if (timer.unref) timer.unref();
6441
+ pendingClient.once("ready", onReady);
6442
+ pendingClient.once("error", onError);
5456
6443
  });
6444
+ if (this._destroyed) {
6445
+ try {
6446
+ client.disconnect();
6447
+ } catch {
6448
+ }
6449
+ this._assertActive("getRedis");
6450
+ }
5457
6451
  this.cb.onSuccess();
5458
6452
  this.redis = client;
5459
6453
  this.pipeliner = new AutoPipeliner(client, {
@@ -5463,6 +6457,10 @@ return 0
5463
6457
  this.redisConnecting = null;
5464
6458
  return client;
5465
6459
  } catch (err) {
6460
+ try {
6461
+ client?.disconnect();
6462
+ } catch {
6463
+ }
5466
6464
  this.cb.onFailure();
5467
6465
  this.redisConnecting = null;
5468
6466
  this._checkAndLogResp3Hint(err);
@@ -5482,7 +6480,12 @@ return 0
5482
6480
  try {
5483
6481
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
5484
6482
  if (entries.length === 0) return;
5485
- const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
6483
+ const payload = {
6484
+ version: SNAPSHOT_VERSION,
6485
+ writtenAt: Date.now(),
6486
+ entries,
6487
+ streamId: this.opts.backplaneMode === "stream" && this._lastStreamId !== "$" ? this._lastStreamId : void 0
6488
+ };
5486
6489
  const packed = this.codec.encode(payload);
5487
6490
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
5488
6491
  const dest = altPath ?? this.opts.snapshotPath;
@@ -5550,6 +6553,9 @@ return 0
5550
6553
  return;
5551
6554
  }
5552
6555
  const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
6556
+ this._restoredSnapshot ||= loaded > 0;
6557
+ if (typeof snapshot.streamId === "string" && /^\d{1,20}-\d{1,20}$/.test(snapshot.streamId)) this._lastStreamId = snapshot.streamId;
6558
+ for (const { key, entry } of snapshot.entries) if (this.l1.has(key)) this._restoreEntryMetadata(key, entry);
5553
6559
  this.logger.info("Cache snapshot loaded (L1 is warm)", {
5554
6560
  loaded,
5555
6561
  total: snapshot.entries.length,
@@ -5574,7 +6580,12 @@ return 0
5574
6580
  try {
5575
6581
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
5576
6582
  if (entries.length === 0) return false;
5577
- const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
6583
+ const payload = {
6584
+ version: SNAPSHOT_VERSION,
6585
+ writtenAt: Date.now(),
6586
+ entries,
6587
+ streamId: this.opts.backplaneMode === "stream" && this._lastStreamId !== "$" ? this._lastStreamId : void 0
6588
+ };
5578
6589
  const packed = this.codec.encode(payload);
5579
6590
  let final;
5580
6591
  if (this.opts.remoteSnapshot.envelope) {
@@ -5605,13 +6616,16 @@ return 0
5605
6616
  async loadRemoteSnapshot() {
5606
6617
  if (!this.opts.remoteSnapshot) return 0;
5607
6618
  const maxAgeMs = this.opts.remoteSnapshot.maxAgeMs ?? this.opts.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE;
6619
+ const epoch = this._globalEpoch;
5608
6620
  try {
5609
6621
  const raw = await this.opts.remoteSnapshot.adapter.get();
6622
+ if (this._destroyed || this._globalEpoch !== epoch) return 0;
5610
6623
  if (!raw || raw.length === 0) {
5611
6624
  this.logger.debug("Remote snapshot not found or empty \u2014 starting cold");
5612
6625
  return 0;
5613
6626
  }
5614
6627
  const rawBuf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
6628
+ if (rawBuf.length > SNAPSHOT_MAX_FILE_BYTES) throw new Error("Remote snapshot exceeds size limit");
5615
6629
  let buf;
5616
6630
  try {
5617
6631
  if (EnvelopeEncryption.isEnvelope(rawBuf)) {
@@ -5657,7 +6671,12 @@ return 0
5657
6671
  this.logger.warn("Remote snapshot rejected: entries is not an array");
5658
6672
  return 0;
5659
6673
  }
5660
- const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
6674
+ if (this._destroyed || this._globalEpoch !== epoch) return 0;
6675
+ const eligible = snapshot.entries.filter((item) => item && !this._keyMutationEpochs.has(item.key));
6676
+ const loaded = this.l1.importEntries(eligible, this.opts.forbiddenSnapshotPrefixes);
6677
+ this._restoredSnapshot ||= loaded > 0;
6678
+ if (typeof snapshot.streamId === "string" && /^\d{1,20}-\d{1,20}$/.test(snapshot.streamId)) this._lastStreamId = snapshot.streamId;
6679
+ for (const { key, entry } of eligible) if (this.l1.has(key)) this._restoreEntryMetadata(key, entry);
5661
6680
  this.counters.remoteSnapshotDownloads++;
5662
6681
  this.counters.remoteSnapshotLastDownloadedAt = Date.now();
5663
6682
  this.logger.info("Remote cache snapshot loaded (L1 hydrated)", {
@@ -5706,20 +6725,10 @@ return 0
5706
6725
  const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
5707
6726
  const l1Hit = this.l1.get(k);
5708
6727
  if (l1Hit !== null) {
5709
- let isGenerationalStale = false;
5710
- if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
5711
- const tags = Object.keys(l1Hit.tagVersions);
5712
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5713
- for (let i = 0; i < tags.length; i++) {
5714
- if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
5715
- isGenerationalStale = true;
5716
- break;
5717
- }
5718
- }
5719
- }
6728
+ const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
5720
6729
  if (isGenerationalStale) {
5721
6730
  this._deleteIfStale(k, l1Hit.setAt ?? 0);
5722
- } else {
6731
+ } else if (!l1Hit.isStale || optSwr > 0) {
5723
6732
  if (l1Hit.isStale) {
5724
6733
  const swrGraceMs2 = optSwr * 1e3;
5725
6734
  if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
@@ -5782,115 +6791,58 @@ return 0
5782
6791
  this.counters.stampedes++;
5783
6792
  this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch/read", { cacheKey });
5784
6793
  span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
5785
- return existing;
6794
+ return this._prepareReadValue(await existing);
5786
6795
  }
5787
6796
  const mutationEpochAtStart = this._getKeyMutationEpoch(k);
5788
- const executionPromise = (async () => {
6797
+ const executionPromise = Promise.resolve().then(async () => {
5789
6798
  try {
5790
- if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
5791
- if (this._isTombstonedByPattern(k)) {
5792
- try {
5793
- this.disk.delete(k);
5794
- } catch {
5795
- }
5796
- } else {
5797
- const isDiskAllowed = this.watchdog.isDiskAllowed();
5798
- if (isDiskAllowed) {
5799
- const diskStart = performance.now();
5800
- const diskHit = this.disk.load(k);
5801
- const diskElapsed = performance.now() - diskStart;
5802
- this.watchdog.recordDisk(diskElapsed);
5803
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
5804
- if (diskHit !== null) {
5805
- let isDiskStale = false;
5806
- if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
5807
- const tags = Object.keys(diskHit.tagVersions);
5808
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5809
- for (let i = 0; i < tags.length; i++) {
5810
- if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
5811
- isDiskStale = true;
5812
- break;
5813
- }
5814
- }
5815
- }
5816
- if (isDiskStale) {
5817
- this.disk.delete(k);
5818
- } else {
5819
- const promoted = this.l1.importEntries(
5820
- [{ key: k, entry: diskHit }],
5821
- this.opts.forbiddenSnapshotPrefixes
5822
- );
5823
- if (promoted > 0) {
5824
- const l1Check = this.l1.get(k);
5825
- if (l1Check !== null) {
5826
- this.counters.diskHits++;
5827
- this.opts.onHit?.(cacheKey, "disk");
5828
- this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
5829
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
5830
- if (this.opts.frozen) deepFreeze(l1Check.value);
5831
- return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
5832
- }
5833
- }
5834
- }
5835
- }
5836
- }
6799
+ const diskHit = await this._readDiskEntry(k, mutationEpochAtStart);
6800
+ if (diskHit && (diskHit.entry.staleAt === void 0 || diskHit.entry.staleAt > Date.now() || optSwr > 0)) {
6801
+ this.counters.diskHits++;
6802
+ this.opts.onHit?.(cacheKey, "disk");
6803
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
6804
+ if (diskHit.entry.staleAt !== void 0 && diskHit.entry.staleAt <= Date.now() && optSwr > 0 && !this.revalidating.has(k)) {
6805
+ this.revalidating.add(k);
6806
+ this.counters.swrRevalidations++;
6807
+ void this._revalidate(
6808
+ k,
6809
+ fetchFn,
6810
+ ttlMs,
6811
+ swrGraceMs,
6812
+ priority,
6813
+ diskHit.entry.tagVersions ?? Object.fromEntries((diskHit.entry.tags ?? []).map((tag) => [tag, 0]))
6814
+ );
5837
6815
  }
6816
+ return diskHit.value;
5838
6817
  }
5839
6818
  if (!this._redisDisabled) {
5840
6819
  try {
5841
6820
  const client = await this.getRedis();
5842
6821
  const redisStart = performance.now();
5843
- if (this.opts.tagStrategy === "generational") {
5844
- const hashData = await client.hgetall(k);
5845
- const redisElapsed = performance.now() - redisStart;
5846
- this.watchdog.recordRedis(redisElapsed);
5847
- this.cb.onSuccess();
5848
- if (hashData && hashData.d) {
5849
- let isStale = false;
5850
- let storedTagVersions = {};
5851
- if (hashData.tv) {
5852
- try {
5853
- storedTagVersions = JSON.parse(hashData.tv);
5854
- } catch {
5855
- }
5856
- }
5857
- const tags = Object.keys(storedTagVersions);
5858
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5859
- for (let i = 0; i < tags.length; i++) {
5860
- if (currentVers[i] > storedTagVersions[tags[i]]) {
5861
- isStale = true;
5862
- break;
5863
- }
5864
- }
5865
- if (isStale) {
5866
- const setAtMs = parseInt(hashData.t, 10) || 0;
5867
- this._deleteIfStale(k, setAtMs);
5868
- } else {
5869
- const parsed = await this._decryptAndDeserialize(hashData.d);
5870
- this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
5871
- this.counters.l2Hits++;
5872
- this.opts.onHit?.(cacheKey, "l2");
5873
- this.logger.debug("L2 hit (Redis hash)", { cacheKey });
5874
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5875
- if (this.opts.frozen) deepFreeze(parsed);
5876
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
5877
- }
6822
+ const redisHit = await this._readRedisEntry(client, k, true);
6823
+ const redisElapsed = performance.now() - redisStart;
6824
+ this.watchdog.recordRedis(redisElapsed);
6825
+ this.cb.onSuccess();
6826
+ if (redisHit && !redisHit.stale && (redisHit.staleAt === void 0 || redisHit.staleAt > Date.now() || optSwr > 0)) {
6827
+ const parsed = redisHit.value;
6828
+ if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
6829
+ this.logger.debug("Aborting L2 promotion \u2014 key was mutated or deleted during Redis read", { cacheKey });
6830
+ span.setAttribute("cache.aborted_mutation_race", true);
6831
+ const current = this.l1.get(k);
6832
+ const liveVal = current && !current.isStale ? current.value : parsed;
6833
+ return liveVal;
5878
6834
  }
5879
- } else {
5880
- const raw = this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
5881
- const redisElapsed = performance.now() - redisStart;
5882
- this.watchdog.recordRedis(redisElapsed);
5883
- this.cb.onSuccess();
5884
- if (raw) {
5885
- const parsed = await this._decryptAndDeserialize(raw);
5886
- this.l1.set(k, parsed, ttlMs, priority);
5887
- this.counters.l2Hits++;
5888
- this.opts.onHit?.(cacheKey, "l2");
5889
- this.logger.debug("L2 hit (Redis)", { cacheKey });
5890
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5891
- if (this.opts.frozen) deepFreeze(parsed);
5892
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
6835
+ if (!this._promoteRedisEntry(k, redisHit, ttlMs, priority)) throw new Error("Redis entry expired during promotion");
6836
+ this.counters.l2Hits++;
6837
+ this.opts.onHit?.(cacheKey, "l2");
6838
+ this.logger.debug(redisHit.tagVersions ? "L2 hit (Redis hash)" : "L2 hit (Redis)", { cacheKey });
6839
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
6840
+ if (redisHit.staleAt !== void 0 && redisHit.staleAt <= Date.now() && optSwr > 0 && !this.revalidating.has(k)) {
6841
+ this.revalidating.add(k);
6842
+ this.counters.swrRevalidations++;
6843
+ void this._revalidate(k, fetchFn, ttlMs, swrGraceMs, priority, redisHit.tagVersions);
5893
6844
  }
6845
+ return parsed;
5894
6846
  }
5895
6847
  } catch (err) {
5896
6848
  this.cb.onFailure();
@@ -5900,6 +6852,7 @@ return 0
5900
6852
  span.setAttribute("cache.hit", false).setAttribute("cache.hit_tier", "miss");
5901
6853
  this.opts.onMiss?.(cacheKey);
5902
6854
  this.counters.fetches++;
6855
+ const tagSnapshot = this.opts.tagStrategy === "generational" && optTags?.length ? Object.fromEntries(await Promise.all(optTags.map(async (tag) => [tag, await this._getTagVersion(tag)]))) : void 0;
5903
6856
  const fetchStart = Date.now();
5904
6857
  let data;
5905
6858
  try {
@@ -5928,50 +6881,41 @@ return 0
5928
6881
  }
5929
6882
  const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
5930
6883
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
5931
- let activeTagVersions;
6884
+ const activeTagVersions = tagSnapshot;
5932
6885
  if (optTags?.length) {
5933
6886
  if (this.opts.tagStrategy === "generational") {
5934
- const vers = await Promise.all(optTags.map((tag) => this._getTagVersion(tag)));
5935
- activeTagVersions = {};
5936
- for (let i = 0; i < optTags.length; i++) {
5937
- activeTagVersions[optTags[i]] = vers[i];
5938
- }
6887
+ if (await this._isGenerationalEntryStale(tagSnapshot)) return data;
5939
6888
  } else {
5940
- await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
6889
+ await this._registerTags(k, optTags, Math.ceil(storeTtl / 1e3));
5941
6890
  }
5942
6891
  }
5943
6892
  if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
5944
6893
  this.logger.debug("Aborting in-flight cache commit \u2014 key was mutated or deleted during fetch", { cacheKey });
5945
6894
  span.setAttribute("cache.aborted_mutation_race", true);
5946
6895
  const current = this.l1.get(k);
5947
- if (current && !current.isStale && current.value !== void 0) {
6896
+ if (current && !current.isStale) {
5948
6897
  const freshVal = current.value;
5949
- if (this.opts.frozen) deepFreeze(freshVal);
5950
- return this.opts.cloneStrategy === "structuredClone" && freshVal != null && typeof freshVal === "object" ? structuredClone(freshVal) : freshVal;
6898
+ return freshVal;
5951
6899
  }
5952
- if (this.opts.frozen) deepFreeze(data);
5953
- return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
6900
+ return data;
5954
6901
  }
5955
- this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
5956
- if (!this._redisDisabled) {
6902
+ const writeTs = Date.now();
6903
+ this._invalidateDiskKey(k);
6904
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs, optTags, opts.dependsOn);
6905
+ this._restoreEntryMetadata(k, { tags: optTags, dependsOn: opts.dependsOn, expiresAt: writeTs + storeTtl });
6906
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
5957
6907
  try {
5958
- const client = await this.getRedis();
5959
- const serialized = JSON.stringify(data);
5960
- const toStore = await this._serializeAndEncrypt(serialized);
5961
- const ttlSec = Math.ceil(effectiveTtl / 1e3);
5962
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
5963
- const now = Date.now();
5964
- const tx = client.multi();
5965
- tx.hset(k, {
5966
- d: toStore,
5967
- t: String(now),
5968
- tv: JSON.stringify(activeTagVersions)
5969
- });
5970
- tx.expire(k, ttlSec);
5971
- await tx.exec();
5972
- } else {
5973
- await client.setex(k, ttlSec, toStore);
5974
- }
6908
+ await this._writeRedisEntry(
6909
+ k,
6910
+ data,
6911
+ writeTs + storeTtl,
6912
+ writeTs,
6913
+ activeTagVersions,
6914
+ staleAt,
6915
+ optTags,
6916
+ opts.dependsOn,
6917
+ () => this._getKeyMutationEpoch(k) === mutationEpochAtStart
6918
+ );
5975
6919
  this.cb.onSuccess();
5976
6920
  this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
5977
6921
  } catch {
@@ -5981,15 +6925,14 @@ return 0
5981
6925
  } else {
5982
6926
  this.logger.debug("Cached L1", { cacheKey });
5983
6927
  }
5984
- if (this.opts.frozen) deepFreeze(data);
5985
- return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
6928
+ return data;
5986
6929
  } finally {
5987
- this.inflight.delete(k);
6930
+ if (this.inflight.get(k) === executionPromise) this.inflight.delete(k);
5988
6931
  span.end();
5989
6932
  }
5990
- })();
6933
+ });
5991
6934
  this.inflight.set(k, executionPromise);
5992
- return executionPromise;
6935
+ return this._prepareReadValue(await executionPromise);
5993
6936
  }
5994
6937
  /**
5995
6938
  * Graceful shutdown flusher for Kubernetes preStop hooks, NestJS onApplicationShutdown,
@@ -6070,6 +7013,9 @@ return 0
6070
7013
  }
6071
7014
  async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority, knownTagVersions) {
6072
7015
  const startEpoch = this._getKeyMutationEpoch(cacheKey);
7016
+ const previous = this.l1.getEntry(cacheKey);
7017
+ const tags = previous?.tags ?? Object.keys(knownTagVersions ?? {});
7018
+ const dependencies = previous?.dependsOn;
6073
7019
  try {
6074
7020
  const fetchStart = Date.now();
6075
7021
  const data = await fetchFn();
@@ -6084,14 +7030,14 @@ return 0
6084
7030
  const l1Existing = this.l1.get(cacheKey);
6085
7031
  const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
6086
7032
  if (this.opts.tagStrategy === "generational" && tagVersionsSource) {
6087
- const tags = Object.keys(tagVersionsSource);
6088
- const vers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
7033
+ const tags2 = Object.keys(tagVersionsSource);
7034
+ const vers = await Promise.all(tags2.map((tag) => this._getTagVersion(tag)));
6089
7035
  activeTagVersions = {};
6090
- for (let i = 0; i < tags.length; i++) {
6091
- activeTagVersions[tags[i]] = vers[i];
7036
+ for (let i = 0; i < tags2.length; i++) {
7037
+ activeTagVersions[tags2[i]] = vers[i];
6092
7038
  }
6093
7039
  if (knownTagVersions) {
6094
- for (const t of tags) {
7040
+ for (const t of tags2) {
6095
7041
  if (knownTagVersions[t] !== void 0 && activeTagVersions[t] !== knownTagVersions[t]) {
6096
7042
  this.logger.debug("SWR: aborting revalidation commit \u2014 tag version bumped during revalidation", { cacheKey, tag: t });
6097
7043
  return;
@@ -6103,32 +7049,29 @@ return 0
6103
7049
  this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
6104
7050
  return;
6105
7051
  }
6106
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
7052
+ const writeTs = Date.now();
7053
+ this._invalidateDiskKey(cacheKey);
7054
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs, tags, dependencies);
7055
+ this._restoreEntryMetadata(cacheKey, { tags, dependsOn: dependencies, expiresAt: writeTs + ttlMs + swrGraceMs });
6107
7056
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6108
7057
  try {
6109
- const client = await this.getRedis();
6110
- const s = JSON.stringify(data);
6111
- const stored = await this._serializeAndEncrypt(s);
6112
- const ttlSec = Math.ceil(ttlMs / 1e3);
6113
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
6114
- const now = Date.now();
6115
- const tx = client.multi();
6116
- tx.hset(cacheKey, {
6117
- d: stored,
6118
- t: String(now),
6119
- tv: JSON.stringify(activeTagVersions)
6120
- });
6121
- tx.expire(cacheKey, ttlSec);
6122
- await tx.exec();
6123
- } else {
6124
- await client.setex(cacheKey, ttlSec, stored);
6125
- }
7058
+ await this._writeRedisEntry(
7059
+ cacheKey,
7060
+ data,
7061
+ writeTs + ttlMs + swrGraceMs,
7062
+ writeTs,
7063
+ activeTagVersions,
7064
+ staleAt,
7065
+ tags,
7066
+ dependencies,
7067
+ () => this._getKeyMutationEpoch(cacheKey) === startEpoch
7068
+ );
6126
7069
  } catch {
6127
7070
  }
6128
7071
  }
6129
7072
  this.logger.debug("SWR: revalidation complete", { cacheKey });
6130
7073
  } catch (err) {
6131
- if (this.opts.staleIfError > 0) {
7074
+ if (this.opts.staleIfError > 0 && this._getKeyMutationEpoch(cacheKey) === startEpoch) {
6132
7075
  const additionalMs = this.opts.staleIfError * 1e3;
6133
7076
  this.l1.bumpExpiry(cacheKey, additionalMs);
6134
7077
  this.logger.debug("SWR: revalidation failed, stale-if-error extending expiry", {
@@ -6156,12 +7099,16 @@ return 0
6156
7099
  const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
6157
7100
  const p = priority ?? inferPriority(cacheKey);
6158
7101
  const k = this.nk(cacheKey);
7102
+ const existingEntry = this.l1.getEntry(k);
7103
+ const requestedTags = opts?.tags ?? existingEntry?.tags ?? this.keyTags.get(k)?.tags;
7104
+ const requestedDependencies = opts?.dependsOn ?? existingEntry?.dependsOn;
6159
7105
  this._bumpKeyMutation(k);
7106
+ const epoch = this._getKeyMutationEpoch(k);
6160
7107
  this.inflight.delete(k);
6161
- this._pendingDiskDeletes.delete(k);
7108
+ this._invalidateDiskKey(k);
6162
7109
  this.counters.sets++;
6163
7110
  let activeTagVersions;
6164
- const tagsToRegister = opts?.tags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
7111
+ const tagsToRegister = requestedTags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(requestedTags, this.opts.tagHierarchyDelimiter) : requestedTags : void 0;
6165
7112
  if (tagsToRegister?.length) {
6166
7113
  if (this.opts.tagStrategy === "generational") {
6167
7114
  const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
@@ -6170,44 +7117,27 @@ return 0
6170
7117
  activeTagVersions[tagsToRegister[i]] = vers[i];
6171
7118
  }
6172
7119
  } else {
6173
- await this._registerTags(k, tagsToRegister, ttlSeconds);
6174
- }
6175
- }
6176
- this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
6177
- if (opts?.dependsOn?.length) {
6178
- for (const pattern of opts.dependsOn) {
6179
- const nsPattern = this.nk(pattern);
6180
- let deps = this.dependencyIndex.get(nsPattern);
6181
- if (!deps) {
6182
- deps = /* @__PURE__ */ new Set();
6183
- this.dependencyIndex.set(nsPattern, deps);
6184
- }
6185
- deps.add(k);
7120
+ await this._registerTags(k, tagsToRegister, effectiveTtlSeconds);
6186
7121
  }
6187
7122
  }
7123
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return;
7124
+ const writeTs = Date.now();
7125
+ this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions, writeTs, tagsToRegister, requestedDependencies);
7126
+ this._rememberTags(k, tagsToRegister ?? [], writeTs + ttlMs);
7127
+ this._registerDependencies(k, requestedDependencies);
6188
7128
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6189
7129
  try {
6190
- const client = await this.getRedis();
6191
- const s = JSON.stringify(data);
6192
- const stored = await this._serializeAndEncrypt(s);
6193
- const ttlSec = Math.ceil(ttlMs / 1e3);
6194
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
6195
- const now = Date.now();
6196
- const tx = client.multi();
6197
- tx.hset(k, {
6198
- d: stored,
6199
- t: String(now),
6200
- tv: JSON.stringify(activeTagVersions)
6201
- });
6202
- tx.expire(k, ttlSec);
6203
- await tx.exec();
6204
- } else {
6205
- if (this.opts.autoPipeline && this.pipeliner) {
6206
- await this.pipeliner.setex(k, ttlSec, stored);
6207
- } else {
6208
- await client.setex(k, ttlSec, stored);
6209
- }
6210
- }
7130
+ await this._writeRedisEntry(
7131
+ k,
7132
+ data,
7133
+ writeTs + ttlMs,
7134
+ writeTs,
7135
+ activeTagVersions,
7136
+ void 0,
7137
+ tagsToRegister,
7138
+ requestedDependencies,
7139
+ () => this._getKeyMutationEpoch(k) === epoch
7140
+ );
6211
7141
  this.cb.onSuccess();
6212
7142
  } catch (err) {
6213
7143
  this.cb.onFailure();
@@ -6232,23 +7162,18 @@ return 0
6232
7162
  * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
6233
7163
  */
6234
7164
  async _registerTags(k, tags, ttlSeconds) {
6235
- for (const tag of tags) {
6236
- const tagKey = this.nk(`_tag_:${tag}`);
6237
- let members = this.tagIndex.get(tagKey);
6238
- if (!members) {
6239
- members = /* @__PURE__ */ new Set();
6240
- this.tagIndex.set(tagKey, members);
6241
- }
6242
- members.add(k);
6243
- }
7165
+ const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
7166
+ const expiresAt = Date.now() + effectiveTtl * 1e3;
7167
+ const uniqueTags = Array.from(new Set(tags));
7168
+ this._rememberTags(k, uniqueTags, expiresAt);
6244
7169
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6245
7170
  try {
6246
7171
  const client = await this.getRedis();
6247
7172
  const pl = client.pipeline();
6248
- for (const tag of tags) {
7173
+ for (const tag of uniqueTags) {
6249
7174
  const tagKey = this.nk(`_tag_:${tag}`);
6250
7175
  pl.sadd(tagKey, k);
6251
- pl.expire(tagKey, ttlSeconds + 3600);
7176
+ pl.expire(tagKey, effectiveTtl + 3600);
6252
7177
  }
6253
7178
  await pl.exec();
6254
7179
  this.cb.onSuccess();
@@ -6273,6 +7198,7 @@ return 0
6273
7198
  const k = this.nk(cacheKey);
6274
7199
  this.counters.deletes++;
6275
7200
  if (isPattern) {
7201
+ this._fenceInvalidation();
6276
7202
  const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6277
7203
  for (const liveKey of this.l1.liveKeys()) {
6278
7204
  if (liveKey.startsWith(pfx)) {
@@ -6285,29 +7211,30 @@ return 0
6285
7211
  this.inflight.delete(inflightKey);
6286
7212
  }
6287
7213
  }
6288
- this._addPatternTombstone(pfx);
7214
+ this._addPatternTombstone(k);
6289
7215
  this.l1.deletePattern(k);
7216
+ this._removePatternFromIndices(k);
7217
+ for (const ktKey of Array.from(this.keyTags.keys())) {
7218
+ if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
7219
+ }
7220
+ for (const kdKey of Array.from(this.keyDependencies.keys())) {
7221
+ if (this._matchesGlob(kdKey, k)) this._removeKeyDependencies(kdKey);
7222
+ }
6290
7223
  } else {
6291
7224
  this._bumpKeyMutation(k);
6292
7225
  this.inflight.delete(k);
6293
7226
  this.l1.delete(k);
6294
- this._pendingDiskDeletes.add(k);
6295
- setImmediate(() => {
6296
- try {
6297
- if (!this._diskDisabled) this.disk.delete(k);
6298
- } finally {
6299
- this._pendingDiskDeletes.delete(k);
6300
- }
6301
- });
7227
+ this._invalidateDiskKey(k);
7228
+ this._removeKeyTags(k);
6302
7229
  this._cascadeDependencies(k);
6303
- for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
7230
+ this._removeKeyDependencies(k);
6304
7231
  }
6305
7232
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6306
7233
  try {
6307
7234
  const client = await this.getRedis();
6308
7235
  if (isPattern) {
6309
7236
  const keys = await this._scanKeys(client, k);
6310
- if (keys.length > 0) await client.del(...keys);
7237
+ await this._deleteRedisKeys(client, keys);
6311
7238
  } else {
6312
7239
  if (this.opts.autoPipeline && this.pipeliner) {
6313
7240
  await this.pipeliner.del(k);
@@ -6354,7 +7281,7 @@ return 0
6354
7281
  async increment(cacheKey, ttlSeconds) {
6355
7282
  this._assertActive("increment");
6356
7283
  const k = this.nk(cacheKey);
6357
- if (this._redisDisabled) {
7284
+ if (this._redisDisabled || this.opts.l2WriteMode === "read-only") {
6358
7285
  if (!this._incrementFallbackWarned) {
6359
7286
  this._incrementFallbackWarned = true;
6360
7287
  this.logger.warn(
@@ -6369,6 +7296,15 @@ return 0
6369
7296
  entry.value++;
6370
7297
  return entry.value;
6371
7298
  }
7299
+ if (this._l1Counters.size >= 5e4 && !this._l1Counters.has(k)) {
7300
+ for (const [ck, cv] of this._l1Counters) {
7301
+ if (cv.expiresAt <= now) this._l1Counters.delete(ck);
7302
+ }
7303
+ if (this._l1Counters.size >= 5e4) {
7304
+ const oldest = this._l1Counters.keys().next().value;
7305
+ if (oldest !== void 0) this._l1Counters.delete(oldest);
7306
+ }
7307
+ }
6372
7308
  this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
6373
7309
  return 1;
6374
7310
  }
@@ -6401,6 +7337,7 @@ return 0
6401
7337
  this.counters.deletes++;
6402
7338
  const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
6403
7339
  if (k) {
7340
+ this._fenceInvalidation();
6404
7341
  const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6405
7342
  for (const liveKey of this.l1.liveKeys()) {
6406
7343
  if (liveKey.startsWith(pfx)) {
@@ -6413,8 +7350,9 @@ return 0
6413
7350
  this.inflight.delete(inflightKey);
6414
7351
  }
6415
7352
  }
6416
- this._addPatternTombstone(pfx);
7353
+ this._addPatternTombstone(k);
6417
7354
  this.l1.deletePattern(k);
7355
+ this._removePatternFromIndices(k);
6418
7356
  } else {
6419
7357
  this._globalEpoch++;
6420
7358
  this.inflight.clear();
@@ -6423,7 +7361,10 @@ return 0
6423
7361
  if (!this._diskDisabled) this.disk.clear();
6424
7362
  this._l1Counters.clear();
6425
7363
  this.tagIndex.clear();
7364
+ this.keyTags.clear();
6426
7365
  this.tagVersions.clear();
7366
+ this.dependencyIndex.clear();
7367
+ this.keyDependencies.clear();
6427
7368
  this._pendingDiskDeletes.clear();
6428
7369
  this._keyMutationEpochs.clear();
6429
7370
  }
@@ -6432,7 +7373,7 @@ return 0
6432
7373
  const client = await this.getRedis();
6433
7374
  const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
6434
7375
  const keys = await this._scanKeys(client, pattern);
6435
- if (keys.length > 0) await client.del(...keys);
7376
+ await this._deleteRedisKeys(client, keys);
6436
7377
  } catch (err) {
6437
7378
  this.logger.debug("clear: Redis unavailable", { error: err.message });
6438
7379
  }
@@ -6561,24 +7502,34 @@ return 0
6561
7502
  this._assertActive("scan");
6562
7503
  const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
6563
7504
  this.l1.scan((key, entry, pfx) => {
6564
- const value = entry.value !== void 0 ? entry.value : entry.data;
6565
- fn(key, value, pfx);
7505
+ fn(key, this._prepareReadValue(this.l1.resolveValue(entry)), pfx);
6566
7506
  }, prefixLen);
6567
7507
  }
6568
7508
  /**
6569
- * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
7509
+ * Extend the TTL of a key in L1 and Redis without fetching.
6570
7510
  * Returns `false` if the key is absent or already expired.
6571
7511
  *
6572
7512
  * @param newTtlSeconds - The new TTL from now, in seconds.
6573
7513
  */
6574
7514
  async touch(cacheKey, newTtlSeconds) {
6575
7515
  this._assertActive("touch");
7516
+ if (!Number.isFinite(newTtlSeconds) || newTtlSeconds <= 0) throw new Error("touch TTL must be finite and positive");
6576
7517
  const k = this.nk(cacheKey);
7518
+ const epoch = this._getKeyMutationEpoch(k);
6577
7519
  const hit = this.l1.touch(k, newTtlSeconds * 1e3);
6578
- if (hit && !this._redisDisabled) {
7520
+ const entry = this.l1.getEntry(k);
7521
+ if (hit) {
7522
+ const kt = this.keyTags.get(k);
7523
+ if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1e3;
7524
+ }
7525
+ if (hit && !this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6579
7526
  try {
6580
7527
  const client = await this.getRedis();
6581
- void client.expire(k, newTtlSeconds);
7528
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return hit;
7529
+ if (entry && typeof client.pttl === "function" && typeof client.eval === "function") {
7530
+ await client.eval(LUA_TOUCH_CACHE_ENTRY, 1, k, String(entry.setAt ?? 0), String(entry.expiresAt), String(Math.ceil(newTtlSeconds * 1e3)));
7531
+ } else await client.expire(k, Math.ceil(newTtlSeconds));
7532
+ this.cb.onSuccess();
6582
7533
  } catch {
6583
7534
  }
6584
7535
  }
@@ -6600,7 +7551,12 @@ return 0
6600
7551
  const now = Date.now();
6601
7552
  if (entry.expiresAt <= now) return null;
6602
7553
  if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
6603
- return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
7554
+ if (entry.tagVersions && Object.entries(entry.tagVersions).some(([tag, version]) => (this.tagVersions.get(tag)?.version ?? 0) > version)) return null;
7555
+ return this._prepareReadValue(entry.value !== void 0 ? entry.value : this.codec.decode(entry.data));
7556
+ }
7557
+ _prepareReadValue(val) {
7558
+ if (this.opts.frozen) deepFreeze(val);
7559
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6604
7560
  }
6605
7561
  /**
6606
7562
  * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
@@ -6613,59 +7569,36 @@ return 0
6613
7569
  async peek(cacheKey) {
6614
7570
  this._assertActive("peek");
6615
7571
  const k = this.nk(cacheKey);
7572
+ const epoch = this._getKeyMutationEpoch(k);
7573
+ this.counters.gets++;
6616
7574
  const l1Hit = this.l1.get(k);
6617
7575
  if (l1Hit !== null) {
6618
- this.counters.gets++;
6619
- this.counters.l1Hits++;
6620
- const val = l1Hit.value;
6621
- if (this.opts.frozen) deepFreeze(val);
6622
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6623
- }
6624
- if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
6625
- if (this._isTombstonedByPattern(k)) {
6626
- try {
6627
- this.disk.delete(k);
6628
- } catch {
6629
- }
6630
- } else if (this.watchdog.isDiskAllowed()) {
6631
- const diskStart = performance.now();
6632
- const diskHit = this.disk.load(k);
6633
- const diskElapsed = performance.now() - diskStart;
6634
- this.watchdog.recordDisk(diskElapsed);
6635
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6636
- if (diskHit !== null) {
6637
- const promoted = this.l1.importEntries(
6638
- [{ key: k, entry: diskHit }],
6639
- this.opts.forbiddenSnapshotPrefixes
6640
- );
6641
- if (promoted > 0) {
6642
- const l1Check = this.l1.get(k);
6643
- if (l1Check !== null) {
6644
- this.counters.gets++;
6645
- this.counters.diskHits++;
6646
- const val = l1Check.value;
6647
- if (this.opts.frozen) deepFreeze(val);
6648
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6649
- }
6650
- }
6651
- }
7576
+ if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
7577
+ this._deleteIfStale(k, l1Hit.setAt ?? 0);
7578
+ } else {
7579
+ this.counters.l1Hits++;
7580
+ return this._prepareReadValue(l1Hit.value);
6652
7581
  }
6653
7582
  }
6654
- if (!this._redisDisabled && !this.cb.isOpen) {
7583
+ const diskHit = await this._readDiskEntry(k, epoch);
7584
+ if (diskHit) {
7585
+ this.counters.diskHits++;
7586
+ return this._prepareReadValue(diskHit.value);
7587
+ }
7588
+ if (!this._redisDisabled) {
6655
7589
  try {
6656
7590
  const client = await this.getRedis();
6657
7591
  const redisStart = performance.now();
6658
- const raw = await client.get(k);
7592
+ const redisHit = await this._readRedisEntry(client, k);
6659
7593
  const redisElapsed = performance.now() - redisStart;
6660
7594
  this.watchdog.recordRedis(redisElapsed);
6661
- if (raw !== null) {
6662
- const parsed = await this._decryptAndDeserialize(raw);
6663
- this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
6664
- this.counters.gets++;
7595
+ this.cb.onSuccess();
7596
+ if (redisHit && !redisHit.stale) {
7597
+ const parsed = redisHit.value;
7598
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return null;
7599
+ if (!this._promoteRedisEntry(k, redisHit, 6e4, inferPriority(cacheKey))) return null;
6665
7600
  this.counters.l2Hits++;
6666
- this.cb.onSuccess();
6667
- if (this.opts.frozen) deepFreeze(parsed);
6668
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
7601
+ return this._prepareReadValue(parsed);
6669
7602
  }
6670
7603
  } catch (err) {
6671
7604
  this.cb.onFailure();
@@ -6685,6 +7618,8 @@ return 0
6685
7618
  */
6686
7619
  async mget(keys, fetchFn, ttl = 300, priority) {
6687
7620
  this._assertActive("mget");
7621
+ this.counters.gets += keys.length;
7622
+ const epochs = new Map(keys.map((key) => [this.nk(key), this._getKeyMutationEpoch(this.nk(key))]));
6688
7623
  const span = this._startSpan("tricache.mget");
6689
7624
  if (this.opts.tracer) {
6690
7625
  span.setAttribute("cache.batch.size", keys.length);
@@ -6693,12 +7628,20 @@ return 0
6693
7628
  const result = Array.from({ length: keys.length });
6694
7629
  const missIndexes = [];
6695
7630
  const missKeys = [];
7631
+ const now = Date.now();
6696
7632
  for (let i = 0; i < keys.length; i++) {
6697
7633
  const k = this.nk(keys[i]);
6698
7634
  const entry = this.l1.getEntry(k);
6699
- if (entry && entry.expiresAt > Date.now()) {
6700
- result[i] = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
6701
- this.counters.l1Hits++;
7635
+ if (entry && entry.expiresAt > now && (entry.staleAt === void 0 || entry.staleAt > now)) {
7636
+ if (await this._isGenerationalEntryStale(entry.tagVersions)) {
7637
+ this._deleteIfStale(k, entry.setAt ?? 0);
7638
+ missIndexes.push(i);
7639
+ missKeys.push(keys[i]);
7640
+ } else {
7641
+ const val = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
7642
+ result[i] = this._prepareReadValue(val);
7643
+ this.counters.l1Hits++;
7644
+ }
6702
7645
  } else {
6703
7646
  missIndexes.push(i);
6704
7647
  missKeys.push(keys[i]);
@@ -6718,30 +7661,24 @@ return 0
6718
7661
  try {
6719
7662
  const client = await this.getRedis();
6720
7663
  const nsKeys = missKeys.map((k) => this.nk(k));
6721
- const pipeline = client.multi();
6722
- for (const nk of nsKeys) pipeline.get(nk);
6723
- const redisStart = performance.now();
6724
- const raws = await pipeline.exec();
6725
- const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
6726
- this.watchdog.recordRedis(redisElapsed);
6727
- this.cb.onSuccess();
7664
+ const remoteEntries = await this._readRedisBatch(client, nsKeys);
6728
7665
  for (let j = 0; j < missKeys.length; j++) {
6729
- const raw = raws[j] ? raws[j][1] : null;
6730
7666
  const idx = missIndexes[j];
6731
- if (raw) {
6732
- const parsed = await this._decryptAndDeserialize(raw);
6733
- const k = nsKeys[j];
7667
+ const k = nsKeys[j];
7668
+ const entry = remoteEntries.get(k);
7669
+ if (entry && (entry.staleAt === void 0 || entry.staleAt > Date.now()) && !this._destroyed && this._getKeyMutationEpoch(k) === epochs.get(k)) {
6734
7670
  const p = priority ?? inferPriority(missKeys[j]);
6735
- this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
7671
+ const ttlVal = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
7672
+ if (!this._promoteRedisEntry(k, entry, this._jitterTtl(ttlVal * 1e3), p)) continue;
6736
7673
  this.counters.l2Hits++;
6737
7674
  l2HitCount++;
6738
- result[idx] = parsed;
7675
+ result[idx] = this._prepareReadValue(entry.value);
6739
7676
  missIndexes[j] = -1;
6740
7677
  missKeys[j] = "";
6741
7678
  }
6742
7679
  }
6743
7680
  const remainingIdx = missIndexes.filter((i) => i >= 0);
6744
- const remainingKeys = missKeys.filter((k) => k !== "");
7681
+ const remainingKeys = missKeys.filter((_key, index) => missIndexes[index] >= 0);
6745
7682
  missIndexes.length = 0;
6746
7683
  missKeys.length = 0;
6747
7684
  missIndexes.push(...remainingIdx);
@@ -6754,58 +7691,64 @@ return 0
6754
7691
  if (!this._diskDisabled && missKeys.length > 0) {
6755
7692
  for (let j = missKeys.length - 1; j >= 0; j--) {
6756
7693
  const k = this.nk(missKeys[j]);
6757
- if (this._pendingDiskDeletes.has(k)) continue;
6758
- if (this._isTombstonedByPattern(k)) {
6759
- try {
6760
- this.disk.delete(k);
6761
- } catch {
6762
- }
6763
- continue;
6764
- }
6765
- if (!this.watchdog.isDiskAllowed()) continue;
6766
- const diskStart = performance.now();
6767
- const diskHit = this.disk.load(k);
6768
- const diskElapsed = performance.now() - diskStart;
6769
- this.watchdog.recordDisk(diskElapsed);
6770
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6771
- if (diskHit !== null) {
6772
- const promoted = this.l1.importEntries(
6773
- [{ key: k, entry: diskHit }],
6774
- this.opts.forbiddenSnapshotPrefixes
6775
- );
6776
- if (promoted > 0) {
6777
- const l1Check = this.l1.get(k);
6778
- if (l1Check !== null) {
6779
- this.counters.diskHits++;
6780
- result[missIndexes[j]] = l1Check.value;
6781
- missIndexes.splice(j, 1);
6782
- missKeys.splice(j, 1);
6783
- }
6784
- }
7694
+ const diskHit = await this._readDiskEntry(k, epochs.get(k));
7695
+ if (diskHit && (diskHit.entry.staleAt === void 0 || diskHit.entry.staleAt > Date.now())) {
7696
+ this.counters.diskHits++;
7697
+ result[missIndexes[j]] = this._prepareReadValue(diskHit.value);
7698
+ missIndexes.splice(j, 1);
7699
+ missKeys.splice(j, 1);
6785
7700
  }
6786
7701
  }
6787
7702
  }
6788
7703
  if (missKeys.length > 0 && fetchFn) {
6789
- this.counters.fetches++;
6790
- const fetched = await fetchFn(missKeys);
6791
- const isMap = fetched instanceof Map;
6792
- const setPromises = [];
7704
+ const owned = /* @__PURE__ */ new Map();
7705
+ const waiting = [];
6793
7706
  for (let j = 0; j < missKeys.length; j++) {
6794
- const k = missKeys[j];
6795
- const v = isMap ? fetched.get(k) : fetched[k];
6796
- result[missIndexes[j]] = v;
6797
- if (v !== void 0 && v !== null) {
6798
- const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
6799
- setPromises.push(this.set(k, v, resolvedTtl, priority));
6800
- } else if (v == null && this.opts.notFoundTtl > 0) {
6801
- setPromises.push(this.set(k, null, this.opts.notFoundTtl, priority));
6802
- } else if (v === null) {
6803
- const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
6804
- setPromises.push(this.set(k, null, resolvedTtl, priority));
7707
+ const key = missKeys[j];
7708
+ const namespaced = this.nk(key);
7709
+ let promise = this.inflight.get(namespaced);
7710
+ if (!promise) {
7711
+ let resolve;
7712
+ let reject;
7713
+ promise = new Promise((yes, no) => {
7714
+ resolve = yes;
7715
+ reject = no;
7716
+ });
7717
+ owned.set(key, { promise, resolve, reject });
7718
+ this.inflight.set(namespaced, promise);
7719
+ } else {
7720
+ this.counters.stampedes++;
6805
7721
  }
7722
+ const index = missIndexes[j];
7723
+ waiting.push(promise.then((value) => {
7724
+ result[index] = this._prepareReadValue(value);
7725
+ }));
6806
7726
  }
6807
- if (setPromises.length > 0) {
6808
- await Promise.all(setPromises);
7727
+ const settled = Promise.allSettled(waiting);
7728
+ try {
7729
+ if (owned.size > 0) {
7730
+ this.counters.fetches++;
7731
+ const fetched = await fetchFn([...owned.keys()]);
7732
+ await Promise.all([...owned].map(async ([key, entry]) => {
7733
+ const value = fetched instanceof Map ? fetched.get(key) : Object.hasOwn(fetched, key) ? fetched[key] : void 0;
7734
+ if (!this._destroyed && this._getKeyMutationEpoch(this.nk(key)) === epochs.get(this.nk(key))) {
7735
+ const resolvedTtl = value == null && this.opts.notFoundTtl > 0 ? this.opts.notFoundTtl : typeof ttl === "function" ? ttl(key) : ttl;
7736
+ if (value !== void 0 || this.opts.notFoundTtl > 0) await this.set(key, value === void 0 && this.opts.notFoundTtl > 0 ? null : value, resolvedTtl, priority);
7737
+ }
7738
+ entry.resolve(value);
7739
+ }));
7740
+ }
7741
+ const outcomes = await settled;
7742
+ const failed = outcomes.find((outcome) => outcome.status === "rejected");
7743
+ if (failed?.status === "rejected") throw failed.reason;
7744
+ } catch (error) {
7745
+ for (const entry of owned.values()) entry.reject(error);
7746
+ throw error;
7747
+ } finally {
7748
+ for (const [key, entry] of owned) {
7749
+ const namespaced = this.nk(key);
7750
+ if (this.inflight.get(namespaced) === entry.promise) this.inflight.delete(namespaced);
7751
+ }
6809
7752
  }
6810
7753
  }
6811
7754
  if (this.opts.tracer) {
@@ -6858,7 +7801,7 @@ return 0
6858
7801
  try {
6859
7802
  await Promise.all(keys.map((key) => {
6860
7803
  const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
6861
- const hasOpts = tags?.length || dependsOn?.length;
7804
+ const hasOpts = tags !== void 0 || dependsOn !== void 0;
6862
7805
  return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
6863
7806
  }));
6864
7807
  } catch (err) {
@@ -6910,26 +7853,21 @@ return 0
6910
7853
  try {
6911
7854
  const client = await this.getRedis();
6912
7855
  const nsPattern = this.nk(pattern);
6913
- const matchedKeys = await this._scanKeys(client, nsPattern);
7856
+ const matchedKeys = (await this._scanKeys(client, nsPattern)).filter((key) => {
7857
+ const raw = this.unnk(key);
7858
+ return !raw.startsWith("_tag_:") && !raw.startsWith("tag_ver:") && !raw.startsWith("lock:") && key !== this.backplaneStreamKey;
7859
+ });
6914
7860
  if (matchedKeys.length === 0) {
6915
7861
  this.cb.onSuccess();
6916
7862
  return 0;
6917
7863
  }
6918
- const pl = client.pipeline();
6919
- for (const k of matchedKeys) pl.get(k);
6920
- const results = await pl.exec();
6921
- this.cb.onSuccess();
7864
+ const epochs = new Map(matchedKeys.map((key) => [key, this._getKeyMutationEpoch(key)]));
7865
+ const results = await this._readRedisBatch(client, matchedKeys);
6922
7866
  let loaded = 0;
6923
- for (let i = 0; i < matchedKeys.length; i++) {
6924
- const [err, raw] = results[i];
6925
- if (err || raw == null) continue;
6926
- try {
6927
- const parsed = await this._decryptAndDeserialize(raw);
6928
- const remainingMs = 10 * 60 * 1e3;
6929
- this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
6930
- loaded++;
6931
- } catch {
6932
- }
7867
+ for (const key of matchedKeys) {
7868
+ const entry = results.get(key);
7869
+ if (!entry || this._destroyed || this._getKeyMutationEpoch(key) !== epochs.get(key)) continue;
7870
+ if (this._promoteRedisEntry(key, entry, 10 * 60 * 1e3, opts?.priority ?? inferPriority(this.unnk(key))) && this.l1.has(key)) loaded++;
6933
7871
  }
6934
7872
  this.logger.info("warmFromL2 complete", {
6935
7873
  pattern,
@@ -7002,6 +7940,139 @@ return 0
7002
7940
  }
7003
7941
  return matched;
7004
7942
  }
7943
+ async _publishTagInvalidation(op, key, tagVersion) {
7944
+ if (this.opts.awaitInvalidationBackplane) {
7945
+ await this.publishInvalidation(op, key, tagVersion, false, true);
7946
+ } else {
7947
+ void this.publishInvalidation(op, key, tagVersion, false, true);
7948
+ }
7949
+ }
7950
+ _removeTagMembersLocal(keys) {
7951
+ const keyList = Array.isArray(keys) ? keys : Array.from(keys);
7952
+ for (const k of keyList) {
7953
+ this.l1.delete(k);
7954
+ this._bumpKeyMutation(k);
7955
+ this._removeKeyTags(k);
7956
+ this._removeKeyDependencies(k);
7957
+ this._invalidateDiskKey(k);
7958
+ }
7959
+ }
7960
+ /**
7961
+ * Executes invalidation for a single already-resolved concrete tag without
7962
+ * wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
7963
+ */
7964
+ async _invalidateConcreteTag(tag) {
7965
+ this._fenceInvalidation();
7966
+ if (this.opts.tagStrategy === "generational") {
7967
+ let newVer = 1;
7968
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7969
+ try {
7970
+ const client = await this.getRedis();
7971
+ newVer = await client.incr(this.nk(`tag_ver:${tag}`));
7972
+ } catch (err) {
7973
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7974
+ const current = this.tagVersions.get(tag)?.version ?? 0;
7975
+ newVer = current + 1;
7976
+ }
7977
+ } else {
7978
+ const current = this.tagVersions.get(tag)?.version ?? 0;
7979
+ newVer = current + 1;
7980
+ }
7981
+ this._setLocalTagVersion(tag, newVer, performance.now());
7982
+ await this._publishTagInvalidation("tag_incr", tag, newVer);
7983
+ return;
7984
+ }
7985
+ const tagKey = this.nk(`_tag_:${tag}`);
7986
+ const members = new Set(this.tagIndex.get(tagKey) ?? []);
7987
+ this.tagIndex.delete(tagKey);
7988
+ this._removeTagMembersLocal(members);
7989
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7990
+ try {
7991
+ const client = await this.getRedis();
7992
+ const redisMembers = await client.smembers(tagKey);
7993
+ for (const key of redisMembers) members.add(key);
7994
+ this._removeTagMembersLocal(redisMembers);
7995
+ const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers, tagKey])];
7996
+ await this._deleteRedisKeys(client, toDelete);
7997
+ } catch (err) {
7998
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7999
+ }
8000
+ }
8001
+ await Promise.all([...members].map((key) => this._publishTagInvalidation("del", key)));
8002
+ await this._publishTagInvalidation("tag_pattern_del", tag);
8003
+ }
8004
+ /**
8005
+ * Executes invalidation for an array of already-resolved concrete tags
8006
+ * without re-entering wildcard/cascade resolution or invalidateTag().
8007
+ */
8008
+ async _invalidateConcreteTags(tags) {
8009
+ if (tags.length === 0) return;
8010
+ if (tags.length === 1) {
8011
+ await this._invalidateConcreteTag(tags[0]);
8012
+ return;
8013
+ }
8014
+ this._fenceInvalidation();
8015
+ if (this.opts.tagStrategy === "generational") {
8016
+ const now = performance.now();
8017
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
8018
+ try {
8019
+ const client = await this.getRedis();
8020
+ const pl = client.pipeline();
8021
+ for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
8022
+ const results = await pl.exec();
8023
+ for (let i = 0; i < tags.length; i++) {
8024
+ const [err, newVer] = results[i] ?? [null, null];
8025
+ const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
8026
+ this._setLocalTagVersion(tags[i], ver, now);
8027
+ await this._publishTagInvalidation("tag_incr", tags[i], ver);
8028
+ }
8029
+ return;
8030
+ } catch (err) {
8031
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
8032
+ }
8033
+ }
8034
+ for (const tag of tags) {
8035
+ const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
8036
+ this._setLocalTagVersion(tag, ver, now);
8037
+ await this._publishTagInvalidation("tag_incr", tag, ver);
8038
+ }
8039
+ return;
8040
+ }
8041
+ const tagKeys = [];
8042
+ const allMembers = /* @__PURE__ */ new Set();
8043
+ for (const tag of tags) {
8044
+ const tagKey = this.nk(`_tag_:${tag}`);
8045
+ tagKeys.push(tagKey);
8046
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
8047
+ for (const k of members) allMembers.add(k);
8048
+ this.tagIndex.delete(tagKey);
8049
+ }
8050
+ this._removeTagMembersLocal(allMembers);
8051
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
8052
+ try {
8053
+ const client = await this.getRedis();
8054
+ const pl = client.pipeline();
8055
+ for (const tagKey of tagKeys) pl.smembers(tagKey);
8056
+ const smResults = await pl.exec();
8057
+ const toDelete = [...allMembers];
8058
+ for (const [err, redisMembers] of smResults) {
8059
+ if (!err && redisMembers) {
8060
+ for (const k of redisMembers) {
8061
+ if (!allMembers.has(k)) toDelete.push(k);
8062
+ allMembers.add(k);
8063
+ }
8064
+ }
8065
+ }
8066
+ const keysToRemove = [...toDelete, ...tagKeys];
8067
+ await this._deleteRedisKeys(client, keysToRemove);
8068
+ this._removeTagMembersLocal(allMembers);
8069
+ } catch (err) {
8070
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
8071
+ }
8072
+ }
8073
+ await Promise.all([...allMembers].map((key) => this._publishTagInvalidation("del", key)));
8074
+ for (const tag of tags) await this._publishTagInvalidation("tag_pattern_del", tag);
8075
+ }
7005
8076
  /**
7006
8077
  * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
7007
8078
  * Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
@@ -7037,68 +8108,13 @@ return 0
7037
8108
  const delim = this.opts.tagHierarchyDelimiter;
7038
8109
  const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
7039
8110
  if (matchedTags.size > 0) {
7040
- await this.invalidateTags(Array.from(matchedTags));
8111
+ await this._invalidateConcreteTags(Array.from(matchedTags));
7041
8112
  }
7042
8113
  const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
7043
- if (this.opts.awaitInvalidationBackplane) {
7044
- await this.publishInvalidation(op, broadcastPattern, void 0, false, true);
7045
- } else {
7046
- void this.publishInvalidation(op, broadcastPattern, void 0, false, true);
7047
- }
8114
+ await this._publishTagInvalidation(op, broadcastPattern);
7048
8115
  return;
7049
8116
  }
7050
- if (this.opts.tagStrategy === "generational") {
7051
- let newVer = 1;
7052
- if (!this._redisDisabled) {
7053
- try {
7054
- const client = await this.getRedis();
7055
- newVer = await client.incr(this.nk(`tag_ver:${tag}`));
7056
- } catch (err) {
7057
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7058
- const current = this.tagVersions.get(tag)?.version ?? 0;
7059
- newVer = current + 1;
7060
- }
7061
- } else {
7062
- const current = this.tagVersions.get(tag)?.version ?? 0;
7063
- newVer = current + 1;
7064
- }
7065
- this._setLocalTagVersion(tag, newVer, performance.now());
7066
- if (this.opts.awaitInvalidationBackplane) {
7067
- await this.publishInvalidation("tag_incr", tag, newVer, false, true);
7068
- } else {
7069
- void this.publishInvalidation("tag_incr", tag, newVer, false, true);
7070
- }
7071
- return;
7072
- }
7073
- const tagKey = this.nk(`_tag_:${tag}`);
7074
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
7075
- for (const k of members) {
7076
- this.l1.delete(k);
7077
- this._bumpKeyMutation(k);
7078
- this._pendingDiskDeletes.add(k);
7079
- setImmediate(() => {
7080
- try {
7081
- if (!this._diskDisabled) this.disk.delete(k);
7082
- } finally {
7083
- this._pendingDiskDeletes.delete(k);
7084
- }
7085
- });
7086
- }
7087
- this.tagIndex.delete(tagKey);
7088
- if (!this._redisDisabled) {
7089
- try {
7090
- const client = await this.getRedis();
7091
- const redisMembers = await client.smembers(tagKey);
7092
- const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
7093
- if (toDelete.length > 0) {
7094
- await client.del(...toDelete, tagKey);
7095
- } else {
7096
- await client.del(tagKey);
7097
- }
7098
- } catch (err) {
7099
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7100
- }
7101
- }
8117
+ await this._invalidateConcreteTag(tag);
7102
8118
  } catch (err) {
7103
8119
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
7104
8120
  span.recordException?.(err);
@@ -7125,96 +8141,28 @@ return 0
7125
8141
  const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
7126
8142
  if (hasWildcards || shouldCascade) {
7127
8143
  const allResolvedTags = /* @__PURE__ */ new Set();
8144
+ const broadcastPatterns = /* @__PURE__ */ new Set();
8145
+ const delim = this.opts.tagHierarchyDelimiter;
7128
8146
  for (const t of tags) {
7129
- if (isWildcardTag(t) || shouldCascade) {
8147
+ const tIsPattern = isWildcardTag(t);
8148
+ if (tIsPattern || shouldCascade) {
8149
+ broadcastPatterns.add(tIsPattern ? t : `${t}${delim}*`);
7130
8150
  const resolved = await this._resolveMatchingTags(t, shouldCascade);
7131
8151
  for (const rt of resolved) allResolvedTags.add(rt);
7132
8152
  } else {
7133
8153
  allResolvedTags.add(t);
7134
8154
  }
7135
8155
  }
7136
- if (allResolvedTags.size === 0) return;
7137
- tags = Array.from(allResolvedTags);
7138
- }
7139
- if (tags.length === 1) {
7140
- await this.invalidateTag(tags[0], opts);
7141
- return;
7142
- }
7143
- if (this.opts.tagStrategy === "generational") {
7144
- const now = performance.now();
7145
- if (!this._redisDisabled) {
7146
- try {
7147
- const client = await this.getRedis();
7148
- const pl = client.pipeline();
7149
- for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
7150
- const results = await pl.exec();
7151
- for (let i = 0; i < tags.length; i++) {
7152
- const [err, newVer] = results[i] ?? [null, null];
7153
- const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
7154
- this._setLocalTagVersion(tags[i], ver, now);
7155
- if (this.opts.awaitInvalidationBackplane) {
7156
- await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7157
- } else {
7158
- void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7159
- }
7160
- }
7161
- return;
7162
- } catch (err) {
7163
- this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7164
- }
8156
+ if (allResolvedTags.size > 0) {
8157
+ await this._invalidateConcreteTags(Array.from(allResolvedTags));
7165
8158
  }
7166
- for (const tag of tags) {
7167
- const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
7168
- this._setLocalTagVersion(tag, ver, now);
7169
- if (this.opts.awaitInvalidationBackplane) {
7170
- await this.publishInvalidation("tag_incr", tag, ver, false, true);
7171
- } else {
7172
- void this.publishInvalidation("tag_incr", tag, ver, false, true);
7173
- }
8159
+ const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
8160
+ for (const pattern of broadcastPatterns) {
8161
+ await this._publishTagInvalidation(op, pattern);
7174
8162
  }
7175
8163
  return;
7176
8164
  }
7177
- const tagKeys = [];
7178
- const allMembers = /* @__PURE__ */ new Set();
7179
- for (const tag of tags) {
7180
- const tagKey = this.nk(`_tag_:${tag}`);
7181
- tagKeys.push(tagKey);
7182
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
7183
- for (const k of members) allMembers.add(k);
7184
- this.tagIndex.delete(tagKey);
7185
- }
7186
- for (const k of allMembers) {
7187
- this.l1.delete(k);
7188
- this._bumpKeyMutation(k);
7189
- this._pendingDiskDeletes.add(k);
7190
- setImmediate(() => {
7191
- try {
7192
- if (!this._diskDisabled) this.disk.delete(k);
7193
- } finally {
7194
- this._pendingDiskDeletes.delete(k);
7195
- }
7196
- });
7197
- }
7198
- if (!this._redisDisabled) {
7199
- try {
7200
- const client = await this.getRedis();
7201
- const pl = client.pipeline();
7202
- for (const tagKey of tagKeys) pl.smembers(tagKey);
7203
- const smResults = await pl.exec();
7204
- const toDelete = [...allMembers];
7205
- for (const [err, redisMembers] of smResults) {
7206
- if (!err && redisMembers) {
7207
- for (const k of redisMembers) {
7208
- if (!allMembers.has(k)) toDelete.push(k);
7209
- }
7210
- }
7211
- }
7212
- const keysToRemove = [...toDelete, ...tagKeys];
7213
- if (keysToRemove.length > 0) await client.del(...keysToRemove);
7214
- } catch (err) {
7215
- this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7216
- }
7217
- }
8165
+ await this._invalidateConcreteTags(Array.from(new Set(tags)));
7218
8166
  }
7219
8167
  /**
7220
8168
  * Get the current generational tag version for a tag (synced with Redis when due).
@@ -7277,19 +8225,23 @@ return 0
7277
8225
  const diskLowSpace = !this._diskDisabled && this.disk.hostVolumeLowSpace;
7278
8226
  const circuitOpen = this.cb.isOpen;
7279
8227
  const latencyBypass = watchdogTel.bypassActive;
7280
- const degraded = circuitOpen || latencyBypass || diskPruning || diskLowSpace;
7281
- const healthy = this.opts.failReadinessOnDegraded ? !degraded : true;
8228
+ const backplaneUnavailable = this.opts.invalidationBackplane && !this._redisDisabled && !this._backplaneAvailable;
8229
+ const degraded = this._destroyed || circuitOpen || latencyBypass || diskPruning || diskLowSpace || backplaneUnavailable;
8230
+ const healthy = !this._destroyed && (this.opts.failReadinessOnDegraded ? !degraded : true);
7282
8231
  const reasons = [];
7283
8232
  if (circuitOpen) reasons.push("redis_circuit_breaker_open");
7284
8233
  if (latencyBypass) reasons.push(`disk_latency_bypass_stage_${watchdogTel.bypassStage}`);
7285
8234
  if (diskPruning) reasons.push("disk_quota_watermark_pruning_active");
7286
8235
  if (diskLowSpace) reasons.push("disk_host_volume_low_space");
8236
+ if (backplaneUnavailable) reasons.push("invalidation_backplane_unavailable");
8237
+ if (this._destroyed) reasons.push("cache_destroyed");
7287
8238
  return {
7288
8239
  healthy,
7289
8240
  degraded,
7290
8241
  reasons,
7291
8242
  details: {
7292
- redisConnected: !circuitOpen && !this._redisDisabled,
8243
+ redisConnected: !this._destroyed && !circuitOpen && !!this.redis && (this.redis.status === "ready" || this.redis.isOpen === true),
8244
+ backplaneReady: this._backplaneAvailable,
7293
8245
  circuitBreakerState: this.cb.currentState,
7294
8246
  diskPruningActive: diskPruning,
7295
8247
  diskHostVolumeLowSpace: diskLowSpace,
@@ -7311,23 +8263,28 @@ return 0
7311
8263
  */
7312
8264
  async drainToL2() {
7313
8265
  this._assertActive("drainToL2");
7314
- if (this._redisDisabled) return 0;
8266
+ if (this._redisDisabled || this.opts.l2WriteMode === "read-only") return 0;
7315
8267
  try {
7316
- const client = await this.getRedis();
7317
8268
  const entries = this.l1.exportEntries([]);
7318
- const now = Date.now();
7319
8269
  if (entries.length === 0) return 0;
7320
- const pl = client.pipeline();
7321
- for (const { key, entry } of entries) {
7322
- const remainingMs = entry.expiresAt - now;
7323
- if (remainingMs <= 0) continue;
7324
- const ttlSecs = Math.max(1, Math.ceil(remainingMs / 1e3));
7325
- const s = JSON.stringify(entry.value);
7326
- const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
7327
- pl.setex(key, ttlSecs, stored);
7328
- }
7329
- await pl.exec();
7330
- return entries.length;
8270
+ let written = 0;
8271
+ await Promise.all(entries.map(async ({ key, entry }) => {
8272
+ const epoch = this._getKeyMutationEpoch(key);
8273
+ if (entry.expiresAt <= Date.now()) return;
8274
+ await this._writeRedisEntry(
8275
+ key,
8276
+ this.l1.resolveValue(entry),
8277
+ entry.expiresAt,
8278
+ entry.setAt ?? Date.now(),
8279
+ entry.tagVersions,
8280
+ entry.staleAt,
8281
+ entry.tags,
8282
+ entry.dependsOn,
8283
+ () => this._getKeyMutationEpoch(key) === epoch
8284
+ );
8285
+ written++;
8286
+ }));
8287
+ return written;
7331
8288
  } catch (err) {
7332
8289
  this.logger.debug("drainToL2: Redis unavailable", { error: err.message });
7333
8290
  return 0;
@@ -7357,7 +8314,7 @@ return 0
7357
8314
  this._assertActive("setIfAbsent");
7358
8315
  const k = this.nk(cacheKey);
7359
8316
  if (this.l1.has(k)) return false;
7360
- if (!this._redisDisabled) {
8317
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7361
8318
  try {
7362
8319
  const client = await this.getRedis();
7363
8320
  const serialized = JSON.stringify(value);
@@ -7374,7 +8331,7 @@ return 0
7374
8331
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
7375
8332
  const p = priority ?? inferPriority(cacheKey);
7376
8333
  this._bumpKeyMutation(k);
7377
- this._pendingDiskDeletes.delete(k);
8334
+ this._invalidateDiskKey(k);
7378
8335
  this.l1.set(k, value, ttlMs, p);
7379
8336
  this.counters.sets++;
7380
8337
  return true;
@@ -7401,7 +8358,7 @@ return 0
7401
8358
  const token = import_crypto3.default.randomUUID();
7402
8359
  const deadline = Date.now() + acquireTimeout;
7403
8360
  let acquired = false;
7404
- if (!this._redisDisabled) {
8361
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7405
8362
  let client = null;
7406
8363
  try {
7407
8364
  client = await this.getRedis();
@@ -7496,7 +8453,9 @@ return 0
7496
8453
  const gDiskFiles = meter.createObservableGauge("tricache.disk.files", { description: "Current L1.5 disk file count" });
7497
8454
  const gDiskBytes = meter.createObservableGauge("tricache.disk.bytes", { description: "Current L1.5 disk size in bytes" });
7498
8455
  const gBloomFpr = meter.createObservableGauge("tricache.bloom.fpr", { description: "Bloom filter false-positive rate" });
7499
- meter.addBatchObservableCallback((observableResult) => {
8456
+ const observables = [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr];
8457
+ const callback = (observableResult) => {
8458
+ if (this._destroyed) return;
7500
8459
  const stats = this.stats();
7501
8460
  const l1 = stats.l1;
7502
8461
  const disk = stats.disk;
@@ -7509,7 +8468,9 @@ return 0
7509
8468
  observableResult.observe(gDiskFiles, disk.files, attrs);
7510
8469
  observableResult.observe(gDiskBytes, disk.sizeKB * 1024, attrs);
7511
8470
  observableResult.observe(gBloomFpr, fpr, attrs);
7512
- }, [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr]);
8471
+ };
8472
+ meter.addBatchObservableCallback(callback, observables);
8473
+ this._otelCleanup = () => meter.removeBatchObservableCallback?.(callback, observables);
7513
8474
  } catch (err) {
7514
8475
  this.logger.warn("Failed to initialize OpenTelemetry metrics meter", { error: err.message });
7515
8476
  }
@@ -7779,8 +8740,25 @@ return 0
7779
8740
  /** Close Redis connections and stop all background timers. */
7780
8741
  async destroy() {
7781
8742
  this._destroyed = true;
8743
+ this._fenceInvalidation();
8744
+ this._backplaneAvailable = false;
8745
+ this.l1.clear();
8746
+ try {
8747
+ this._otelCleanup?.();
8748
+ } catch {
8749
+ }
8750
+ this._otelCleanup = null;
8751
+ this.tagVersions.clear();
8752
+ for (const dispose of this._backplaneDisposers.splice(0)) dispose();
7782
8753
  this._pendingDiskDeletes.clear();
7783
8754
  this._keyMutationEpochs.clear();
8755
+ this.inflight.clear();
8756
+ this.revalidating.clear();
8757
+ this._l1Counters.clear();
8758
+ this.tagIndex.clear();
8759
+ this.keyTags.clear();
8760
+ this.dependencyIndex.clear();
8761
+ this.keyDependencies.clear();
7784
8762
  const g = globalThis;
7785
8763
  const key = _CacheService.globalKey(this.opts);
7786
8764
  if (g[key] === this) {
@@ -7801,6 +8779,12 @@ return 0
7801
8779
  this._workerPool = null;
7802
8780
  }
7803
8781
  if (this.subClient) {
8782
+ if (this.opts.redisSubClient) {
8783
+ try {
8784
+ await this.subClient.unsubscribe?.(this.backplaneChannel);
8785
+ } catch {
8786
+ }
8787
+ }
7804
8788
  if (!this.opts.redisSubClient) {
7805
8789
  try {
7806
8790
  this.subClient.disconnect();
@@ -7810,7 +8794,7 @@ return 0
7810
8794
  this.subClient = null;
7811
8795
  }
7812
8796
  if (this.streamClient) {
7813
- try {
8797
+ if (!this.opts.redisSubClient) try {
7814
8798
  this.streamClient.disconnect();
7815
8799
  } catch {
7816
8800
  }