tricache 1.0.1 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +36 -28
- package/dist/{cache-service-CREOp7MM.d.ts → cache-service-B108FzER.d.ts} +36 -4
- package/dist/cache-service-CWI4jkS7.d.cts +963 -0
- package/dist/{cache-service-MG7PN6MX.js → cache-service-GYPZFB7O.js} +2 -2
- package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
- package/dist/{chunk-2AJKEQMZ.js → chunk-H4GFLQ26.js} +7 -4
- package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
- package/dist/chunk-OYDU3SMI.js +89 -0
- package/dist/{chunk-3I5L7K6I.js → chunk-VNRDL5RA.js} +102 -140
- package/dist/{chunk-JYQFQJNJ.js → chunk-WYF7NOAT.js} +1443 -609
- package/dist/cli.cjs +1367 -625
- package/dist/cli.d.cts +12 -0
- package/dist/cli.js +27 -6
- package/dist/dashboard/index.cjs +111 -29
- package/dist/dashboard/index.d.cts +185 -0
- package/dist/dashboard/index.d.ts +5 -3
- package/dist/dashboard/index.js +1 -1
- package/dist/drizzle/index.cjs +1370 -624
- package/dist/drizzle/index.d.cts +46 -0
- package/dist/drizzle/index.d.ts +2 -2
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +227 -123
- package/dist/edge/index.d.cts +127 -0
- package/dist/edge/index.d.ts +3 -3
- package/dist/edge/index.js +201 -117
- package/dist/hono/index.cjs +1418 -644
- package/dist/hono/index.d.cts +93 -0
- package/dist/hono/index.d.ts +7 -5
- package/dist/hono/index.js +16 -9
- package/dist/{hono-DSV2ve66.d.ts → hono-3rDMYVtY.d.ts} +16 -3
- package/dist/hono-C886ok3X.d.cts +391 -0
- package/dist/http/index.cjs +1514 -679
- package/dist/http/index.d.cts +103 -0
- package/dist/http/index.d.ts +13 -5
- package/dist/http/index.js +92 -43
- package/dist/index.cjs +1671 -790
- package/dist/index.d.cts +1006 -0
- package/dist/index.d.ts +39 -8
- package/dist/index.js +8 -8
- package/dist/murmur3-CMGw9PbV.d.cts +98 -0
- package/dist/nestjs/index.cjs +1454 -649
- package/dist/nestjs/index.d.cts +285 -0
- package/dist/nestjs/index.d.ts +103 -30
- package/dist/nestjs/index.js +115 -32
- package/dist/next/index.cjs +1512 -718
- package/dist/next/index.d.cts +232 -0
- package/dist/next/index.d.ts +33 -11
- package/dist/next/index.js +172 -99
- package/dist/prisma/index.cjs +11 -1
- package/dist/prisma/index.d.cts +62 -0
- package/dist/prisma/index.d.ts +2 -2
- package/dist/prisma/index.js +11 -1
- package/dist/serialize-worker.d.cts +2 -0
- package/dist/{types-Dyip5wAl.d.ts → types-BA4pz1A0.d.cts} +24 -9
- package/dist/types-BA4pz1A0.d.ts +1519 -0
- package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
- package/dist/utils-Bvzn-rKS.d.ts +29 -0
- package/package.json +96 -36
- package/src/adapters/auto-pipeliner.ts +107 -24
- package/src/adapters/node-redis.ts +106 -27
- package/src/cache-service.ts +802 -502
- package/src/cli.ts +24 -6
- package/src/cross-region.ts +21 -3
- package/src/dashboard/handler.ts +26 -6
- package/src/dashboard/html.ts +35 -10
- package/src/dashboard/index.ts +35 -13
- package/src/dashboard/types.ts +3 -1
- package/src/disk-tier.ts +171 -65
- package/src/edge/cache.ts +145 -97
- package/src/edge/hono.ts +23 -6
- package/src/edge/types.ts +2 -0
- package/src/hono/index.ts +19 -9
- package/src/http/express.ts +62 -17
- package/src/http/fastify.ts +35 -21
- package/src/http/utils.ts +54 -20
- package/src/ipc-telemetry.ts +35 -9
- package/src/nestjs/decorators.ts +1 -1
- package/src/nestjs/index.ts +2 -0
- package/src/nestjs/keyv-adapter.ts +68 -0
- package/src/nestjs/tricache.module.ts +13 -11
- package/src/nestjs/tricache.store.ts +51 -20
- package/src/nestjs/types.ts +29 -15
- package/src/next/cache-handler.ts +131 -53
- package/src/next/index.ts +1 -0
- package/src/next/types.ts +21 -0
- package/src/prisma/index.ts +12 -1
- package/src/smart-memory-cache.ts +63 -26
- package/src/types.ts +25 -2
- package/src/utils/cgroup.ts +12 -0
- package/src/utils/deadline.ts +14 -0
- package/src/utils/diagnostics.ts +27 -0
- package/src/utils/redis-slot.ts +13 -0
- package/src/wasm/bloom-filter-wasm.ts +9 -4
- package/src/worker-pool.ts +17 -8
- package/src/wtiny-lfu.ts +20 -6
- package/dist/chunk-BQRURGGD.js +0 -60
package/dist/next/index.cjs
CHANGED
|
@@ -40,7 +40,7 @@ __export(next_exports, {
|
|
|
40
40
|
module.exports = __toCommonJS(next_exports);
|
|
41
41
|
|
|
42
42
|
// src/cache-service.ts
|
|
43
|
-
var
|
|
43
|
+
var import_ioredis2 = require("ioredis");
|
|
44
44
|
|
|
45
45
|
// src/codec.ts
|
|
46
46
|
var import_msgpackr = require("msgpackr");
|
|
@@ -75,6 +75,15 @@ var defaultCodec = new CacheCodec({
|
|
|
75
75
|
moreTypes: true
|
|
76
76
|
});
|
|
77
77
|
|
|
78
|
+
// src/cross-region.ts
|
|
79
|
+
var import_node_crypto = require("crypto");
|
|
80
|
+
function isCrossRegionInvalidationEvent(value) {
|
|
81
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
82
|
+
const event = value;
|
|
83
|
+
const text = (key, max) => typeof event[key] === "string" && event[key].length > 0 && event[key].length <= max;
|
|
84
|
+
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);
|
|
85
|
+
}
|
|
86
|
+
|
|
78
87
|
// src/cache-service.ts
|
|
79
88
|
var import_crypto3 = __toESM(require("crypto"), 1);
|
|
80
89
|
var import_os3 = __toESM(require("os"), 1);
|
|
@@ -101,7 +110,8 @@ try {
|
|
|
101
110
|
_workerFile = jsPath;
|
|
102
111
|
}
|
|
103
112
|
} catch {
|
|
104
|
-
|
|
113
|
+
const sibling = (0, import_path.join)(__dirname, "serialize-worker.js");
|
|
114
|
+
_workerFile = (0, import_fs.existsSync)(sibling) ? sibling : (0, import_path.join)((0, import_path.dirname)(__dirname), "serialize-worker.js");
|
|
105
115
|
}
|
|
106
116
|
function getTransferableArrayBuffer(buf) {
|
|
107
117
|
if (buf.buffer instanceof ArrayBuffer) {
|
|
@@ -134,6 +144,7 @@ var WorkerPool = class {
|
|
|
134
144
|
}
|
|
135
145
|
_spawnWorkers(opts) {
|
|
136
146
|
const size = Math.max(1, opts.size ?? Math.min(4, availableCpus()));
|
|
147
|
+
if (!Number.isInteger(size) || size > 32 || !(0, import_fs.existsSync)(_workerFile)) throw new Error("Worker pool unavailable or invalid worker count");
|
|
137
148
|
const workerData = {
|
|
138
149
|
keyBase64: opts.keyBase64,
|
|
139
150
|
mode: opts.mode,
|
|
@@ -147,7 +158,8 @@ var WorkerPool = class {
|
|
|
147
158
|
const createWorker = (index) => {
|
|
148
159
|
const worker = new import_worker_threads.Worker(_workerFile, {
|
|
149
160
|
workerData,
|
|
150
|
-
execArgv: _workerExecArgv
|
|
161
|
+
execArgv: _workerExecArgv
|
|
162
|
+
// Do not inherit --input-type/eval or application loader flags.
|
|
151
163
|
});
|
|
152
164
|
const pending = pendingList[index] ?? /* @__PURE__ */ new Map();
|
|
153
165
|
if (!pendingList[index]) pendingList[index] = pending;
|
|
@@ -177,7 +189,7 @@ var WorkerPool = class {
|
|
|
177
189
|
}
|
|
178
190
|
pending.clear();
|
|
179
191
|
worker.unref();
|
|
180
|
-
if (this._available &&
|
|
192
|
+
if (this._available && this.workers === workers && workers[index] === worker) {
|
|
181
193
|
try {
|
|
182
194
|
workers[index] = createWorker(index);
|
|
183
195
|
} catch {
|
|
@@ -187,9 +199,12 @@ var WorkerPool = class {
|
|
|
187
199
|
worker.unref();
|
|
188
200
|
return worker;
|
|
189
201
|
};
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
202
|
+
try {
|
|
203
|
+
for (let i = 0; i < size; i++) workers.push(createWorker(i));
|
|
204
|
+
} catch (error) {
|
|
205
|
+
for (const worker of workers) void worker.terminate().catch(() => {
|
|
206
|
+
});
|
|
207
|
+
throw error;
|
|
193
208
|
}
|
|
194
209
|
return { workers, pending: pendingList };
|
|
195
210
|
}
|
|
@@ -216,7 +231,7 @@ var WorkerPool = class {
|
|
|
216
231
|
entry.reject(new Error("WorkerPool replaced during key rotation"));
|
|
217
232
|
}
|
|
218
233
|
oldPending[i]?.clear();
|
|
219
|
-
oldWorkers[i]?.terminate().catch(() => {
|
|
234
|
+
await oldWorkers[i]?.terminate().catch(() => {
|
|
220
235
|
});
|
|
221
236
|
}
|
|
222
237
|
}
|
|
@@ -258,7 +273,13 @@ var WorkerPool = class {
|
|
|
258
273
|
return new Promise((resolve, reject) => {
|
|
259
274
|
pending.set(id, { resolve, reject });
|
|
260
275
|
worker.ref();
|
|
261
|
-
|
|
276
|
+
try {
|
|
277
|
+
worker.postMessage({ id, type, payload: dataToSend }, transferList);
|
|
278
|
+
} catch (error) {
|
|
279
|
+
pending.delete(id);
|
|
280
|
+
if (pending.size === 0) worker.unref();
|
|
281
|
+
reject(error);
|
|
282
|
+
}
|
|
262
283
|
});
|
|
263
284
|
}
|
|
264
285
|
/** Terminate all worker threads. In-flight promises are rejected. */
|
|
@@ -769,8 +790,9 @@ var EnvelopeEncryption = class {
|
|
|
769
790
|
|
|
770
791
|
// src/wtiny-lfu.ts
|
|
771
792
|
var WTinyLfuPolicy = class {
|
|
772
|
-
constructor(capacity, sketch, windowPercent = 0.01, protectedPercent = 0.8) {
|
|
793
|
+
constructor(capacity, sketch, windowPercent = 0.01, protectedPercent = 0.8, canEvict) {
|
|
773
794
|
this.sketch = sketch;
|
|
795
|
+
this.canEvict = canEvict;
|
|
774
796
|
this.maxTotal = Math.max(2, capacity);
|
|
775
797
|
this.maxWindow = Math.max(1, Math.floor(this.maxTotal * windowPercent));
|
|
776
798
|
const mainCapacity = Math.max(1, this.maxTotal - this.maxWindow);
|
|
@@ -778,6 +800,7 @@ var WTinyLfuPolicy = class {
|
|
|
778
800
|
this.maxProbation = Math.max(1, mainCapacity - this.maxProtected);
|
|
779
801
|
}
|
|
780
802
|
sketch;
|
|
803
|
+
canEvict;
|
|
781
804
|
maxTotal;
|
|
782
805
|
maxWindow;
|
|
783
806
|
maxProtected;
|
|
@@ -857,15 +880,33 @@ var WTinyLfuPolicy = class {
|
|
|
857
880
|
}
|
|
858
881
|
let victimKey;
|
|
859
882
|
let victimIsProbation = true;
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
883
|
+
for (const candidate of this.probation) {
|
|
884
|
+
if (!this.canEvict || this.canEvict(candidate)) {
|
|
885
|
+
victimKey = candidate;
|
|
886
|
+
break;
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
if (victimKey === void 0) {
|
|
890
|
+
for (const candidate of this.protected_) {
|
|
891
|
+
if (!this.canEvict || this.canEvict(candidate)) {
|
|
892
|
+
victimKey = candidate;
|
|
893
|
+
break;
|
|
894
|
+
}
|
|
895
|
+
}
|
|
864
896
|
victimIsProbation = false;
|
|
865
897
|
}
|
|
898
|
+
if (victimKey === void 0) {
|
|
899
|
+
if (this.canEvict && !this.canEvict(candKey)) {
|
|
900
|
+
this.window.delete(key);
|
|
901
|
+
this.window.add(candKey);
|
|
902
|
+
return { admit: false, candidateKey: key };
|
|
903
|
+
}
|
|
904
|
+
this.rejectionCount++;
|
|
905
|
+
return { admit: false, candidateKey: candKey };
|
|
906
|
+
}
|
|
866
907
|
const candFreq = this.sketch.estimate(candKey);
|
|
867
908
|
const victimFreq = this.sketch.estimate(victimKey);
|
|
868
|
-
if (candFreq > victimFreq) {
|
|
909
|
+
if (this.canEvict && !this.canEvict(candKey) || candFreq > victimFreq) {
|
|
869
910
|
if (victimIsProbation) {
|
|
870
911
|
this.probation.delete(victimKey);
|
|
871
912
|
} else {
|
|
@@ -939,9 +980,12 @@ function base64ToUint8Array(base64) {
|
|
|
939
980
|
var BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
|
|
940
981
|
var KEY_STAGING_OFFSET = 2e4;
|
|
941
982
|
var MAX_KEY_BYTES = 512;
|
|
942
|
-
var
|
|
943
|
-
|
|
944
|
-
|
|
983
|
+
var bloomWasmModule;
|
|
984
|
+
function getBloomWasmModule() {
|
|
985
|
+
return bloomWasmModule ??= new WebAssembly.Module(
|
|
986
|
+
base64ToUint8Array(BLOOM_WASM_BASE64)
|
|
987
|
+
);
|
|
988
|
+
}
|
|
945
989
|
var WasmBloomFilter = class {
|
|
946
990
|
exports;
|
|
947
991
|
mem;
|
|
@@ -953,7 +997,7 @@ var WasmBloomFilter = class {
|
|
|
953
997
|
/** Tracks total add() calls so we know when phantom bits have saturated the filter. */
|
|
954
998
|
_insertionCount = 0;
|
|
955
999
|
constructor() {
|
|
956
|
-
const instance = new WebAssembly.Instance(
|
|
1000
|
+
const instance = new WebAssembly.Instance(getBloomWasmModule(), {});
|
|
957
1001
|
this.exports = instance.exports;
|
|
958
1002
|
this.mem = new Uint8Array(this.exports.memory.buffer);
|
|
959
1003
|
this.stagingTarget = new Uint8Array(this.exports.memory.buffer, KEY_STAGING_OFFSET, MAX_KEY_BYTES);
|
|
@@ -1085,8 +1129,9 @@ var JsBloomFilter = class {
|
|
|
1085
1129
|
};
|
|
1086
1130
|
function createBloomFilter(logger, maxEntries) {
|
|
1087
1131
|
const LN2_SQ = Math.LN2 * Math.LN2;
|
|
1088
|
-
const
|
|
1089
|
-
const
|
|
1132
|
+
const capacity = Math.max(1, maxEntries);
|
|
1133
|
+
const optimalBits = Math.ceil(-capacity * Math.log(0.01) / LN2_SQ);
|
|
1134
|
+
const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / capacity)));
|
|
1090
1135
|
try {
|
|
1091
1136
|
const wasm = new WasmBloomFilter();
|
|
1092
1137
|
if (wasm.maxCapacity >= maxEntries) {
|
|
@@ -1210,7 +1255,10 @@ var SmartMemoryCache = class {
|
|
|
1210
1255
|
this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
|
|
1211
1256
|
this.categoryPrefixes = Object.keys(opts.categories).filter((k) => k !== "default");
|
|
1212
1257
|
if (opts.admissionPolicy === "wtinylfu") {
|
|
1213
|
-
this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch)
|
|
1258
|
+
this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch, 0.01, 0.8, (key) => {
|
|
1259
|
+
const entry = this.cache.get(key);
|
|
1260
|
+
return !entry || entry.priority !== 4 || entry.expiresAt <= Date.now();
|
|
1261
|
+
});
|
|
1214
1262
|
}
|
|
1215
1263
|
if (existing) {
|
|
1216
1264
|
for (const [k, v] of existing) this.cache.set(k, v);
|
|
@@ -1289,6 +1337,7 @@ var SmartMemoryCache = class {
|
|
|
1289
1337
|
const MAX_EVICT_PASSES = 64;
|
|
1290
1338
|
let passes = 0;
|
|
1291
1339
|
do {
|
|
1340
|
+
const before = this.cache.size;
|
|
1292
1341
|
this.smartEvict(category, catOvf);
|
|
1293
1342
|
const lim2 = this.getCategoryLimit(category);
|
|
1294
1343
|
const catCnt2 = this.categoryCount.get(category) ?? 0;
|
|
@@ -1296,6 +1345,7 @@ var SmartMemoryCache = class {
|
|
|
1296
1345
|
catOvf = catCnt2 >= lim2.maxEntries || catSz2 + neededSize > lim2.maxSizeBytes;
|
|
1297
1346
|
glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
|
|
1298
1347
|
passes++;
|
|
1348
|
+
if (this.cache.size === before) break;
|
|
1299
1349
|
} while ((catOvf || glbOvf) && passes < MAX_EVICT_PASSES);
|
|
1300
1350
|
}
|
|
1301
1351
|
score(entry, catBonus, now, key) {
|
|
@@ -1426,20 +1476,26 @@ var SmartMemoryCache = class {
|
|
|
1426
1476
|
delta: entry.delta,
|
|
1427
1477
|
fetchedAt: now,
|
|
1428
1478
|
tagVersions: entry.tagVersions,
|
|
1429
|
-
setAt: entry.setAt
|
|
1479
|
+
setAt: entry.setAt,
|
|
1480
|
+
tags: entry.tags,
|
|
1481
|
+
dependsOn: entry.dependsOn
|
|
1430
1482
|
};
|
|
1431
1483
|
return hit;
|
|
1432
1484
|
}
|
|
1433
|
-
set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions, setAt) {
|
|
1485
|
+
set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions, setAt, tags, dependsOn) {
|
|
1434
1486
|
const packed = this.codec.encode(data);
|
|
1487
|
+
return this.storePacked(key, packed, data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn);
|
|
1488
|
+
}
|
|
1489
|
+
storePacked(key, packed, data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn) {
|
|
1435
1490
|
const size = packed.byteLength;
|
|
1436
1491
|
this.compressions++;
|
|
1437
1492
|
this.sketch.increment(key);
|
|
1438
1493
|
const cat = this.getCategory(key);
|
|
1439
1494
|
const lim = this.getCategoryLimit(cat);
|
|
1440
|
-
if (size > lim.maxSizeBytes * 0.5) {
|
|
1495
|
+
if (!Number.isFinite(ttlMs) || ttlMs <= 0 || this.opts.maxEntries <= 0 || lim.maxEntries <= 0 || size > this.opts.maxBytes || size > lim.maxSizeBytes * 0.5) {
|
|
1496
|
+
this.delete(key);
|
|
1441
1497
|
this.opts.logger.debug("SmartMemoryCache: entry too large, skipping", { key, sizeBytes: size });
|
|
1442
|
-
return;
|
|
1498
|
+
return false;
|
|
1443
1499
|
}
|
|
1444
1500
|
const existingEntry = this.cache.get(key);
|
|
1445
1501
|
if (existingEntry) {
|
|
@@ -1468,10 +1524,12 @@ var SmartMemoryCache = class {
|
|
|
1468
1524
|
ttlMs,
|
|
1469
1525
|
delta,
|
|
1470
1526
|
setAt: setAt ?? now2,
|
|
1471
|
-
tagVersions
|
|
1527
|
+
tagVersions,
|
|
1528
|
+
tags,
|
|
1529
|
+
dependsOn
|
|
1472
1530
|
});
|
|
1473
1531
|
}
|
|
1474
|
-
return;
|
|
1532
|
+
return false;
|
|
1475
1533
|
} else if (decision.candidateKey) {
|
|
1476
1534
|
const candEntry = this.cache.get(decision.candidateKey);
|
|
1477
1535
|
if (candEntry && this.opts.diskSpill) {
|
|
@@ -1487,15 +1545,19 @@ var SmartMemoryCache = class {
|
|
|
1487
1545
|
this._delete(decision.evictKey, "capacity");
|
|
1488
1546
|
}
|
|
1489
1547
|
const catSz = this.categorySize.get(cat) ?? 0;
|
|
1490
|
-
if (catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
|
|
1548
|
+
if ((this.categoryCount.get(cat) ?? 0) >= lim.maxEntries || this.cache.size >= this.opts.maxEntries || catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
|
|
1491
1549
|
this.ensureCapacity(cat, size);
|
|
1492
1550
|
}
|
|
1493
1551
|
} else {
|
|
1494
1552
|
this.ensureCapacity(cat, size);
|
|
1495
1553
|
}
|
|
1554
|
+
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) {
|
|
1555
|
+
this.wtinyPolicy?.onDelete(key);
|
|
1556
|
+
return false;
|
|
1557
|
+
}
|
|
1496
1558
|
const now = Date.now();
|
|
1497
1559
|
const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
|
|
1498
|
-
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 });
|
|
1560
|
+
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 });
|
|
1499
1561
|
if (!existingEntry) this.bloom.add(key);
|
|
1500
1562
|
this.maybeRebuildBloom();
|
|
1501
1563
|
this.totalSize += size;
|
|
@@ -1507,6 +1569,7 @@ var SmartMemoryCache = class {
|
|
|
1507
1569
|
this.categoryKeys.set(cat, ks);
|
|
1508
1570
|
}
|
|
1509
1571
|
ks.add(key);
|
|
1572
|
+
return true;
|
|
1510
1573
|
}
|
|
1511
1574
|
delete(key) {
|
|
1512
1575
|
const deleted = this._delete(key, "manual");
|
|
@@ -1708,25 +1771,48 @@ var SmartMemoryCache = class {
|
|
|
1708
1771
|
if (entry.expiresAt <= now) continue;
|
|
1709
1772
|
if (entry.priority === 4) continue;
|
|
1710
1773
|
if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
|
|
1711
|
-
|
|
1774
|
+
const { value: _value, ...stored } = entry;
|
|
1775
|
+
out.push({ key, entry: { ...stored } });
|
|
1712
1776
|
}
|
|
1713
1777
|
return out;
|
|
1714
1778
|
}
|
|
1715
1779
|
importEntries(entries, forbiddenPrefixes) {
|
|
1716
1780
|
const now = Date.now();
|
|
1717
1781
|
let loaded = 0;
|
|
1718
|
-
for (const
|
|
1719
|
-
if (
|
|
1782
|
+
for (const item of entries) {
|
|
1783
|
+
if (!item || typeof item.key !== "string" || !item.entry) continue;
|
|
1784
|
+
const { key, entry } = item;
|
|
1785
|
+
if (!Number.isFinite(entry.expiresAt) || entry.expiresAt <= now) continue;
|
|
1720
1786
|
if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
|
|
1721
1787
|
if (this.cache.has(key)) continue;
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1788
|
+
try {
|
|
1789
|
+
const rawData = entry.data;
|
|
1790
|
+
const data = !entry.isCompressed ? this.codec.encode(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : null;
|
|
1791
|
+
if (!data) continue;
|
|
1792
|
+
const value = data.length <= LARGE_VALUE_BYTES ? this.codec.decode(data) : void 0;
|
|
1793
|
+
if (this.storePacked(
|
|
1794
|
+
key,
|
|
1795
|
+
data,
|
|
1796
|
+
value,
|
|
1797
|
+
entry.expiresAt - now,
|
|
1798
|
+
entry.priority,
|
|
1799
|
+
entry.staleAt,
|
|
1800
|
+
entry.delta,
|
|
1801
|
+
entry.tagVersions,
|
|
1802
|
+
entry.setAt,
|
|
1803
|
+
entry.tags,
|
|
1804
|
+
entry.dependsOn
|
|
1805
|
+
)) {
|
|
1806
|
+
const restored = this.cache.get(key);
|
|
1807
|
+
restored.expiresAt = entry.expiresAt;
|
|
1808
|
+
restored.ttlMs = entry.ttlMs ?? entry.expiresAt - now;
|
|
1809
|
+
restored.hits = Number.isFinite(entry.hits) ? Math.max(1, entry.hits) : 1;
|
|
1810
|
+
restored.lastAccess = Number.isFinite(entry.lastAccess) ? entry.lastAccess : now;
|
|
1811
|
+
loaded++;
|
|
1812
|
+
}
|
|
1813
|
+
} catch {
|
|
1814
|
+
}
|
|
1815
|
+
}
|
|
1730
1816
|
return loaded;
|
|
1731
1817
|
}
|
|
1732
1818
|
// ── Iterators ─────────────────────────────────────────────────────────────
|
|
@@ -2090,6 +2176,9 @@ var BoundedDiskQueue = class {
|
|
|
2090
2176
|
this.writeTimeoutMs = writeTimeoutMs;
|
|
2091
2177
|
this.failureThreshold = failureThreshold;
|
|
2092
2178
|
this.cooldownMs = cooldownMs;
|
|
2179
|
+
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) {
|
|
2180
|
+
throw new Error("Disk queue limits and timeout must be finite positive values (pending/cooldown may be zero)");
|
|
2181
|
+
}
|
|
2093
2182
|
}
|
|
2094
2183
|
maxConcurrent;
|
|
2095
2184
|
maxPending;
|
|
@@ -2102,6 +2191,17 @@ var BoundedDiskQueue = class {
|
|
|
2102
2191
|
consecutiveFailures = 0;
|
|
2103
2192
|
circuitState = "closed";
|
|
2104
2193
|
lastStateChangeMonotonic = performance.now();
|
|
2194
|
+
get isSaturated() {
|
|
2195
|
+
return this.active >= this.maxConcurrent && this.queue.length >= this.maxPending;
|
|
2196
|
+
}
|
|
2197
|
+
releaseSlot() {
|
|
2198
|
+
if (this.circuitState === "open") {
|
|
2199
|
+
for (const next2 of this.queue.splice(0)) next2(false);
|
|
2200
|
+
}
|
|
2201
|
+
const next = this.queue.shift();
|
|
2202
|
+
if (next) next(true);
|
|
2203
|
+
else this.active--;
|
|
2204
|
+
}
|
|
2105
2205
|
async schedule(task) {
|
|
2106
2206
|
const now = performance.now();
|
|
2107
2207
|
if (this.circuitState === "open") {
|
|
@@ -2117,18 +2217,25 @@ var BoundedDiskQueue = class {
|
|
|
2117
2217
|
this.spillsDropped++;
|
|
2118
2218
|
return null;
|
|
2119
2219
|
}
|
|
2120
|
-
if (this.
|
|
2220
|
+
if (this.isSaturated) {
|
|
2121
2221
|
this.spillsDropped++;
|
|
2122
2222
|
return null;
|
|
2123
2223
|
}
|
|
2124
2224
|
if (this.active >= this.maxConcurrent) {
|
|
2125
|
-
await new Promise((resolve) => this.queue.push(resolve));
|
|
2225
|
+
const admitted = await new Promise((resolve) => this.queue.push(resolve));
|
|
2226
|
+
if (!admitted) {
|
|
2227
|
+
this.spillsDropped++;
|
|
2228
|
+
return null;
|
|
2229
|
+
}
|
|
2230
|
+
} else {
|
|
2231
|
+
this.active++;
|
|
2126
2232
|
}
|
|
2127
|
-
this.active++;
|
|
2128
2233
|
let timeoutId = null;
|
|
2234
|
+
const work = Promise.resolve().then(task);
|
|
2235
|
+
void work.then(() => this.releaseSlot(), () => this.releaseSlot());
|
|
2129
2236
|
try {
|
|
2130
2237
|
const result = await Promise.race([
|
|
2131
|
-
|
|
2238
|
+
work,
|
|
2132
2239
|
new Promise((_, reject) => {
|
|
2133
2240
|
timeoutId = setTimeout(
|
|
2134
2241
|
() => reject(new Error(`Disk write exceeded timeout of ${this.writeTimeoutMs}ms`)),
|
|
@@ -2147,14 +2254,12 @@ var BoundedDiskQueue = class {
|
|
|
2147
2254
|
if (this.consecutiveFailures >= this.failureThreshold || this.circuitState === "half-open") {
|
|
2148
2255
|
this.circuitState = "open";
|
|
2149
2256
|
this.lastStateChangeMonotonic = performance.now();
|
|
2257
|
+
for (const next of this.queue.splice(0)) next(false);
|
|
2150
2258
|
}
|
|
2151
2259
|
this.spillsDropped++;
|
|
2152
2260
|
return null;
|
|
2153
2261
|
} finally {
|
|
2154
2262
|
if (timeoutId) clearTimeout(timeoutId);
|
|
2155
|
-
this.active--;
|
|
2156
|
-
const next = this.queue.shift();
|
|
2157
|
-
if (next) next();
|
|
2158
2263
|
}
|
|
2159
2264
|
}
|
|
2160
2265
|
getStats() {
|
|
@@ -2228,6 +2333,13 @@ var DiskTier = class {
|
|
|
2228
2333
|
usageCounted = false;
|
|
2229
2334
|
fileCount = 0;
|
|
2230
2335
|
// maintained in-memory; avoids walkCacheFiles() in stats
|
|
2336
|
+
reservedBytes = 0;
|
|
2337
|
+
reservedFiles = 0;
|
|
2338
|
+
saveSequence = 0;
|
|
2339
|
+
epoch = 0;
|
|
2340
|
+
pendingSaves = /* @__PURE__ */ new Map();
|
|
2341
|
+
closed = false;
|
|
2342
|
+
invalidatedKeys = /* @__PURE__ */ new Set();
|
|
2231
2343
|
/** Next bucket index (0–255) for the staggered janitor wheel. */
|
|
2232
2344
|
_nextJanitorBucket = 0;
|
|
2233
2345
|
// ── High-watermark pruning & host volume health state ─────────────────────
|
|
@@ -2268,6 +2380,7 @@ var DiskTier = class {
|
|
|
2268
2380
|
}
|
|
2269
2381
|
// ── Helpers ───────────────────────────────────────────────────────────────
|
|
2270
2382
|
ensureDir() {
|
|
2383
|
+
if (this.closed) return;
|
|
2271
2384
|
if (this.dirReady) return;
|
|
2272
2385
|
try {
|
|
2273
2386
|
import_fs2.default.mkdirSync(this.opts.dir, { recursive: true, mode: 448 });
|
|
@@ -2389,8 +2502,24 @@ var DiskTier = class {
|
|
|
2389
2502
|
*
|
|
2390
2503
|
* 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
|
|
2391
2504
|
*/
|
|
2392
|
-
hashToWritePath(hash, expiresAt) {
|
|
2393
|
-
|
|
2505
|
+
hashToWritePath(hash, expiresAt, setAt) {
|
|
2506
|
+
const expiry = Math.floor(expiresAt).toString(16).padStart(12, "0");
|
|
2507
|
+
if (setAt === void 0) return import_path2.default.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}`);
|
|
2508
|
+
const written = Math.floor(setAt).toString(16).padStart(12, "0");
|
|
2509
|
+
const sequence = (++this.saveSequence).toString(16).padStart(12, "0");
|
|
2510
|
+
return import_path2.default.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}_${written}_${sequence}_${import_crypto2.default.randomBytes(6).toString("hex")}`);
|
|
2511
|
+
}
|
|
2512
|
+
findFilePaths(hash) {
|
|
2513
|
+
const bucket = import_path2.default.join(this.opts.dir, hash.slice(0, 2));
|
|
2514
|
+
try {
|
|
2515
|
+
return import_fs2.default.readdirSync(bucket).filter((file) => !file.endsWith(".tmp") && (file === hash || file.startsWith(hash + "_"))).map((file) => import_path2.default.join(bucket, file));
|
|
2516
|
+
} catch {
|
|
2517
|
+
return [];
|
|
2518
|
+
}
|
|
2519
|
+
}
|
|
2520
|
+
fileWrittenAt(file) {
|
|
2521
|
+
const parts = import_path2.default.basename(file).split("_");
|
|
2522
|
+
return parts.length >= 4 ? parseInt(parts[2], 16) : import_fs2.default.statSync(file).mtimeMs;
|
|
2394
2523
|
}
|
|
2395
2524
|
/**
|
|
2396
2525
|
* Find the on-disk file for a key hash, handling all filename generations:
|
|
@@ -2399,19 +2528,31 @@ var DiskTier = class {
|
|
|
2399
2528
|
* Returns null when the bucket dir does not exist or the key is absent.
|
|
2400
2529
|
*/
|
|
2401
2530
|
findFilePath(hash) {
|
|
2402
|
-
|
|
2403
|
-
let
|
|
2531
|
+
let match = null;
|
|
2532
|
+
let newest = -Infinity;
|
|
2533
|
+
let sequence = -1;
|
|
2534
|
+
for (const file of this.findFilePaths(hash)) {
|
|
2535
|
+
try {
|
|
2536
|
+
const written = this.fileWrittenAt(file);
|
|
2537
|
+
const order = parseInt(import_path2.default.basename(file).split("_")[3] ?? "0", 16);
|
|
2538
|
+
if (written > newest || written === newest && order > sequence) {
|
|
2539
|
+
match = file;
|
|
2540
|
+
newest = written;
|
|
2541
|
+
sequence = order;
|
|
2542
|
+
}
|
|
2543
|
+
} catch {
|
|
2544
|
+
}
|
|
2545
|
+
}
|
|
2546
|
+
return match;
|
|
2547
|
+
}
|
|
2548
|
+
removeFile(filePath) {
|
|
2404
2549
|
try {
|
|
2405
|
-
|
|
2550
|
+
const size = import_fs2.default.statSync(filePath).size;
|
|
2551
|
+
import_fs2.default.unlinkSync(filePath);
|
|
2552
|
+
this.diskUsageBytes = Math.max(0, this.diskUsageBytes - size);
|
|
2553
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2406
2554
|
} catch {
|
|
2407
|
-
return null;
|
|
2408
2555
|
}
|
|
2409
|
-
let match;
|
|
2410
|
-
for (const f of files) {
|
|
2411
|
-
if ((f === hash || f.startsWith(hash + "_")) && (!match || f > match)) match = f;
|
|
2412
|
-
}
|
|
2413
|
-
if (!match) return null;
|
|
2414
|
-
return import_path2.default.join(bucketPath, match);
|
|
2415
2556
|
}
|
|
2416
2557
|
/**
|
|
2417
2558
|
* Recursively list all cache file paths across the 2-level sharded subdirs.
|
|
@@ -2486,6 +2627,7 @@ var DiskTier = class {
|
|
|
2486
2627
|
* so the Node.js event loop is never stalled waiting for disk I/O.
|
|
2487
2628
|
*/
|
|
2488
2629
|
async save(key, entry) {
|
|
2630
|
+
if (this.closed || this.diskQueue.isSaturated) return;
|
|
2489
2631
|
if (this.isForbidden(key)) return;
|
|
2490
2632
|
if (entry.expiresAt <= Date.now()) return;
|
|
2491
2633
|
this.ensureDir();
|
|
@@ -2494,7 +2636,7 @@ var DiskTier = class {
|
|
|
2494
2636
|
if (++this._writeCounter % 2e3 === 0) {
|
|
2495
2637
|
this.checkHostVolumeHealth();
|
|
2496
2638
|
}
|
|
2497
|
-
if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes >= this.opts.maxBytes) {
|
|
2639
|
+
if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes + this.reservedBytes >= this.opts.maxBytes) {
|
|
2498
2640
|
this._spillsShedTotal++;
|
|
2499
2641
|
return;
|
|
2500
2642
|
}
|
|
@@ -2503,11 +2645,12 @@ var DiskTier = class {
|
|
|
2503
2645
|
}
|
|
2504
2646
|
let final;
|
|
2505
2647
|
try {
|
|
2648
|
+
const { value: _value, ...storedEntry } = entry;
|
|
2506
2649
|
const payload = {
|
|
2507
2650
|
version: DISK_TIER_VERSION,
|
|
2508
2651
|
key,
|
|
2509
2652
|
entry: {
|
|
2510
|
-
...
|
|
2653
|
+
...storedEntry,
|
|
2511
2654
|
data: entry.data instanceof Uint8Array ? Buffer.from(entry.data) : entry.data
|
|
2512
2655
|
},
|
|
2513
2656
|
writtenAt: Date.now()
|
|
@@ -2520,24 +2663,46 @@ var DiskTier = class {
|
|
|
2520
2663
|
}
|
|
2521
2664
|
const header = Buffer.allocUnsafe(V2_HEADER_LEN);
|
|
2522
2665
|
DISK_MAGIC_V2.copy(header, 0);
|
|
2523
|
-
header.writeBigUInt64LE(BigInt(entry.expiresAt), 8);
|
|
2666
|
+
header.writeBigUInt64LE(BigInt(Math.floor(entry.expiresAt)), 8);
|
|
2524
2667
|
final = Buffer.concat([header, this.encryptV2(toEncrypt)]);
|
|
2668
|
+
if (final.length > this.opts.entryMaxBytes || this.diskUsageBytes + this.reservedBytes + final.length > this.opts.maxBytes) return;
|
|
2525
2669
|
} catch (err) {
|
|
2526
2670
|
this.opts.logger.debug("DiskTier: pack/encrypt failed", { key: key.slice(0, 50), error: err.message });
|
|
2527
2671
|
return;
|
|
2528
2672
|
}
|
|
2529
2673
|
const hash = this.keyToHash(key);
|
|
2530
|
-
const
|
|
2674
|
+
const setAt = entry.setAt ?? Date.now();
|
|
2675
|
+
if ((this.pendingSaves.get(key)?.setAt ?? 0) > setAt) return;
|
|
2676
|
+
const filePath = this.hashToWritePath(hash, entry.expiresAt, setAt);
|
|
2531
2677
|
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${import_crypto2.default.randomBytes(6).toString("hex")}.tmp`;
|
|
2532
|
-
|
|
2533
|
-
this.
|
|
2678
|
+
const token = Symbol(key);
|
|
2679
|
+
const epoch = this.epoch;
|
|
2680
|
+
this.pendingSaves.set(key, { token, setAt });
|
|
2681
|
+
const current = () => !this.closed && this.epoch === epoch && this.pendingSaves.get(key)?.token === token;
|
|
2682
|
+
let started = false;
|
|
2683
|
+
let released = false;
|
|
2684
|
+
let accounted = false;
|
|
2685
|
+
const releaseReservation = () => {
|
|
2686
|
+
if (released) return;
|
|
2687
|
+
released = true;
|
|
2688
|
+
this.reservedBytes = Math.max(0, this.reservedBytes - final.length);
|
|
2689
|
+
this.reservedFiles = Math.max(0, this.reservedFiles - 1);
|
|
2690
|
+
if (this.pendingSaves.get(key)?.token === token) this.pendingSaves.delete(key);
|
|
2691
|
+
};
|
|
2692
|
+
this.reservedBytes += final.length;
|
|
2693
|
+
this.reservedFiles++;
|
|
2534
2694
|
if (this.diskUsageBytes >= this.opts.maxBytes * 0.8 && !this._isPruning) {
|
|
2535
2695
|
void this.triggerChunkedPrune();
|
|
2536
2696
|
}
|
|
2537
2697
|
const result = await this.diskQueue.schedule(async () => {
|
|
2698
|
+
started = true;
|
|
2538
2699
|
try {
|
|
2700
|
+
if (!current()) return false;
|
|
2701
|
+
const previous = this.findFilePath(hash);
|
|
2702
|
+
if (previous && this.fileWrittenAt(previous) > setAt) return false;
|
|
2539
2703
|
await import_fs2.default.promises.mkdir(import_path2.default.dirname(filePath), { recursive: true });
|
|
2540
2704
|
await import_fs2.default.promises.writeFile(tmpPath, final, { mode: 384 });
|
|
2705
|
+
if (!current()) return false;
|
|
2541
2706
|
try {
|
|
2542
2707
|
await import_fs2.default.promises.rename(tmpPath, filePath);
|
|
2543
2708
|
} catch (renameErr) {
|
|
@@ -2549,6 +2714,20 @@ var DiskTier = class {
|
|
|
2549
2714
|
throw renameErr;
|
|
2550
2715
|
}
|
|
2551
2716
|
}
|
|
2717
|
+
if (!current()) {
|
|
2718
|
+
try {
|
|
2719
|
+
await import_fs2.default.promises.unlink(filePath);
|
|
2720
|
+
} catch {
|
|
2721
|
+
}
|
|
2722
|
+
return false;
|
|
2723
|
+
}
|
|
2724
|
+
for (const previousPath of this.findFilePaths(hash)) {
|
|
2725
|
+
if (previousPath !== filePath) this.removeFile(previousPath);
|
|
2726
|
+
}
|
|
2727
|
+
this.diskUsageBytes += final.length;
|
|
2728
|
+
this.fileCount++;
|
|
2729
|
+
accounted = true;
|
|
2730
|
+
this.invalidatedKeys.delete(key);
|
|
2552
2731
|
if (this._db) {
|
|
2553
2732
|
const priority = typeof entry.priority === "number" ? entry.priority : 2;
|
|
2554
2733
|
const lastAccess = typeof entry.lastAccess === "number" ? entry.lastAccess : Date.now();
|
|
@@ -2561,23 +2740,25 @@ var DiskTier = class {
|
|
|
2561
2740
|
await import_fs2.default.promises.unlink(tmpPath);
|
|
2562
2741
|
} catch {
|
|
2563
2742
|
}
|
|
2564
|
-
|
|
2565
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2566
|
-
if (this._db) try {
|
|
2567
|
-
this._stmtDelete.run(hash);
|
|
2568
|
-
} catch {
|
|
2569
|
-
}
|
|
2743
|
+
if (accounted) this.removeFile(filePath);
|
|
2570
2744
|
this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
|
|
2571
2745
|
throw err;
|
|
2746
|
+
} finally {
|
|
2747
|
+
try {
|
|
2748
|
+
await import_fs2.default.promises.unlink(tmpPath);
|
|
2749
|
+
} catch {
|
|
2750
|
+
}
|
|
2751
|
+
releaseReservation();
|
|
2752
|
+
if (this.invalidatedKeys.has(key) && !this.pendingSaves.has(key)) this.delete(key, true);
|
|
2572
2753
|
}
|
|
2573
2754
|
});
|
|
2574
|
-
if (result === null) {
|
|
2575
|
-
|
|
2576
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2755
|
+
if (result === null && !started) {
|
|
2756
|
+
releaseReservation();
|
|
2577
2757
|
}
|
|
2578
2758
|
}
|
|
2579
2759
|
/** Load a key from disk, or return null on miss/expiry/corruption. */
|
|
2580
2760
|
load(key) {
|
|
2761
|
+
if (this.invalidatedKeys.has(key) || this.closed) return null;
|
|
2581
2762
|
if (this.isForbidden(key)) return null;
|
|
2582
2763
|
this.ensureDir();
|
|
2583
2764
|
if (!this.dirReady) return null;
|
|
@@ -2605,8 +2786,8 @@ var DiskTier = class {
|
|
|
2605
2786
|
try {
|
|
2606
2787
|
if (!this._db) {
|
|
2607
2788
|
const filename = import_path2.default.basename(filePath);
|
|
2608
|
-
if (filename.length
|
|
2609
|
-
const expiresAt = parseInt(filename.slice(65), 16);
|
|
2789
|
+
if (filename.length >= 77 && filename[64] === "_") {
|
|
2790
|
+
const expiresAt = parseInt(filename.slice(65, 77), 16);
|
|
2610
2791
|
if (expiresAt <= Date.now()) {
|
|
2611
2792
|
try {
|
|
2612
2793
|
const sz = import_fs2.default.statSync(filePath).size;
|
|
@@ -2627,12 +2808,7 @@ var DiskTier = class {
|
|
|
2627
2808
|
return null;
|
|
2628
2809
|
}
|
|
2629
2810
|
const raw = import_fs2.default.readFileSync(filePath);
|
|
2630
|
-
|
|
2631
|
-
import_fs2.default.unlinkSync(filePath);
|
|
2632
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
2633
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2634
|
-
} catch {
|
|
2635
|
-
}
|
|
2811
|
+
for (const storedPath of this.findFilePaths(hash)) this.removeFile(storedPath);
|
|
2636
2812
|
if (this._db) this._stmtDelete.run(hash);
|
|
2637
2813
|
let decrypted;
|
|
2638
2814
|
if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
|
|
@@ -2667,25 +2843,24 @@ var DiskTier = class {
|
|
|
2667
2843
|
return null;
|
|
2668
2844
|
}
|
|
2669
2845
|
}
|
|
2670
|
-
/**
|
|
2671
|
-
|
|
2846
|
+
/** Synchronously fence queued/running saves while leaving filesystem cleanup deferred. */
|
|
2847
|
+
invalidate(key) {
|
|
2848
|
+
this.pendingSaves.delete(key);
|
|
2849
|
+
this.invalidatedKeys.add(key);
|
|
2850
|
+
}
|
|
2851
|
+
/** Delete all versions; deferred cleanup must not cancel a newer save. */
|
|
2852
|
+
delete(key, invalidatedOnly = false) {
|
|
2853
|
+
if (invalidatedOnly && (!this.invalidatedKeys.has(key) || this.pendingSaves.has(key))) return;
|
|
2854
|
+
if (!invalidatedOnly) this.pendingSaves.delete(key);
|
|
2672
2855
|
const hash = this.keyToHash(key);
|
|
2673
|
-
|
|
2856
|
+
const files = new Set(this.findFilePaths(hash));
|
|
2674
2857
|
if (this._db) {
|
|
2675
2858
|
const row = this._stmtSelect.get(hash);
|
|
2676
|
-
|
|
2859
|
+
if (row?.file_path) files.add(row.file_path);
|
|
2677
2860
|
this._stmtDelete.run(hash);
|
|
2678
|
-
} else {
|
|
2679
|
-
filePath = this.findFilePath(hash);
|
|
2680
|
-
}
|
|
2681
|
-
if (!filePath) return;
|
|
2682
|
-
try {
|
|
2683
|
-
const stat = import_fs2.default.statSync(filePath);
|
|
2684
|
-
import_fs2.default.unlinkSync(filePath);
|
|
2685
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
2686
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2687
|
-
} catch {
|
|
2688
2861
|
}
|
|
2862
|
+
for (const file of files) this.removeFile(file);
|
|
2863
|
+
this.invalidatedKeys.delete(key);
|
|
2689
2864
|
}
|
|
2690
2865
|
/** Purge all expired entries. Returns number deleted. */
|
|
2691
2866
|
purgeExpired() {
|
|
@@ -2721,8 +2896,8 @@ var DiskTier = class {
|
|
|
2721
2896
|
}
|
|
2722
2897
|
continue;
|
|
2723
2898
|
}
|
|
2724
|
-
if (filename.length
|
|
2725
|
-
const expiresAt = parseInt(filename.slice(65), 16);
|
|
2899
|
+
if (filename.length >= 77 && filename[64] === "_") {
|
|
2900
|
+
const expiresAt = parseInt(filename.slice(65, 77), 16);
|
|
2726
2901
|
if (expiresAt <= now) {
|
|
2727
2902
|
try {
|
|
2728
2903
|
const sz = import_fs2.default.statSync(filePath).size;
|
|
@@ -2842,8 +3017,8 @@ var DiskTier = class {
|
|
|
2842
3017
|
}
|
|
2843
3018
|
continue;
|
|
2844
3019
|
}
|
|
2845
|
-
if (file.length
|
|
2846
|
-
const expiresAt = parseInt(file.slice(65), 16);
|
|
3020
|
+
if (file.length >= 77 && file[64] === "_") {
|
|
3021
|
+
const expiresAt = parseInt(file.slice(65, 77), 16);
|
|
2847
3022
|
if (expiresAt <= now2) {
|
|
2848
3023
|
const fp = import_path2.default.join(orphanBucketP, file);
|
|
2849
3024
|
try {
|
|
@@ -2883,8 +3058,8 @@ var DiskTier = class {
|
|
|
2883
3058
|
}
|
|
2884
3059
|
continue;
|
|
2885
3060
|
}
|
|
2886
|
-
if (file.length
|
|
2887
|
-
const expiresAt = parseInt(file.slice(65), 16);
|
|
3061
|
+
if (file.length >= 77 && file[64] === "_") {
|
|
3062
|
+
const expiresAt = parseInt(file.slice(65, 77), 16);
|
|
2888
3063
|
if (expiresAt <= now) {
|
|
2889
3064
|
const filePath2 = import_path2.default.join(bucketPath, file);
|
|
2890
3065
|
try {
|
|
@@ -2957,6 +3132,9 @@ var DiskTier = class {
|
|
|
2957
3132
|
}
|
|
2958
3133
|
/** Delete every file in the disk cache. Returns the count deleted. */
|
|
2959
3134
|
clear() {
|
|
3135
|
+
this.epoch++;
|
|
3136
|
+
this.pendingSaves.clear();
|
|
3137
|
+
this.invalidatedKeys.clear();
|
|
2960
3138
|
this.ensureDir();
|
|
2961
3139
|
if (!this.dirReady) return 0;
|
|
2962
3140
|
let cleared = 0;
|
|
@@ -3020,6 +3198,7 @@ var DiskTier = class {
|
|
|
3020
3198
|
* yielding to the event loop via setImmediate between chunks.
|
|
3021
3199
|
*/
|
|
3022
3200
|
async triggerChunkedPrune() {
|
|
3201
|
+
if (this.closed) return 0;
|
|
3023
3202
|
if (this._isPruning) return 0;
|
|
3024
3203
|
this._isPruning = true;
|
|
3025
3204
|
this._pruneRounds++;
|
|
@@ -3028,7 +3207,7 @@ var DiskTier = class {
|
|
|
3028
3207
|
this.ensureUsageCounted();
|
|
3029
3208
|
const targetBytes = Math.floor(this.opts.maxBytes * 0.6);
|
|
3030
3209
|
if (this._db && this._stmtPruneChunk) {
|
|
3031
|
-
while (this.diskUsageBytes > targetBytes) {
|
|
3210
|
+
while (!this.closed && this.diskUsageBytes > targetBytes) {
|
|
3032
3211
|
const rows = this._stmtPruneChunk.all();
|
|
3033
3212
|
if (!rows || rows.length === 0) break;
|
|
3034
3213
|
for (const row of rows) {
|
|
@@ -3051,7 +3230,7 @@ var DiskTier = class {
|
|
|
3051
3230
|
}
|
|
3052
3231
|
}
|
|
3053
3232
|
} else {
|
|
3054
|
-
while (this.diskUsageBytes > targetBytes) {
|
|
3233
|
+
while (!this.closed && this.diskUsageBytes > targetBytes) {
|
|
3055
3234
|
const files = this.walkCacheFiles();
|
|
3056
3235
|
if (files.length === 0) break;
|
|
3057
3236
|
const chunk = files.slice(0, 500);
|
|
@@ -3119,6 +3298,10 @@ var DiskTier = class {
|
|
|
3119
3298
|
}
|
|
3120
3299
|
/** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
|
|
3121
3300
|
close() {
|
|
3301
|
+
this.closed = true;
|
|
3302
|
+
this.epoch++;
|
|
3303
|
+
this.pendingSaves.clear();
|
|
3304
|
+
this.invalidatedKeys.clear();
|
|
3122
3305
|
if (this._db) {
|
|
3123
3306
|
try {
|
|
3124
3307
|
this._db.close();
|
|
@@ -3361,6 +3544,17 @@ function readCgroupMemoryLimit() {
|
|
|
3361
3544
|
}
|
|
3362
3545
|
return Infinity;
|
|
3363
3546
|
}
|
|
3547
|
+
function readCgroupMemoryUsage() {
|
|
3548
|
+
if (process.platform !== "linux") return null;
|
|
3549
|
+
for (const file of ["/sys/fs/cgroup/memory.current", "/sys/fs/cgroup/memory/memory.usage_in_bytes"]) {
|
|
3550
|
+
try {
|
|
3551
|
+
const value = Number(import_node_fs.default.readFileSync(file, "utf8").trim());
|
|
3552
|
+
if (Number.isFinite(value) && value >= 0) return value;
|
|
3553
|
+
} catch {
|
|
3554
|
+
}
|
|
3555
|
+
}
|
|
3556
|
+
return null;
|
|
3557
|
+
}
|
|
3364
3558
|
function getV8HeapLimit() {
|
|
3365
3559
|
try {
|
|
3366
3560
|
const stats = import_node_v8.default.getHeapStatistics();
|
|
@@ -3384,7 +3578,81 @@ function resolveAutonomousL1MaxBytes(options) {
|
|
|
3384
3578
|
return Math.max(MIN_AUTONOMOUS_L1_FLOOR_BYTES, Math.floor(resolved));
|
|
3385
3579
|
}
|
|
3386
3580
|
|
|
3581
|
+
// src/utils/diagnostics.ts
|
|
3582
|
+
function redactDiagnostics(value, seen = /* @__PURE__ */ new WeakSet(), depth = 0) {
|
|
3583
|
+
if (typeof value === "string" && /^[a-z][a-z\d+.-]*:\/\//i.test(value)) {
|
|
3584
|
+
try {
|
|
3585
|
+
const url = new URL(value);
|
|
3586
|
+
if (url.username) url.username = "[REDACTED]";
|
|
3587
|
+
if (url.password) url.password = "[REDACTED]";
|
|
3588
|
+
for (const key of url.searchParams.keys()) {
|
|
3589
|
+
if (/key|token|secret|password|credential|authorization|cookie/i.test(key)) url.searchParams.set(key, "[REDACTED]");
|
|
3590
|
+
}
|
|
3591
|
+
return url.toString();
|
|
3592
|
+
} catch {
|
|
3593
|
+
return "[REDACTED URL]";
|
|
3594
|
+
}
|
|
3595
|
+
}
|
|
3596
|
+
if (value == null || typeof value !== "object") return typeof value === "function" ? void 0 : value;
|
|
3597
|
+
if (depth >= 8) return "[OMITTED]";
|
|
3598
|
+
if (seen.has(value)) return "[CIRCULAR]";
|
|
3599
|
+
seen.add(value);
|
|
3600
|
+
if (Array.isArray(value)) return value.map((item) => redactDiagnostics(item, seen, depth + 1));
|
|
3601
|
+
const result = {};
|
|
3602
|
+
for (const [key, item] of Object.entries(value)) {
|
|
3603
|
+
if (typeof item === "function") continue;
|
|
3604
|
+
result[key] = /key|token|secret|password|credential|authorization|cookie|headers/i.test(key) ? item == null ? item : "[REDACTED]" : redactDiagnostics(item, seen, depth + 1);
|
|
3605
|
+
}
|
|
3606
|
+
return result;
|
|
3607
|
+
}
|
|
3608
|
+
|
|
3609
|
+
// src/utils/redis-slot.ts
|
|
3610
|
+
function redisHashSlot(key) {
|
|
3611
|
+
const open = key.indexOf("{");
|
|
3612
|
+
const close = open < 0 ? -1 : key.indexOf("}", open + 1);
|
|
3613
|
+
const bytes = Buffer.from(close > open + 1 ? key.slice(open + 1, close) : key, "utf8");
|
|
3614
|
+
let crc = 0;
|
|
3615
|
+
for (const byte of bytes) {
|
|
3616
|
+
crc ^= byte << 8;
|
|
3617
|
+
for (let bit = 0; bit < 8; bit++) crc = crc << 1 ^ (crc & 32768 ? 4129 : 0);
|
|
3618
|
+
crc &= 65535;
|
|
3619
|
+
}
|
|
3620
|
+
return crc & 16383;
|
|
3621
|
+
}
|
|
3622
|
+
|
|
3623
|
+
// src/utils/deadline.ts
|
|
3624
|
+
async function withDeadline(operation, timeoutMs, label) {
|
|
3625
|
+
let timer;
|
|
3626
|
+
try {
|
|
3627
|
+
return await Promise.race([
|
|
3628
|
+
operation,
|
|
3629
|
+
new Promise((_resolve, reject) => {
|
|
3630
|
+
timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs);
|
|
3631
|
+
})
|
|
3632
|
+
]);
|
|
3633
|
+
} finally {
|
|
3634
|
+
if (timer) clearTimeout(timer);
|
|
3635
|
+
}
|
|
3636
|
+
}
|
|
3637
|
+
|
|
3387
3638
|
// src/adapters/auto-pipeliner.ts
|
|
3639
|
+
var import_ioredis = require("ioredis");
|
|
3640
|
+
async function readRedisValue(client, key, hash = false) {
|
|
3641
|
+
if (typeof client.pttl === "function" && typeof client.multi === "function") {
|
|
3642
|
+
const transaction = client.multi();
|
|
3643
|
+
if (typeof transaction.pttl === "function" && (!hash || typeof transaction.hgetall === "function")) {
|
|
3644
|
+
if (hash) transaction.hgetall(key);
|
|
3645
|
+
else transaction.get(key);
|
|
3646
|
+
transaction.pttl(key);
|
|
3647
|
+
const results = await transaction.exec();
|
|
3648
|
+
if (!results) throw new Error("Redis read transaction aborted");
|
|
3649
|
+
if (results[0]?.[0]) throw results[0][0];
|
|
3650
|
+
if (results[1]?.[0]) throw results[1][0];
|
|
3651
|
+
return { raw: results[0]?.[1] ?? null, ttlMs: Number(results[1]?.[1]) };
|
|
3652
|
+
}
|
|
3653
|
+
}
|
|
3654
|
+
return { raw: await (hash ? client.hgetall(key) : client.get(key)) };
|
|
3655
|
+
}
|
|
3388
3656
|
var AutoPipeliner = class {
|
|
3389
3657
|
constructor(client, options) {
|
|
3390
3658
|
this.client = client;
|
|
@@ -3416,6 +3684,17 @@ var AutoPipeliner = class {
|
|
|
3416
3684
|
this.enqueue({ type: "get", key, resolve, reject });
|
|
3417
3685
|
});
|
|
3418
3686
|
}
|
|
3687
|
+
async read(key, hash = false) {
|
|
3688
|
+
if (!hash && typeof this.client.pttl !== "function") return { raw: await this.get(key) };
|
|
3689
|
+
if (!this.enabled || !this.supportsPipelines() || typeof this.client.pttl !== "function") {
|
|
3690
|
+
return readRedisValue(this.client, key, hash);
|
|
3691
|
+
}
|
|
3692
|
+
const probe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
|
|
3693
|
+
if (typeof probe.pttl !== "function" || hash && typeof probe.hgetall !== "function") {
|
|
3694
|
+
return readRedisValue(this.client, key, hash);
|
|
3695
|
+
}
|
|
3696
|
+
return new Promise((resolve, reject) => this.enqueue({ type: "read", key, hash, resolve, reject }));
|
|
3697
|
+
}
|
|
3419
3698
|
async setex(key, seconds, value) {
|
|
3420
3699
|
if (!this.enabled || !this.supportsPipelines()) {
|
|
3421
3700
|
if (typeof this.client.setex === "function") {
|
|
@@ -3429,8 +3708,18 @@ var AutoPipeliner = class {
|
|
|
3429
3708
|
this.enqueue({ type: "setex", key, seconds, value, resolve, reject });
|
|
3430
3709
|
});
|
|
3431
3710
|
}
|
|
3711
|
+
async setpx(key, milliseconds, value) {
|
|
3712
|
+
if (!this.enabled || !this.supportsPipelines()) {
|
|
3713
|
+
await this.client.set(key, value, "PX", milliseconds);
|
|
3714
|
+
return;
|
|
3715
|
+
}
|
|
3716
|
+
return new Promise((resolve, reject) => this.enqueue({ type: "setpx", key, milliseconds, value, resolve, reject }));
|
|
3717
|
+
}
|
|
3432
3718
|
async del(...keys) {
|
|
3433
3719
|
if (keys.length === 0) return 0;
|
|
3720
|
+
if (this.client instanceof import_ioredis.Cluster && keys.length > 1) {
|
|
3721
|
+
return (await Promise.all(keys.map((key) => this.del(key)))).reduce((sum, value) => sum + value, 0);
|
|
3722
|
+
}
|
|
3434
3723
|
if (!this.enabled || !this.supportsPipelines()) {
|
|
3435
3724
|
return this.client.del(...keys);
|
|
3436
3725
|
}
|
|
@@ -3464,44 +3753,72 @@ var AutoPipeliner = class {
|
|
|
3464
3753
|
this.scheduled = false;
|
|
3465
3754
|
this.statsInternal.batchesDispatched++;
|
|
3466
3755
|
this.statsInternal.operationsBatched += batch.length;
|
|
3467
|
-
|
|
3468
|
-
|
|
3469
|
-
|
|
3470
|
-
|
|
3471
|
-
|
|
3472
|
-
|
|
3473
|
-
|
|
3474
|
-
|
|
3475
|
-
|
|
3476
|
-
|
|
3477
|
-
|
|
3478
|
-
|
|
3479
|
-
}
|
|
3756
|
+
if (this.client instanceof import_ioredis.Cluster) {
|
|
3757
|
+
const groups = /* @__PURE__ */ new Map();
|
|
3758
|
+
for (const operation of batch) {
|
|
3759
|
+
const key = operation.type === "del" ? operation.keys[0] : operation.key;
|
|
3760
|
+
const slot = redisHashSlot(key);
|
|
3761
|
+
const master = this.client.slots[slot]?.[0] ?? String(slot);
|
|
3762
|
+
const members = groups.get(master) ?? [];
|
|
3763
|
+
members.push(operation);
|
|
3764
|
+
groups.set(master, members);
|
|
3765
|
+
}
|
|
3766
|
+
await Promise.all([...groups.values()].map((members) => this.dispatch(members)));
|
|
3767
|
+
return;
|
|
3480
3768
|
}
|
|
3769
|
+
await this.dispatch(batch);
|
|
3770
|
+
}
|
|
3771
|
+
async dispatch(batch) {
|
|
3481
3772
|
try {
|
|
3773
|
+
const pipe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
|
|
3774
|
+
const indexes = [];
|
|
3775
|
+
let commandCount = 0;
|
|
3776
|
+
for (const op of batch) {
|
|
3777
|
+
indexes.push(commandCount++);
|
|
3778
|
+
switch (op.type) {
|
|
3779
|
+
case "get":
|
|
3780
|
+
pipe.get(op.key);
|
|
3781
|
+
break;
|
|
3782
|
+
case "setex":
|
|
3783
|
+
pipe.setex(op.key, op.seconds, op.value);
|
|
3784
|
+
break;
|
|
3785
|
+
case "setpx":
|
|
3786
|
+
pipe.set(op.key, op.value, "PX", op.milliseconds);
|
|
3787
|
+
break;
|
|
3788
|
+
case "del":
|
|
3789
|
+
pipe.del(...op.keys);
|
|
3790
|
+
break;
|
|
3791
|
+
case "read":
|
|
3792
|
+
if (op.hash) pipe.hgetall(op.key);
|
|
3793
|
+
else pipe.get(op.key);
|
|
3794
|
+
pipe.pttl(op.key);
|
|
3795
|
+
commandCount++;
|
|
3796
|
+
break;
|
|
3797
|
+
}
|
|
3798
|
+
}
|
|
3482
3799
|
const results = await pipe.exec();
|
|
3483
3800
|
if (!results) {
|
|
3484
3801
|
for (const op of batch) {
|
|
3485
|
-
|
|
3486
|
-
else if (op.type === "del") op.resolve(0);
|
|
3487
|
-
else op.resolve();
|
|
3802
|
+
op.reject(new Error("Redis pipeline aborted"));
|
|
3488
3803
|
}
|
|
3489
3804
|
return;
|
|
3490
3805
|
}
|
|
3491
3806
|
for (let i = 0; i < batch.length; i++) {
|
|
3492
3807
|
const op = batch[i];
|
|
3493
|
-
const resTuple = results[i];
|
|
3808
|
+
const resTuple = results[indexes[i]];
|
|
3494
3809
|
if (!resTuple) {
|
|
3495
|
-
|
|
3496
|
-
else if (op.type === "del") op.resolve(0);
|
|
3497
|
-
else op.resolve();
|
|
3810
|
+
op.reject(new Error("Missing Redis pipeline result"));
|
|
3498
3811
|
continue;
|
|
3499
3812
|
}
|
|
3500
3813
|
const [err, val] = resTuple;
|
|
3501
3814
|
if (err) {
|
|
3502
3815
|
op.reject(err instanceof Error ? err : new Error(String(err)));
|
|
3503
3816
|
} else {
|
|
3504
|
-
if (op.type === "
|
|
3817
|
+
if (op.type === "read") {
|
|
3818
|
+
const ttlResult = results[indexes[i] + 1];
|
|
3819
|
+
if (!ttlResult || ttlResult[0]) op.reject(ttlResult?.[0] ?? new Error("Missing Redis PTTL result"));
|
|
3820
|
+
else op.resolve({ raw: val, ttlMs: Number(ttlResult[1]) });
|
|
3821
|
+
} else if (op.type === "get") {
|
|
3505
3822
|
op.resolve(val != null ? String(val) : null);
|
|
3506
3823
|
} else if (op.type === "del") {
|
|
3507
3824
|
op.resolve(typeof val === "number" ? val : Number(val) || 0);
|
|
@@ -3538,6 +3855,8 @@ var IpcTelemetryServer = class {
|
|
|
3538
3855
|
server = null;
|
|
3539
3856
|
socketPath;
|
|
3540
3857
|
_closed = false;
|
|
3858
|
+
_starting = null;
|
|
3859
|
+
sockets = /* @__PURE__ */ new Set();
|
|
3541
3860
|
_exitHandler = null;
|
|
3542
3861
|
_sigintHandler = null;
|
|
3543
3862
|
_sigtermHandler = null;
|
|
@@ -3545,10 +3864,23 @@ var IpcTelemetryServer = class {
|
|
|
3545
3864
|
* Start listening on the IPC socket / pipe.
|
|
3546
3865
|
*/
|
|
3547
3866
|
async start() {
|
|
3548
|
-
if (this.
|
|
3867
|
+
if (this._closed || this.server?.listening) return;
|
|
3868
|
+
if (this._starting) return this._starting;
|
|
3869
|
+
this._starting = this.startInternal();
|
|
3870
|
+
try {
|
|
3871
|
+
await this._starting;
|
|
3872
|
+
} finally {
|
|
3873
|
+
this._starting = null;
|
|
3874
|
+
}
|
|
3875
|
+
}
|
|
3876
|
+
async startInternal() {
|
|
3549
3877
|
if (process.platform !== "win32" && import_node_fs2.default.existsSync(this.socketPath)) {
|
|
3550
3878
|
await new Promise((resolve) => {
|
|
3551
3879
|
const testSocket = import_node_net.default.createConnection(this.socketPath);
|
|
3880
|
+
testSocket.setTimeout(1e3, () => {
|
|
3881
|
+
testSocket.destroy();
|
|
3882
|
+
resolve();
|
|
3883
|
+
});
|
|
3552
3884
|
testSocket.once("connect", () => {
|
|
3553
3885
|
testSocket.destroy();
|
|
3554
3886
|
resolve();
|
|
@@ -3563,17 +3895,37 @@ var IpcTelemetryServer = class {
|
|
|
3563
3895
|
});
|
|
3564
3896
|
});
|
|
3565
3897
|
}
|
|
3898
|
+
if (this._closed) return;
|
|
3566
3899
|
this.server = import_node_net.default.createServer((socket) => {
|
|
3900
|
+
if (this._closed) {
|
|
3901
|
+
socket.destroy();
|
|
3902
|
+
return;
|
|
3903
|
+
}
|
|
3904
|
+
this.sockets.add(socket);
|
|
3905
|
+
socket.once("close", () => this.sockets.delete(socket));
|
|
3906
|
+
socket.setTimeout(5e3, () => socket.destroy());
|
|
3567
3907
|
let buffer = "";
|
|
3908
|
+
let pending = 0;
|
|
3568
3909
|
socket.on("data", (chunk) => {
|
|
3910
|
+
if (Buffer.byteLength(buffer) + chunk.length > 4096 || socket.writableLength > 65536) {
|
|
3911
|
+
socket.destroy();
|
|
3912
|
+
return;
|
|
3913
|
+
}
|
|
3569
3914
|
buffer += chunk.toString("utf8");
|
|
3570
3915
|
let newlineIndex;
|
|
3571
3916
|
while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
|
|
3572
3917
|
const line = buffer.slice(0, newlineIndex).trim();
|
|
3573
3918
|
buffer = buffer.slice(newlineIndex + 1);
|
|
3574
3919
|
if (!line) continue;
|
|
3920
|
+
if (++pending > 8) {
|
|
3921
|
+
socket.destroy();
|
|
3922
|
+
return;
|
|
3923
|
+
}
|
|
3575
3924
|
setImmediate(() => {
|
|
3576
|
-
if (socket.destroyed)
|
|
3925
|
+
if (socket.destroyed) {
|
|
3926
|
+
pending--;
|
|
3927
|
+
return;
|
|
3928
|
+
}
|
|
3577
3929
|
try {
|
|
3578
3930
|
let cmd = line;
|
|
3579
3931
|
try {
|
|
@@ -3598,6 +3950,8 @@ var IpcTelemetryServer = class {
|
|
|
3598
3950
|
if (!socket.destroyed) {
|
|
3599
3951
|
socket.write(JSON.stringify({ error: err.message }) + "\n");
|
|
3600
3952
|
}
|
|
3953
|
+
} finally {
|
|
3954
|
+
pending--;
|
|
3601
3955
|
}
|
|
3602
3956
|
});
|
|
3603
3957
|
}
|
|
@@ -3605,21 +3959,38 @@ var IpcTelemetryServer = class {
|
|
|
3605
3959
|
socket.on("error", () => {
|
|
3606
3960
|
});
|
|
3607
3961
|
});
|
|
3962
|
+
this.server.maxConnections = 128;
|
|
3608
3963
|
await new Promise((resolve, reject) => {
|
|
3609
|
-
this.server
|
|
3610
|
-
|
|
3611
|
-
|
|
3964
|
+
const server = this.server;
|
|
3965
|
+
const cleanup = () => {
|
|
3966
|
+
server.off("error", failed);
|
|
3967
|
+
server.off("close", closed);
|
|
3968
|
+
};
|
|
3969
|
+
const failed = (error) => {
|
|
3970
|
+
cleanup();
|
|
3971
|
+
reject(error);
|
|
3972
|
+
};
|
|
3973
|
+
const closed = () => {
|
|
3974
|
+
cleanup();
|
|
3975
|
+
resolve();
|
|
3976
|
+
};
|
|
3977
|
+
server.once("error", failed);
|
|
3978
|
+
server.once("close", closed);
|
|
3979
|
+
server.listen(this.socketPath, () => {
|
|
3980
|
+
cleanup();
|
|
3612
3981
|
resolve();
|
|
3613
3982
|
});
|
|
3614
3983
|
});
|
|
3984
|
+
if (this._closed) {
|
|
3985
|
+
if (this.server.listening) this.server.close();
|
|
3986
|
+
return;
|
|
3987
|
+
}
|
|
3615
3988
|
this._exitHandler = () => this._unlinkSocket();
|
|
3616
3989
|
this._sigintHandler = () => {
|
|
3617
3990
|
this._unlinkSocket();
|
|
3618
|
-
process.exit(0);
|
|
3619
3991
|
};
|
|
3620
3992
|
this._sigtermHandler = () => {
|
|
3621
3993
|
this._unlinkSocket();
|
|
3622
|
-
process.exit(0);
|
|
3623
3994
|
};
|
|
3624
3995
|
process.once("exit", this._exitHandler);
|
|
3625
3996
|
process.once("SIGINT", this._sigintHandler);
|
|
@@ -3649,6 +4020,7 @@ var IpcTelemetryServer = class {
|
|
|
3649
4020
|
_unlinkSocket() {
|
|
3650
4021
|
if (this._closed) return;
|
|
3651
4022
|
this._closed = true;
|
|
4023
|
+
for (const socket of this.sockets) socket.destroy();
|
|
3652
4024
|
try {
|
|
3653
4025
|
this.server?.close();
|
|
3654
4026
|
} catch {
|
|
@@ -3666,6 +4038,9 @@ var IpcTelemetryServer = class {
|
|
|
3666
4038
|
* Gracefully close the IPC telemetry server and clean up handlers and sockets.
|
|
3667
4039
|
*/
|
|
3668
4040
|
async close() {
|
|
4041
|
+
this._unlinkSocket();
|
|
4042
|
+
await this._starting?.catch(() => {
|
|
4043
|
+
});
|
|
3669
4044
|
if (this._exitHandler) {
|
|
3670
4045
|
process.removeListener("exit", this._exitHandler);
|
|
3671
4046
|
this._exitHandler = null;
|
|
@@ -3678,7 +4053,6 @@ var IpcTelemetryServer = class {
|
|
|
3678
4053
|
process.removeListener("SIGTERM", this._sigtermHandler);
|
|
3679
4054
|
this._sigtermHandler = null;
|
|
3680
4055
|
}
|
|
3681
|
-
this._unlinkSocket();
|
|
3682
4056
|
return new Promise((resolve) => {
|
|
3683
4057
|
if (!this.server || !this.server.listening) {
|
|
3684
4058
|
resolve();
|
|
@@ -3749,6 +4123,37 @@ if currentTs and currentTs == ARGV[1] then
|
|
|
3749
4123
|
end
|
|
3750
4124
|
return 0
|
|
3751
4125
|
`;
|
|
4126
|
+
var LUA_READ_CACHE_ENTRY = `
|
|
4127
|
+
local kind = redis.call('TYPE', KEYS[1]).ok
|
|
4128
|
+
if kind == 'string' then
|
|
4129
|
+
return { kind, redis.call('GET', KEYS[1]), redis.call('PTTL', KEYS[1]) }
|
|
4130
|
+
elseif kind == 'hash' then
|
|
4131
|
+
return { kind, redis.call('HGETALL', KEYS[1]), redis.call('PTTL', KEYS[1]) }
|
|
4132
|
+
end
|
|
4133
|
+
return { 'none', false, -2 }
|
|
4134
|
+
`;
|
|
4135
|
+
var LUA_MAX_TAG_VERSION = `
|
|
4136
|
+
local current = tonumber(redis.call('GET', KEYS[1]) or '0')
|
|
4137
|
+
local floor = tonumber(ARGV[1])
|
|
4138
|
+
if current < floor then redis.call('SET', KEYS[1], floor) return floor end
|
|
4139
|
+
return current
|
|
4140
|
+
`;
|
|
4141
|
+
var LUA_RECEIVE_TAG_VERSION = `
|
|
4142
|
+
local current = tonumber(redis.call('GET', KEYS[1]) or '0')
|
|
4143
|
+
local next = math.max(current + 1, tonumber(ARGV[1]))
|
|
4144
|
+
redis.call('SET', KEYS[1], next)
|
|
4145
|
+
return next
|
|
4146
|
+
`;
|
|
4147
|
+
var LUA_TOUCH_CACHE_ENTRY = `
|
|
4148
|
+
local kind = redis.call('TYPE', KEYS[1]).ok
|
|
4149
|
+
if kind == 'hash' then
|
|
4150
|
+
if redis.call('HGET', KEYS[1], 't') ~= ARGV[1] then return 0 end
|
|
4151
|
+
redis.call('HSET', KEYS[1], 'e', ARGV[2])
|
|
4152
|
+
elseif kind ~= 'string' then
|
|
4153
|
+
return 0
|
|
4154
|
+
end
|
|
4155
|
+
return redis.call('PEXPIRE', KEYS[1], ARGV[3])
|
|
4156
|
+
`;
|
|
3752
4157
|
var SNAPSHOT_VERSION = 1;
|
|
3753
4158
|
var DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
|
|
3754
4159
|
var INDEFINITE_TTL_SECONDS = 31536e3;
|
|
@@ -4041,6 +4446,7 @@ var CacheService = class _CacheService {
|
|
|
4041
4446
|
keyTags = /* @__PURE__ */ new Map();
|
|
4042
4447
|
/** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
|
|
4043
4448
|
tagVersions = /* @__PURE__ */ new Map();
|
|
4449
|
+
_tagRefreshEpoch = 0;
|
|
4044
4450
|
/**
|
|
4045
4451
|
* Dependency index: source glob pattern → Set of namespaced dependent keys.
|
|
4046
4452
|
* When an exact-key delete matches a registered pattern, all dependents are cascaded.
|
|
@@ -4071,9 +4477,17 @@ var CacheService = class _CacheService {
|
|
|
4071
4477
|
subClient = null;
|
|
4072
4478
|
streamClient = null;
|
|
4073
4479
|
_lastStreamId = "$";
|
|
4480
|
+
_restoredSnapshot = false;
|
|
4481
|
+
_backplaneAvailable = false;
|
|
4482
|
+
_otelCleanup = null;
|
|
4483
|
+
_streamRecovering = false;
|
|
4484
|
+
_backplaneDisposers = [];
|
|
4074
4485
|
_destroyed = false;
|
|
4075
4486
|
_pendingDiskDeletes = /* @__PURE__ */ new Set();
|
|
4076
4487
|
_globalEpoch = 0;
|
|
4488
|
+
_pendingSpillCount = 0;
|
|
4489
|
+
_suppressSpills = false;
|
|
4490
|
+
_diskCleanupScheduled = false;
|
|
4077
4491
|
_keyMutationEpochs = /* @__PURE__ */ new Map();
|
|
4078
4492
|
/**
|
|
4079
4493
|
* Pattern tombstones for disk tier.
|
|
@@ -4082,20 +4496,24 @@ var CacheService = class _CacheService {
|
|
|
4082
4496
|
* pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
|
|
4083
4497
|
*/
|
|
4084
4498
|
_patternTombstones = [];
|
|
4085
|
-
|
|
4499
|
+
_diskInvalidatedBefore = 0;
|
|
4500
|
+
_addPatternTombstone(pattern) {
|
|
4086
4501
|
const now = Date.now();
|
|
4087
4502
|
while (this._patternTombstones.length > 0 && now - this._patternTombstones[0].createdAt > 36e5) {
|
|
4088
|
-
this._patternTombstones.shift();
|
|
4503
|
+
const forgotten = this._patternTombstones.shift();
|
|
4504
|
+
this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
|
|
4089
4505
|
}
|
|
4090
4506
|
if (this._patternTombstones.length >= 2e3) {
|
|
4091
|
-
this._patternTombstones.shift();
|
|
4507
|
+
const forgotten = this._patternTombstones.shift();
|
|
4508
|
+
this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
|
|
4092
4509
|
}
|
|
4093
|
-
this._patternTombstones.push({
|
|
4510
|
+
this._patternTombstones.push({ pattern, createdAt: now });
|
|
4094
4511
|
}
|
|
4095
|
-
_isTombstonedByPattern(namespacedKey) {
|
|
4512
|
+
_isTombstonedByPattern(namespacedKey, setAt = 0) {
|
|
4513
|
+
if (this._diskInvalidatedBefore > 0 && setAt <= this._diskInvalidatedBefore) return true;
|
|
4096
4514
|
if (this._patternTombstones.length === 0) return false;
|
|
4097
4515
|
for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
|
|
4098
|
-
if (
|
|
4516
|
+
if (setAt <= this._patternTombstones[i].createdAt && this._matchesGlob(namespacedKey, this._patternTombstones[i].pattern)) {
|
|
4099
4517
|
return true;
|
|
4100
4518
|
}
|
|
4101
4519
|
}
|
|
@@ -4110,13 +4528,86 @@ var CacheService = class _CacheService {
|
|
|
4110
4528
|
const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
|
|
4111
4529
|
this._keyMutationEpochs.set(namespacedKey, next);
|
|
4112
4530
|
if (this._keyMutationEpochs.size > 5e4) {
|
|
4113
|
-
|
|
4114
|
-
|
|
4531
|
+
this._globalEpoch++;
|
|
4532
|
+
this._keyMutationEpochs.clear();
|
|
4533
|
+
this._keyMutationEpochs.set(namespacedKey, next);
|
|
4115
4534
|
}
|
|
4116
4535
|
return next;
|
|
4117
4536
|
}
|
|
4118
4537
|
_getKeyMutationEpoch(namespacedKey) {
|
|
4119
|
-
return this._globalEpoch
|
|
4538
|
+
return `${this._globalEpoch}:${this._keyMutationEpochs.get(namespacedKey) ?? 0}`;
|
|
4539
|
+
}
|
|
4540
|
+
/** Capture a commit fence before asynchronous computation outside the cache. */
|
|
4541
|
+
captureMutationFence(cacheKey) {
|
|
4542
|
+
this._assertActive("captureMutationFence");
|
|
4543
|
+
const key = this.nk(cacheKey);
|
|
4544
|
+
const epoch = this._getKeyMutationEpoch(key);
|
|
4545
|
+
return () => !this._destroyed && this._getKeyMutationEpoch(key) === epoch;
|
|
4546
|
+
}
|
|
4547
|
+
/** Force tag re-sync without forgetting locally observed monotonic generations. */
|
|
4548
|
+
refreshTagVersions() {
|
|
4549
|
+
this._assertActive("refreshTagVersions");
|
|
4550
|
+
this._tagRefreshEpoch++;
|
|
4551
|
+
}
|
|
4552
|
+
_fenceInvalidation() {
|
|
4553
|
+
this._globalEpoch++;
|
|
4554
|
+
this.inflight.clear();
|
|
4555
|
+
}
|
|
4556
|
+
_invalidateDiskKey(key) {
|
|
4557
|
+
if (this._diskDisabled) return;
|
|
4558
|
+
this.disk.invalidate(key);
|
|
4559
|
+
this._pendingDiskDeletes.add(key);
|
|
4560
|
+
this._scheduleDiskCleanup();
|
|
4561
|
+
}
|
|
4562
|
+
_scheduleDiskCleanup() {
|
|
4563
|
+
if (this._diskCleanupScheduled || this._pendingDiskDeletes.size === 0) return;
|
|
4564
|
+
this._diskCleanupScheduled = true;
|
|
4565
|
+
setImmediate(() => {
|
|
4566
|
+
this._diskCleanupScheduled = false;
|
|
4567
|
+
if (this._destroyed) return;
|
|
4568
|
+
let processed = 0;
|
|
4569
|
+
for (const key of this._pendingDiskDeletes) {
|
|
4570
|
+
try {
|
|
4571
|
+
this.disk.delete(key, true);
|
|
4572
|
+
} finally {
|
|
4573
|
+
this._pendingDiskDeletes.delete(key);
|
|
4574
|
+
}
|
|
4575
|
+
if (++processed >= 16) break;
|
|
4576
|
+
}
|
|
4577
|
+
this._scheduleDiskCleanup();
|
|
4578
|
+
});
|
|
4579
|
+
}
|
|
4580
|
+
_registerDependencies(key, patterns) {
|
|
4581
|
+
this._removeKeyDependencies(key);
|
|
4582
|
+
if (!patterns?.length) return;
|
|
4583
|
+
const namespaced = [...new Set(patterns.map((pattern) => this.nk(pattern)))];
|
|
4584
|
+
for (const pattern of namespaced) {
|
|
4585
|
+
const dependents = this.dependencyIndex.get(pattern) ?? /* @__PURE__ */ new Set();
|
|
4586
|
+
dependents.add(key);
|
|
4587
|
+
this.dependencyIndex.set(pattern, dependents);
|
|
4588
|
+
}
|
|
4589
|
+
this.keyDependencies.set(key, namespaced);
|
|
4590
|
+
}
|
|
4591
|
+
_rememberTags(key, tags, expiresAt) {
|
|
4592
|
+
this._removeKeyTags(key);
|
|
4593
|
+
if (!tags.length) return;
|
|
4594
|
+
if (this.keyTags.size >= 1e5) {
|
|
4595
|
+
this._sweepExpiredMetadata();
|
|
4596
|
+
const oldest = this.keyTags.keys().next().value;
|
|
4597
|
+
if (this.keyTags.size >= 1e5 && oldest !== void 0) this._removeKeyTags(oldest);
|
|
4598
|
+
}
|
|
4599
|
+
const unique = [...new Set(tags)];
|
|
4600
|
+
for (const tag of unique) {
|
|
4601
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
4602
|
+
const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
|
|
4603
|
+
members.add(key);
|
|
4604
|
+
this.tagIndex.set(tagKey, members);
|
|
4605
|
+
}
|
|
4606
|
+
this.keyTags.set(key, { tags: unique, expiresAt });
|
|
4607
|
+
}
|
|
4608
|
+
_restoreEntryMetadata(key, entry) {
|
|
4609
|
+
if (entry.tags?.length) this._rememberTags(key, entry.tags, entry.expiresAt);
|
|
4610
|
+
if (entry.dependsOn?.length) this._registerDependencies(key, entry.dependsOn);
|
|
4120
4611
|
}
|
|
4121
4612
|
_removeKeyTags(namespacedKey) {
|
|
4122
4613
|
const entry = this.keyTags.get(namespacedKey);
|
|
@@ -4150,21 +4641,21 @@ var CacheService = class _CacheService {
|
|
|
4150
4641
|
}
|
|
4151
4642
|
}
|
|
4152
4643
|
_handleL1Eviction(namespacedKey, reason) {
|
|
4153
|
-
const spilledToDisk = !this._diskDisabled && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
|
|
4644
|
+
const spilledToDisk = !this._diskDisabled && !this._suppressSpills && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
|
|
4154
4645
|
if (!spilledToDisk) {
|
|
4155
4646
|
this._removeKeyTags(namespacedKey);
|
|
4156
4647
|
this._removeKeyDependencies(namespacedKey);
|
|
4157
4648
|
}
|
|
4158
4649
|
}
|
|
4159
|
-
|
|
4650
|
+
_removePatternFromIndices(pattern) {
|
|
4160
4651
|
for (const k of Array.from(this.keyTags.keys())) {
|
|
4161
|
-
if (
|
|
4652
|
+
if (this._matchesGlob(k, pattern)) this._removeKeyTags(k);
|
|
4162
4653
|
}
|
|
4163
4654
|
for (const k of Array.from(this.keyDependencies.keys())) {
|
|
4164
|
-
if (
|
|
4655
|
+
if (this._matchesGlob(k, pattern)) this._removeKeyDependencies(k);
|
|
4165
4656
|
}
|
|
4166
4657
|
for (const k of Array.from(this._l1Counters.keys())) {
|
|
4167
|
-
if (
|
|
4658
|
+
if (this._matchesGlob(k, pattern)) this._l1Counters.delete(k);
|
|
4168
4659
|
}
|
|
4169
4660
|
}
|
|
4170
4661
|
_sweepExpiredMetadata() {
|
|
@@ -4182,10 +4673,16 @@ var CacheService = class _CacheService {
|
|
|
4182
4673
|
_runOomCheck() {
|
|
4183
4674
|
const heap = import_node_v82.default.getHeapStatistics();
|
|
4184
4675
|
const heapUsed = heap.used_heap_size / heap.heap_size_limit;
|
|
4185
|
-
const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? process.memoryUsage().rss / this._cgroupMemoryLimit : 0;
|
|
4676
|
+
const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? (readCgroupMemoryUsage() ?? process.memoryUsage().rss) / this._cgroupMemoryLimit : 0;
|
|
4186
4677
|
const used = Math.max(heapUsed, cgroupUsed);
|
|
4187
4678
|
if (used >= this.opts.oomHeapThreshold) {
|
|
4188
|
-
|
|
4679
|
+
this._suppressSpills = cgroupUsed >= this.opts.oomHeapThreshold;
|
|
4680
|
+
let evicted;
|
|
4681
|
+
try {
|
|
4682
|
+
evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
|
|
4683
|
+
} finally {
|
|
4684
|
+
this._suppressSpills = false;
|
|
4685
|
+
}
|
|
4189
4686
|
this.counters.oomEvictions++;
|
|
4190
4687
|
this.counters.oomLastAt = Date.now();
|
|
4191
4688
|
this.logger.warn("tricache OOM guard: emergency L1 eviction", {
|
|
@@ -4421,9 +4918,13 @@ var CacheService = class _CacheService {
|
|
|
4421
4918
|
admissionPolicy: this.opts.l1AdmissionPolicy,
|
|
4422
4919
|
codec: this.codec,
|
|
4423
4920
|
diskSpill: (key, entry) => {
|
|
4424
|
-
if (this._diskDisabled) return;
|
|
4921
|
+
if (this._diskDisabled || this._suppressSpills) return;
|
|
4922
|
+
if (this._pendingSpillCount >= (this.opts.diskMaxPendingWrites ?? 512)) return;
|
|
4923
|
+
const epoch = this._getKeyMutationEpoch(key);
|
|
4924
|
+
this._pendingSpillCount++;
|
|
4425
4925
|
setImmediate(() => {
|
|
4426
|
-
|
|
4926
|
+
this._pendingSpillCount--;
|
|
4927
|
+
if (!this._destroyed && this._getKeyMutationEpoch(key) === epoch) void this.disk.save(key, entry);
|
|
4427
4928
|
});
|
|
4428
4929
|
},
|
|
4429
4930
|
onEviction: (key, reason) => {
|
|
@@ -4502,7 +5003,7 @@ var CacheService = class _CacheService {
|
|
|
4502
5003
|
this.instanceId = import_crypto3.default.randomBytes(8).toString("hex");
|
|
4503
5004
|
this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
|
|
4504
5005
|
this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
|
|
4505
|
-
this.initBackplane();
|
|
5006
|
+
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 }));
|
|
4506
5007
|
const startupPromises = [];
|
|
4507
5008
|
if (this.opts.compression === "zstd") {
|
|
4508
5009
|
startupPromises.push(initZstd().then(() => void 0));
|
|
@@ -4513,9 +5014,8 @@ var CacheService = class _CacheService {
|
|
|
4513
5014
|
if (this.opts.warmKeys) {
|
|
4514
5015
|
startupPromises.push(this.warmFromL2(this.opts.warmKeys).then(() => void 0));
|
|
4515
5016
|
}
|
|
4516
|
-
|
|
4517
|
-
|
|
4518
|
-
}
|
|
5017
|
+
const backplaneReady = this.opts.remoteSnapshot || this.opts.warmKeys ? Promise.all(startupPromises).then(startBackplane) : startBackplane();
|
|
5018
|
+
this._readyPromise = Promise.all([...startupPromises, backplaneReady]).then(() => void 0);
|
|
4519
5019
|
if (this.opts.meter) {
|
|
4520
5020
|
this._initOtelMetrics(this.opts.meter);
|
|
4521
5021
|
const otel = this._otelMetrics;
|
|
@@ -4528,7 +5028,10 @@ var CacheService = class _CacheService {
|
|
|
4528
5028
|
if (typeof prop === "string" && typeof value === "number" && typeof oldVal === "number") {
|
|
4529
5029
|
const diff = value - oldVal;
|
|
4530
5030
|
if (diff > 0 && otel[prop]) {
|
|
4531
|
-
|
|
5031
|
+
try {
|
|
5032
|
+
otel[prop].add(diff, nsAttr);
|
|
5033
|
+
} catch {
|
|
5034
|
+
}
|
|
4532
5035
|
}
|
|
4533
5036
|
}
|
|
4534
5037
|
return ok;
|
|
@@ -4620,7 +5123,7 @@ var CacheService = class _CacheService {
|
|
|
4620
5123
|
return g[key];
|
|
4621
5124
|
}
|
|
4622
5125
|
const existing = g[key];
|
|
4623
|
-
const diff = _CacheService.optionsDiff(options ?? {}, existing.
|
|
5126
|
+
const diff = _CacheService.optionsDiff(options ?? {}, existing.opts);
|
|
4624
5127
|
if (diff.length > 0) {
|
|
4625
5128
|
existing.bumpSingletonDivergence();
|
|
4626
5129
|
const msg = `tricache: singleton already initialised for namespace '${existing.options.namespace || "(default)"}' \u2014 ignoring divergent options: ${diff.join(", ")}`;
|
|
@@ -4654,7 +5157,13 @@ var CacheService = class _CacheService {
|
|
|
4654
5157
|
"instanceName",
|
|
4655
5158
|
"invalidationBackplane",
|
|
4656
5159
|
"awaitInvalidationBackplane",
|
|
4657
|
-
"lockFailClosed"
|
|
5160
|
+
"lockFailClosed",
|
|
5161
|
+
"tagStrategy",
|
|
5162
|
+
"cloneStrategy",
|
|
5163
|
+
"compression",
|
|
5164
|
+
"backplaneMode",
|
|
5165
|
+
"redisProtocol",
|
|
5166
|
+
"failClosed"
|
|
4658
5167
|
];
|
|
4659
5168
|
/** Returns the names of options that differ between `a` and the live `b`. */
|
|
4660
5169
|
static optionsDiff(a, b) {
|
|
@@ -4672,12 +5181,12 @@ var CacheService = class _CacheService {
|
|
|
4672
5181
|
bumpSingletonDivergence() {
|
|
4673
5182
|
this.counters.singletonDivergences++;
|
|
4674
5183
|
}
|
|
4675
|
-
/**
|
|
5184
|
+
/** Sanitized diagnostic view; retain the original options/adapters to reuse configuration. */
|
|
4676
5185
|
get options() {
|
|
4677
5186
|
const o = this.opts;
|
|
4678
5187
|
return {
|
|
4679
5188
|
namespace: o.namespace,
|
|
4680
|
-
logger: o.logger,
|
|
5189
|
+
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) },
|
|
4681
5190
|
l1MaxBytes: o.l1MaxBytes,
|
|
4682
5191
|
l1MaxEntries: o.l1MaxEntries,
|
|
4683
5192
|
redisHost: o.redisHost,
|
|
@@ -4698,8 +5207,8 @@ var CacheService = class _CacheService {
|
|
|
4698
5207
|
awaitInvalidationBackplane: o.awaitInvalidationBackplane,
|
|
4699
5208
|
lockFailClosed: o.lockFailClosed,
|
|
4700
5209
|
strictSingleton: o.strictSingleton,
|
|
4701
|
-
remoteSnapshot: o.remoteSnapshot,
|
|
4702
|
-
crossRegion: o.crossRegion
|
|
5210
|
+
remoteSnapshot: redactDiagnostics(o.remoteSnapshot),
|
|
5211
|
+
crossRegion: redactDiagnostics(o.crossRegion)
|
|
4703
5212
|
};
|
|
4704
5213
|
}
|
|
4705
5214
|
/**
|
|
@@ -4782,21 +5291,26 @@ var CacheService = class _CacheService {
|
|
|
4782
5291
|
if (this.opts.redisClient && typeof this.opts.redisClient.duplicate === "function") {
|
|
4783
5292
|
return this.opts.redisClient.duplicate();
|
|
4784
5293
|
}
|
|
5294
|
+
if (this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel) {
|
|
5295
|
+
throw new Error("Invalidation backplane requires redisSubClient or a driver supporting duplicate()");
|
|
5296
|
+
}
|
|
4785
5297
|
if (this.opts.redisClusterNodes?.length) {
|
|
4786
|
-
return new
|
|
5298
|
+
return new import_ioredis2.Cluster(this.opts.redisClusterNodes, {
|
|
4787
5299
|
redisOptions: {
|
|
4788
5300
|
tls: this.opts.redisTls ? {} : void 0,
|
|
4789
5301
|
connectTimeout: 1e4,
|
|
5302
|
+
commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
|
|
4790
5303
|
maxRetriesPerRequest: null,
|
|
4791
5304
|
...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
|
|
4792
5305
|
}
|
|
4793
5306
|
});
|
|
4794
5307
|
} else if (this.opts.redisSentinel) {
|
|
4795
|
-
return new
|
|
5308
|
+
return new import_ioredis2.Redis({
|
|
4796
5309
|
sentinels: this.opts.redisSentinel.sentinels,
|
|
4797
5310
|
name: this.opts.redisSentinel.name,
|
|
4798
5311
|
tls: this.opts.redisTls ? {} : void 0,
|
|
4799
5312
|
connectTimeout: 1e4,
|
|
5313
|
+
commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
|
|
4800
5314
|
lazyConnect: true,
|
|
4801
5315
|
maxRetriesPerRequest: null,
|
|
4802
5316
|
enableAutoPipelining: false,
|
|
@@ -4804,11 +5318,12 @@ var CacheService = class _CacheService {
|
|
|
4804
5318
|
...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
|
|
4805
5319
|
});
|
|
4806
5320
|
} else {
|
|
4807
|
-
return new
|
|
5321
|
+
return new import_ioredis2.Redis({
|
|
4808
5322
|
host: this.opts.redisHost,
|
|
4809
5323
|
port: this.opts.redisPort,
|
|
4810
5324
|
tls: this.opts.redisTls ? {} : void 0,
|
|
4811
5325
|
connectTimeout: 1e4,
|
|
5326
|
+
commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
|
|
4812
5327
|
lazyConnect: true,
|
|
4813
5328
|
maxRetriesPerRequest: null,
|
|
4814
5329
|
enableAutoPipelining: false,
|
|
@@ -4818,26 +5333,32 @@ var CacheService = class _CacheService {
|
|
|
4818
5333
|
});
|
|
4819
5334
|
}
|
|
4820
5335
|
}
|
|
4821
|
-
|
|
5336
|
+
_listenBackplane(client, event, listener) {
|
|
5337
|
+
client.on?.(event, listener);
|
|
5338
|
+
this._backplaneDisposers.push(() => client.removeListener?.(event, listener));
|
|
5339
|
+
}
|
|
5340
|
+
async initBackplane() {
|
|
4822
5341
|
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
4823
5342
|
if (this.opts.backplaneMode === "stream") {
|
|
4824
5343
|
if (this.streamClient) return;
|
|
4825
|
-
|
|
5344
|
+
await this._startStreamConsumer();
|
|
4826
5345
|
return;
|
|
4827
5346
|
}
|
|
4828
5347
|
if (this.subClient) return;
|
|
4829
5348
|
const sub = this.createDedicatedRedisClient();
|
|
4830
|
-
|
|
5349
|
+
this.subClient = sub;
|
|
5350
|
+
this._listenBackplane(sub, "error", (e) => {
|
|
4831
5351
|
this._checkAndLogResp3Hint(e);
|
|
4832
5352
|
this.logger.debug("Backplane subscriber error", { error: e.message });
|
|
4833
5353
|
});
|
|
4834
|
-
|
|
5354
|
+
this._listenBackplane(sub, "close", () => {
|
|
5355
|
+
this._backplaneAvailable = false;
|
|
4835
5356
|
if (this._subDisconnectedAt === null) {
|
|
4836
5357
|
this._subDisconnectedAt = Date.now();
|
|
4837
5358
|
this.logger.debug("Backplane: subscriber disconnected", { at: this._subDisconnectedAt });
|
|
4838
5359
|
}
|
|
4839
5360
|
});
|
|
4840
|
-
|
|
5361
|
+
this._listenBackplane(sub, "ready", () => {
|
|
4841
5362
|
if (this._subDisconnectedAt !== null && this.opts.backplaneMaxStalenessMs > 0) {
|
|
4842
5363
|
const gapMs = Date.now() - this._subDisconnectedAt;
|
|
4843
5364
|
if (gapMs > this.opts.backplaneMaxStalenessMs) {
|
|
@@ -4850,52 +5371,119 @@ var CacheService = class _CacheService {
|
|
|
4850
5371
|
}
|
|
4851
5372
|
this._subDisconnectedAt = null;
|
|
4852
5373
|
}
|
|
5374
|
+
if (!this._destroyed) this._backplaneAvailable = true;
|
|
4853
5375
|
});
|
|
4854
5376
|
const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
|
|
4855
5377
|
if (isClusterSharded) {
|
|
4856
|
-
|
|
5378
|
+
this._listenBackplane(sub, "smessage", (_channel, message) => {
|
|
4857
5379
|
this._handleBackplaneMessage(message);
|
|
4858
5380
|
});
|
|
4859
|
-
sub.
|
|
5381
|
+
if (typeof sub.connect === "function" && (sub.isOpen === false || sub.status === "wait")) await sub.connect();
|
|
5382
|
+
await sub.ssubscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: sharded subscribed", {
|
|
4860
5383
|
channel: this.backplaneChannel,
|
|
4861
5384
|
instanceId: this.instanceId
|
|
4862
|
-
})).catch((err) => this.logger.warn("Backplane: sharded subscribe failed", {
|
|
4863
|
-
error: err.message
|
|
4864
5385
|
}));
|
|
4865
5386
|
} else {
|
|
4866
|
-
|
|
5387
|
+
this._listenBackplane(sub, "message", (_channel, message) => {
|
|
4867
5388
|
this._handleBackplaneMessage(message);
|
|
4868
5389
|
});
|
|
4869
|
-
sub.
|
|
5390
|
+
if (typeof sub.connect === "function" && (sub.isOpen === false || sub.status === "wait")) await sub.connect();
|
|
5391
|
+
if (this._destroyed) return;
|
|
5392
|
+
await sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
|
|
4870
5393
|
channel: this.backplaneChannel,
|
|
4871
5394
|
instanceId: this.instanceId
|
|
4872
|
-
})).catch((err) => this.logger.warn("Backplane: subscribe failed", {
|
|
4873
|
-
error: err.message
|
|
4874
5395
|
}));
|
|
4875
5396
|
}
|
|
4876
|
-
this.
|
|
5397
|
+
if (!this._destroyed) this._backplaneAvailable = true;
|
|
5398
|
+
}
|
|
5399
|
+
_resetAfterStreamGap() {
|
|
5400
|
+
this.counters.streamGaps++;
|
|
5401
|
+
this._fenceInvalidation();
|
|
5402
|
+
this.l1.clear();
|
|
5403
|
+
this.tagIndex.clear();
|
|
5404
|
+
this.keyTags.clear();
|
|
5405
|
+
this.tagVersions.clear();
|
|
5406
|
+
this.dependencyIndex.clear();
|
|
5407
|
+
this.keyDependencies.clear();
|
|
5408
|
+
this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, Date.now());
|
|
5409
|
+
this._addPatternTombstone(this.nk("*"));
|
|
5410
|
+
this._lastStreamId = "0-0";
|
|
4877
5411
|
}
|
|
4878
5412
|
async _startStreamConsumer() {
|
|
5413
|
+
this._streamRecovering ||= this._lastStreamId !== "$" && this._lastStreamId !== "0-0";
|
|
4879
5414
|
const sub = this.streamClient ?? this.createDedicatedRedisClient();
|
|
4880
5415
|
this.streamClient = sub;
|
|
5416
|
+
if (typeof sub.xread !== "function") throw new Error("backplaneMode: stream requires a driver supporting XREAD");
|
|
4881
5417
|
if (typeof sub.on === "function") {
|
|
4882
|
-
|
|
4883
|
-
|
|
5418
|
+
this._listenBackplane(sub, "error", (e) => this.logger.debug("Backplane stream consumer error", { error: e.message }));
|
|
5419
|
+
this._listenBackplane(sub, "close", () => {
|
|
5420
|
+
this._streamRecovering = true;
|
|
5421
|
+
this._backplaneAvailable = false;
|
|
4884
5422
|
if (this._subDisconnectedAt === null) {
|
|
4885
5423
|
this._subDisconnectedAt = Date.now();
|
|
4886
5424
|
this.logger.debug("Backplane stream: consumer disconnected", { at: this._subDisconnectedAt });
|
|
4887
5425
|
}
|
|
4888
5426
|
});
|
|
4889
|
-
|
|
5427
|
+
this._listenBackplane(sub, "ready", () => {
|
|
4890
5428
|
if (this._subDisconnectedAt !== null) {
|
|
4891
5429
|
this.logger.debug("Backplane stream: consumer reconnected, resuming stream read", { lastId: this._lastStreamId });
|
|
4892
5430
|
this._subDisconnectedAt = null;
|
|
4893
5431
|
}
|
|
4894
5432
|
});
|
|
4895
5433
|
}
|
|
5434
|
+
const checkGap = async () => {
|
|
5435
|
+
if (this._lastStreamId === "$" || this._lastStreamId === "0-0" || typeof sub.xrange !== "function") return;
|
|
5436
|
+
const first = await sub.xrange(this.backplaneStreamKey, "-", "+", "COUNT", 1);
|
|
5437
|
+
const firstId = first?.[0]?.[0];
|
|
5438
|
+
if (!firstId) return;
|
|
5439
|
+
const [firstMs, firstSequence] = firstId.split("-").map(BigInt);
|
|
5440
|
+
const [lastMs, lastSequence] = this._lastStreamId.split("-").map(BigInt);
|
|
5441
|
+
if (firstMs > lastMs || firstMs === lastMs && firstSequence > lastSequence) this._resetAfterStreamGap();
|
|
5442
|
+
};
|
|
5443
|
+
const apply = (response) => {
|
|
5444
|
+
if (this._destroyed || !response) return;
|
|
5445
|
+
if (this._streamRecovering && response.some(([, entries]) => entries.length > 0)) {
|
|
5446
|
+
this.counters.streamReplays++;
|
|
5447
|
+
this._streamRecovering = false;
|
|
5448
|
+
}
|
|
5449
|
+
for (const [, entries] of response) {
|
|
5450
|
+
for (const [id, fields] of entries) {
|
|
5451
|
+
this._lastStreamId = id;
|
|
5452
|
+
this.counters.streamEntriesReceived++;
|
|
5453
|
+
this._processStreamEntry(fields);
|
|
5454
|
+
}
|
|
5455
|
+
}
|
|
5456
|
+
};
|
|
5457
|
+
let initialized = false;
|
|
5458
|
+
const initialize = async () => {
|
|
5459
|
+
if (typeof sub.connect === "function" && (sub.isOpen === false || sub.status === "wait")) await sub.connect();
|
|
5460
|
+
if (this._destroyed) return;
|
|
5461
|
+
if (this._lastStreamId === "$") {
|
|
5462
|
+
if (this._restoredSnapshot) this._resetAfterStreamGap();
|
|
5463
|
+
else if (typeof sub.xrevrange === "function") {
|
|
5464
|
+
const latest = await sub.xrevrange(this.backplaneStreamKey, "+", "-", "COUNT", 1);
|
|
5465
|
+
this._lastStreamId = latest?.[0]?.[0] ?? "0-0";
|
|
5466
|
+
} else this._lastStreamId = "0-0";
|
|
5467
|
+
}
|
|
5468
|
+
if (typeof sub.xrange === "function") {
|
|
5469
|
+
await checkGap();
|
|
5470
|
+
apply(await sub.xread("STREAMS", this.backplaneStreamKey, this._lastStreamId));
|
|
5471
|
+
}
|
|
5472
|
+
initialized = true;
|
|
5473
|
+
this._backplaneAvailable = true;
|
|
5474
|
+
};
|
|
5475
|
+
try {
|
|
5476
|
+
await initialize();
|
|
5477
|
+
} catch (error) {
|
|
5478
|
+
this._backplaneAvailable = false;
|
|
5479
|
+
this.logger.warn("Backplane stream initialization failed; retrying in consumer loop", { error: error.message });
|
|
5480
|
+
}
|
|
4896
5481
|
const runLoop = async () => {
|
|
4897
5482
|
while (!this._destroyed && !this._redisDisabled) {
|
|
4898
5483
|
try {
|
|
5484
|
+
if (!initialized) await initialize();
|
|
5485
|
+
if (this._destroyed) break;
|
|
5486
|
+
await checkGap();
|
|
4899
5487
|
const res = await sub.xread(
|
|
4900
5488
|
"BLOCK",
|
|
4901
5489
|
this.opts.backplaneStreamBlockMs,
|
|
@@ -4904,19 +5492,10 @@ var CacheService = class _CacheService {
|
|
|
4904
5492
|
this._lastStreamId
|
|
4905
5493
|
);
|
|
4906
5494
|
if (this._destroyed) break;
|
|
5495
|
+
this._backplaneAvailable = true;
|
|
4907
5496
|
if (res && res.length > 0) {
|
|
4908
|
-
|
|
4909
|
-
|
|
4910
|
-
if (this._lastStreamId !== "$") {
|
|
4911
|
-
this.counters.streamReplays++;
|
|
4912
|
-
}
|
|
4913
|
-
for (const [id, fields] of entries) {
|
|
4914
|
-
this._lastStreamId = id;
|
|
4915
|
-
this.counters.streamEntriesReceived++;
|
|
4916
|
-
this._processStreamEntry(fields);
|
|
4917
|
-
}
|
|
4918
|
-
}
|
|
4919
|
-
}
|
|
5497
|
+
apply(res);
|
|
5498
|
+
this._backplaneAvailable = true;
|
|
4920
5499
|
} else {
|
|
4921
5500
|
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
4922
5501
|
}
|
|
@@ -4924,10 +5503,9 @@ var CacheService = class _CacheService {
|
|
|
4924
5503
|
if (this._destroyed) break;
|
|
4925
5504
|
const msg = err.message ?? "";
|
|
4926
5505
|
if (msg.includes("NOGROUP") || msg.includes("smaller than") || msg.includes("trimmed")) {
|
|
4927
|
-
this.
|
|
4928
|
-
this.l1.clear();
|
|
4929
|
-
this._lastStreamId = "$";
|
|
5506
|
+
this._resetAfterStreamGap();
|
|
4930
5507
|
}
|
|
5508
|
+
this._backplaneAvailable = false;
|
|
4931
5509
|
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
4932
5510
|
}
|
|
4933
5511
|
}
|
|
@@ -4956,7 +5534,7 @@ var CacheService = class _CacheService {
|
|
|
4956
5534
|
else if (f === "tagVersion") tagVersionRaw = v;
|
|
4957
5535
|
}
|
|
4958
5536
|
const validOp = op === "del" || op === "del-glob" || op === "tag_incr" || op === "tag_pattern_incr" || op === "tag_pattern_del";
|
|
4959
|
-
if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
|
|
5537
|
+
if (!validOp || typeof key !== "string" || !key || typeof src !== "string" || !src || (op === "del" || op === "del-glob") && this._namespace && !key.startsWith(`${this._namespace}:`)) {
|
|
4960
5538
|
this.logger.warn("Backplane: rejected invalid stream entry", {
|
|
4961
5539
|
op: String(op).slice(0, 40),
|
|
4962
5540
|
key: typeof key === "string" ? key.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(key)
|
|
@@ -4965,8 +5543,8 @@ var CacheService = class _CacheService {
|
|
|
4965
5543
|
}
|
|
4966
5544
|
let tagVersion;
|
|
4967
5545
|
if (tagVersionRaw !== void 0) {
|
|
4968
|
-
const parsed =
|
|
4969
|
-
if (!Number.
|
|
5546
|
+
const parsed = Number(tagVersionRaw);
|
|
5547
|
+
if (!Number.isSafeInteger(parsed) || parsed < 0) {
|
|
4970
5548
|
this.logger.warn("Backplane: rejected stream entry with non-numeric tagVersion", { key });
|
|
4971
5549
|
return;
|
|
4972
5550
|
}
|
|
@@ -4984,16 +5562,10 @@ var CacheService = class _CacheService {
|
|
|
4984
5562
|
this.l1.delete(key);
|
|
4985
5563
|
this._bumpKeyMutation(key);
|
|
4986
5564
|
this.inflight.delete(key);
|
|
4987
|
-
this.
|
|
4988
|
-
setImmediate(() => {
|
|
4989
|
-
try {
|
|
4990
|
-
if (!this._diskDisabled) this.disk.delete(key);
|
|
4991
|
-
} finally {
|
|
4992
|
-
this._pendingDiskDeletes.delete(key);
|
|
4993
|
-
}
|
|
4994
|
-
});
|
|
5565
|
+
this._invalidateDiskKey(key);
|
|
4995
5566
|
this._cascadeDependencies(key);
|
|
4996
5567
|
} else if (op === "del-glob") {
|
|
5568
|
+
this._fenceInvalidation();
|
|
4997
5569
|
this.l1.deletePattern(key);
|
|
4998
5570
|
const pfx = key.endsWith("*") ? key.slice(0, -1) : key;
|
|
4999
5571
|
for (const liveKey of this.l1.liveKeys()) {
|
|
@@ -5007,12 +5579,22 @@ var CacheService = class _CacheService {
|
|
|
5007
5579
|
this.inflight.delete(inflightKey);
|
|
5008
5580
|
}
|
|
5009
5581
|
}
|
|
5010
|
-
this._addPatternTombstone(
|
|
5582
|
+
this._addPatternTombstone(key);
|
|
5583
|
+
this._removePatternFromIndices(key);
|
|
5584
|
+
if (key === this.nk("*")) {
|
|
5585
|
+
this.tagIndex.clear();
|
|
5586
|
+
this.keyTags.clear();
|
|
5587
|
+
this.tagVersions.clear();
|
|
5588
|
+
this.dependencyIndex.clear();
|
|
5589
|
+
this.keyDependencies.clear();
|
|
5590
|
+
}
|
|
5011
5591
|
} else if (op === "tag_incr") {
|
|
5592
|
+
this._fenceInvalidation();
|
|
5012
5593
|
const tag = key;
|
|
5013
5594
|
const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
5014
5595
|
this._setLocalTagVersion(tag, ver, performance.now());
|
|
5015
5596
|
} else if (op === "tag_pattern_incr") {
|
|
5597
|
+
this._fenceInvalidation();
|
|
5016
5598
|
const pattern = key;
|
|
5017
5599
|
const now = performance.now();
|
|
5018
5600
|
for (const [tag, info] of this.tagVersions) {
|
|
@@ -5032,6 +5614,7 @@ var CacheService = class _CacheService {
|
|
|
5032
5614
|
}
|
|
5033
5615
|
}, 0);
|
|
5034
5616
|
} else if (op === "tag_pattern_del") {
|
|
5617
|
+
this._fenceInvalidation();
|
|
5035
5618
|
const pattern = key;
|
|
5036
5619
|
const matchedTagKeys = [];
|
|
5037
5620
|
const prefix = this.nk("_tag_:");
|
|
@@ -5042,14 +5625,7 @@ var CacheService = class _CacheService {
|
|
|
5042
5625
|
for (const k of members) {
|
|
5043
5626
|
this.l1.delete(k);
|
|
5044
5627
|
this._bumpKeyMutation(k);
|
|
5045
|
-
this.
|
|
5046
|
-
setImmediate(() => {
|
|
5047
|
-
try {
|
|
5048
|
-
if (!this._diskDisabled) this.disk.delete(k);
|
|
5049
|
-
} finally {
|
|
5050
|
-
this._pendingDiskDeletes.delete(k);
|
|
5051
|
-
}
|
|
5052
|
-
});
|
|
5628
|
+
this._invalidateDiskKey(k);
|
|
5053
5629
|
}
|
|
5054
5630
|
}
|
|
5055
5631
|
}
|
|
@@ -5080,6 +5656,7 @@ var CacheService = class _CacheService {
|
|
|
5080
5656
|
}
|
|
5081
5657
|
}
|
|
5082
5658
|
async publishInvalidation(op, key, tagVersion, isCrossRegionRelay = false, isExplicitInvalidation = false) {
|
|
5659
|
+
if (this.opts.l2WriteMode === "read-only") return;
|
|
5083
5660
|
if (!isCrossRegionRelay && this.opts.crossRegion) {
|
|
5084
5661
|
const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
|
|
5085
5662
|
if (shouldBroadcast) {
|
|
@@ -5162,13 +5739,13 @@ var CacheService = class _CacheService {
|
|
|
5162
5739
|
timestamp: Date.now(),
|
|
5163
5740
|
namespace: this._namespace || void 0
|
|
5164
5741
|
};
|
|
5165
|
-
this.counters.crossRegionSent++;
|
|
5166
5742
|
await cr.relay.broadcast(event);
|
|
5743
|
+
this.counters.crossRegionSent++;
|
|
5167
5744
|
this.logger.debug("Cross-region invalidation broadcast", { op, key, region: cr.currentRegion });
|
|
5168
5745
|
} catch (err) {
|
|
5169
|
-
this.counters.crossRegionSent = Math.max(0, this.counters.crossRegionSent - 1);
|
|
5170
5746
|
this.counters.crossRegionErrors++;
|
|
5171
5747
|
this.logger.warn("Cross-region invalidation broadcast failed", { error: err.message });
|
|
5748
|
+
if (this.opts.awaitInvalidationBackplane) throw err;
|
|
5172
5749
|
}
|
|
5173
5750
|
}
|
|
5174
5751
|
/**
|
|
@@ -5179,11 +5756,12 @@ var CacheService = class _CacheService {
|
|
|
5179
5756
|
* Returns true if the event was accepted and applied, or false if ignored/deduplicated.
|
|
5180
5757
|
*/
|
|
5181
5758
|
async receiveCrossRegionInvalidation(event) {
|
|
5759
|
+
this._assertActive("receiveCrossRegionInvalidation");
|
|
5182
5760
|
const cr = this.opts.crossRegion;
|
|
5183
5761
|
if (!cr) return false;
|
|
5184
|
-
if (!event
|
|
5762
|
+
if (!isCrossRegionInvalidationEvent(event)) {
|
|
5185
5763
|
this.counters.crossRegionErrors++;
|
|
5186
|
-
this.logger.warn("Cross-region: rejected invalid event payload"
|
|
5764
|
+
this.logger.warn("Cross-region: rejected invalid event payload");
|
|
5187
5765
|
return false;
|
|
5188
5766
|
}
|
|
5189
5767
|
if (event.originRegion === cr.currentRegion) {
|
|
@@ -5194,13 +5772,52 @@ var CacheService = class _CacheService {
|
|
|
5194
5772
|
this.counters.crossRegionDeduplicated++;
|
|
5195
5773
|
return false;
|
|
5196
5774
|
}
|
|
5197
|
-
this._markCrossRegionEventSeen(event.id);
|
|
5198
5775
|
if (event.namespace !== void 0 && event.namespace !== (this._namespace || void 0)) {
|
|
5199
5776
|
return false;
|
|
5200
5777
|
}
|
|
5778
|
+
if ((event.op === "del" || event.op === "del-glob") && this._namespace && !event.key.startsWith(`${this._namespace}:`)) return false;
|
|
5779
|
+
this._markCrossRegionEventSeen(event.id);
|
|
5201
5780
|
this.counters.crossRegionReceived++;
|
|
5202
|
-
this.
|
|
5203
|
-
|
|
5781
|
+
const localTags = /* @__PURE__ */ new Set([...this.tagVersions.keys(), ...[...this.tagIndex.keys()].map((key) => this.unnk(key).replace(/^_tag_:/, ""))]);
|
|
5782
|
+
let version = event.tagVersion;
|
|
5783
|
+
if (event.op === "tag_incr") version = Math.max((this.tagVersions.get(event.key)?.version ?? 0) + 1, version ?? 0);
|
|
5784
|
+
this._applyInvalidationEvent(event.op, event.key, version);
|
|
5785
|
+
try {
|
|
5786
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5787
|
+
const client = await this.getRedis();
|
|
5788
|
+
if (event.op === "del" || event.op === "del-glob") {
|
|
5789
|
+
await this._deleteRedisKeys(client, event.op === "del" ? [event.key] : await this._scanKeys(client, event.key));
|
|
5790
|
+
} else if (event.op === "tag_incr") {
|
|
5791
|
+
version = Number(await client.eval(LUA_RECEIVE_TAG_VERSION, 1, this.nk(`tag_ver:${event.key}`), String(version)));
|
|
5792
|
+
this._setLocalTagVersion(event.key, version);
|
|
5793
|
+
} else {
|
|
5794
|
+
const matched = await this._resolveMatchingTags(event.key, false);
|
|
5795
|
+
for (const tag of localTags) if (matchesTagPattern(event.key, tag)) matched.add(tag);
|
|
5796
|
+
for (const tag of matched) {
|
|
5797
|
+
if (event.op === "tag_pattern_incr") {
|
|
5798
|
+
const floor = this.tagVersions.get(tag)?.version ?? 1;
|
|
5799
|
+
const next = Number(await client.eval(LUA_RECEIVE_TAG_VERSION, 1, this.nk(`tag_ver:${tag}`), String(floor)));
|
|
5800
|
+
this._setLocalTagVersion(tag, next);
|
|
5801
|
+
await this.publishInvalidation("tag_incr", tag, next, true);
|
|
5802
|
+
} else {
|
|
5803
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
5804
|
+
const members = await client.smembers(tagKey);
|
|
5805
|
+
this._removeTagMembersLocal(members);
|
|
5806
|
+
await this._deleteRedisKeys(client, [...members, tagKey]);
|
|
5807
|
+
await Promise.all(members.map((key) => this.publishInvalidation("del", key, void 0, true)));
|
|
5808
|
+
}
|
|
5809
|
+
}
|
|
5810
|
+
}
|
|
5811
|
+
this.cb.onSuccess();
|
|
5812
|
+
}
|
|
5813
|
+
await this.publishInvalidation(event.op, event.key, version, true);
|
|
5814
|
+
} catch (error) {
|
|
5815
|
+
this._seenCrossRegionEvents.delete(event.id);
|
|
5816
|
+
this.counters.crossRegionErrors++;
|
|
5817
|
+
this.logger.warn("Cross-region regional invalidation failed", { error: error.message });
|
|
5818
|
+
if (this.opts.awaitInvalidationBackplane) throw error;
|
|
5819
|
+
return false;
|
|
5820
|
+
}
|
|
5204
5821
|
this.logger.info("Cross-region invalidation applied", {
|
|
5205
5822
|
op: event.op,
|
|
5206
5823
|
key: event.key,
|
|
@@ -5215,10 +5832,10 @@ var CacheService = class _CacheService {
|
|
|
5215
5832
|
const oldestKey = this.tagVersions.keys().next().value;
|
|
5216
5833
|
if (oldestKey !== void 0) this.tagVersions.delete(oldestKey);
|
|
5217
5834
|
}
|
|
5218
|
-
this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
|
|
5835
|
+
this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now, refreshEpoch: this._tagRefreshEpoch });
|
|
5219
5836
|
}
|
|
5220
5837
|
async _isGenerationalEntryStale(tagVersions) {
|
|
5221
|
-
if (
|
|
5838
|
+
if (!tagVersions) return false;
|
|
5222
5839
|
const tags = Object.keys(tagVersions);
|
|
5223
5840
|
if (tags.length === 0) return false;
|
|
5224
5841
|
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
@@ -5230,13 +5847,23 @@ var CacheService = class _CacheService {
|
|
|
5230
5847
|
async _deleteRedisKeys(client, keys) {
|
|
5231
5848
|
if (keys.length === 0) return;
|
|
5232
5849
|
const CHUNK_SIZE = 1e3;
|
|
5233
|
-
if (client instanceof
|
|
5234
|
-
|
|
5235
|
-
|
|
5236
|
-
const
|
|
5237
|
-
|
|
5238
|
-
|
|
5239
|
-
|
|
5850
|
+
if (client instanceof import_ioredis2.Cluster) {
|
|
5851
|
+
const groups = /* @__PURE__ */ new Map();
|
|
5852
|
+
for (const key of keys) {
|
|
5853
|
+
const slot = redisHashSlot(key);
|
|
5854
|
+
const master = client.slots?.[slot]?.[0] ?? String(slot);
|
|
5855
|
+
const members = groups.get(master) ?? [];
|
|
5856
|
+
members.push(key);
|
|
5857
|
+
groups.set(master, members);
|
|
5858
|
+
}
|
|
5859
|
+
await Promise.all([...groups.values()].map(async (members) => {
|
|
5860
|
+
for (let offset = 0; offset < members.length; offset += CHUNK_SIZE) {
|
|
5861
|
+
const pipeline = client.pipeline();
|
|
5862
|
+
for (const key of members.slice(offset, offset + CHUNK_SIZE)) pipeline.del(key);
|
|
5863
|
+
const result = await pipeline.exec();
|
|
5864
|
+
if (!result || result.some(([error]) => error)) throw new Error("Redis Cluster delete failed");
|
|
5865
|
+
}
|
|
5866
|
+
}));
|
|
5240
5867
|
return;
|
|
5241
5868
|
}
|
|
5242
5869
|
for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
|
|
@@ -5249,8 +5876,11 @@ var CacheService = class _CacheService {
|
|
|
5249
5876
|
let storedTagVersions = {};
|
|
5250
5877
|
if (hashData.tv) {
|
|
5251
5878
|
try {
|
|
5252
|
-
|
|
5879
|
+
const parsed = JSON.parse(hashData.tv);
|
|
5880
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || Object.values(parsed).some((version) => !Number.isSafeInteger(version) || Number(version) < 0)) return null;
|
|
5881
|
+
storedTagVersions = parsed;
|
|
5253
5882
|
} catch {
|
|
5883
|
+
return null;
|
|
5254
5884
|
}
|
|
5255
5885
|
}
|
|
5256
5886
|
if (await this._isGenerationalEntryStale(storedTagVersions)) {
|
|
@@ -5259,18 +5889,48 @@ var CacheService = class _CacheService {
|
|
|
5259
5889
|
return { stale: true };
|
|
5260
5890
|
}
|
|
5261
5891
|
const value = await this._decryptAndDeserialize(hashData.d);
|
|
5262
|
-
|
|
5892
|
+
const expiresAt = Number(hashData.e);
|
|
5893
|
+
const staleAt = Number(hashData.s);
|
|
5894
|
+
let tags;
|
|
5895
|
+
let dependsOn;
|
|
5896
|
+
try {
|
|
5897
|
+
const parsedTags = hashData.tags ? JSON.parse(hashData.tags) : Object.keys(storedTagVersions);
|
|
5898
|
+
const parsedDependencies = hashData.deps ? JSON.parse(hashData.deps) : void 0;
|
|
5899
|
+
if (Array.isArray(parsedTags) && parsedTags.every((tag) => typeof tag === "string")) tags = parsedTags;
|
|
5900
|
+
if (Array.isArray(parsedDependencies) && parsedDependencies.every((pattern) => typeof pattern === "string")) dependsOn = parsedDependencies;
|
|
5901
|
+
} catch {
|
|
5902
|
+
return null;
|
|
5903
|
+
}
|
|
5904
|
+
return {
|
|
5905
|
+
value,
|
|
5906
|
+
tagVersions: storedTagVersions,
|
|
5907
|
+
stale: false,
|
|
5908
|
+
tags,
|
|
5909
|
+
dependsOn,
|
|
5910
|
+
setAt: Number(hashData.t) || void 0,
|
|
5911
|
+
expiresAt: Number.isFinite(expiresAt) && expiresAt > 0 ? expiresAt : void 0,
|
|
5912
|
+
staleAt: Number.isFinite(staleAt) && staleAt > 0 ? staleAt : void 0
|
|
5913
|
+
};
|
|
5263
5914
|
}
|
|
5264
5915
|
async _readRedisEntry(client, k, allowAutoPipeline = false) {
|
|
5916
|
+
const readStartedAt = Date.now();
|
|
5917
|
+
const read = async (hash) => allowAutoPipeline && this.opts.autoPipeline && this.pipeliner ? this.pipeliner.read(k, hash) : readRedisValue(client, k, hash);
|
|
5918
|
+
const withExpiry = (entry, ttlMs2) => {
|
|
5919
|
+
if (!entry || ttlMs2 === -2 || ttlMs2 === 0) return null;
|
|
5920
|
+
if (ttlMs2 !== void 0 && Number.isFinite(ttlMs2) && ttlMs2 > 0) {
|
|
5921
|
+
entry.expiresAt = Math.min(entry.expiresAt ?? Infinity, readStartedAt + ttlMs2);
|
|
5922
|
+
}
|
|
5923
|
+
return entry.expiresAt !== void 0 && entry.expiresAt <= Date.now() ? null : entry;
|
|
5924
|
+
};
|
|
5265
5925
|
if (this.opts.tagStrategy === "generational" && typeof client.hgetall === "function") {
|
|
5266
5926
|
try {
|
|
5267
|
-
const hashData = await
|
|
5927
|
+
const { raw: hashData, ttlMs: ttlMs2 } = await read(true);
|
|
5268
5928
|
if (typeof hashData === "string") {
|
|
5269
5929
|
const value2 = await this._decryptAndDeserialize(hashData);
|
|
5270
|
-
return { value: value2, stale: false };
|
|
5930
|
+
return withExpiry({ value: value2, stale: false }, ttlMs2);
|
|
5271
5931
|
}
|
|
5272
5932
|
if (hashData && hashData.d) {
|
|
5273
|
-
return await this._parseGenerationalRedisHash(k, hashData);
|
|
5933
|
+
return withExpiry(await this._parseGenerationalRedisHash(k, hashData), ttlMs2);
|
|
5274
5934
|
}
|
|
5275
5935
|
return null;
|
|
5276
5936
|
} catch (err) {
|
|
@@ -5278,28 +5938,163 @@ var CacheService = class _CacheService {
|
|
|
5278
5938
|
if (!msg.includes("WRONGTYPE")) throw err;
|
|
5279
5939
|
}
|
|
5280
5940
|
}
|
|
5281
|
-
const raw
|
|
5941
|
+
const { raw, ttlMs } = await read(false);
|
|
5282
5942
|
if (raw == null) return null;
|
|
5943
|
+
if (typeof raw !== "string") return null;
|
|
5283
5944
|
const value = await this._decryptAndDeserialize(raw);
|
|
5284
|
-
return { value, stale: false };
|
|
5945
|
+
return withExpiry({ value, stale: false }, ttlMs);
|
|
5285
5946
|
}
|
|
5286
5947
|
async _getTagVersion(tag) {
|
|
5287
5948
|
const now = performance.now();
|
|
5288
5949
|
const local = this.tagVersions.get(tag);
|
|
5289
|
-
if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
|
|
5950
|
+
if (local && (local.refreshEpoch ?? 0) === this._tagRefreshEpoch && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
|
|
5290
5951
|
return local.version;
|
|
5291
5952
|
}
|
|
5292
5953
|
if (!this._redisDisabled) {
|
|
5293
5954
|
try {
|
|
5294
5955
|
const client = await this.getRedis();
|
|
5295
5956
|
const raw = await client.get(this.nk(`tag_ver:${tag}`));
|
|
5296
|
-
const
|
|
5297
|
-
|
|
5298
|
-
|
|
5957
|
+
const parsed = raw ? Number(raw) : 0;
|
|
5958
|
+
if (!Number.isSafeInteger(parsed) || parsed < 0) throw new Error("Invalid Redis tag generation");
|
|
5959
|
+
const version2 = Math.max(this.tagVersions.get(tag)?.version ?? 0, parsed);
|
|
5960
|
+
if (this.opts.l2WriteMode === "read-write") {
|
|
5961
|
+
if (raw === null) await client.set(this.nk(`tag_ver:${tag}`), String(version2), "NX");
|
|
5962
|
+
else if (version2 > parsed) await client.eval(LUA_MAX_TAG_VERSION, 1, this.nk(`tag_ver:${tag}`), String(version2));
|
|
5963
|
+
}
|
|
5964
|
+
this._setLocalTagVersion(tag, version2, now);
|
|
5965
|
+
this.cb.onSuccess();
|
|
5966
|
+
return version2;
|
|
5299
5967
|
} catch {
|
|
5300
5968
|
}
|
|
5301
5969
|
}
|
|
5302
|
-
|
|
5970
|
+
const version = this.tagVersions.get(tag)?.version ?? local?.version ?? 0;
|
|
5971
|
+
if (this._redisDisabled) this._setLocalTagVersion(tag, version, now);
|
|
5972
|
+
return version;
|
|
5973
|
+
}
|
|
5974
|
+
async _readRedisBatch(client, keys) {
|
|
5975
|
+
const entries = /* @__PURE__ */ new Map();
|
|
5976
|
+
const groups = /* @__PURE__ */ new Map();
|
|
5977
|
+
for (const key of new Set(keys)) {
|
|
5978
|
+
const group = client instanceof import_ioredis2.Cluster ? client.slots[redisHashSlot(key)]?.[0] ?? String(redisHashSlot(key)) : "single";
|
|
5979
|
+
const members = groups.get(group) ?? [];
|
|
5980
|
+
members.push(key);
|
|
5981
|
+
groups.set(group, members);
|
|
5982
|
+
}
|
|
5983
|
+
await Promise.all([...groups.values()].map(async (members) => {
|
|
5984
|
+
for (let offset = 0; offset < members.length; offset += 1e3) {
|
|
5985
|
+
const chunk = members.slice(offset, offset + 1e3);
|
|
5986
|
+
const pipeline = typeof client.pipeline === "function" ? client.pipeline() : client.multi();
|
|
5987
|
+
const timedScripts = typeof pipeline.eval === "function";
|
|
5988
|
+
const hashes = this.opts.tagStrategy === "generational" && typeof pipeline.hgetall === "function";
|
|
5989
|
+
for (const key of chunk) {
|
|
5990
|
+
if (timedScripts) pipeline.eval(LUA_READ_CACHE_ENTRY, 1, key);
|
|
5991
|
+
else if (hashes) pipeline.hgetall(key);
|
|
5992
|
+
else pipeline.get(key);
|
|
5993
|
+
}
|
|
5994
|
+
const startedAt = Date.now();
|
|
5995
|
+
const start = performance.now();
|
|
5996
|
+
const results = await pipeline.exec();
|
|
5997
|
+
this.watchdog.recordRedis(performance.now() - start);
|
|
5998
|
+
if (!results) throw new Error("Redis batch read aborted");
|
|
5999
|
+
for (let index = 0; index < chunk.length; index++) {
|
|
6000
|
+
try {
|
|
6001
|
+
const tuple = results[index];
|
|
6002
|
+
if (!tuple) continue;
|
|
6003
|
+
let [error, raw] = tuple;
|
|
6004
|
+
let ttl;
|
|
6005
|
+
if (error?.message?.includes("WRONGTYPE")) {
|
|
6006
|
+
const fallback = await this._readRedisEntry(client, chunk[index]);
|
|
6007
|
+
if (fallback && !fallback.stale) entries.set(chunk[index], fallback);
|
|
6008
|
+
continue;
|
|
6009
|
+
}
|
|
6010
|
+
if (error) continue;
|
|
6011
|
+
if (timedScripts) {
|
|
6012
|
+
if (!Array.isArray(raw) || raw[0] === "none") continue;
|
|
6013
|
+
const kind = raw[0];
|
|
6014
|
+
ttl = Number(raw[2]);
|
|
6015
|
+
const payload = raw[1];
|
|
6016
|
+
if (kind === "hash") {
|
|
6017
|
+
if (!Array.isArray(payload) || payload.length % 2 !== 0) continue;
|
|
6018
|
+
raw = Object.fromEntries(Array.from({ length: payload.length / 2 }, (_unused, i) => [String(payload[i * 2]), String(payload[i * 2 + 1])]));
|
|
6019
|
+
} else if (kind === "string") raw = payload;
|
|
6020
|
+
else continue;
|
|
6021
|
+
if (ttl === -2 || ttl === 0) continue;
|
|
6022
|
+
}
|
|
6023
|
+
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;
|
|
6024
|
+
if (!entry || entry.stale) continue;
|
|
6025
|
+
if (ttl !== void 0 && ttl > 0) entry.expiresAt = Math.min(entry.expiresAt ?? Infinity, startedAt + ttl);
|
|
6026
|
+
if (entry.expiresAt !== void 0 && entry.expiresAt <= Date.now()) continue;
|
|
6027
|
+
entries.set(chunk[index], entry);
|
|
6028
|
+
} catch (error) {
|
|
6029
|
+
this.logger.debug("mget: skipping invalid remote entry", { key: chunk[index], error: error.message });
|
|
6030
|
+
}
|
|
6031
|
+
}
|
|
6032
|
+
}
|
|
6033
|
+
}));
|
|
6034
|
+
this.cb.onSuccess();
|
|
6035
|
+
return entries;
|
|
6036
|
+
}
|
|
6037
|
+
_promoteRedisEntry(key, entry, fallbackTtlMs, priority) {
|
|
6038
|
+
const expiresAt = entry.expiresAt ?? Date.now() + fallbackTtlMs;
|
|
6039
|
+
if (expiresAt <= Date.now()) return false;
|
|
6040
|
+
const admitted = this.l1.set(
|
|
6041
|
+
key,
|
|
6042
|
+
entry.value,
|
|
6043
|
+
expiresAt - Date.now(),
|
|
6044
|
+
priority,
|
|
6045
|
+
entry.staleAt,
|
|
6046
|
+
void 0,
|
|
6047
|
+
entry.tagVersions,
|
|
6048
|
+
entry.setAt,
|
|
6049
|
+
entry.tags,
|
|
6050
|
+
entry.dependsOn
|
|
6051
|
+
);
|
|
6052
|
+
if (admitted) this._restoreEntryMetadata(key, { ...entry, expiresAt });
|
|
6053
|
+
return true;
|
|
6054
|
+
}
|
|
6055
|
+
async _readDiskEntry(key, epoch) {
|
|
6056
|
+
if (this._diskDisabled || this._pendingDiskDeletes.has(key) || !this.watchdog.isDiskAllowed()) return null;
|
|
6057
|
+
const start = performance.now();
|
|
6058
|
+
const entry = this.disk.load(key);
|
|
6059
|
+
const elapsed = performance.now() - start;
|
|
6060
|
+
this.watchdog.recordDisk(elapsed);
|
|
6061
|
+
this.watchdog.onCanaryResult(entry !== null, elapsed);
|
|
6062
|
+
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;
|
|
6063
|
+
this.l1.importEntries([{ key, entry }], this.opts.forbiddenSnapshotPrefixes);
|
|
6064
|
+
const hit = this.l1.get(key);
|
|
6065
|
+
const value = hit ? hit.value : entry.isCompressed ? this.codec.decode(entry.data) : JSON.parse(entry.data);
|
|
6066
|
+
this._restoreEntryMetadata(key, entry);
|
|
6067
|
+
return { value, entry };
|
|
6068
|
+
}
|
|
6069
|
+
/** Common write policy and metadata across get/set/revalidation/draining. */
|
|
6070
|
+
async _writeRedisEntry(key, data, expiresAt, setAt, tagVersions, staleAt, tags, dependsOn, canCommit = () => true) {
|
|
6071
|
+
if (this._redisDisabled || this.opts.l2WriteMode !== "read-write" || !canCommit() || this._destroyed) return;
|
|
6072
|
+
const client = await this.getRedis();
|
|
6073
|
+
const stored = await this._serializeAndEncrypt(JSON.stringify(data) ?? "undefined");
|
|
6074
|
+
if (!canCommit() || this._destroyed) return;
|
|
6075
|
+
const useHash = this.opts.tagStrategy === "generational" && (tagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function");
|
|
6076
|
+
const remaining = (useHash ? expiresAt : staleAt ?? expiresAt) - Date.now();
|
|
6077
|
+
if (remaining <= 0) return;
|
|
6078
|
+
const ttl = Math.max(1, Math.ceil(remaining / 1e3));
|
|
6079
|
+
if (useHash) {
|
|
6080
|
+
const transaction = client.multi();
|
|
6081
|
+
transaction.del(key);
|
|
6082
|
+
const hash = { d: stored, t: String(setAt), tv: JSON.stringify(tagVersions ?? {}), e: String(expiresAt) };
|
|
6083
|
+
if (staleAt !== void 0) hash.s = String(staleAt);
|
|
6084
|
+
if (tags?.length) hash.tags = JSON.stringify(tags);
|
|
6085
|
+
if (dependsOn?.length) hash.deps = JSON.stringify(dependsOn);
|
|
6086
|
+
transaction.hset(key, hash);
|
|
6087
|
+
transaction.expire(key, ttl);
|
|
6088
|
+
const result = await transaction.exec();
|
|
6089
|
+
if (!result || result.some(([error]) => error)) throw new Error("Redis cache write transaction failed");
|
|
6090
|
+
} else if (this.opts.autoPipeline && this.pipeliner) {
|
|
6091
|
+
if (typeof client.pttl === "function" && typeof client.set === "function") await this.pipeliner.setpx(key, Math.ceil(remaining), stored);
|
|
6092
|
+
else await this.pipeliner.setex(key, ttl, stored);
|
|
6093
|
+
} else {
|
|
6094
|
+
if (typeof client.pttl === "function" && typeof client.set === "function") await client.set(key, stored, "PX", Math.ceil(remaining));
|
|
6095
|
+
else await client.setex(key, ttl, stored);
|
|
6096
|
+
}
|
|
6097
|
+
this.cb.onSuccess();
|
|
5303
6098
|
}
|
|
5304
6099
|
_deleteIfStale(k, setAtMs) {
|
|
5305
6100
|
this.l1.deleteIfSetBefore(k, setAtMs);
|
|
@@ -5352,7 +6147,7 @@ var CacheService = class _CacheService {
|
|
|
5352
6147
|
} else {
|
|
5353
6148
|
plain = raw;
|
|
5354
6149
|
}
|
|
5355
|
-
return JSON.parse(plain);
|
|
6150
|
+
return plain === "undefined" ? void 0 : JSON.parse(plain);
|
|
5356
6151
|
}
|
|
5357
6152
|
/**
|
|
5358
6153
|
* Scan all keys matching `pattern` across single-node or Cluster clients.
|
|
@@ -5360,7 +6155,7 @@ var CacheService = class _CacheService {
|
|
|
5360
6155
|
*/
|
|
5361
6156
|
async _scanKeys(client, pattern) {
|
|
5362
6157
|
const keys = [];
|
|
5363
|
-
if (client instanceof
|
|
6158
|
+
if (client instanceof import_ioredis2.Cluster) {
|
|
5364
6159
|
const masters = client.nodes("master");
|
|
5365
6160
|
await Promise.all(masters.map(
|
|
5366
6161
|
(node) => new Promise((resolve, reject) => {
|
|
@@ -5423,7 +6218,7 @@ var CacheService = class _CacheService {
|
|
|
5423
6218
|
let client = null;
|
|
5424
6219
|
try {
|
|
5425
6220
|
if (this.opts.redisClusterNodes?.length) {
|
|
5426
|
-
client = new
|
|
6221
|
+
client = new import_ioredis2.Cluster(this.opts.redisClusterNodes, {
|
|
5427
6222
|
redisOptions: {
|
|
5428
6223
|
tls: this.opts.redisTls ? {} : void 0,
|
|
5429
6224
|
connectTimeout: 1e4,
|
|
@@ -5443,7 +6238,7 @@ var CacheService = class _CacheService {
|
|
|
5443
6238
|
});
|
|
5444
6239
|
client.on("reconnecting", () => this.logger.debug("Redis Cluster reconnecting"));
|
|
5445
6240
|
} else if (this.opts.redisSentinel) {
|
|
5446
|
-
client = new
|
|
6241
|
+
client = new import_ioredis2.Redis({
|
|
5447
6242
|
sentinels: this.opts.redisSentinel.sentinels,
|
|
5448
6243
|
name: this.opts.redisSentinel.name,
|
|
5449
6244
|
tls: this.opts.redisTls ? {} : void 0,
|
|
@@ -5463,7 +6258,7 @@ var CacheService = class _CacheService {
|
|
|
5463
6258
|
});
|
|
5464
6259
|
client.on("reconnecting", () => this.logger.debug("Redis Sentinel reconnecting"));
|
|
5465
6260
|
} else {
|
|
5466
|
-
client = new
|
|
6261
|
+
client = new import_ioredis2.Redis({
|
|
5467
6262
|
host: this.opts.redisHost,
|
|
5468
6263
|
port: this.opts.redisPort,
|
|
5469
6264
|
tls: this.opts.redisTls ? {} : void 0,
|
|
@@ -5555,7 +6350,12 @@ var CacheService = class _CacheService {
|
|
|
5555
6350
|
try {
|
|
5556
6351
|
const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
|
|
5557
6352
|
if (entries.length === 0) return;
|
|
5558
|
-
const payload = {
|
|
6353
|
+
const payload = {
|
|
6354
|
+
version: SNAPSHOT_VERSION,
|
|
6355
|
+
writtenAt: Date.now(),
|
|
6356
|
+
entries,
|
|
6357
|
+
streamId: this.opts.backplaneMode === "stream" && this._lastStreamId !== "$" ? this._lastStreamId : void 0
|
|
6358
|
+
};
|
|
5559
6359
|
const packed = this.codec.encode(payload);
|
|
5560
6360
|
const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
|
|
5561
6361
|
const dest = altPath ?? this.opts.snapshotPath;
|
|
@@ -5623,6 +6423,9 @@ var CacheService = class _CacheService {
|
|
|
5623
6423
|
return;
|
|
5624
6424
|
}
|
|
5625
6425
|
const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
|
|
6426
|
+
this._restoredSnapshot ||= loaded > 0;
|
|
6427
|
+
if (typeof snapshot.streamId === "string" && /^\d{1,20}-\d{1,20}$/.test(snapshot.streamId)) this._lastStreamId = snapshot.streamId;
|
|
6428
|
+
for (const { key, entry } of snapshot.entries) if (this.l1.has(key)) this._restoreEntryMetadata(key, entry);
|
|
5626
6429
|
this.logger.info("Cache snapshot loaded (L1 is warm)", {
|
|
5627
6430
|
loaded,
|
|
5628
6431
|
total: snapshot.entries.length,
|
|
@@ -5647,7 +6450,12 @@ var CacheService = class _CacheService {
|
|
|
5647
6450
|
try {
|
|
5648
6451
|
const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
|
|
5649
6452
|
if (entries.length === 0) return false;
|
|
5650
|
-
const payload = {
|
|
6453
|
+
const payload = {
|
|
6454
|
+
version: SNAPSHOT_VERSION,
|
|
6455
|
+
writtenAt: Date.now(),
|
|
6456
|
+
entries,
|
|
6457
|
+
streamId: this.opts.backplaneMode === "stream" && this._lastStreamId !== "$" ? this._lastStreamId : void 0
|
|
6458
|
+
};
|
|
5651
6459
|
const packed = this.codec.encode(payload);
|
|
5652
6460
|
let final;
|
|
5653
6461
|
if (this.opts.remoteSnapshot.envelope) {
|
|
@@ -5678,13 +6486,16 @@ var CacheService = class _CacheService {
|
|
|
5678
6486
|
async loadRemoteSnapshot() {
|
|
5679
6487
|
if (!this.opts.remoteSnapshot) return 0;
|
|
5680
6488
|
const maxAgeMs = this.opts.remoteSnapshot.maxAgeMs ?? this.opts.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE;
|
|
6489
|
+
const epoch = this._globalEpoch;
|
|
5681
6490
|
try {
|
|
5682
6491
|
const raw = await this.opts.remoteSnapshot.adapter.get();
|
|
6492
|
+
if (this._destroyed || this._globalEpoch !== epoch) return 0;
|
|
5683
6493
|
if (!raw || raw.length === 0) {
|
|
5684
6494
|
this.logger.debug("Remote snapshot not found or empty \u2014 starting cold");
|
|
5685
6495
|
return 0;
|
|
5686
6496
|
}
|
|
5687
6497
|
const rawBuf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
|
|
6498
|
+
if (rawBuf.length > SNAPSHOT_MAX_FILE_BYTES) throw new Error("Remote snapshot exceeds size limit");
|
|
5688
6499
|
let buf;
|
|
5689
6500
|
try {
|
|
5690
6501
|
if (EnvelopeEncryption.isEnvelope(rawBuf)) {
|
|
@@ -5730,7 +6541,12 @@ var CacheService = class _CacheService {
|
|
|
5730
6541
|
this.logger.warn("Remote snapshot rejected: entries is not an array");
|
|
5731
6542
|
return 0;
|
|
5732
6543
|
}
|
|
5733
|
-
|
|
6544
|
+
if (this._destroyed || this._globalEpoch !== epoch) return 0;
|
|
6545
|
+
const eligible = snapshot.entries.filter((item) => item && !this._keyMutationEpochs.has(item.key));
|
|
6546
|
+
const loaded = this.l1.importEntries(eligible, this.opts.forbiddenSnapshotPrefixes);
|
|
6547
|
+
this._restoredSnapshot ||= loaded > 0;
|
|
6548
|
+
if (typeof snapshot.streamId === "string" && /^\d{1,20}-\d{1,20}$/.test(snapshot.streamId)) this._lastStreamId = snapshot.streamId;
|
|
6549
|
+
for (const { key, entry } of eligible) if (this.l1.has(key)) this._restoreEntryMetadata(key, entry);
|
|
5734
6550
|
this.counters.remoteSnapshotDownloads++;
|
|
5735
6551
|
this.counters.remoteSnapshotLastDownloadedAt = Date.now();
|
|
5736
6552
|
this.logger.info("Remote cache snapshot loaded (L1 hydrated)", {
|
|
@@ -5782,7 +6598,7 @@ var CacheService = class _CacheService {
|
|
|
5782
6598
|
const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
|
|
5783
6599
|
if (isGenerationalStale) {
|
|
5784
6600
|
this._deleteIfStale(k, l1Hit.setAt ?? 0);
|
|
5785
|
-
} else {
|
|
6601
|
+
} else if (!l1Hit.isStale || optSwr > 0) {
|
|
5786
6602
|
if (l1Hit.isStale) {
|
|
5787
6603
|
const swrGraceMs2 = optSwr * 1e3;
|
|
5788
6604
|
if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
|
|
@@ -5845,49 +6661,29 @@ var CacheService = class _CacheService {
|
|
|
5845
6661
|
this.counters.stampedes++;
|
|
5846
6662
|
this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch/read", { cacheKey });
|
|
5847
6663
|
span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
|
|
5848
|
-
return existing;
|
|
6664
|
+
return this._prepareReadValue(await existing);
|
|
5849
6665
|
}
|
|
5850
6666
|
const mutationEpochAtStart = this._getKeyMutationEpoch(k);
|
|
5851
|
-
const executionPromise = (async () => {
|
|
6667
|
+
const executionPromise = Promise.resolve().then(async () => {
|
|
5852
6668
|
try {
|
|
5853
|
-
|
|
5854
|
-
|
|
5855
|
-
|
|
5856
|
-
|
|
5857
|
-
|
|
5858
|
-
|
|
5859
|
-
|
|
5860
|
-
|
|
5861
|
-
|
|
5862
|
-
|
|
5863
|
-
|
|
5864
|
-
|
|
5865
|
-
|
|
5866
|
-
|
|
5867
|
-
|
|
5868
|
-
|
|
5869
|
-
if (isDiskStale) {
|
|
5870
|
-
this.disk.delete(k);
|
|
5871
|
-
} else {
|
|
5872
|
-
const promoted = this.l1.importEntries(
|
|
5873
|
-
[{ key: k, entry: diskHit }],
|
|
5874
|
-
this.opts.forbiddenSnapshotPrefixes
|
|
5875
|
-
);
|
|
5876
|
-
if (promoted > 0) {
|
|
5877
|
-
const l1Check = this.l1.get(k);
|
|
5878
|
-
if (l1Check !== null) {
|
|
5879
|
-
this.counters.diskHits++;
|
|
5880
|
-
this.opts.onHit?.(cacheKey, "disk");
|
|
5881
|
-
this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
|
|
5882
|
-
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
|
|
5883
|
-
if (this.opts.frozen) deepFreeze(l1Check.value);
|
|
5884
|
-
return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
|
|
5885
|
-
}
|
|
5886
|
-
}
|
|
5887
|
-
}
|
|
5888
|
-
}
|
|
5889
|
-
}
|
|
6669
|
+
const diskHit = await this._readDiskEntry(k, mutationEpochAtStart);
|
|
6670
|
+
if (diskHit && (diskHit.entry.staleAt === void 0 || diskHit.entry.staleAt > Date.now() || optSwr > 0)) {
|
|
6671
|
+
this.counters.diskHits++;
|
|
6672
|
+
this.opts.onHit?.(cacheKey, "disk");
|
|
6673
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
|
|
6674
|
+
if (diskHit.entry.staleAt !== void 0 && diskHit.entry.staleAt <= Date.now() && optSwr > 0 && !this.revalidating.has(k)) {
|
|
6675
|
+
this.revalidating.add(k);
|
|
6676
|
+
this.counters.swrRevalidations++;
|
|
6677
|
+
void this._revalidate(
|
|
6678
|
+
k,
|
|
6679
|
+
fetchFn,
|
|
6680
|
+
ttlMs,
|
|
6681
|
+
swrGraceMs,
|
|
6682
|
+
priority,
|
|
6683
|
+
diskHit.entry.tagVersions ?? Object.fromEntries((diskHit.entry.tags ?? []).map((tag) => [tag, 0]))
|
|
6684
|
+
);
|
|
5890
6685
|
}
|
|
6686
|
+
return diskHit.value;
|
|
5891
6687
|
}
|
|
5892
6688
|
if (!this._redisDisabled) {
|
|
5893
6689
|
try {
|
|
@@ -5897,23 +6693,26 @@ var CacheService = class _CacheService {
|
|
|
5897
6693
|
const redisElapsed = performance.now() - redisStart;
|
|
5898
6694
|
this.watchdog.recordRedis(redisElapsed);
|
|
5899
6695
|
this.cb.onSuccess();
|
|
5900
|
-
if (redisHit && !redisHit.stale && redisHit.
|
|
6696
|
+
if (redisHit && !redisHit.stale && (redisHit.staleAt === void 0 || redisHit.staleAt > Date.now() || optSwr > 0)) {
|
|
5901
6697
|
const parsed = redisHit.value;
|
|
5902
6698
|
if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
|
|
5903
6699
|
this.logger.debug("Aborting L2 promotion \u2014 key was mutated or deleted during Redis read", { cacheKey });
|
|
5904
6700
|
span.setAttribute("cache.aborted_mutation_race", true);
|
|
5905
6701
|
const current = this.l1.get(k);
|
|
5906
|
-
const liveVal = current && !current.isStale
|
|
5907
|
-
|
|
5908
|
-
return this.opts.cloneStrategy === "structuredClone" && liveVal != null && typeof liveVal === "object" ? structuredClone(liveVal) : liveVal;
|
|
6702
|
+
const liveVal = current && !current.isStale ? current.value : parsed;
|
|
6703
|
+
return liveVal;
|
|
5909
6704
|
}
|
|
5910
|
-
this.
|
|
6705
|
+
if (!this._promoteRedisEntry(k, redisHit, ttlMs, priority)) throw new Error("Redis entry expired during promotion");
|
|
5911
6706
|
this.counters.l2Hits++;
|
|
5912
6707
|
this.opts.onHit?.(cacheKey, "l2");
|
|
5913
6708
|
this.logger.debug(redisHit.tagVersions ? "L2 hit (Redis hash)" : "L2 hit (Redis)", { cacheKey });
|
|
5914
6709
|
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
5915
|
-
if (
|
|
5916
|
-
|
|
6710
|
+
if (redisHit.staleAt !== void 0 && redisHit.staleAt <= Date.now() && optSwr > 0 && !this.revalidating.has(k)) {
|
|
6711
|
+
this.revalidating.add(k);
|
|
6712
|
+
this.counters.swrRevalidations++;
|
|
6713
|
+
void this._revalidate(k, fetchFn, ttlMs, swrGraceMs, priority, redisHit.tagVersions);
|
|
6714
|
+
}
|
|
6715
|
+
return parsed;
|
|
5917
6716
|
}
|
|
5918
6717
|
} catch (err) {
|
|
5919
6718
|
this.cb.onFailure();
|
|
@@ -5923,6 +6722,7 @@ var CacheService = class _CacheService {
|
|
|
5923
6722
|
span.setAttribute("cache.hit", false).setAttribute("cache.hit_tier", "miss");
|
|
5924
6723
|
this.opts.onMiss?.(cacheKey);
|
|
5925
6724
|
this.counters.fetches++;
|
|
6725
|
+
const tagSnapshot = this.opts.tagStrategy === "generational" && optTags?.length ? Object.fromEntries(await Promise.all(optTags.map(async (tag) => [tag, await this._getTagVersion(tag)]))) : void 0;
|
|
5926
6726
|
const fetchStart = Date.now();
|
|
5927
6727
|
let data;
|
|
5928
6728
|
try {
|
|
@@ -5951,50 +6751,41 @@ var CacheService = class _CacheService {
|
|
|
5951
6751
|
}
|
|
5952
6752
|
const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
|
|
5953
6753
|
const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
|
|
5954
|
-
|
|
6754
|
+
const activeTagVersions = tagSnapshot;
|
|
5955
6755
|
if (optTags?.length) {
|
|
5956
6756
|
if (this.opts.tagStrategy === "generational") {
|
|
5957
|
-
|
|
5958
|
-
activeTagVersions = {};
|
|
5959
|
-
for (let i = 0; i < optTags.length; i++) {
|
|
5960
|
-
activeTagVersions[optTags[i]] = vers[i];
|
|
5961
|
-
}
|
|
6757
|
+
if (await this._isGenerationalEntryStale(tagSnapshot)) return data;
|
|
5962
6758
|
} else {
|
|
5963
|
-
await this._registerTags(k, optTags, Math.ceil(
|
|
6759
|
+
await this._registerTags(k, optTags, Math.ceil(storeTtl / 1e3));
|
|
5964
6760
|
}
|
|
5965
6761
|
}
|
|
5966
6762
|
if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
|
|
5967
6763
|
this.logger.debug("Aborting in-flight cache commit \u2014 key was mutated or deleted during fetch", { cacheKey });
|
|
5968
6764
|
span.setAttribute("cache.aborted_mutation_race", true);
|
|
5969
6765
|
const current = this.l1.get(k);
|
|
5970
|
-
if (current && !current.isStale
|
|
6766
|
+
if (current && !current.isStale) {
|
|
5971
6767
|
const freshVal = current.value;
|
|
5972
|
-
|
|
5973
|
-
return this.opts.cloneStrategy === "structuredClone" && freshVal != null && typeof freshVal === "object" ? structuredClone(freshVal) : freshVal;
|
|
6768
|
+
return freshVal;
|
|
5974
6769
|
}
|
|
5975
|
-
|
|
5976
|
-
return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
|
|
6770
|
+
return data;
|
|
5977
6771
|
}
|
|
5978
6772
|
const writeTs = Date.now();
|
|
5979
|
-
this.
|
|
5980
|
-
|
|
6773
|
+
this._invalidateDiskKey(k);
|
|
6774
|
+
this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs, optTags, opts.dependsOn);
|
|
6775
|
+
this._restoreEntryMetadata(k, { tags: optTags, dependsOn: opts.dependsOn, expiresAt: writeTs + storeTtl });
|
|
6776
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5981
6777
|
try {
|
|
5982
|
-
|
|
5983
|
-
|
|
5984
|
-
|
|
5985
|
-
|
|
5986
|
-
|
|
5987
|
-
|
|
5988
|
-
|
|
5989
|
-
|
|
5990
|
-
|
|
5991
|
-
|
|
5992
|
-
|
|
5993
|
-
tx.expire(k, ttlSec);
|
|
5994
|
-
await tx.exec();
|
|
5995
|
-
} else {
|
|
5996
|
-
await client.setex(k, ttlSec, toStore);
|
|
5997
|
-
}
|
|
6778
|
+
await this._writeRedisEntry(
|
|
6779
|
+
k,
|
|
6780
|
+
data,
|
|
6781
|
+
writeTs + storeTtl,
|
|
6782
|
+
writeTs,
|
|
6783
|
+
activeTagVersions,
|
|
6784
|
+
staleAt,
|
|
6785
|
+
optTags,
|
|
6786
|
+
opts.dependsOn,
|
|
6787
|
+
() => this._getKeyMutationEpoch(k) === mutationEpochAtStart
|
|
6788
|
+
);
|
|
5998
6789
|
this.cb.onSuccess();
|
|
5999
6790
|
this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
|
|
6000
6791
|
} catch {
|
|
@@ -6004,15 +6795,14 @@ var CacheService = class _CacheService {
|
|
|
6004
6795
|
} else {
|
|
6005
6796
|
this.logger.debug("Cached L1", { cacheKey });
|
|
6006
6797
|
}
|
|
6007
|
-
|
|
6008
|
-
return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
|
|
6798
|
+
return data;
|
|
6009
6799
|
} finally {
|
|
6010
|
-
this.inflight.delete(k);
|
|
6800
|
+
if (this.inflight.get(k) === executionPromise) this.inflight.delete(k);
|
|
6011
6801
|
span.end();
|
|
6012
6802
|
}
|
|
6013
|
-
})
|
|
6803
|
+
});
|
|
6014
6804
|
this.inflight.set(k, executionPromise);
|
|
6015
|
-
return executionPromise;
|
|
6805
|
+
return this._prepareReadValue(await executionPromise);
|
|
6016
6806
|
}
|
|
6017
6807
|
/**
|
|
6018
6808
|
* Graceful shutdown flusher for Kubernetes preStop hooks, NestJS onApplicationShutdown,
|
|
@@ -6093,6 +6883,9 @@ var CacheService = class _CacheService {
|
|
|
6093
6883
|
}
|
|
6094
6884
|
async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority, knownTagVersions) {
|
|
6095
6885
|
const startEpoch = this._getKeyMutationEpoch(cacheKey);
|
|
6886
|
+
const previous = this.l1.getEntry(cacheKey);
|
|
6887
|
+
const tags = previous?.tags ?? Object.keys(knownTagVersions ?? {});
|
|
6888
|
+
const dependencies = previous?.dependsOn;
|
|
6096
6889
|
try {
|
|
6097
6890
|
const fetchStart = Date.now();
|
|
6098
6891
|
const data = await fetchFn();
|
|
@@ -6107,14 +6900,14 @@ var CacheService = class _CacheService {
|
|
|
6107
6900
|
const l1Existing = this.l1.get(cacheKey);
|
|
6108
6901
|
const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
|
|
6109
6902
|
if (this.opts.tagStrategy === "generational" && tagVersionsSource) {
|
|
6110
|
-
const
|
|
6111
|
-
const vers = await Promise.all(
|
|
6903
|
+
const tags2 = Object.keys(tagVersionsSource);
|
|
6904
|
+
const vers = await Promise.all(tags2.map((tag) => this._getTagVersion(tag)));
|
|
6112
6905
|
activeTagVersions = {};
|
|
6113
|
-
for (let i = 0; i <
|
|
6114
|
-
activeTagVersions[
|
|
6906
|
+
for (let i = 0; i < tags2.length; i++) {
|
|
6907
|
+
activeTagVersions[tags2[i]] = vers[i];
|
|
6115
6908
|
}
|
|
6116
6909
|
if (knownTagVersions) {
|
|
6117
|
-
for (const t of
|
|
6910
|
+
for (const t of tags2) {
|
|
6118
6911
|
if (knownTagVersions[t] !== void 0 && activeTagVersions[t] !== knownTagVersions[t]) {
|
|
6119
6912
|
this.logger.debug("SWR: aborting revalidation commit \u2014 tag version bumped during revalidation", { cacheKey, tag: t });
|
|
6120
6913
|
return;
|
|
@@ -6127,31 +6920,28 @@ var CacheService = class _CacheService {
|
|
|
6127
6920
|
return;
|
|
6128
6921
|
}
|
|
6129
6922
|
const writeTs = Date.now();
|
|
6130
|
-
this.
|
|
6923
|
+
this._invalidateDiskKey(cacheKey);
|
|
6924
|
+
this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs, tags, dependencies);
|
|
6925
|
+
this._restoreEntryMetadata(cacheKey, { tags, dependsOn: dependencies, expiresAt: writeTs + ttlMs + swrGraceMs });
|
|
6131
6926
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
6132
6927
|
try {
|
|
6133
|
-
|
|
6134
|
-
|
|
6135
|
-
|
|
6136
|
-
|
|
6137
|
-
|
|
6138
|
-
|
|
6139
|
-
|
|
6140
|
-
|
|
6141
|
-
|
|
6142
|
-
|
|
6143
|
-
|
|
6144
|
-
tx.expire(cacheKey, ttlSec);
|
|
6145
|
-
await tx.exec();
|
|
6146
|
-
} else {
|
|
6147
|
-
await client.setex(cacheKey, ttlSec, stored);
|
|
6148
|
-
}
|
|
6928
|
+
await this._writeRedisEntry(
|
|
6929
|
+
cacheKey,
|
|
6930
|
+
data,
|
|
6931
|
+
writeTs + ttlMs + swrGraceMs,
|
|
6932
|
+
writeTs,
|
|
6933
|
+
activeTagVersions,
|
|
6934
|
+
staleAt,
|
|
6935
|
+
tags,
|
|
6936
|
+
dependencies,
|
|
6937
|
+
() => this._getKeyMutationEpoch(cacheKey) === startEpoch
|
|
6938
|
+
);
|
|
6149
6939
|
} catch {
|
|
6150
6940
|
}
|
|
6151
6941
|
}
|
|
6152
6942
|
this.logger.debug("SWR: revalidation complete", { cacheKey });
|
|
6153
6943
|
} catch (err) {
|
|
6154
|
-
if (this.opts.staleIfError > 0) {
|
|
6944
|
+
if (this.opts.staleIfError > 0 && this._getKeyMutationEpoch(cacheKey) === startEpoch) {
|
|
6155
6945
|
const additionalMs = this.opts.staleIfError * 1e3;
|
|
6156
6946
|
this.l1.bumpExpiry(cacheKey, additionalMs);
|
|
6157
6947
|
this.logger.debug("SWR: revalidation failed, stale-if-error extending expiry", {
|
|
@@ -6179,12 +6969,16 @@ var CacheService = class _CacheService {
|
|
|
6179
6969
|
const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
|
|
6180
6970
|
const p = priority ?? inferPriority(cacheKey);
|
|
6181
6971
|
const k = this.nk(cacheKey);
|
|
6972
|
+
const existingEntry = this.l1.getEntry(k);
|
|
6973
|
+
const requestedTags = opts?.tags ?? existingEntry?.tags ?? this.keyTags.get(k)?.tags;
|
|
6974
|
+
const requestedDependencies = opts?.dependsOn ?? existingEntry?.dependsOn;
|
|
6182
6975
|
this._bumpKeyMutation(k);
|
|
6976
|
+
const epoch = this._getKeyMutationEpoch(k);
|
|
6183
6977
|
this.inflight.delete(k);
|
|
6184
|
-
this.
|
|
6978
|
+
this._invalidateDiskKey(k);
|
|
6185
6979
|
this.counters.sets++;
|
|
6186
6980
|
let activeTagVersions;
|
|
6187
|
-
const tagsToRegister =
|
|
6981
|
+
const tagsToRegister = requestedTags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(requestedTags, this.opts.tagHierarchyDelimiter) : requestedTags : void 0;
|
|
6188
6982
|
if (tagsToRegister?.length) {
|
|
6189
6983
|
if (this.opts.tagStrategy === "generational") {
|
|
6190
6984
|
const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
|
|
@@ -6193,50 +6987,27 @@ var CacheService = class _CacheService {
|
|
|
6193
6987
|
activeTagVersions[tagsToRegister[i]] = vers[i];
|
|
6194
6988
|
}
|
|
6195
6989
|
} else {
|
|
6196
|
-
await this._registerTags(k, tagsToRegister,
|
|
6990
|
+
await this._registerTags(k, tagsToRegister, effectiveTtlSeconds);
|
|
6197
6991
|
}
|
|
6198
6992
|
}
|
|
6993
|
+
if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return;
|
|
6199
6994
|
const writeTs = Date.now();
|
|
6200
|
-
this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions, writeTs);
|
|
6201
|
-
|
|
6202
|
-
|
|
6203
|
-
if (opts.dependsOn.length > 0) {
|
|
6204
|
-
const nsPatterns = [];
|
|
6205
|
-
for (const pattern of opts.dependsOn) {
|
|
6206
|
-
const nsPattern = this.nk(pattern);
|
|
6207
|
-
nsPatterns.push(nsPattern);
|
|
6208
|
-
let deps = this.dependencyIndex.get(nsPattern);
|
|
6209
|
-
if (!deps) {
|
|
6210
|
-
deps = /* @__PURE__ */ new Set();
|
|
6211
|
-
this.dependencyIndex.set(nsPattern, deps);
|
|
6212
|
-
}
|
|
6213
|
-
deps.add(k);
|
|
6214
|
-
}
|
|
6215
|
-
this.keyDependencies.set(k, nsPatterns);
|
|
6216
|
-
}
|
|
6217
|
-
}
|
|
6995
|
+
this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions, writeTs, tagsToRegister, requestedDependencies);
|
|
6996
|
+
this._rememberTags(k, tagsToRegister ?? [], writeTs + ttlMs);
|
|
6997
|
+
this._registerDependencies(k, requestedDependencies);
|
|
6218
6998
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
6219
6999
|
try {
|
|
6220
|
-
|
|
6221
|
-
|
|
6222
|
-
|
|
6223
|
-
|
|
6224
|
-
|
|
6225
|
-
|
|
6226
|
-
|
|
6227
|
-
|
|
6228
|
-
|
|
6229
|
-
|
|
6230
|
-
|
|
6231
|
-
tx.expire(k, ttlSec);
|
|
6232
|
-
await tx.exec();
|
|
6233
|
-
} else {
|
|
6234
|
-
if (this.opts.autoPipeline && this.pipeliner) {
|
|
6235
|
-
await this.pipeliner.setex(k, ttlSec, stored);
|
|
6236
|
-
} else {
|
|
6237
|
-
await client.setex(k, ttlSec, stored);
|
|
6238
|
-
}
|
|
6239
|
-
}
|
|
7000
|
+
await this._writeRedisEntry(
|
|
7001
|
+
k,
|
|
7002
|
+
data,
|
|
7003
|
+
writeTs + ttlMs,
|
|
7004
|
+
writeTs,
|
|
7005
|
+
activeTagVersions,
|
|
7006
|
+
void 0,
|
|
7007
|
+
tagsToRegister,
|
|
7008
|
+
requestedDependencies,
|
|
7009
|
+
() => this._getKeyMutationEpoch(k) === epoch
|
|
7010
|
+
);
|
|
6240
7011
|
this.cb.onSuccess();
|
|
6241
7012
|
} catch (err) {
|
|
6242
7013
|
this.cb.onFailure();
|
|
@@ -6261,27 +7032,10 @@ var CacheService = class _CacheService {
|
|
|
6261
7032
|
* the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
|
|
6262
7033
|
*/
|
|
6263
7034
|
async _registerTags(k, tags, ttlSeconds) {
|
|
6264
|
-
this._removeKeyTags(k);
|
|
6265
7035
|
const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
|
|
6266
7036
|
const expiresAt = Date.now() + effectiveTtl * 1e3;
|
|
6267
|
-
if (this.keyTags.size >= 1e5 && !this.keyTags.has(k)) {
|
|
6268
|
-
this._sweepExpiredMetadata();
|
|
6269
|
-
if (this.keyTags.size >= 1e5) {
|
|
6270
|
-
const oldestKey = this.keyTags.keys().next().value;
|
|
6271
|
-
if (oldestKey !== void 0) this._removeKeyTags(oldestKey);
|
|
6272
|
-
}
|
|
6273
|
-
}
|
|
6274
7037
|
const uniqueTags = Array.from(new Set(tags));
|
|
6275
|
-
|
|
6276
|
-
const tagKey = this.nk(`_tag_:${tag}`);
|
|
6277
|
-
let members = this.tagIndex.get(tagKey);
|
|
6278
|
-
if (!members) {
|
|
6279
|
-
members = /* @__PURE__ */ new Set();
|
|
6280
|
-
this.tagIndex.set(tagKey, members);
|
|
6281
|
-
}
|
|
6282
|
-
members.add(k);
|
|
6283
|
-
}
|
|
6284
|
-
this.keyTags.set(k, { tags: uniqueTags, expiresAt });
|
|
7038
|
+
this._rememberTags(k, uniqueTags, expiresAt);
|
|
6285
7039
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
6286
7040
|
try {
|
|
6287
7041
|
const client = await this.getRedis();
|
|
@@ -6314,6 +7068,7 @@ var CacheService = class _CacheService {
|
|
|
6314
7068
|
const k = this.nk(cacheKey);
|
|
6315
7069
|
this.counters.deletes++;
|
|
6316
7070
|
if (isPattern) {
|
|
7071
|
+
this._fenceInvalidation();
|
|
6317
7072
|
const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
|
|
6318
7073
|
for (const liveKey of this.l1.liveKeys()) {
|
|
6319
7074
|
if (liveKey.startsWith(pfx)) {
|
|
@@ -6326,9 +7081,9 @@ var CacheService = class _CacheService {
|
|
|
6326
7081
|
this.inflight.delete(inflightKey);
|
|
6327
7082
|
}
|
|
6328
7083
|
}
|
|
6329
|
-
this._addPatternTombstone(
|
|
7084
|
+
this._addPatternTombstone(k);
|
|
6330
7085
|
this.l1.deletePattern(k);
|
|
6331
|
-
this.
|
|
7086
|
+
this._removePatternFromIndices(k);
|
|
6332
7087
|
for (const ktKey of Array.from(this.keyTags.keys())) {
|
|
6333
7088
|
if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
|
|
6334
7089
|
}
|
|
@@ -6339,14 +7094,7 @@ var CacheService = class _CacheService {
|
|
|
6339
7094
|
this._bumpKeyMutation(k);
|
|
6340
7095
|
this.inflight.delete(k);
|
|
6341
7096
|
this.l1.delete(k);
|
|
6342
|
-
this.
|
|
6343
|
-
setImmediate(() => {
|
|
6344
|
-
try {
|
|
6345
|
-
if (!this._diskDisabled) this.disk.delete(k);
|
|
6346
|
-
} finally {
|
|
6347
|
-
this._pendingDiskDeletes.delete(k);
|
|
6348
|
-
}
|
|
6349
|
-
});
|
|
7097
|
+
this._invalidateDiskKey(k);
|
|
6350
7098
|
this._removeKeyTags(k);
|
|
6351
7099
|
this._cascadeDependencies(k);
|
|
6352
7100
|
this._removeKeyDependencies(k);
|
|
@@ -6403,7 +7151,7 @@ var CacheService = class _CacheService {
|
|
|
6403
7151
|
async increment(cacheKey, ttlSeconds) {
|
|
6404
7152
|
this._assertActive("increment");
|
|
6405
7153
|
const k = this.nk(cacheKey);
|
|
6406
|
-
if (this._redisDisabled) {
|
|
7154
|
+
if (this._redisDisabled || this.opts.l2WriteMode === "read-only") {
|
|
6407
7155
|
if (!this._incrementFallbackWarned) {
|
|
6408
7156
|
this._incrementFallbackWarned = true;
|
|
6409
7157
|
this.logger.warn(
|
|
@@ -6459,6 +7207,7 @@ var CacheService = class _CacheService {
|
|
|
6459
7207
|
this.counters.deletes++;
|
|
6460
7208
|
const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
|
|
6461
7209
|
if (k) {
|
|
7210
|
+
this._fenceInvalidation();
|
|
6462
7211
|
const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
|
|
6463
7212
|
for (const liveKey of this.l1.liveKeys()) {
|
|
6464
7213
|
if (liveKey.startsWith(pfx)) {
|
|
@@ -6471,9 +7220,9 @@ var CacheService = class _CacheService {
|
|
|
6471
7220
|
this.inflight.delete(inflightKey);
|
|
6472
7221
|
}
|
|
6473
7222
|
}
|
|
6474
|
-
this._addPatternTombstone(
|
|
7223
|
+
this._addPatternTombstone(k);
|
|
6475
7224
|
this.l1.deletePattern(k);
|
|
6476
|
-
this.
|
|
7225
|
+
this._removePatternFromIndices(k);
|
|
6477
7226
|
} else {
|
|
6478
7227
|
this._globalEpoch++;
|
|
6479
7228
|
this.inflight.clear();
|
|
@@ -6623,28 +7372,34 @@ var CacheService = class _CacheService {
|
|
|
6623
7372
|
this._assertActive("scan");
|
|
6624
7373
|
const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
|
|
6625
7374
|
this.l1.scan((key, entry, pfx) => {
|
|
6626
|
-
|
|
6627
|
-
fn(key, value, pfx);
|
|
7375
|
+
fn(key, this._prepareReadValue(this.l1.resolveValue(entry)), pfx);
|
|
6628
7376
|
}, prefixLen);
|
|
6629
7377
|
}
|
|
6630
7378
|
/**
|
|
6631
|
-
|
|
7379
|
+
* Extend the TTL of a key in L1 and Redis without fetching.
|
|
6632
7380
|
* Returns `false` if the key is absent or already expired.
|
|
6633
7381
|
*
|
|
6634
7382
|
* @param newTtlSeconds - The new TTL from now, in seconds.
|
|
6635
7383
|
*/
|
|
6636
7384
|
async touch(cacheKey, newTtlSeconds) {
|
|
6637
7385
|
this._assertActive("touch");
|
|
7386
|
+
if (!Number.isFinite(newTtlSeconds) || newTtlSeconds <= 0) throw new Error("touch TTL must be finite and positive");
|
|
6638
7387
|
const k = this.nk(cacheKey);
|
|
7388
|
+
const epoch = this._getKeyMutationEpoch(k);
|
|
6639
7389
|
const hit = this.l1.touch(k, newTtlSeconds * 1e3);
|
|
7390
|
+
const entry = this.l1.getEntry(k);
|
|
6640
7391
|
if (hit) {
|
|
6641
7392
|
const kt = this.keyTags.get(k);
|
|
6642
7393
|
if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1e3;
|
|
6643
7394
|
}
|
|
6644
|
-
if (hit && !this._redisDisabled) {
|
|
7395
|
+
if (hit && !this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
6645
7396
|
try {
|
|
6646
7397
|
const client = await this.getRedis();
|
|
6647
|
-
|
|
7398
|
+
if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return hit;
|
|
7399
|
+
if (entry && typeof client.pttl === "function" && typeof client.eval === "function") {
|
|
7400
|
+
await client.eval(LUA_TOUCH_CACHE_ENTRY, 1, k, String(entry.setAt ?? 0), String(entry.expiresAt), String(Math.ceil(newTtlSeconds * 1e3)));
|
|
7401
|
+
} else await client.expire(k, Math.ceil(newTtlSeconds));
|
|
7402
|
+
this.cb.onSuccess();
|
|
6648
7403
|
} catch {
|
|
6649
7404
|
}
|
|
6650
7405
|
}
|
|
@@ -6666,7 +7421,8 @@ var CacheService = class _CacheService {
|
|
|
6666
7421
|
const now = Date.now();
|
|
6667
7422
|
if (entry.expiresAt <= now) return null;
|
|
6668
7423
|
if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
|
|
6669
|
-
|
|
7424
|
+
if (entry.tagVersions && Object.entries(entry.tagVersions).some(([tag, version]) => (this.tagVersions.get(tag)?.version ?? 0) > version)) return null;
|
|
7425
|
+
return this._prepareReadValue(entry.value !== void 0 ? entry.value : this.codec.decode(entry.data));
|
|
6670
7426
|
}
|
|
6671
7427
|
_prepareReadValue(val) {
|
|
6672
7428
|
if (this.opts.frozen) deepFreeze(val);
|
|
@@ -6683,49 +7439,23 @@ var CacheService = class _CacheService {
|
|
|
6683
7439
|
async peek(cacheKey) {
|
|
6684
7440
|
this._assertActive("peek");
|
|
6685
7441
|
const k = this.nk(cacheKey);
|
|
7442
|
+
const epoch = this._getKeyMutationEpoch(k);
|
|
7443
|
+
this.counters.gets++;
|
|
6686
7444
|
const l1Hit = this.l1.get(k);
|
|
6687
7445
|
if (l1Hit !== null) {
|
|
6688
7446
|
if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
|
|
6689
7447
|
this._deleteIfStale(k, l1Hit.setAt ?? 0);
|
|
6690
7448
|
} else {
|
|
6691
|
-
this.counters.gets++;
|
|
6692
7449
|
this.counters.l1Hits++;
|
|
6693
7450
|
return this._prepareReadValue(l1Hit.value);
|
|
6694
7451
|
}
|
|
6695
7452
|
}
|
|
6696
|
-
|
|
6697
|
-
|
|
6698
|
-
|
|
6699
|
-
|
|
6700
|
-
} catch {
|
|
6701
|
-
}
|
|
6702
|
-
} else if (this.watchdog.isDiskAllowed()) {
|
|
6703
|
-
const diskStart = performance.now();
|
|
6704
|
-
const diskHit = this.disk.load(k);
|
|
6705
|
-
const diskElapsed = performance.now() - diskStart;
|
|
6706
|
-
this.watchdog.recordDisk(diskElapsed);
|
|
6707
|
-
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
6708
|
-
if (diskHit !== null) {
|
|
6709
|
-
if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
|
|
6710
|
-
this.disk.delete(k);
|
|
6711
|
-
} else {
|
|
6712
|
-
const promoted = this.l1.importEntries(
|
|
6713
|
-
[{ key: k, entry: diskHit }],
|
|
6714
|
-
this.opts.forbiddenSnapshotPrefixes
|
|
6715
|
-
);
|
|
6716
|
-
if (promoted > 0) {
|
|
6717
|
-
const l1Check = this.l1.get(k);
|
|
6718
|
-
if (l1Check !== null) {
|
|
6719
|
-
this.counters.gets++;
|
|
6720
|
-
this.counters.diskHits++;
|
|
6721
|
-
return this._prepareReadValue(l1Check.value);
|
|
6722
|
-
}
|
|
6723
|
-
}
|
|
6724
|
-
}
|
|
6725
|
-
}
|
|
6726
|
-
}
|
|
7453
|
+
const diskHit = await this._readDiskEntry(k, epoch);
|
|
7454
|
+
if (diskHit) {
|
|
7455
|
+
this.counters.diskHits++;
|
|
7456
|
+
return this._prepareReadValue(diskHit.value);
|
|
6727
7457
|
}
|
|
6728
|
-
if (!this._redisDisabled
|
|
7458
|
+
if (!this._redisDisabled) {
|
|
6729
7459
|
try {
|
|
6730
7460
|
const client = await this.getRedis();
|
|
6731
7461
|
const redisStart = performance.now();
|
|
@@ -6733,10 +7463,10 @@ var CacheService = class _CacheService {
|
|
|
6733
7463
|
const redisElapsed = performance.now() - redisStart;
|
|
6734
7464
|
this.watchdog.recordRedis(redisElapsed);
|
|
6735
7465
|
this.cb.onSuccess();
|
|
6736
|
-
if (redisHit && !redisHit.stale
|
|
7466
|
+
if (redisHit && !redisHit.stale) {
|
|
6737
7467
|
const parsed = redisHit.value;
|
|
6738
|
-
this.
|
|
6739
|
-
this.
|
|
7468
|
+
if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return null;
|
|
7469
|
+
if (!this._promoteRedisEntry(k, redisHit, 6e4, inferPriority(cacheKey))) return null;
|
|
6740
7470
|
this.counters.l2Hits++;
|
|
6741
7471
|
return this._prepareReadValue(parsed);
|
|
6742
7472
|
}
|
|
@@ -6758,6 +7488,8 @@ var CacheService = class _CacheService {
|
|
|
6758
7488
|
*/
|
|
6759
7489
|
async mget(keys, fetchFn, ttl = 300, priority) {
|
|
6760
7490
|
this._assertActive("mget");
|
|
7491
|
+
this.counters.gets += keys.length;
|
|
7492
|
+
const epochs = new Map(keys.map((key) => [this.nk(key), this._getKeyMutationEpoch(this.nk(key))]));
|
|
6761
7493
|
const span = this._startSpan("tricache.mget");
|
|
6762
7494
|
if (this.opts.tracer) {
|
|
6763
7495
|
span.setAttribute("cache.batch.size", keys.length);
|
|
@@ -6770,7 +7502,7 @@ var CacheService = class _CacheService {
|
|
|
6770
7502
|
for (let i = 0; i < keys.length; i++) {
|
|
6771
7503
|
const k = this.nk(keys[i]);
|
|
6772
7504
|
const entry = this.l1.getEntry(k);
|
|
6773
|
-
if (entry && entry.expiresAt > now) {
|
|
7505
|
+
if (entry && entry.expiresAt > now && (entry.staleAt === void 0 || entry.staleAt > now)) {
|
|
6774
7506
|
if (await this._isGenerationalEntryStale(entry.tagVersions)) {
|
|
6775
7507
|
this._deleteIfStale(k, entry.setAt ?? 0);
|
|
6776
7508
|
missIndexes.push(i);
|
|
@@ -6799,64 +7531,24 @@ var CacheService = class _CacheService {
|
|
|
6799
7531
|
try {
|
|
6800
7532
|
const client = await this.getRedis();
|
|
6801
7533
|
const nsKeys = missKeys.map((k) => this.nk(k));
|
|
6802
|
-
const
|
|
6803
|
-
const useHashPipeline = this.opts.tagStrategy === "generational" && typeof pipeline.hgetall === "function";
|
|
6804
|
-
for (const nk of nsKeys) {
|
|
6805
|
-
if (useHashPipeline) {
|
|
6806
|
-
pipeline.hgetall(nk);
|
|
6807
|
-
} else {
|
|
6808
|
-
pipeline.get(nk);
|
|
6809
|
-
}
|
|
6810
|
-
}
|
|
6811
|
-
const redisStart = performance.now();
|
|
6812
|
-
const raws = await pipeline.exec();
|
|
6813
|
-
const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
|
|
6814
|
-
this.watchdog.recordRedis(redisElapsed);
|
|
6815
|
-
this.cb.onSuccess();
|
|
7534
|
+
const remoteEntries = await this._readRedisBatch(client, nsKeys);
|
|
6816
7535
|
for (let j = 0; j < missKeys.length; j++) {
|
|
6817
|
-
const tuple = raws[j];
|
|
6818
|
-
const err = tuple ? tuple[0] : null;
|
|
6819
|
-
const rawVal = tuple ? tuple[1] : null;
|
|
6820
7536
|
const idx = missIndexes[j];
|
|
6821
7537
|
const k = nsKeys[j];
|
|
6822
|
-
|
|
6823
|
-
|
|
6824
|
-
let hit = false;
|
|
6825
|
-
if (useHashPipeline) {
|
|
6826
|
-
if (err && err.message?.includes("WRONGTYPE")) {
|
|
6827
|
-
const fallbackRaw = await client.get(k);
|
|
6828
|
-
if (fallbackRaw) {
|
|
6829
|
-
parsed = await this._decryptAndDeserialize(fallbackRaw);
|
|
6830
|
-
hit = true;
|
|
6831
|
-
}
|
|
6832
|
-
} else if (!err && typeof rawVal === "string") {
|
|
6833
|
-
parsed = await this._decryptAndDeserialize(rawVal);
|
|
6834
|
-
hit = true;
|
|
6835
|
-
} else if (!err && rawVal && typeof rawVal === "object" && rawVal.d) {
|
|
6836
|
-
const hashHit = await this._parseGenerationalRedisHash(k, rawVal);
|
|
6837
|
-
if (hashHit && !hashHit.stale && hashHit.value !== void 0) {
|
|
6838
|
-
parsed = hashHit.value;
|
|
6839
|
-
tagVersions = hashHit.tagVersions;
|
|
6840
|
-
hit = true;
|
|
6841
|
-
}
|
|
6842
|
-
}
|
|
6843
|
-
} else if (!err && rawVal) {
|
|
6844
|
-
parsed = await this._decryptAndDeserialize(rawVal);
|
|
6845
|
-
hit = true;
|
|
6846
|
-
}
|
|
6847
|
-
if (hit && parsed !== void 0) {
|
|
7538
|
+
const entry = remoteEntries.get(k);
|
|
7539
|
+
if (entry && (entry.staleAt === void 0 || entry.staleAt > Date.now()) && !this._destroyed && this._getKeyMutationEpoch(k) === epochs.get(k)) {
|
|
6848
7540
|
const p = priority ?? inferPriority(missKeys[j]);
|
|
6849
7541
|
const ttlVal = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
|
|
6850
|
-
this.
|
|
7542
|
+
if (!this._promoteRedisEntry(k, entry, this._jitterTtl(ttlVal * 1e3), p)) continue;
|
|
6851
7543
|
this.counters.l2Hits++;
|
|
6852
7544
|
l2HitCount++;
|
|
6853
|
-
result[idx] = this._prepareReadValue(
|
|
7545
|
+
result[idx] = this._prepareReadValue(entry.value);
|
|
6854
7546
|
missIndexes[j] = -1;
|
|
6855
7547
|
missKeys[j] = "";
|
|
6856
7548
|
}
|
|
6857
7549
|
}
|
|
6858
7550
|
const remainingIdx = missIndexes.filter((i) => i >= 0);
|
|
6859
|
-
const remainingKeys = missKeys.filter((
|
|
7551
|
+
const remainingKeys = missKeys.filter((_key, index) => missIndexes[index] >= 0);
|
|
6860
7552
|
missIndexes.length = 0;
|
|
6861
7553
|
missKeys.length = 0;
|
|
6862
7554
|
missIndexes.push(...remainingIdx);
|
|
@@ -6869,62 +7561,64 @@ var CacheService = class _CacheService {
|
|
|
6869
7561
|
if (!this._diskDisabled && missKeys.length > 0) {
|
|
6870
7562
|
for (let j = missKeys.length - 1; j >= 0; j--) {
|
|
6871
7563
|
const k = this.nk(missKeys[j]);
|
|
6872
|
-
|
|
6873
|
-
if (
|
|
6874
|
-
|
|
6875
|
-
|
|
6876
|
-
|
|
6877
|
-
|
|
6878
|
-
continue;
|
|
6879
|
-
}
|
|
6880
|
-
if (!this.watchdog.isDiskAllowed()) continue;
|
|
6881
|
-
const diskStart = performance.now();
|
|
6882
|
-
const diskHit = this.disk.load(k);
|
|
6883
|
-
const diskElapsed = performance.now() - diskStart;
|
|
6884
|
-
this.watchdog.recordDisk(diskElapsed);
|
|
6885
|
-
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
6886
|
-
if (diskHit !== null) {
|
|
6887
|
-
if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
|
|
6888
|
-
this.disk.delete(k);
|
|
6889
|
-
continue;
|
|
6890
|
-
}
|
|
6891
|
-
const promoted = this.l1.importEntries(
|
|
6892
|
-
[{ key: k, entry: diskHit }],
|
|
6893
|
-
this.opts.forbiddenSnapshotPrefixes
|
|
6894
|
-
);
|
|
6895
|
-
if (promoted > 0) {
|
|
6896
|
-
const l1Check = this.l1.get(k);
|
|
6897
|
-
if (l1Check !== null) {
|
|
6898
|
-
this.counters.diskHits++;
|
|
6899
|
-
result[missIndexes[j]] = this._prepareReadValue(l1Check.value);
|
|
6900
|
-
missIndexes.splice(j, 1);
|
|
6901
|
-
missKeys.splice(j, 1);
|
|
6902
|
-
}
|
|
6903
|
-
}
|
|
7564
|
+
const diskHit = await this._readDiskEntry(k, epochs.get(k));
|
|
7565
|
+
if (diskHit && (diskHit.entry.staleAt === void 0 || diskHit.entry.staleAt > Date.now())) {
|
|
7566
|
+
this.counters.diskHits++;
|
|
7567
|
+
result[missIndexes[j]] = this._prepareReadValue(diskHit.value);
|
|
7568
|
+
missIndexes.splice(j, 1);
|
|
7569
|
+
missKeys.splice(j, 1);
|
|
6904
7570
|
}
|
|
6905
7571
|
}
|
|
6906
7572
|
}
|
|
6907
7573
|
if (missKeys.length > 0 && fetchFn) {
|
|
6908
|
-
|
|
6909
|
-
const
|
|
6910
|
-
const isMap = fetched instanceof Map;
|
|
6911
|
-
const setPromises = [];
|
|
7574
|
+
const owned = /* @__PURE__ */ new Map();
|
|
7575
|
+
const waiting = [];
|
|
6912
7576
|
for (let j = 0; j < missKeys.length; j++) {
|
|
6913
|
-
const
|
|
6914
|
-
const
|
|
6915
|
-
|
|
6916
|
-
if (
|
|
6917
|
-
|
|
6918
|
-
|
|
6919
|
-
|
|
6920
|
-
|
|
6921
|
-
|
|
6922
|
-
|
|
6923
|
-
|
|
7577
|
+
const key = missKeys[j];
|
|
7578
|
+
const namespaced = this.nk(key);
|
|
7579
|
+
let promise = this.inflight.get(namespaced);
|
|
7580
|
+
if (!promise) {
|
|
7581
|
+
let resolve;
|
|
7582
|
+
let reject;
|
|
7583
|
+
promise = new Promise((yes, no) => {
|
|
7584
|
+
resolve = yes;
|
|
7585
|
+
reject = no;
|
|
7586
|
+
});
|
|
7587
|
+
owned.set(key, { promise, resolve, reject });
|
|
7588
|
+
this.inflight.set(namespaced, promise);
|
|
7589
|
+
} else {
|
|
7590
|
+
this.counters.stampedes++;
|
|
6924
7591
|
}
|
|
7592
|
+
const index = missIndexes[j];
|
|
7593
|
+
waiting.push(promise.then((value) => {
|
|
7594
|
+
result[index] = this._prepareReadValue(value);
|
|
7595
|
+
}));
|
|
6925
7596
|
}
|
|
6926
|
-
|
|
6927
|
-
|
|
7597
|
+
const settled = Promise.allSettled(waiting);
|
|
7598
|
+
try {
|
|
7599
|
+
if (owned.size > 0) {
|
|
7600
|
+
this.counters.fetches++;
|
|
7601
|
+
const fetched = await fetchFn([...owned.keys()]);
|
|
7602
|
+
await Promise.all([...owned].map(async ([key, entry]) => {
|
|
7603
|
+
const value = fetched instanceof Map ? fetched.get(key) : Object.hasOwn(fetched, key) ? fetched[key] : void 0;
|
|
7604
|
+
if (!this._destroyed && this._getKeyMutationEpoch(this.nk(key)) === epochs.get(this.nk(key))) {
|
|
7605
|
+
const resolvedTtl = value == null && this.opts.notFoundTtl > 0 ? this.opts.notFoundTtl : typeof ttl === "function" ? ttl(key) : ttl;
|
|
7606
|
+
if (value !== void 0 || this.opts.notFoundTtl > 0) await this.set(key, value === void 0 && this.opts.notFoundTtl > 0 ? null : value, resolvedTtl, priority);
|
|
7607
|
+
}
|
|
7608
|
+
entry.resolve(value);
|
|
7609
|
+
}));
|
|
7610
|
+
}
|
|
7611
|
+
const outcomes = await settled;
|
|
7612
|
+
const failed = outcomes.find((outcome) => outcome.status === "rejected");
|
|
7613
|
+
if (failed?.status === "rejected") throw failed.reason;
|
|
7614
|
+
} catch (error) {
|
|
7615
|
+
for (const entry of owned.values()) entry.reject(error);
|
|
7616
|
+
throw error;
|
|
7617
|
+
} finally {
|
|
7618
|
+
for (const [key, entry] of owned) {
|
|
7619
|
+
const namespaced = this.nk(key);
|
|
7620
|
+
if (this.inflight.get(namespaced) === entry.promise) this.inflight.delete(namespaced);
|
|
7621
|
+
}
|
|
6928
7622
|
}
|
|
6929
7623
|
}
|
|
6930
7624
|
if (this.opts.tracer) {
|
|
@@ -6977,7 +7671,7 @@ var CacheService = class _CacheService {
|
|
|
6977
7671
|
try {
|
|
6978
7672
|
await Promise.all(keys.map((key) => {
|
|
6979
7673
|
const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
|
|
6980
|
-
const hasOpts = tags
|
|
7674
|
+
const hasOpts = tags !== void 0 || dependsOn !== void 0;
|
|
6981
7675
|
return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
|
|
6982
7676
|
}));
|
|
6983
7677
|
} catch (err) {
|
|
@@ -7029,26 +7723,21 @@ var CacheService = class _CacheService {
|
|
|
7029
7723
|
try {
|
|
7030
7724
|
const client = await this.getRedis();
|
|
7031
7725
|
const nsPattern = this.nk(pattern);
|
|
7032
|
-
const matchedKeys = await this._scanKeys(client, nsPattern)
|
|
7726
|
+
const matchedKeys = (await this._scanKeys(client, nsPattern)).filter((key) => {
|
|
7727
|
+
const raw = this.unnk(key);
|
|
7728
|
+
return !raw.startsWith("_tag_:") && !raw.startsWith("tag_ver:") && !raw.startsWith("lock:") && key !== this.backplaneStreamKey;
|
|
7729
|
+
});
|
|
7033
7730
|
if (matchedKeys.length === 0) {
|
|
7034
7731
|
this.cb.onSuccess();
|
|
7035
7732
|
return 0;
|
|
7036
7733
|
}
|
|
7037
|
-
const
|
|
7038
|
-
|
|
7039
|
-
const results = await pl.exec();
|
|
7040
|
-
this.cb.onSuccess();
|
|
7734
|
+
const epochs = new Map(matchedKeys.map((key) => [key, this._getKeyMutationEpoch(key)]));
|
|
7735
|
+
const results = await this._readRedisBatch(client, matchedKeys);
|
|
7041
7736
|
let loaded = 0;
|
|
7042
|
-
for (
|
|
7043
|
-
const
|
|
7044
|
-
if (
|
|
7045
|
-
|
|
7046
|
-
const parsed = await this._decryptAndDeserialize(raw);
|
|
7047
|
-
const remainingMs = 10 * 60 * 1e3;
|
|
7048
|
-
this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
|
|
7049
|
-
loaded++;
|
|
7050
|
-
} catch {
|
|
7051
|
-
}
|
|
7737
|
+
for (const key of matchedKeys) {
|
|
7738
|
+
const entry = results.get(key);
|
|
7739
|
+
if (!entry || this._destroyed || this._getKeyMutationEpoch(key) !== epochs.get(key)) continue;
|
|
7740
|
+
if (this._promoteRedisEntry(key, entry, 10 * 60 * 1e3, opts?.priority ?? inferPriority(this.unnk(key))) && this.l1.has(key)) loaded++;
|
|
7052
7741
|
}
|
|
7053
7742
|
this.logger.info("warmFromL2 complete", {
|
|
7054
7743
|
pattern,
|
|
@@ -7135,14 +7824,7 @@ var CacheService = class _CacheService {
|
|
|
7135
7824
|
this._bumpKeyMutation(k);
|
|
7136
7825
|
this._removeKeyTags(k);
|
|
7137
7826
|
this._removeKeyDependencies(k);
|
|
7138
|
-
this.
|
|
7139
|
-
setImmediate(() => {
|
|
7140
|
-
try {
|
|
7141
|
-
if (!this._diskDisabled) this.disk.delete(k);
|
|
7142
|
-
} finally {
|
|
7143
|
-
this._pendingDiskDeletes.delete(k);
|
|
7144
|
-
}
|
|
7145
|
-
});
|
|
7827
|
+
this._invalidateDiskKey(k);
|
|
7146
7828
|
}
|
|
7147
7829
|
}
|
|
7148
7830
|
/**
|
|
@@ -7150,9 +7832,10 @@ var CacheService = class _CacheService {
|
|
|
7150
7832
|
* wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
|
|
7151
7833
|
*/
|
|
7152
7834
|
async _invalidateConcreteTag(tag) {
|
|
7835
|
+
this._fenceInvalidation();
|
|
7153
7836
|
if (this.opts.tagStrategy === "generational") {
|
|
7154
7837
|
let newVer = 1;
|
|
7155
|
-
if (!this._redisDisabled) {
|
|
7838
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
7156
7839
|
try {
|
|
7157
7840
|
const client = await this.getRedis();
|
|
7158
7841
|
newVer = await client.incr(this.nk(`tag_ver:${tag}`));
|
|
@@ -7170,19 +7853,23 @@ var CacheService = class _CacheService {
|
|
|
7170
7853
|
return;
|
|
7171
7854
|
}
|
|
7172
7855
|
const tagKey = this.nk(`_tag_:${tag}`);
|
|
7173
|
-
const members =
|
|
7856
|
+
const members = new Set(this.tagIndex.get(tagKey) ?? []);
|
|
7174
7857
|
this.tagIndex.delete(tagKey);
|
|
7175
7858
|
this._removeTagMembersLocal(members);
|
|
7176
|
-
if (!this._redisDisabled) {
|
|
7859
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
7177
7860
|
try {
|
|
7178
7861
|
const client = await this.getRedis();
|
|
7179
7862
|
const redisMembers = await client.smembers(tagKey);
|
|
7863
|
+
for (const key of redisMembers) members.add(key);
|
|
7864
|
+
this._removeTagMembersLocal(redisMembers);
|
|
7180
7865
|
const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers, tagKey])];
|
|
7181
7866
|
await this._deleteRedisKeys(client, toDelete);
|
|
7182
7867
|
} catch (err) {
|
|
7183
7868
|
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
7184
7869
|
}
|
|
7185
7870
|
}
|
|
7871
|
+
await Promise.all([...members].map((key) => this._publishTagInvalidation("del", key)));
|
|
7872
|
+
await this._publishTagInvalidation("tag_pattern_del", tag);
|
|
7186
7873
|
}
|
|
7187
7874
|
/**
|
|
7188
7875
|
* Executes invalidation for an array of already-resolved concrete tags
|
|
@@ -7194,9 +7881,10 @@ var CacheService = class _CacheService {
|
|
|
7194
7881
|
await this._invalidateConcreteTag(tags[0]);
|
|
7195
7882
|
return;
|
|
7196
7883
|
}
|
|
7884
|
+
this._fenceInvalidation();
|
|
7197
7885
|
if (this.opts.tagStrategy === "generational") {
|
|
7198
7886
|
const now = performance.now();
|
|
7199
|
-
if (!this._redisDisabled) {
|
|
7887
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
7200
7888
|
try {
|
|
7201
7889
|
const client = await this.getRedis();
|
|
7202
7890
|
const pl = client.pipeline();
|
|
@@ -7230,7 +7918,7 @@ var CacheService = class _CacheService {
|
|
|
7230
7918
|
this.tagIndex.delete(tagKey);
|
|
7231
7919
|
}
|
|
7232
7920
|
this._removeTagMembersLocal(allMembers);
|
|
7233
|
-
if (!this._redisDisabled) {
|
|
7921
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
7234
7922
|
try {
|
|
7235
7923
|
const client = await this.getRedis();
|
|
7236
7924
|
const pl = client.pipeline();
|
|
@@ -7241,15 +7929,19 @@ var CacheService = class _CacheService {
|
|
|
7241
7929
|
if (!err && redisMembers) {
|
|
7242
7930
|
for (const k of redisMembers) {
|
|
7243
7931
|
if (!allMembers.has(k)) toDelete.push(k);
|
|
7932
|
+
allMembers.add(k);
|
|
7244
7933
|
}
|
|
7245
7934
|
}
|
|
7246
7935
|
}
|
|
7247
7936
|
const keysToRemove = [...toDelete, ...tagKeys];
|
|
7248
7937
|
await this._deleteRedisKeys(client, keysToRemove);
|
|
7938
|
+
this._removeTagMembersLocal(allMembers);
|
|
7249
7939
|
} catch (err) {
|
|
7250
7940
|
this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
|
|
7251
7941
|
}
|
|
7252
7942
|
}
|
|
7943
|
+
await Promise.all([...allMembers].map((key) => this._publishTagInvalidation("del", key)));
|
|
7944
|
+
for (const tag of tags) await this._publishTagInvalidation("tag_pattern_del", tag);
|
|
7253
7945
|
}
|
|
7254
7946
|
/**
|
|
7255
7947
|
* Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
|
|
@@ -7403,19 +8095,23 @@ var CacheService = class _CacheService {
|
|
|
7403
8095
|
const diskLowSpace = !this._diskDisabled && this.disk.hostVolumeLowSpace;
|
|
7404
8096
|
const circuitOpen = this.cb.isOpen;
|
|
7405
8097
|
const latencyBypass = watchdogTel.bypassActive;
|
|
7406
|
-
const
|
|
7407
|
-
const
|
|
8098
|
+
const backplaneUnavailable = this.opts.invalidationBackplane && !this._redisDisabled && !this._backplaneAvailable;
|
|
8099
|
+
const degraded = this._destroyed || circuitOpen || latencyBypass || diskPruning || diskLowSpace || backplaneUnavailable;
|
|
8100
|
+
const healthy = !this._destroyed && (this.opts.failReadinessOnDegraded ? !degraded : true);
|
|
7408
8101
|
const reasons = [];
|
|
7409
8102
|
if (circuitOpen) reasons.push("redis_circuit_breaker_open");
|
|
7410
8103
|
if (latencyBypass) reasons.push(`disk_latency_bypass_stage_${watchdogTel.bypassStage}`);
|
|
7411
8104
|
if (diskPruning) reasons.push("disk_quota_watermark_pruning_active");
|
|
7412
8105
|
if (diskLowSpace) reasons.push("disk_host_volume_low_space");
|
|
8106
|
+
if (backplaneUnavailable) reasons.push("invalidation_backplane_unavailable");
|
|
8107
|
+
if (this._destroyed) reasons.push("cache_destroyed");
|
|
7413
8108
|
return {
|
|
7414
8109
|
healthy,
|
|
7415
8110
|
degraded,
|
|
7416
8111
|
reasons,
|
|
7417
8112
|
details: {
|
|
7418
|
-
redisConnected: !circuitOpen &&
|
|
8113
|
+
redisConnected: !this._destroyed && !circuitOpen && !!this.redis && (this.redis.status === "ready" || this.redis.isOpen === true),
|
|
8114
|
+
backplaneReady: this._backplaneAvailable,
|
|
7419
8115
|
circuitBreakerState: this.cb.currentState,
|
|
7420
8116
|
diskPruningActive: diskPruning,
|
|
7421
8117
|
diskHostVolumeLowSpace: diskLowSpace,
|
|
@@ -7437,23 +8133,28 @@ var CacheService = class _CacheService {
|
|
|
7437
8133
|
*/
|
|
7438
8134
|
async drainToL2() {
|
|
7439
8135
|
this._assertActive("drainToL2");
|
|
7440
|
-
if (this._redisDisabled) return 0;
|
|
8136
|
+
if (this._redisDisabled || this.opts.l2WriteMode === "read-only") return 0;
|
|
7441
8137
|
try {
|
|
7442
|
-
const client = await this.getRedis();
|
|
7443
8138
|
const entries = this.l1.exportEntries([]);
|
|
7444
|
-
const now = Date.now();
|
|
7445
8139
|
if (entries.length === 0) return 0;
|
|
7446
|
-
|
|
7447
|
-
|
|
7448
|
-
const
|
|
7449
|
-
if (
|
|
7450
|
-
|
|
7451
|
-
|
|
7452
|
-
|
|
7453
|
-
|
|
7454
|
-
|
|
7455
|
-
|
|
7456
|
-
|
|
8140
|
+
let written = 0;
|
|
8141
|
+
await Promise.all(entries.map(async ({ key, entry }) => {
|
|
8142
|
+
const epoch = this._getKeyMutationEpoch(key);
|
|
8143
|
+
if (entry.expiresAt <= Date.now()) return;
|
|
8144
|
+
await this._writeRedisEntry(
|
|
8145
|
+
key,
|
|
8146
|
+
this.l1.resolveValue(entry),
|
|
8147
|
+
entry.expiresAt,
|
|
8148
|
+
entry.setAt ?? Date.now(),
|
|
8149
|
+
entry.tagVersions,
|
|
8150
|
+
entry.staleAt,
|
|
8151
|
+
entry.tags,
|
|
8152
|
+
entry.dependsOn,
|
|
8153
|
+
() => this._getKeyMutationEpoch(key) === epoch
|
|
8154
|
+
);
|
|
8155
|
+
written++;
|
|
8156
|
+
}));
|
|
8157
|
+
return written;
|
|
7457
8158
|
} catch (err) {
|
|
7458
8159
|
this.logger.debug("drainToL2: Redis unavailable", { error: err.message });
|
|
7459
8160
|
return 0;
|
|
@@ -7483,7 +8184,7 @@ var CacheService = class _CacheService {
|
|
|
7483
8184
|
this._assertActive("setIfAbsent");
|
|
7484
8185
|
const k = this.nk(cacheKey);
|
|
7485
8186
|
if (this.l1.has(k)) return false;
|
|
7486
|
-
if (!this._redisDisabled) {
|
|
8187
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
7487
8188
|
try {
|
|
7488
8189
|
const client = await this.getRedis();
|
|
7489
8190
|
const serialized = JSON.stringify(value);
|
|
@@ -7500,7 +8201,7 @@ var CacheService = class _CacheService {
|
|
|
7500
8201
|
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
7501
8202
|
const p = priority ?? inferPriority(cacheKey);
|
|
7502
8203
|
this._bumpKeyMutation(k);
|
|
7503
|
-
this.
|
|
8204
|
+
this._invalidateDiskKey(k);
|
|
7504
8205
|
this.l1.set(k, value, ttlMs, p);
|
|
7505
8206
|
this.counters.sets++;
|
|
7506
8207
|
return true;
|
|
@@ -7527,7 +8228,7 @@ var CacheService = class _CacheService {
|
|
|
7527
8228
|
const token = import_crypto3.default.randomUUID();
|
|
7528
8229
|
const deadline = Date.now() + acquireTimeout;
|
|
7529
8230
|
let acquired = false;
|
|
7530
|
-
if (!this._redisDisabled) {
|
|
8231
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
7531
8232
|
let client = null;
|
|
7532
8233
|
try {
|
|
7533
8234
|
client = await this.getRedis();
|
|
@@ -7622,7 +8323,9 @@ var CacheService = class _CacheService {
|
|
|
7622
8323
|
const gDiskFiles = meter.createObservableGauge("tricache.disk.files", { description: "Current L1.5 disk file count" });
|
|
7623
8324
|
const gDiskBytes = meter.createObservableGauge("tricache.disk.bytes", { description: "Current L1.5 disk size in bytes" });
|
|
7624
8325
|
const gBloomFpr = meter.createObservableGauge("tricache.bloom.fpr", { description: "Bloom filter false-positive rate" });
|
|
7625
|
-
|
|
8326
|
+
const observables = [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr];
|
|
8327
|
+
const callback = (observableResult) => {
|
|
8328
|
+
if (this._destroyed) return;
|
|
7626
8329
|
const stats = this.stats();
|
|
7627
8330
|
const l1 = stats.l1;
|
|
7628
8331
|
const disk = stats.disk;
|
|
@@ -7635,7 +8338,9 @@ var CacheService = class _CacheService {
|
|
|
7635
8338
|
observableResult.observe(gDiskFiles, disk.files, attrs);
|
|
7636
8339
|
observableResult.observe(gDiskBytes, disk.sizeKB * 1024, attrs);
|
|
7637
8340
|
observableResult.observe(gBloomFpr, fpr, attrs);
|
|
7638
|
-
}
|
|
8341
|
+
};
|
|
8342
|
+
meter.addBatchObservableCallback(callback, observables);
|
|
8343
|
+
this._otelCleanup = () => meter.removeBatchObservableCallback?.(callback, observables);
|
|
7639
8344
|
} catch (err) {
|
|
7640
8345
|
this.logger.warn("Failed to initialize OpenTelemetry metrics meter", { error: err.message });
|
|
7641
8346
|
}
|
|
@@ -7905,6 +8610,16 @@ var CacheService = class _CacheService {
|
|
|
7905
8610
|
/** Close Redis connections and stop all background timers. */
|
|
7906
8611
|
async destroy() {
|
|
7907
8612
|
this._destroyed = true;
|
|
8613
|
+
this._fenceInvalidation();
|
|
8614
|
+
this._backplaneAvailable = false;
|
|
8615
|
+
this.l1.clear();
|
|
8616
|
+
try {
|
|
8617
|
+
this._otelCleanup?.();
|
|
8618
|
+
} catch {
|
|
8619
|
+
}
|
|
8620
|
+
this._otelCleanup = null;
|
|
8621
|
+
this.tagVersions.clear();
|
|
8622
|
+
for (const dispose of this._backplaneDisposers.splice(0)) dispose();
|
|
7908
8623
|
this._pendingDiskDeletes.clear();
|
|
7909
8624
|
this._keyMutationEpochs.clear();
|
|
7910
8625
|
this.inflight.clear();
|
|
@@ -7934,6 +8649,12 @@ var CacheService = class _CacheService {
|
|
|
7934
8649
|
this._workerPool = null;
|
|
7935
8650
|
}
|
|
7936
8651
|
if (this.subClient) {
|
|
8652
|
+
if (this.opts.redisSubClient) {
|
|
8653
|
+
try {
|
|
8654
|
+
await this.subClient.unsubscribe?.(this.backplaneChannel);
|
|
8655
|
+
} catch {
|
|
8656
|
+
}
|
|
8657
|
+
}
|
|
7937
8658
|
if (!this.opts.redisSubClient) {
|
|
7938
8659
|
try {
|
|
7939
8660
|
this.subClient.disconnect();
|
|
@@ -7943,7 +8664,7 @@ var CacheService = class _CacheService {
|
|
|
7943
8664
|
this.subClient = null;
|
|
7944
8665
|
}
|
|
7945
8666
|
if (this.streamClient) {
|
|
7946
|
-
try {
|
|
8667
|
+
if (!this.opts.redisSubClient) try {
|
|
7947
8668
|
this.streamClient.disconnect();
|
|
7948
8669
|
} catch {
|
|
7949
8670
|
}
|
|
@@ -8011,18 +8732,31 @@ function resolveCacheLife(profileOrName) {
|
|
|
8011
8732
|
}
|
|
8012
8733
|
return null;
|
|
8013
8734
|
}
|
|
8014
|
-
async function drainStream(stream) {
|
|
8735
|
+
async function drainStream(stream, maxBytes) {
|
|
8015
8736
|
const reader = stream.getReader();
|
|
8016
8737
|
const chunks = [];
|
|
8017
|
-
|
|
8018
|
-
|
|
8019
|
-
|
|
8020
|
-
|
|
8738
|
+
let size = 0;
|
|
8739
|
+
try {
|
|
8740
|
+
while (true) {
|
|
8741
|
+
const { done, value } = await reader.read();
|
|
8742
|
+
if (done) break;
|
|
8743
|
+
if (value) {
|
|
8744
|
+
size += value.byteLength;
|
|
8745
|
+
if (size > maxBytes) throw new Error("RSC stream exceeds maxStreamBytes");
|
|
8746
|
+
chunks.push(Uint8Array.from(value));
|
|
8747
|
+
}
|
|
8748
|
+
}
|
|
8749
|
+
return Buffer.concat(chunks);
|
|
8750
|
+
} catch (error) {
|
|
8751
|
+
void reader.cancel(error).catch(() => {
|
|
8752
|
+
});
|
|
8753
|
+
throw error;
|
|
8754
|
+
} finally {
|
|
8755
|
+
reader.releaseLock();
|
|
8021
8756
|
}
|
|
8022
|
-
return Buffer.concat(chunks);
|
|
8023
8757
|
}
|
|
8024
8758
|
function createReadableStream(buffer) {
|
|
8025
|
-
const uint8 =
|
|
8759
|
+
const uint8 = Uint8Array.from(buffer);
|
|
8026
8760
|
return new ReadableStream({
|
|
8027
8761
|
start(controller) {
|
|
8028
8762
|
controller.enqueue(uint8);
|
|
@@ -8033,8 +8767,14 @@ function createReadableStream(buffer) {
|
|
|
8033
8767
|
var TriCacheHandler = class {
|
|
8034
8768
|
cache;
|
|
8035
8769
|
logger;
|
|
8770
|
+
maxStreamBytes;
|
|
8771
|
+
pendingSets = /* @__PURE__ */ new Map();
|
|
8772
|
+
observedTags = /* @__PURE__ */ new Map();
|
|
8036
8773
|
constructor(options = {}) {
|
|
8037
8774
|
this.logger = options.logger ?? consoleLogger;
|
|
8775
|
+
this.maxStreamBytes = options.maxStreamBytes ?? 16 * 1024 * 1024;
|
|
8776
|
+
if (!Number.isFinite(this.maxStreamBytes) || this.maxStreamBytes <= 0) throw new Error("maxStreamBytes must be finite and positive");
|
|
8777
|
+
if (options.tagStrategy && options.tagStrategy !== "generational") throw new Error("Next.js cache handlers require tagStrategy: generational");
|
|
8038
8778
|
const isBuildPhase = options.isBuildPhase ?? (typeof process !== "undefined" && (process.env.NEXT_PHASE === "phase-production-build" || process.env.NEXT_PHASE === "phase-export"));
|
|
8039
8779
|
this.cache = CacheService.create({
|
|
8040
8780
|
...options,
|
|
@@ -8044,34 +8784,62 @@ var TriCacheHandler = class {
|
|
|
8044
8784
|
disableRedis: isBuildPhase ? true : options.disableRedis
|
|
8045
8785
|
});
|
|
8046
8786
|
}
|
|
8047
|
-
|
|
8048
|
-
|
|
8049
|
-
|
|
8050
|
-
|
|
8051
|
-
|
|
8787
|
+
async get(cacheKey, context) {
|
|
8788
|
+
let pending = this.pendingSets.get(cacheKey);
|
|
8789
|
+
while (pending) {
|
|
8790
|
+
await pending.completion;
|
|
8791
|
+
pending = this.pendingSets.get(cacheKey);
|
|
8792
|
+
}
|
|
8793
|
+
const native = Array.isArray(context);
|
|
8794
|
+
const ctx = native ? { softTags: context } : context;
|
|
8052
8795
|
const stored = await this.cache.peek(cacheKey);
|
|
8053
8796
|
if (!stored || stored.data == null) {
|
|
8054
8797
|
return void 0;
|
|
8055
8798
|
}
|
|
8056
|
-
|
|
8057
|
-
|
|
8058
|
-
|
|
8059
|
-
|
|
8060
|
-
|
|
8061
|
-
|
|
8062
|
-
|
|
8799
|
+
const expire = stored.expire ?? stored.ttl;
|
|
8800
|
+
if (!Number.isFinite(stored.timestamp) || !Number.isFinite(expire) || Date.now() >= stored.timestamp + expire * 1e3) return void 0;
|
|
8801
|
+
const tags = [.../* @__PURE__ */ new Set([...stored.tags, ...ctx?.softTags ?? []])];
|
|
8802
|
+
const versions = await Promise.all(tags.map((tag) => this.cache.getTagVersion(tag)));
|
|
8803
|
+
const states = await this.cache.mget(tags.map((tag) => `_next_tag_state_:${tag}`));
|
|
8804
|
+
let revalidate = stored.revalidate ?? stored.ttl;
|
|
8805
|
+
for (let index = 0; index < tags.length; index++) {
|
|
8806
|
+
const tag = tags[index];
|
|
8807
|
+
const state = states[index];
|
|
8808
|
+
const snapshot = stored.generations?.[tag] ?? stored.softTagVersions?.[tag];
|
|
8809
|
+
if (state && (state.revalidatedAt > stored.timestamp || state.revalidatedAt === stored.timestamp && snapshot !== versions[index])) {
|
|
8810
|
+
if (state.expiredAt !== void 0 && state.expiredAt <= Date.now()) return void 0;
|
|
8811
|
+
revalidate = -1;
|
|
8812
|
+
} else if (!state && versions[index] > 0) {
|
|
8813
|
+
if (snapshot !== void 0 && versions[index] > snapshot) return void 0;
|
|
8814
|
+
if (snapshot === void 0) {
|
|
8815
|
+
const observed = this.observeTag(tag, versions[index]);
|
|
8816
|
+
if (stored.timestamp <= observed) return void 0;
|
|
8063
8817
|
}
|
|
8064
8818
|
}
|
|
8065
8819
|
}
|
|
8066
8820
|
let val = stored.data;
|
|
8067
|
-
if (stored.isStream
|
|
8068
|
-
|
|
8821
|
+
if (stored.isStream) {
|
|
8822
|
+
let bytes;
|
|
8823
|
+
if (stored.streamEncoding === "base64" && typeof val === "string") {
|
|
8824
|
+
if (val.length > Math.ceil(this.maxStreamBytes / 3) * 4) return void 0;
|
|
8825
|
+
bytes = Buffer.from(val, "base64");
|
|
8826
|
+
} else if (Buffer.isBuffer(val) || val instanceof Uint8Array) bytes = val;
|
|
8827
|
+
else if (val && typeof val === "object" && val.type === "Buffer" && Array.isArray(val.data)) {
|
|
8828
|
+
bytes = Buffer.from(val.data);
|
|
8829
|
+
} else return void 0;
|
|
8830
|
+
if (bytes.length > this.maxStreamBytes) return void 0;
|
|
8831
|
+
val = createReadableStream(bytes);
|
|
8832
|
+
} else if (native) {
|
|
8833
|
+
return void 0;
|
|
8069
8834
|
}
|
|
8070
8835
|
return {
|
|
8071
8836
|
value: val,
|
|
8072
8837
|
tags: stored.tags,
|
|
8073
8838
|
timestamp: stored.timestamp,
|
|
8074
|
-
ttl: stored.ttl
|
|
8839
|
+
ttl: stored.ttl,
|
|
8840
|
+
stale: stored.stale ?? 300,
|
|
8841
|
+
revalidate,
|
|
8842
|
+
expire
|
|
8075
8843
|
};
|
|
8076
8844
|
}
|
|
8077
8845
|
/**
|
|
@@ -8079,92 +8847,111 @@ var TriCacheHandler = class {
|
|
|
8079
8847
|
* before storing. Catches mid-flight stream aborts to avoid crashing Next.js.
|
|
8080
8848
|
*/
|
|
8081
8849
|
async set(cacheKey, pendingEntry, ctx) {
|
|
8082
|
-
const
|
|
8083
|
-
|
|
8084
|
-
|
|
8085
|
-
|
|
8086
|
-
|
|
8087
|
-
);
|
|
8088
|
-
|
|
8089
|
-
|
|
8090
|
-
|
|
8091
|
-
|
|
8092
|
-
|
|
8093
|
-
|
|
8094
|
-
|
|
8095
|
-
|
|
8096
|
-
|
|
8850
|
+
const token = Symbol(cacheKey);
|
|
8851
|
+
let finish;
|
|
8852
|
+
const completion = new Promise((resolve) => {
|
|
8853
|
+
finish = resolve;
|
|
8854
|
+
});
|
|
8855
|
+
this.pendingSets.set(cacheKey, { token, completion });
|
|
8856
|
+
try {
|
|
8857
|
+
const canCommit = this.cache.captureMutationFence(cacheKey);
|
|
8858
|
+
const entry = await pendingEntry;
|
|
8859
|
+
if (!entry || entry.value == null) return;
|
|
8860
|
+
const tags = Array.from(/* @__PURE__ */ new Set([...entry.tags ?? [], ...ctx?.tags ?? []]));
|
|
8861
|
+
const allTags = [.../* @__PURE__ */ new Set([...tags, ...ctx?.softTags ?? []])];
|
|
8862
|
+
const initialVersions = Object.fromEntries(await Promise.all(allTags.map(async (tag) => [tag, await this.cache.getTagVersion(tag)])));
|
|
8863
|
+
let dataToStore = entry.value;
|
|
8864
|
+
const isStream = Boolean(
|
|
8865
|
+
dataToStore && typeof dataToStore.getReader === "function"
|
|
8866
|
+
);
|
|
8867
|
+
if (isStream) {
|
|
8868
|
+
try {
|
|
8869
|
+
dataToStore = (await drainStream(dataToStore, this.maxStreamBytes)).toString("base64");
|
|
8870
|
+
} catch (streamErr) {
|
|
8871
|
+
this.logger.debug("Next.js cacheHandler: stream drain failed mid-flight, skipping cache", {
|
|
8872
|
+
cacheKey,
|
|
8873
|
+
error: streamErr.message
|
|
8874
|
+
});
|
|
8875
|
+
return;
|
|
8876
|
+
}
|
|
8097
8877
|
}
|
|
8878
|
+
let ttl;
|
|
8879
|
+
const resolvedLife = resolveCacheLife(ctx?.cacheLife);
|
|
8880
|
+
if (resolvedLife) {
|
|
8881
|
+
ttl = resolvedLife.ttl;
|
|
8882
|
+
} else if (typeof entry.revalidate === "number") {
|
|
8883
|
+
ttl = entry.revalidate;
|
|
8884
|
+
} else if (typeof entry.ttl === "number") {
|
|
8885
|
+
ttl = entry.ttl;
|
|
8886
|
+
} else if (typeof ctx?.revalidate === "number") {
|
|
8887
|
+
if (ctx.revalidate <= 0) return;
|
|
8888
|
+
ttl = ctx.revalidate;
|
|
8889
|
+
} else if (ctx?.revalidate === false) {
|
|
8890
|
+
ttl = 31536e3;
|
|
8891
|
+
} else {
|
|
8892
|
+
ttl = 300;
|
|
8893
|
+
}
|
|
8894
|
+
const expire = entry.expire ?? (resolvedLife ? resolvedLife.ttl + resolvedLife.swr : ttl);
|
|
8895
|
+
const timestamp = entry.timestamp ?? Date.now();
|
|
8896
|
+
if (!Number.isFinite(expire) || expire <= 0 || !Number.isFinite(timestamp) || timestamp > Date.now() + (this.cache.options.clockSkewToleranceMs ?? 250)) return;
|
|
8897
|
+
const remaining = timestamp + expire * 1e3 - Date.now();
|
|
8898
|
+
if (remaining <= 0 || !canCommit() || this.pendingSets.get(cacheKey)?.token !== token) return;
|
|
8899
|
+
const finalVersions = await Promise.all(allTags.map((tag) => this.cache.getTagVersion(tag)));
|
|
8900
|
+
if (allTags.some((tag, index) => finalVersions[index] !== initialVersions[tag])) return;
|
|
8901
|
+
const tagStates = await this.cache.mget(allTags.map((tag) => `_next_tag_state_:${tag}`));
|
|
8902
|
+
if (tagStates.some((state) => state && state.revalidatedAt > timestamp)) return;
|
|
8903
|
+
let softTagVersions;
|
|
8904
|
+
if (ctx?.softTags && ctx.softTags.length > 0) {
|
|
8905
|
+
const softTags = ctx.softTags;
|
|
8906
|
+
const vers = await Promise.all(softTags.map((st) => this.cache.getTagVersion(st)));
|
|
8907
|
+
softTagVersions = {};
|
|
8908
|
+
for (let i = 0; i < softTags.length; i++) {
|
|
8909
|
+
softTagVersions[softTags[i]] = vers[i];
|
|
8910
|
+
}
|
|
8911
|
+
}
|
|
8912
|
+
const stored = {
|
|
8913
|
+
data: dataToStore,
|
|
8914
|
+
isStream,
|
|
8915
|
+
tags,
|
|
8916
|
+
timestamp,
|
|
8917
|
+
ttl,
|
|
8918
|
+
softTagVersions,
|
|
8919
|
+
generations: initialVersions,
|
|
8920
|
+
stale: entry.stale ?? (typeof ctx?.cacheLife === "string" ? PRESET_CACHE_LIFE_PROFILES[ctx.cacheLife]?.stale : typeof ctx?.cacheLife === "object" ? ctx.cacheLife.stale : void 0) ?? 300,
|
|
8921
|
+
revalidate: ttl,
|
|
8922
|
+
expire,
|
|
8923
|
+
streamEncoding: isStream ? "base64" : void 0
|
|
8924
|
+
};
|
|
8925
|
+
if (!canCommit() || this.pendingSets.get(cacheKey)?.token !== token) return;
|
|
8926
|
+
await this.cache.set(cacheKey, stored, remaining / 1e3, void 0, { tags: [] });
|
|
8927
|
+
} finally {
|
|
8928
|
+
finish();
|
|
8929
|
+
if (this.pendingSets.get(cacheKey)?.token === token) this.pendingSets.delete(cacheKey);
|
|
8098
8930
|
}
|
|
8099
|
-
|
|
8100
|
-
|
|
8101
|
-
|
|
8102
|
-
|
|
8103
|
-
|
|
8104
|
-
|
|
8105
|
-
|
|
8106
|
-
if (ctx.revalidate <= 0) return;
|
|
8107
|
-
ttl = ctx.revalidate;
|
|
8108
|
-
} else if (ctx?.revalidate === false) {
|
|
8109
|
-
ttl = 31536e3;
|
|
8110
|
-
} else {
|
|
8111
|
-
ttl = 300;
|
|
8112
|
-
}
|
|
8113
|
-
const tags = Array.from(/* @__PURE__ */ new Set([...entry.tags ?? [], ...ctx?.tags ?? []]));
|
|
8114
|
-
let softTagVersions;
|
|
8115
|
-
if (ctx?.softTags && ctx.softTags.length > 0) {
|
|
8116
|
-
const softTags = ctx.softTags;
|
|
8117
|
-
const vers = await Promise.all(softTags.map((st) => this.cache.getTagVersion(st)));
|
|
8118
|
-
softTagVersions = {};
|
|
8119
|
-
for (let i = 0; i < softTags.length; i++) {
|
|
8120
|
-
softTagVersions[softTags[i]] = vers[i];
|
|
8121
|
-
}
|
|
8931
|
+
}
|
|
8932
|
+
observeTag(tag, version) {
|
|
8933
|
+
const known = this.observedTags.get(tag);
|
|
8934
|
+
if (known?.version === version) return known.observedAt;
|
|
8935
|
+
if (this.observedTags.size >= 1e4) {
|
|
8936
|
+
const oldest = this.observedTags.keys().next().value;
|
|
8937
|
+
if (oldest !== void 0) this.observedTags.delete(oldest);
|
|
8122
8938
|
}
|
|
8123
|
-
const
|
|
8124
|
-
|
|
8125
|
-
|
|
8126
|
-
tags,
|
|
8127
|
-
timestamp: entry.timestamp ?? Date.now(),
|
|
8128
|
-
ttl,
|
|
8129
|
-
softTagVersions
|
|
8130
|
-
};
|
|
8131
|
-
await this.cache.set(cacheKey, stored, ttl, void 0, tags.length > 0 ? { tags } : void 0);
|
|
8939
|
+
const observedAt = Date.now();
|
|
8940
|
+
this.observedTags.set(tag, { version, observedAt });
|
|
8941
|
+
return observedAt;
|
|
8132
8942
|
}
|
|
8133
8943
|
/**
|
|
8134
|
-
*
|
|
8135
|
-
* cached entry for the given tags, or 0 when nothing is tracked. Next.js
|
|
8136
|
-
* uses this to decide whether a revalidation is due — a hardcoded 0 means
|
|
8137
|
-
* "always expired", so this reads the real stored entries instead.
|
|
8944
|
+
* Delegate soft-tag checking to get() using Next's Infinity sentinel.
|
|
8138
8945
|
*/
|
|
8139
8946
|
async getExpiration(tags) {
|
|
8140
|
-
|
|
8141
|
-
let maxExpiration = 0;
|
|
8142
|
-
const tagSet = new Set(tags);
|
|
8143
|
-
const l1 = this.cache.l1;
|
|
8144
|
-
l1.scan((key, entry) => {
|
|
8145
|
-
if (!entry.tagVersions) return;
|
|
8146
|
-
for (const tag of Object.keys(entry.tagVersions)) {
|
|
8147
|
-
if (!tagSet.has(tag)) continue;
|
|
8148
|
-
const exp = entry.expiresAt ?? 0;
|
|
8149
|
-
if (exp > maxExpiration) maxExpiration = exp;
|
|
8150
|
-
return;
|
|
8151
|
-
}
|
|
8152
|
-
}, 0);
|
|
8153
|
-
return maxExpiration;
|
|
8154
|
-
} catch (err) {
|
|
8155
|
-
this.logger.debug("Next.js cacheHandler getExpiration fail-soft", { error: err.message });
|
|
8156
|
-
return 0;
|
|
8157
|
-
}
|
|
8947
|
+
return tags.length ? Infinity : 0;
|
|
8158
8948
|
}
|
|
8159
8949
|
/**
|
|
8160
|
-
*
|
|
8161
|
-
* in-memory tag-version cache so every subsequent read re-syncs versions
|
|
8162
|
-
* from Redis. The previous implementation was an empty try/catch.
|
|
8950
|
+
* Force subsequent tag reads to re-sync without forgetting monotonic versions.
|
|
8163
8951
|
*/
|
|
8164
8952
|
async refreshTags() {
|
|
8165
8953
|
try {
|
|
8166
|
-
|
|
8167
|
-
cache.tagVersions?.clear();
|
|
8954
|
+
this.cache.refreshTagVersions();
|
|
8168
8955
|
} catch (err) {
|
|
8169
8956
|
this.logger.debug("Next.js cacheHandler refreshTags fail-soft catch", {
|
|
8170
8957
|
error: err.message
|
|
@@ -8174,8 +8961,15 @@ var TriCacheHandler = class {
|
|
|
8174
8961
|
/**
|
|
8175
8962
|
* Update or invalidate tags cluster-wide.
|
|
8176
8963
|
*/
|
|
8177
|
-
async updateTags(tags) {
|
|
8964
|
+
async updateTags(tags, durations) {
|
|
8178
8965
|
if (!tags || tags.length === 0) return;
|
|
8966
|
+
const now = Date.now();
|
|
8967
|
+
const delay = durations && durations.expire === void 0 ? void 0 : Math.max(0, durations?.expire ?? 0) * 1e3;
|
|
8968
|
+
if (delay !== void 0 && !Number.isFinite(delay)) throw new Error("Tag expiry duration must be finite");
|
|
8969
|
+
await Promise.all(tags.map((tag) => this.cache.set(`_next_tag_state_:${tag}`, {
|
|
8970
|
+
revalidatedAt: now,
|
|
8971
|
+
expiredAt: delay === void 0 ? void 0 : now + delay
|
|
8972
|
+
}, 0, 3 /* HIGH */)));
|
|
8179
8973
|
await this.cache.invalidateTags(tags);
|
|
8180
8974
|
}
|
|
8181
8975
|
};
|