tricache 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +36 -28
  2. package/dist/{cache-service-pJ-nFcVj.d.ts → cache-service-B108FzER.d.ts} +63 -3
  3. package/dist/cache-service-CWI4jkS7.d.cts +963 -0
  4. package/dist/{cache-service-26GCO3UU.js → cache-service-GYPZFB7O.js} +2 -2
  5. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  6. package/dist/{chunk-2AJKEQMZ.js → chunk-H4GFLQ26.js} +7 -4
  7. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  8. package/dist/chunk-OYDU3SMI.js +89 -0
  9. package/dist/{chunk-VXFTFZ5N.js → chunk-VNRDL5RA.js} +117 -138
  10. package/dist/{chunk-7SZSQS55.js → chunk-WYF7NOAT.js} +1831 -759
  11. package/dist/cli.cjs +1757 -777
  12. package/dist/cli.d.cts +12 -0
  13. package/dist/cli.js +27 -6
  14. package/dist/dashboard/index.cjs +111 -29
  15. package/dist/dashboard/index.d.cts +185 -0
  16. package/dist/dashboard/index.d.ts +5 -3
  17. package/dist/dashboard/index.js +1 -1
  18. package/dist/drizzle/index.cjs +1757 -773
  19. package/dist/drizzle/index.d.cts +46 -0
  20. package/dist/drizzle/index.d.ts +2 -2
  21. package/dist/drizzle/index.js +1 -1
  22. package/dist/edge/index.cjs +280 -153
  23. package/dist/edge/index.d.cts +127 -0
  24. package/dist/edge/index.d.ts +3 -3
  25. package/dist/edge/index.js +254 -147
  26. package/dist/hono/index.cjs +1805 -793
  27. package/dist/hono/index.d.cts +93 -0
  28. package/dist/hono/index.d.ts +7 -5
  29. package/dist/hono/index.js +16 -9
  30. package/dist/{hono-DuNvciyq.d.ts → hono-3rDMYVtY.d.ts} +23 -3
  31. package/dist/hono-C886ok3X.d.cts +391 -0
  32. package/dist/http/index.cjs +1946 -842
  33. package/dist/http/index.d.cts +103 -0
  34. package/dist/http/index.d.ts +13 -5
  35. package/dist/http/index.js +137 -57
  36. package/dist/index.cjs +2073 -937
  37. package/dist/index.d.cts +1006 -0
  38. package/dist/index.d.ts +40 -8
  39. package/dist/index.js +8 -8
  40. package/dist/murmur3-CMGw9PbV.d.cts +98 -0
  41. package/dist/nestjs/index.cjs +1849 -806
  42. package/dist/nestjs/index.d.cts +285 -0
  43. package/dist/nestjs/index.d.ts +103 -30
  44. package/dist/nestjs/index.js +115 -32
  45. package/dist/next/index.cjs +1913 -887
  46. package/dist/next/index.d.cts +232 -0
  47. package/dist/next/index.d.ts +33 -11
  48. package/dist/next/index.js +174 -107
  49. package/dist/prisma/index.cjs +11 -1
  50. package/dist/prisma/index.d.cts +62 -0
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +11 -1
  53. package/dist/serialize-worker.d.cts +2 -0
  54. package/dist/{types-5HXqBfAf.d.ts → types-BA4pz1A0.d.cts} +26 -9
  55. package/dist/types-BA4pz1A0.d.ts +1519 -0
  56. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  57. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  58. package/package.json +96 -36
  59. package/src/adapters/auto-pipeliner.ts +107 -24
  60. package/src/adapters/node-redis.ts +123 -25
  61. package/src/cache-service.ts +1238 -659
  62. package/src/cli.ts +24 -6
  63. package/src/cross-region.ts +21 -3
  64. package/src/dashboard/handler.ts +26 -6
  65. package/src/dashboard/html.ts +35 -10
  66. package/src/dashboard/index.ts +35 -13
  67. package/src/dashboard/types.ts +3 -1
  68. package/src/disk-tier.ts +171 -65
  69. package/src/edge/cache.ts +202 -129
  70. package/src/edge/hono.ts +23 -6
  71. package/src/edge/types.ts +2 -0
  72. package/src/hono/index.ts +19 -9
  73. package/src/http/express.ts +110 -26
  74. package/src/http/fastify.ts +38 -28
  75. package/src/http/utils.ts +54 -20
  76. package/src/ipc-telemetry.ts +35 -9
  77. package/src/nestjs/decorators.ts +1 -1
  78. package/src/nestjs/index.ts +2 -0
  79. package/src/nestjs/keyv-adapter.ts +68 -0
  80. package/src/nestjs/tricache.module.ts +13 -11
  81. package/src/nestjs/tricache.store.ts +51 -20
  82. package/src/nestjs/types.ts +29 -15
  83. package/src/next/cache-handler.ts +132 -57
  84. package/src/next/index.ts +1 -0
  85. package/src/next/isr-handler.ts +1 -4
  86. package/src/next/types.ts +21 -0
  87. package/src/prisma/index.ts +12 -1
  88. package/src/smart-memory-cache.ts +65 -27
  89. package/src/types.ts +27 -2
  90. package/src/utils/cgroup.ts +12 -0
  91. package/src/utils/deadline.ts +14 -0
  92. package/src/utils/diagnostics.ts +27 -0
  93. package/src/utils/redis-slot.ts +13 -0
  94. package/src/wasm/bloom-filter-wasm.ts +9 -4
  95. package/src/worker-pool.ts +17 -8
  96. package/src/wtiny-lfu.ts +20 -6
  97. package/dist/chunk-BQRURGGD.js +0 -60
@@ -34,6 +34,7 @@ __export(nestjs_exports, {
34
34
  CacheEvict: () => CacheEvict,
35
35
  Cacheable: () => Cacheable,
36
36
  TRICACHE_SERVICE: () => TRICACHE_SERVICE,
37
+ TriCacheKeyvAdapter: () => TriCacheKeyvAdapter,
37
38
  TriCacheModule: () => TriCacheModule,
38
39
  TriCacheStore: () => TriCacheStore,
39
40
  default: () => nestjs_default
@@ -41,7 +42,7 @@ __export(nestjs_exports, {
41
42
  module.exports = __toCommonJS(nestjs_exports);
42
43
 
43
44
  // src/cache-service.ts
44
- var import_ioredis = require("ioredis");
45
+ var import_ioredis2 = require("ioredis");
45
46
 
46
47
  // src/codec.ts
47
48
  var import_msgpackr = require("msgpackr");
@@ -76,6 +77,15 @@ var defaultCodec = new CacheCodec({
76
77
  moreTypes: true
77
78
  });
78
79
 
80
+ // src/cross-region.ts
81
+ var import_node_crypto = require("crypto");
82
+ function isCrossRegionInvalidationEvent(value) {
83
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
84
+ const event = value;
85
+ const text = (key, max) => typeof event[key] === "string" && event[key].length > 0 && event[key].length <= max;
86
+ 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);
87
+ }
88
+
79
89
  // src/cache-service.ts
80
90
  var import_crypto3 = __toESM(require("crypto"), 1);
81
91
  var import_os3 = __toESM(require("os"), 1);
@@ -102,7 +112,8 @@ try {
102
112
  _workerFile = jsPath;
103
113
  }
104
114
  } catch {
105
- _workerFile = (0, import_path.join)(__dirname, "serialize-worker.js");
115
+ const sibling = (0, import_path.join)(__dirname, "serialize-worker.js");
116
+ _workerFile = (0, import_fs.existsSync)(sibling) ? sibling : (0, import_path.join)((0, import_path.dirname)(__dirname), "serialize-worker.js");
106
117
  }
107
118
  function getTransferableArrayBuffer(buf) {
108
119
  if (buf.buffer instanceof ArrayBuffer) {
@@ -135,6 +146,7 @@ var WorkerPool = class {
135
146
  }
136
147
  _spawnWorkers(opts) {
137
148
  const size = Math.max(1, opts.size ?? Math.min(4, availableCpus()));
149
+ if (!Number.isInteger(size) || size > 32 || !(0, import_fs.existsSync)(_workerFile)) throw new Error("Worker pool unavailable or invalid worker count");
138
150
  const workerData = {
139
151
  keyBase64: opts.keyBase64,
140
152
  mode: opts.mode,
@@ -148,7 +160,8 @@ var WorkerPool = class {
148
160
  const createWorker = (index) => {
149
161
  const worker = new import_worker_threads.Worker(_workerFile, {
150
162
  workerData,
151
- execArgv: _workerExecArgv.length > 0 ? _workerExecArgv : void 0
163
+ execArgv: _workerExecArgv
164
+ // Do not inherit --input-type/eval or application loader flags.
152
165
  });
153
166
  const pending = pendingList[index] ?? /* @__PURE__ */ new Map();
154
167
  if (!pendingList[index]) pendingList[index] = pending;
@@ -178,7 +191,7 @@ var WorkerPool = class {
178
191
  }
179
192
  pending.clear();
180
193
  worker.unref();
181
- if (this._available && exitCode !== 0 && workers[index] === worker) {
194
+ if (this._available && this.workers === workers && workers[index] === worker) {
182
195
  try {
183
196
  workers[index] = createWorker(index);
184
197
  } catch {
@@ -188,9 +201,12 @@ var WorkerPool = class {
188
201
  worker.unref();
189
202
  return worker;
190
203
  };
191
- for (let i = 0; i < size; i++) {
192
- const worker = createWorker(i);
193
- workers.push(worker);
204
+ try {
205
+ for (let i = 0; i < size; i++) workers.push(createWorker(i));
206
+ } catch (error) {
207
+ for (const worker of workers) void worker.terminate().catch(() => {
208
+ });
209
+ throw error;
194
210
  }
195
211
  return { workers, pending: pendingList };
196
212
  }
@@ -217,7 +233,7 @@ var WorkerPool = class {
217
233
  entry.reject(new Error("WorkerPool replaced during key rotation"));
218
234
  }
219
235
  oldPending[i]?.clear();
220
- oldWorkers[i]?.terminate().catch(() => {
236
+ await oldWorkers[i]?.terminate().catch(() => {
221
237
  });
222
238
  }
223
239
  }
@@ -259,7 +275,13 @@ var WorkerPool = class {
259
275
  return new Promise((resolve, reject) => {
260
276
  pending.set(id, { resolve, reject });
261
277
  worker.ref();
262
- worker.postMessage({ id, type, payload: dataToSend }, transferList);
278
+ try {
279
+ worker.postMessage({ id, type, payload: dataToSend }, transferList);
280
+ } catch (error) {
281
+ pending.delete(id);
282
+ if (pending.size === 0) worker.unref();
283
+ reject(error);
284
+ }
263
285
  });
264
286
  }
265
287
  /** Terminate all worker threads. In-flight promises are rejected. */
@@ -770,8 +792,9 @@ var EnvelopeEncryption = class {
770
792
 
771
793
  // src/wtiny-lfu.ts
772
794
  var WTinyLfuPolicy = class {
773
- constructor(capacity, sketch, windowPercent = 0.01, protectedPercent = 0.8) {
795
+ constructor(capacity, sketch, windowPercent = 0.01, protectedPercent = 0.8, canEvict) {
774
796
  this.sketch = sketch;
797
+ this.canEvict = canEvict;
775
798
  this.maxTotal = Math.max(2, capacity);
776
799
  this.maxWindow = Math.max(1, Math.floor(this.maxTotal * windowPercent));
777
800
  const mainCapacity = Math.max(1, this.maxTotal - this.maxWindow);
@@ -779,6 +802,7 @@ var WTinyLfuPolicy = class {
779
802
  this.maxProbation = Math.max(1, mainCapacity - this.maxProtected);
780
803
  }
781
804
  sketch;
805
+ canEvict;
782
806
  maxTotal;
783
807
  maxWindow;
784
808
  maxProtected;
@@ -858,15 +882,33 @@ var WTinyLfuPolicy = class {
858
882
  }
859
883
  let victimKey;
860
884
  let victimIsProbation = true;
861
- if (this.probation.size > 0) {
862
- victimKey = this.probation.values().next().value;
863
- } else {
864
- victimKey = this.protected_.values().next().value;
885
+ for (const candidate of this.probation) {
886
+ if (!this.canEvict || this.canEvict(candidate)) {
887
+ victimKey = candidate;
888
+ break;
889
+ }
890
+ }
891
+ if (victimKey === void 0) {
892
+ for (const candidate of this.protected_) {
893
+ if (!this.canEvict || this.canEvict(candidate)) {
894
+ victimKey = candidate;
895
+ break;
896
+ }
897
+ }
865
898
  victimIsProbation = false;
866
899
  }
900
+ if (victimKey === void 0) {
901
+ if (this.canEvict && !this.canEvict(candKey)) {
902
+ this.window.delete(key);
903
+ this.window.add(candKey);
904
+ return { admit: false, candidateKey: key };
905
+ }
906
+ this.rejectionCount++;
907
+ return { admit: false, candidateKey: candKey };
908
+ }
867
909
  const candFreq = this.sketch.estimate(candKey);
868
910
  const victimFreq = this.sketch.estimate(victimKey);
869
- if (candFreq > victimFreq) {
911
+ if (this.canEvict && !this.canEvict(candKey) || candFreq > victimFreq) {
870
912
  if (victimIsProbation) {
871
913
  this.probation.delete(victimKey);
872
914
  } else {
@@ -940,9 +982,12 @@ function base64ToUint8Array(base64) {
940
982
  var BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
941
983
  var KEY_STAGING_OFFSET = 2e4;
942
984
  var MAX_KEY_BYTES = 512;
943
- var BLOOM_WASM_MODULE = new WebAssembly.Module(
944
- base64ToUint8Array(BLOOM_WASM_BASE64)
945
- );
985
+ var bloomWasmModule;
986
+ function getBloomWasmModule() {
987
+ return bloomWasmModule ??= new WebAssembly.Module(
988
+ base64ToUint8Array(BLOOM_WASM_BASE64)
989
+ );
990
+ }
946
991
  var WasmBloomFilter = class {
947
992
  exports;
948
993
  mem;
@@ -954,7 +999,7 @@ var WasmBloomFilter = class {
954
999
  /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
955
1000
  _insertionCount = 0;
956
1001
  constructor() {
957
- const instance = new WebAssembly.Instance(BLOOM_WASM_MODULE, {});
1002
+ const instance = new WebAssembly.Instance(getBloomWasmModule(), {});
958
1003
  this.exports = instance.exports;
959
1004
  this.mem = new Uint8Array(this.exports.memory.buffer);
960
1005
  this.stagingTarget = new Uint8Array(this.exports.memory.buffer, KEY_STAGING_OFFSET, MAX_KEY_BYTES);
@@ -1086,8 +1131,9 @@ var JsBloomFilter = class {
1086
1131
  };
1087
1132
  function createBloomFilter(logger, maxEntries) {
1088
1133
  const LN2_SQ = Math.LN2 * Math.LN2;
1089
- const optimalBits = Math.ceil(-maxEntries * Math.log(0.01) / LN2_SQ);
1090
- const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / maxEntries)));
1134
+ const capacity = Math.max(1, maxEntries);
1135
+ const optimalBits = Math.ceil(-capacity * Math.log(0.01) / LN2_SQ);
1136
+ const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / capacity)));
1091
1137
  try {
1092
1138
  const wasm = new WasmBloomFilter();
1093
1139
  if (wasm.maxCapacity >= maxEntries) {
@@ -1211,7 +1257,10 @@ var SmartMemoryCache = class {
1211
1257
  this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
1212
1258
  this.categoryPrefixes = Object.keys(opts.categories).filter((k) => k !== "default");
1213
1259
  if (opts.admissionPolicy === "wtinylfu") {
1214
- this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch);
1260
+ this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch, 0.01, 0.8, (key) => {
1261
+ const entry = this.cache.get(key);
1262
+ return !entry || entry.priority !== 4 || entry.expiresAt <= Date.now();
1263
+ });
1215
1264
  }
1216
1265
  if (existing) {
1217
1266
  for (const [k, v] of existing) this.cache.set(k, v);
@@ -1290,6 +1339,7 @@ var SmartMemoryCache = class {
1290
1339
  const MAX_EVICT_PASSES = 64;
1291
1340
  let passes = 0;
1292
1341
  do {
1342
+ const before = this.cache.size;
1293
1343
  this.smartEvict(category, catOvf);
1294
1344
  const lim2 = this.getCategoryLimit(category);
1295
1345
  const catCnt2 = this.categoryCount.get(category) ?? 0;
@@ -1297,6 +1347,7 @@ var SmartMemoryCache = class {
1297
1347
  catOvf = catCnt2 >= lim2.maxEntries || catSz2 + neededSize > lim2.maxSizeBytes;
1298
1348
  glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
1299
1349
  passes++;
1350
+ if (this.cache.size === before) break;
1300
1351
  } while ((catOvf || glbOvf) && passes < MAX_EVICT_PASSES);
1301
1352
  }
1302
1353
  score(entry, catBonus, now, key) {
@@ -1427,20 +1478,26 @@ var SmartMemoryCache = class {
1427
1478
  delta: entry.delta,
1428
1479
  fetchedAt: now,
1429
1480
  tagVersions: entry.tagVersions,
1430
- setAt: entry.setAt
1481
+ setAt: entry.setAt,
1482
+ tags: entry.tags,
1483
+ dependsOn: entry.dependsOn
1431
1484
  };
1432
1485
  return hit;
1433
1486
  }
1434
- set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
1487
+ set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions, setAt, tags, dependsOn) {
1435
1488
  const packed = this.codec.encode(data);
1489
+ return this.storePacked(key, packed, data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn);
1490
+ }
1491
+ storePacked(key, packed, data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn) {
1436
1492
  const size = packed.byteLength;
1437
1493
  this.compressions++;
1438
1494
  this.sketch.increment(key);
1439
1495
  const cat = this.getCategory(key);
1440
1496
  const lim = this.getCategoryLimit(cat);
1441
- if (size > lim.maxSizeBytes * 0.5) {
1497
+ if (!Number.isFinite(ttlMs) || ttlMs <= 0 || this.opts.maxEntries <= 0 || lim.maxEntries <= 0 || size > this.opts.maxBytes || size > lim.maxSizeBytes * 0.5) {
1498
+ this.delete(key);
1442
1499
  this.opts.logger.debug("SmartMemoryCache: entry too large, skipping", { key, sizeBytes: size });
1443
- return;
1500
+ return false;
1444
1501
  }
1445
1502
  const existingEntry = this.cache.get(key);
1446
1503
  if (existingEntry) {
@@ -1468,11 +1525,13 @@ var SmartMemoryCache = class {
1468
1525
  priority,
1469
1526
  ttlMs,
1470
1527
  delta,
1471
- setAt: now2,
1472
- tagVersions
1528
+ setAt: setAt ?? now2,
1529
+ tagVersions,
1530
+ tags,
1531
+ dependsOn
1473
1532
  });
1474
1533
  }
1475
- return;
1534
+ return false;
1476
1535
  } else if (decision.candidateKey) {
1477
1536
  const candEntry = this.cache.get(decision.candidateKey);
1478
1537
  if (candEntry && this.opts.diskSpill) {
@@ -1488,15 +1547,19 @@ var SmartMemoryCache = class {
1488
1547
  this._delete(decision.evictKey, "capacity");
1489
1548
  }
1490
1549
  const catSz = this.categorySize.get(cat) ?? 0;
1491
- if (catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
1550
+ if ((this.categoryCount.get(cat) ?? 0) >= lim.maxEntries || this.cache.size >= this.opts.maxEntries || catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
1492
1551
  this.ensureCapacity(cat, size);
1493
1552
  }
1494
1553
  } else {
1495
1554
  this.ensureCapacity(cat, size);
1496
1555
  }
1556
+ 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) {
1557
+ this.wtinyPolicy?.onDelete(key);
1558
+ return false;
1559
+ }
1497
1560
  const now = Date.now();
1498
1561
  const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
1499
- this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: now, tagVersions });
1562
+ 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 });
1500
1563
  if (!existingEntry) this.bloom.add(key);
1501
1564
  this.maybeRebuildBloom();
1502
1565
  this.totalSize += size;
@@ -1508,6 +1571,7 @@ var SmartMemoryCache = class {
1508
1571
  this.categoryKeys.set(cat, ks);
1509
1572
  }
1510
1573
  ks.add(key);
1574
+ return true;
1511
1575
  }
1512
1576
  delete(key) {
1513
1577
  const deleted = this._delete(key, "manual");
@@ -1709,25 +1773,48 @@ var SmartMemoryCache = class {
1709
1773
  if (entry.expiresAt <= now) continue;
1710
1774
  if (entry.priority === 4) continue;
1711
1775
  if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
1712
- out.push({ key, entry: { ...entry } });
1776
+ const { value: _value, ...stored } = entry;
1777
+ out.push({ key, entry: { ...stored } });
1713
1778
  }
1714
1779
  return out;
1715
1780
  }
1716
1781
  importEntries(entries, forbiddenPrefixes) {
1717
1782
  const now = Date.now();
1718
1783
  let loaded = 0;
1719
- for (const { key, entry } of entries) {
1720
- if (entry.expiresAt <= now) continue;
1784
+ for (const item of entries) {
1785
+ if (!item || typeof item.key !== "string" || !item.entry) continue;
1786
+ const { key, entry } = item;
1787
+ if (!Number.isFinite(entry.expiresAt) || entry.expiresAt <= now) continue;
1721
1788
  if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
1722
1789
  if (this.cache.has(key)) continue;
1723
- const rawData = entry.data;
1724
- const data = !entry.isCompressed ? this.codec.encode(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
1725
- const value = entry.size <= LARGE_VALUE_BYTES ? this.codec.decode(data) : void 0;
1726
- this.cache.set(key, { ...entry, data, value, isCompressed: true });
1727
- this.bloom.add(key);
1728
- loaded++;
1729
- }
1730
- this.recalculateStats();
1790
+ try {
1791
+ const rawData = entry.data;
1792
+ const data = !entry.isCompressed ? this.codec.encode(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : null;
1793
+ if (!data) continue;
1794
+ const value = data.length <= LARGE_VALUE_BYTES ? this.codec.decode(data) : void 0;
1795
+ if (this.storePacked(
1796
+ key,
1797
+ data,
1798
+ value,
1799
+ entry.expiresAt - now,
1800
+ entry.priority,
1801
+ entry.staleAt,
1802
+ entry.delta,
1803
+ entry.tagVersions,
1804
+ entry.setAt,
1805
+ entry.tags,
1806
+ entry.dependsOn
1807
+ )) {
1808
+ const restored = this.cache.get(key);
1809
+ restored.expiresAt = entry.expiresAt;
1810
+ restored.ttlMs = entry.ttlMs ?? entry.expiresAt - now;
1811
+ restored.hits = Number.isFinite(entry.hits) ? Math.max(1, entry.hits) : 1;
1812
+ restored.lastAccess = Number.isFinite(entry.lastAccess) ? entry.lastAccess : now;
1813
+ loaded++;
1814
+ }
1815
+ } catch {
1816
+ }
1817
+ }
1731
1818
  return loaded;
1732
1819
  }
1733
1820
  // ── Iterators ─────────────────────────────────────────────────────────────
@@ -2091,6 +2178,9 @@ var BoundedDiskQueue = class {
2091
2178
  this.writeTimeoutMs = writeTimeoutMs;
2092
2179
  this.failureThreshold = failureThreshold;
2093
2180
  this.cooldownMs = cooldownMs;
2181
+ 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) {
2182
+ throw new Error("Disk queue limits and timeout must be finite positive values (pending/cooldown may be zero)");
2183
+ }
2094
2184
  }
2095
2185
  maxConcurrent;
2096
2186
  maxPending;
@@ -2103,6 +2193,17 @@ var BoundedDiskQueue = class {
2103
2193
  consecutiveFailures = 0;
2104
2194
  circuitState = "closed";
2105
2195
  lastStateChangeMonotonic = performance.now();
2196
+ get isSaturated() {
2197
+ return this.active >= this.maxConcurrent && this.queue.length >= this.maxPending;
2198
+ }
2199
+ releaseSlot() {
2200
+ if (this.circuitState === "open") {
2201
+ for (const next2 of this.queue.splice(0)) next2(false);
2202
+ }
2203
+ const next = this.queue.shift();
2204
+ if (next) next(true);
2205
+ else this.active--;
2206
+ }
2106
2207
  async schedule(task) {
2107
2208
  const now = performance.now();
2108
2209
  if (this.circuitState === "open") {
@@ -2118,18 +2219,25 @@ var BoundedDiskQueue = class {
2118
2219
  this.spillsDropped++;
2119
2220
  return null;
2120
2221
  }
2121
- if (this.queue.length >= this.maxPending) {
2222
+ if (this.isSaturated) {
2122
2223
  this.spillsDropped++;
2123
2224
  return null;
2124
2225
  }
2125
2226
  if (this.active >= this.maxConcurrent) {
2126
- await new Promise((resolve) => this.queue.push(resolve));
2227
+ const admitted = await new Promise((resolve) => this.queue.push(resolve));
2228
+ if (!admitted) {
2229
+ this.spillsDropped++;
2230
+ return null;
2231
+ }
2232
+ } else {
2233
+ this.active++;
2127
2234
  }
2128
- this.active++;
2129
2235
  let timeoutId = null;
2236
+ const work = Promise.resolve().then(task);
2237
+ void work.then(() => this.releaseSlot(), () => this.releaseSlot());
2130
2238
  try {
2131
2239
  const result = await Promise.race([
2132
- task(),
2240
+ work,
2133
2241
  new Promise((_, reject) => {
2134
2242
  timeoutId = setTimeout(
2135
2243
  () => reject(new Error(`Disk write exceeded timeout of ${this.writeTimeoutMs}ms`)),
@@ -2148,14 +2256,12 @@ var BoundedDiskQueue = class {
2148
2256
  if (this.consecutiveFailures >= this.failureThreshold || this.circuitState === "half-open") {
2149
2257
  this.circuitState = "open";
2150
2258
  this.lastStateChangeMonotonic = performance.now();
2259
+ for (const next of this.queue.splice(0)) next(false);
2151
2260
  }
2152
2261
  this.spillsDropped++;
2153
2262
  return null;
2154
2263
  } finally {
2155
2264
  if (timeoutId) clearTimeout(timeoutId);
2156
- this.active--;
2157
- const next = this.queue.shift();
2158
- if (next) next();
2159
2265
  }
2160
2266
  }
2161
2267
  getStats() {
@@ -2229,6 +2335,13 @@ var DiskTier = class {
2229
2335
  usageCounted = false;
2230
2336
  fileCount = 0;
2231
2337
  // maintained in-memory; avoids walkCacheFiles() in stats
2338
+ reservedBytes = 0;
2339
+ reservedFiles = 0;
2340
+ saveSequence = 0;
2341
+ epoch = 0;
2342
+ pendingSaves = /* @__PURE__ */ new Map();
2343
+ closed = false;
2344
+ invalidatedKeys = /* @__PURE__ */ new Set();
2232
2345
  /** Next bucket index (0–255) for the staggered janitor wheel. */
2233
2346
  _nextJanitorBucket = 0;
2234
2347
  // ── High-watermark pruning & host volume health state ─────────────────────
@@ -2269,6 +2382,7 @@ var DiskTier = class {
2269
2382
  }
2270
2383
  // ── Helpers ───────────────────────────────────────────────────────────────
2271
2384
  ensureDir() {
2385
+ if (this.closed) return;
2272
2386
  if (this.dirReady) return;
2273
2387
  try {
2274
2388
  import_fs2.default.mkdirSync(this.opts.dir, { recursive: true, mode: 448 });
@@ -2390,8 +2504,24 @@ var DiskTier = class {
2390
2504
  *
2391
2505
  * 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
2392
2506
  */
2393
- hashToWritePath(hash, expiresAt) {
2394
- return import_path2.default.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiresAt.toString(16).padStart(12, "0")}`);
2507
+ hashToWritePath(hash, expiresAt, setAt) {
2508
+ const expiry = Math.floor(expiresAt).toString(16).padStart(12, "0");
2509
+ if (setAt === void 0) return import_path2.default.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}`);
2510
+ const written = Math.floor(setAt).toString(16).padStart(12, "0");
2511
+ const sequence = (++this.saveSequence).toString(16).padStart(12, "0");
2512
+ return import_path2.default.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}_${written}_${sequence}_${import_crypto2.default.randomBytes(6).toString("hex")}`);
2513
+ }
2514
+ findFilePaths(hash) {
2515
+ const bucket = import_path2.default.join(this.opts.dir, hash.slice(0, 2));
2516
+ try {
2517
+ return import_fs2.default.readdirSync(bucket).filter((file) => !file.endsWith(".tmp") && (file === hash || file.startsWith(hash + "_"))).map((file) => import_path2.default.join(bucket, file));
2518
+ } catch {
2519
+ return [];
2520
+ }
2521
+ }
2522
+ fileWrittenAt(file) {
2523
+ const parts = import_path2.default.basename(file).split("_");
2524
+ return parts.length >= 4 ? parseInt(parts[2], 16) : import_fs2.default.statSync(file).mtimeMs;
2395
2525
  }
2396
2526
  /**
2397
2527
  * Find the on-disk file for a key hash, handling all filename generations:
@@ -2400,19 +2530,31 @@ var DiskTier = class {
2400
2530
  * Returns null when the bucket dir does not exist or the key is absent.
2401
2531
  */
2402
2532
  findFilePath(hash) {
2403
- const bucketPath = import_path2.default.join(this.opts.dir, hash.slice(0, 2));
2404
- let files;
2533
+ let match = null;
2534
+ let newest = -Infinity;
2535
+ let sequence = -1;
2536
+ for (const file of this.findFilePaths(hash)) {
2537
+ try {
2538
+ const written = this.fileWrittenAt(file);
2539
+ const order = parseInt(import_path2.default.basename(file).split("_")[3] ?? "0", 16);
2540
+ if (written > newest || written === newest && order > sequence) {
2541
+ match = file;
2542
+ newest = written;
2543
+ sequence = order;
2544
+ }
2545
+ } catch {
2546
+ }
2547
+ }
2548
+ return match;
2549
+ }
2550
+ removeFile(filePath) {
2405
2551
  try {
2406
- files = import_fs2.default.readdirSync(bucketPath);
2552
+ const size = import_fs2.default.statSync(filePath).size;
2553
+ import_fs2.default.unlinkSync(filePath);
2554
+ this.diskUsageBytes = Math.max(0, this.diskUsageBytes - size);
2555
+ this.fileCount = Math.max(0, this.fileCount - 1);
2407
2556
  } catch {
2408
- return null;
2409
- }
2410
- let match;
2411
- for (const f of files) {
2412
- if ((f === hash || f.startsWith(hash + "_")) && (!match || f > match)) match = f;
2413
2557
  }
2414
- if (!match) return null;
2415
- return import_path2.default.join(bucketPath, match);
2416
2558
  }
2417
2559
  /**
2418
2560
  * Recursively list all cache file paths across the 2-level sharded subdirs.
@@ -2487,6 +2629,7 @@ var DiskTier = class {
2487
2629
  * so the Node.js event loop is never stalled waiting for disk I/O.
2488
2630
  */
2489
2631
  async save(key, entry) {
2632
+ if (this.closed || this.diskQueue.isSaturated) return;
2490
2633
  if (this.isForbidden(key)) return;
2491
2634
  if (entry.expiresAt <= Date.now()) return;
2492
2635
  this.ensureDir();
@@ -2495,7 +2638,7 @@ var DiskTier = class {
2495
2638
  if (++this._writeCounter % 2e3 === 0) {
2496
2639
  this.checkHostVolumeHealth();
2497
2640
  }
2498
- if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes >= this.opts.maxBytes) {
2641
+ if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes + this.reservedBytes >= this.opts.maxBytes) {
2499
2642
  this._spillsShedTotal++;
2500
2643
  return;
2501
2644
  }
@@ -2504,11 +2647,12 @@ var DiskTier = class {
2504
2647
  }
2505
2648
  let final;
2506
2649
  try {
2650
+ const { value: _value, ...storedEntry } = entry;
2507
2651
  const payload = {
2508
2652
  version: DISK_TIER_VERSION,
2509
2653
  key,
2510
2654
  entry: {
2511
- ...entry,
2655
+ ...storedEntry,
2512
2656
  data: entry.data instanceof Uint8Array ? Buffer.from(entry.data) : entry.data
2513
2657
  },
2514
2658
  writtenAt: Date.now()
@@ -2521,24 +2665,46 @@ var DiskTier = class {
2521
2665
  }
2522
2666
  const header = Buffer.allocUnsafe(V2_HEADER_LEN);
2523
2667
  DISK_MAGIC_V2.copy(header, 0);
2524
- header.writeBigUInt64LE(BigInt(entry.expiresAt), 8);
2668
+ header.writeBigUInt64LE(BigInt(Math.floor(entry.expiresAt)), 8);
2525
2669
  final = Buffer.concat([header, this.encryptV2(toEncrypt)]);
2670
+ if (final.length > this.opts.entryMaxBytes || this.diskUsageBytes + this.reservedBytes + final.length > this.opts.maxBytes) return;
2526
2671
  } catch (err) {
2527
2672
  this.opts.logger.debug("DiskTier: pack/encrypt failed", { key: key.slice(0, 50), error: err.message });
2528
2673
  return;
2529
2674
  }
2530
2675
  const hash = this.keyToHash(key);
2531
- const filePath = this.hashToWritePath(hash, entry.expiresAt);
2676
+ const setAt = entry.setAt ?? Date.now();
2677
+ if ((this.pendingSaves.get(key)?.setAt ?? 0) > setAt) return;
2678
+ const filePath = this.hashToWritePath(hash, entry.expiresAt, setAt);
2532
2679
  const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${import_crypto2.default.randomBytes(6).toString("hex")}.tmp`;
2533
- this.diskUsageBytes += final.length;
2534
- this.fileCount++;
2680
+ const token = Symbol(key);
2681
+ const epoch = this.epoch;
2682
+ this.pendingSaves.set(key, { token, setAt });
2683
+ const current = () => !this.closed && this.epoch === epoch && this.pendingSaves.get(key)?.token === token;
2684
+ let started = false;
2685
+ let released = false;
2686
+ let accounted = false;
2687
+ const releaseReservation = () => {
2688
+ if (released) return;
2689
+ released = true;
2690
+ this.reservedBytes = Math.max(0, this.reservedBytes - final.length);
2691
+ this.reservedFiles = Math.max(0, this.reservedFiles - 1);
2692
+ if (this.pendingSaves.get(key)?.token === token) this.pendingSaves.delete(key);
2693
+ };
2694
+ this.reservedBytes += final.length;
2695
+ this.reservedFiles++;
2535
2696
  if (this.diskUsageBytes >= this.opts.maxBytes * 0.8 && !this._isPruning) {
2536
2697
  void this.triggerChunkedPrune();
2537
2698
  }
2538
2699
  const result = await this.diskQueue.schedule(async () => {
2700
+ started = true;
2539
2701
  try {
2702
+ if (!current()) return false;
2703
+ const previous = this.findFilePath(hash);
2704
+ if (previous && this.fileWrittenAt(previous) > setAt) return false;
2540
2705
  await import_fs2.default.promises.mkdir(import_path2.default.dirname(filePath), { recursive: true });
2541
2706
  await import_fs2.default.promises.writeFile(tmpPath, final, { mode: 384 });
2707
+ if (!current()) return false;
2542
2708
  try {
2543
2709
  await import_fs2.default.promises.rename(tmpPath, filePath);
2544
2710
  } catch (renameErr) {
@@ -2550,6 +2716,20 @@ var DiskTier = class {
2550
2716
  throw renameErr;
2551
2717
  }
2552
2718
  }
2719
+ if (!current()) {
2720
+ try {
2721
+ await import_fs2.default.promises.unlink(filePath);
2722
+ } catch {
2723
+ }
2724
+ return false;
2725
+ }
2726
+ for (const previousPath of this.findFilePaths(hash)) {
2727
+ if (previousPath !== filePath) this.removeFile(previousPath);
2728
+ }
2729
+ this.diskUsageBytes += final.length;
2730
+ this.fileCount++;
2731
+ accounted = true;
2732
+ this.invalidatedKeys.delete(key);
2553
2733
  if (this._db) {
2554
2734
  const priority = typeof entry.priority === "number" ? entry.priority : 2;
2555
2735
  const lastAccess = typeof entry.lastAccess === "number" ? entry.lastAccess : Date.now();
@@ -2562,23 +2742,25 @@ var DiskTier = class {
2562
2742
  await import_fs2.default.promises.unlink(tmpPath);
2563
2743
  } catch {
2564
2744
  }
2565
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
2566
- this.fileCount = Math.max(0, this.fileCount - 1);
2567
- if (this._db) try {
2568
- this._stmtDelete.run(hash);
2569
- } catch {
2570
- }
2745
+ if (accounted) this.removeFile(filePath);
2571
2746
  this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
2572
2747
  throw err;
2748
+ } finally {
2749
+ try {
2750
+ await import_fs2.default.promises.unlink(tmpPath);
2751
+ } catch {
2752
+ }
2753
+ releaseReservation();
2754
+ if (this.invalidatedKeys.has(key) && !this.pendingSaves.has(key)) this.delete(key, true);
2573
2755
  }
2574
2756
  });
2575
- if (result === null) {
2576
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
2577
- this.fileCount = Math.max(0, this.fileCount - 1);
2757
+ if (result === null && !started) {
2758
+ releaseReservation();
2578
2759
  }
2579
2760
  }
2580
2761
  /** Load a key from disk, or return null on miss/expiry/corruption. */
2581
2762
  load(key) {
2763
+ if (this.invalidatedKeys.has(key) || this.closed) return null;
2582
2764
  if (this.isForbidden(key)) return null;
2583
2765
  this.ensureDir();
2584
2766
  if (!this.dirReady) return null;
@@ -2606,8 +2788,8 @@ var DiskTier = class {
2606
2788
  try {
2607
2789
  if (!this._db) {
2608
2790
  const filename = import_path2.default.basename(filePath);
2609
- if (filename.length === 77 && filename[64] === "_") {
2610
- const expiresAt = parseInt(filename.slice(65), 16);
2791
+ if (filename.length >= 77 && filename[64] === "_") {
2792
+ const expiresAt = parseInt(filename.slice(65, 77), 16);
2611
2793
  if (expiresAt <= Date.now()) {
2612
2794
  try {
2613
2795
  const sz = import_fs2.default.statSync(filePath).size;
@@ -2628,12 +2810,7 @@ var DiskTier = class {
2628
2810
  return null;
2629
2811
  }
2630
2812
  const raw = import_fs2.default.readFileSync(filePath);
2631
- try {
2632
- import_fs2.default.unlinkSync(filePath);
2633
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
2634
- this.fileCount = Math.max(0, this.fileCount - 1);
2635
- } catch {
2636
- }
2813
+ for (const storedPath of this.findFilePaths(hash)) this.removeFile(storedPath);
2637
2814
  if (this._db) this._stmtDelete.run(hash);
2638
2815
  let decrypted;
2639
2816
  if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
@@ -2668,25 +2845,24 @@ var DiskTier = class {
2668
2845
  return null;
2669
2846
  }
2670
2847
  }
2671
- /** Explicitly delete a key from disk (cache invalidation). */
2672
- delete(key) {
2848
+ /** Synchronously fence queued/running saves while leaving filesystem cleanup deferred. */
2849
+ invalidate(key) {
2850
+ this.pendingSaves.delete(key);
2851
+ this.invalidatedKeys.add(key);
2852
+ }
2853
+ /** Delete all versions; deferred cleanup must not cancel a newer save. */
2854
+ delete(key, invalidatedOnly = false) {
2855
+ if (invalidatedOnly && (!this.invalidatedKeys.has(key) || this.pendingSaves.has(key))) return;
2856
+ if (!invalidatedOnly) this.pendingSaves.delete(key);
2673
2857
  const hash = this.keyToHash(key);
2674
- let filePath;
2858
+ const files = new Set(this.findFilePaths(hash));
2675
2859
  if (this._db) {
2676
2860
  const row = this._stmtSelect.get(hash);
2677
- filePath = row?.file_path ?? null;
2861
+ if (row?.file_path) files.add(row.file_path);
2678
2862
  this._stmtDelete.run(hash);
2679
- } else {
2680
- filePath = this.findFilePath(hash);
2681
- }
2682
- if (!filePath) return;
2683
- try {
2684
- const stat = import_fs2.default.statSync(filePath);
2685
- import_fs2.default.unlinkSync(filePath);
2686
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
2687
- this.fileCount = Math.max(0, this.fileCount - 1);
2688
- } catch {
2689
2863
  }
2864
+ for (const file of files) this.removeFile(file);
2865
+ this.invalidatedKeys.delete(key);
2690
2866
  }
2691
2867
  /** Purge all expired entries. Returns number deleted. */
2692
2868
  purgeExpired() {
@@ -2722,8 +2898,8 @@ var DiskTier = class {
2722
2898
  }
2723
2899
  continue;
2724
2900
  }
2725
- if (filename.length === 77 && filename[64] === "_") {
2726
- const expiresAt = parseInt(filename.slice(65), 16);
2901
+ if (filename.length >= 77 && filename[64] === "_") {
2902
+ const expiresAt = parseInt(filename.slice(65, 77), 16);
2727
2903
  if (expiresAt <= now) {
2728
2904
  try {
2729
2905
  const sz = import_fs2.default.statSync(filePath).size;
@@ -2843,8 +3019,8 @@ var DiskTier = class {
2843
3019
  }
2844
3020
  continue;
2845
3021
  }
2846
- if (file.length === 77 && file[64] === "_") {
2847
- const expiresAt = parseInt(file.slice(65), 16);
3022
+ if (file.length >= 77 && file[64] === "_") {
3023
+ const expiresAt = parseInt(file.slice(65, 77), 16);
2848
3024
  if (expiresAt <= now2) {
2849
3025
  const fp = import_path2.default.join(orphanBucketP, file);
2850
3026
  try {
@@ -2884,8 +3060,8 @@ var DiskTier = class {
2884
3060
  }
2885
3061
  continue;
2886
3062
  }
2887
- if (file.length === 77 && file[64] === "_") {
2888
- const expiresAt = parseInt(file.slice(65), 16);
3063
+ if (file.length >= 77 && file[64] === "_") {
3064
+ const expiresAt = parseInt(file.slice(65, 77), 16);
2889
3065
  if (expiresAt <= now) {
2890
3066
  const filePath2 = import_path2.default.join(bucketPath, file);
2891
3067
  try {
@@ -2958,6 +3134,9 @@ var DiskTier = class {
2958
3134
  }
2959
3135
  /** Delete every file in the disk cache. Returns the count deleted. */
2960
3136
  clear() {
3137
+ this.epoch++;
3138
+ this.pendingSaves.clear();
3139
+ this.invalidatedKeys.clear();
2961
3140
  this.ensureDir();
2962
3141
  if (!this.dirReady) return 0;
2963
3142
  let cleared = 0;
@@ -3021,6 +3200,7 @@ var DiskTier = class {
3021
3200
  * yielding to the event loop via setImmediate between chunks.
3022
3201
  */
3023
3202
  async triggerChunkedPrune() {
3203
+ if (this.closed) return 0;
3024
3204
  if (this._isPruning) return 0;
3025
3205
  this._isPruning = true;
3026
3206
  this._pruneRounds++;
@@ -3029,7 +3209,7 @@ var DiskTier = class {
3029
3209
  this.ensureUsageCounted();
3030
3210
  const targetBytes = Math.floor(this.opts.maxBytes * 0.6);
3031
3211
  if (this._db && this._stmtPruneChunk) {
3032
- while (this.diskUsageBytes > targetBytes) {
3212
+ while (!this.closed && this.diskUsageBytes > targetBytes) {
3033
3213
  const rows = this._stmtPruneChunk.all();
3034
3214
  if (!rows || rows.length === 0) break;
3035
3215
  for (const row of rows) {
@@ -3052,7 +3232,7 @@ var DiskTier = class {
3052
3232
  }
3053
3233
  }
3054
3234
  } else {
3055
- while (this.diskUsageBytes > targetBytes) {
3235
+ while (!this.closed && this.diskUsageBytes > targetBytes) {
3056
3236
  const files = this.walkCacheFiles();
3057
3237
  if (files.length === 0) break;
3058
3238
  const chunk = files.slice(0, 500);
@@ -3120,6 +3300,10 @@ var DiskTier = class {
3120
3300
  }
3121
3301
  /** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
3122
3302
  close() {
3303
+ this.closed = true;
3304
+ this.epoch++;
3305
+ this.pendingSaves.clear();
3306
+ this.invalidatedKeys.clear();
3123
3307
  if (this._db) {
3124
3308
  try {
3125
3309
  this._db.close();
@@ -3362,6 +3546,17 @@ function readCgroupMemoryLimit() {
3362
3546
  }
3363
3547
  return Infinity;
3364
3548
  }
3549
+ function readCgroupMemoryUsage() {
3550
+ if (process.platform !== "linux") return null;
3551
+ for (const file of ["/sys/fs/cgroup/memory.current", "/sys/fs/cgroup/memory/memory.usage_in_bytes"]) {
3552
+ try {
3553
+ const value = Number(import_node_fs.default.readFileSync(file, "utf8").trim());
3554
+ if (Number.isFinite(value) && value >= 0) return value;
3555
+ } catch {
3556
+ }
3557
+ }
3558
+ return null;
3559
+ }
3365
3560
  function getV8HeapLimit() {
3366
3561
  try {
3367
3562
  const stats = import_node_v8.default.getHeapStatistics();
@@ -3385,7 +3580,81 @@ function resolveAutonomousL1MaxBytes(options) {
3385
3580
  return Math.max(MIN_AUTONOMOUS_L1_FLOOR_BYTES, Math.floor(resolved));
3386
3581
  }
3387
3582
 
3583
+ // src/utils/diagnostics.ts
3584
+ function redactDiagnostics(value, seen = /* @__PURE__ */ new WeakSet(), depth = 0) {
3585
+ if (typeof value === "string" && /^[a-z][a-z\d+.-]*:\/\//i.test(value)) {
3586
+ try {
3587
+ const url = new URL(value);
3588
+ if (url.username) url.username = "[REDACTED]";
3589
+ if (url.password) url.password = "[REDACTED]";
3590
+ for (const key of url.searchParams.keys()) {
3591
+ if (/key|token|secret|password|credential|authorization|cookie/i.test(key)) url.searchParams.set(key, "[REDACTED]");
3592
+ }
3593
+ return url.toString();
3594
+ } catch {
3595
+ return "[REDACTED URL]";
3596
+ }
3597
+ }
3598
+ if (value == null || typeof value !== "object") return typeof value === "function" ? void 0 : value;
3599
+ if (depth >= 8) return "[OMITTED]";
3600
+ if (seen.has(value)) return "[CIRCULAR]";
3601
+ seen.add(value);
3602
+ if (Array.isArray(value)) return value.map((item) => redactDiagnostics(item, seen, depth + 1));
3603
+ const result = {};
3604
+ for (const [key, item] of Object.entries(value)) {
3605
+ if (typeof item === "function") continue;
3606
+ result[key] = /key|token|secret|password|credential|authorization|cookie|headers/i.test(key) ? item == null ? item : "[REDACTED]" : redactDiagnostics(item, seen, depth + 1);
3607
+ }
3608
+ return result;
3609
+ }
3610
+
3611
+ // src/utils/redis-slot.ts
3612
+ function redisHashSlot(key) {
3613
+ const open = key.indexOf("{");
3614
+ const close = open < 0 ? -1 : key.indexOf("}", open + 1);
3615
+ const bytes = Buffer.from(close > open + 1 ? key.slice(open + 1, close) : key, "utf8");
3616
+ let crc = 0;
3617
+ for (const byte of bytes) {
3618
+ crc ^= byte << 8;
3619
+ for (let bit = 0; bit < 8; bit++) crc = crc << 1 ^ (crc & 32768 ? 4129 : 0);
3620
+ crc &= 65535;
3621
+ }
3622
+ return crc & 16383;
3623
+ }
3624
+
3625
+ // src/utils/deadline.ts
3626
+ async function withDeadline(operation, timeoutMs, label) {
3627
+ let timer;
3628
+ try {
3629
+ return await Promise.race([
3630
+ operation,
3631
+ new Promise((_resolve, reject) => {
3632
+ timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs);
3633
+ })
3634
+ ]);
3635
+ } finally {
3636
+ if (timer) clearTimeout(timer);
3637
+ }
3638
+ }
3639
+
3388
3640
  // src/adapters/auto-pipeliner.ts
3641
+ var import_ioredis = require("ioredis");
3642
+ async function readRedisValue(client, key, hash = false) {
3643
+ if (typeof client.pttl === "function" && typeof client.multi === "function") {
3644
+ const transaction = client.multi();
3645
+ if (typeof transaction.pttl === "function" && (!hash || typeof transaction.hgetall === "function")) {
3646
+ if (hash) transaction.hgetall(key);
3647
+ else transaction.get(key);
3648
+ transaction.pttl(key);
3649
+ const results = await transaction.exec();
3650
+ if (!results) throw new Error("Redis read transaction aborted");
3651
+ if (results[0]?.[0]) throw results[0][0];
3652
+ if (results[1]?.[0]) throw results[1][0];
3653
+ return { raw: results[0]?.[1] ?? null, ttlMs: Number(results[1]?.[1]) };
3654
+ }
3655
+ }
3656
+ return { raw: await (hash ? client.hgetall(key) : client.get(key)) };
3657
+ }
3389
3658
  var AutoPipeliner = class {
3390
3659
  constructor(client, options) {
3391
3660
  this.client = client;
@@ -3417,6 +3686,17 @@ var AutoPipeliner = class {
3417
3686
  this.enqueue({ type: "get", key, resolve, reject });
3418
3687
  });
3419
3688
  }
3689
+ async read(key, hash = false) {
3690
+ if (!hash && typeof this.client.pttl !== "function") return { raw: await this.get(key) };
3691
+ if (!this.enabled || !this.supportsPipelines() || typeof this.client.pttl !== "function") {
3692
+ return readRedisValue(this.client, key, hash);
3693
+ }
3694
+ const probe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
3695
+ if (typeof probe.pttl !== "function" || hash && typeof probe.hgetall !== "function") {
3696
+ return readRedisValue(this.client, key, hash);
3697
+ }
3698
+ return new Promise((resolve, reject) => this.enqueue({ type: "read", key, hash, resolve, reject }));
3699
+ }
3420
3700
  async setex(key, seconds, value) {
3421
3701
  if (!this.enabled || !this.supportsPipelines()) {
3422
3702
  if (typeof this.client.setex === "function") {
@@ -3430,8 +3710,18 @@ var AutoPipeliner = class {
3430
3710
  this.enqueue({ type: "setex", key, seconds, value, resolve, reject });
3431
3711
  });
3432
3712
  }
3713
+ async setpx(key, milliseconds, value) {
3714
+ if (!this.enabled || !this.supportsPipelines()) {
3715
+ await this.client.set(key, value, "PX", milliseconds);
3716
+ return;
3717
+ }
3718
+ return new Promise((resolve, reject) => this.enqueue({ type: "setpx", key, milliseconds, value, resolve, reject }));
3719
+ }
3433
3720
  async del(...keys) {
3434
3721
  if (keys.length === 0) return 0;
3722
+ if (this.client instanceof import_ioredis.Cluster && keys.length > 1) {
3723
+ return (await Promise.all(keys.map((key) => this.del(key)))).reduce((sum, value) => sum + value, 0);
3724
+ }
3435
3725
  if (!this.enabled || !this.supportsPipelines()) {
3436
3726
  return this.client.del(...keys);
3437
3727
  }
@@ -3465,44 +3755,72 @@ var AutoPipeliner = class {
3465
3755
  this.scheduled = false;
3466
3756
  this.statsInternal.batchesDispatched++;
3467
3757
  this.statsInternal.operationsBatched += batch.length;
3468
- const pipe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
3469
- for (const op of batch) {
3470
- switch (op.type) {
3471
- case "get":
3472
- pipe.get(op.key);
3473
- break;
3474
- case "setex":
3475
- pipe.setex(op.key, op.seconds, op.value);
3476
- break;
3477
- case "del":
3478
- pipe.del(...op.keys);
3479
- break;
3480
- }
3758
+ if (this.client instanceof import_ioredis.Cluster) {
3759
+ const groups = /* @__PURE__ */ new Map();
3760
+ for (const operation of batch) {
3761
+ const key = operation.type === "del" ? operation.keys[0] : operation.key;
3762
+ const slot = redisHashSlot(key);
3763
+ const master = this.client.slots[slot]?.[0] ?? String(slot);
3764
+ const members = groups.get(master) ?? [];
3765
+ members.push(operation);
3766
+ groups.set(master, members);
3767
+ }
3768
+ await Promise.all([...groups.values()].map((members) => this.dispatch(members)));
3769
+ return;
3481
3770
  }
3771
+ await this.dispatch(batch);
3772
+ }
3773
+ async dispatch(batch) {
3482
3774
  try {
3775
+ const pipe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
3776
+ const indexes = [];
3777
+ let commandCount = 0;
3778
+ for (const op of batch) {
3779
+ indexes.push(commandCount++);
3780
+ switch (op.type) {
3781
+ case "get":
3782
+ pipe.get(op.key);
3783
+ break;
3784
+ case "setex":
3785
+ pipe.setex(op.key, op.seconds, op.value);
3786
+ break;
3787
+ case "setpx":
3788
+ pipe.set(op.key, op.value, "PX", op.milliseconds);
3789
+ break;
3790
+ case "del":
3791
+ pipe.del(...op.keys);
3792
+ break;
3793
+ case "read":
3794
+ if (op.hash) pipe.hgetall(op.key);
3795
+ else pipe.get(op.key);
3796
+ pipe.pttl(op.key);
3797
+ commandCount++;
3798
+ break;
3799
+ }
3800
+ }
3483
3801
  const results = await pipe.exec();
3484
3802
  if (!results) {
3485
3803
  for (const op of batch) {
3486
- if (op.type === "get") op.resolve(null);
3487
- else if (op.type === "del") op.resolve(0);
3488
- else op.resolve();
3804
+ op.reject(new Error("Redis pipeline aborted"));
3489
3805
  }
3490
3806
  return;
3491
3807
  }
3492
3808
  for (let i = 0; i < batch.length; i++) {
3493
3809
  const op = batch[i];
3494
- const resTuple = results[i];
3810
+ const resTuple = results[indexes[i]];
3495
3811
  if (!resTuple) {
3496
- if (op.type === "get") op.resolve(null);
3497
- else if (op.type === "del") op.resolve(0);
3498
- else op.resolve();
3812
+ op.reject(new Error("Missing Redis pipeline result"));
3499
3813
  continue;
3500
3814
  }
3501
3815
  const [err, val] = resTuple;
3502
3816
  if (err) {
3503
3817
  op.reject(err instanceof Error ? err : new Error(String(err)));
3504
3818
  } else {
3505
- if (op.type === "get") {
3819
+ if (op.type === "read") {
3820
+ const ttlResult = results[indexes[i] + 1];
3821
+ if (!ttlResult || ttlResult[0]) op.reject(ttlResult?.[0] ?? new Error("Missing Redis PTTL result"));
3822
+ else op.resolve({ raw: val, ttlMs: Number(ttlResult[1]) });
3823
+ } else if (op.type === "get") {
3506
3824
  op.resolve(val != null ? String(val) : null);
3507
3825
  } else if (op.type === "del") {
3508
3826
  op.resolve(typeof val === "number" ? val : Number(val) || 0);
@@ -3539,6 +3857,8 @@ var IpcTelemetryServer = class {
3539
3857
  server = null;
3540
3858
  socketPath;
3541
3859
  _closed = false;
3860
+ _starting = null;
3861
+ sockets = /* @__PURE__ */ new Set();
3542
3862
  _exitHandler = null;
3543
3863
  _sigintHandler = null;
3544
3864
  _sigtermHandler = null;
@@ -3546,10 +3866,23 @@ var IpcTelemetryServer = class {
3546
3866
  * Start listening on the IPC socket / pipe.
3547
3867
  */
3548
3868
  async start() {
3549
- if (this.server && this.server.listening) return;
3869
+ if (this._closed || this.server?.listening) return;
3870
+ if (this._starting) return this._starting;
3871
+ this._starting = this.startInternal();
3872
+ try {
3873
+ await this._starting;
3874
+ } finally {
3875
+ this._starting = null;
3876
+ }
3877
+ }
3878
+ async startInternal() {
3550
3879
  if (process.platform !== "win32" && import_node_fs2.default.existsSync(this.socketPath)) {
3551
3880
  await new Promise((resolve) => {
3552
3881
  const testSocket = import_node_net.default.createConnection(this.socketPath);
3882
+ testSocket.setTimeout(1e3, () => {
3883
+ testSocket.destroy();
3884
+ resolve();
3885
+ });
3553
3886
  testSocket.once("connect", () => {
3554
3887
  testSocket.destroy();
3555
3888
  resolve();
@@ -3564,17 +3897,37 @@ var IpcTelemetryServer = class {
3564
3897
  });
3565
3898
  });
3566
3899
  }
3900
+ if (this._closed) return;
3567
3901
  this.server = import_node_net.default.createServer((socket) => {
3902
+ if (this._closed) {
3903
+ socket.destroy();
3904
+ return;
3905
+ }
3906
+ this.sockets.add(socket);
3907
+ socket.once("close", () => this.sockets.delete(socket));
3908
+ socket.setTimeout(5e3, () => socket.destroy());
3568
3909
  let buffer = "";
3910
+ let pending = 0;
3569
3911
  socket.on("data", (chunk) => {
3912
+ if (Buffer.byteLength(buffer) + chunk.length > 4096 || socket.writableLength > 65536) {
3913
+ socket.destroy();
3914
+ return;
3915
+ }
3570
3916
  buffer += chunk.toString("utf8");
3571
3917
  let newlineIndex;
3572
3918
  while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
3573
3919
  const line = buffer.slice(0, newlineIndex).trim();
3574
3920
  buffer = buffer.slice(newlineIndex + 1);
3575
3921
  if (!line) continue;
3922
+ if (++pending > 8) {
3923
+ socket.destroy();
3924
+ return;
3925
+ }
3576
3926
  setImmediate(() => {
3577
- if (socket.destroyed) return;
3927
+ if (socket.destroyed) {
3928
+ pending--;
3929
+ return;
3930
+ }
3578
3931
  try {
3579
3932
  let cmd = line;
3580
3933
  try {
@@ -3599,6 +3952,8 @@ var IpcTelemetryServer = class {
3599
3952
  if (!socket.destroyed) {
3600
3953
  socket.write(JSON.stringify({ error: err.message }) + "\n");
3601
3954
  }
3955
+ } finally {
3956
+ pending--;
3602
3957
  }
3603
3958
  });
3604
3959
  }
@@ -3606,21 +3961,38 @@ var IpcTelemetryServer = class {
3606
3961
  socket.on("error", () => {
3607
3962
  });
3608
3963
  });
3964
+ this.server.maxConnections = 128;
3609
3965
  await new Promise((resolve, reject) => {
3610
- this.server.once("error", reject);
3611
- this.server.listen(this.socketPath, () => {
3612
- this.server.removeListener("error", reject);
3966
+ const server = this.server;
3967
+ const cleanup = () => {
3968
+ server.off("error", failed);
3969
+ server.off("close", closed);
3970
+ };
3971
+ const failed = (error) => {
3972
+ cleanup();
3973
+ reject(error);
3974
+ };
3975
+ const closed = () => {
3976
+ cleanup();
3977
+ resolve();
3978
+ };
3979
+ server.once("error", failed);
3980
+ server.once("close", closed);
3981
+ server.listen(this.socketPath, () => {
3982
+ cleanup();
3613
3983
  resolve();
3614
3984
  });
3615
3985
  });
3986
+ if (this._closed) {
3987
+ if (this.server.listening) this.server.close();
3988
+ return;
3989
+ }
3616
3990
  this._exitHandler = () => this._unlinkSocket();
3617
3991
  this._sigintHandler = () => {
3618
3992
  this._unlinkSocket();
3619
- process.exit(0);
3620
3993
  };
3621
3994
  this._sigtermHandler = () => {
3622
3995
  this._unlinkSocket();
3623
- process.exit(0);
3624
3996
  };
3625
3997
  process.once("exit", this._exitHandler);
3626
3998
  process.once("SIGINT", this._sigintHandler);
@@ -3650,6 +4022,7 @@ var IpcTelemetryServer = class {
3650
4022
  _unlinkSocket() {
3651
4023
  if (this._closed) return;
3652
4024
  this._closed = true;
4025
+ for (const socket of this.sockets) socket.destroy();
3653
4026
  try {
3654
4027
  this.server?.close();
3655
4028
  } catch {
@@ -3667,6 +4040,9 @@ var IpcTelemetryServer = class {
3667
4040
  * Gracefully close the IPC telemetry server and clean up handlers and sockets.
3668
4041
  */
3669
4042
  async close() {
4043
+ this._unlinkSocket();
4044
+ await this._starting?.catch(() => {
4045
+ });
3670
4046
  if (this._exitHandler) {
3671
4047
  process.removeListener("exit", this._exitHandler);
3672
4048
  this._exitHandler = null;
@@ -3679,7 +4055,6 @@ var IpcTelemetryServer = class {
3679
4055
  process.removeListener("SIGTERM", this._sigtermHandler);
3680
4056
  this._sigtermHandler = null;
3681
4057
  }
3682
- this._unlinkSocket();
3683
4058
  return new Promise((resolve) => {
3684
4059
  if (!this.server || !this.server.listening) {
3685
4060
  resolve();
@@ -3750,6 +4125,37 @@ if currentTs and currentTs == ARGV[1] then
3750
4125
  end
3751
4126
  return 0
3752
4127
  `;
4128
+ var LUA_READ_CACHE_ENTRY = `
4129
+ local kind = redis.call('TYPE', KEYS[1]).ok
4130
+ if kind == 'string' then
4131
+ return { kind, redis.call('GET', KEYS[1]), redis.call('PTTL', KEYS[1]) }
4132
+ elseif kind == 'hash' then
4133
+ return { kind, redis.call('HGETALL', KEYS[1]), redis.call('PTTL', KEYS[1]) }
4134
+ end
4135
+ return { 'none', false, -2 }
4136
+ `;
4137
+ var LUA_MAX_TAG_VERSION = `
4138
+ local current = tonumber(redis.call('GET', KEYS[1]) or '0')
4139
+ local floor = tonumber(ARGV[1])
4140
+ if current < floor then redis.call('SET', KEYS[1], floor) return floor end
4141
+ return current
4142
+ `;
4143
+ var LUA_RECEIVE_TAG_VERSION = `
4144
+ local current = tonumber(redis.call('GET', KEYS[1]) or '0')
4145
+ local next = math.max(current + 1, tonumber(ARGV[1]))
4146
+ redis.call('SET', KEYS[1], next)
4147
+ return next
4148
+ `;
4149
+ var LUA_TOUCH_CACHE_ENTRY = `
4150
+ local kind = redis.call('TYPE', KEYS[1]).ok
4151
+ if kind == 'hash' then
4152
+ if redis.call('HGET', KEYS[1], 't') ~= ARGV[1] then return 0 end
4153
+ redis.call('HSET', KEYS[1], 'e', ARGV[2])
4154
+ elseif kind ~= 'string' then
4155
+ return 0
4156
+ end
4157
+ return redis.call('PEXPIRE', KEYS[1], ARGV[3])
4158
+ `;
3753
4159
  var SNAPSHOT_VERSION = 1;
3754
4160
  var DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
3755
4161
  var INDEFINITE_TTL_SECONDS = 31536e3;
@@ -4038,13 +4444,19 @@ var CacheService = class _CacheService {
4038
4444
  _l1Counters = /* @__PURE__ */ new Map();
4039
4445
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
4040
4446
  tagIndex = /* @__PURE__ */ new Map();
4447
+ /** Reverse index of namespaced key → { tags, expiresAt } for bounded cleanup on eviction/delete */
4448
+ keyTags = /* @__PURE__ */ new Map();
4041
4449
  /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
4042
4450
  tagVersions = /* @__PURE__ */ new Map();
4451
+ _tagRefreshEpoch = 0;
4043
4452
  /**
4044
4453
  * Dependency index: source glob pattern → Set of namespaced dependent keys.
4045
4454
  * When an exact-key delete matches a registered pattern, all dependents are cascaded.
4046
4455
  */
4047
4456
  dependencyIndex = /* @__PURE__ */ new Map();
4457
+ /** Reverse index of namespaced dependent key → source glob patterns */
4458
+ keyDependencies = /* @__PURE__ */ new Map();
4459
+ _cgroupMemoryLimit;
4048
4460
  redis = null;
4049
4461
  redisConnecting = null;
4050
4462
  cb;
@@ -4067,9 +4479,17 @@ var CacheService = class _CacheService {
4067
4479
  subClient = null;
4068
4480
  streamClient = null;
4069
4481
  _lastStreamId = "$";
4482
+ _restoredSnapshot = false;
4483
+ _backplaneAvailable = false;
4484
+ _otelCleanup = null;
4485
+ _streamRecovering = false;
4486
+ _backplaneDisposers = [];
4070
4487
  _destroyed = false;
4071
4488
  _pendingDiskDeletes = /* @__PURE__ */ new Set();
4072
4489
  _globalEpoch = 0;
4490
+ _pendingSpillCount = 0;
4491
+ _suppressSpills = false;
4492
+ _diskCleanupScheduled = false;
4073
4493
  _keyMutationEpochs = /* @__PURE__ */ new Map();
4074
4494
  /**
4075
4495
  * Pattern tombstones for disk tier.
@@ -4078,20 +4498,24 @@ var CacheService = class _CacheService {
4078
4498
  * pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
4079
4499
  */
4080
4500
  _patternTombstones = [];
4081
- _addPatternTombstone(prefix) {
4501
+ _diskInvalidatedBefore = 0;
4502
+ _addPatternTombstone(pattern) {
4082
4503
  const now = Date.now();
4083
4504
  while (this._patternTombstones.length > 0 && now - this._patternTombstones[0].createdAt > 36e5) {
4084
- this._patternTombstones.shift();
4505
+ const forgotten = this._patternTombstones.shift();
4506
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
4085
4507
  }
4086
4508
  if (this._patternTombstones.length >= 2e3) {
4087
- this._patternTombstones.shift();
4509
+ const forgotten = this._patternTombstones.shift();
4510
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
4088
4511
  }
4089
- this._patternTombstones.push({ prefix, createdAt: now });
4512
+ this._patternTombstones.push({ pattern, createdAt: now });
4090
4513
  }
4091
- _isTombstonedByPattern(namespacedKey) {
4514
+ _isTombstonedByPattern(namespacedKey, setAt = 0) {
4515
+ if (this._diskInvalidatedBefore > 0 && setAt <= this._diskInvalidatedBefore) return true;
4092
4516
  if (this._patternTombstones.length === 0) return false;
4093
4517
  for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
4094
- if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
4518
+ if (setAt <= this._patternTombstones[i].createdAt && this._matchesGlob(namespacedKey, this._patternTombstones[i].pattern)) {
4095
4519
  return true;
4096
4520
  }
4097
4521
  }
@@ -4106,13 +4530,170 @@ var CacheService = class _CacheService {
4106
4530
  const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
4107
4531
  this._keyMutationEpochs.set(namespacedKey, next);
4108
4532
  if (this._keyMutationEpochs.size > 5e4) {
4109
- const oldest = this._keyMutationEpochs.keys().next().value;
4110
- if (oldest !== void 0) this._keyMutationEpochs.delete(oldest);
4533
+ this._globalEpoch++;
4534
+ this._keyMutationEpochs.clear();
4535
+ this._keyMutationEpochs.set(namespacedKey, next);
4111
4536
  }
4112
4537
  return next;
4113
4538
  }
4114
4539
  _getKeyMutationEpoch(namespacedKey) {
4115
- return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
4540
+ return `${this._globalEpoch}:${this._keyMutationEpochs.get(namespacedKey) ?? 0}`;
4541
+ }
4542
+ /** Capture a commit fence before asynchronous computation outside the cache. */
4543
+ captureMutationFence(cacheKey) {
4544
+ this._assertActive("captureMutationFence");
4545
+ const key = this.nk(cacheKey);
4546
+ const epoch = this._getKeyMutationEpoch(key);
4547
+ return () => !this._destroyed && this._getKeyMutationEpoch(key) === epoch;
4548
+ }
4549
+ /** Force tag re-sync without forgetting locally observed monotonic generations. */
4550
+ refreshTagVersions() {
4551
+ this._assertActive("refreshTagVersions");
4552
+ this._tagRefreshEpoch++;
4553
+ }
4554
+ _fenceInvalidation() {
4555
+ this._globalEpoch++;
4556
+ this.inflight.clear();
4557
+ }
4558
+ _invalidateDiskKey(key) {
4559
+ if (this._diskDisabled) return;
4560
+ this.disk.invalidate(key);
4561
+ this._pendingDiskDeletes.add(key);
4562
+ this._scheduleDiskCleanup();
4563
+ }
4564
+ _scheduleDiskCleanup() {
4565
+ if (this._diskCleanupScheduled || this._pendingDiskDeletes.size === 0) return;
4566
+ this._diskCleanupScheduled = true;
4567
+ setImmediate(() => {
4568
+ this._diskCleanupScheduled = false;
4569
+ if (this._destroyed) return;
4570
+ let processed = 0;
4571
+ for (const key of this._pendingDiskDeletes) {
4572
+ try {
4573
+ this.disk.delete(key, true);
4574
+ } finally {
4575
+ this._pendingDiskDeletes.delete(key);
4576
+ }
4577
+ if (++processed >= 16) break;
4578
+ }
4579
+ this._scheduleDiskCleanup();
4580
+ });
4581
+ }
4582
+ _registerDependencies(key, patterns) {
4583
+ this._removeKeyDependencies(key);
4584
+ if (!patterns?.length) return;
4585
+ const namespaced = [...new Set(patterns.map((pattern) => this.nk(pattern)))];
4586
+ for (const pattern of namespaced) {
4587
+ const dependents = this.dependencyIndex.get(pattern) ?? /* @__PURE__ */ new Set();
4588
+ dependents.add(key);
4589
+ this.dependencyIndex.set(pattern, dependents);
4590
+ }
4591
+ this.keyDependencies.set(key, namespaced);
4592
+ }
4593
+ _rememberTags(key, tags, expiresAt) {
4594
+ this._removeKeyTags(key);
4595
+ if (!tags.length) return;
4596
+ if (this.keyTags.size >= 1e5) {
4597
+ this._sweepExpiredMetadata();
4598
+ const oldest = this.keyTags.keys().next().value;
4599
+ if (this.keyTags.size >= 1e5 && oldest !== void 0) this._removeKeyTags(oldest);
4600
+ }
4601
+ const unique = [...new Set(tags)];
4602
+ for (const tag of unique) {
4603
+ const tagKey = this.nk(`_tag_:${tag}`);
4604
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
4605
+ members.add(key);
4606
+ this.tagIndex.set(tagKey, members);
4607
+ }
4608
+ this.keyTags.set(key, { tags: unique, expiresAt });
4609
+ }
4610
+ _restoreEntryMetadata(key, entry) {
4611
+ if (entry.tags?.length) this._rememberTags(key, entry.tags, entry.expiresAt);
4612
+ if (entry.dependsOn?.length) this._registerDependencies(key, entry.dependsOn);
4613
+ }
4614
+ _removeKeyTags(namespacedKey) {
4615
+ const entry = this.keyTags.get(namespacedKey);
4616
+ if (!entry) return;
4617
+ for (const tag of entry.tags) {
4618
+ const tagKey = this.nk(`_tag_:${tag}`);
4619
+ const members = this.tagIndex.get(tagKey);
4620
+ if (members) {
4621
+ members.delete(namespacedKey);
4622
+ if (members.size === 0) this.tagIndex.delete(tagKey);
4623
+ }
4624
+ }
4625
+ this.keyTags.delete(namespacedKey);
4626
+ }
4627
+ _removeKeyDependencies(namespacedKey) {
4628
+ const patterns = this.keyDependencies.get(namespacedKey);
4629
+ if (patterns) {
4630
+ for (const pat of patterns) {
4631
+ const deps = this.dependencyIndex.get(pat);
4632
+ if (deps) {
4633
+ deps.delete(namespacedKey);
4634
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
4635
+ }
4636
+ }
4637
+ this.keyDependencies.delete(namespacedKey);
4638
+ } else if (this.dependencyIndex.size > 0) {
4639
+ for (const [pat, deps] of this.dependencyIndex) {
4640
+ deps.delete(namespacedKey);
4641
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
4642
+ }
4643
+ }
4644
+ }
4645
+ _handleL1Eviction(namespacedKey, reason) {
4646
+ const spilledToDisk = !this._diskDisabled && !this._suppressSpills && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
4647
+ if (!spilledToDisk) {
4648
+ this._removeKeyTags(namespacedKey);
4649
+ this._removeKeyDependencies(namespacedKey);
4650
+ }
4651
+ }
4652
+ _removePatternFromIndices(pattern) {
4653
+ for (const k of Array.from(this.keyTags.keys())) {
4654
+ if (this._matchesGlob(k, pattern)) this._removeKeyTags(k);
4655
+ }
4656
+ for (const k of Array.from(this.keyDependencies.keys())) {
4657
+ if (this._matchesGlob(k, pattern)) this._removeKeyDependencies(k);
4658
+ }
4659
+ for (const k of Array.from(this._l1Counters.keys())) {
4660
+ if (this._matchesGlob(k, pattern)) this._l1Counters.delete(k);
4661
+ }
4662
+ }
4663
+ _sweepExpiredMetadata() {
4664
+ const now = Date.now();
4665
+ for (const [k, c] of this._l1Counters) {
4666
+ if (c.expiresAt <= now) this._l1Counters.delete(k);
4667
+ }
4668
+ for (const [k, meta] of this.keyTags) {
4669
+ if (meta.expiresAt <= now && !this.l1.has(k)) {
4670
+ this._removeKeyTags(k);
4671
+ this._removeKeyDependencies(k);
4672
+ }
4673
+ }
4674
+ }
4675
+ _runOomCheck() {
4676
+ const heap = import_node_v82.default.getHeapStatistics();
4677
+ const heapUsed = heap.used_heap_size / heap.heap_size_limit;
4678
+ const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? (readCgroupMemoryUsage() ?? process.memoryUsage().rss) / this._cgroupMemoryLimit : 0;
4679
+ const used = Math.max(heapUsed, cgroupUsed);
4680
+ if (used >= this.opts.oomHeapThreshold) {
4681
+ this._suppressSpills = cgroupUsed >= this.opts.oomHeapThreshold;
4682
+ let evicted;
4683
+ try {
4684
+ evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
4685
+ } finally {
4686
+ this._suppressSpills = false;
4687
+ }
4688
+ this.counters.oomEvictions++;
4689
+ this.counters.oomLastAt = Date.now();
4690
+ this.logger.warn("tricache OOM guard: emergency L1 eviction", {
4691
+ heapUsedPct: Math.round(heapUsed * 100),
4692
+ cgroupUsedPct: cgroupUsed > 0 ? Math.round(cgroupUsed * 100) : void 0,
4693
+ threshold: Math.round(this.opts.oomHeapThreshold * 100),
4694
+ evicted
4695
+ });
4696
+ }
4116
4697
  }
4117
4698
  _ipcServer;
4118
4699
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
@@ -4160,6 +4741,7 @@ var CacheService = class _CacheService {
4160
4741
  constructor(options = {}) {
4161
4742
  const logger = options.logger ?? consoleLogger;
4162
4743
  this.logger = logger;
4744
+ this._cgroupMemoryLimit = readCgroupMemoryLimit();
4163
4745
  const ns = options.namespace?.trim() ?? "";
4164
4746
  const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
4165
4747
  this.enc = new CacheEncryption(
@@ -4338,12 +4920,19 @@ var CacheService = class _CacheService {
4338
4920
  admissionPolicy: this.opts.l1AdmissionPolicy,
4339
4921
  codec: this.codec,
4340
4922
  diskSpill: (key, entry) => {
4341
- if (this._diskDisabled) return;
4923
+ if (this._diskDisabled || this._suppressSpills) return;
4924
+ if (this._pendingSpillCount >= (this.opts.diskMaxPendingWrites ?? 512)) return;
4925
+ const epoch = this._getKeyMutationEpoch(key);
4926
+ this._pendingSpillCount++;
4342
4927
  setImmediate(() => {
4343
- void this.disk.save(key, entry);
4928
+ this._pendingSpillCount--;
4929
+ if (!this._destroyed && this._getKeyMutationEpoch(key) === epoch) void this.disk.save(key, entry);
4344
4930
  });
4345
4931
  },
4346
- onEviction: options.onEviction,
4932
+ onEviction: (key, reason) => {
4933
+ this._handleL1Eviction(key, reason);
4934
+ options.onEviction?.(key, reason);
4935
+ },
4347
4936
  logger
4348
4937
  });
4349
4938
  if (!this.snapshotLoaded) {
@@ -4381,6 +4970,7 @@ var CacheService = class _CacheService {
4381
4970
  }
4382
4971
  this.cleanupInterval = setInterval(() => {
4383
4972
  const cleaned = this.l1.cleanup();
4973
+ this._sweepExpiredMetadata();
4384
4974
  if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
4385
4975
  }, 5 * 60 * 1e3);
4386
4976
  if (this.cleanupInterval.unref) this.cleanupInterval.unref();
@@ -4393,18 +4983,7 @@ var CacheService = class _CacheService {
4393
4983
  }
4394
4984
  if (this.opts.oomProtection) {
4395
4985
  this.oomInterval = setInterval(() => {
4396
- const heap = import_node_v82.default.getHeapStatistics();
4397
- const used = heap.used_heap_size / heap.heap_size_limit;
4398
- if (used >= this.opts.oomHeapThreshold) {
4399
- const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
4400
- this.counters.oomEvictions++;
4401
- this.counters.oomLastAt = Date.now();
4402
- this.logger.warn("tricache OOM guard: emergency L1 eviction", {
4403
- heapUsedPct: Math.round(used * 100),
4404
- threshold: Math.round(this.opts.oomHeapThreshold * 100),
4405
- evicted
4406
- });
4407
- }
4986
+ this._runOomCheck();
4408
4987
  }, this.opts.oomCheckIntervalMs);
4409
4988
  if (this.oomInterval.unref) this.oomInterval.unref();
4410
4989
  }
@@ -4426,7 +5005,7 @@ var CacheService = class _CacheService {
4426
5005
  this.instanceId = import_crypto3.default.randomBytes(8).toString("hex");
4427
5006
  this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
4428
5007
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
4429
- this.initBackplane();
5008
+ 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 }));
4430
5009
  const startupPromises = [];
4431
5010
  if (this.opts.compression === "zstd") {
4432
5011
  startupPromises.push(initZstd().then(() => void 0));
@@ -4437,9 +5016,8 @@ var CacheService = class _CacheService {
4437
5016
  if (this.opts.warmKeys) {
4438
5017
  startupPromises.push(this.warmFromL2(this.opts.warmKeys).then(() => void 0));
4439
5018
  }
4440
- if (startupPromises.length > 0) {
4441
- this._readyPromise = Promise.all(startupPromises).then(() => void 0);
4442
- }
5019
+ const backplaneReady = this.opts.remoteSnapshot || this.opts.warmKeys ? Promise.all(startupPromises).then(startBackplane) : startBackplane();
5020
+ this._readyPromise = Promise.all([...startupPromises, backplaneReady]).then(() => void 0);
4443
5021
  if (this.opts.meter) {
4444
5022
  this._initOtelMetrics(this.opts.meter);
4445
5023
  const otel = this._otelMetrics;
@@ -4452,7 +5030,10 @@ var CacheService = class _CacheService {
4452
5030
  if (typeof prop === "string" && typeof value === "number" && typeof oldVal === "number") {
4453
5031
  const diff = value - oldVal;
4454
5032
  if (diff > 0 && otel[prop]) {
4455
- otel[prop].add(diff, nsAttr);
5033
+ try {
5034
+ otel[prop].add(diff, nsAttr);
5035
+ } catch {
5036
+ }
4456
5037
  }
4457
5038
  }
4458
5039
  return ok;
@@ -4544,7 +5125,7 @@ var CacheService = class _CacheService {
4544
5125
  return g[key];
4545
5126
  }
4546
5127
  const existing = g[key];
4547
- const diff = _CacheService.optionsDiff(options ?? {}, existing.options);
5128
+ const diff = _CacheService.optionsDiff(options ?? {}, existing.opts);
4548
5129
  if (diff.length > 0) {
4549
5130
  existing.bumpSingletonDivergence();
4550
5131
  const msg = `tricache: singleton already initialised for namespace '${existing.options.namespace || "(default)"}' \u2014 ignoring divergent options: ${diff.join(", ")}`;
@@ -4578,7 +5159,13 @@ var CacheService = class _CacheService {
4578
5159
  "instanceName",
4579
5160
  "invalidationBackplane",
4580
5161
  "awaitInvalidationBackplane",
4581
- "lockFailClosed"
5162
+ "lockFailClosed",
5163
+ "tagStrategy",
5164
+ "cloneStrategy",
5165
+ "compression",
5166
+ "backplaneMode",
5167
+ "redisProtocol",
5168
+ "failClosed"
4582
5169
  ];
4583
5170
  /** Returns the names of options that differ between `a` and the live `b`. */
4584
5171
  static optionsDiff(a, b) {
@@ -4596,12 +5183,12 @@ var CacheService = class _CacheService {
4596
5183
  bumpSingletonDivergence() {
4597
5184
  this.counters.singletonDivergences++;
4598
5185
  }
4599
- /** Read-only view of the options the singleton was constructed with. */
5186
+ /** Sanitized diagnostic view; retain the original options/adapters to reuse configuration. */
4600
5187
  get options() {
4601
5188
  const o = this.opts;
4602
5189
  return {
4603
5190
  namespace: o.namespace,
4604
- logger: o.logger,
5191
+ 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) },
4605
5192
  l1MaxBytes: o.l1MaxBytes,
4606
5193
  l1MaxEntries: o.l1MaxEntries,
4607
5194
  redisHost: o.redisHost,
@@ -4622,8 +5209,8 @@ var CacheService = class _CacheService {
4622
5209
  awaitInvalidationBackplane: o.awaitInvalidationBackplane,
4623
5210
  lockFailClosed: o.lockFailClosed,
4624
5211
  strictSingleton: o.strictSingleton,
4625
- remoteSnapshot: o.remoteSnapshot,
4626
- crossRegion: o.crossRegion
5212
+ remoteSnapshot: redactDiagnostics(o.remoteSnapshot),
5213
+ crossRegion: redactDiagnostics(o.crossRegion)
4627
5214
  };
4628
5215
  }
4629
5216
  /**
@@ -4706,21 +5293,26 @@ var CacheService = class _CacheService {
4706
5293
  if (this.opts.redisClient && typeof this.opts.redisClient.duplicate === "function") {
4707
5294
  return this.opts.redisClient.duplicate();
4708
5295
  }
5296
+ if (this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel) {
5297
+ throw new Error("Invalidation backplane requires redisSubClient or a driver supporting duplicate()");
5298
+ }
4709
5299
  if (this.opts.redisClusterNodes?.length) {
4710
- return new import_ioredis.Cluster(this.opts.redisClusterNodes, {
5300
+ return new import_ioredis2.Cluster(this.opts.redisClusterNodes, {
4711
5301
  redisOptions: {
4712
5302
  tls: this.opts.redisTls ? {} : void 0,
4713
5303
  connectTimeout: 1e4,
5304
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
4714
5305
  maxRetriesPerRequest: null,
4715
5306
  ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
4716
5307
  }
4717
5308
  });
4718
5309
  } else if (this.opts.redisSentinel) {
4719
- return new import_ioredis.Redis({
5310
+ return new import_ioredis2.Redis({
4720
5311
  sentinels: this.opts.redisSentinel.sentinels,
4721
5312
  name: this.opts.redisSentinel.name,
4722
5313
  tls: this.opts.redisTls ? {} : void 0,
4723
5314
  connectTimeout: 1e4,
5315
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
4724
5316
  lazyConnect: true,
4725
5317
  maxRetriesPerRequest: null,
4726
5318
  enableAutoPipelining: false,
@@ -4728,11 +5320,12 @@ var CacheService = class _CacheService {
4728
5320
  ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
4729
5321
  });
4730
5322
  } else {
4731
- return new import_ioredis.Redis({
5323
+ return new import_ioredis2.Redis({
4732
5324
  host: this.opts.redisHost,
4733
5325
  port: this.opts.redisPort,
4734
5326
  tls: this.opts.redisTls ? {} : void 0,
4735
5327
  connectTimeout: 1e4,
5328
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
4736
5329
  lazyConnect: true,
4737
5330
  maxRetriesPerRequest: null,
4738
5331
  enableAutoPipelining: false,
@@ -4742,26 +5335,32 @@ var CacheService = class _CacheService {
4742
5335
  });
4743
5336
  }
4744
5337
  }
4745
- initBackplane() {
5338
+ _listenBackplane(client, event, listener) {
5339
+ client.on?.(event, listener);
5340
+ this._backplaneDisposers.push(() => client.removeListener?.(event, listener));
5341
+ }
5342
+ async initBackplane() {
4746
5343
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
4747
5344
  if (this.opts.backplaneMode === "stream") {
4748
5345
  if (this.streamClient) return;
4749
- void this._startStreamConsumer();
5346
+ await this._startStreamConsumer();
4750
5347
  return;
4751
5348
  }
4752
5349
  if (this.subClient) return;
4753
5350
  const sub = this.createDedicatedRedisClient();
4754
- sub.on("error", (e) => {
5351
+ this.subClient = sub;
5352
+ this._listenBackplane(sub, "error", (e) => {
4755
5353
  this._checkAndLogResp3Hint(e);
4756
5354
  this.logger.debug("Backplane subscriber error", { error: e.message });
4757
5355
  });
4758
- sub.on("close", () => {
5356
+ this._listenBackplane(sub, "close", () => {
5357
+ this._backplaneAvailable = false;
4759
5358
  if (this._subDisconnectedAt === null) {
4760
5359
  this._subDisconnectedAt = Date.now();
4761
5360
  this.logger.debug("Backplane: subscriber disconnected", { at: this._subDisconnectedAt });
4762
5361
  }
4763
5362
  });
4764
- sub.on("ready", () => {
5363
+ this._listenBackplane(sub, "ready", () => {
4765
5364
  if (this._subDisconnectedAt !== null && this.opts.backplaneMaxStalenessMs > 0) {
4766
5365
  const gapMs = Date.now() - this._subDisconnectedAt;
4767
5366
  if (gapMs > this.opts.backplaneMaxStalenessMs) {
@@ -4774,52 +5373,119 @@ var CacheService = class _CacheService {
4774
5373
  }
4775
5374
  this._subDisconnectedAt = null;
4776
5375
  }
5376
+ if (!this._destroyed) this._backplaneAvailable = true;
4777
5377
  });
4778
5378
  const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
4779
5379
  if (isClusterSharded) {
4780
- sub.on("smessage", (_channel, message) => {
5380
+ this._listenBackplane(sub, "smessage", (_channel, message) => {
4781
5381
  this._handleBackplaneMessage(message);
4782
5382
  });
4783
- sub.ssubscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: sharded subscribed", {
5383
+ if (typeof sub.connect === "function" && (sub.isOpen === false || sub.status === "wait")) await sub.connect();
5384
+ await sub.ssubscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: sharded subscribed", {
4784
5385
  channel: this.backplaneChannel,
4785
5386
  instanceId: this.instanceId
4786
- })).catch((err) => this.logger.warn("Backplane: sharded subscribe failed", {
4787
- error: err.message
4788
5387
  }));
4789
5388
  } else {
4790
- sub.on("message", (_channel, message) => {
5389
+ this._listenBackplane(sub, "message", (_channel, message) => {
4791
5390
  this._handleBackplaneMessage(message);
4792
5391
  });
4793
- sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
5392
+ if (typeof sub.connect === "function" && (sub.isOpen === false || sub.status === "wait")) await sub.connect();
5393
+ if (this._destroyed) return;
5394
+ await sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
4794
5395
  channel: this.backplaneChannel,
4795
5396
  instanceId: this.instanceId
4796
- })).catch((err) => this.logger.warn("Backplane: subscribe failed", {
4797
- error: err.message
4798
5397
  }));
4799
5398
  }
4800
- this.subClient = sub;
5399
+ if (!this._destroyed) this._backplaneAvailable = true;
5400
+ }
5401
+ _resetAfterStreamGap() {
5402
+ this.counters.streamGaps++;
5403
+ this._fenceInvalidation();
5404
+ this.l1.clear();
5405
+ this.tagIndex.clear();
5406
+ this.keyTags.clear();
5407
+ this.tagVersions.clear();
5408
+ this.dependencyIndex.clear();
5409
+ this.keyDependencies.clear();
5410
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, Date.now());
5411
+ this._addPatternTombstone(this.nk("*"));
5412
+ this._lastStreamId = "0-0";
4801
5413
  }
4802
5414
  async _startStreamConsumer() {
5415
+ this._streamRecovering ||= this._lastStreamId !== "$" && this._lastStreamId !== "0-0";
4803
5416
  const sub = this.streamClient ?? this.createDedicatedRedisClient();
4804
5417
  this.streamClient = sub;
5418
+ if (typeof sub.xread !== "function") throw new Error("backplaneMode: stream requires a driver supporting XREAD");
4805
5419
  if (typeof sub.on === "function") {
4806
- sub.on("error", (e) => this.logger.debug("Backplane stream consumer error", { error: e.message }));
4807
- sub.on("close", () => {
5420
+ this._listenBackplane(sub, "error", (e) => this.logger.debug("Backplane stream consumer error", { error: e.message }));
5421
+ this._listenBackplane(sub, "close", () => {
5422
+ this._streamRecovering = true;
5423
+ this._backplaneAvailable = false;
4808
5424
  if (this._subDisconnectedAt === null) {
4809
5425
  this._subDisconnectedAt = Date.now();
4810
5426
  this.logger.debug("Backplane stream: consumer disconnected", { at: this._subDisconnectedAt });
4811
5427
  }
4812
5428
  });
4813
- sub.on("ready", () => {
5429
+ this._listenBackplane(sub, "ready", () => {
4814
5430
  if (this._subDisconnectedAt !== null) {
4815
5431
  this.logger.debug("Backplane stream: consumer reconnected, resuming stream read", { lastId: this._lastStreamId });
4816
5432
  this._subDisconnectedAt = null;
4817
5433
  }
4818
5434
  });
4819
5435
  }
5436
+ const checkGap = async () => {
5437
+ if (this._lastStreamId === "$" || this._lastStreamId === "0-0" || typeof sub.xrange !== "function") return;
5438
+ const first = await sub.xrange(this.backplaneStreamKey, "-", "+", "COUNT", 1);
5439
+ const firstId = first?.[0]?.[0];
5440
+ if (!firstId) return;
5441
+ const [firstMs, firstSequence] = firstId.split("-").map(BigInt);
5442
+ const [lastMs, lastSequence] = this._lastStreamId.split("-").map(BigInt);
5443
+ if (firstMs > lastMs || firstMs === lastMs && firstSequence > lastSequence) this._resetAfterStreamGap();
5444
+ };
5445
+ const apply = (response) => {
5446
+ if (this._destroyed || !response) return;
5447
+ if (this._streamRecovering && response.some(([, entries]) => entries.length > 0)) {
5448
+ this.counters.streamReplays++;
5449
+ this._streamRecovering = false;
5450
+ }
5451
+ for (const [, entries] of response) {
5452
+ for (const [id, fields] of entries) {
5453
+ this._lastStreamId = id;
5454
+ this.counters.streamEntriesReceived++;
5455
+ this._processStreamEntry(fields);
5456
+ }
5457
+ }
5458
+ };
5459
+ let initialized = false;
5460
+ const initialize = async () => {
5461
+ if (typeof sub.connect === "function" && (sub.isOpen === false || sub.status === "wait")) await sub.connect();
5462
+ if (this._destroyed) return;
5463
+ if (this._lastStreamId === "$") {
5464
+ if (this._restoredSnapshot) this._resetAfterStreamGap();
5465
+ else if (typeof sub.xrevrange === "function") {
5466
+ const latest = await sub.xrevrange(this.backplaneStreamKey, "+", "-", "COUNT", 1);
5467
+ this._lastStreamId = latest?.[0]?.[0] ?? "0-0";
5468
+ } else this._lastStreamId = "0-0";
5469
+ }
5470
+ if (typeof sub.xrange === "function") {
5471
+ await checkGap();
5472
+ apply(await sub.xread("STREAMS", this.backplaneStreamKey, this._lastStreamId));
5473
+ }
5474
+ initialized = true;
5475
+ this._backplaneAvailable = true;
5476
+ };
5477
+ try {
5478
+ await initialize();
5479
+ } catch (error) {
5480
+ this._backplaneAvailable = false;
5481
+ this.logger.warn("Backplane stream initialization failed; retrying in consumer loop", { error: error.message });
5482
+ }
4820
5483
  const runLoop = async () => {
4821
5484
  while (!this._destroyed && !this._redisDisabled) {
4822
5485
  try {
5486
+ if (!initialized) await initialize();
5487
+ if (this._destroyed) break;
5488
+ await checkGap();
4823
5489
  const res = await sub.xread(
4824
5490
  "BLOCK",
4825
5491
  this.opts.backplaneStreamBlockMs,
@@ -4828,19 +5494,10 @@ var CacheService = class _CacheService {
4828
5494
  this._lastStreamId
4829
5495
  );
4830
5496
  if (this._destroyed) break;
5497
+ this._backplaneAvailable = true;
4831
5498
  if (res && res.length > 0) {
4832
- for (const [, entries] of res) {
4833
- if (entries.length > 0) {
4834
- if (this._lastStreamId !== "$") {
4835
- this.counters.streamReplays++;
4836
- }
4837
- for (const [id, fields] of entries) {
4838
- this._lastStreamId = id;
4839
- this.counters.streamEntriesReceived++;
4840
- this._processStreamEntry(fields);
4841
- }
4842
- }
4843
- }
5499
+ apply(res);
5500
+ this._backplaneAvailable = true;
4844
5501
  } else {
4845
5502
  await new Promise((resolve) => setTimeout(resolve, 10));
4846
5503
  }
@@ -4848,10 +5505,9 @@ var CacheService = class _CacheService {
4848
5505
  if (this._destroyed) break;
4849
5506
  const msg = err.message ?? "";
4850
5507
  if (msg.includes("NOGROUP") || msg.includes("smaller than") || msg.includes("trimmed")) {
4851
- this.counters.streamGaps++;
4852
- this.l1.clear();
4853
- this._lastStreamId = "$";
5508
+ this._resetAfterStreamGap();
4854
5509
  }
5510
+ this._backplaneAvailable = false;
4855
5511
  await new Promise((resolve) => setTimeout(resolve, 200));
4856
5512
  }
4857
5513
  }
@@ -4879,8 +5535,8 @@ var CacheService = class _CacheService {
4879
5535
  else if (f === "src") src = v;
4880
5536
  else if (f === "tagVersion") tagVersionRaw = v;
4881
5537
  }
4882
- const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
4883
- if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
5538
+ const validOp = op === "del" || op === "del-glob" || op === "tag_incr" || op === "tag_pattern_incr" || op === "tag_pattern_del";
5539
+ if (!validOp || typeof key !== "string" || !key || typeof src !== "string" || !src || (op === "del" || op === "del-glob") && this._namespace && !key.startsWith(`${this._namespace}:`)) {
4884
5540
  this.logger.warn("Backplane: rejected invalid stream entry", {
4885
5541
  op: String(op).slice(0, 40),
4886
5542
  key: typeof key === "string" ? key.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(key)
@@ -4889,8 +5545,8 @@ var CacheService = class _CacheService {
4889
5545
  }
4890
5546
  let tagVersion;
4891
5547
  if (tagVersionRaw !== void 0) {
4892
- const parsed = parseInt(tagVersionRaw, 10);
4893
- if (!Number.isFinite(parsed)) {
5548
+ const parsed = Number(tagVersionRaw);
5549
+ if (!Number.isSafeInteger(parsed) || parsed < 0) {
4894
5550
  this.logger.warn("Backplane: rejected stream entry with non-numeric tagVersion", { key });
4895
5551
  return;
4896
5552
  }
@@ -4908,16 +5564,10 @@ var CacheService = class _CacheService {
4908
5564
  this.l1.delete(key);
4909
5565
  this._bumpKeyMutation(key);
4910
5566
  this.inflight.delete(key);
4911
- this._pendingDiskDeletes.add(key);
4912
- setImmediate(() => {
4913
- try {
4914
- if (!this._diskDisabled) this.disk.delete(key);
4915
- } finally {
4916
- this._pendingDiskDeletes.delete(key);
4917
- }
4918
- });
5567
+ this._invalidateDiskKey(key);
4919
5568
  this._cascadeDependencies(key);
4920
5569
  } else if (op === "del-glob") {
5570
+ this._fenceInvalidation();
4921
5571
  this.l1.deletePattern(key);
4922
5572
  const pfx = key.endsWith("*") ? key.slice(0, -1) : key;
4923
5573
  for (const liveKey of this.l1.liveKeys()) {
@@ -4931,12 +5581,22 @@ var CacheService = class _CacheService {
4931
5581
  this.inflight.delete(inflightKey);
4932
5582
  }
4933
5583
  }
4934
- this._addPatternTombstone(pfx);
5584
+ this._addPatternTombstone(key);
5585
+ this._removePatternFromIndices(key);
5586
+ if (key === this.nk("*")) {
5587
+ this.tagIndex.clear();
5588
+ this.keyTags.clear();
5589
+ this.tagVersions.clear();
5590
+ this.dependencyIndex.clear();
5591
+ this.keyDependencies.clear();
5592
+ }
4935
5593
  } else if (op === "tag_incr") {
5594
+ this._fenceInvalidation();
4936
5595
  const tag = key;
4937
5596
  const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
4938
5597
  this._setLocalTagVersion(tag, ver, performance.now());
4939
5598
  } else if (op === "tag_pattern_incr") {
5599
+ this._fenceInvalidation();
4940
5600
  const pattern = key;
4941
5601
  const now = performance.now();
4942
5602
  for (const [tag, info] of this.tagVersions) {
@@ -4956,6 +5616,7 @@ var CacheService = class _CacheService {
4956
5616
  }
4957
5617
  }, 0);
4958
5618
  } else if (op === "tag_pattern_del") {
5619
+ this._fenceInvalidation();
4959
5620
  const pattern = key;
4960
5621
  const matchedTagKeys = [];
4961
5622
  const prefix = this.nk("_tag_:");
@@ -4966,14 +5627,7 @@ var CacheService = class _CacheService {
4966
5627
  for (const k of members) {
4967
5628
  this.l1.delete(k);
4968
5629
  this._bumpKeyMutation(k);
4969
- this._pendingDiskDeletes.add(k);
4970
- setImmediate(() => {
4971
- try {
4972
- if (!this._diskDisabled) this.disk.delete(k);
4973
- } finally {
4974
- this._pendingDiskDeletes.delete(k);
4975
- }
4976
- });
5630
+ this._invalidateDiskKey(k);
4977
5631
  }
4978
5632
  }
4979
5633
  }
@@ -5004,6 +5658,7 @@ var CacheService = class _CacheService {
5004
5658
  }
5005
5659
  }
5006
5660
  async publishInvalidation(op, key, tagVersion, isCrossRegionRelay = false, isExplicitInvalidation = false) {
5661
+ if (this.opts.l2WriteMode === "read-only") return;
5007
5662
  if (!isCrossRegionRelay && this.opts.crossRegion) {
5008
5663
  const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
5009
5664
  if (shouldBroadcast) {
@@ -5086,13 +5741,13 @@ var CacheService = class _CacheService {
5086
5741
  timestamp: Date.now(),
5087
5742
  namespace: this._namespace || void 0
5088
5743
  };
5089
- this.counters.crossRegionSent++;
5090
5744
  await cr.relay.broadcast(event);
5745
+ this.counters.crossRegionSent++;
5091
5746
  this.logger.debug("Cross-region invalidation broadcast", { op, key, region: cr.currentRegion });
5092
5747
  } catch (err) {
5093
- this.counters.crossRegionSent = Math.max(0, this.counters.crossRegionSent - 1);
5094
5748
  this.counters.crossRegionErrors++;
5095
5749
  this.logger.warn("Cross-region invalidation broadcast failed", { error: err.message });
5750
+ if (this.opts.awaitInvalidationBackplane) throw err;
5096
5751
  }
5097
5752
  }
5098
5753
  /**
@@ -5103,11 +5758,12 @@ var CacheService = class _CacheService {
5103
5758
  * Returns true if the event was accepted and applied, or false if ignored/deduplicated.
5104
5759
  */
5105
5760
  async receiveCrossRegionInvalidation(event) {
5761
+ this._assertActive("receiveCrossRegionInvalidation");
5106
5762
  const cr = this.opts.crossRegion;
5107
5763
  if (!cr) return false;
5108
- if (!event || typeof event !== "object" || !event.id || !event.originRegion || !event.op || !event.key) {
5764
+ if (!isCrossRegionInvalidationEvent(event)) {
5109
5765
  this.counters.crossRegionErrors++;
5110
- this.logger.warn("Cross-region: rejected invalid event payload", { event });
5766
+ this.logger.warn("Cross-region: rejected invalid event payload");
5111
5767
  return false;
5112
5768
  }
5113
5769
  if (event.originRegion === cr.currentRegion) {
@@ -5118,46 +5774,329 @@ var CacheService = class _CacheService {
5118
5774
  this.counters.crossRegionDeduplicated++;
5119
5775
  return false;
5120
5776
  }
5121
- this._markCrossRegionEventSeen(event.id);
5122
5777
  if (event.namespace !== void 0 && event.namespace !== (this._namespace || void 0)) {
5123
5778
  return false;
5124
5779
  }
5780
+ if ((event.op === "del" || event.op === "del-glob") && this._namespace && !event.key.startsWith(`${this._namespace}:`)) return false;
5781
+ this._markCrossRegionEventSeen(event.id);
5125
5782
  this.counters.crossRegionReceived++;
5126
- this._applyInvalidationEvent(event.op, event.key, event.tagVersion);
5127
- void this.publishInvalidation(event.op, event.key, event.tagVersion, true);
5128
- this.logger.info("Cross-region invalidation applied", {
5129
- op: event.op,
5130
- key: event.key,
5131
- originRegion: event.originRegion
5132
- });
5133
- return true;
5134
- }
5135
- _setLocalTagVersion(tag, version, now = performance.now()) {
5783
+ const localTags = /* @__PURE__ */ new Set([...this.tagVersions.keys(), ...[...this.tagIndex.keys()].map((key) => this.unnk(key).replace(/^_tag_:/, ""))]);
5784
+ let version = event.tagVersion;
5785
+ if (event.op === "tag_incr") version = Math.max((this.tagVersions.get(event.key)?.version ?? 0) + 1, version ?? 0);
5786
+ this._applyInvalidationEvent(event.op, event.key, version);
5787
+ try {
5788
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
5789
+ const client = await this.getRedis();
5790
+ if (event.op === "del" || event.op === "del-glob") {
5791
+ await this._deleteRedisKeys(client, event.op === "del" ? [event.key] : await this._scanKeys(client, event.key));
5792
+ } else if (event.op === "tag_incr") {
5793
+ version = Number(await client.eval(LUA_RECEIVE_TAG_VERSION, 1, this.nk(`tag_ver:${event.key}`), String(version)));
5794
+ this._setLocalTagVersion(event.key, version);
5795
+ } else {
5796
+ const matched = await this._resolveMatchingTags(event.key, false);
5797
+ for (const tag of localTags) if (matchesTagPattern(event.key, tag)) matched.add(tag);
5798
+ for (const tag of matched) {
5799
+ if (event.op === "tag_pattern_incr") {
5800
+ const floor = this.tagVersions.get(tag)?.version ?? 1;
5801
+ const next = Number(await client.eval(LUA_RECEIVE_TAG_VERSION, 1, this.nk(`tag_ver:${tag}`), String(floor)));
5802
+ this._setLocalTagVersion(tag, next);
5803
+ await this.publishInvalidation("tag_incr", tag, next, true);
5804
+ } else {
5805
+ const tagKey = this.nk(`_tag_:${tag}`);
5806
+ const members = await client.smembers(tagKey);
5807
+ this._removeTagMembersLocal(members);
5808
+ await this._deleteRedisKeys(client, [...members, tagKey]);
5809
+ await Promise.all(members.map((key) => this.publishInvalidation("del", key, void 0, true)));
5810
+ }
5811
+ }
5812
+ }
5813
+ this.cb.onSuccess();
5814
+ }
5815
+ await this.publishInvalidation(event.op, event.key, version, true);
5816
+ } catch (error) {
5817
+ this._seenCrossRegionEvents.delete(event.id);
5818
+ this.counters.crossRegionErrors++;
5819
+ this.logger.warn("Cross-region regional invalidation failed", { error: error.message });
5820
+ if (this.opts.awaitInvalidationBackplane) throw error;
5821
+ return false;
5822
+ }
5823
+ this.logger.info("Cross-region invalidation applied", {
5824
+ op: event.op,
5825
+ key: event.key,
5826
+ originRegion: event.originRegion
5827
+ });
5828
+ return true;
5829
+ }
5830
+ _setLocalTagVersion(tag, version, now = performance.now()) {
5136
5831
  const existing = this.tagVersions.get(tag)?.version ?? 0;
5137
5832
  const finalVersion = Math.max(existing, version);
5138
5833
  if (this.tagVersions.size >= 1e4 && !this.tagVersions.has(tag)) {
5139
5834
  const oldestKey = this.tagVersions.keys().next().value;
5140
5835
  if (oldestKey !== void 0) this.tagVersions.delete(oldestKey);
5141
5836
  }
5142
- this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
5837
+ this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now, refreshEpoch: this._tagRefreshEpoch });
5838
+ }
5839
+ async _isGenerationalEntryStale(tagVersions) {
5840
+ if (!tagVersions) return false;
5841
+ const tags = Object.keys(tagVersions);
5842
+ if (tags.length === 0) return false;
5843
+ const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5844
+ for (let i = 0; i < tags.length; i++) {
5845
+ if (currentVers[i] > tagVersions[tags[i]]) return true;
5846
+ }
5847
+ return false;
5848
+ }
5849
+ async _deleteRedisKeys(client, keys) {
5850
+ if (keys.length === 0) return;
5851
+ const CHUNK_SIZE = 1e3;
5852
+ if (client instanceof import_ioredis2.Cluster) {
5853
+ const groups = /* @__PURE__ */ new Map();
5854
+ for (const key of keys) {
5855
+ const slot = redisHashSlot(key);
5856
+ const master = client.slots?.[slot]?.[0] ?? String(slot);
5857
+ const members = groups.get(master) ?? [];
5858
+ members.push(key);
5859
+ groups.set(master, members);
5860
+ }
5861
+ await Promise.all([...groups.values()].map(async (members) => {
5862
+ for (let offset = 0; offset < members.length; offset += CHUNK_SIZE) {
5863
+ const pipeline = client.pipeline();
5864
+ for (const key of members.slice(offset, offset + CHUNK_SIZE)) pipeline.del(key);
5865
+ const result = await pipeline.exec();
5866
+ if (!result || result.some(([error]) => error)) throw new Error("Redis Cluster delete failed");
5867
+ }
5868
+ }));
5869
+ return;
5870
+ }
5871
+ for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
5872
+ const chunk = keys.slice(i, i + CHUNK_SIZE);
5873
+ await client.del(...chunk);
5874
+ }
5875
+ }
5876
+ async _parseGenerationalRedisHash(k, hashData) {
5877
+ if (!hashData || !hashData.d) return null;
5878
+ let storedTagVersions = {};
5879
+ if (hashData.tv) {
5880
+ try {
5881
+ const parsed = JSON.parse(hashData.tv);
5882
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || Object.values(parsed).some((version) => !Number.isSafeInteger(version) || Number(version) < 0)) return null;
5883
+ storedTagVersions = parsed;
5884
+ } catch {
5885
+ return null;
5886
+ }
5887
+ }
5888
+ if (await this._isGenerationalEntryStale(storedTagVersions)) {
5889
+ const setAtMs = parseInt(hashData.t, 10) || 0;
5890
+ this._deleteIfStale(k, setAtMs);
5891
+ return { stale: true };
5892
+ }
5893
+ const value = await this._decryptAndDeserialize(hashData.d);
5894
+ const expiresAt = Number(hashData.e);
5895
+ const staleAt = Number(hashData.s);
5896
+ let tags;
5897
+ let dependsOn;
5898
+ try {
5899
+ const parsedTags = hashData.tags ? JSON.parse(hashData.tags) : Object.keys(storedTagVersions);
5900
+ const parsedDependencies = hashData.deps ? JSON.parse(hashData.deps) : void 0;
5901
+ if (Array.isArray(parsedTags) && parsedTags.every((tag) => typeof tag === "string")) tags = parsedTags;
5902
+ if (Array.isArray(parsedDependencies) && parsedDependencies.every((pattern) => typeof pattern === "string")) dependsOn = parsedDependencies;
5903
+ } catch {
5904
+ return null;
5905
+ }
5906
+ return {
5907
+ value,
5908
+ tagVersions: storedTagVersions,
5909
+ stale: false,
5910
+ tags,
5911
+ dependsOn,
5912
+ setAt: Number(hashData.t) || void 0,
5913
+ expiresAt: Number.isFinite(expiresAt) && expiresAt > 0 ? expiresAt : void 0,
5914
+ staleAt: Number.isFinite(staleAt) && staleAt > 0 ? staleAt : void 0
5915
+ };
5916
+ }
5917
+ async _readRedisEntry(client, k, allowAutoPipeline = false) {
5918
+ const readStartedAt = Date.now();
5919
+ const read = async (hash) => allowAutoPipeline && this.opts.autoPipeline && this.pipeliner ? this.pipeliner.read(k, hash) : readRedisValue(client, k, hash);
5920
+ const withExpiry = (entry, ttlMs2) => {
5921
+ if (!entry || ttlMs2 === -2 || ttlMs2 === 0) return null;
5922
+ if (ttlMs2 !== void 0 && Number.isFinite(ttlMs2) && ttlMs2 > 0) {
5923
+ entry.expiresAt = Math.min(entry.expiresAt ?? Infinity, readStartedAt + ttlMs2);
5924
+ }
5925
+ return entry.expiresAt !== void 0 && entry.expiresAt <= Date.now() ? null : entry;
5926
+ };
5927
+ if (this.opts.tagStrategy === "generational" && typeof client.hgetall === "function") {
5928
+ try {
5929
+ const { raw: hashData, ttlMs: ttlMs2 } = await read(true);
5930
+ if (typeof hashData === "string") {
5931
+ const value2 = await this._decryptAndDeserialize(hashData);
5932
+ return withExpiry({ value: value2, stale: false }, ttlMs2);
5933
+ }
5934
+ if (hashData && hashData.d) {
5935
+ return withExpiry(await this._parseGenerationalRedisHash(k, hashData), ttlMs2);
5936
+ }
5937
+ return null;
5938
+ } catch (err) {
5939
+ const msg = err instanceof Error ? err.message : String(err);
5940
+ if (!msg.includes("WRONGTYPE")) throw err;
5941
+ }
5942
+ }
5943
+ const { raw, ttlMs } = await read(false);
5944
+ if (raw == null) return null;
5945
+ if (typeof raw !== "string") return null;
5946
+ const value = await this._decryptAndDeserialize(raw);
5947
+ return withExpiry({ value, stale: false }, ttlMs);
5143
5948
  }
5144
5949
  async _getTagVersion(tag) {
5145
5950
  const now = performance.now();
5146
5951
  const local = this.tagVersions.get(tag);
5147
- if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
5952
+ if (local && (local.refreshEpoch ?? 0) === this._tagRefreshEpoch && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
5148
5953
  return local.version;
5149
5954
  }
5150
5955
  if (!this._redisDisabled) {
5151
5956
  try {
5152
5957
  const client = await this.getRedis();
5153
5958
  const raw = await client.get(this.nk(`tag_ver:${tag}`));
5154
- const version = raw ? parseInt(raw, 10) : 0;
5155
- this._setLocalTagVersion(tag, version, now);
5156
- return version;
5959
+ const parsed = raw ? Number(raw) : 0;
5960
+ if (!Number.isSafeInteger(parsed) || parsed < 0) throw new Error("Invalid Redis tag generation");
5961
+ const version2 = Math.max(this.tagVersions.get(tag)?.version ?? 0, parsed);
5962
+ if (this.opts.l2WriteMode === "read-write") {
5963
+ if (raw === null) await client.set(this.nk(`tag_ver:${tag}`), String(version2), "NX");
5964
+ else if (version2 > parsed) await client.eval(LUA_MAX_TAG_VERSION, 1, this.nk(`tag_ver:${tag}`), String(version2));
5965
+ }
5966
+ this._setLocalTagVersion(tag, version2, now);
5967
+ this.cb.onSuccess();
5968
+ return version2;
5157
5969
  } catch {
5158
5970
  }
5159
5971
  }
5160
- return local?.version ?? 0;
5972
+ const version = this.tagVersions.get(tag)?.version ?? local?.version ?? 0;
5973
+ if (this._redisDisabled) this._setLocalTagVersion(tag, version, now);
5974
+ return version;
5975
+ }
5976
+ async _readRedisBatch(client, keys) {
5977
+ const entries = /* @__PURE__ */ new Map();
5978
+ const groups = /* @__PURE__ */ new Map();
5979
+ for (const key of new Set(keys)) {
5980
+ const group = client instanceof import_ioredis2.Cluster ? client.slots[redisHashSlot(key)]?.[0] ?? String(redisHashSlot(key)) : "single";
5981
+ const members = groups.get(group) ?? [];
5982
+ members.push(key);
5983
+ groups.set(group, members);
5984
+ }
5985
+ await Promise.all([...groups.values()].map(async (members) => {
5986
+ for (let offset = 0; offset < members.length; offset += 1e3) {
5987
+ const chunk = members.slice(offset, offset + 1e3);
5988
+ const pipeline = typeof client.pipeline === "function" ? client.pipeline() : client.multi();
5989
+ const timedScripts = typeof pipeline.eval === "function";
5990
+ const hashes = this.opts.tagStrategy === "generational" && typeof pipeline.hgetall === "function";
5991
+ for (const key of chunk) {
5992
+ if (timedScripts) pipeline.eval(LUA_READ_CACHE_ENTRY, 1, key);
5993
+ else if (hashes) pipeline.hgetall(key);
5994
+ else pipeline.get(key);
5995
+ }
5996
+ const startedAt = Date.now();
5997
+ const start = performance.now();
5998
+ const results = await pipeline.exec();
5999
+ this.watchdog.recordRedis(performance.now() - start);
6000
+ if (!results) throw new Error("Redis batch read aborted");
6001
+ for (let index = 0; index < chunk.length; index++) {
6002
+ try {
6003
+ const tuple = results[index];
6004
+ if (!tuple) continue;
6005
+ let [error, raw] = tuple;
6006
+ let ttl;
6007
+ if (error?.message?.includes("WRONGTYPE")) {
6008
+ const fallback = await this._readRedisEntry(client, chunk[index]);
6009
+ if (fallback && !fallback.stale) entries.set(chunk[index], fallback);
6010
+ continue;
6011
+ }
6012
+ if (error) continue;
6013
+ if (timedScripts) {
6014
+ if (!Array.isArray(raw) || raw[0] === "none") continue;
6015
+ const kind = raw[0];
6016
+ ttl = Number(raw[2]);
6017
+ const payload = raw[1];
6018
+ if (kind === "hash") {
6019
+ if (!Array.isArray(payload) || payload.length % 2 !== 0) continue;
6020
+ raw = Object.fromEntries(Array.from({ length: payload.length / 2 }, (_unused, i) => [String(payload[i * 2]), String(payload[i * 2 + 1])]));
6021
+ } else if (kind === "string") raw = payload;
6022
+ else continue;
6023
+ if (ttl === -2 || ttl === 0) continue;
6024
+ }
6025
+ 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;
6026
+ if (!entry || entry.stale) continue;
6027
+ if (ttl !== void 0 && ttl > 0) entry.expiresAt = Math.min(entry.expiresAt ?? Infinity, startedAt + ttl);
6028
+ if (entry.expiresAt !== void 0 && entry.expiresAt <= Date.now()) continue;
6029
+ entries.set(chunk[index], entry);
6030
+ } catch (error) {
6031
+ this.logger.debug("mget: skipping invalid remote entry", { key: chunk[index], error: error.message });
6032
+ }
6033
+ }
6034
+ }
6035
+ }));
6036
+ this.cb.onSuccess();
6037
+ return entries;
6038
+ }
6039
+ _promoteRedisEntry(key, entry, fallbackTtlMs, priority) {
6040
+ const expiresAt = entry.expiresAt ?? Date.now() + fallbackTtlMs;
6041
+ if (expiresAt <= Date.now()) return false;
6042
+ const admitted = this.l1.set(
6043
+ key,
6044
+ entry.value,
6045
+ expiresAt - Date.now(),
6046
+ priority,
6047
+ entry.staleAt,
6048
+ void 0,
6049
+ entry.tagVersions,
6050
+ entry.setAt,
6051
+ entry.tags,
6052
+ entry.dependsOn
6053
+ );
6054
+ if (admitted) this._restoreEntryMetadata(key, { ...entry, expiresAt });
6055
+ return true;
6056
+ }
6057
+ async _readDiskEntry(key, epoch) {
6058
+ if (this._diskDisabled || this._pendingDiskDeletes.has(key) || !this.watchdog.isDiskAllowed()) return null;
6059
+ const start = performance.now();
6060
+ const entry = this.disk.load(key);
6061
+ const elapsed = performance.now() - start;
6062
+ this.watchdog.recordDisk(elapsed);
6063
+ this.watchdog.onCanaryResult(entry !== null, elapsed);
6064
+ 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;
6065
+ this.l1.importEntries([{ key, entry }], this.opts.forbiddenSnapshotPrefixes);
6066
+ const hit = this.l1.get(key);
6067
+ const value = hit ? hit.value : entry.isCompressed ? this.codec.decode(entry.data) : JSON.parse(entry.data);
6068
+ this._restoreEntryMetadata(key, entry);
6069
+ return { value, entry };
6070
+ }
6071
+ /** Common write policy and metadata across get/set/revalidation/draining. */
6072
+ async _writeRedisEntry(key, data, expiresAt, setAt, tagVersions, staleAt, tags, dependsOn, canCommit = () => true) {
6073
+ if (this._redisDisabled || this.opts.l2WriteMode !== "read-write" || !canCommit() || this._destroyed) return;
6074
+ const client = await this.getRedis();
6075
+ const stored = await this._serializeAndEncrypt(JSON.stringify(data) ?? "undefined");
6076
+ if (!canCommit() || this._destroyed) return;
6077
+ const useHash = this.opts.tagStrategy === "generational" && (tagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function");
6078
+ const remaining = (useHash ? expiresAt : staleAt ?? expiresAt) - Date.now();
6079
+ if (remaining <= 0) return;
6080
+ const ttl = Math.max(1, Math.ceil(remaining / 1e3));
6081
+ if (useHash) {
6082
+ const transaction = client.multi();
6083
+ transaction.del(key);
6084
+ const hash = { d: stored, t: String(setAt), tv: JSON.stringify(tagVersions ?? {}), e: String(expiresAt) };
6085
+ if (staleAt !== void 0) hash.s = String(staleAt);
6086
+ if (tags?.length) hash.tags = JSON.stringify(tags);
6087
+ if (dependsOn?.length) hash.deps = JSON.stringify(dependsOn);
6088
+ transaction.hset(key, hash);
6089
+ transaction.expire(key, ttl);
6090
+ const result = await transaction.exec();
6091
+ if (!result || result.some(([error]) => error)) throw new Error("Redis cache write transaction failed");
6092
+ } else if (this.opts.autoPipeline && this.pipeliner) {
6093
+ if (typeof client.pttl === "function" && typeof client.set === "function") await this.pipeliner.setpx(key, Math.ceil(remaining), stored);
6094
+ else await this.pipeliner.setex(key, ttl, stored);
6095
+ } else {
6096
+ if (typeof client.pttl === "function" && typeof client.set === "function") await client.set(key, stored, "PX", Math.ceil(remaining));
6097
+ else await client.setex(key, ttl, stored);
6098
+ }
6099
+ this.cb.onSuccess();
5161
6100
  }
5162
6101
  _deleteIfStale(k, setAtMs) {
5163
6102
  this.l1.deleteIfSetBefore(k, setAtMs);
@@ -5210,7 +6149,7 @@ var CacheService = class _CacheService {
5210
6149
  } else {
5211
6150
  plain = raw;
5212
6151
  }
5213
- return JSON.parse(plain);
6152
+ return plain === "undefined" ? void 0 : JSON.parse(plain);
5214
6153
  }
5215
6154
  /**
5216
6155
  * Scan all keys matching `pattern` across single-node or Cluster clients.
@@ -5218,7 +6157,7 @@ var CacheService = class _CacheService {
5218
6157
  */
5219
6158
  async _scanKeys(client, pattern) {
5220
6159
  const keys = [];
5221
- if (client instanceof import_ioredis.Cluster) {
6160
+ if (client instanceof import_ioredis2.Cluster) {
5222
6161
  const masters = client.nodes("master");
5223
6162
  await Promise.all(masters.map(
5224
6163
  (node) => new Promise((resolve, reject) => {
@@ -5278,10 +6217,10 @@ var CacheService = class _CacheService {
5278
6217
  return client;
5279
6218
  }
5280
6219
  this.redisConnecting = (async () => {
6220
+ let client = null;
5281
6221
  try {
5282
- let client;
5283
6222
  if (this.opts.redisClusterNodes?.length) {
5284
- client = new import_ioredis.Cluster(this.opts.redisClusterNodes, {
6223
+ client = new import_ioredis2.Cluster(this.opts.redisClusterNodes, {
5285
6224
  redisOptions: {
5286
6225
  tls: this.opts.redisTls ? {} : void 0,
5287
6226
  connectTimeout: 1e4,
@@ -5301,7 +6240,7 @@ var CacheService = class _CacheService {
5301
6240
  });
5302
6241
  client.on("reconnecting", () => this.logger.debug("Redis Cluster reconnecting"));
5303
6242
  } else if (this.opts.redisSentinel) {
5304
- client = new import_ioredis.Redis({
6243
+ client = new import_ioredis2.Redis({
5305
6244
  sentinels: this.opts.redisSentinel.sentinels,
5306
6245
  name: this.opts.redisSentinel.name,
5307
6246
  tls: this.opts.redisTls ? {} : void 0,
@@ -5321,7 +6260,7 @@ var CacheService = class _CacheService {
5321
6260
  });
5322
6261
  client.on("reconnecting", () => this.logger.debug("Redis Sentinel reconnecting"));
5323
6262
  } else {
5324
- client = new import_ioredis.Redis({
6263
+ client = new import_ioredis2.Redis({
5325
6264
  host: this.opts.redisHost,
5326
6265
  port: this.opts.redisPort,
5327
6266
  tls: this.opts.redisTls ? {} : void 0,
@@ -5342,14 +6281,45 @@ var CacheService = class _CacheService {
5342
6281
  });
5343
6282
  client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
5344
6283
  }
6284
+ const pendingClient = client;
5345
6285
  await new Promise((resolve, reject) => {
5346
- client.once("ready", resolve);
5347
- client.once("error", (e) => {
6286
+ let settled = false;
6287
+ const cleanupListeners = () => {
6288
+ pendingClient.removeListener?.("ready", onReady);
6289
+ pendingClient.removeListener?.("error", onError);
6290
+ };
6291
+ const onReady = () => {
6292
+ if (settled) return;
6293
+ settled = true;
6294
+ clearTimeout(timer);
6295
+ cleanupListeners();
6296
+ resolve();
6297
+ };
6298
+ const onError = (e) => {
6299
+ if (settled) return;
6300
+ settled = true;
6301
+ clearTimeout(timer);
6302
+ cleanupListeners();
5348
6303
  this._checkAndLogResp3Hint(e);
5349
6304
  reject(e);
5350
- });
5351
- setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
6305
+ };
6306
+ const timer = setTimeout(() => {
6307
+ if (settled) return;
6308
+ settled = true;
6309
+ cleanupListeners();
6310
+ reject(new Error("Redis connection timeout"));
6311
+ }, 15e3);
6312
+ if (timer.unref) timer.unref();
6313
+ pendingClient.once("ready", onReady);
6314
+ pendingClient.once("error", onError);
5352
6315
  });
6316
+ if (this._destroyed) {
6317
+ try {
6318
+ client.disconnect();
6319
+ } catch {
6320
+ }
6321
+ this._assertActive("getRedis");
6322
+ }
5353
6323
  this.cb.onSuccess();
5354
6324
  this.redis = client;
5355
6325
  this.pipeliner = new AutoPipeliner(client, {
@@ -5359,6 +6329,10 @@ var CacheService = class _CacheService {
5359
6329
  this.redisConnecting = null;
5360
6330
  return client;
5361
6331
  } catch (err) {
6332
+ try {
6333
+ client?.disconnect();
6334
+ } catch {
6335
+ }
5362
6336
  this.cb.onFailure();
5363
6337
  this.redisConnecting = null;
5364
6338
  this._checkAndLogResp3Hint(err);
@@ -5378,7 +6352,12 @@ var CacheService = class _CacheService {
5378
6352
  try {
5379
6353
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
5380
6354
  if (entries.length === 0) return;
5381
- const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
6355
+ const payload = {
6356
+ version: SNAPSHOT_VERSION,
6357
+ writtenAt: Date.now(),
6358
+ entries,
6359
+ streamId: this.opts.backplaneMode === "stream" && this._lastStreamId !== "$" ? this._lastStreamId : void 0
6360
+ };
5382
6361
  const packed = this.codec.encode(payload);
5383
6362
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
5384
6363
  const dest = altPath ?? this.opts.snapshotPath;
@@ -5446,6 +6425,9 @@ var CacheService = class _CacheService {
5446
6425
  return;
5447
6426
  }
5448
6427
  const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
6428
+ this._restoredSnapshot ||= loaded > 0;
6429
+ if (typeof snapshot.streamId === "string" && /^\d{1,20}-\d{1,20}$/.test(snapshot.streamId)) this._lastStreamId = snapshot.streamId;
6430
+ for (const { key, entry } of snapshot.entries) if (this.l1.has(key)) this._restoreEntryMetadata(key, entry);
5449
6431
  this.logger.info("Cache snapshot loaded (L1 is warm)", {
5450
6432
  loaded,
5451
6433
  total: snapshot.entries.length,
@@ -5470,7 +6452,12 @@ var CacheService = class _CacheService {
5470
6452
  try {
5471
6453
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
5472
6454
  if (entries.length === 0) return false;
5473
- const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
6455
+ const payload = {
6456
+ version: SNAPSHOT_VERSION,
6457
+ writtenAt: Date.now(),
6458
+ entries,
6459
+ streamId: this.opts.backplaneMode === "stream" && this._lastStreamId !== "$" ? this._lastStreamId : void 0
6460
+ };
5474
6461
  const packed = this.codec.encode(payload);
5475
6462
  let final;
5476
6463
  if (this.opts.remoteSnapshot.envelope) {
@@ -5501,13 +6488,16 @@ var CacheService = class _CacheService {
5501
6488
  async loadRemoteSnapshot() {
5502
6489
  if (!this.opts.remoteSnapshot) return 0;
5503
6490
  const maxAgeMs = this.opts.remoteSnapshot.maxAgeMs ?? this.opts.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE;
6491
+ const epoch = this._globalEpoch;
5504
6492
  try {
5505
6493
  const raw = await this.opts.remoteSnapshot.adapter.get();
6494
+ if (this._destroyed || this._globalEpoch !== epoch) return 0;
5506
6495
  if (!raw || raw.length === 0) {
5507
6496
  this.logger.debug("Remote snapshot not found or empty \u2014 starting cold");
5508
6497
  return 0;
5509
6498
  }
5510
6499
  const rawBuf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
6500
+ if (rawBuf.length > SNAPSHOT_MAX_FILE_BYTES) throw new Error("Remote snapshot exceeds size limit");
5511
6501
  let buf;
5512
6502
  try {
5513
6503
  if (EnvelopeEncryption.isEnvelope(rawBuf)) {
@@ -5553,7 +6543,12 @@ var CacheService = class _CacheService {
5553
6543
  this.logger.warn("Remote snapshot rejected: entries is not an array");
5554
6544
  return 0;
5555
6545
  }
5556
- const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
6546
+ if (this._destroyed || this._globalEpoch !== epoch) return 0;
6547
+ const eligible = snapshot.entries.filter((item) => item && !this._keyMutationEpochs.has(item.key));
6548
+ const loaded = this.l1.importEntries(eligible, this.opts.forbiddenSnapshotPrefixes);
6549
+ this._restoredSnapshot ||= loaded > 0;
6550
+ if (typeof snapshot.streamId === "string" && /^\d{1,20}-\d{1,20}$/.test(snapshot.streamId)) this._lastStreamId = snapshot.streamId;
6551
+ for (const { key, entry } of eligible) if (this.l1.has(key)) this._restoreEntryMetadata(key, entry);
5557
6552
  this.counters.remoteSnapshotDownloads++;
5558
6553
  this.counters.remoteSnapshotLastDownloadedAt = Date.now();
5559
6554
  this.logger.info("Remote cache snapshot loaded (L1 hydrated)", {
@@ -5602,20 +6597,10 @@ var CacheService = class _CacheService {
5602
6597
  const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
5603
6598
  const l1Hit = this.l1.get(k);
5604
6599
  if (l1Hit !== null) {
5605
- let isGenerationalStale = false;
5606
- if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
5607
- const tags = Object.keys(l1Hit.tagVersions);
5608
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5609
- for (let i = 0; i < tags.length; i++) {
5610
- if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
5611
- isGenerationalStale = true;
5612
- break;
5613
- }
5614
- }
5615
- }
6600
+ const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
5616
6601
  if (isGenerationalStale) {
5617
6602
  this._deleteIfStale(k, l1Hit.setAt ?? 0);
5618
- } else {
6603
+ } else if (!l1Hit.isStale || optSwr > 0) {
5619
6604
  if (l1Hit.isStale) {
5620
6605
  const swrGraceMs2 = optSwr * 1e3;
5621
6606
  if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
@@ -5678,115 +6663,58 @@ var CacheService = class _CacheService {
5678
6663
  this.counters.stampedes++;
5679
6664
  this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch/read", { cacheKey });
5680
6665
  span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
5681
- return existing;
6666
+ return this._prepareReadValue(await existing);
5682
6667
  }
5683
6668
  const mutationEpochAtStart = this._getKeyMutationEpoch(k);
5684
- const executionPromise = (async () => {
6669
+ const executionPromise = Promise.resolve().then(async () => {
5685
6670
  try {
5686
- if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
5687
- if (this._isTombstonedByPattern(k)) {
5688
- try {
5689
- this.disk.delete(k);
5690
- } catch {
5691
- }
5692
- } else {
5693
- const isDiskAllowed = this.watchdog.isDiskAllowed();
5694
- if (isDiskAllowed) {
5695
- const diskStart = performance.now();
5696
- const diskHit = this.disk.load(k);
5697
- const diskElapsed = performance.now() - diskStart;
5698
- this.watchdog.recordDisk(diskElapsed);
5699
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
5700
- if (diskHit !== null) {
5701
- let isDiskStale = false;
5702
- if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
5703
- const tags = Object.keys(diskHit.tagVersions);
5704
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5705
- for (let i = 0; i < tags.length; i++) {
5706
- if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
5707
- isDiskStale = true;
5708
- break;
5709
- }
5710
- }
5711
- }
5712
- if (isDiskStale) {
5713
- this.disk.delete(k);
5714
- } else {
5715
- const promoted = this.l1.importEntries(
5716
- [{ key: k, entry: diskHit }],
5717
- this.opts.forbiddenSnapshotPrefixes
5718
- );
5719
- if (promoted > 0) {
5720
- const l1Check = this.l1.get(k);
5721
- if (l1Check !== null) {
5722
- this.counters.diskHits++;
5723
- this.opts.onHit?.(cacheKey, "disk");
5724
- this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
5725
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
5726
- if (this.opts.frozen) deepFreeze(l1Check.value);
5727
- return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
5728
- }
5729
- }
5730
- }
5731
- }
5732
- }
6671
+ const diskHit = await this._readDiskEntry(k, mutationEpochAtStart);
6672
+ if (diskHit && (diskHit.entry.staleAt === void 0 || diskHit.entry.staleAt > Date.now() || optSwr > 0)) {
6673
+ this.counters.diskHits++;
6674
+ this.opts.onHit?.(cacheKey, "disk");
6675
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
6676
+ if (diskHit.entry.staleAt !== void 0 && diskHit.entry.staleAt <= Date.now() && optSwr > 0 && !this.revalidating.has(k)) {
6677
+ this.revalidating.add(k);
6678
+ this.counters.swrRevalidations++;
6679
+ void this._revalidate(
6680
+ k,
6681
+ fetchFn,
6682
+ ttlMs,
6683
+ swrGraceMs,
6684
+ priority,
6685
+ diskHit.entry.tagVersions ?? Object.fromEntries((diskHit.entry.tags ?? []).map((tag) => [tag, 0]))
6686
+ );
5733
6687
  }
6688
+ return diskHit.value;
5734
6689
  }
5735
6690
  if (!this._redisDisabled) {
5736
6691
  try {
5737
6692
  const client = await this.getRedis();
5738
6693
  const redisStart = performance.now();
5739
- if (this.opts.tagStrategy === "generational") {
5740
- const hashData = await client.hgetall(k);
5741
- const redisElapsed = performance.now() - redisStart;
5742
- this.watchdog.recordRedis(redisElapsed);
5743
- this.cb.onSuccess();
5744
- if (hashData && hashData.d) {
5745
- let isStale = false;
5746
- let storedTagVersions = {};
5747
- if (hashData.tv) {
5748
- try {
5749
- storedTagVersions = JSON.parse(hashData.tv);
5750
- } catch {
5751
- }
5752
- }
5753
- const tags = Object.keys(storedTagVersions);
5754
- const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5755
- for (let i = 0; i < tags.length; i++) {
5756
- if (currentVers[i] > storedTagVersions[tags[i]]) {
5757
- isStale = true;
5758
- break;
5759
- }
5760
- }
5761
- if (isStale) {
5762
- const setAtMs = parseInt(hashData.t, 10) || 0;
5763
- this._deleteIfStale(k, setAtMs);
5764
- } else {
5765
- const parsed = await this._decryptAndDeserialize(hashData.d);
5766
- this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
5767
- this.counters.l2Hits++;
5768
- this.opts.onHit?.(cacheKey, "l2");
5769
- this.logger.debug("L2 hit (Redis hash)", { cacheKey });
5770
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5771
- if (this.opts.frozen) deepFreeze(parsed);
5772
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
5773
- }
6694
+ const redisHit = await this._readRedisEntry(client, k, true);
6695
+ const redisElapsed = performance.now() - redisStart;
6696
+ this.watchdog.recordRedis(redisElapsed);
6697
+ this.cb.onSuccess();
6698
+ if (redisHit && !redisHit.stale && (redisHit.staleAt === void 0 || redisHit.staleAt > Date.now() || optSwr > 0)) {
6699
+ const parsed = redisHit.value;
6700
+ if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
6701
+ this.logger.debug("Aborting L2 promotion \u2014 key was mutated or deleted during Redis read", { cacheKey });
6702
+ span.setAttribute("cache.aborted_mutation_race", true);
6703
+ const current = this.l1.get(k);
6704
+ const liveVal = current && !current.isStale ? current.value : parsed;
6705
+ return liveVal;
5774
6706
  }
5775
- } else {
5776
- const raw = this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
5777
- const redisElapsed = performance.now() - redisStart;
5778
- this.watchdog.recordRedis(redisElapsed);
5779
- this.cb.onSuccess();
5780
- if (raw) {
5781
- const parsed = await this._decryptAndDeserialize(raw);
5782
- this.l1.set(k, parsed, ttlMs, priority);
5783
- this.counters.l2Hits++;
5784
- this.opts.onHit?.(cacheKey, "l2");
5785
- this.logger.debug("L2 hit (Redis)", { cacheKey });
5786
- span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5787
- if (this.opts.frozen) deepFreeze(parsed);
5788
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
6707
+ if (!this._promoteRedisEntry(k, redisHit, ttlMs, priority)) throw new Error("Redis entry expired during promotion");
6708
+ this.counters.l2Hits++;
6709
+ this.opts.onHit?.(cacheKey, "l2");
6710
+ this.logger.debug(redisHit.tagVersions ? "L2 hit (Redis hash)" : "L2 hit (Redis)", { cacheKey });
6711
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
6712
+ if (redisHit.staleAt !== void 0 && redisHit.staleAt <= Date.now() && optSwr > 0 && !this.revalidating.has(k)) {
6713
+ this.revalidating.add(k);
6714
+ this.counters.swrRevalidations++;
6715
+ void this._revalidate(k, fetchFn, ttlMs, swrGraceMs, priority, redisHit.tagVersions);
5789
6716
  }
6717
+ return parsed;
5790
6718
  }
5791
6719
  } catch (err) {
5792
6720
  this.cb.onFailure();
@@ -5796,6 +6724,7 @@ var CacheService = class _CacheService {
5796
6724
  span.setAttribute("cache.hit", false).setAttribute("cache.hit_tier", "miss");
5797
6725
  this.opts.onMiss?.(cacheKey);
5798
6726
  this.counters.fetches++;
6727
+ const tagSnapshot = this.opts.tagStrategy === "generational" && optTags?.length ? Object.fromEntries(await Promise.all(optTags.map(async (tag) => [tag, await this._getTagVersion(tag)]))) : void 0;
5799
6728
  const fetchStart = Date.now();
5800
6729
  let data;
5801
6730
  try {
@@ -5824,50 +6753,41 @@ var CacheService = class _CacheService {
5824
6753
  }
5825
6754
  const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
5826
6755
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
5827
- let activeTagVersions;
6756
+ const activeTagVersions = tagSnapshot;
5828
6757
  if (optTags?.length) {
5829
6758
  if (this.opts.tagStrategy === "generational") {
5830
- const vers = await Promise.all(optTags.map((tag) => this._getTagVersion(tag)));
5831
- activeTagVersions = {};
5832
- for (let i = 0; i < optTags.length; i++) {
5833
- activeTagVersions[optTags[i]] = vers[i];
5834
- }
6759
+ if (await this._isGenerationalEntryStale(tagSnapshot)) return data;
5835
6760
  } else {
5836
- await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
6761
+ await this._registerTags(k, optTags, Math.ceil(storeTtl / 1e3));
5837
6762
  }
5838
6763
  }
5839
6764
  if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
5840
6765
  this.logger.debug("Aborting in-flight cache commit \u2014 key was mutated or deleted during fetch", { cacheKey });
5841
6766
  span.setAttribute("cache.aborted_mutation_race", true);
5842
6767
  const current = this.l1.get(k);
5843
- if (current && !current.isStale && current.value !== void 0) {
6768
+ if (current && !current.isStale) {
5844
6769
  const freshVal = current.value;
5845
- if (this.opts.frozen) deepFreeze(freshVal);
5846
- return this.opts.cloneStrategy === "structuredClone" && freshVal != null && typeof freshVal === "object" ? structuredClone(freshVal) : freshVal;
6770
+ return freshVal;
5847
6771
  }
5848
- if (this.opts.frozen) deepFreeze(data);
5849
- return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
6772
+ return data;
5850
6773
  }
5851
- this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
5852
- if (!this._redisDisabled) {
6774
+ const writeTs = Date.now();
6775
+ this._invalidateDiskKey(k);
6776
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs, optTags, opts.dependsOn);
6777
+ this._restoreEntryMetadata(k, { tags: optTags, dependsOn: opts.dependsOn, expiresAt: writeTs + storeTtl });
6778
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
5853
6779
  try {
5854
- const client = await this.getRedis();
5855
- const serialized = JSON.stringify(data);
5856
- const toStore = await this._serializeAndEncrypt(serialized);
5857
- const ttlSec = Math.ceil(effectiveTtl / 1e3);
5858
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
5859
- const now = Date.now();
5860
- const tx = client.multi();
5861
- tx.hset(k, {
5862
- d: toStore,
5863
- t: String(now),
5864
- tv: JSON.stringify(activeTagVersions)
5865
- });
5866
- tx.expire(k, ttlSec);
5867
- await tx.exec();
5868
- } else {
5869
- await client.setex(k, ttlSec, toStore);
5870
- }
6780
+ await this._writeRedisEntry(
6781
+ k,
6782
+ data,
6783
+ writeTs + storeTtl,
6784
+ writeTs,
6785
+ activeTagVersions,
6786
+ staleAt,
6787
+ optTags,
6788
+ opts.dependsOn,
6789
+ () => this._getKeyMutationEpoch(k) === mutationEpochAtStart
6790
+ );
5871
6791
  this.cb.onSuccess();
5872
6792
  this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
5873
6793
  } catch {
@@ -5877,15 +6797,14 @@ var CacheService = class _CacheService {
5877
6797
  } else {
5878
6798
  this.logger.debug("Cached L1", { cacheKey });
5879
6799
  }
5880
- if (this.opts.frozen) deepFreeze(data);
5881
- return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
6800
+ return data;
5882
6801
  } finally {
5883
- this.inflight.delete(k);
6802
+ if (this.inflight.get(k) === executionPromise) this.inflight.delete(k);
5884
6803
  span.end();
5885
6804
  }
5886
- })();
6805
+ });
5887
6806
  this.inflight.set(k, executionPromise);
5888
- return executionPromise;
6807
+ return this._prepareReadValue(await executionPromise);
5889
6808
  }
5890
6809
  /**
5891
6810
  * Graceful shutdown flusher for Kubernetes preStop hooks, NestJS onApplicationShutdown,
@@ -5966,6 +6885,9 @@ var CacheService = class _CacheService {
5966
6885
  }
5967
6886
  async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority, knownTagVersions) {
5968
6887
  const startEpoch = this._getKeyMutationEpoch(cacheKey);
6888
+ const previous = this.l1.getEntry(cacheKey);
6889
+ const tags = previous?.tags ?? Object.keys(knownTagVersions ?? {});
6890
+ const dependencies = previous?.dependsOn;
5969
6891
  try {
5970
6892
  const fetchStart = Date.now();
5971
6893
  const data = await fetchFn();
@@ -5980,14 +6902,14 @@ var CacheService = class _CacheService {
5980
6902
  const l1Existing = this.l1.get(cacheKey);
5981
6903
  const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
5982
6904
  if (this.opts.tagStrategy === "generational" && tagVersionsSource) {
5983
- const tags = Object.keys(tagVersionsSource);
5984
- const vers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
6905
+ const tags2 = Object.keys(tagVersionsSource);
6906
+ const vers = await Promise.all(tags2.map((tag) => this._getTagVersion(tag)));
5985
6907
  activeTagVersions = {};
5986
- for (let i = 0; i < tags.length; i++) {
5987
- activeTagVersions[tags[i]] = vers[i];
6908
+ for (let i = 0; i < tags2.length; i++) {
6909
+ activeTagVersions[tags2[i]] = vers[i];
5988
6910
  }
5989
6911
  if (knownTagVersions) {
5990
- for (const t of tags) {
6912
+ for (const t of tags2) {
5991
6913
  if (knownTagVersions[t] !== void 0 && activeTagVersions[t] !== knownTagVersions[t]) {
5992
6914
  this.logger.debug("SWR: aborting revalidation commit \u2014 tag version bumped during revalidation", { cacheKey, tag: t });
5993
6915
  return;
@@ -5999,32 +6921,29 @@ var CacheService = class _CacheService {
5999
6921
  this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
6000
6922
  return;
6001
6923
  }
6002
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
6924
+ const writeTs = Date.now();
6925
+ this._invalidateDiskKey(cacheKey);
6926
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs, tags, dependencies);
6927
+ this._restoreEntryMetadata(cacheKey, { tags, dependsOn: dependencies, expiresAt: writeTs + ttlMs + swrGraceMs });
6003
6928
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6004
6929
  try {
6005
- const client = await this.getRedis();
6006
- const s = JSON.stringify(data);
6007
- const stored = await this._serializeAndEncrypt(s);
6008
- const ttlSec = Math.ceil(ttlMs / 1e3);
6009
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
6010
- const now = Date.now();
6011
- const tx = client.multi();
6012
- tx.hset(cacheKey, {
6013
- d: stored,
6014
- t: String(now),
6015
- tv: JSON.stringify(activeTagVersions)
6016
- });
6017
- tx.expire(cacheKey, ttlSec);
6018
- await tx.exec();
6019
- } else {
6020
- await client.setex(cacheKey, ttlSec, stored);
6021
- }
6930
+ await this._writeRedisEntry(
6931
+ cacheKey,
6932
+ data,
6933
+ writeTs + ttlMs + swrGraceMs,
6934
+ writeTs,
6935
+ activeTagVersions,
6936
+ staleAt,
6937
+ tags,
6938
+ dependencies,
6939
+ () => this._getKeyMutationEpoch(cacheKey) === startEpoch
6940
+ );
6022
6941
  } catch {
6023
6942
  }
6024
6943
  }
6025
6944
  this.logger.debug("SWR: revalidation complete", { cacheKey });
6026
6945
  } catch (err) {
6027
- if (this.opts.staleIfError > 0) {
6946
+ if (this.opts.staleIfError > 0 && this._getKeyMutationEpoch(cacheKey) === startEpoch) {
6028
6947
  const additionalMs = this.opts.staleIfError * 1e3;
6029
6948
  this.l1.bumpExpiry(cacheKey, additionalMs);
6030
6949
  this.logger.debug("SWR: revalidation failed, stale-if-error extending expiry", {
@@ -6052,12 +6971,16 @@ var CacheService = class _CacheService {
6052
6971
  const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
6053
6972
  const p = priority ?? inferPriority(cacheKey);
6054
6973
  const k = this.nk(cacheKey);
6974
+ const existingEntry = this.l1.getEntry(k);
6975
+ const requestedTags = opts?.tags ?? existingEntry?.tags ?? this.keyTags.get(k)?.tags;
6976
+ const requestedDependencies = opts?.dependsOn ?? existingEntry?.dependsOn;
6055
6977
  this._bumpKeyMutation(k);
6978
+ const epoch = this._getKeyMutationEpoch(k);
6056
6979
  this.inflight.delete(k);
6057
- this._pendingDiskDeletes.delete(k);
6980
+ this._invalidateDiskKey(k);
6058
6981
  this.counters.sets++;
6059
6982
  let activeTagVersions;
6060
- const tagsToRegister = opts?.tags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
6983
+ const tagsToRegister = requestedTags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(requestedTags, this.opts.tagHierarchyDelimiter) : requestedTags : void 0;
6061
6984
  if (tagsToRegister?.length) {
6062
6985
  if (this.opts.tagStrategy === "generational") {
6063
6986
  const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
@@ -6066,44 +6989,27 @@ var CacheService = class _CacheService {
6066
6989
  activeTagVersions[tagsToRegister[i]] = vers[i];
6067
6990
  }
6068
6991
  } else {
6069
- await this._registerTags(k, tagsToRegister, ttlSeconds);
6070
- }
6071
- }
6072
- this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
6073
- if (opts?.dependsOn?.length) {
6074
- for (const pattern of opts.dependsOn) {
6075
- const nsPattern = this.nk(pattern);
6076
- let deps = this.dependencyIndex.get(nsPattern);
6077
- if (!deps) {
6078
- deps = /* @__PURE__ */ new Set();
6079
- this.dependencyIndex.set(nsPattern, deps);
6080
- }
6081
- deps.add(k);
6992
+ await this._registerTags(k, tagsToRegister, effectiveTtlSeconds);
6082
6993
  }
6083
6994
  }
6995
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return;
6996
+ const writeTs = Date.now();
6997
+ this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions, writeTs, tagsToRegister, requestedDependencies);
6998
+ this._rememberTags(k, tagsToRegister ?? [], writeTs + ttlMs);
6999
+ this._registerDependencies(k, requestedDependencies);
6084
7000
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6085
7001
  try {
6086
- const client = await this.getRedis();
6087
- const s = JSON.stringify(data);
6088
- const stored = await this._serializeAndEncrypt(s);
6089
- const ttlSec = Math.ceil(ttlMs / 1e3);
6090
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
6091
- const now = Date.now();
6092
- const tx = client.multi();
6093
- tx.hset(k, {
6094
- d: stored,
6095
- t: String(now),
6096
- tv: JSON.stringify(activeTagVersions)
6097
- });
6098
- tx.expire(k, ttlSec);
6099
- await tx.exec();
6100
- } else {
6101
- if (this.opts.autoPipeline && this.pipeliner) {
6102
- await this.pipeliner.setex(k, ttlSec, stored);
6103
- } else {
6104
- await client.setex(k, ttlSec, stored);
6105
- }
6106
- }
7002
+ await this._writeRedisEntry(
7003
+ k,
7004
+ data,
7005
+ writeTs + ttlMs,
7006
+ writeTs,
7007
+ activeTagVersions,
7008
+ void 0,
7009
+ tagsToRegister,
7010
+ requestedDependencies,
7011
+ () => this._getKeyMutationEpoch(k) === epoch
7012
+ );
6107
7013
  this.cb.onSuccess();
6108
7014
  } catch (err) {
6109
7015
  this.cb.onFailure();
@@ -6128,23 +7034,18 @@ var CacheService = class _CacheService {
6128
7034
  * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
6129
7035
  */
6130
7036
  async _registerTags(k, tags, ttlSeconds) {
6131
- for (const tag of tags) {
6132
- const tagKey = this.nk(`_tag_:${tag}`);
6133
- let members = this.tagIndex.get(tagKey);
6134
- if (!members) {
6135
- members = /* @__PURE__ */ new Set();
6136
- this.tagIndex.set(tagKey, members);
6137
- }
6138
- members.add(k);
6139
- }
7037
+ const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
7038
+ const expiresAt = Date.now() + effectiveTtl * 1e3;
7039
+ const uniqueTags = Array.from(new Set(tags));
7040
+ this._rememberTags(k, uniqueTags, expiresAt);
6140
7041
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6141
7042
  try {
6142
7043
  const client = await this.getRedis();
6143
7044
  const pl = client.pipeline();
6144
- for (const tag of tags) {
7045
+ for (const tag of uniqueTags) {
6145
7046
  const tagKey = this.nk(`_tag_:${tag}`);
6146
7047
  pl.sadd(tagKey, k);
6147
- pl.expire(tagKey, ttlSeconds + 3600);
7048
+ pl.expire(tagKey, effectiveTtl + 3600);
6148
7049
  }
6149
7050
  await pl.exec();
6150
7051
  this.cb.onSuccess();
@@ -6169,6 +7070,7 @@ var CacheService = class _CacheService {
6169
7070
  const k = this.nk(cacheKey);
6170
7071
  this.counters.deletes++;
6171
7072
  if (isPattern) {
7073
+ this._fenceInvalidation();
6172
7074
  const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6173
7075
  for (const liveKey of this.l1.liveKeys()) {
6174
7076
  if (liveKey.startsWith(pfx)) {
@@ -6181,29 +7083,30 @@ var CacheService = class _CacheService {
6181
7083
  this.inflight.delete(inflightKey);
6182
7084
  }
6183
7085
  }
6184
- this._addPatternTombstone(pfx);
7086
+ this._addPatternTombstone(k);
6185
7087
  this.l1.deletePattern(k);
7088
+ this._removePatternFromIndices(k);
7089
+ for (const ktKey of Array.from(this.keyTags.keys())) {
7090
+ if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
7091
+ }
7092
+ for (const kdKey of Array.from(this.keyDependencies.keys())) {
7093
+ if (this._matchesGlob(kdKey, k)) this._removeKeyDependencies(kdKey);
7094
+ }
6186
7095
  } else {
6187
7096
  this._bumpKeyMutation(k);
6188
7097
  this.inflight.delete(k);
6189
7098
  this.l1.delete(k);
6190
- this._pendingDiskDeletes.add(k);
6191
- setImmediate(() => {
6192
- try {
6193
- if (!this._diskDisabled) this.disk.delete(k);
6194
- } finally {
6195
- this._pendingDiskDeletes.delete(k);
6196
- }
6197
- });
7099
+ this._invalidateDiskKey(k);
7100
+ this._removeKeyTags(k);
6198
7101
  this._cascadeDependencies(k);
6199
- for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
7102
+ this._removeKeyDependencies(k);
6200
7103
  }
6201
7104
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6202
7105
  try {
6203
7106
  const client = await this.getRedis();
6204
7107
  if (isPattern) {
6205
7108
  const keys = await this._scanKeys(client, k);
6206
- if (keys.length > 0) await client.del(...keys);
7109
+ await this._deleteRedisKeys(client, keys);
6207
7110
  } else {
6208
7111
  if (this.opts.autoPipeline && this.pipeliner) {
6209
7112
  await this.pipeliner.del(k);
@@ -6250,7 +7153,7 @@ var CacheService = class _CacheService {
6250
7153
  async increment(cacheKey, ttlSeconds) {
6251
7154
  this._assertActive("increment");
6252
7155
  const k = this.nk(cacheKey);
6253
- if (this._redisDisabled) {
7156
+ if (this._redisDisabled || this.opts.l2WriteMode === "read-only") {
6254
7157
  if (!this._incrementFallbackWarned) {
6255
7158
  this._incrementFallbackWarned = true;
6256
7159
  this.logger.warn(
@@ -6265,6 +7168,15 @@ var CacheService = class _CacheService {
6265
7168
  entry.value++;
6266
7169
  return entry.value;
6267
7170
  }
7171
+ if (this._l1Counters.size >= 5e4 && !this._l1Counters.has(k)) {
7172
+ for (const [ck, cv] of this._l1Counters) {
7173
+ if (cv.expiresAt <= now) this._l1Counters.delete(ck);
7174
+ }
7175
+ if (this._l1Counters.size >= 5e4) {
7176
+ const oldest = this._l1Counters.keys().next().value;
7177
+ if (oldest !== void 0) this._l1Counters.delete(oldest);
7178
+ }
7179
+ }
6268
7180
  this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
6269
7181
  return 1;
6270
7182
  }
@@ -6297,6 +7209,7 @@ var CacheService = class _CacheService {
6297
7209
  this.counters.deletes++;
6298
7210
  const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
6299
7211
  if (k) {
7212
+ this._fenceInvalidation();
6300
7213
  const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6301
7214
  for (const liveKey of this.l1.liveKeys()) {
6302
7215
  if (liveKey.startsWith(pfx)) {
@@ -6309,8 +7222,9 @@ var CacheService = class _CacheService {
6309
7222
  this.inflight.delete(inflightKey);
6310
7223
  }
6311
7224
  }
6312
- this._addPatternTombstone(pfx);
7225
+ this._addPatternTombstone(k);
6313
7226
  this.l1.deletePattern(k);
7227
+ this._removePatternFromIndices(k);
6314
7228
  } else {
6315
7229
  this._globalEpoch++;
6316
7230
  this.inflight.clear();
@@ -6319,7 +7233,10 @@ var CacheService = class _CacheService {
6319
7233
  if (!this._diskDisabled) this.disk.clear();
6320
7234
  this._l1Counters.clear();
6321
7235
  this.tagIndex.clear();
7236
+ this.keyTags.clear();
6322
7237
  this.tagVersions.clear();
7238
+ this.dependencyIndex.clear();
7239
+ this.keyDependencies.clear();
6323
7240
  this._pendingDiskDeletes.clear();
6324
7241
  this._keyMutationEpochs.clear();
6325
7242
  }
@@ -6328,7 +7245,7 @@ var CacheService = class _CacheService {
6328
7245
  const client = await this.getRedis();
6329
7246
  const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
6330
7247
  const keys = await this._scanKeys(client, pattern);
6331
- if (keys.length > 0) await client.del(...keys);
7248
+ await this._deleteRedisKeys(client, keys);
6332
7249
  } catch (err) {
6333
7250
  this.logger.debug("clear: Redis unavailable", { error: err.message });
6334
7251
  }
@@ -6457,24 +7374,34 @@ var CacheService = class _CacheService {
6457
7374
  this._assertActive("scan");
6458
7375
  const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
6459
7376
  this.l1.scan((key, entry, pfx) => {
6460
- const value = entry.value !== void 0 ? entry.value : entry.data;
6461
- fn(key, value, pfx);
7377
+ fn(key, this._prepareReadValue(this.l1.resolveValue(entry)), pfx);
6462
7378
  }, prefixLen);
6463
7379
  }
6464
7380
  /**
6465
- * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
7381
+ * Extend the TTL of a key in L1 and Redis without fetching.
6466
7382
  * Returns `false` if the key is absent or already expired.
6467
7383
  *
6468
7384
  * @param newTtlSeconds - The new TTL from now, in seconds.
6469
7385
  */
6470
7386
  async touch(cacheKey, newTtlSeconds) {
6471
7387
  this._assertActive("touch");
7388
+ if (!Number.isFinite(newTtlSeconds) || newTtlSeconds <= 0) throw new Error("touch TTL must be finite and positive");
6472
7389
  const k = this.nk(cacheKey);
7390
+ const epoch = this._getKeyMutationEpoch(k);
6473
7391
  const hit = this.l1.touch(k, newTtlSeconds * 1e3);
6474
- if (hit && !this._redisDisabled) {
7392
+ const entry = this.l1.getEntry(k);
7393
+ if (hit) {
7394
+ const kt = this.keyTags.get(k);
7395
+ if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1e3;
7396
+ }
7397
+ if (hit && !this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6475
7398
  try {
6476
7399
  const client = await this.getRedis();
6477
- void client.expire(k, newTtlSeconds);
7400
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return hit;
7401
+ if (entry && typeof client.pttl === "function" && typeof client.eval === "function") {
7402
+ await client.eval(LUA_TOUCH_CACHE_ENTRY, 1, k, String(entry.setAt ?? 0), String(entry.expiresAt), String(Math.ceil(newTtlSeconds * 1e3)));
7403
+ } else await client.expire(k, Math.ceil(newTtlSeconds));
7404
+ this.cb.onSuccess();
6478
7405
  } catch {
6479
7406
  }
6480
7407
  }
@@ -6496,7 +7423,12 @@ var CacheService = class _CacheService {
6496
7423
  const now = Date.now();
6497
7424
  if (entry.expiresAt <= now) return null;
6498
7425
  if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
6499
- return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
7426
+ if (entry.tagVersions && Object.entries(entry.tagVersions).some(([tag, version]) => (this.tagVersions.get(tag)?.version ?? 0) > version)) return null;
7427
+ return this._prepareReadValue(entry.value !== void 0 ? entry.value : this.codec.decode(entry.data));
7428
+ }
7429
+ _prepareReadValue(val) {
7430
+ if (this.opts.frozen) deepFreeze(val);
7431
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6500
7432
  }
6501
7433
  /**
6502
7434
  * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
@@ -6509,59 +7441,36 @@ var CacheService = class _CacheService {
6509
7441
  async peek(cacheKey) {
6510
7442
  this._assertActive("peek");
6511
7443
  const k = this.nk(cacheKey);
7444
+ const epoch = this._getKeyMutationEpoch(k);
7445
+ this.counters.gets++;
6512
7446
  const l1Hit = this.l1.get(k);
6513
7447
  if (l1Hit !== null) {
6514
- this.counters.gets++;
6515
- this.counters.l1Hits++;
6516
- const val = l1Hit.value;
6517
- if (this.opts.frozen) deepFreeze(val);
6518
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6519
- }
6520
- if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
6521
- if (this._isTombstonedByPattern(k)) {
6522
- try {
6523
- this.disk.delete(k);
6524
- } catch {
6525
- }
6526
- } else if (this.watchdog.isDiskAllowed()) {
6527
- const diskStart = performance.now();
6528
- const diskHit = this.disk.load(k);
6529
- const diskElapsed = performance.now() - diskStart;
6530
- this.watchdog.recordDisk(diskElapsed);
6531
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6532
- if (diskHit !== null) {
6533
- const promoted = this.l1.importEntries(
6534
- [{ key: k, entry: diskHit }],
6535
- this.opts.forbiddenSnapshotPrefixes
6536
- );
6537
- if (promoted > 0) {
6538
- const l1Check = this.l1.get(k);
6539
- if (l1Check !== null) {
6540
- this.counters.gets++;
6541
- this.counters.diskHits++;
6542
- const val = l1Check.value;
6543
- if (this.opts.frozen) deepFreeze(val);
6544
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6545
- }
6546
- }
6547
- }
7448
+ if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
7449
+ this._deleteIfStale(k, l1Hit.setAt ?? 0);
7450
+ } else {
7451
+ this.counters.l1Hits++;
7452
+ return this._prepareReadValue(l1Hit.value);
6548
7453
  }
6549
7454
  }
6550
- if (!this._redisDisabled && !this.cb.isOpen) {
7455
+ const diskHit = await this._readDiskEntry(k, epoch);
7456
+ if (diskHit) {
7457
+ this.counters.diskHits++;
7458
+ return this._prepareReadValue(diskHit.value);
7459
+ }
7460
+ if (!this._redisDisabled) {
6551
7461
  try {
6552
7462
  const client = await this.getRedis();
6553
7463
  const redisStart = performance.now();
6554
- const raw = await client.get(k);
7464
+ const redisHit = await this._readRedisEntry(client, k);
6555
7465
  const redisElapsed = performance.now() - redisStart;
6556
7466
  this.watchdog.recordRedis(redisElapsed);
6557
- if (raw !== null) {
6558
- const parsed = await this._decryptAndDeserialize(raw);
6559
- this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
6560
- this.counters.gets++;
7467
+ this.cb.onSuccess();
7468
+ if (redisHit && !redisHit.stale) {
7469
+ const parsed = redisHit.value;
7470
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return null;
7471
+ if (!this._promoteRedisEntry(k, redisHit, 6e4, inferPriority(cacheKey))) return null;
6561
7472
  this.counters.l2Hits++;
6562
- this.cb.onSuccess();
6563
- if (this.opts.frozen) deepFreeze(parsed);
6564
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
7473
+ return this._prepareReadValue(parsed);
6565
7474
  }
6566
7475
  } catch (err) {
6567
7476
  this.cb.onFailure();
@@ -6581,6 +7490,8 @@ var CacheService = class _CacheService {
6581
7490
  */
6582
7491
  async mget(keys, fetchFn, ttl = 300, priority) {
6583
7492
  this._assertActive("mget");
7493
+ this.counters.gets += keys.length;
7494
+ const epochs = new Map(keys.map((key) => [this.nk(key), this._getKeyMutationEpoch(this.nk(key))]));
6584
7495
  const span = this._startSpan("tricache.mget");
6585
7496
  if (this.opts.tracer) {
6586
7497
  span.setAttribute("cache.batch.size", keys.length);
@@ -6589,12 +7500,20 @@ var CacheService = class _CacheService {
6589
7500
  const result = Array.from({ length: keys.length });
6590
7501
  const missIndexes = [];
6591
7502
  const missKeys = [];
7503
+ const now = Date.now();
6592
7504
  for (let i = 0; i < keys.length; i++) {
6593
7505
  const k = this.nk(keys[i]);
6594
7506
  const entry = this.l1.getEntry(k);
6595
- if (entry && entry.expiresAt > Date.now()) {
6596
- result[i] = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
6597
- this.counters.l1Hits++;
7507
+ if (entry && entry.expiresAt > now && (entry.staleAt === void 0 || entry.staleAt > now)) {
7508
+ if (await this._isGenerationalEntryStale(entry.tagVersions)) {
7509
+ this._deleteIfStale(k, entry.setAt ?? 0);
7510
+ missIndexes.push(i);
7511
+ missKeys.push(keys[i]);
7512
+ } else {
7513
+ const val = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
7514
+ result[i] = this._prepareReadValue(val);
7515
+ this.counters.l1Hits++;
7516
+ }
6598
7517
  } else {
6599
7518
  missIndexes.push(i);
6600
7519
  missKeys.push(keys[i]);
@@ -6614,30 +7533,24 @@ var CacheService = class _CacheService {
6614
7533
  try {
6615
7534
  const client = await this.getRedis();
6616
7535
  const nsKeys = missKeys.map((k) => this.nk(k));
6617
- const pipeline = client.multi();
6618
- for (const nk of nsKeys) pipeline.get(nk);
6619
- const redisStart = performance.now();
6620
- const raws = await pipeline.exec();
6621
- const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
6622
- this.watchdog.recordRedis(redisElapsed);
6623
- this.cb.onSuccess();
7536
+ const remoteEntries = await this._readRedisBatch(client, nsKeys);
6624
7537
  for (let j = 0; j < missKeys.length; j++) {
6625
- const raw = raws[j] ? raws[j][1] : null;
6626
7538
  const idx = missIndexes[j];
6627
- if (raw) {
6628
- const parsed = await this._decryptAndDeserialize(raw);
6629
- const k = nsKeys[j];
7539
+ const k = nsKeys[j];
7540
+ const entry = remoteEntries.get(k);
7541
+ if (entry && (entry.staleAt === void 0 || entry.staleAt > Date.now()) && !this._destroyed && this._getKeyMutationEpoch(k) === epochs.get(k)) {
6630
7542
  const p = priority ?? inferPriority(missKeys[j]);
6631
- this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
7543
+ const ttlVal = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
7544
+ if (!this._promoteRedisEntry(k, entry, this._jitterTtl(ttlVal * 1e3), p)) continue;
6632
7545
  this.counters.l2Hits++;
6633
7546
  l2HitCount++;
6634
- result[idx] = parsed;
7547
+ result[idx] = this._prepareReadValue(entry.value);
6635
7548
  missIndexes[j] = -1;
6636
7549
  missKeys[j] = "";
6637
7550
  }
6638
7551
  }
6639
7552
  const remainingIdx = missIndexes.filter((i) => i >= 0);
6640
- const remainingKeys = missKeys.filter((k) => k !== "");
7553
+ const remainingKeys = missKeys.filter((_key, index) => missIndexes[index] >= 0);
6641
7554
  missIndexes.length = 0;
6642
7555
  missKeys.length = 0;
6643
7556
  missIndexes.push(...remainingIdx);
@@ -6650,58 +7563,64 @@ var CacheService = class _CacheService {
6650
7563
  if (!this._diskDisabled && missKeys.length > 0) {
6651
7564
  for (let j = missKeys.length - 1; j >= 0; j--) {
6652
7565
  const k = this.nk(missKeys[j]);
6653
- if (this._pendingDiskDeletes.has(k)) continue;
6654
- if (this._isTombstonedByPattern(k)) {
6655
- try {
6656
- this.disk.delete(k);
6657
- } catch {
6658
- }
6659
- continue;
6660
- }
6661
- if (!this.watchdog.isDiskAllowed()) continue;
6662
- const diskStart = performance.now();
6663
- const diskHit = this.disk.load(k);
6664
- const diskElapsed = performance.now() - diskStart;
6665
- this.watchdog.recordDisk(diskElapsed);
6666
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6667
- if (diskHit !== null) {
6668
- const promoted = this.l1.importEntries(
6669
- [{ key: k, entry: diskHit }],
6670
- this.opts.forbiddenSnapshotPrefixes
6671
- );
6672
- if (promoted > 0) {
6673
- const l1Check = this.l1.get(k);
6674
- if (l1Check !== null) {
6675
- this.counters.diskHits++;
6676
- result[missIndexes[j]] = l1Check.value;
6677
- missIndexes.splice(j, 1);
6678
- missKeys.splice(j, 1);
6679
- }
6680
- }
7566
+ const diskHit = await this._readDiskEntry(k, epochs.get(k));
7567
+ if (diskHit && (diskHit.entry.staleAt === void 0 || diskHit.entry.staleAt > Date.now())) {
7568
+ this.counters.diskHits++;
7569
+ result[missIndexes[j]] = this._prepareReadValue(diskHit.value);
7570
+ missIndexes.splice(j, 1);
7571
+ missKeys.splice(j, 1);
6681
7572
  }
6682
7573
  }
6683
7574
  }
6684
7575
  if (missKeys.length > 0 && fetchFn) {
6685
- this.counters.fetches++;
6686
- const fetched = await fetchFn(missKeys);
6687
- const isMap = fetched instanceof Map;
6688
- const setPromises = [];
7576
+ const owned = /* @__PURE__ */ new Map();
7577
+ const waiting = [];
6689
7578
  for (let j = 0; j < missKeys.length; j++) {
6690
- const k = missKeys[j];
6691
- const v = isMap ? fetched.get(k) : fetched[k];
6692
- result[missIndexes[j]] = v;
6693
- if (v !== void 0 && v !== null) {
6694
- const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
6695
- setPromises.push(this.set(k, v, resolvedTtl, priority));
6696
- } else if (v == null && this.opts.notFoundTtl > 0) {
6697
- setPromises.push(this.set(k, null, this.opts.notFoundTtl, priority));
6698
- } else if (v === null) {
6699
- const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
6700
- setPromises.push(this.set(k, null, resolvedTtl, priority));
7579
+ const key = missKeys[j];
7580
+ const namespaced = this.nk(key);
7581
+ let promise = this.inflight.get(namespaced);
7582
+ if (!promise) {
7583
+ let resolve;
7584
+ let reject;
7585
+ promise = new Promise((yes, no) => {
7586
+ resolve = yes;
7587
+ reject = no;
7588
+ });
7589
+ owned.set(key, { promise, resolve, reject });
7590
+ this.inflight.set(namespaced, promise);
7591
+ } else {
7592
+ this.counters.stampedes++;
6701
7593
  }
7594
+ const index = missIndexes[j];
7595
+ waiting.push(promise.then((value) => {
7596
+ result[index] = this._prepareReadValue(value);
7597
+ }));
6702
7598
  }
6703
- if (setPromises.length > 0) {
6704
- await Promise.all(setPromises);
7599
+ const settled = Promise.allSettled(waiting);
7600
+ try {
7601
+ if (owned.size > 0) {
7602
+ this.counters.fetches++;
7603
+ const fetched = await fetchFn([...owned.keys()]);
7604
+ await Promise.all([...owned].map(async ([key, entry]) => {
7605
+ const value = fetched instanceof Map ? fetched.get(key) : Object.hasOwn(fetched, key) ? fetched[key] : void 0;
7606
+ if (!this._destroyed && this._getKeyMutationEpoch(this.nk(key)) === epochs.get(this.nk(key))) {
7607
+ const resolvedTtl = value == null && this.opts.notFoundTtl > 0 ? this.opts.notFoundTtl : typeof ttl === "function" ? ttl(key) : ttl;
7608
+ if (value !== void 0 || this.opts.notFoundTtl > 0) await this.set(key, value === void 0 && this.opts.notFoundTtl > 0 ? null : value, resolvedTtl, priority);
7609
+ }
7610
+ entry.resolve(value);
7611
+ }));
7612
+ }
7613
+ const outcomes = await settled;
7614
+ const failed = outcomes.find((outcome) => outcome.status === "rejected");
7615
+ if (failed?.status === "rejected") throw failed.reason;
7616
+ } catch (error) {
7617
+ for (const entry of owned.values()) entry.reject(error);
7618
+ throw error;
7619
+ } finally {
7620
+ for (const [key, entry] of owned) {
7621
+ const namespaced = this.nk(key);
7622
+ if (this.inflight.get(namespaced) === entry.promise) this.inflight.delete(namespaced);
7623
+ }
6705
7624
  }
6706
7625
  }
6707
7626
  if (this.opts.tracer) {
@@ -6754,7 +7673,7 @@ var CacheService = class _CacheService {
6754
7673
  try {
6755
7674
  await Promise.all(keys.map((key) => {
6756
7675
  const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
6757
- const hasOpts = tags?.length || dependsOn?.length;
7676
+ const hasOpts = tags !== void 0 || dependsOn !== void 0;
6758
7677
  return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
6759
7678
  }));
6760
7679
  } catch (err) {
@@ -6806,26 +7725,21 @@ var CacheService = class _CacheService {
6806
7725
  try {
6807
7726
  const client = await this.getRedis();
6808
7727
  const nsPattern = this.nk(pattern);
6809
- const matchedKeys = await this._scanKeys(client, nsPattern);
7728
+ const matchedKeys = (await this._scanKeys(client, nsPattern)).filter((key) => {
7729
+ const raw = this.unnk(key);
7730
+ return !raw.startsWith("_tag_:") && !raw.startsWith("tag_ver:") && !raw.startsWith("lock:") && key !== this.backplaneStreamKey;
7731
+ });
6810
7732
  if (matchedKeys.length === 0) {
6811
7733
  this.cb.onSuccess();
6812
7734
  return 0;
6813
7735
  }
6814
- const pl = client.pipeline();
6815
- for (const k of matchedKeys) pl.get(k);
6816
- const results = await pl.exec();
6817
- this.cb.onSuccess();
7736
+ const epochs = new Map(matchedKeys.map((key) => [key, this._getKeyMutationEpoch(key)]));
7737
+ const results = await this._readRedisBatch(client, matchedKeys);
6818
7738
  let loaded = 0;
6819
- for (let i = 0; i < matchedKeys.length; i++) {
6820
- const [err, raw] = results[i];
6821
- if (err || raw == null) continue;
6822
- try {
6823
- const parsed = await this._decryptAndDeserialize(raw);
6824
- const remainingMs = 10 * 60 * 1e3;
6825
- this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
6826
- loaded++;
6827
- } catch {
6828
- }
7739
+ for (const key of matchedKeys) {
7740
+ const entry = results.get(key);
7741
+ if (!entry || this._destroyed || this._getKeyMutationEpoch(key) !== epochs.get(key)) continue;
7742
+ if (this._promoteRedisEntry(key, entry, 10 * 60 * 1e3, opts?.priority ?? inferPriority(this.unnk(key))) && this.l1.has(key)) loaded++;
6829
7743
  }
6830
7744
  this.logger.info("warmFromL2 complete", {
6831
7745
  pattern,
@@ -6898,6 +7812,139 @@ var CacheService = class _CacheService {
6898
7812
  }
6899
7813
  return matched;
6900
7814
  }
7815
+ async _publishTagInvalidation(op, key, tagVersion) {
7816
+ if (this.opts.awaitInvalidationBackplane) {
7817
+ await this.publishInvalidation(op, key, tagVersion, false, true);
7818
+ } else {
7819
+ void this.publishInvalidation(op, key, tagVersion, false, true);
7820
+ }
7821
+ }
7822
+ _removeTagMembersLocal(keys) {
7823
+ const keyList = Array.isArray(keys) ? keys : Array.from(keys);
7824
+ for (const k of keyList) {
7825
+ this.l1.delete(k);
7826
+ this._bumpKeyMutation(k);
7827
+ this._removeKeyTags(k);
7828
+ this._removeKeyDependencies(k);
7829
+ this._invalidateDiskKey(k);
7830
+ }
7831
+ }
7832
+ /**
7833
+ * Executes invalidation for a single already-resolved concrete tag without
7834
+ * wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
7835
+ */
7836
+ async _invalidateConcreteTag(tag) {
7837
+ this._fenceInvalidation();
7838
+ if (this.opts.tagStrategy === "generational") {
7839
+ let newVer = 1;
7840
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7841
+ try {
7842
+ const client = await this.getRedis();
7843
+ newVer = await client.incr(this.nk(`tag_ver:${tag}`));
7844
+ } catch (err) {
7845
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7846
+ const current = this.tagVersions.get(tag)?.version ?? 0;
7847
+ newVer = current + 1;
7848
+ }
7849
+ } else {
7850
+ const current = this.tagVersions.get(tag)?.version ?? 0;
7851
+ newVer = current + 1;
7852
+ }
7853
+ this._setLocalTagVersion(tag, newVer, performance.now());
7854
+ await this._publishTagInvalidation("tag_incr", tag, newVer);
7855
+ return;
7856
+ }
7857
+ const tagKey = this.nk(`_tag_:${tag}`);
7858
+ const members = new Set(this.tagIndex.get(tagKey) ?? []);
7859
+ this.tagIndex.delete(tagKey);
7860
+ this._removeTagMembersLocal(members);
7861
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7862
+ try {
7863
+ const client = await this.getRedis();
7864
+ const redisMembers = await client.smembers(tagKey);
7865
+ for (const key of redisMembers) members.add(key);
7866
+ this._removeTagMembersLocal(redisMembers);
7867
+ const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers, tagKey])];
7868
+ await this._deleteRedisKeys(client, toDelete);
7869
+ } catch (err) {
7870
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
7871
+ }
7872
+ }
7873
+ await Promise.all([...members].map((key) => this._publishTagInvalidation("del", key)));
7874
+ await this._publishTagInvalidation("tag_pattern_del", tag);
7875
+ }
7876
+ /**
7877
+ * Executes invalidation for an array of already-resolved concrete tags
7878
+ * without re-entering wildcard/cascade resolution or invalidateTag().
7879
+ */
7880
+ async _invalidateConcreteTags(tags) {
7881
+ if (tags.length === 0) return;
7882
+ if (tags.length === 1) {
7883
+ await this._invalidateConcreteTag(tags[0]);
7884
+ return;
7885
+ }
7886
+ this._fenceInvalidation();
7887
+ if (this.opts.tagStrategy === "generational") {
7888
+ const now = performance.now();
7889
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7890
+ try {
7891
+ const client = await this.getRedis();
7892
+ const pl = client.pipeline();
7893
+ for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
7894
+ const results = await pl.exec();
7895
+ for (let i = 0; i < tags.length; i++) {
7896
+ const [err, newVer] = results[i] ?? [null, null];
7897
+ const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
7898
+ this._setLocalTagVersion(tags[i], ver, now);
7899
+ await this._publishTagInvalidation("tag_incr", tags[i], ver);
7900
+ }
7901
+ return;
7902
+ } catch (err) {
7903
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7904
+ }
7905
+ }
7906
+ for (const tag of tags) {
7907
+ const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
7908
+ this._setLocalTagVersion(tag, ver, now);
7909
+ await this._publishTagInvalidation("tag_incr", tag, ver);
7910
+ }
7911
+ return;
7912
+ }
7913
+ const tagKeys = [];
7914
+ const allMembers = /* @__PURE__ */ new Set();
7915
+ for (const tag of tags) {
7916
+ const tagKey = this.nk(`_tag_:${tag}`);
7917
+ tagKeys.push(tagKey);
7918
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
7919
+ for (const k of members) allMembers.add(k);
7920
+ this.tagIndex.delete(tagKey);
7921
+ }
7922
+ this._removeTagMembersLocal(allMembers);
7923
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7924
+ try {
7925
+ const client = await this.getRedis();
7926
+ const pl = client.pipeline();
7927
+ for (const tagKey of tagKeys) pl.smembers(tagKey);
7928
+ const smResults = await pl.exec();
7929
+ const toDelete = [...allMembers];
7930
+ for (const [err, redisMembers] of smResults) {
7931
+ if (!err && redisMembers) {
7932
+ for (const k of redisMembers) {
7933
+ if (!allMembers.has(k)) toDelete.push(k);
7934
+ allMembers.add(k);
7935
+ }
7936
+ }
7937
+ }
7938
+ const keysToRemove = [...toDelete, ...tagKeys];
7939
+ await this._deleteRedisKeys(client, keysToRemove);
7940
+ this._removeTagMembersLocal(allMembers);
7941
+ } catch (err) {
7942
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7943
+ }
7944
+ }
7945
+ await Promise.all([...allMembers].map((key) => this._publishTagInvalidation("del", key)));
7946
+ for (const tag of tags) await this._publishTagInvalidation("tag_pattern_del", tag);
7947
+ }
6901
7948
  /**
6902
7949
  * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
6903
7950
  * Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
@@ -6933,68 +7980,13 @@ var CacheService = class _CacheService {
6933
7980
  const delim = this.opts.tagHierarchyDelimiter;
6934
7981
  const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
6935
7982
  if (matchedTags.size > 0) {
6936
- await this.invalidateTags(Array.from(matchedTags));
7983
+ await this._invalidateConcreteTags(Array.from(matchedTags));
6937
7984
  }
6938
7985
  const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
6939
- if (this.opts.awaitInvalidationBackplane) {
6940
- await this.publishInvalidation(op, broadcastPattern, void 0, false, true);
6941
- } else {
6942
- void this.publishInvalidation(op, broadcastPattern, void 0, false, true);
6943
- }
6944
- return;
6945
- }
6946
- if (this.opts.tagStrategy === "generational") {
6947
- let newVer = 1;
6948
- if (!this._redisDisabled) {
6949
- try {
6950
- const client = await this.getRedis();
6951
- newVer = await client.incr(this.nk(`tag_ver:${tag}`));
6952
- } catch (err) {
6953
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
6954
- const current = this.tagVersions.get(tag)?.version ?? 0;
6955
- newVer = current + 1;
6956
- }
6957
- } else {
6958
- const current = this.tagVersions.get(tag)?.version ?? 0;
6959
- newVer = current + 1;
6960
- }
6961
- this._setLocalTagVersion(tag, newVer, performance.now());
6962
- if (this.opts.awaitInvalidationBackplane) {
6963
- await this.publishInvalidation("tag_incr", tag, newVer, false, true);
6964
- } else {
6965
- void this.publishInvalidation("tag_incr", tag, newVer, false, true);
6966
- }
7986
+ await this._publishTagInvalidation(op, broadcastPattern);
6967
7987
  return;
6968
7988
  }
6969
- const tagKey = this.nk(`_tag_:${tag}`);
6970
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
6971
- for (const k of members) {
6972
- this.l1.delete(k);
6973
- this._bumpKeyMutation(k);
6974
- this._pendingDiskDeletes.add(k);
6975
- setImmediate(() => {
6976
- try {
6977
- if (!this._diskDisabled) this.disk.delete(k);
6978
- } finally {
6979
- this._pendingDiskDeletes.delete(k);
6980
- }
6981
- });
6982
- }
6983
- this.tagIndex.delete(tagKey);
6984
- if (!this._redisDisabled) {
6985
- try {
6986
- const client = await this.getRedis();
6987
- const redisMembers = await client.smembers(tagKey);
6988
- const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
6989
- if (toDelete.length > 0) {
6990
- await client.del(...toDelete, tagKey);
6991
- } else {
6992
- await client.del(tagKey);
6993
- }
6994
- } catch (err) {
6995
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
6996
- }
6997
- }
7989
+ await this._invalidateConcreteTag(tag);
6998
7990
  } catch (err) {
6999
7991
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
7000
7992
  span.recordException?.(err);
@@ -7021,96 +8013,28 @@ var CacheService = class _CacheService {
7021
8013
  const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
7022
8014
  if (hasWildcards || shouldCascade) {
7023
8015
  const allResolvedTags = /* @__PURE__ */ new Set();
8016
+ const broadcastPatterns = /* @__PURE__ */ new Set();
8017
+ const delim = this.opts.tagHierarchyDelimiter;
7024
8018
  for (const t of tags) {
7025
- if (isWildcardTag(t) || shouldCascade) {
8019
+ const tIsPattern = isWildcardTag(t);
8020
+ if (tIsPattern || shouldCascade) {
8021
+ broadcastPatterns.add(tIsPattern ? t : `${t}${delim}*`);
7026
8022
  const resolved = await this._resolveMatchingTags(t, shouldCascade);
7027
8023
  for (const rt of resolved) allResolvedTags.add(rt);
7028
8024
  } else {
7029
8025
  allResolvedTags.add(t);
7030
8026
  }
7031
8027
  }
7032
- if (allResolvedTags.size === 0) return;
7033
- tags = Array.from(allResolvedTags);
7034
- }
7035
- if (tags.length === 1) {
7036
- await this.invalidateTag(tags[0], opts);
7037
- return;
7038
- }
7039
- if (this.opts.tagStrategy === "generational") {
7040
- const now = performance.now();
7041
- if (!this._redisDisabled) {
7042
- try {
7043
- const client = await this.getRedis();
7044
- const pl = client.pipeline();
7045
- for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
7046
- const results = await pl.exec();
7047
- for (let i = 0; i < tags.length; i++) {
7048
- const [err, newVer] = results[i] ?? [null, null];
7049
- const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
7050
- this._setLocalTagVersion(tags[i], ver, now);
7051
- if (this.opts.awaitInvalidationBackplane) {
7052
- await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7053
- } else {
7054
- void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
7055
- }
7056
- }
7057
- return;
7058
- } catch (err) {
7059
- this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7060
- }
8028
+ if (allResolvedTags.size > 0) {
8029
+ await this._invalidateConcreteTags(Array.from(allResolvedTags));
7061
8030
  }
7062
- for (const tag of tags) {
7063
- const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
7064
- this._setLocalTagVersion(tag, ver, now);
7065
- if (this.opts.awaitInvalidationBackplane) {
7066
- await this.publishInvalidation("tag_incr", tag, ver, false, true);
7067
- } else {
7068
- void this.publishInvalidation("tag_incr", tag, ver, false, true);
7069
- }
8031
+ const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
8032
+ for (const pattern of broadcastPatterns) {
8033
+ await this._publishTagInvalidation(op, pattern);
7070
8034
  }
7071
8035
  return;
7072
8036
  }
7073
- const tagKeys = [];
7074
- const allMembers = /* @__PURE__ */ new Set();
7075
- for (const tag of tags) {
7076
- const tagKey = this.nk(`_tag_:${tag}`);
7077
- tagKeys.push(tagKey);
7078
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
7079
- for (const k of members) allMembers.add(k);
7080
- this.tagIndex.delete(tagKey);
7081
- }
7082
- for (const k of allMembers) {
7083
- this.l1.delete(k);
7084
- this._bumpKeyMutation(k);
7085
- this._pendingDiskDeletes.add(k);
7086
- setImmediate(() => {
7087
- try {
7088
- if (!this._diskDisabled) this.disk.delete(k);
7089
- } finally {
7090
- this._pendingDiskDeletes.delete(k);
7091
- }
7092
- });
7093
- }
7094
- if (!this._redisDisabled) {
7095
- try {
7096
- const client = await this.getRedis();
7097
- const pl = client.pipeline();
7098
- for (const tagKey of tagKeys) pl.smembers(tagKey);
7099
- const smResults = await pl.exec();
7100
- const toDelete = [...allMembers];
7101
- for (const [err, redisMembers] of smResults) {
7102
- if (!err && redisMembers) {
7103
- for (const k of redisMembers) {
7104
- if (!allMembers.has(k)) toDelete.push(k);
7105
- }
7106
- }
7107
- }
7108
- const keysToRemove = [...toDelete, ...tagKeys];
7109
- if (keysToRemove.length > 0) await client.del(...keysToRemove);
7110
- } catch (err) {
7111
- this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
7112
- }
7113
- }
8037
+ await this._invalidateConcreteTags(Array.from(new Set(tags)));
7114
8038
  }
7115
8039
  /**
7116
8040
  * Get the current generational tag version for a tag (synced with Redis when due).
@@ -7173,19 +8097,23 @@ var CacheService = class _CacheService {
7173
8097
  const diskLowSpace = !this._diskDisabled && this.disk.hostVolumeLowSpace;
7174
8098
  const circuitOpen = this.cb.isOpen;
7175
8099
  const latencyBypass = watchdogTel.bypassActive;
7176
- const degraded = circuitOpen || latencyBypass || diskPruning || diskLowSpace;
7177
- const healthy = this.opts.failReadinessOnDegraded ? !degraded : true;
8100
+ const backplaneUnavailable = this.opts.invalidationBackplane && !this._redisDisabled && !this._backplaneAvailable;
8101
+ const degraded = this._destroyed || circuitOpen || latencyBypass || diskPruning || diskLowSpace || backplaneUnavailable;
8102
+ const healthy = !this._destroyed && (this.opts.failReadinessOnDegraded ? !degraded : true);
7178
8103
  const reasons = [];
7179
8104
  if (circuitOpen) reasons.push("redis_circuit_breaker_open");
7180
8105
  if (latencyBypass) reasons.push(`disk_latency_bypass_stage_${watchdogTel.bypassStage}`);
7181
8106
  if (diskPruning) reasons.push("disk_quota_watermark_pruning_active");
7182
8107
  if (diskLowSpace) reasons.push("disk_host_volume_low_space");
8108
+ if (backplaneUnavailable) reasons.push("invalidation_backplane_unavailable");
8109
+ if (this._destroyed) reasons.push("cache_destroyed");
7183
8110
  return {
7184
8111
  healthy,
7185
8112
  degraded,
7186
8113
  reasons,
7187
8114
  details: {
7188
- redisConnected: !circuitOpen && !this._redisDisabled,
8115
+ redisConnected: !this._destroyed && !circuitOpen && !!this.redis && (this.redis.status === "ready" || this.redis.isOpen === true),
8116
+ backplaneReady: this._backplaneAvailable,
7189
8117
  circuitBreakerState: this.cb.currentState,
7190
8118
  diskPruningActive: diskPruning,
7191
8119
  diskHostVolumeLowSpace: diskLowSpace,
@@ -7207,23 +8135,28 @@ var CacheService = class _CacheService {
7207
8135
  */
7208
8136
  async drainToL2() {
7209
8137
  this._assertActive("drainToL2");
7210
- if (this._redisDisabled) return 0;
8138
+ if (this._redisDisabled || this.opts.l2WriteMode === "read-only") return 0;
7211
8139
  try {
7212
- const client = await this.getRedis();
7213
8140
  const entries = this.l1.exportEntries([]);
7214
- const now = Date.now();
7215
8141
  if (entries.length === 0) return 0;
7216
- const pl = client.pipeline();
7217
- for (const { key, entry } of entries) {
7218
- const remainingMs = entry.expiresAt - now;
7219
- if (remainingMs <= 0) continue;
7220
- const ttlSecs = Math.max(1, Math.ceil(remainingMs / 1e3));
7221
- const s = JSON.stringify(entry.value);
7222
- const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
7223
- pl.setex(key, ttlSecs, stored);
7224
- }
7225
- await pl.exec();
7226
- return entries.length;
8142
+ let written = 0;
8143
+ await Promise.all(entries.map(async ({ key, entry }) => {
8144
+ const epoch = this._getKeyMutationEpoch(key);
8145
+ if (entry.expiresAt <= Date.now()) return;
8146
+ await this._writeRedisEntry(
8147
+ key,
8148
+ this.l1.resolveValue(entry),
8149
+ entry.expiresAt,
8150
+ entry.setAt ?? Date.now(),
8151
+ entry.tagVersions,
8152
+ entry.staleAt,
8153
+ entry.tags,
8154
+ entry.dependsOn,
8155
+ () => this._getKeyMutationEpoch(key) === epoch
8156
+ );
8157
+ written++;
8158
+ }));
8159
+ return written;
7227
8160
  } catch (err) {
7228
8161
  this.logger.debug("drainToL2: Redis unavailable", { error: err.message });
7229
8162
  return 0;
@@ -7253,7 +8186,7 @@ var CacheService = class _CacheService {
7253
8186
  this._assertActive("setIfAbsent");
7254
8187
  const k = this.nk(cacheKey);
7255
8188
  if (this.l1.has(k)) return false;
7256
- if (!this._redisDisabled) {
8189
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7257
8190
  try {
7258
8191
  const client = await this.getRedis();
7259
8192
  const serialized = JSON.stringify(value);
@@ -7270,7 +8203,7 @@ var CacheService = class _CacheService {
7270
8203
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
7271
8204
  const p = priority ?? inferPriority(cacheKey);
7272
8205
  this._bumpKeyMutation(k);
7273
- this._pendingDiskDeletes.delete(k);
8206
+ this._invalidateDiskKey(k);
7274
8207
  this.l1.set(k, value, ttlMs, p);
7275
8208
  this.counters.sets++;
7276
8209
  return true;
@@ -7297,7 +8230,7 @@ var CacheService = class _CacheService {
7297
8230
  const token = import_crypto3.default.randomUUID();
7298
8231
  const deadline = Date.now() + acquireTimeout;
7299
8232
  let acquired = false;
7300
- if (!this._redisDisabled) {
8233
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
7301
8234
  let client = null;
7302
8235
  try {
7303
8236
  client = await this.getRedis();
@@ -7392,7 +8325,9 @@ var CacheService = class _CacheService {
7392
8325
  const gDiskFiles = meter.createObservableGauge("tricache.disk.files", { description: "Current L1.5 disk file count" });
7393
8326
  const gDiskBytes = meter.createObservableGauge("tricache.disk.bytes", { description: "Current L1.5 disk size in bytes" });
7394
8327
  const gBloomFpr = meter.createObservableGauge("tricache.bloom.fpr", { description: "Bloom filter false-positive rate" });
7395
- meter.addBatchObservableCallback((observableResult) => {
8328
+ const observables = [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr];
8329
+ const callback = (observableResult) => {
8330
+ if (this._destroyed) return;
7396
8331
  const stats = this.stats();
7397
8332
  const l1 = stats.l1;
7398
8333
  const disk = stats.disk;
@@ -7405,7 +8340,9 @@ var CacheService = class _CacheService {
7405
8340
  observableResult.observe(gDiskFiles, disk.files, attrs);
7406
8341
  observableResult.observe(gDiskBytes, disk.sizeKB * 1024, attrs);
7407
8342
  observableResult.observe(gBloomFpr, fpr, attrs);
7408
- }, [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr]);
8343
+ };
8344
+ meter.addBatchObservableCallback(callback, observables);
8345
+ this._otelCleanup = () => meter.removeBatchObservableCallback?.(callback, observables);
7409
8346
  } catch (err) {
7410
8347
  this.logger.warn("Failed to initialize OpenTelemetry metrics meter", { error: err.message });
7411
8348
  }
@@ -7675,8 +8612,25 @@ var CacheService = class _CacheService {
7675
8612
  /** Close Redis connections and stop all background timers. */
7676
8613
  async destroy() {
7677
8614
  this._destroyed = true;
8615
+ this._fenceInvalidation();
8616
+ this._backplaneAvailable = false;
8617
+ this.l1.clear();
8618
+ try {
8619
+ this._otelCleanup?.();
8620
+ } catch {
8621
+ }
8622
+ this._otelCleanup = null;
8623
+ this.tagVersions.clear();
8624
+ for (const dispose of this._backplaneDisposers.splice(0)) dispose();
7678
8625
  this._pendingDiskDeletes.clear();
7679
8626
  this._keyMutationEpochs.clear();
8627
+ this.inflight.clear();
8628
+ this.revalidating.clear();
8629
+ this._l1Counters.clear();
8630
+ this.tagIndex.clear();
8631
+ this.keyTags.clear();
8632
+ this.dependencyIndex.clear();
8633
+ this.keyDependencies.clear();
7680
8634
  const g = globalThis;
7681
8635
  const key = _CacheService.globalKey(this.opts);
7682
8636
  if (g[key] === this) {
@@ -7697,6 +8651,12 @@ var CacheService = class _CacheService {
7697
8651
  this._workerPool = null;
7698
8652
  }
7699
8653
  if (this.subClient) {
8654
+ if (this.opts.redisSubClient) {
8655
+ try {
8656
+ await this.subClient.unsubscribe?.(this.backplaneChannel);
8657
+ } catch {
8658
+ }
8659
+ }
7700
8660
  if (!this.opts.redisSubClient) {
7701
8661
  try {
7702
8662
  this.subClient.disconnect();
@@ -7706,7 +8666,7 @@ var CacheService = class _CacheService {
7706
8666
  this.subClient = null;
7707
8667
  }
7708
8668
  if (this.streamClient) {
7709
- try {
8669
+ if (!this.opts.redisSubClient) try {
7710
8670
  this.streamClient.disconnect();
7711
8671
  } catch {
7712
8672
  }
@@ -7743,18 +8703,21 @@ var CacheService = class _CacheService {
7743
8703
  };
7744
8704
 
7745
8705
  // src/nestjs/tricache.store.ts
7746
- var TriCacheStore = class {
8706
+ var import_node_events = require("events");
8707
+ var TriCacheStore = class extends import_node_events.EventEmitter {
7747
8708
  constructor(cache) {
8709
+ super();
7748
8710
  this.cache = cache;
7749
8711
  }
7750
8712
  cache;
7751
- /**
7752
- * Retrieve an item from the cache.
7753
- * Returns undefined on miss (matching cache-manager v5/v6 contract).
7754
- */
7755
- async get(key) {
8713
+ async get(key, options) {
7756
8714
  const val = await this.cache.peek(key);
7757
- return val !== null ? val : void 0;
8715
+ if (val === null) return void 0;
8716
+ if (options?.raw) {
8717
+ const remaining = this.cache.ttl(key);
8718
+ return { value: val, expires: remaining === null ? void 0 : Date.now() + remaining * 1e3 };
8719
+ }
8720
+ return val;
7758
8721
  }
7759
8722
  /**
7760
8723
  * Set an item in the cache.
@@ -7763,48 +8726,49 @@ var TriCacheStore = class {
7763
8726
  * @param ttl - TTL in milliseconds (0 = indefinite / default engine TTL)
7764
8727
  */
7765
8728
  async set(key, value, ttl) {
7766
- const ttlSeconds = typeof ttl === "number" && ttl > 0 ? Math.round(ttl / 1e3) : ttl === 0 ? 0 : void 0;
8729
+ const ttlSeconds = typeof ttl === "number" && ttl > 0 ? ttl / 1e3 : ttl === 0 ? 0 : void 0;
7767
8730
  await this.cache.set(key, value, ttlSeconds);
8731
+ return value;
7768
8732
  }
7769
8733
  /**
7770
8734
  * Remove an item from the cache.
7771
8735
  */
7772
8736
  async del(key) {
7773
8737
  await this.cache.delete(key);
8738
+ return true;
7774
8739
  }
7775
8740
  /**
7776
8741
  * Clear the entire cache namespace.
7777
8742
  */
7778
8743
  async reset() {
7779
8744
  await this.cache.clear();
8745
+ return true;
7780
8746
  }
7781
- /**
7782
- * Batch get multiple items from the cache.
7783
- */
7784
- async mget(...keys) {
8747
+ async mget(keysOrFirst = [], ...rest) {
8748
+ const keys = Array.isArray(keysOrFirst) ? keysOrFirst : [keysOrFirst, ...rest];
7785
8749
  if (keys.length === 0) return [];
7786
- return this.cache.mget(keys, async () => ({}));
8750
+ return this.cache.mget(keys);
7787
8751
  }
7788
8752
  /**
7789
8753
  * Batch set multiple entries with per-entry millisecond TTL.
7790
8754
  */
7791
8755
  async mset(entries) {
7792
- if (entries.length === 0) return;
8756
+ if (entries.length === 0) return [];
7793
8757
  const batch = {};
7794
8758
  for (const e of entries) {
7795
8759
  batch[e.key] = {
7796
8760
  value: e.value,
7797
- ttl: typeof e.ttl === "number" && e.ttl > 0 ? Math.round(e.ttl / 1e3) : e.ttl === 0 ? 0 : void 0
8761
+ ttl: typeof e.ttl === "number" && e.ttl > 0 ? e.ttl / 1e3 : e.ttl === 0 ? 0 : void 0
7798
8762
  };
7799
8763
  }
7800
8764
  await this.cache.mset(batch);
8765
+ return entries;
7801
8766
  }
7802
- /**
7803
- * Batch delete multiple keys.
7804
- */
7805
- async mdel(...keys) {
7806
- if (keys.length === 0) return;
8767
+ async mdel(keysOrFirst = [], ...rest) {
8768
+ const keys = Array.isArray(keysOrFirst) ? keysOrFirst : [keysOrFirst, ...rest];
8769
+ if (keys.length === 0) return true;
7807
8770
  await this.cache.mdel(keys);
8771
+ return true;
7808
8772
  }
7809
8773
  /**
7810
8774
  * Scan keys currently resident in the cache.
@@ -7823,6 +8787,24 @@ var TriCacheStore = class {
7823
8787
  const rem = this.cache.ttl(key);
7824
8788
  return rem !== null ? rem * 1e3 : void 0;
7825
8789
  }
8790
+ async wrap(key, fetch, ttl, refreshThreshold) {
8791
+ const seconds = ttl === void 0 ? 0 : ttl / 1e3;
8792
+ const refreshAhead = ttl && refreshThreshold ? Math.max(0, Math.min(1, (ttl - refreshThreshold) / ttl)) : void 0;
8793
+ return this.cache.wrap(key, async () => await fetch(), { ttl: seconds, refreshAhead });
8794
+ }
8795
+ cacheId() {
8796
+ return `tricache:${this.cache.options.namespace ?? "default"}`;
8797
+ }
8798
+ get stores() {
8799
+ return [this];
8800
+ }
8801
+ async clear() {
8802
+ await this.reset();
8803
+ return true;
8804
+ }
8805
+ async disconnect() {
8806
+ return void 0;
8807
+ }
7826
8808
  };
7827
8809
 
7828
8810
  // src/nestjs/types.ts
@@ -7834,17 +8816,17 @@ var TriCacheModule = class _TriCacheModule {
7834
8816
  /**
7835
8817
  * Register TriCache module synchronously with static configuration options.
7836
8818
  */
7837
- static register(options = {}) {
8819
+ static register(options = {}, moduleOptions = {}) {
7838
8820
  const cache = CacheService.create(options);
7839
- const store = new TriCacheStore(cache);
8821
+ const provideCacheManager = moduleOptions.provideCacheManager ?? true;
7840
8822
  return {
7841
8823
  module: _TriCacheModule,
7842
8824
  global: true,
7843
8825
  providers: [
7844
8826
  { provide: TRICACHE_SERVICE, useValue: cache },
7845
- { provide: CACHE_MANAGER, useValue: store }
8827
+ ...provideCacheManager ? [{ provide: CACHE_MANAGER, useValue: new TriCacheStore(cache) }] : []
7846
8828
  ],
7847
- exports: [TRICACHE_SERVICE, CACHE_MANAGER]
8829
+ exports: [TRICACHE_SERVICE, ...provideCacheManager ? [CACHE_MANAGER] : []]
7848
8830
  };
7849
8831
  }
7850
8832
  /**
@@ -7852,20 +8834,21 @@ var TriCacheModule = class _TriCacheModule {
7852
8834
  */
7853
8835
  static registerAsync(asyncOptions) {
7854
8836
  const asyncProviders = this.createAsyncProviders(asyncOptions);
8837
+ const provideCacheManager = asyncOptions.provideCacheManager ?? true;
7855
8838
  return {
7856
8839
  module: _TriCacheModule,
7857
8840
  global: true,
7858
8841
  imports: asyncOptions.imports || [],
7859
8842
  providers: [
7860
8843
  ...asyncProviders,
7861
- {
8844
+ ...provideCacheManager ? [{
7862
8845
  provide: CACHE_MANAGER,
7863
8846
  useFactory: (cache) => new TriCacheStore(cache),
7864
8847
  inject: [TRICACHE_SERVICE]
7865
- },
8848
+ }] : [],
7866
8849
  ...asyncOptions.extraProviders || []
7867
8850
  ],
7868
- exports: [TRICACHE_SERVICE, CACHE_MANAGER]
8851
+ exports: [TRICACHE_SERVICE, ...provideCacheManager ? [CACHE_MANAGER] : []]
7869
8852
  };
7870
8853
  }
7871
8854
  static createAsyncProviders(options) {
@@ -7906,6 +8889,65 @@ var TriCacheModule = class _TriCacheModule {
7906
8889
  }
7907
8890
  };
7908
8891
 
8892
+ // src/nestjs/keyv-adapter.ts
8893
+ var import_node_events2 = require("events");
8894
+ var TriCacheKeyvAdapter = class extends import_node_events2.EventEmitter {
8895
+ constructor(cache) {
8896
+ super();
8897
+ this.cache = cache;
8898
+ }
8899
+ cache;
8900
+ _namespace;
8901
+ get namespace() {
8902
+ return this._namespace;
8903
+ }
8904
+ set namespace(value) {
8905
+ if (value && ["*", "?", "[", "]", "\\"].some((character) => value.includes(character))) {
8906
+ throw new Error("Keyv namespace must not contain glob characters");
8907
+ }
8908
+ this._namespace = value;
8909
+ }
8910
+ async get(key) {
8911
+ const value = await this.cache.peek(key);
8912
+ return value === null ? void 0 : value;
8913
+ }
8914
+ async set(key, value, ttl) {
8915
+ if (ttl !== void 0 && (!Number.isFinite(ttl) || ttl < 0)) throw new Error("Keyv TTL must be finite and non-negative");
8916
+ const ttlSeconds = ttl === void 0 ? 0 : ttl / 1e3;
8917
+ await this.cache.set(key, value, ttlSeconds);
8918
+ return true;
8919
+ }
8920
+ async delete(key) {
8921
+ const found = await this.has(key);
8922
+ await this.cache.delete(key);
8923
+ return found;
8924
+ }
8925
+ async clear() {
8926
+ await this.cache.clear(this._namespace ? `${this._namespace}:` : void 0);
8927
+ }
8928
+ async has(key) {
8929
+ return await this.cache.peek(key) !== null;
8930
+ }
8931
+ async getMany(keys) {
8932
+ return this.cache.mget(keys);
8933
+ }
8934
+ async deleteMany(keys) {
8935
+ const found = await this.cache.mget(keys);
8936
+ await this.cache.mdel(keys);
8937
+ return found.every((value) => value !== void 0 && value !== null);
8938
+ }
8939
+ async setMany(entries) {
8940
+ const results = await Promise.all(entries.map((entry) => this.set(entry.key, entry.value, entry.ttl)));
8941
+ return results;
8942
+ }
8943
+ async hasMany(keys) {
8944
+ const values = await this.cache.mget(keys);
8945
+ return values.map((value) => value !== null && value !== void 0);
8946
+ }
8947
+ async disconnect() {
8948
+ }
8949
+ };
8950
+
7909
8951
  // src/nestjs/decorators.ts
7910
8952
  function resolveCacheInstance(ctx) {
7911
8953
  return ctx?.cacheService || ctx?.cache || ctx?.cacheStore?.cache || CacheService.create();
@@ -7925,7 +8967,7 @@ function Cacheable(options = {}) {
7925
8967
  const rawTtl = options.ttl;
7926
8968
  if (typeof rawTtl === "number") {
7927
8969
  if (options.ttlUnit === "milliseconds" || rawTtl >= 1e3 && rawTtl % 1e3 === 0 && options.ttlUnit !== "seconds") {
7928
- ttlSeconds = Math.round(rawTtl / 1e3);
8970
+ ttlSeconds = rawTtl / 1e3;
7929
8971
  }
7930
8972
  }
7931
8973
  const tags = typeof options.tags === "function" ? options.tags(...args) : options.tags;
@@ -7983,6 +9025,7 @@ var nestjs_default = TriCacheModule;
7983
9025
  CacheEvict,
7984
9026
  Cacheable,
7985
9027
  TRICACHE_SERVICE,
9028
+ TriCacheKeyvAdapter,
7986
9029
  TriCacheModule,
7987
9030
  TriCacheStore
7988
9031
  });