tricache 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +36 -28
  2. package/dist/{cache-service-CREOp7MM.d.ts → cache-service-B108FzER.d.ts} +36 -4
  3. package/dist/cache-service-CWI4jkS7.d.cts +963 -0
  4. package/dist/{cache-service-MG7PN6MX.js → cache-service-GYPZFB7O.js} +2 -2
  5. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  6. package/dist/{chunk-2AJKEQMZ.js → chunk-H4GFLQ26.js} +7 -4
  7. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  8. package/dist/chunk-OYDU3SMI.js +89 -0
  9. package/dist/{chunk-3I5L7K6I.js → chunk-VNRDL5RA.js} +102 -140
  10. package/dist/{chunk-JYQFQJNJ.js → chunk-WYF7NOAT.js} +1443 -609
  11. package/dist/cli.cjs +1367 -625
  12. package/dist/cli.d.cts +12 -0
  13. package/dist/cli.js +27 -6
  14. package/dist/dashboard/index.cjs +111 -29
  15. package/dist/dashboard/index.d.cts +185 -0
  16. package/dist/dashboard/index.d.ts +5 -3
  17. package/dist/dashboard/index.js +1 -1
  18. package/dist/drizzle/index.cjs +1370 -624
  19. package/dist/drizzle/index.d.cts +46 -0
  20. package/dist/drizzle/index.d.ts +2 -2
  21. package/dist/drizzle/index.js +1 -1
  22. package/dist/edge/index.cjs +227 -123
  23. package/dist/edge/index.d.cts +127 -0
  24. package/dist/edge/index.d.ts +3 -3
  25. package/dist/edge/index.js +201 -117
  26. package/dist/hono/index.cjs +1418 -644
  27. package/dist/hono/index.d.cts +93 -0
  28. package/dist/hono/index.d.ts +7 -5
  29. package/dist/hono/index.js +16 -9
  30. package/dist/{hono-DSV2ve66.d.ts → hono-3rDMYVtY.d.ts} +16 -3
  31. package/dist/hono-C886ok3X.d.cts +391 -0
  32. package/dist/http/index.cjs +1514 -679
  33. package/dist/http/index.d.cts +103 -0
  34. package/dist/http/index.d.ts +13 -5
  35. package/dist/http/index.js +92 -43
  36. package/dist/index.cjs +1671 -790
  37. package/dist/index.d.cts +1006 -0
  38. package/dist/index.d.ts +39 -8
  39. package/dist/index.js +8 -8
  40. package/dist/murmur3-CMGw9PbV.d.cts +98 -0
  41. package/dist/nestjs/index.cjs +1454 -649
  42. package/dist/nestjs/index.d.cts +285 -0
  43. package/dist/nestjs/index.d.ts +103 -30
  44. package/dist/nestjs/index.js +115 -32
  45. package/dist/next/index.cjs +1512 -718
  46. package/dist/next/index.d.cts +232 -0
  47. package/dist/next/index.d.ts +33 -11
  48. package/dist/next/index.js +172 -99
  49. package/dist/prisma/index.cjs +11 -1
  50. package/dist/prisma/index.d.cts +62 -0
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +11 -1
  53. package/dist/serialize-worker.d.cts +2 -0
  54. package/dist/{types-Dyip5wAl.d.ts → types-BA4pz1A0.d.cts} +24 -9
  55. package/dist/types-BA4pz1A0.d.ts +1519 -0
  56. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  57. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  58. package/package.json +96 -36
  59. package/src/adapters/auto-pipeliner.ts +107 -24
  60. package/src/adapters/node-redis.ts +106 -27
  61. package/src/cache-service.ts +802 -502
  62. package/src/cli.ts +24 -6
  63. package/src/cross-region.ts +21 -3
  64. package/src/dashboard/handler.ts +26 -6
  65. package/src/dashboard/html.ts +35 -10
  66. package/src/dashboard/index.ts +35 -13
  67. package/src/dashboard/types.ts +3 -1
  68. package/src/disk-tier.ts +171 -65
  69. package/src/edge/cache.ts +145 -97
  70. package/src/edge/hono.ts +23 -6
  71. package/src/edge/types.ts +2 -0
  72. package/src/hono/index.ts +19 -9
  73. package/src/http/express.ts +62 -17
  74. package/src/http/fastify.ts +35 -21
  75. package/src/http/utils.ts +54 -20
  76. package/src/ipc-telemetry.ts +35 -9
  77. package/src/nestjs/decorators.ts +1 -1
  78. package/src/nestjs/index.ts +2 -0
  79. package/src/nestjs/keyv-adapter.ts +68 -0
  80. package/src/nestjs/tricache.module.ts +13 -11
  81. package/src/nestjs/tricache.store.ts +51 -20
  82. package/src/nestjs/types.ts +29 -15
  83. package/src/next/cache-handler.ts +131 -53
  84. package/src/next/index.ts +1 -0
  85. package/src/next/types.ts +21 -0
  86. package/src/prisma/index.ts +12 -1
  87. package/src/smart-memory-cache.ts +63 -26
  88. package/src/types.ts +25 -2
  89. package/src/utils/cgroup.ts +12 -0
  90. package/src/utils/deadline.ts +14 -0
  91. package/src/utils/diagnostics.ts +27 -0
  92. package/src/utils/redis-slot.ts +13 -0
  93. package/src/wasm/bloom-filter-wasm.ts +9 -4
  94. package/src/worker-pool.ts +17 -8
  95. package/src/wtiny-lfu.ts +20 -6
  96. package/dist/chunk-BQRURGGD.js +0 -60
@@ -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, setAt) {
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) {
@@ -1501,10 +1562,12 @@ var init_smart_memory_cache = __esm({
1501
1562
  ttlMs,
1502
1563
  delta,
1503
1564
  setAt: setAt ?? now2,
1504
- tagVersions
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: 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
2605
  }
2454
- let match;
2455
- for (const f of files) {
2456
- if ((f === hash || f.startsWith(hash + "_")) && (!match || f > match)) match = f;
2457
- }
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;
@@ -4146,6 +4576,7 @@ return 0
4146
4576
  keyTags = /* @__PURE__ */ new Map();
4147
4577
  /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
4148
4578
  tagVersions = /* @__PURE__ */ new Map();
4579
+ _tagRefreshEpoch = 0;
4149
4580
  /**
4150
4581
  * Dependency index: source glob pattern → Set of namespaced dependent keys.
4151
4582
  * When an exact-key delete matches a registered pattern, all dependents are cascaded.
@@ -4176,9 +4607,17 @@ return 0
4176
4607
  subClient = null;
4177
4608
  streamClient = null;
4178
4609
  _lastStreamId = "$";
4610
+ _restoredSnapshot = false;
4611
+ _backplaneAvailable = false;
4612
+ _otelCleanup = null;
4613
+ _streamRecovering = false;
4614
+ _backplaneDisposers = [];
4179
4615
  _destroyed = false;
4180
4616
  _pendingDiskDeletes = /* @__PURE__ */ new Set();
4181
4617
  _globalEpoch = 0;
4618
+ _pendingSpillCount = 0;
4619
+ _suppressSpills = false;
4620
+ _diskCleanupScheduled = false;
4182
4621
  _keyMutationEpochs = /* @__PURE__ */ new Map();
4183
4622
  /**
4184
4623
  * Pattern tombstones for disk tier.
@@ -4187,20 +4626,24 @@ return 0
4187
4626
  * pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
4188
4627
  */
4189
4628
  _patternTombstones = [];
4190
- _addPatternTombstone(prefix) {
4629
+ _diskInvalidatedBefore = 0;
4630
+ _addPatternTombstone(pattern) {
4191
4631
  const now = Date.now();
4192
4632
  while (this._patternTombstones.length > 0 && now - this._patternTombstones[0].createdAt > 36e5) {
4193
- this._patternTombstones.shift();
4633
+ const forgotten = this._patternTombstones.shift();
4634
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
4194
4635
  }
4195
4636
  if (this._patternTombstones.length >= 2e3) {
4196
- this._patternTombstones.shift();
4637
+ const forgotten = this._patternTombstones.shift();
4638
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
4197
4639
  }
4198
- this._patternTombstones.push({ prefix, createdAt: now });
4640
+ this._patternTombstones.push({ pattern, createdAt: now });
4199
4641
  }
4200
- _isTombstonedByPattern(namespacedKey) {
4642
+ _isTombstonedByPattern(namespacedKey, setAt = 0) {
4643
+ if (this._diskInvalidatedBefore > 0 && setAt <= this._diskInvalidatedBefore) return true;
4201
4644
  if (this._patternTombstones.length === 0) return false;
4202
4645
  for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
4203
- if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
4646
+ if (setAt <= this._patternTombstones[i].createdAt && this._matchesGlob(namespacedKey, this._patternTombstones[i].pattern)) {
4204
4647
  return true;
4205
4648
  }
4206
4649
  }
@@ -4215,13 +4658,86 @@ return 0
4215
4658
  const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
4216
4659
  this._keyMutationEpochs.set(namespacedKey, next);
4217
4660
  if (this._keyMutationEpochs.size > 5e4) {
4218
- const oldest = this._keyMutationEpochs.keys().next().value;
4219
- if (oldest !== void 0) this._keyMutationEpochs.delete(oldest);
4661
+ this._globalEpoch++;
4662
+ this._keyMutationEpochs.clear();
4663
+ this._keyMutationEpochs.set(namespacedKey, next);
4220
4664
  }
4221
4665
  return next;
4222
4666
  }
4223
4667
  _getKeyMutationEpoch(namespacedKey) {
4224
- 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);
4225
4741
  }
4226
4742
  _removeKeyTags(namespacedKey) {
4227
4743
  const entry = this.keyTags.get(namespacedKey);
@@ -4255,21 +4771,21 @@ return 0
4255
4771
  }
4256
4772
  }
4257
4773
  _handleL1Eviction(namespacedKey, reason) {
4258
- const spilledToDisk = !this._diskDisabled && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
4774
+ const spilledToDisk = !this._diskDisabled && !this._suppressSpills && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
4259
4775
  if (!spilledToDisk) {
4260
4776
  this._removeKeyTags(namespacedKey);
4261
4777
  this._removeKeyDependencies(namespacedKey);
4262
4778
  }
4263
4779
  }
4264
- _removePrefixFromIndices(prefix) {
4780
+ _removePatternFromIndices(pattern) {
4265
4781
  for (const k of Array.from(this.keyTags.keys())) {
4266
- if (k.startsWith(prefix)) this._removeKeyTags(k);
4782
+ if (this._matchesGlob(k, pattern)) this._removeKeyTags(k);
4267
4783
  }
4268
4784
  for (const k of Array.from(this.keyDependencies.keys())) {
4269
- if (k.startsWith(prefix)) this._removeKeyDependencies(k);
4785
+ if (this._matchesGlob(k, pattern)) this._removeKeyDependencies(k);
4270
4786
  }
4271
4787
  for (const k of Array.from(this._l1Counters.keys())) {
4272
- if (k.startsWith(prefix)) this._l1Counters.delete(k);
4788
+ if (this._matchesGlob(k, pattern)) this._l1Counters.delete(k);
4273
4789
  }
4274
4790
  }
4275
4791
  _sweepExpiredMetadata() {
@@ -4287,10 +4803,16 @@ return 0
4287
4803
  _runOomCheck() {
4288
4804
  const heap = import_node_v82.default.getHeapStatistics();
4289
4805
  const heapUsed = heap.used_heap_size / heap.heap_size_limit;
4290
- const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? process.memoryUsage().rss / this._cgroupMemoryLimit : 0;
4806
+ const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? (readCgroupMemoryUsage() ?? process.memoryUsage().rss) / this._cgroupMemoryLimit : 0;
4291
4807
  const used = Math.max(heapUsed, cgroupUsed);
4292
4808
  if (used >= this.opts.oomHeapThreshold) {
4293
- const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
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
+ }
4294
4816
  this.counters.oomEvictions++;
4295
4817
  this.counters.oomLastAt = Date.now();
4296
4818
  this.logger.warn("tricache OOM guard: emergency L1 eviction", {
@@ -4526,9 +5048,13 @@ return 0
4526
5048
  admissionPolicy: this.opts.l1AdmissionPolicy,
4527
5049
  codec: this.codec,
4528
5050
  diskSpill: (key, entry) => {
4529
- 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++;
4530
5055
  setImmediate(() => {
4531
- void this.disk.save(key, entry);
5056
+ this._pendingSpillCount--;
5057
+ if (!this._destroyed && this._getKeyMutationEpoch(key) === epoch) void this.disk.save(key, entry);
4532
5058
  });
4533
5059
  },
4534
5060
  onEviction: (key, reason) => {
@@ -4607,7 +5133,7 @@ return 0
4607
5133
  this.instanceId = import_crypto3.default.randomBytes(8).toString("hex");
4608
5134
  this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
4609
5135
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
4610
- 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 }));
4611
5137
  const startupPromises = [];
4612
5138
  if (this.opts.compression === "zstd") {
4613
5139
  startupPromises.push(initZstd().then(() => void 0));
@@ -4618,9 +5144,8 @@ return 0
4618
5144
  if (this.opts.warmKeys) {
4619
5145
  startupPromises.push(this.warmFromL2(this.opts.warmKeys).then(() => void 0));
4620
5146
  }
4621
- if (startupPromises.length > 0) {
4622
- this._readyPromise = Promise.all(startupPromises).then(() => void 0);
4623
- }
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);
4624
5149
  if (this.opts.meter) {
4625
5150
  this._initOtelMetrics(this.opts.meter);
4626
5151
  const otel = this._otelMetrics;
@@ -4633,7 +5158,10 @@ return 0
4633
5158
  if (typeof prop === "string" && typeof value === "number" && typeof oldVal === "number") {
4634
5159
  const diff = value - oldVal;
4635
5160
  if (diff > 0 && otel[prop]) {
4636
- otel[prop].add(diff, nsAttr);
5161
+ try {
5162
+ otel[prop].add(diff, nsAttr);
5163
+ } catch {
5164
+ }
4637
5165
  }
4638
5166
  }
4639
5167
  return ok;
@@ -4725,7 +5253,7 @@ return 0
4725
5253
  return g[key];
4726
5254
  }
4727
5255
  const existing = g[key];
4728
- const diff = _CacheService.optionsDiff(options ?? {}, existing.options);
5256
+ const diff = _CacheService.optionsDiff(options ?? {}, existing.opts);
4729
5257
  if (diff.length > 0) {
4730
5258
  existing.bumpSingletonDivergence();
4731
5259
  const msg = `tricache: singleton already initialised for namespace '${existing.options.namespace || "(default)"}' \u2014 ignoring divergent options: ${diff.join(", ")}`;
@@ -4759,7 +5287,13 @@ return 0
4759
5287
  "instanceName",
4760
5288
  "invalidationBackplane",
4761
5289
  "awaitInvalidationBackplane",
4762
- "lockFailClosed"
5290
+ "lockFailClosed",
5291
+ "tagStrategy",
5292
+ "cloneStrategy",
5293
+ "compression",
5294
+ "backplaneMode",
5295
+ "redisProtocol",
5296
+ "failClosed"
4763
5297
  ];
4764
5298
  /** Returns the names of options that differ between `a` and the live `b`. */
4765
5299
  static optionsDiff(a, b) {
@@ -4777,12 +5311,12 @@ return 0
4777
5311
  bumpSingletonDivergence() {
4778
5312
  this.counters.singletonDivergences++;
4779
5313
  }
4780
- /** Read-only view of the options the singleton was constructed with. */
5314
+ /** Sanitized diagnostic view; retain the original options/adapters to reuse configuration. */
4781
5315
  get options() {
4782
5316
  const o = this.opts;
4783
5317
  return {
4784
5318
  namespace: o.namespace,
4785
- 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) },
4786
5320
  l1MaxBytes: o.l1MaxBytes,
4787
5321
  l1MaxEntries: o.l1MaxEntries,
4788
5322
  redisHost: o.redisHost,
@@ -4803,8 +5337,8 @@ return 0
4803
5337
  awaitInvalidationBackplane: o.awaitInvalidationBackplane,
4804
5338
  lockFailClosed: o.lockFailClosed,
4805
5339
  strictSingleton: o.strictSingleton,
4806
- remoteSnapshot: o.remoteSnapshot,
4807
- crossRegion: o.crossRegion
5340
+ remoteSnapshot: redactDiagnostics(o.remoteSnapshot),
5341
+ crossRegion: redactDiagnostics(o.crossRegion)
4808
5342
  };
4809
5343
  }
4810
5344
  /**
@@ -4887,21 +5421,26 @@ return 0
4887
5421
  if (this.opts.redisClient && typeof this.opts.redisClient.duplicate === "function") {
4888
5422
  return this.opts.redisClient.duplicate();
4889
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
+ }
4890
5427
  if (this.opts.redisClusterNodes?.length) {
4891
- return new import_ioredis.Cluster(this.opts.redisClusterNodes, {
5428
+ return new import_ioredis2.Cluster(this.opts.redisClusterNodes, {
4892
5429
  redisOptions: {
4893
5430
  tls: this.opts.redisTls ? {} : void 0,
4894
5431
  connectTimeout: 1e4,
5432
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
4895
5433
  maxRetriesPerRequest: null,
4896
5434
  ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
4897
5435
  }
4898
5436
  });
4899
5437
  } else if (this.opts.redisSentinel) {
4900
- return new import_ioredis.Redis({
5438
+ return new import_ioredis2.Redis({
4901
5439
  sentinels: this.opts.redisSentinel.sentinels,
4902
5440
  name: this.opts.redisSentinel.name,
4903
5441
  tls: this.opts.redisTls ? {} : void 0,
4904
5442
  connectTimeout: 1e4,
5443
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
4905
5444
  lazyConnect: true,
4906
5445
  maxRetriesPerRequest: null,
4907
5446
  enableAutoPipelining: false,
@@ -4909,11 +5448,12 @@ return 0
4909
5448
  ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
4910
5449
  });
4911
5450
  } else {
4912
- return new import_ioredis.Redis({
5451
+ return new import_ioredis2.Redis({
4913
5452
  host: this.opts.redisHost,
4914
5453
  port: this.opts.redisPort,
4915
5454
  tls: this.opts.redisTls ? {} : void 0,
4916
5455
  connectTimeout: 1e4,
5456
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
4917
5457
  lazyConnect: true,
4918
5458
  maxRetriesPerRequest: null,
4919
5459
  enableAutoPipelining: false,
@@ -4923,26 +5463,32 @@ return 0
4923
5463
  });
4924
5464
  }
4925
5465
  }
4926
- initBackplane() {
5466
+ _listenBackplane(client, event, listener) {
5467
+ client.on?.(event, listener);
5468
+ this._backplaneDisposers.push(() => client.removeListener?.(event, listener));
5469
+ }
5470
+ async initBackplane() {
4927
5471
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
4928
5472
  if (this.opts.backplaneMode === "stream") {
4929
5473
  if (this.streamClient) return;
4930
- void this._startStreamConsumer();
5474
+ await this._startStreamConsumer();
4931
5475
  return;
4932
5476
  }
4933
5477
  if (this.subClient) return;
4934
5478
  const sub = this.createDedicatedRedisClient();
4935
- sub.on("error", (e) => {
5479
+ this.subClient = sub;
5480
+ this._listenBackplane(sub, "error", (e) => {
4936
5481
  this._checkAndLogResp3Hint(e);
4937
5482
  this.logger.debug("Backplane subscriber error", { error: e.message });
4938
5483
  });
4939
- sub.on("close", () => {
5484
+ this._listenBackplane(sub, "close", () => {
5485
+ this._backplaneAvailable = false;
4940
5486
  if (this._subDisconnectedAt === null) {
4941
5487
  this._subDisconnectedAt = Date.now();
4942
5488
  this.logger.debug("Backplane: subscriber disconnected", { at: this._subDisconnectedAt });
4943
5489
  }
4944
5490
  });
4945
- sub.on("ready", () => {
5491
+ this._listenBackplane(sub, "ready", () => {
4946
5492
  if (this._subDisconnectedAt !== null && this.opts.backplaneMaxStalenessMs > 0) {
4947
5493
  const gapMs = Date.now() - this._subDisconnectedAt;
4948
5494
  if (gapMs > this.opts.backplaneMaxStalenessMs) {
@@ -4955,52 +5501,119 @@ return 0
4955
5501
  }
4956
5502
  this._subDisconnectedAt = null;
4957
5503
  }
5504
+ if (!this._destroyed) this._backplaneAvailable = true;
4958
5505
  });
4959
5506
  const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
4960
5507
  if (isClusterSharded) {
4961
- sub.on("smessage", (_channel, message) => {
5508
+ this._listenBackplane(sub, "smessage", (_channel, message) => {
4962
5509
  this._handleBackplaneMessage(message);
4963
5510
  });
4964
- 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", {
4965
5513
  channel: this.backplaneChannel,
4966
5514
  instanceId: this.instanceId
4967
- })).catch((err) => this.logger.warn("Backplane: sharded subscribe failed", {
4968
- error: err.message
4969
5515
  }));
4970
5516
  } else {
4971
- sub.on("message", (_channel, message) => {
5517
+ this._listenBackplane(sub, "message", (_channel, message) => {
4972
5518
  this._handleBackplaneMessage(message);
4973
5519
  });
4974
- 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", {
4975
5523
  channel: this.backplaneChannel,
4976
5524
  instanceId: this.instanceId
4977
- })).catch((err) => this.logger.warn("Backplane: subscribe failed", {
4978
- error: err.message
4979
5525
  }));
4980
5526
  }
4981
- 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";
4982
5541
  }
4983
5542
  async _startStreamConsumer() {
5543
+ this._streamRecovering ||= this._lastStreamId !== "$" && this._lastStreamId !== "0-0";
4984
5544
  const sub = this.streamClient ?? this.createDedicatedRedisClient();
4985
5545
  this.streamClient = sub;
5546
+ if (typeof sub.xread !== "function") throw new Error("backplaneMode: stream requires a driver supporting XREAD");
4986
5547
  if (typeof sub.on === "function") {
4987
- sub.on("error", (e) => this.logger.debug("Backplane stream consumer error", { error: e.message }));
4988
- 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;
4989
5552
  if (this._subDisconnectedAt === null) {
4990
5553
  this._subDisconnectedAt = Date.now();
4991
5554
  this.logger.debug("Backplane stream: consumer disconnected", { at: this._subDisconnectedAt });
4992
5555
  }
4993
5556
  });
4994
- sub.on("ready", () => {
5557
+ this._listenBackplane(sub, "ready", () => {
4995
5558
  if (this._subDisconnectedAt !== null) {
4996
5559
  this.logger.debug("Backplane stream: consumer reconnected, resuming stream read", { lastId: this._lastStreamId });
4997
5560
  this._subDisconnectedAt = null;
4998
5561
  }
4999
5562
  });
5000
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
+ }
5001
5611
  const runLoop = async () => {
5002
5612
  while (!this._destroyed && !this._redisDisabled) {
5003
5613
  try {
5614
+ if (!initialized) await initialize();
5615
+ if (this._destroyed) break;
5616
+ await checkGap();
5004
5617
  const res = await sub.xread(
5005
5618
  "BLOCK",
5006
5619
  this.opts.backplaneStreamBlockMs,
@@ -5009,19 +5622,10 @@ return 0
5009
5622
  this._lastStreamId
5010
5623
  );
5011
5624
  if (this._destroyed) break;
5625
+ this._backplaneAvailable = true;
5012
5626
  if (res && res.length > 0) {
5013
- for (const [, entries] of res) {
5014
- if (entries.length > 0) {
5015
- if (this._lastStreamId !== "$") {
5016
- this.counters.streamReplays++;
5017
- }
5018
- for (const [id, fields] of entries) {
5019
- this._lastStreamId = id;
5020
- this.counters.streamEntriesReceived++;
5021
- this._processStreamEntry(fields);
5022
- }
5023
- }
5024
- }
5627
+ apply(res);
5628
+ this._backplaneAvailable = true;
5025
5629
  } else {
5026
5630
  await new Promise((resolve) => setTimeout(resolve, 10));
5027
5631
  }
@@ -5029,10 +5633,9 @@ return 0
5029
5633
  if (this._destroyed) break;
5030
5634
  const msg = err.message ?? "";
5031
5635
  if (msg.includes("NOGROUP") || msg.includes("smaller than") || msg.includes("trimmed")) {
5032
- this.counters.streamGaps++;
5033
- this.l1.clear();
5034
- this._lastStreamId = "$";
5636
+ this._resetAfterStreamGap();
5035
5637
  }
5638
+ this._backplaneAvailable = false;
5036
5639
  await new Promise((resolve) => setTimeout(resolve, 200));
5037
5640
  }
5038
5641
  }
@@ -5061,7 +5664,7 @@ return 0
5061
5664
  else if (f === "tagVersion") tagVersionRaw = v;
5062
5665
  }
5063
5666
  const validOp = op === "del" || op === "del-glob" || op === "tag_incr" || op === "tag_pattern_incr" || op === "tag_pattern_del";
5064
- if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
5667
+ if (!validOp || typeof key !== "string" || !key || typeof src !== "string" || !src || (op === "del" || op === "del-glob") && this._namespace && !key.startsWith(`${this._namespace}:`)) {
5065
5668
  this.logger.warn("Backplane: rejected invalid stream entry", {
5066
5669
  op: String(op).slice(0, 40),
5067
5670
  key: typeof key === "string" ? key.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(key)
@@ -5070,8 +5673,8 @@ return 0
5070
5673
  }
5071
5674
  let tagVersion;
5072
5675
  if (tagVersionRaw !== void 0) {
5073
- const parsed = parseInt(tagVersionRaw, 10);
5074
- if (!Number.isFinite(parsed)) {
5676
+ const parsed = Number(tagVersionRaw);
5677
+ if (!Number.isSafeInteger(parsed) || parsed < 0) {
5075
5678
  this.logger.warn("Backplane: rejected stream entry with non-numeric tagVersion", { key });
5076
5679
  return;
5077
5680
  }
@@ -5089,16 +5692,10 @@ return 0
5089
5692
  this.l1.delete(key);
5090
5693
  this._bumpKeyMutation(key);
5091
5694
  this.inflight.delete(key);
5092
- this._pendingDiskDeletes.add(key);
5093
- setImmediate(() => {
5094
- try {
5095
- if (!this._diskDisabled) this.disk.delete(key);
5096
- } finally {
5097
- this._pendingDiskDeletes.delete(key);
5098
- }
5099
- });
5695
+ this._invalidateDiskKey(key);
5100
5696
  this._cascadeDependencies(key);
5101
5697
  } else if (op === "del-glob") {
5698
+ this._fenceInvalidation();
5102
5699
  this.l1.deletePattern(key);
5103
5700
  const pfx = key.endsWith("*") ? key.slice(0, -1) : key;
5104
5701
  for (const liveKey of this.l1.liveKeys()) {
@@ -5112,12 +5709,22 @@ return 0
5112
5709
  this.inflight.delete(inflightKey);
5113
5710
  }
5114
5711
  }
5115
- 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
+ }
5116
5721
  } else if (op === "tag_incr") {
5722
+ this._fenceInvalidation();
5117
5723
  const tag = key;
5118
5724
  const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
5119
5725
  this._setLocalTagVersion(tag, ver, performance.now());
5120
5726
  } else if (op === "tag_pattern_incr") {
5727
+ this._fenceInvalidation();
5121
5728
  const pattern = key;
5122
5729
  const now = performance.now();
5123
5730
  for (const [tag, info] of this.tagVersions) {
@@ -5137,6 +5744,7 @@ return 0
5137
5744
  }
5138
5745
  }, 0);
5139
5746
  } else if (op === "tag_pattern_del") {
5747
+ this._fenceInvalidation();
5140
5748
  const pattern = key;
5141
5749
  const matchedTagKeys = [];
5142
5750
  const prefix = this.nk("_tag_:");
@@ -5147,14 +5755,7 @@ return 0
5147
5755
  for (const k of members) {
5148
5756
  this.l1.delete(k);
5149
5757
  this._bumpKeyMutation(k);
5150
- this._pendingDiskDeletes.add(k);
5151
- setImmediate(() => {
5152
- try {
5153
- if (!this._diskDisabled) this.disk.delete(k);
5154
- } finally {
5155
- this._pendingDiskDeletes.delete(k);
5156
- }
5157
- });
5758
+ this._invalidateDiskKey(k);
5158
5759
  }
5159
5760
  }
5160
5761
  }
@@ -5185,6 +5786,7 @@ return 0
5185
5786
  }
5186
5787
  }
5187
5788
  async publishInvalidation(op, key, tagVersion, isCrossRegionRelay = false, isExplicitInvalidation = false) {
5789
+ if (this.opts.l2WriteMode === "read-only") return;
5188
5790
  if (!isCrossRegionRelay && this.opts.crossRegion) {
5189
5791
  const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
5190
5792
  if (shouldBroadcast) {
@@ -5267,13 +5869,13 @@ return 0
5267
5869
  timestamp: Date.now(),
5268
5870
  namespace: this._namespace || void 0
5269
5871
  };
5270
- this.counters.crossRegionSent++;
5271
5872
  await cr.relay.broadcast(event);
5873
+ this.counters.crossRegionSent++;
5272
5874
  this.logger.debug("Cross-region invalidation broadcast", { op, key, region: cr.currentRegion });
5273
5875
  } catch (err) {
5274
- this.counters.crossRegionSent = Math.max(0, this.counters.crossRegionSent - 1);
5275
5876
  this.counters.crossRegionErrors++;
5276
5877
  this.logger.warn("Cross-region invalidation broadcast failed", { error: err.message });
5878
+ if (this.opts.awaitInvalidationBackplane) throw err;
5277
5879
  }
5278
5880
  }
5279
5881
  /**
@@ -5284,11 +5886,12 @@ return 0
5284
5886
  * Returns true if the event was accepted and applied, or false if ignored/deduplicated.
5285
5887
  */
5286
5888
  async receiveCrossRegionInvalidation(event) {
5889
+ this._assertActive("receiveCrossRegionInvalidation");
5287
5890
  const cr = this.opts.crossRegion;
5288
5891
  if (!cr) return false;
5289
- if (!event || typeof event !== "object" || !event.id || !event.originRegion || !event.op || !event.key) {
5892
+ if (!isCrossRegionInvalidationEvent(event)) {
5290
5893
  this.counters.crossRegionErrors++;
5291
- this.logger.warn("Cross-region: rejected invalid event payload", { event });
5894
+ this.logger.warn("Cross-region: rejected invalid event payload");
5292
5895
  return false;
5293
5896
  }
5294
5897
  if (event.originRegion === cr.currentRegion) {
@@ -5299,13 +5902,52 @@ return 0
5299
5902
  this.counters.crossRegionDeduplicated++;
5300
5903
  return false;
5301
5904
  }
5302
- this._markCrossRegionEventSeen(event.id);
5303
5905
  if (event.namespace !== void 0 && event.namespace !== (this._namespace || void 0)) {
5304
5906
  return false;
5305
5907
  }
5908
+ if ((event.op === "del" || event.op === "del-glob") && this._namespace && !event.key.startsWith(`${this._namespace}:`)) return false;
5909
+ this._markCrossRegionEventSeen(event.id);
5306
5910
  this.counters.crossRegionReceived++;
5307
- this._applyInvalidationEvent(event.op, event.key, event.tagVersion);
5308
- 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
+ }
5309
5951
  this.logger.info("Cross-region invalidation applied", {
5310
5952
  op: event.op,
5311
5953
  key: event.key,
@@ -5320,10 +5962,10 @@ return 0
5320
5962
  const oldestKey = this.tagVersions.keys().next().value;
5321
5963
  if (oldestKey !== void 0) this.tagVersions.delete(oldestKey);
5322
5964
  }
5323
- this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
5965
+ this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now, refreshEpoch: this._tagRefreshEpoch });
5324
5966
  }
5325
5967
  async _isGenerationalEntryStale(tagVersions) {
5326
- if (this.opts.tagStrategy !== "generational" || !tagVersions) return false;
5968
+ if (!tagVersions) return false;
5327
5969
  const tags = Object.keys(tagVersions);
5328
5970
  if (tags.length === 0) return false;
5329
5971
  const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
@@ -5335,13 +5977,23 @@ return 0
5335
5977
  async _deleteRedisKeys(client, keys) {
5336
5978
  if (keys.length === 0) return;
5337
5979
  const CHUNK_SIZE = 1e3;
5338
- if (client instanceof import_ioredis.Cluster) {
5339
- for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
5340
- const chunk = keys.slice(i, i + CHUNK_SIZE);
5341
- const pl = client.pipeline();
5342
- for (const k of chunk) pl.del(k);
5343
- await pl.exec();
5344
- }
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
+ }));
5345
5997
  return;
5346
5998
  }
5347
5999
  for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
@@ -5354,8 +6006,11 @@ return 0
5354
6006
  let storedTagVersions = {};
5355
6007
  if (hashData.tv) {
5356
6008
  try {
5357
- storedTagVersions = JSON.parse(hashData.tv);
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;
5358
6012
  } catch {
6013
+ return null;
5359
6014
  }
5360
6015
  }
5361
6016
  if (await this._isGenerationalEntryStale(storedTagVersions)) {
@@ -5364,18 +6019,48 @@ return 0
5364
6019
  return { stale: true };
5365
6020
  }
5366
6021
  const value = await this._decryptAndDeserialize(hashData.d);
5367
- return { value, tagVersions: storedTagVersions, stale: false };
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
+ };
5368
6044
  }
5369
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
+ };
5370
6055
  if (this.opts.tagStrategy === "generational" && typeof client.hgetall === "function") {
5371
6056
  try {
5372
- const hashData = await client.hgetall(k);
6057
+ const { raw: hashData, ttlMs: ttlMs2 } = await read(true);
5373
6058
  if (typeof hashData === "string") {
5374
6059
  const value2 = await this._decryptAndDeserialize(hashData);
5375
- return { value: value2, stale: false };
6060
+ return withExpiry({ value: value2, stale: false }, ttlMs2);
5376
6061
  }
5377
6062
  if (hashData && hashData.d) {
5378
- return await this._parseGenerationalRedisHash(k, hashData);
6063
+ return withExpiry(await this._parseGenerationalRedisHash(k, hashData), ttlMs2);
5379
6064
  }
5380
6065
  return null;
5381
6066
  } catch (err) {
@@ -5383,28 +6068,163 @@ return 0
5383
6068
  if (!msg.includes("WRONGTYPE")) throw err;
5384
6069
  }
5385
6070
  }
5386
- const raw = allowAutoPipeline && this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
6071
+ const { raw, ttlMs } = await read(false);
5387
6072
  if (raw == null) return null;
6073
+ if (typeof raw !== "string") return null;
5388
6074
  const value = await this._decryptAndDeserialize(raw);
5389
- return { value, stale: false };
6075
+ return withExpiry({ value, stale: false }, ttlMs);
5390
6076
  }
5391
6077
  async _getTagVersion(tag) {
5392
6078
  const now = performance.now();
5393
6079
  const local = this.tagVersions.get(tag);
5394
- if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
6080
+ if (local && (local.refreshEpoch ?? 0) === this._tagRefreshEpoch && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
5395
6081
  return local.version;
5396
6082
  }
5397
6083
  if (!this._redisDisabled) {
5398
6084
  try {
5399
6085
  const client = await this.getRedis();
5400
6086
  const raw = await client.get(this.nk(`tag_ver:${tag}`));
5401
- const version = raw ? parseInt(raw, 10) : 0;
5402
- this._setLocalTagVersion(tag, version, now);
5403
- 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;
5404
6097
  } catch {
5405
6098
  }
5406
6099
  }
5407
- 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();
5408
6228
  }
5409
6229
  _deleteIfStale(k, setAtMs) {
5410
6230
  this.l1.deleteIfSetBefore(k, setAtMs);
@@ -5457,7 +6277,7 @@ return 0
5457
6277
  } else {
5458
6278
  plain = raw;
5459
6279
  }
5460
- return JSON.parse(plain);
6280
+ return plain === "undefined" ? void 0 : JSON.parse(plain);
5461
6281
  }
5462
6282
  /**
5463
6283
  * Scan all keys matching `pattern` across single-node or Cluster clients.
@@ -5465,7 +6285,7 @@ return 0
5465
6285
  */
5466
6286
  async _scanKeys(client, pattern) {
5467
6287
  const keys = [];
5468
- if (client instanceof import_ioredis.Cluster) {
6288
+ if (client instanceof import_ioredis2.Cluster) {
5469
6289
  const masters = client.nodes("master");
5470
6290
  await Promise.all(masters.map(
5471
6291
  (node) => new Promise((resolve, reject) => {
@@ -5528,7 +6348,7 @@ return 0
5528
6348
  let client = null;
5529
6349
  try {
5530
6350
  if (this.opts.redisClusterNodes?.length) {
5531
- client = new import_ioredis.Cluster(this.opts.redisClusterNodes, {
6351
+ client = new import_ioredis2.Cluster(this.opts.redisClusterNodes, {
5532
6352
  redisOptions: {
5533
6353
  tls: this.opts.redisTls ? {} : void 0,
5534
6354
  connectTimeout: 1e4,
@@ -5548,7 +6368,7 @@ return 0
5548
6368
  });
5549
6369
  client.on("reconnecting", () => this.logger.debug("Redis Cluster reconnecting"));
5550
6370
  } else if (this.opts.redisSentinel) {
5551
- client = new import_ioredis.Redis({
6371
+ client = new import_ioredis2.Redis({
5552
6372
  sentinels: this.opts.redisSentinel.sentinels,
5553
6373
  name: this.opts.redisSentinel.name,
5554
6374
  tls: this.opts.redisTls ? {} : void 0,
@@ -5568,7 +6388,7 @@ return 0
5568
6388
  });
5569
6389
  client.on("reconnecting", () => this.logger.debug("Redis Sentinel reconnecting"));
5570
6390
  } else {
5571
- client = new import_ioredis.Redis({
6391
+ client = new import_ioredis2.Redis({
5572
6392
  host: this.opts.redisHost,
5573
6393
  port: this.opts.redisPort,
5574
6394
  tls: this.opts.redisTls ? {} : void 0,
@@ -5660,7 +6480,12 @@ return 0
5660
6480
  try {
5661
6481
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
5662
6482
  if (entries.length === 0) return;
5663
- 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
+ };
5664
6489
  const packed = this.codec.encode(payload);
5665
6490
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
5666
6491
  const dest = altPath ?? this.opts.snapshotPath;
@@ -5728,6 +6553,9 @@ return 0
5728
6553
  return;
5729
6554
  }
5730
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);
5731
6559
  this.logger.info("Cache snapshot loaded (L1 is warm)", {
5732
6560
  loaded,
5733
6561
  total: snapshot.entries.length,
@@ -5752,7 +6580,12 @@ return 0
5752
6580
  try {
5753
6581
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
5754
6582
  if (entries.length === 0) return false;
5755
- 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
+ };
5756
6589
  const packed = this.codec.encode(payload);
5757
6590
  let final;
5758
6591
  if (this.opts.remoteSnapshot.envelope) {
@@ -5783,13 +6616,16 @@ return 0
5783
6616
  async loadRemoteSnapshot() {
5784
6617
  if (!this.opts.remoteSnapshot) return 0;
5785
6618
  const maxAgeMs = this.opts.remoteSnapshot.maxAgeMs ?? this.opts.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE;
6619
+ const epoch = this._globalEpoch;
5786
6620
  try {
5787
6621
  const raw = await this.opts.remoteSnapshot.adapter.get();
6622
+ if (this._destroyed || this._globalEpoch !== epoch) return 0;
5788
6623
  if (!raw || raw.length === 0) {
5789
6624
  this.logger.debug("Remote snapshot not found or empty \u2014 starting cold");
5790
6625
  return 0;
5791
6626
  }
5792
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");
5793
6629
  let buf;
5794
6630
  try {
5795
6631
  if (EnvelopeEncryption.isEnvelope(rawBuf)) {
@@ -5835,7 +6671,12 @@ return 0
5835
6671
  this.logger.warn("Remote snapshot rejected: entries is not an array");
5836
6672
  return 0;
5837
6673
  }
5838
- 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);
5839
6680
  this.counters.remoteSnapshotDownloads++;
5840
6681
  this.counters.remoteSnapshotLastDownloadedAt = Date.now();
5841
6682
  this.logger.info("Remote cache snapshot loaded (L1 hydrated)", {
@@ -5887,7 +6728,7 @@ return 0
5887
6728
  const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
5888
6729
  if (isGenerationalStale) {
5889
6730
  this._deleteIfStale(k, l1Hit.setAt ?? 0);
5890
- } else {
6731
+ } else if (!l1Hit.isStale || optSwr > 0) {
5891
6732
  if (l1Hit.isStale) {
5892
6733
  const swrGraceMs2 = optSwr * 1e3;
5893
6734
  if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
@@ -5950,49 +6791,29 @@ return 0
5950
6791
  this.counters.stampedes++;
5951
6792
  this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch/read", { cacheKey });
5952
6793
  span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
5953
- return existing;
6794
+ return this._prepareReadValue(await existing);
5954
6795
  }
5955
6796
  const mutationEpochAtStart = this._getKeyMutationEpoch(k);
5956
- const executionPromise = (async () => {
6797
+ const executionPromise = Promise.resolve().then(async () => {
5957
6798
  try {
5958
- if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
5959
- if (this._isTombstonedByPattern(k)) {
5960
- try {
5961
- this.disk.delete(k);
5962
- } catch {
5963
- }
5964
- } else {
5965
- const isDiskAllowed = this.watchdog.isDiskAllowed();
5966
- if (isDiskAllowed) {
5967
- const diskStart = performance.now();
5968
- const diskHit = this.disk.load(k);
5969
- const diskElapsed = performance.now() - diskStart;
5970
- this.watchdog.recordDisk(diskElapsed);
5971
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
5972
- if (diskHit !== null) {
5973
- const isDiskStale = await this._isGenerationalEntryStale(diskHit.tagVersions);
5974
- if (isDiskStale) {
5975
- this.disk.delete(k);
5976
- } else {
5977
- const promoted = this.l1.importEntries(
5978
- [{ key: k, entry: diskHit }],
5979
- this.opts.forbiddenSnapshotPrefixes
5980
- );
5981
- if (promoted > 0) {
5982
- const l1Check = this.l1.get(k);
5983
- if (l1Check !== null) {
5984
- this.counters.diskHits++;
5985
- this.opts.onHit?.(cacheKey, "disk");
5986
- this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
5987
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
5988
- if (this.opts.frozen) deepFreeze(l1Check.value);
5989
- return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
5990
- }
5991
- }
5992
- }
5993
- }
5994
- }
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
+ );
5995
6815
  }
6816
+ return diskHit.value;
5996
6817
  }
5997
6818
  if (!this._redisDisabled) {
5998
6819
  try {
@@ -6002,23 +6823,26 @@ return 0
6002
6823
  const redisElapsed = performance.now() - redisStart;
6003
6824
  this.watchdog.recordRedis(redisElapsed);
6004
6825
  this.cb.onSuccess();
6005
- if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
6826
+ if (redisHit && !redisHit.stale && (redisHit.staleAt === void 0 || redisHit.staleAt > Date.now() || optSwr > 0)) {
6006
6827
  const parsed = redisHit.value;
6007
6828
  if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
6008
6829
  this.logger.debug("Aborting L2 promotion \u2014 key was mutated or deleted during Redis read", { cacheKey });
6009
6830
  span.setAttribute("cache.aborted_mutation_race", true);
6010
6831
  const current = this.l1.get(k);
6011
- const liveVal = current && !current.isStale && current.value !== void 0 ? current.value : parsed;
6012
- if (this.opts.frozen) deepFreeze(liveVal);
6013
- return this.opts.cloneStrategy === "structuredClone" && liveVal != null && typeof liveVal === "object" ? structuredClone(liveVal) : liveVal;
6832
+ const liveVal = current && !current.isStale ? current.value : parsed;
6833
+ return liveVal;
6014
6834
  }
6015
- this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, redisHit.tagVersions);
6835
+ if (!this._promoteRedisEntry(k, redisHit, ttlMs, priority)) throw new Error("Redis entry expired during promotion");
6016
6836
  this.counters.l2Hits++;
6017
6837
  this.opts.onHit?.(cacheKey, "l2");
6018
6838
  this.logger.debug(redisHit.tagVersions ? "L2 hit (Redis hash)" : "L2 hit (Redis)", { cacheKey });
6019
6839
  span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
6020
- if (this.opts.frozen) deepFreeze(parsed);
6021
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
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);
6844
+ }
6845
+ return parsed;
6022
6846
  }
6023
6847
  } catch (err) {
6024
6848
  this.cb.onFailure();
@@ -6028,6 +6852,7 @@ return 0
6028
6852
  span.setAttribute("cache.hit", false).setAttribute("cache.hit_tier", "miss");
6029
6853
  this.opts.onMiss?.(cacheKey);
6030
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;
6031
6856
  const fetchStart = Date.now();
6032
6857
  let data;
6033
6858
  try {
@@ -6056,50 +6881,41 @@ return 0
6056
6881
  }
6057
6882
  const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
6058
6883
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
6059
- let activeTagVersions;
6884
+ const activeTagVersions = tagSnapshot;
6060
6885
  if (optTags?.length) {
6061
6886
  if (this.opts.tagStrategy === "generational") {
6062
- const vers = await Promise.all(optTags.map((tag) => this._getTagVersion(tag)));
6063
- activeTagVersions = {};
6064
- for (let i = 0; i < optTags.length; i++) {
6065
- activeTagVersions[optTags[i]] = vers[i];
6066
- }
6887
+ if (await this._isGenerationalEntryStale(tagSnapshot)) return data;
6067
6888
  } else {
6068
- await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
6889
+ await this._registerTags(k, optTags, Math.ceil(storeTtl / 1e3));
6069
6890
  }
6070
6891
  }
6071
6892
  if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
6072
6893
  this.logger.debug("Aborting in-flight cache commit \u2014 key was mutated or deleted during fetch", { cacheKey });
6073
6894
  span.setAttribute("cache.aborted_mutation_race", true);
6074
6895
  const current = this.l1.get(k);
6075
- if (current && !current.isStale && current.value !== void 0) {
6896
+ if (current && !current.isStale) {
6076
6897
  const freshVal = current.value;
6077
- if (this.opts.frozen) deepFreeze(freshVal);
6078
- return this.opts.cloneStrategy === "structuredClone" && freshVal != null && typeof freshVal === "object" ? structuredClone(freshVal) : freshVal;
6898
+ return freshVal;
6079
6899
  }
6080
- if (this.opts.frozen) deepFreeze(data);
6081
- return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
6900
+ return data;
6082
6901
  }
6083
6902
  const writeTs = Date.now();
6084
- this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs);
6085
- if (!this._redisDisabled) {
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") {
6086
6907
  try {
6087
- const client = await this.getRedis();
6088
- const serialized = JSON.stringify(data);
6089
- const toStore = await this._serializeAndEncrypt(serialized);
6090
- const ttlSec = Math.ceil(effectiveTtl / 1e3);
6091
- if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
6092
- const tx = client.multi();
6093
- tx.hset(k, {
6094
- d: toStore,
6095
- t: String(writeTs),
6096
- tv: JSON.stringify(activeTagVersions ?? {})
6097
- });
6098
- tx.expire(k, ttlSec);
6099
- await tx.exec();
6100
- } else {
6101
- await client.setex(k, ttlSec, toStore);
6102
- }
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
+ );
6103
6919
  this.cb.onSuccess();
6104
6920
  this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
6105
6921
  } catch {
@@ -6109,15 +6925,14 @@ return 0
6109
6925
  } else {
6110
6926
  this.logger.debug("Cached L1", { cacheKey });
6111
6927
  }
6112
- if (this.opts.frozen) deepFreeze(data);
6113
- return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
6928
+ return data;
6114
6929
  } finally {
6115
- this.inflight.delete(k);
6930
+ if (this.inflight.get(k) === executionPromise) this.inflight.delete(k);
6116
6931
  span.end();
6117
6932
  }
6118
- })();
6933
+ });
6119
6934
  this.inflight.set(k, executionPromise);
6120
- return executionPromise;
6935
+ return this._prepareReadValue(await executionPromise);
6121
6936
  }
6122
6937
  /**
6123
6938
  * Graceful shutdown flusher for Kubernetes preStop hooks, NestJS onApplicationShutdown,
@@ -6198,6 +7013,9 @@ return 0
6198
7013
  }
6199
7014
  async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority, knownTagVersions) {
6200
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;
6201
7019
  try {
6202
7020
  const fetchStart = Date.now();
6203
7021
  const data = await fetchFn();
@@ -6212,14 +7030,14 @@ return 0
6212
7030
  const l1Existing = this.l1.get(cacheKey);
6213
7031
  const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
6214
7032
  if (this.opts.tagStrategy === "generational" && tagVersionsSource) {
6215
- const tags = Object.keys(tagVersionsSource);
6216
- 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)));
6217
7035
  activeTagVersions = {};
6218
- for (let i = 0; i < tags.length; i++) {
6219
- activeTagVersions[tags[i]] = vers[i];
7036
+ for (let i = 0; i < tags2.length; i++) {
7037
+ activeTagVersions[tags2[i]] = vers[i];
6220
7038
  }
6221
7039
  if (knownTagVersions) {
6222
- for (const t of tags) {
7040
+ for (const t of tags2) {
6223
7041
  if (knownTagVersions[t] !== void 0 && activeTagVersions[t] !== knownTagVersions[t]) {
6224
7042
  this.logger.debug("SWR: aborting revalidation commit \u2014 tag version bumped during revalidation", { cacheKey, tag: t });
6225
7043
  return;
@@ -6232,31 +7050,28 @@ return 0
6232
7050
  return;
6233
7051
  }
6234
7052
  const writeTs = Date.now();
6235
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs);
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 });
6236
7056
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6237
7057
  try {
6238
- const client = await this.getRedis();
6239
- const s = JSON.stringify(data);
6240
- const stored = await this._serializeAndEncrypt(s);
6241
- const ttlSec = Math.ceil(ttlMs / 1e3);
6242
- if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
6243
- const tx = client.multi();
6244
- tx.hset(cacheKey, {
6245
- d: stored,
6246
- t: String(writeTs),
6247
- tv: JSON.stringify(activeTagVersions ?? {})
6248
- });
6249
- tx.expire(cacheKey, ttlSec);
6250
- await tx.exec();
6251
- } else {
6252
- await client.setex(cacheKey, ttlSec, stored);
6253
- }
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
+ );
6254
7069
  } catch {
6255
7070
  }
6256
7071
  }
6257
7072
  this.logger.debug("SWR: revalidation complete", { cacheKey });
6258
7073
  } catch (err) {
6259
- if (this.opts.staleIfError > 0) {
7074
+ if (this.opts.staleIfError > 0 && this._getKeyMutationEpoch(cacheKey) === startEpoch) {
6260
7075
  const additionalMs = this.opts.staleIfError * 1e3;
6261
7076
  this.l1.bumpExpiry(cacheKey, additionalMs);
6262
7077
  this.logger.debug("SWR: revalidation failed, stale-if-error extending expiry", {
@@ -6284,12 +7099,16 @@ return 0
6284
7099
  const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
6285
7100
  const p = priority ?? inferPriority(cacheKey);
6286
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;
6287
7105
  this._bumpKeyMutation(k);
7106
+ const epoch = this._getKeyMutationEpoch(k);
6288
7107
  this.inflight.delete(k);
6289
- this._pendingDiskDeletes.delete(k);
7108
+ this._invalidateDiskKey(k);
6290
7109
  this.counters.sets++;
6291
7110
  let activeTagVersions;
6292
- 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;
6293
7112
  if (tagsToRegister?.length) {
6294
7113
  if (this.opts.tagStrategy === "generational") {
6295
7114
  const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
@@ -6298,50 +7117,27 @@ return 0
6298
7117
  activeTagVersions[tagsToRegister[i]] = vers[i];
6299
7118
  }
6300
7119
  } else {
6301
- await this._registerTags(k, tagsToRegister, ttlSeconds);
7120
+ await this._registerTags(k, tagsToRegister, effectiveTtlSeconds);
6302
7121
  }
6303
7122
  }
7123
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return;
6304
7124
  const writeTs = Date.now();
6305
- this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions, writeTs);
6306
- if (opts?.dependsOn !== void 0) {
6307
- this._removeKeyDependencies(k);
6308
- if (opts.dependsOn.length > 0) {
6309
- const nsPatterns = [];
6310
- for (const pattern of opts.dependsOn) {
6311
- const nsPattern = this.nk(pattern);
6312
- nsPatterns.push(nsPattern);
6313
- let deps = this.dependencyIndex.get(nsPattern);
6314
- if (!deps) {
6315
- deps = /* @__PURE__ */ new Set();
6316
- this.dependencyIndex.set(nsPattern, deps);
6317
- }
6318
- deps.add(k);
6319
- }
6320
- this.keyDependencies.set(k, nsPatterns);
6321
- }
6322
- }
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);
6323
7128
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6324
7129
  try {
6325
- const client = await this.getRedis();
6326
- const s = JSON.stringify(data);
6327
- const stored = await this._serializeAndEncrypt(s);
6328
- const ttlSec = Math.ceil(ttlMs / 1e3);
6329
- if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
6330
- const tx = client.multi();
6331
- tx.hset(k, {
6332
- d: stored,
6333
- t: String(writeTs),
6334
- tv: JSON.stringify(activeTagVersions ?? {})
6335
- });
6336
- tx.expire(k, ttlSec);
6337
- await tx.exec();
6338
- } else {
6339
- if (this.opts.autoPipeline && this.pipeliner) {
6340
- await this.pipeliner.setex(k, ttlSec, stored);
6341
- } else {
6342
- await client.setex(k, ttlSec, stored);
6343
- }
6344
- }
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
+ );
6345
7141
  this.cb.onSuccess();
6346
7142
  } catch (err) {
6347
7143
  this.cb.onFailure();
@@ -6366,27 +7162,10 @@ return 0
6366
7162
  * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
6367
7163
  */
6368
7164
  async _registerTags(k, tags, ttlSeconds) {
6369
- this._removeKeyTags(k);
6370
7165
  const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
6371
7166
  const expiresAt = Date.now() + effectiveTtl * 1e3;
6372
- if (this.keyTags.size >= 1e5 && !this.keyTags.has(k)) {
6373
- this._sweepExpiredMetadata();
6374
- if (this.keyTags.size >= 1e5) {
6375
- const oldestKey = this.keyTags.keys().next().value;
6376
- if (oldestKey !== void 0) this._removeKeyTags(oldestKey);
6377
- }
6378
- }
6379
7167
  const uniqueTags = Array.from(new Set(tags));
6380
- for (const tag of uniqueTags) {
6381
- const tagKey = this.nk(`_tag_:${tag}`);
6382
- let members = this.tagIndex.get(tagKey);
6383
- if (!members) {
6384
- members = /* @__PURE__ */ new Set();
6385
- this.tagIndex.set(tagKey, members);
6386
- }
6387
- members.add(k);
6388
- }
6389
- this.keyTags.set(k, { tags: uniqueTags, expiresAt });
7168
+ this._rememberTags(k, uniqueTags, expiresAt);
6390
7169
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6391
7170
  try {
6392
7171
  const client = await this.getRedis();
@@ -6419,6 +7198,7 @@ return 0
6419
7198
  const k = this.nk(cacheKey);
6420
7199
  this.counters.deletes++;
6421
7200
  if (isPattern) {
7201
+ this._fenceInvalidation();
6422
7202
  const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6423
7203
  for (const liveKey of this.l1.liveKeys()) {
6424
7204
  if (liveKey.startsWith(pfx)) {
@@ -6431,9 +7211,9 @@ return 0
6431
7211
  this.inflight.delete(inflightKey);
6432
7212
  }
6433
7213
  }
6434
- this._addPatternTombstone(pfx);
7214
+ this._addPatternTombstone(k);
6435
7215
  this.l1.deletePattern(k);
6436
- this._removePrefixFromIndices(pfx);
7216
+ this._removePatternFromIndices(k);
6437
7217
  for (const ktKey of Array.from(this.keyTags.keys())) {
6438
7218
  if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
6439
7219
  }
@@ -6444,14 +7224,7 @@ return 0
6444
7224
  this._bumpKeyMutation(k);
6445
7225
  this.inflight.delete(k);
6446
7226
  this.l1.delete(k);
6447
- this._pendingDiskDeletes.add(k);
6448
- setImmediate(() => {
6449
- try {
6450
- if (!this._diskDisabled) this.disk.delete(k);
6451
- } finally {
6452
- this._pendingDiskDeletes.delete(k);
6453
- }
6454
- });
7227
+ this._invalidateDiskKey(k);
6455
7228
  this._removeKeyTags(k);
6456
7229
  this._cascadeDependencies(k);
6457
7230
  this._removeKeyDependencies(k);
@@ -6508,7 +7281,7 @@ return 0
6508
7281
  async increment(cacheKey, ttlSeconds) {
6509
7282
  this._assertActive("increment");
6510
7283
  const k = this.nk(cacheKey);
6511
- if (this._redisDisabled) {
7284
+ if (this._redisDisabled || this.opts.l2WriteMode === "read-only") {
6512
7285
  if (!this._incrementFallbackWarned) {
6513
7286
  this._incrementFallbackWarned = true;
6514
7287
  this.logger.warn(
@@ -6564,6 +7337,7 @@ return 0
6564
7337
  this.counters.deletes++;
6565
7338
  const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
6566
7339
  if (k) {
7340
+ this._fenceInvalidation();
6567
7341
  const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6568
7342
  for (const liveKey of this.l1.liveKeys()) {
6569
7343
  if (liveKey.startsWith(pfx)) {
@@ -6576,9 +7350,9 @@ return 0
6576
7350
  this.inflight.delete(inflightKey);
6577
7351
  }
6578
7352
  }
6579
- this._addPatternTombstone(pfx);
7353
+ this._addPatternTombstone(k);
6580
7354
  this.l1.deletePattern(k);
6581
- this._removePrefixFromIndices(pfx);
7355
+ this._removePatternFromIndices(k);
6582
7356
  } else {
6583
7357
  this._globalEpoch++;
6584
7358
  this.inflight.clear();
@@ -6728,28 +7502,34 @@ return 0
6728
7502
  this._assertActive("scan");
6729
7503
  const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
6730
7504
  this.l1.scan((key, entry, pfx) => {
6731
- const value = entry.value !== void 0 ? entry.value : entry.data;
6732
- fn(key, value, pfx);
7505
+ fn(key, this._prepareReadValue(this.l1.resolveValue(entry)), pfx);
6733
7506
  }, prefixLen);
6734
7507
  }
6735
7508
  /**
6736
- * 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.
6737
7510
  * Returns `false` if the key is absent or already expired.
6738
7511
  *
6739
7512
  * @param newTtlSeconds - The new TTL from now, in seconds.
6740
7513
  */
6741
7514
  async touch(cacheKey, newTtlSeconds) {
6742
7515
  this._assertActive("touch");
7516
+ if (!Number.isFinite(newTtlSeconds) || newTtlSeconds <= 0) throw new Error("touch TTL must be finite and positive");
6743
7517
  const k = this.nk(cacheKey);
7518
+ const epoch = this._getKeyMutationEpoch(k);
6744
7519
  const hit = this.l1.touch(k, newTtlSeconds * 1e3);
7520
+ const entry = this.l1.getEntry(k);
6745
7521
  if (hit) {
6746
7522
  const kt = this.keyTags.get(k);
6747
7523
  if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1e3;
6748
7524
  }
6749
- if (hit && !this._redisDisabled) {
7525
+ if (hit && !this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6750
7526
  try {
6751
7527
  const client = await this.getRedis();
6752
- 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();
6753
7533
  } catch {
6754
7534
  }
6755
7535
  }
@@ -6771,7 +7551,8 @@ return 0
6771
7551
  const now = Date.now();
6772
7552
  if (entry.expiresAt <= now) return null;
6773
7553
  if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
6774
- 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));
6775
7556
  }
6776
7557
  _prepareReadValue(val) {
6777
7558
  if (this.opts.frozen) deepFreeze(val);
@@ -6788,49 +7569,23 @@ return 0
6788
7569
  async peek(cacheKey) {
6789
7570
  this._assertActive("peek");
6790
7571
  const k = this.nk(cacheKey);
7572
+ const epoch = this._getKeyMutationEpoch(k);
7573
+ this.counters.gets++;
6791
7574
  const l1Hit = this.l1.get(k);
6792
7575
  if (l1Hit !== null) {
6793
7576
  if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
6794
7577
  this._deleteIfStale(k, l1Hit.setAt ?? 0);
6795
7578
  } else {
6796
- this.counters.gets++;
6797
7579
  this.counters.l1Hits++;
6798
7580
  return this._prepareReadValue(l1Hit.value);
6799
7581
  }
6800
7582
  }
6801
- if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
6802
- if (this._isTombstonedByPattern(k)) {
6803
- try {
6804
- this.disk.delete(k);
6805
- } catch {
6806
- }
6807
- } else if (this.watchdog.isDiskAllowed()) {
6808
- const diskStart = performance.now();
6809
- const diskHit = this.disk.load(k);
6810
- const diskElapsed = performance.now() - diskStart;
6811
- this.watchdog.recordDisk(diskElapsed);
6812
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6813
- if (diskHit !== null) {
6814
- if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
6815
- this.disk.delete(k);
6816
- } else {
6817
- const promoted = this.l1.importEntries(
6818
- [{ key: k, entry: diskHit }],
6819
- this.opts.forbiddenSnapshotPrefixes
6820
- );
6821
- if (promoted > 0) {
6822
- const l1Check = this.l1.get(k);
6823
- if (l1Check !== null) {
6824
- this.counters.gets++;
6825
- this.counters.diskHits++;
6826
- return this._prepareReadValue(l1Check.value);
6827
- }
6828
- }
6829
- }
6830
- }
6831
- }
7583
+ const diskHit = await this._readDiskEntry(k, epoch);
7584
+ if (diskHit) {
7585
+ this.counters.diskHits++;
7586
+ return this._prepareReadValue(diskHit.value);
6832
7587
  }
6833
- if (!this._redisDisabled && !this.cb.isOpen) {
7588
+ if (!this._redisDisabled) {
6834
7589
  try {
6835
7590
  const client = await this.getRedis();
6836
7591
  const redisStart = performance.now();
@@ -6838,10 +7593,10 @@ return 0
6838
7593
  const redisElapsed = performance.now() - redisStart;
6839
7594
  this.watchdog.recordRedis(redisElapsed);
6840
7595
  this.cb.onSuccess();
6841
- if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
7596
+ if (redisHit && !redisHit.stale) {
6842
7597
  const parsed = redisHit.value;
6843
- this.l1.set(k, parsed, 6e4, inferPriority(cacheKey), void 0, void 0, redisHit.tagVersions);
6844
- this.counters.gets++;
7598
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return null;
7599
+ if (!this._promoteRedisEntry(k, redisHit, 6e4, inferPriority(cacheKey))) return null;
6845
7600
  this.counters.l2Hits++;
6846
7601
  return this._prepareReadValue(parsed);
6847
7602
  }
@@ -6863,6 +7618,8 @@ return 0
6863
7618
  */
6864
7619
  async mget(keys, fetchFn, ttl = 300, priority) {
6865
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))]));
6866
7623
  const span = this._startSpan("tricache.mget");
6867
7624
  if (this.opts.tracer) {
6868
7625
  span.setAttribute("cache.batch.size", keys.length);
@@ -6875,7 +7632,7 @@ return 0
6875
7632
  for (let i = 0; i < keys.length; i++) {
6876
7633
  const k = this.nk(keys[i]);
6877
7634
  const entry = this.l1.getEntry(k);
6878
- if (entry && entry.expiresAt > now) {
7635
+ if (entry && entry.expiresAt > now && (entry.staleAt === void 0 || entry.staleAt > now)) {
6879
7636
  if (await this._isGenerationalEntryStale(entry.tagVersions)) {
6880
7637
  this._deleteIfStale(k, entry.setAt ?? 0);
6881
7638
  missIndexes.push(i);
@@ -6904,64 +7661,24 @@ return 0
6904
7661
  try {
6905
7662
  const client = await this.getRedis();
6906
7663
  const nsKeys = missKeys.map((k) => this.nk(k));
6907
- const pipeline = client.multi();
6908
- const useHashPipeline = this.opts.tagStrategy === "generational" && typeof pipeline.hgetall === "function";
6909
- for (const nk of nsKeys) {
6910
- if (useHashPipeline) {
6911
- pipeline.hgetall(nk);
6912
- } else {
6913
- pipeline.get(nk);
6914
- }
6915
- }
6916
- const redisStart = performance.now();
6917
- const raws = await pipeline.exec();
6918
- const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
6919
- this.watchdog.recordRedis(redisElapsed);
6920
- this.cb.onSuccess();
7664
+ const remoteEntries = await this._readRedisBatch(client, nsKeys);
6921
7665
  for (let j = 0; j < missKeys.length; j++) {
6922
- const tuple = raws[j];
6923
- const err = tuple ? tuple[0] : null;
6924
- const rawVal = tuple ? tuple[1] : null;
6925
7666
  const idx = missIndexes[j];
6926
7667
  const k = nsKeys[j];
6927
- let parsed;
6928
- let tagVersions;
6929
- let hit = false;
6930
- if (useHashPipeline) {
6931
- if (err && err.message?.includes("WRONGTYPE")) {
6932
- const fallbackRaw = await client.get(k);
6933
- if (fallbackRaw) {
6934
- parsed = await this._decryptAndDeserialize(fallbackRaw);
6935
- hit = true;
6936
- }
6937
- } else if (!err && typeof rawVal === "string") {
6938
- parsed = await this._decryptAndDeserialize(rawVal);
6939
- hit = true;
6940
- } else if (!err && rawVal && typeof rawVal === "object" && rawVal.d) {
6941
- const hashHit = await this._parseGenerationalRedisHash(k, rawVal);
6942
- if (hashHit && !hashHit.stale && hashHit.value !== void 0) {
6943
- parsed = hashHit.value;
6944
- tagVersions = hashHit.tagVersions;
6945
- hit = true;
6946
- }
6947
- }
6948
- } else if (!err && rawVal) {
6949
- parsed = await this._decryptAndDeserialize(rawVal);
6950
- hit = true;
6951
- }
6952
- if (hit && parsed !== void 0) {
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)) {
6953
7670
  const p = priority ?? inferPriority(missKeys[j]);
6954
7671
  const ttlVal = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
6955
- this.l1.set(k, parsed, this._jitterTtl(ttlVal * 1e3), p, void 0, void 0, tagVersions);
7672
+ if (!this._promoteRedisEntry(k, entry, this._jitterTtl(ttlVal * 1e3), p)) continue;
6956
7673
  this.counters.l2Hits++;
6957
7674
  l2HitCount++;
6958
- result[idx] = this._prepareReadValue(parsed);
7675
+ result[idx] = this._prepareReadValue(entry.value);
6959
7676
  missIndexes[j] = -1;
6960
7677
  missKeys[j] = "";
6961
7678
  }
6962
7679
  }
6963
7680
  const remainingIdx = missIndexes.filter((i) => i >= 0);
6964
- const remainingKeys = missKeys.filter((k) => k !== "");
7681
+ const remainingKeys = missKeys.filter((_key, index) => missIndexes[index] >= 0);
6965
7682
  missIndexes.length = 0;
6966
7683
  missKeys.length = 0;
6967
7684
  missIndexes.push(...remainingIdx);
@@ -6974,62 +7691,64 @@ return 0
6974
7691
  if (!this._diskDisabled && missKeys.length > 0) {
6975
7692
  for (let j = missKeys.length - 1; j >= 0; j--) {
6976
7693
  const k = this.nk(missKeys[j]);
6977
- if (this._pendingDiskDeletes.has(k)) continue;
6978
- if (this._isTombstonedByPattern(k)) {
6979
- try {
6980
- this.disk.delete(k);
6981
- } catch {
6982
- }
6983
- continue;
6984
- }
6985
- if (!this.watchdog.isDiskAllowed()) continue;
6986
- const diskStart = performance.now();
6987
- const diskHit = this.disk.load(k);
6988
- const diskElapsed = performance.now() - diskStart;
6989
- this.watchdog.recordDisk(diskElapsed);
6990
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6991
- if (diskHit !== null) {
6992
- if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
6993
- this.disk.delete(k);
6994
- continue;
6995
- }
6996
- const promoted = this.l1.importEntries(
6997
- [{ key: k, entry: diskHit }],
6998
- this.opts.forbiddenSnapshotPrefixes
6999
- );
7000
- if (promoted > 0) {
7001
- const l1Check = this.l1.get(k);
7002
- if (l1Check !== null) {
7003
- this.counters.diskHits++;
7004
- result[missIndexes[j]] = this._prepareReadValue(l1Check.value);
7005
- missIndexes.splice(j, 1);
7006
- missKeys.splice(j, 1);
7007
- }
7008
- }
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);
7009
7700
  }
7010
7701
  }
7011
7702
  }
7012
7703
  if (missKeys.length > 0 && fetchFn) {
7013
- this.counters.fetches++;
7014
- const fetched = await fetchFn(missKeys);
7015
- const isMap = fetched instanceof Map;
7016
- const setPromises = [];
7704
+ const owned = /* @__PURE__ */ new Map();
7705
+ const waiting = [];
7017
7706
  for (let j = 0; j < missKeys.length; j++) {
7018
- const k = missKeys[j];
7019
- const v = isMap ? fetched.get(k) : fetched[k];
7020
- result[missIndexes[j]] = v;
7021
- if (v !== void 0 && v !== null) {
7022
- const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
7023
- setPromises.push(this.set(k, v, resolvedTtl, priority));
7024
- } else if (v == null && this.opts.notFoundTtl > 0) {
7025
- setPromises.push(this.set(k, null, this.opts.notFoundTtl, priority));
7026
- } else if (v === null) {
7027
- const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
7028
- 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++;
7029
7721
  }
7722
+ const index = missIndexes[j];
7723
+ waiting.push(promise.then((value) => {
7724
+ result[index] = this._prepareReadValue(value);
7725
+ }));
7030
7726
  }
7031
- if (setPromises.length > 0) {
7032
- 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
+ }
7033
7752
  }
7034
7753
  }
7035
7754
  if (this.opts.tracer) {
@@ -7082,7 +7801,7 @@ return 0
7082
7801
  try {
7083
7802
  await Promise.all(keys.map((key) => {
7084
7803
  const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
7085
- const hasOpts = tags?.length || dependsOn?.length;
7804
+ const hasOpts = tags !== void 0 || dependsOn !== void 0;
7086
7805
  return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
7087
7806
  }));
7088
7807
  } catch (err) {
@@ -7134,26 +7853,21 @@ return 0
7134
7853
  try {
7135
7854
  const client = await this.getRedis();
7136
7855
  const nsPattern = this.nk(pattern);
7137
- 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
+ });
7138
7860
  if (matchedKeys.length === 0) {
7139
7861
  this.cb.onSuccess();
7140
7862
  return 0;
7141
7863
  }
7142
- const pl = client.pipeline();
7143
- for (const k of matchedKeys) pl.get(k);
7144
- const results = await pl.exec();
7145
- this.cb.onSuccess();
7864
+ const epochs = new Map(matchedKeys.map((key) => [key, this._getKeyMutationEpoch(key)]));
7865
+ const results = await this._readRedisBatch(client, matchedKeys);
7146
7866
  let loaded = 0;
7147
- for (let i = 0; i < matchedKeys.length; i++) {
7148
- const [err, raw] = results[i];
7149
- if (err || raw == null) continue;
7150
- try {
7151
- const parsed = await this._decryptAndDeserialize(raw);
7152
- const remainingMs = 10 * 60 * 1e3;
7153
- this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
7154
- loaded++;
7155
- } catch {
7156
- }
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++;
7157
7871
  }
7158
7872
  this.logger.info("warmFromL2 complete", {
7159
7873
  pattern,
@@ -7240,14 +7954,7 @@ return 0
7240
7954
  this._bumpKeyMutation(k);
7241
7955
  this._removeKeyTags(k);
7242
7956
  this._removeKeyDependencies(k);
7243
- this._pendingDiskDeletes.add(k);
7244
- setImmediate(() => {
7245
- try {
7246
- if (!this._diskDisabled) this.disk.delete(k);
7247
- } finally {
7248
- this._pendingDiskDeletes.delete(k);
7249
- }
7250
- });
7957
+ this._invalidateDiskKey(k);
7251
7958
  }
7252
7959
  }
7253
7960
  /**
@@ -7255,9 +7962,10 @@ return 0
7255
7962
  * wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
7256
7963
  */
7257
7964
  async _invalidateConcreteTag(tag) {
7965
+ this._fenceInvalidation();
7258
7966
  if (this.opts.tagStrategy === "generational") {
7259
7967
  let newVer = 1;
7260
- if (!this._redisDisabled) {
7968
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7261
7969
  try {
7262
7970
  const client = await this.getRedis();
7263
7971
  newVer = await client.incr(this.nk(`tag_ver:${tag}`));
@@ -7275,19 +7983,23 @@ return 0
7275
7983
  return;
7276
7984
  }
7277
7985
  const tagKey = this.nk(`_tag_:${tag}`);
7278
- const members = Array.from(this.tagIndex.get(tagKey) ?? []);
7986
+ const members = new Set(this.tagIndex.get(tagKey) ?? []);
7279
7987
  this.tagIndex.delete(tagKey);
7280
7988
  this._removeTagMembersLocal(members);
7281
- if (!this._redisDisabled) {
7989
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7282
7990
  try {
7283
7991
  const client = await this.getRedis();
7284
7992
  const redisMembers = await client.smembers(tagKey);
7993
+ for (const key of redisMembers) members.add(key);
7994
+ this._removeTagMembersLocal(redisMembers);
7285
7995
  const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers, tagKey])];
7286
7996
  await this._deleteRedisKeys(client, toDelete);
7287
7997
  } catch (err) {
7288
7998
  this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7289
7999
  }
7290
8000
  }
8001
+ await Promise.all([...members].map((key) => this._publishTagInvalidation("del", key)));
8002
+ await this._publishTagInvalidation("tag_pattern_del", tag);
7291
8003
  }
7292
8004
  /**
7293
8005
  * Executes invalidation for an array of already-resolved concrete tags
@@ -7299,9 +8011,10 @@ return 0
7299
8011
  await this._invalidateConcreteTag(tags[0]);
7300
8012
  return;
7301
8013
  }
8014
+ this._fenceInvalidation();
7302
8015
  if (this.opts.tagStrategy === "generational") {
7303
8016
  const now = performance.now();
7304
- if (!this._redisDisabled) {
8017
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7305
8018
  try {
7306
8019
  const client = await this.getRedis();
7307
8020
  const pl = client.pipeline();
@@ -7335,7 +8048,7 @@ return 0
7335
8048
  this.tagIndex.delete(tagKey);
7336
8049
  }
7337
8050
  this._removeTagMembersLocal(allMembers);
7338
- if (!this._redisDisabled) {
8051
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7339
8052
  try {
7340
8053
  const client = await this.getRedis();
7341
8054
  const pl = client.pipeline();
@@ -7346,15 +8059,19 @@ return 0
7346
8059
  if (!err && redisMembers) {
7347
8060
  for (const k of redisMembers) {
7348
8061
  if (!allMembers.has(k)) toDelete.push(k);
8062
+ allMembers.add(k);
7349
8063
  }
7350
8064
  }
7351
8065
  }
7352
8066
  const keysToRemove = [...toDelete, ...tagKeys];
7353
8067
  await this._deleteRedisKeys(client, keysToRemove);
8068
+ this._removeTagMembersLocal(allMembers);
7354
8069
  } catch (err) {
7355
8070
  this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7356
8071
  }
7357
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);
7358
8075
  }
7359
8076
  /**
7360
8077
  * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
@@ -7508,19 +8225,23 @@ return 0
7508
8225
  const diskLowSpace = !this._diskDisabled && this.disk.hostVolumeLowSpace;
7509
8226
  const circuitOpen = this.cb.isOpen;
7510
8227
  const latencyBypass = watchdogTel.bypassActive;
7511
- const degraded = circuitOpen || latencyBypass || diskPruning || diskLowSpace;
7512
- 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);
7513
8231
  const reasons = [];
7514
8232
  if (circuitOpen) reasons.push("redis_circuit_breaker_open");
7515
8233
  if (latencyBypass) reasons.push(`disk_latency_bypass_stage_${watchdogTel.bypassStage}`);
7516
8234
  if (diskPruning) reasons.push("disk_quota_watermark_pruning_active");
7517
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");
7518
8238
  return {
7519
8239
  healthy,
7520
8240
  degraded,
7521
8241
  reasons,
7522
8242
  details: {
7523
- redisConnected: !circuitOpen && !this._redisDisabled,
8243
+ redisConnected: !this._destroyed && !circuitOpen && !!this.redis && (this.redis.status === "ready" || this.redis.isOpen === true),
8244
+ backplaneReady: this._backplaneAvailable,
7524
8245
  circuitBreakerState: this.cb.currentState,
7525
8246
  diskPruningActive: diskPruning,
7526
8247
  diskHostVolumeLowSpace: diskLowSpace,
@@ -7542,23 +8263,28 @@ return 0
7542
8263
  */
7543
8264
  async drainToL2() {
7544
8265
  this._assertActive("drainToL2");
7545
- if (this._redisDisabled) return 0;
8266
+ if (this._redisDisabled || this.opts.l2WriteMode === "read-only") return 0;
7546
8267
  try {
7547
- const client = await this.getRedis();
7548
8268
  const entries = this.l1.exportEntries([]);
7549
- const now = Date.now();
7550
8269
  if (entries.length === 0) return 0;
7551
- const pl = client.pipeline();
7552
- for (const { key, entry } of entries) {
7553
- const remainingMs = entry.expiresAt - now;
7554
- if (remainingMs <= 0) continue;
7555
- const ttlSecs = Math.max(1, Math.ceil(remainingMs / 1e3));
7556
- const s = JSON.stringify(entry.value);
7557
- const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
7558
- pl.setex(key, ttlSecs, stored);
7559
- }
7560
- await pl.exec();
7561
- 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;
7562
8288
  } catch (err) {
7563
8289
  this.logger.debug("drainToL2: Redis unavailable", { error: err.message });
7564
8290
  return 0;
@@ -7588,7 +8314,7 @@ return 0
7588
8314
  this._assertActive("setIfAbsent");
7589
8315
  const k = this.nk(cacheKey);
7590
8316
  if (this.l1.has(k)) return false;
7591
- if (!this._redisDisabled) {
8317
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7592
8318
  try {
7593
8319
  const client = await this.getRedis();
7594
8320
  const serialized = JSON.stringify(value);
@@ -7605,7 +8331,7 @@ return 0
7605
8331
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
7606
8332
  const p = priority ?? inferPriority(cacheKey);
7607
8333
  this._bumpKeyMutation(k);
7608
- this._pendingDiskDeletes.delete(k);
8334
+ this._invalidateDiskKey(k);
7609
8335
  this.l1.set(k, value, ttlMs, p);
7610
8336
  this.counters.sets++;
7611
8337
  return true;
@@ -7632,7 +8358,7 @@ return 0
7632
8358
  const token = import_crypto3.default.randomUUID();
7633
8359
  const deadline = Date.now() + acquireTimeout;
7634
8360
  let acquired = false;
7635
- if (!this._redisDisabled) {
8361
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7636
8362
  let client = null;
7637
8363
  try {
7638
8364
  client = await this.getRedis();
@@ -7727,7 +8453,9 @@ return 0
7727
8453
  const gDiskFiles = meter.createObservableGauge("tricache.disk.files", { description: "Current L1.5 disk file count" });
7728
8454
  const gDiskBytes = meter.createObservableGauge("tricache.disk.bytes", { description: "Current L1.5 disk size in bytes" });
7729
8455
  const gBloomFpr = meter.createObservableGauge("tricache.bloom.fpr", { description: "Bloom filter false-positive rate" });
7730
- meter.addBatchObservableCallback((observableResult) => {
8456
+ const observables = [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr];
8457
+ const callback = (observableResult) => {
8458
+ if (this._destroyed) return;
7731
8459
  const stats = this.stats();
7732
8460
  const l1 = stats.l1;
7733
8461
  const disk = stats.disk;
@@ -7740,7 +8468,9 @@ return 0
7740
8468
  observableResult.observe(gDiskFiles, disk.files, attrs);
7741
8469
  observableResult.observe(gDiskBytes, disk.sizeKB * 1024, attrs);
7742
8470
  observableResult.observe(gBloomFpr, fpr, attrs);
7743
- }, [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr]);
8471
+ };
8472
+ meter.addBatchObservableCallback(callback, observables);
8473
+ this._otelCleanup = () => meter.removeBatchObservableCallback?.(callback, observables);
7744
8474
  } catch (err) {
7745
8475
  this.logger.warn("Failed to initialize OpenTelemetry metrics meter", { error: err.message });
7746
8476
  }
@@ -8010,6 +8740,16 @@ return 0
8010
8740
  /** Close Redis connections and stop all background timers. */
8011
8741
  async destroy() {
8012
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();
8013
8753
  this._pendingDiskDeletes.clear();
8014
8754
  this._keyMutationEpochs.clear();
8015
8755
  this.inflight.clear();
@@ -8039,6 +8779,12 @@ return 0
8039
8779
  this._workerPool = null;
8040
8780
  }
8041
8781
  if (this.subClient) {
8782
+ if (this.opts.redisSubClient) {
8783
+ try {
8784
+ await this.subClient.unsubscribe?.(this.backplaneChannel);
8785
+ } catch {
8786
+ }
8787
+ }
8042
8788
  if (!this.opts.redisSubClient) {
8043
8789
  try {
8044
8790
  this.subClient.disconnect();
@@ -8048,7 +8794,7 @@ return 0
8048
8794
  this.subClient = null;
8049
8795
  }
8050
8796
  if (this.streamClient) {
8051
- try {
8797
+ if (!this.opts.redisSubClient) try {
8052
8798
  this.streamClient.disconnect();
8053
8799
  } catch {
8054
8800
  }