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