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
|
@@ -16,7 +16,7 @@ import {
|
|
|
16
16
|
isChildTag,
|
|
17
17
|
isWildcardTag,
|
|
18
18
|
matchesTagPattern
|
|
19
|
-
} from "./chunk-
|
|
19
|
+
} from "./chunk-H4GFLQ26.js";
|
|
20
20
|
|
|
21
21
|
// src/cache-service.ts
|
|
22
22
|
import { Redis as RedisClient, Cluster as RedisCluster } from "ioredis";
|
|
@@ -54,6 +54,127 @@ var defaultCodec = new CacheCodec({
|
|
|
54
54
|
moreTypes: true
|
|
55
55
|
});
|
|
56
56
|
|
|
57
|
+
// src/cross-region.ts
|
|
58
|
+
import { createHash, timingSafeEqual } from "crypto";
|
|
59
|
+
function isCrossRegionInvalidationEvent(value) {
|
|
60
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
61
|
+
const event = value;
|
|
62
|
+
const text = (key, max) => typeof event[key] === "string" && event[key].length > 0 && event[key].length <= max;
|
|
63
|
+
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);
|
|
64
|
+
}
|
|
65
|
+
function createHttpMeshRelay(options) {
|
|
66
|
+
const peerUrls = options.peerUrls;
|
|
67
|
+
const timeoutMs = options.timeoutMs ?? 3e3;
|
|
68
|
+
const fetcher = options.fetchFn ?? globalThis.fetch;
|
|
69
|
+
const headers = {
|
|
70
|
+
"Content-Type": "application/json"
|
|
71
|
+
};
|
|
72
|
+
if (options.authSecret) {
|
|
73
|
+
headers["Authorization"] = `Bearer ${options.authSecret}`;
|
|
74
|
+
headers["X-TriCache-Auth"] = options.authSecret;
|
|
75
|
+
}
|
|
76
|
+
return {
|
|
77
|
+
async broadcast(event) {
|
|
78
|
+
if (!peerUrls.length) return;
|
|
79
|
+
const body = JSON.stringify(event);
|
|
80
|
+
const results = await Promise.allSettled(
|
|
81
|
+
peerUrls.map(async (url) => {
|
|
82
|
+
const res = await fetcher(url, {
|
|
83
|
+
method: "POST",
|
|
84
|
+
headers,
|
|
85
|
+
body,
|
|
86
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
87
|
+
});
|
|
88
|
+
if (!res.ok) {
|
|
89
|
+
throw new Error(`HttpMeshRelay: peer ${url} returned HTTP ${res.status} ${res.statusText}`);
|
|
90
|
+
}
|
|
91
|
+
})
|
|
92
|
+
);
|
|
93
|
+
const failures = results.filter((result) => result.status === "rejected");
|
|
94
|
+
if (failures.length) throw new AggregateError(failures.map((result) => result.reason), `Cross-region delivery failed for ${failures.length} peer(s)`);
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
function createCustomCrossRegionRelay(relay) {
|
|
99
|
+
return relay;
|
|
100
|
+
}
|
|
101
|
+
function createMemoryCrossRegionRelay() {
|
|
102
|
+
const handlers = /* @__PURE__ */ new Map();
|
|
103
|
+
let broadcastCount = 0;
|
|
104
|
+
return {
|
|
105
|
+
async broadcast(event) {
|
|
106
|
+
broadcastCount++;
|
|
107
|
+
const promises = [];
|
|
108
|
+
for (const [region, set] of handlers.entries()) {
|
|
109
|
+
if (region !== event.originRegion) {
|
|
110
|
+
for (const fn of set) {
|
|
111
|
+
promises.push(Promise.resolve(fn(event)));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
const results = await Promise.allSettled(promises);
|
|
116
|
+
const failures = results.filter((result) => result.status === "rejected");
|
|
117
|
+
if (failures.length) throw new AggregateError(failures.map((result) => result.reason), "Cross-region handler failed");
|
|
118
|
+
},
|
|
119
|
+
register(region, handler) {
|
|
120
|
+
if (!handlers.has(region)) {
|
|
121
|
+
handlers.set(region, /* @__PURE__ */ new Set());
|
|
122
|
+
}
|
|
123
|
+
handlers.get(region).add(handler);
|
|
124
|
+
return () => {
|
|
125
|
+
handlers.get(region)?.delete(handler);
|
|
126
|
+
};
|
|
127
|
+
},
|
|
128
|
+
getBroadcastCount() {
|
|
129
|
+
return broadcastCount;
|
|
130
|
+
},
|
|
131
|
+
clear() {
|
|
132
|
+
handlers.clear();
|
|
133
|
+
broadcastCount = 0;
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
function createCrossRegionWebhookHandler(cache, options = {}) {
|
|
138
|
+
return async function handleCrossRegionWebhook(req) {
|
|
139
|
+
if (options.authSecret) {
|
|
140
|
+
const authHeader = req.headers["authorization"] ?? req.headers["Authorization"];
|
|
141
|
+
const customHeader = req.headers["x-tricache-auth"] ?? req.headers["X-TriCache-Auth"];
|
|
142
|
+
const bearer = typeof authHeader === "string" && authHeader.startsWith("Bearer ") ? authHeader.slice(7).trim() : authHeader;
|
|
143
|
+
const provided = typeof customHeader === "string" ? customHeader : bearer;
|
|
144
|
+
if (typeof provided !== "string" || !timingSafeEqual(createHash("sha256").update(provided).digest(), createHash("sha256").update(options.authSecret).digest())) {
|
|
145
|
+
return {
|
|
146
|
+
status: 401,
|
|
147
|
+
body: { ok: false, message: "Unauthorized: invalid or missing auth secret" }
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
try {
|
|
152
|
+
let event;
|
|
153
|
+
if (typeof req.body === "string") {
|
|
154
|
+
event = JSON.parse(req.body);
|
|
155
|
+
} else if (req.body && typeof req.body === "object") {
|
|
156
|
+
event = req.body;
|
|
157
|
+
} else {
|
|
158
|
+
return {
|
|
159
|
+
status: 400,
|
|
160
|
+
body: { ok: false, message: "Invalid payload: body must be JSON object" }
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
if (!isCrossRegionInvalidationEvent(event)) return { status: 400, body: { ok: false, message: "Invalid invalidation event" } };
|
|
164
|
+
const accepted = await cache.receiveCrossRegionInvalidation(event);
|
|
165
|
+
return {
|
|
166
|
+
status: 200,
|
|
167
|
+
body: { ok: true, message: accepted ? "Invalidation applied" : "Invalidation ignored (deduplicated or self)" }
|
|
168
|
+
};
|
|
169
|
+
} catch (err) {
|
|
170
|
+
return {
|
|
171
|
+
status: 400,
|
|
172
|
+
body: { ok: false, message: err.message }
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
57
178
|
// src/cache-service.ts
|
|
58
179
|
import crypto2 from "crypto";
|
|
59
180
|
import os3 from "os";
|
|
@@ -79,7 +200,8 @@ try {
|
|
|
79
200
|
_workerFile = jsPath;
|
|
80
201
|
}
|
|
81
202
|
} catch {
|
|
82
|
-
|
|
203
|
+
const sibling = join(__dirname, "serialize-worker.js");
|
|
204
|
+
_workerFile = existsSync(sibling) ? sibling : join(dirname(__dirname), "serialize-worker.js");
|
|
83
205
|
}
|
|
84
206
|
function getTransferableArrayBuffer(buf) {
|
|
85
207
|
if (buf.buffer instanceof ArrayBuffer) {
|
|
@@ -112,6 +234,7 @@ var WorkerPool = class {
|
|
|
112
234
|
}
|
|
113
235
|
_spawnWorkers(opts) {
|
|
114
236
|
const size = Math.max(1, opts.size ?? Math.min(4, availableCpus()));
|
|
237
|
+
if (!Number.isInteger(size) || size > 32 || !existsSync(_workerFile)) throw new Error("Worker pool unavailable or invalid worker count");
|
|
115
238
|
const workerData = {
|
|
116
239
|
keyBase64: opts.keyBase64,
|
|
117
240
|
mode: opts.mode,
|
|
@@ -125,7 +248,8 @@ var WorkerPool = class {
|
|
|
125
248
|
const createWorker = (index) => {
|
|
126
249
|
const worker = new Worker(_workerFile, {
|
|
127
250
|
workerData,
|
|
128
|
-
execArgv: _workerExecArgv
|
|
251
|
+
execArgv: _workerExecArgv
|
|
252
|
+
// Do not inherit --input-type/eval or application loader flags.
|
|
129
253
|
});
|
|
130
254
|
const pending = pendingList[index] ?? /* @__PURE__ */ new Map();
|
|
131
255
|
if (!pendingList[index]) pendingList[index] = pending;
|
|
@@ -155,7 +279,7 @@ var WorkerPool = class {
|
|
|
155
279
|
}
|
|
156
280
|
pending.clear();
|
|
157
281
|
worker.unref();
|
|
158
|
-
if (this._available &&
|
|
282
|
+
if (this._available && this.workers === workers && workers[index] === worker) {
|
|
159
283
|
try {
|
|
160
284
|
workers[index] = createWorker(index);
|
|
161
285
|
} catch {
|
|
@@ -165,9 +289,12 @@ var WorkerPool = class {
|
|
|
165
289
|
worker.unref();
|
|
166
290
|
return worker;
|
|
167
291
|
};
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
292
|
+
try {
|
|
293
|
+
for (let i = 0; i < size; i++) workers.push(createWorker(i));
|
|
294
|
+
} catch (error) {
|
|
295
|
+
for (const worker of workers) void worker.terminate().catch(() => {
|
|
296
|
+
});
|
|
297
|
+
throw error;
|
|
171
298
|
}
|
|
172
299
|
return { workers, pending: pendingList };
|
|
173
300
|
}
|
|
@@ -194,7 +321,7 @@ var WorkerPool = class {
|
|
|
194
321
|
entry.reject(new Error("WorkerPool replaced during key rotation"));
|
|
195
322
|
}
|
|
196
323
|
oldPending[i]?.clear();
|
|
197
|
-
oldWorkers[i]?.terminate().catch(() => {
|
|
324
|
+
await oldWorkers[i]?.terminate().catch(() => {
|
|
198
325
|
});
|
|
199
326
|
}
|
|
200
327
|
}
|
|
@@ -236,7 +363,13 @@ var WorkerPool = class {
|
|
|
236
363
|
return new Promise((resolve, reject) => {
|
|
237
364
|
pending.set(id, { resolve, reject });
|
|
238
365
|
worker.ref();
|
|
239
|
-
|
|
366
|
+
try {
|
|
367
|
+
worker.postMessage({ id, type, payload: dataToSend }, transferList);
|
|
368
|
+
} catch (error) {
|
|
369
|
+
pending.delete(id);
|
|
370
|
+
if (pending.size === 0) worker.unref();
|
|
371
|
+
reject(error);
|
|
372
|
+
}
|
|
240
373
|
});
|
|
241
374
|
}
|
|
242
375
|
/** Terminate all worker threads. In-flight promises are rejected. */
|
|
@@ -550,8 +683,9 @@ var WTinyLfuCache = class {
|
|
|
550
683
|
}
|
|
551
684
|
};
|
|
552
685
|
var WTinyLfuPolicy = class {
|
|
553
|
-
constructor(capacity, sketch, windowPercent = 0.01, protectedPercent = 0.8) {
|
|
686
|
+
constructor(capacity, sketch, windowPercent = 0.01, protectedPercent = 0.8, canEvict) {
|
|
554
687
|
this.sketch = sketch;
|
|
688
|
+
this.canEvict = canEvict;
|
|
555
689
|
this.maxTotal = Math.max(2, capacity);
|
|
556
690
|
this.maxWindow = Math.max(1, Math.floor(this.maxTotal * windowPercent));
|
|
557
691
|
const mainCapacity = Math.max(1, this.maxTotal - this.maxWindow);
|
|
@@ -559,6 +693,7 @@ var WTinyLfuPolicy = class {
|
|
|
559
693
|
this.maxProbation = Math.max(1, mainCapacity - this.maxProtected);
|
|
560
694
|
}
|
|
561
695
|
sketch;
|
|
696
|
+
canEvict;
|
|
562
697
|
maxTotal;
|
|
563
698
|
maxWindow;
|
|
564
699
|
maxProtected;
|
|
@@ -638,15 +773,33 @@ var WTinyLfuPolicy = class {
|
|
|
638
773
|
}
|
|
639
774
|
let victimKey;
|
|
640
775
|
let victimIsProbation = true;
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
776
|
+
for (const candidate of this.probation) {
|
|
777
|
+
if (!this.canEvict || this.canEvict(candidate)) {
|
|
778
|
+
victimKey = candidate;
|
|
779
|
+
break;
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
if (victimKey === void 0) {
|
|
783
|
+
for (const candidate of this.protected_) {
|
|
784
|
+
if (!this.canEvict || this.canEvict(candidate)) {
|
|
785
|
+
victimKey = candidate;
|
|
786
|
+
break;
|
|
787
|
+
}
|
|
788
|
+
}
|
|
645
789
|
victimIsProbation = false;
|
|
646
790
|
}
|
|
791
|
+
if (victimKey === void 0) {
|
|
792
|
+
if (this.canEvict && !this.canEvict(candKey)) {
|
|
793
|
+
this.window.delete(key);
|
|
794
|
+
this.window.add(candKey);
|
|
795
|
+
return { admit: false, candidateKey: key };
|
|
796
|
+
}
|
|
797
|
+
this.rejectionCount++;
|
|
798
|
+
return { admit: false, candidateKey: candKey };
|
|
799
|
+
}
|
|
647
800
|
const candFreq = this.sketch.estimate(candKey);
|
|
648
801
|
const victimFreq = this.sketch.estimate(victimKey);
|
|
649
|
-
if (candFreq > victimFreq) {
|
|
802
|
+
if (this.canEvict && !this.canEvict(candKey) || candFreq > victimFreq) {
|
|
650
803
|
if (victimIsProbation) {
|
|
651
804
|
this.probation.delete(victimKey);
|
|
652
805
|
} else {
|
|
@@ -785,8 +938,9 @@ var JsBloomFilter = class {
|
|
|
785
938
|
};
|
|
786
939
|
function createBloomFilter(logger, maxEntries) {
|
|
787
940
|
const LN2_SQ = Math.LN2 * Math.LN2;
|
|
788
|
-
const
|
|
789
|
-
const
|
|
941
|
+
const capacity = Math.max(1, maxEntries);
|
|
942
|
+
const optimalBits = Math.ceil(-capacity * Math.log(0.01) / LN2_SQ);
|
|
943
|
+
const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / capacity)));
|
|
790
944
|
try {
|
|
791
945
|
const wasm = new WasmBloomFilter();
|
|
792
946
|
if (wasm.maxCapacity >= maxEntries) {
|
|
@@ -910,7 +1064,10 @@ var SmartMemoryCache = class {
|
|
|
910
1064
|
this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
|
|
911
1065
|
this.categoryPrefixes = Object.keys(opts.categories).filter((k) => k !== "default");
|
|
912
1066
|
if (opts.admissionPolicy === "wtinylfu") {
|
|
913
|
-
this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch)
|
|
1067
|
+
this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch, 0.01, 0.8, (key) => {
|
|
1068
|
+
const entry = this.cache.get(key);
|
|
1069
|
+
return !entry || entry.priority !== 4 || entry.expiresAt <= Date.now();
|
|
1070
|
+
});
|
|
914
1071
|
}
|
|
915
1072
|
if (existing) {
|
|
916
1073
|
for (const [k, v] of existing) this.cache.set(k, v);
|
|
@@ -989,6 +1146,7 @@ var SmartMemoryCache = class {
|
|
|
989
1146
|
const MAX_EVICT_PASSES = 64;
|
|
990
1147
|
let passes = 0;
|
|
991
1148
|
do {
|
|
1149
|
+
const before = this.cache.size;
|
|
992
1150
|
this.smartEvict(category, catOvf);
|
|
993
1151
|
const lim2 = this.getCategoryLimit(category);
|
|
994
1152
|
const catCnt2 = this.categoryCount.get(category) ?? 0;
|
|
@@ -996,6 +1154,7 @@ var SmartMemoryCache = class {
|
|
|
996
1154
|
catOvf = catCnt2 >= lim2.maxEntries || catSz2 + neededSize > lim2.maxSizeBytes;
|
|
997
1155
|
glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
|
|
998
1156
|
passes++;
|
|
1157
|
+
if (this.cache.size === before) break;
|
|
999
1158
|
} while ((catOvf || glbOvf) && passes < MAX_EVICT_PASSES);
|
|
1000
1159
|
}
|
|
1001
1160
|
score(entry, catBonus, now, key) {
|
|
@@ -1126,20 +1285,26 @@ var SmartMemoryCache = class {
|
|
|
1126
1285
|
delta: entry.delta,
|
|
1127
1286
|
fetchedAt: now,
|
|
1128
1287
|
tagVersions: entry.tagVersions,
|
|
1129
|
-
setAt: entry.setAt
|
|
1288
|
+
setAt: entry.setAt,
|
|
1289
|
+
tags: entry.tags,
|
|
1290
|
+
dependsOn: entry.dependsOn
|
|
1130
1291
|
};
|
|
1131
1292
|
return hit;
|
|
1132
1293
|
}
|
|
1133
|
-
set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions, setAt) {
|
|
1294
|
+
set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions, setAt, tags, dependsOn) {
|
|
1134
1295
|
const packed = this.codec.encode(data);
|
|
1296
|
+
return this.storePacked(key, packed, data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn);
|
|
1297
|
+
}
|
|
1298
|
+
storePacked(key, packed, data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn) {
|
|
1135
1299
|
const size = packed.byteLength;
|
|
1136
1300
|
this.compressions++;
|
|
1137
1301
|
this.sketch.increment(key);
|
|
1138
1302
|
const cat = this.getCategory(key);
|
|
1139
1303
|
const lim = this.getCategoryLimit(cat);
|
|
1140
|
-
if (size > lim.maxSizeBytes * 0.5) {
|
|
1304
|
+
if (!Number.isFinite(ttlMs) || ttlMs <= 0 || this.opts.maxEntries <= 0 || lim.maxEntries <= 0 || size > this.opts.maxBytes || size > lim.maxSizeBytes * 0.5) {
|
|
1305
|
+
this.delete(key);
|
|
1141
1306
|
this.opts.logger.debug("SmartMemoryCache: entry too large, skipping", { key, sizeBytes: size });
|
|
1142
|
-
return;
|
|
1307
|
+
return false;
|
|
1143
1308
|
}
|
|
1144
1309
|
const existingEntry = this.cache.get(key);
|
|
1145
1310
|
if (existingEntry) {
|
|
@@ -1168,10 +1333,12 @@ var SmartMemoryCache = class {
|
|
|
1168
1333
|
ttlMs,
|
|
1169
1334
|
delta,
|
|
1170
1335
|
setAt: setAt ?? now2,
|
|
1171
|
-
tagVersions
|
|
1336
|
+
tagVersions,
|
|
1337
|
+
tags,
|
|
1338
|
+
dependsOn
|
|
1172
1339
|
});
|
|
1173
1340
|
}
|
|
1174
|
-
return;
|
|
1341
|
+
return false;
|
|
1175
1342
|
} else if (decision.candidateKey) {
|
|
1176
1343
|
const candEntry = this.cache.get(decision.candidateKey);
|
|
1177
1344
|
if (candEntry && this.opts.diskSpill) {
|
|
@@ -1187,15 +1354,19 @@ var SmartMemoryCache = class {
|
|
|
1187
1354
|
this._delete(decision.evictKey, "capacity");
|
|
1188
1355
|
}
|
|
1189
1356
|
const catSz = this.categorySize.get(cat) ?? 0;
|
|
1190
|
-
if (catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
|
|
1357
|
+
if ((this.categoryCount.get(cat) ?? 0) >= lim.maxEntries || this.cache.size >= this.opts.maxEntries || catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
|
|
1191
1358
|
this.ensureCapacity(cat, size);
|
|
1192
1359
|
}
|
|
1193
1360
|
} else {
|
|
1194
1361
|
this.ensureCapacity(cat, size);
|
|
1195
1362
|
}
|
|
1363
|
+
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) {
|
|
1364
|
+
this.wtinyPolicy?.onDelete(key);
|
|
1365
|
+
return false;
|
|
1366
|
+
}
|
|
1196
1367
|
const now = Date.now();
|
|
1197
1368
|
const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
|
|
1198
|
-
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 });
|
|
1369
|
+
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 });
|
|
1199
1370
|
if (!existingEntry) this.bloom.add(key);
|
|
1200
1371
|
this.maybeRebuildBloom();
|
|
1201
1372
|
this.totalSize += size;
|
|
@@ -1207,6 +1378,7 @@ var SmartMemoryCache = class {
|
|
|
1207
1378
|
this.categoryKeys.set(cat, ks);
|
|
1208
1379
|
}
|
|
1209
1380
|
ks.add(key);
|
|
1381
|
+
return true;
|
|
1210
1382
|
}
|
|
1211
1383
|
delete(key) {
|
|
1212
1384
|
const deleted = this._delete(key, "manual");
|
|
@@ -1408,25 +1580,48 @@ var SmartMemoryCache = class {
|
|
|
1408
1580
|
if (entry.expiresAt <= now) continue;
|
|
1409
1581
|
if (entry.priority === 4) continue;
|
|
1410
1582
|
if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
|
|
1411
|
-
|
|
1583
|
+
const { value: _value, ...stored } = entry;
|
|
1584
|
+
out.push({ key, entry: { ...stored } });
|
|
1412
1585
|
}
|
|
1413
1586
|
return out;
|
|
1414
1587
|
}
|
|
1415
1588
|
importEntries(entries, forbiddenPrefixes) {
|
|
1416
1589
|
const now = Date.now();
|
|
1417
1590
|
let loaded = 0;
|
|
1418
|
-
for (const
|
|
1419
|
-
if (
|
|
1591
|
+
for (const item of entries) {
|
|
1592
|
+
if (!item || typeof item.key !== "string" || !item.entry) continue;
|
|
1593
|
+
const { key, entry } = item;
|
|
1594
|
+
if (!Number.isFinite(entry.expiresAt) || entry.expiresAt <= now) continue;
|
|
1420
1595
|
if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
|
|
1421
1596
|
if (this.cache.has(key)) continue;
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1597
|
+
try {
|
|
1598
|
+
const rawData = entry.data;
|
|
1599
|
+
const data = !entry.isCompressed ? this.codec.encode(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : null;
|
|
1600
|
+
if (!data) continue;
|
|
1601
|
+
const value = data.length <= LARGE_VALUE_BYTES ? this.codec.decode(data) : void 0;
|
|
1602
|
+
if (this.storePacked(
|
|
1603
|
+
key,
|
|
1604
|
+
data,
|
|
1605
|
+
value,
|
|
1606
|
+
entry.expiresAt - now,
|
|
1607
|
+
entry.priority,
|
|
1608
|
+
entry.staleAt,
|
|
1609
|
+
entry.delta,
|
|
1610
|
+
entry.tagVersions,
|
|
1611
|
+
entry.setAt,
|
|
1612
|
+
entry.tags,
|
|
1613
|
+
entry.dependsOn
|
|
1614
|
+
)) {
|
|
1615
|
+
const restored = this.cache.get(key);
|
|
1616
|
+
restored.expiresAt = entry.expiresAt;
|
|
1617
|
+
restored.ttlMs = entry.ttlMs ?? entry.expiresAt - now;
|
|
1618
|
+
restored.hits = Number.isFinite(entry.hits) ? Math.max(1, entry.hits) : 1;
|
|
1619
|
+
restored.lastAccess = Number.isFinite(entry.lastAccess) ? entry.lastAccess : now;
|
|
1620
|
+
loaded++;
|
|
1621
|
+
}
|
|
1622
|
+
} catch {
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1430
1625
|
return loaded;
|
|
1431
1626
|
}
|
|
1432
1627
|
// ── Iterators ─────────────────────────────────────────────────────────────
|
|
@@ -1618,6 +1813,9 @@ var BoundedDiskQueue = class {
|
|
|
1618
1813
|
this.writeTimeoutMs = writeTimeoutMs;
|
|
1619
1814
|
this.failureThreshold = failureThreshold;
|
|
1620
1815
|
this.cooldownMs = cooldownMs;
|
|
1816
|
+
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) {
|
|
1817
|
+
throw new Error("Disk queue limits and timeout must be finite positive values (pending/cooldown may be zero)");
|
|
1818
|
+
}
|
|
1621
1819
|
}
|
|
1622
1820
|
maxConcurrent;
|
|
1623
1821
|
maxPending;
|
|
@@ -1630,6 +1828,17 @@ var BoundedDiskQueue = class {
|
|
|
1630
1828
|
consecutiveFailures = 0;
|
|
1631
1829
|
circuitState = "closed";
|
|
1632
1830
|
lastStateChangeMonotonic = performance.now();
|
|
1831
|
+
get isSaturated() {
|
|
1832
|
+
return this.active >= this.maxConcurrent && this.queue.length >= this.maxPending;
|
|
1833
|
+
}
|
|
1834
|
+
releaseSlot() {
|
|
1835
|
+
if (this.circuitState === "open") {
|
|
1836
|
+
for (const next2 of this.queue.splice(0)) next2(false);
|
|
1837
|
+
}
|
|
1838
|
+
const next = this.queue.shift();
|
|
1839
|
+
if (next) next(true);
|
|
1840
|
+
else this.active--;
|
|
1841
|
+
}
|
|
1633
1842
|
async schedule(task) {
|
|
1634
1843
|
const now = performance.now();
|
|
1635
1844
|
if (this.circuitState === "open") {
|
|
@@ -1645,18 +1854,25 @@ var BoundedDiskQueue = class {
|
|
|
1645
1854
|
this.spillsDropped++;
|
|
1646
1855
|
return null;
|
|
1647
1856
|
}
|
|
1648
|
-
if (this.
|
|
1857
|
+
if (this.isSaturated) {
|
|
1649
1858
|
this.spillsDropped++;
|
|
1650
1859
|
return null;
|
|
1651
1860
|
}
|
|
1652
1861
|
if (this.active >= this.maxConcurrent) {
|
|
1653
|
-
await new Promise((resolve) => this.queue.push(resolve));
|
|
1862
|
+
const admitted = await new Promise((resolve) => this.queue.push(resolve));
|
|
1863
|
+
if (!admitted) {
|
|
1864
|
+
this.spillsDropped++;
|
|
1865
|
+
return null;
|
|
1866
|
+
}
|
|
1867
|
+
} else {
|
|
1868
|
+
this.active++;
|
|
1654
1869
|
}
|
|
1655
|
-
this.active++;
|
|
1656
1870
|
let timeoutId = null;
|
|
1871
|
+
const work = Promise.resolve().then(task);
|
|
1872
|
+
void work.then(() => this.releaseSlot(), () => this.releaseSlot());
|
|
1657
1873
|
try {
|
|
1658
1874
|
const result = await Promise.race([
|
|
1659
|
-
|
|
1875
|
+
work,
|
|
1660
1876
|
new Promise((_, reject) => {
|
|
1661
1877
|
timeoutId = setTimeout(
|
|
1662
1878
|
() => reject(new Error(`Disk write exceeded timeout of ${this.writeTimeoutMs}ms`)),
|
|
@@ -1675,14 +1891,12 @@ var BoundedDiskQueue = class {
|
|
|
1675
1891
|
if (this.consecutiveFailures >= this.failureThreshold || this.circuitState === "half-open") {
|
|
1676
1892
|
this.circuitState = "open";
|
|
1677
1893
|
this.lastStateChangeMonotonic = performance.now();
|
|
1894
|
+
for (const next of this.queue.splice(0)) next(false);
|
|
1678
1895
|
}
|
|
1679
1896
|
this.spillsDropped++;
|
|
1680
1897
|
return null;
|
|
1681
1898
|
} finally {
|
|
1682
1899
|
if (timeoutId) clearTimeout(timeoutId);
|
|
1683
|
-
this.active--;
|
|
1684
|
-
const next = this.queue.shift();
|
|
1685
|
-
if (next) next();
|
|
1686
1900
|
}
|
|
1687
1901
|
}
|
|
1688
1902
|
getStats() {
|
|
@@ -1756,6 +1970,13 @@ var DiskTier = class {
|
|
|
1756
1970
|
usageCounted = false;
|
|
1757
1971
|
fileCount = 0;
|
|
1758
1972
|
// maintained in-memory; avoids walkCacheFiles() in stats
|
|
1973
|
+
reservedBytes = 0;
|
|
1974
|
+
reservedFiles = 0;
|
|
1975
|
+
saveSequence = 0;
|
|
1976
|
+
epoch = 0;
|
|
1977
|
+
pendingSaves = /* @__PURE__ */ new Map();
|
|
1978
|
+
closed = false;
|
|
1979
|
+
invalidatedKeys = /* @__PURE__ */ new Set();
|
|
1759
1980
|
/** Next bucket index (0–255) for the staggered janitor wheel. */
|
|
1760
1981
|
_nextJanitorBucket = 0;
|
|
1761
1982
|
// ── High-watermark pruning & host volume health state ─────────────────────
|
|
@@ -1796,6 +2017,7 @@ var DiskTier = class {
|
|
|
1796
2017
|
}
|
|
1797
2018
|
// ── Helpers ───────────────────────────────────────────────────────────────
|
|
1798
2019
|
ensureDir() {
|
|
2020
|
+
if (this.closed) return;
|
|
1799
2021
|
if (this.dirReady) return;
|
|
1800
2022
|
try {
|
|
1801
2023
|
fs.mkdirSync(this.opts.dir, { recursive: true, mode: 448 });
|
|
@@ -1917,8 +2139,24 @@ var DiskTier = class {
|
|
|
1917
2139
|
*
|
|
1918
2140
|
* 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
|
|
1919
2141
|
*/
|
|
1920
|
-
hashToWritePath(hash, expiresAt) {
|
|
1921
|
-
|
|
2142
|
+
hashToWritePath(hash, expiresAt, setAt) {
|
|
2143
|
+
const expiry = Math.floor(expiresAt).toString(16).padStart(12, "0");
|
|
2144
|
+
if (setAt === void 0) return path.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}`);
|
|
2145
|
+
const written = Math.floor(setAt).toString(16).padStart(12, "0");
|
|
2146
|
+
const sequence = (++this.saveSequence).toString(16).padStart(12, "0");
|
|
2147
|
+
return path.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}_${written}_${sequence}_${crypto.randomBytes(6).toString("hex")}`);
|
|
2148
|
+
}
|
|
2149
|
+
findFilePaths(hash) {
|
|
2150
|
+
const bucket = path.join(this.opts.dir, hash.slice(0, 2));
|
|
2151
|
+
try {
|
|
2152
|
+
return fs.readdirSync(bucket).filter((file) => !file.endsWith(".tmp") && (file === hash || file.startsWith(hash + "_"))).map((file) => path.join(bucket, file));
|
|
2153
|
+
} catch {
|
|
2154
|
+
return [];
|
|
2155
|
+
}
|
|
2156
|
+
}
|
|
2157
|
+
fileWrittenAt(file) {
|
|
2158
|
+
const parts = path.basename(file).split("_");
|
|
2159
|
+
return parts.length >= 4 ? parseInt(parts[2], 16) : fs.statSync(file).mtimeMs;
|
|
1922
2160
|
}
|
|
1923
2161
|
/**
|
|
1924
2162
|
* Find the on-disk file for a key hash, handling all filename generations:
|
|
@@ -1927,19 +2165,31 @@ var DiskTier = class {
|
|
|
1927
2165
|
* Returns null when the bucket dir does not exist or the key is absent.
|
|
1928
2166
|
*/
|
|
1929
2167
|
findFilePath(hash) {
|
|
1930
|
-
|
|
1931
|
-
let
|
|
2168
|
+
let match = null;
|
|
2169
|
+
let newest = -Infinity;
|
|
2170
|
+
let sequence = -1;
|
|
2171
|
+
for (const file of this.findFilePaths(hash)) {
|
|
2172
|
+
try {
|
|
2173
|
+
const written = this.fileWrittenAt(file);
|
|
2174
|
+
const order = parseInt(path.basename(file).split("_")[3] ?? "0", 16);
|
|
2175
|
+
if (written > newest || written === newest && order > sequence) {
|
|
2176
|
+
match = file;
|
|
2177
|
+
newest = written;
|
|
2178
|
+
sequence = order;
|
|
2179
|
+
}
|
|
2180
|
+
} catch {
|
|
2181
|
+
}
|
|
2182
|
+
}
|
|
2183
|
+
return match;
|
|
2184
|
+
}
|
|
2185
|
+
removeFile(filePath) {
|
|
1932
2186
|
try {
|
|
1933
|
-
|
|
2187
|
+
const size = fs.statSync(filePath).size;
|
|
2188
|
+
fs.unlinkSync(filePath);
|
|
2189
|
+
this.diskUsageBytes = Math.max(0, this.diskUsageBytes - size);
|
|
2190
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1934
2191
|
} catch {
|
|
1935
|
-
return null;
|
|
1936
2192
|
}
|
|
1937
|
-
let match;
|
|
1938
|
-
for (const f of files) {
|
|
1939
|
-
if ((f === hash || f.startsWith(hash + "_")) && (!match || f > match)) match = f;
|
|
1940
|
-
}
|
|
1941
|
-
if (!match) return null;
|
|
1942
|
-
return path.join(bucketPath, match);
|
|
1943
2193
|
}
|
|
1944
2194
|
/**
|
|
1945
2195
|
* Recursively list all cache file paths across the 2-level sharded subdirs.
|
|
@@ -2014,6 +2264,7 @@ var DiskTier = class {
|
|
|
2014
2264
|
* so the Node.js event loop is never stalled waiting for disk I/O.
|
|
2015
2265
|
*/
|
|
2016
2266
|
async save(key, entry) {
|
|
2267
|
+
if (this.closed || this.diskQueue.isSaturated) return;
|
|
2017
2268
|
if (this.isForbidden(key)) return;
|
|
2018
2269
|
if (entry.expiresAt <= Date.now()) return;
|
|
2019
2270
|
this.ensureDir();
|
|
@@ -2022,7 +2273,7 @@ var DiskTier = class {
|
|
|
2022
2273
|
if (++this._writeCounter % 2e3 === 0) {
|
|
2023
2274
|
this.checkHostVolumeHealth();
|
|
2024
2275
|
}
|
|
2025
|
-
if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes >= this.opts.maxBytes) {
|
|
2276
|
+
if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes + this.reservedBytes >= this.opts.maxBytes) {
|
|
2026
2277
|
this._spillsShedTotal++;
|
|
2027
2278
|
return;
|
|
2028
2279
|
}
|
|
@@ -2031,11 +2282,12 @@ var DiskTier = class {
|
|
|
2031
2282
|
}
|
|
2032
2283
|
let final;
|
|
2033
2284
|
try {
|
|
2285
|
+
const { value: _value, ...storedEntry } = entry;
|
|
2034
2286
|
const payload = {
|
|
2035
2287
|
version: DISK_TIER_VERSION,
|
|
2036
2288
|
key,
|
|
2037
2289
|
entry: {
|
|
2038
|
-
...
|
|
2290
|
+
...storedEntry,
|
|
2039
2291
|
data: entry.data instanceof Uint8Array ? Buffer.from(entry.data) : entry.data
|
|
2040
2292
|
},
|
|
2041
2293
|
writtenAt: Date.now()
|
|
@@ -2048,24 +2300,46 @@ var DiskTier = class {
|
|
|
2048
2300
|
}
|
|
2049
2301
|
const header = Buffer.allocUnsafe(V2_HEADER_LEN);
|
|
2050
2302
|
DISK_MAGIC_V2.copy(header, 0);
|
|
2051
|
-
header.writeBigUInt64LE(BigInt(entry.expiresAt), 8);
|
|
2303
|
+
header.writeBigUInt64LE(BigInt(Math.floor(entry.expiresAt)), 8);
|
|
2052
2304
|
final = Buffer.concat([header, this.encryptV2(toEncrypt)]);
|
|
2305
|
+
if (final.length > this.opts.entryMaxBytes || this.diskUsageBytes + this.reservedBytes + final.length > this.opts.maxBytes) return;
|
|
2053
2306
|
} catch (err) {
|
|
2054
2307
|
this.opts.logger.debug("DiskTier: pack/encrypt failed", { key: key.slice(0, 50), error: err.message });
|
|
2055
2308
|
return;
|
|
2056
2309
|
}
|
|
2057
2310
|
const hash = this.keyToHash(key);
|
|
2058
|
-
const
|
|
2311
|
+
const setAt = entry.setAt ?? Date.now();
|
|
2312
|
+
if ((this.pendingSaves.get(key)?.setAt ?? 0) > setAt) return;
|
|
2313
|
+
const filePath = this.hashToWritePath(hash, entry.expiresAt, setAt);
|
|
2059
2314
|
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${crypto.randomBytes(6).toString("hex")}.tmp`;
|
|
2060
|
-
|
|
2061
|
-
this.
|
|
2315
|
+
const token = Symbol(key);
|
|
2316
|
+
const epoch = this.epoch;
|
|
2317
|
+
this.pendingSaves.set(key, { token, setAt });
|
|
2318
|
+
const current = () => !this.closed && this.epoch === epoch && this.pendingSaves.get(key)?.token === token;
|
|
2319
|
+
let started = false;
|
|
2320
|
+
let released = false;
|
|
2321
|
+
let accounted = false;
|
|
2322
|
+
const releaseReservation = () => {
|
|
2323
|
+
if (released) return;
|
|
2324
|
+
released = true;
|
|
2325
|
+
this.reservedBytes = Math.max(0, this.reservedBytes - final.length);
|
|
2326
|
+
this.reservedFiles = Math.max(0, this.reservedFiles - 1);
|
|
2327
|
+
if (this.pendingSaves.get(key)?.token === token) this.pendingSaves.delete(key);
|
|
2328
|
+
};
|
|
2329
|
+
this.reservedBytes += final.length;
|
|
2330
|
+
this.reservedFiles++;
|
|
2062
2331
|
if (this.diskUsageBytes >= this.opts.maxBytes * 0.8 && !this._isPruning) {
|
|
2063
2332
|
void this.triggerChunkedPrune();
|
|
2064
2333
|
}
|
|
2065
2334
|
const result = await this.diskQueue.schedule(async () => {
|
|
2335
|
+
started = true;
|
|
2066
2336
|
try {
|
|
2337
|
+
if (!current()) return false;
|
|
2338
|
+
const previous = this.findFilePath(hash);
|
|
2339
|
+
if (previous && this.fileWrittenAt(previous) > setAt) return false;
|
|
2067
2340
|
await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
|
|
2068
2341
|
await fs.promises.writeFile(tmpPath, final, { mode: 384 });
|
|
2342
|
+
if (!current()) return false;
|
|
2069
2343
|
try {
|
|
2070
2344
|
await fs.promises.rename(tmpPath, filePath);
|
|
2071
2345
|
} catch (renameErr) {
|
|
@@ -2077,6 +2351,20 @@ var DiskTier = class {
|
|
|
2077
2351
|
throw renameErr;
|
|
2078
2352
|
}
|
|
2079
2353
|
}
|
|
2354
|
+
if (!current()) {
|
|
2355
|
+
try {
|
|
2356
|
+
await fs.promises.unlink(filePath);
|
|
2357
|
+
} catch {
|
|
2358
|
+
}
|
|
2359
|
+
return false;
|
|
2360
|
+
}
|
|
2361
|
+
for (const previousPath of this.findFilePaths(hash)) {
|
|
2362
|
+
if (previousPath !== filePath) this.removeFile(previousPath);
|
|
2363
|
+
}
|
|
2364
|
+
this.diskUsageBytes += final.length;
|
|
2365
|
+
this.fileCount++;
|
|
2366
|
+
accounted = true;
|
|
2367
|
+
this.invalidatedKeys.delete(key);
|
|
2080
2368
|
if (this._db) {
|
|
2081
2369
|
const priority = typeof entry.priority === "number" ? entry.priority : 2;
|
|
2082
2370
|
const lastAccess = typeof entry.lastAccess === "number" ? entry.lastAccess : Date.now();
|
|
@@ -2089,23 +2377,25 @@ var DiskTier = class {
|
|
|
2089
2377
|
await fs.promises.unlink(tmpPath);
|
|
2090
2378
|
} catch {
|
|
2091
2379
|
}
|
|
2092
|
-
|
|
2093
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2094
|
-
if (this._db) try {
|
|
2095
|
-
this._stmtDelete.run(hash);
|
|
2096
|
-
} catch {
|
|
2097
|
-
}
|
|
2380
|
+
if (accounted) this.removeFile(filePath);
|
|
2098
2381
|
this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
|
|
2099
2382
|
throw err;
|
|
2383
|
+
} finally {
|
|
2384
|
+
try {
|
|
2385
|
+
await fs.promises.unlink(tmpPath);
|
|
2386
|
+
} catch {
|
|
2387
|
+
}
|
|
2388
|
+
releaseReservation();
|
|
2389
|
+
if (this.invalidatedKeys.has(key) && !this.pendingSaves.has(key)) this.delete(key, true);
|
|
2100
2390
|
}
|
|
2101
2391
|
});
|
|
2102
|
-
if (result === null) {
|
|
2103
|
-
|
|
2104
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2392
|
+
if (result === null && !started) {
|
|
2393
|
+
releaseReservation();
|
|
2105
2394
|
}
|
|
2106
2395
|
}
|
|
2107
2396
|
/** Load a key from disk, or return null on miss/expiry/corruption. */
|
|
2108
2397
|
load(key) {
|
|
2398
|
+
if (this.invalidatedKeys.has(key) || this.closed) return null;
|
|
2109
2399
|
if (this.isForbidden(key)) return null;
|
|
2110
2400
|
this.ensureDir();
|
|
2111
2401
|
if (!this.dirReady) return null;
|
|
@@ -2133,8 +2423,8 @@ var DiskTier = class {
|
|
|
2133
2423
|
try {
|
|
2134
2424
|
if (!this._db) {
|
|
2135
2425
|
const filename = path.basename(filePath);
|
|
2136
|
-
if (filename.length
|
|
2137
|
-
const expiresAt = parseInt(filename.slice(65), 16);
|
|
2426
|
+
if (filename.length >= 77 && filename[64] === "_") {
|
|
2427
|
+
const expiresAt = parseInt(filename.slice(65, 77), 16);
|
|
2138
2428
|
if (expiresAt <= Date.now()) {
|
|
2139
2429
|
try {
|
|
2140
2430
|
const sz = fs.statSync(filePath).size;
|
|
@@ -2155,12 +2445,7 @@ var DiskTier = class {
|
|
|
2155
2445
|
return null;
|
|
2156
2446
|
}
|
|
2157
2447
|
const raw = fs.readFileSync(filePath);
|
|
2158
|
-
|
|
2159
|
-
fs.unlinkSync(filePath);
|
|
2160
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
2161
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2162
|
-
} catch {
|
|
2163
|
-
}
|
|
2448
|
+
for (const storedPath of this.findFilePaths(hash)) this.removeFile(storedPath);
|
|
2164
2449
|
if (this._db) this._stmtDelete.run(hash);
|
|
2165
2450
|
let decrypted;
|
|
2166
2451
|
if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
|
|
@@ -2195,25 +2480,24 @@ var DiskTier = class {
|
|
|
2195
2480
|
return null;
|
|
2196
2481
|
}
|
|
2197
2482
|
}
|
|
2198
|
-
/**
|
|
2199
|
-
|
|
2483
|
+
/** Synchronously fence queued/running saves while leaving filesystem cleanup deferred. */
|
|
2484
|
+
invalidate(key) {
|
|
2485
|
+
this.pendingSaves.delete(key);
|
|
2486
|
+
this.invalidatedKeys.add(key);
|
|
2487
|
+
}
|
|
2488
|
+
/** Delete all versions; deferred cleanup must not cancel a newer save. */
|
|
2489
|
+
delete(key, invalidatedOnly = false) {
|
|
2490
|
+
if (invalidatedOnly && (!this.invalidatedKeys.has(key) || this.pendingSaves.has(key))) return;
|
|
2491
|
+
if (!invalidatedOnly) this.pendingSaves.delete(key);
|
|
2200
2492
|
const hash = this.keyToHash(key);
|
|
2201
|
-
|
|
2493
|
+
const files = new Set(this.findFilePaths(hash));
|
|
2202
2494
|
if (this._db) {
|
|
2203
2495
|
const row = this._stmtSelect.get(hash);
|
|
2204
|
-
|
|
2496
|
+
if (row?.file_path) files.add(row.file_path);
|
|
2205
2497
|
this._stmtDelete.run(hash);
|
|
2206
|
-
} else {
|
|
2207
|
-
filePath = this.findFilePath(hash);
|
|
2208
|
-
}
|
|
2209
|
-
if (!filePath) return;
|
|
2210
|
-
try {
|
|
2211
|
-
const stat = fs.statSync(filePath);
|
|
2212
|
-
fs.unlinkSync(filePath);
|
|
2213
|
-
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
2214
|
-
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2215
|
-
} catch {
|
|
2216
2498
|
}
|
|
2499
|
+
for (const file of files) this.removeFile(file);
|
|
2500
|
+
this.invalidatedKeys.delete(key);
|
|
2217
2501
|
}
|
|
2218
2502
|
/** Purge all expired entries. Returns number deleted. */
|
|
2219
2503
|
purgeExpired() {
|
|
@@ -2249,8 +2533,8 @@ var DiskTier = class {
|
|
|
2249
2533
|
}
|
|
2250
2534
|
continue;
|
|
2251
2535
|
}
|
|
2252
|
-
if (filename.length
|
|
2253
|
-
const expiresAt = parseInt(filename.slice(65), 16);
|
|
2536
|
+
if (filename.length >= 77 && filename[64] === "_") {
|
|
2537
|
+
const expiresAt = parseInt(filename.slice(65, 77), 16);
|
|
2254
2538
|
if (expiresAt <= now) {
|
|
2255
2539
|
try {
|
|
2256
2540
|
const sz = fs.statSync(filePath).size;
|
|
@@ -2370,8 +2654,8 @@ var DiskTier = class {
|
|
|
2370
2654
|
}
|
|
2371
2655
|
continue;
|
|
2372
2656
|
}
|
|
2373
|
-
if (file.length
|
|
2374
|
-
const expiresAt = parseInt(file.slice(65), 16);
|
|
2657
|
+
if (file.length >= 77 && file[64] === "_") {
|
|
2658
|
+
const expiresAt = parseInt(file.slice(65, 77), 16);
|
|
2375
2659
|
if (expiresAt <= now2) {
|
|
2376
2660
|
const fp = path.join(orphanBucketP, file);
|
|
2377
2661
|
try {
|
|
@@ -2411,8 +2695,8 @@ var DiskTier = class {
|
|
|
2411
2695
|
}
|
|
2412
2696
|
continue;
|
|
2413
2697
|
}
|
|
2414
|
-
if (file.length
|
|
2415
|
-
const expiresAt = parseInt(file.slice(65), 16);
|
|
2698
|
+
if (file.length >= 77 && file[64] === "_") {
|
|
2699
|
+
const expiresAt = parseInt(file.slice(65, 77), 16);
|
|
2416
2700
|
if (expiresAt <= now) {
|
|
2417
2701
|
const filePath2 = path.join(bucketPath, file);
|
|
2418
2702
|
try {
|
|
@@ -2485,6 +2769,9 @@ var DiskTier = class {
|
|
|
2485
2769
|
}
|
|
2486
2770
|
/** Delete every file in the disk cache. Returns the count deleted. */
|
|
2487
2771
|
clear() {
|
|
2772
|
+
this.epoch++;
|
|
2773
|
+
this.pendingSaves.clear();
|
|
2774
|
+
this.invalidatedKeys.clear();
|
|
2488
2775
|
this.ensureDir();
|
|
2489
2776
|
if (!this.dirReady) return 0;
|
|
2490
2777
|
let cleared = 0;
|
|
@@ -2548,6 +2835,7 @@ var DiskTier = class {
|
|
|
2548
2835
|
* yielding to the event loop via setImmediate between chunks.
|
|
2549
2836
|
*/
|
|
2550
2837
|
async triggerChunkedPrune() {
|
|
2838
|
+
if (this.closed) return 0;
|
|
2551
2839
|
if (this._isPruning) return 0;
|
|
2552
2840
|
this._isPruning = true;
|
|
2553
2841
|
this._pruneRounds++;
|
|
@@ -2556,7 +2844,7 @@ var DiskTier = class {
|
|
|
2556
2844
|
this.ensureUsageCounted();
|
|
2557
2845
|
const targetBytes = Math.floor(this.opts.maxBytes * 0.6);
|
|
2558
2846
|
if (this._db && this._stmtPruneChunk) {
|
|
2559
|
-
while (this.diskUsageBytes > targetBytes) {
|
|
2847
|
+
while (!this.closed && this.diskUsageBytes > targetBytes) {
|
|
2560
2848
|
const rows = this._stmtPruneChunk.all();
|
|
2561
2849
|
if (!rows || rows.length === 0) break;
|
|
2562
2850
|
for (const row of rows) {
|
|
@@ -2579,7 +2867,7 @@ var DiskTier = class {
|
|
|
2579
2867
|
}
|
|
2580
2868
|
}
|
|
2581
2869
|
} else {
|
|
2582
|
-
while (this.diskUsageBytes > targetBytes) {
|
|
2870
|
+
while (!this.closed && this.diskUsageBytes > targetBytes) {
|
|
2583
2871
|
const files = this.walkCacheFiles();
|
|
2584
2872
|
if (files.length === 0) break;
|
|
2585
2873
|
const chunk = files.slice(0, 500);
|
|
@@ -2647,6 +2935,10 @@ var DiskTier = class {
|
|
|
2647
2935
|
}
|
|
2648
2936
|
/** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
|
|
2649
2937
|
close() {
|
|
2938
|
+
this.closed = true;
|
|
2939
|
+
this.epoch++;
|
|
2940
|
+
this.pendingSaves.clear();
|
|
2941
|
+
this.invalidatedKeys.clear();
|
|
2650
2942
|
if (this._db) {
|
|
2651
2943
|
try {
|
|
2652
2944
|
this._db.close();
|
|
@@ -2889,6 +3181,17 @@ function readCgroupMemoryLimit() {
|
|
|
2889
3181
|
}
|
|
2890
3182
|
return Infinity;
|
|
2891
3183
|
}
|
|
3184
|
+
function readCgroupMemoryUsage() {
|
|
3185
|
+
if (process.platform !== "linux") return null;
|
|
3186
|
+
for (const file of ["/sys/fs/cgroup/memory.current", "/sys/fs/cgroup/memory/memory.usage_in_bytes"]) {
|
|
3187
|
+
try {
|
|
3188
|
+
const value = Number(fs2.readFileSync(file, "utf8").trim());
|
|
3189
|
+
if (Number.isFinite(value) && value >= 0) return value;
|
|
3190
|
+
} catch {
|
|
3191
|
+
}
|
|
3192
|
+
}
|
|
3193
|
+
return null;
|
|
3194
|
+
}
|
|
2892
3195
|
function getV8HeapLimit() {
|
|
2893
3196
|
try {
|
|
2894
3197
|
const stats = v8.getHeapStatistics();
|
|
@@ -2912,7 +3215,81 @@ function resolveAutonomousL1MaxBytes(options) {
|
|
|
2912
3215
|
return Math.max(MIN_AUTONOMOUS_L1_FLOOR_BYTES, Math.floor(resolved));
|
|
2913
3216
|
}
|
|
2914
3217
|
|
|
3218
|
+
// src/utils/diagnostics.ts
|
|
3219
|
+
function redactDiagnostics(value, seen = /* @__PURE__ */ new WeakSet(), depth = 0) {
|
|
3220
|
+
if (typeof value === "string" && /^[a-z][a-z\d+.-]*:\/\//i.test(value)) {
|
|
3221
|
+
try {
|
|
3222
|
+
const url = new URL(value);
|
|
3223
|
+
if (url.username) url.username = "[REDACTED]";
|
|
3224
|
+
if (url.password) url.password = "[REDACTED]";
|
|
3225
|
+
for (const key of url.searchParams.keys()) {
|
|
3226
|
+
if (/key|token|secret|password|credential|authorization|cookie/i.test(key)) url.searchParams.set(key, "[REDACTED]");
|
|
3227
|
+
}
|
|
3228
|
+
return url.toString();
|
|
3229
|
+
} catch {
|
|
3230
|
+
return "[REDACTED URL]";
|
|
3231
|
+
}
|
|
3232
|
+
}
|
|
3233
|
+
if (value == null || typeof value !== "object") return typeof value === "function" ? void 0 : value;
|
|
3234
|
+
if (depth >= 8) return "[OMITTED]";
|
|
3235
|
+
if (seen.has(value)) return "[CIRCULAR]";
|
|
3236
|
+
seen.add(value);
|
|
3237
|
+
if (Array.isArray(value)) return value.map((item) => redactDiagnostics(item, seen, depth + 1));
|
|
3238
|
+
const result = {};
|
|
3239
|
+
for (const [key, item] of Object.entries(value)) {
|
|
3240
|
+
if (typeof item === "function") continue;
|
|
3241
|
+
result[key] = /key|token|secret|password|credential|authorization|cookie|headers/i.test(key) ? item == null ? item : "[REDACTED]" : redactDiagnostics(item, seen, depth + 1);
|
|
3242
|
+
}
|
|
3243
|
+
return result;
|
|
3244
|
+
}
|
|
3245
|
+
|
|
3246
|
+
// src/utils/redis-slot.ts
|
|
3247
|
+
function redisHashSlot(key) {
|
|
3248
|
+
const open = key.indexOf("{");
|
|
3249
|
+
const close = open < 0 ? -1 : key.indexOf("}", open + 1);
|
|
3250
|
+
const bytes = Buffer.from(close > open + 1 ? key.slice(open + 1, close) : key, "utf8");
|
|
3251
|
+
let crc = 0;
|
|
3252
|
+
for (const byte of bytes) {
|
|
3253
|
+
crc ^= byte << 8;
|
|
3254
|
+
for (let bit = 0; bit < 8; bit++) crc = crc << 1 ^ (crc & 32768 ? 4129 : 0);
|
|
3255
|
+
crc &= 65535;
|
|
3256
|
+
}
|
|
3257
|
+
return crc & 16383;
|
|
3258
|
+
}
|
|
3259
|
+
|
|
3260
|
+
// src/utils/deadline.ts
|
|
3261
|
+
async function withDeadline(operation, timeoutMs, label) {
|
|
3262
|
+
let timer;
|
|
3263
|
+
try {
|
|
3264
|
+
return await Promise.race([
|
|
3265
|
+
operation,
|
|
3266
|
+
new Promise((_resolve, reject) => {
|
|
3267
|
+
timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs);
|
|
3268
|
+
})
|
|
3269
|
+
]);
|
|
3270
|
+
} finally {
|
|
3271
|
+
if (timer) clearTimeout(timer);
|
|
3272
|
+
}
|
|
3273
|
+
}
|
|
3274
|
+
|
|
2915
3275
|
// src/adapters/auto-pipeliner.ts
|
|
3276
|
+
import { Cluster } from "ioredis";
|
|
3277
|
+
async function readRedisValue(client, key, hash = false) {
|
|
3278
|
+
if (typeof client.pttl === "function" && typeof client.multi === "function") {
|
|
3279
|
+
const transaction = client.multi();
|
|
3280
|
+
if (typeof transaction.pttl === "function" && (!hash || typeof transaction.hgetall === "function")) {
|
|
3281
|
+
if (hash) transaction.hgetall(key);
|
|
3282
|
+
else transaction.get(key);
|
|
3283
|
+
transaction.pttl(key);
|
|
3284
|
+
const results = await transaction.exec();
|
|
3285
|
+
if (!results) throw new Error("Redis read transaction aborted");
|
|
3286
|
+
if (results[0]?.[0]) throw results[0][0];
|
|
3287
|
+
if (results[1]?.[0]) throw results[1][0];
|
|
3288
|
+
return { raw: results[0]?.[1] ?? null, ttlMs: Number(results[1]?.[1]) };
|
|
3289
|
+
}
|
|
3290
|
+
}
|
|
3291
|
+
return { raw: await (hash ? client.hgetall(key) : client.get(key)) };
|
|
3292
|
+
}
|
|
2916
3293
|
var AutoPipeliner = class {
|
|
2917
3294
|
constructor(client, options) {
|
|
2918
3295
|
this.client = client;
|
|
@@ -2944,6 +3321,17 @@ var AutoPipeliner = class {
|
|
|
2944
3321
|
this.enqueue({ type: "get", key, resolve, reject });
|
|
2945
3322
|
});
|
|
2946
3323
|
}
|
|
3324
|
+
async read(key, hash = false) {
|
|
3325
|
+
if (!hash && typeof this.client.pttl !== "function") return { raw: await this.get(key) };
|
|
3326
|
+
if (!this.enabled || !this.supportsPipelines() || typeof this.client.pttl !== "function") {
|
|
3327
|
+
return readRedisValue(this.client, key, hash);
|
|
3328
|
+
}
|
|
3329
|
+
const probe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
|
|
3330
|
+
if (typeof probe.pttl !== "function" || hash && typeof probe.hgetall !== "function") {
|
|
3331
|
+
return readRedisValue(this.client, key, hash);
|
|
3332
|
+
}
|
|
3333
|
+
return new Promise((resolve, reject) => this.enqueue({ type: "read", key, hash, resolve, reject }));
|
|
3334
|
+
}
|
|
2947
3335
|
async setex(key, seconds, value) {
|
|
2948
3336
|
if (!this.enabled || !this.supportsPipelines()) {
|
|
2949
3337
|
if (typeof this.client.setex === "function") {
|
|
@@ -2957,8 +3345,18 @@ var AutoPipeliner = class {
|
|
|
2957
3345
|
this.enqueue({ type: "setex", key, seconds, value, resolve, reject });
|
|
2958
3346
|
});
|
|
2959
3347
|
}
|
|
3348
|
+
async setpx(key, milliseconds, value) {
|
|
3349
|
+
if (!this.enabled || !this.supportsPipelines()) {
|
|
3350
|
+
await this.client.set(key, value, "PX", milliseconds);
|
|
3351
|
+
return;
|
|
3352
|
+
}
|
|
3353
|
+
return new Promise((resolve, reject) => this.enqueue({ type: "setpx", key, milliseconds, value, resolve, reject }));
|
|
3354
|
+
}
|
|
2960
3355
|
async del(...keys) {
|
|
2961
3356
|
if (keys.length === 0) return 0;
|
|
3357
|
+
if (this.client instanceof Cluster && keys.length > 1) {
|
|
3358
|
+
return (await Promise.all(keys.map((key) => this.del(key)))).reduce((sum, value) => sum + value, 0);
|
|
3359
|
+
}
|
|
2962
3360
|
if (!this.enabled || !this.supportsPipelines()) {
|
|
2963
3361
|
return this.client.del(...keys);
|
|
2964
3362
|
}
|
|
@@ -2992,44 +3390,72 @@ var AutoPipeliner = class {
|
|
|
2992
3390
|
this.scheduled = false;
|
|
2993
3391
|
this.statsInternal.batchesDispatched++;
|
|
2994
3392
|
this.statsInternal.operationsBatched += batch.length;
|
|
2995
|
-
|
|
2996
|
-
|
|
2997
|
-
|
|
2998
|
-
|
|
2999
|
-
|
|
3000
|
-
|
|
3001
|
-
|
|
3002
|
-
|
|
3003
|
-
|
|
3004
|
-
|
|
3005
|
-
|
|
3006
|
-
|
|
3007
|
-
}
|
|
3393
|
+
if (this.client instanceof Cluster) {
|
|
3394
|
+
const groups = /* @__PURE__ */ new Map();
|
|
3395
|
+
for (const operation of batch) {
|
|
3396
|
+
const key = operation.type === "del" ? operation.keys[0] : operation.key;
|
|
3397
|
+
const slot = redisHashSlot(key);
|
|
3398
|
+
const master = this.client.slots[slot]?.[0] ?? String(slot);
|
|
3399
|
+
const members = groups.get(master) ?? [];
|
|
3400
|
+
members.push(operation);
|
|
3401
|
+
groups.set(master, members);
|
|
3402
|
+
}
|
|
3403
|
+
await Promise.all([...groups.values()].map((members) => this.dispatch(members)));
|
|
3404
|
+
return;
|
|
3008
3405
|
}
|
|
3406
|
+
await this.dispatch(batch);
|
|
3407
|
+
}
|
|
3408
|
+
async dispatch(batch) {
|
|
3009
3409
|
try {
|
|
3410
|
+
const pipe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
|
|
3411
|
+
const indexes = [];
|
|
3412
|
+
let commandCount = 0;
|
|
3413
|
+
for (const op of batch) {
|
|
3414
|
+
indexes.push(commandCount++);
|
|
3415
|
+
switch (op.type) {
|
|
3416
|
+
case "get":
|
|
3417
|
+
pipe.get(op.key);
|
|
3418
|
+
break;
|
|
3419
|
+
case "setex":
|
|
3420
|
+
pipe.setex(op.key, op.seconds, op.value);
|
|
3421
|
+
break;
|
|
3422
|
+
case "setpx":
|
|
3423
|
+
pipe.set(op.key, op.value, "PX", op.milliseconds);
|
|
3424
|
+
break;
|
|
3425
|
+
case "del":
|
|
3426
|
+
pipe.del(...op.keys);
|
|
3427
|
+
break;
|
|
3428
|
+
case "read":
|
|
3429
|
+
if (op.hash) pipe.hgetall(op.key);
|
|
3430
|
+
else pipe.get(op.key);
|
|
3431
|
+
pipe.pttl(op.key);
|
|
3432
|
+
commandCount++;
|
|
3433
|
+
break;
|
|
3434
|
+
}
|
|
3435
|
+
}
|
|
3010
3436
|
const results = await pipe.exec();
|
|
3011
3437
|
if (!results) {
|
|
3012
3438
|
for (const op of batch) {
|
|
3013
|
-
|
|
3014
|
-
else if (op.type === "del") op.resolve(0);
|
|
3015
|
-
else op.resolve();
|
|
3439
|
+
op.reject(new Error("Redis pipeline aborted"));
|
|
3016
3440
|
}
|
|
3017
3441
|
return;
|
|
3018
3442
|
}
|
|
3019
3443
|
for (let i = 0; i < batch.length; i++) {
|
|
3020
3444
|
const op = batch[i];
|
|
3021
|
-
const resTuple = results[i];
|
|
3445
|
+
const resTuple = results[indexes[i]];
|
|
3022
3446
|
if (!resTuple) {
|
|
3023
|
-
|
|
3024
|
-
else if (op.type === "del") op.resolve(0);
|
|
3025
|
-
else op.resolve();
|
|
3447
|
+
op.reject(new Error("Missing Redis pipeline result"));
|
|
3026
3448
|
continue;
|
|
3027
3449
|
}
|
|
3028
3450
|
const [err, val] = resTuple;
|
|
3029
3451
|
if (err) {
|
|
3030
3452
|
op.reject(err instanceof Error ? err : new Error(String(err)));
|
|
3031
3453
|
} else {
|
|
3032
|
-
if (op.type === "
|
|
3454
|
+
if (op.type === "read") {
|
|
3455
|
+
const ttlResult = results[indexes[i] + 1];
|
|
3456
|
+
if (!ttlResult || ttlResult[0]) op.reject(ttlResult?.[0] ?? new Error("Missing Redis PTTL result"));
|
|
3457
|
+
else op.resolve({ raw: val, ttlMs: Number(ttlResult[1]) });
|
|
3458
|
+
} else if (op.type === "get") {
|
|
3033
3459
|
op.resolve(val != null ? String(val) : null);
|
|
3034
3460
|
} else if (op.type === "del") {
|
|
3035
3461
|
op.resolve(typeof val === "number" ? val : Number(val) || 0);
|
|
@@ -3066,6 +3492,8 @@ var IpcTelemetryServer = class {
|
|
|
3066
3492
|
server = null;
|
|
3067
3493
|
socketPath;
|
|
3068
3494
|
_closed = false;
|
|
3495
|
+
_starting = null;
|
|
3496
|
+
sockets = /* @__PURE__ */ new Set();
|
|
3069
3497
|
_exitHandler = null;
|
|
3070
3498
|
_sigintHandler = null;
|
|
3071
3499
|
_sigtermHandler = null;
|
|
@@ -3073,10 +3501,23 @@ var IpcTelemetryServer = class {
|
|
|
3073
3501
|
* Start listening on the IPC socket / pipe.
|
|
3074
3502
|
*/
|
|
3075
3503
|
async start() {
|
|
3076
|
-
if (this.
|
|
3504
|
+
if (this._closed || this.server?.listening) return;
|
|
3505
|
+
if (this._starting) return this._starting;
|
|
3506
|
+
this._starting = this.startInternal();
|
|
3507
|
+
try {
|
|
3508
|
+
await this._starting;
|
|
3509
|
+
} finally {
|
|
3510
|
+
this._starting = null;
|
|
3511
|
+
}
|
|
3512
|
+
}
|
|
3513
|
+
async startInternal() {
|
|
3077
3514
|
if (process.platform !== "win32" && fs3.existsSync(this.socketPath)) {
|
|
3078
3515
|
await new Promise((resolve) => {
|
|
3079
3516
|
const testSocket = net.createConnection(this.socketPath);
|
|
3517
|
+
testSocket.setTimeout(1e3, () => {
|
|
3518
|
+
testSocket.destroy();
|
|
3519
|
+
resolve();
|
|
3520
|
+
});
|
|
3080
3521
|
testSocket.once("connect", () => {
|
|
3081
3522
|
testSocket.destroy();
|
|
3082
3523
|
resolve();
|
|
@@ -3091,17 +3532,37 @@ var IpcTelemetryServer = class {
|
|
|
3091
3532
|
});
|
|
3092
3533
|
});
|
|
3093
3534
|
}
|
|
3535
|
+
if (this._closed) return;
|
|
3094
3536
|
this.server = net.createServer((socket) => {
|
|
3537
|
+
if (this._closed) {
|
|
3538
|
+
socket.destroy();
|
|
3539
|
+
return;
|
|
3540
|
+
}
|
|
3541
|
+
this.sockets.add(socket);
|
|
3542
|
+
socket.once("close", () => this.sockets.delete(socket));
|
|
3543
|
+
socket.setTimeout(5e3, () => socket.destroy());
|
|
3095
3544
|
let buffer = "";
|
|
3545
|
+
let pending = 0;
|
|
3096
3546
|
socket.on("data", (chunk) => {
|
|
3547
|
+
if (Buffer.byteLength(buffer) + chunk.length > 4096 || socket.writableLength > 65536) {
|
|
3548
|
+
socket.destroy();
|
|
3549
|
+
return;
|
|
3550
|
+
}
|
|
3097
3551
|
buffer += chunk.toString("utf8");
|
|
3098
3552
|
let newlineIndex;
|
|
3099
3553
|
while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
|
|
3100
3554
|
const line = buffer.slice(0, newlineIndex).trim();
|
|
3101
3555
|
buffer = buffer.slice(newlineIndex + 1);
|
|
3102
3556
|
if (!line) continue;
|
|
3557
|
+
if (++pending > 8) {
|
|
3558
|
+
socket.destroy();
|
|
3559
|
+
return;
|
|
3560
|
+
}
|
|
3103
3561
|
setImmediate(() => {
|
|
3104
|
-
if (socket.destroyed)
|
|
3562
|
+
if (socket.destroyed) {
|
|
3563
|
+
pending--;
|
|
3564
|
+
return;
|
|
3565
|
+
}
|
|
3105
3566
|
try {
|
|
3106
3567
|
let cmd = line;
|
|
3107
3568
|
try {
|
|
@@ -3126,6 +3587,8 @@ var IpcTelemetryServer = class {
|
|
|
3126
3587
|
if (!socket.destroyed) {
|
|
3127
3588
|
socket.write(JSON.stringify({ error: err.message }) + "\n");
|
|
3128
3589
|
}
|
|
3590
|
+
} finally {
|
|
3591
|
+
pending--;
|
|
3129
3592
|
}
|
|
3130
3593
|
});
|
|
3131
3594
|
}
|
|
@@ -3133,21 +3596,38 @@ var IpcTelemetryServer = class {
|
|
|
3133
3596
|
socket.on("error", () => {
|
|
3134
3597
|
});
|
|
3135
3598
|
});
|
|
3599
|
+
this.server.maxConnections = 128;
|
|
3136
3600
|
await new Promise((resolve, reject) => {
|
|
3137
|
-
this.server
|
|
3138
|
-
|
|
3139
|
-
|
|
3601
|
+
const server = this.server;
|
|
3602
|
+
const cleanup = () => {
|
|
3603
|
+
server.off("error", failed);
|
|
3604
|
+
server.off("close", closed);
|
|
3605
|
+
};
|
|
3606
|
+
const failed = (error) => {
|
|
3607
|
+
cleanup();
|
|
3608
|
+
reject(error);
|
|
3609
|
+
};
|
|
3610
|
+
const closed = () => {
|
|
3611
|
+
cleanup();
|
|
3612
|
+
resolve();
|
|
3613
|
+
};
|
|
3614
|
+
server.once("error", failed);
|
|
3615
|
+
server.once("close", closed);
|
|
3616
|
+
server.listen(this.socketPath, () => {
|
|
3617
|
+
cleanup();
|
|
3140
3618
|
resolve();
|
|
3141
3619
|
});
|
|
3142
3620
|
});
|
|
3621
|
+
if (this._closed) {
|
|
3622
|
+
if (this.server.listening) this.server.close();
|
|
3623
|
+
return;
|
|
3624
|
+
}
|
|
3143
3625
|
this._exitHandler = () => this._unlinkSocket();
|
|
3144
3626
|
this._sigintHandler = () => {
|
|
3145
3627
|
this._unlinkSocket();
|
|
3146
|
-
process.exit(0);
|
|
3147
3628
|
};
|
|
3148
3629
|
this._sigtermHandler = () => {
|
|
3149
3630
|
this._unlinkSocket();
|
|
3150
|
-
process.exit(0);
|
|
3151
3631
|
};
|
|
3152
3632
|
process.once("exit", this._exitHandler);
|
|
3153
3633
|
process.once("SIGINT", this._sigintHandler);
|
|
@@ -3177,6 +3657,7 @@ var IpcTelemetryServer = class {
|
|
|
3177
3657
|
_unlinkSocket() {
|
|
3178
3658
|
if (this._closed) return;
|
|
3179
3659
|
this._closed = true;
|
|
3660
|
+
for (const socket of this.sockets) socket.destroy();
|
|
3180
3661
|
try {
|
|
3181
3662
|
this.server?.close();
|
|
3182
3663
|
} catch {
|
|
@@ -3194,6 +3675,9 @@ var IpcTelemetryServer = class {
|
|
|
3194
3675
|
* Gracefully close the IPC telemetry server and clean up handlers and sockets.
|
|
3195
3676
|
*/
|
|
3196
3677
|
async close() {
|
|
3678
|
+
this._unlinkSocket();
|
|
3679
|
+
await this._starting?.catch(() => {
|
|
3680
|
+
});
|
|
3197
3681
|
if (this._exitHandler) {
|
|
3198
3682
|
process.removeListener("exit", this._exitHandler);
|
|
3199
3683
|
this._exitHandler = null;
|
|
@@ -3206,7 +3690,6 @@ var IpcTelemetryServer = class {
|
|
|
3206
3690
|
process.removeListener("SIGTERM", this._sigtermHandler);
|
|
3207
3691
|
this._sigtermHandler = null;
|
|
3208
3692
|
}
|
|
3209
|
-
this._unlinkSocket();
|
|
3210
3693
|
return new Promise((resolve) => {
|
|
3211
3694
|
if (!this.server || !this.server.listening) {
|
|
3212
3695
|
resolve();
|
|
@@ -3443,6 +3926,37 @@ if currentTs and currentTs == ARGV[1] then
|
|
|
3443
3926
|
end
|
|
3444
3927
|
return 0
|
|
3445
3928
|
`;
|
|
3929
|
+
var LUA_READ_CACHE_ENTRY = `
|
|
3930
|
+
local kind = redis.call('TYPE', KEYS[1]).ok
|
|
3931
|
+
if kind == 'string' then
|
|
3932
|
+
return { kind, redis.call('GET', KEYS[1]), redis.call('PTTL', KEYS[1]) }
|
|
3933
|
+
elseif kind == 'hash' then
|
|
3934
|
+
return { kind, redis.call('HGETALL', KEYS[1]), redis.call('PTTL', KEYS[1]) }
|
|
3935
|
+
end
|
|
3936
|
+
return { 'none', false, -2 }
|
|
3937
|
+
`;
|
|
3938
|
+
var LUA_MAX_TAG_VERSION = `
|
|
3939
|
+
local current = tonumber(redis.call('GET', KEYS[1]) or '0')
|
|
3940
|
+
local floor = tonumber(ARGV[1])
|
|
3941
|
+
if current < floor then redis.call('SET', KEYS[1], floor) return floor end
|
|
3942
|
+
return current
|
|
3943
|
+
`;
|
|
3944
|
+
var LUA_RECEIVE_TAG_VERSION = `
|
|
3945
|
+
local current = tonumber(redis.call('GET', KEYS[1]) or '0')
|
|
3946
|
+
local next = math.max(current + 1, tonumber(ARGV[1]))
|
|
3947
|
+
redis.call('SET', KEYS[1], next)
|
|
3948
|
+
return next
|
|
3949
|
+
`;
|
|
3950
|
+
var LUA_TOUCH_CACHE_ENTRY = `
|
|
3951
|
+
local kind = redis.call('TYPE', KEYS[1]).ok
|
|
3952
|
+
if kind == 'hash' then
|
|
3953
|
+
if redis.call('HGET', KEYS[1], 't') ~= ARGV[1] then return 0 end
|
|
3954
|
+
redis.call('HSET', KEYS[1], 'e', ARGV[2])
|
|
3955
|
+
elseif kind ~= 'string' then
|
|
3956
|
+
return 0
|
|
3957
|
+
end
|
|
3958
|
+
return redis.call('PEXPIRE', KEYS[1], ARGV[3])
|
|
3959
|
+
`;
|
|
3446
3960
|
var SNAPSHOT_VERSION = 1;
|
|
3447
3961
|
var DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
|
|
3448
3962
|
var INDEFINITE_TTL_SECONDS = 31536e3;
|
|
@@ -3735,6 +4249,7 @@ var CacheService = class _CacheService {
|
|
|
3735
4249
|
keyTags = /* @__PURE__ */ new Map();
|
|
3736
4250
|
/** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
|
|
3737
4251
|
tagVersions = /* @__PURE__ */ new Map();
|
|
4252
|
+
_tagRefreshEpoch = 0;
|
|
3738
4253
|
/**
|
|
3739
4254
|
* Dependency index: source glob pattern → Set of namespaced dependent keys.
|
|
3740
4255
|
* When an exact-key delete matches a registered pattern, all dependents are cascaded.
|
|
@@ -3765,9 +4280,17 @@ var CacheService = class _CacheService {
|
|
|
3765
4280
|
subClient = null;
|
|
3766
4281
|
streamClient = null;
|
|
3767
4282
|
_lastStreamId = "$";
|
|
4283
|
+
_restoredSnapshot = false;
|
|
4284
|
+
_backplaneAvailable = false;
|
|
4285
|
+
_otelCleanup = null;
|
|
4286
|
+
_streamRecovering = false;
|
|
4287
|
+
_backplaneDisposers = [];
|
|
3768
4288
|
_destroyed = false;
|
|
3769
4289
|
_pendingDiskDeletes = /* @__PURE__ */ new Set();
|
|
3770
4290
|
_globalEpoch = 0;
|
|
4291
|
+
_pendingSpillCount = 0;
|
|
4292
|
+
_suppressSpills = false;
|
|
4293
|
+
_diskCleanupScheduled = false;
|
|
3771
4294
|
_keyMutationEpochs = /* @__PURE__ */ new Map();
|
|
3772
4295
|
/**
|
|
3773
4296
|
* Pattern tombstones for disk tier.
|
|
@@ -3776,20 +4299,24 @@ var CacheService = class _CacheService {
|
|
|
3776
4299
|
* pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
|
|
3777
4300
|
*/
|
|
3778
4301
|
_patternTombstones = [];
|
|
3779
|
-
|
|
4302
|
+
_diskInvalidatedBefore = 0;
|
|
4303
|
+
_addPatternTombstone(pattern) {
|
|
3780
4304
|
const now = Date.now();
|
|
3781
4305
|
while (this._patternTombstones.length > 0 && now - this._patternTombstones[0].createdAt > 36e5) {
|
|
3782
|
-
this._patternTombstones.shift();
|
|
4306
|
+
const forgotten = this._patternTombstones.shift();
|
|
4307
|
+
this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
|
|
3783
4308
|
}
|
|
3784
4309
|
if (this._patternTombstones.length >= 2e3) {
|
|
3785
|
-
this._patternTombstones.shift();
|
|
4310
|
+
const forgotten = this._patternTombstones.shift();
|
|
4311
|
+
this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
|
|
3786
4312
|
}
|
|
3787
|
-
this._patternTombstones.push({
|
|
4313
|
+
this._patternTombstones.push({ pattern, createdAt: now });
|
|
3788
4314
|
}
|
|
3789
|
-
_isTombstonedByPattern(namespacedKey) {
|
|
4315
|
+
_isTombstonedByPattern(namespacedKey, setAt = 0) {
|
|
4316
|
+
if (this._diskInvalidatedBefore > 0 && setAt <= this._diskInvalidatedBefore) return true;
|
|
3790
4317
|
if (this._patternTombstones.length === 0) return false;
|
|
3791
4318
|
for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
|
|
3792
|
-
if (
|
|
4319
|
+
if (setAt <= this._patternTombstones[i].createdAt && this._matchesGlob(namespacedKey, this._patternTombstones[i].pattern)) {
|
|
3793
4320
|
return true;
|
|
3794
4321
|
}
|
|
3795
4322
|
}
|
|
@@ -3804,13 +4331,86 @@ var CacheService = class _CacheService {
|
|
|
3804
4331
|
const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
|
|
3805
4332
|
this._keyMutationEpochs.set(namespacedKey, next);
|
|
3806
4333
|
if (this._keyMutationEpochs.size > 5e4) {
|
|
3807
|
-
|
|
3808
|
-
|
|
4334
|
+
this._globalEpoch++;
|
|
4335
|
+
this._keyMutationEpochs.clear();
|
|
4336
|
+
this._keyMutationEpochs.set(namespacedKey, next);
|
|
3809
4337
|
}
|
|
3810
4338
|
return next;
|
|
3811
4339
|
}
|
|
3812
4340
|
_getKeyMutationEpoch(namespacedKey) {
|
|
3813
|
-
return this._globalEpoch
|
|
4341
|
+
return `${this._globalEpoch}:${this._keyMutationEpochs.get(namespacedKey) ?? 0}`;
|
|
4342
|
+
}
|
|
4343
|
+
/** Capture a commit fence before asynchronous computation outside the cache. */
|
|
4344
|
+
captureMutationFence(cacheKey) {
|
|
4345
|
+
this._assertActive("captureMutationFence");
|
|
4346
|
+
const key = this.nk(cacheKey);
|
|
4347
|
+
const epoch = this._getKeyMutationEpoch(key);
|
|
4348
|
+
return () => !this._destroyed && this._getKeyMutationEpoch(key) === epoch;
|
|
4349
|
+
}
|
|
4350
|
+
/** Force tag re-sync without forgetting locally observed monotonic generations. */
|
|
4351
|
+
refreshTagVersions() {
|
|
4352
|
+
this._assertActive("refreshTagVersions");
|
|
4353
|
+
this._tagRefreshEpoch++;
|
|
4354
|
+
}
|
|
4355
|
+
_fenceInvalidation() {
|
|
4356
|
+
this._globalEpoch++;
|
|
4357
|
+
this.inflight.clear();
|
|
4358
|
+
}
|
|
4359
|
+
_invalidateDiskKey(key) {
|
|
4360
|
+
if (this._diskDisabled) return;
|
|
4361
|
+
this.disk.invalidate(key);
|
|
4362
|
+
this._pendingDiskDeletes.add(key);
|
|
4363
|
+
this._scheduleDiskCleanup();
|
|
4364
|
+
}
|
|
4365
|
+
_scheduleDiskCleanup() {
|
|
4366
|
+
if (this._diskCleanupScheduled || this._pendingDiskDeletes.size === 0) return;
|
|
4367
|
+
this._diskCleanupScheduled = true;
|
|
4368
|
+
setImmediate(() => {
|
|
4369
|
+
this._diskCleanupScheduled = false;
|
|
4370
|
+
if (this._destroyed) return;
|
|
4371
|
+
let processed = 0;
|
|
4372
|
+
for (const key of this._pendingDiskDeletes) {
|
|
4373
|
+
try {
|
|
4374
|
+
this.disk.delete(key, true);
|
|
4375
|
+
} finally {
|
|
4376
|
+
this._pendingDiskDeletes.delete(key);
|
|
4377
|
+
}
|
|
4378
|
+
if (++processed >= 16) break;
|
|
4379
|
+
}
|
|
4380
|
+
this._scheduleDiskCleanup();
|
|
4381
|
+
});
|
|
4382
|
+
}
|
|
4383
|
+
_registerDependencies(key, patterns) {
|
|
4384
|
+
this._removeKeyDependencies(key);
|
|
4385
|
+
if (!patterns?.length) return;
|
|
4386
|
+
const namespaced = [...new Set(patterns.map((pattern) => this.nk(pattern)))];
|
|
4387
|
+
for (const pattern of namespaced) {
|
|
4388
|
+
const dependents = this.dependencyIndex.get(pattern) ?? /* @__PURE__ */ new Set();
|
|
4389
|
+
dependents.add(key);
|
|
4390
|
+
this.dependencyIndex.set(pattern, dependents);
|
|
4391
|
+
}
|
|
4392
|
+
this.keyDependencies.set(key, namespaced);
|
|
4393
|
+
}
|
|
4394
|
+
_rememberTags(key, tags, expiresAt) {
|
|
4395
|
+
this._removeKeyTags(key);
|
|
4396
|
+
if (!tags.length) return;
|
|
4397
|
+
if (this.keyTags.size >= 1e5) {
|
|
4398
|
+
this._sweepExpiredMetadata();
|
|
4399
|
+
const oldest = this.keyTags.keys().next().value;
|
|
4400
|
+
if (this.keyTags.size >= 1e5 && oldest !== void 0) this._removeKeyTags(oldest);
|
|
4401
|
+
}
|
|
4402
|
+
const unique = [...new Set(tags)];
|
|
4403
|
+
for (const tag of unique) {
|
|
4404
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
4405
|
+
const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
|
|
4406
|
+
members.add(key);
|
|
4407
|
+
this.tagIndex.set(tagKey, members);
|
|
4408
|
+
}
|
|
4409
|
+
this.keyTags.set(key, { tags: unique, expiresAt });
|
|
4410
|
+
}
|
|
4411
|
+
_restoreEntryMetadata(key, entry) {
|
|
4412
|
+
if (entry.tags?.length) this._rememberTags(key, entry.tags, entry.expiresAt);
|
|
4413
|
+
if (entry.dependsOn?.length) this._registerDependencies(key, entry.dependsOn);
|
|
3814
4414
|
}
|
|
3815
4415
|
_removeKeyTags(namespacedKey) {
|
|
3816
4416
|
const entry = this.keyTags.get(namespacedKey);
|
|
@@ -3844,21 +4444,21 @@ var CacheService = class _CacheService {
|
|
|
3844
4444
|
}
|
|
3845
4445
|
}
|
|
3846
4446
|
_handleL1Eviction(namespacedKey, reason) {
|
|
3847
|
-
const spilledToDisk = !this._diskDisabled && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
|
|
4447
|
+
const spilledToDisk = !this._diskDisabled && !this._suppressSpills && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
|
|
3848
4448
|
if (!spilledToDisk) {
|
|
3849
4449
|
this._removeKeyTags(namespacedKey);
|
|
3850
4450
|
this._removeKeyDependencies(namespacedKey);
|
|
3851
4451
|
}
|
|
3852
4452
|
}
|
|
3853
|
-
|
|
4453
|
+
_removePatternFromIndices(pattern) {
|
|
3854
4454
|
for (const k of Array.from(this.keyTags.keys())) {
|
|
3855
|
-
if (
|
|
4455
|
+
if (this._matchesGlob(k, pattern)) this._removeKeyTags(k);
|
|
3856
4456
|
}
|
|
3857
4457
|
for (const k of Array.from(this.keyDependencies.keys())) {
|
|
3858
|
-
if (
|
|
4458
|
+
if (this._matchesGlob(k, pattern)) this._removeKeyDependencies(k);
|
|
3859
4459
|
}
|
|
3860
4460
|
for (const k of Array.from(this._l1Counters.keys())) {
|
|
3861
|
-
if (
|
|
4461
|
+
if (this._matchesGlob(k, pattern)) this._l1Counters.delete(k);
|
|
3862
4462
|
}
|
|
3863
4463
|
}
|
|
3864
4464
|
_sweepExpiredMetadata() {
|
|
@@ -3876,10 +4476,16 @@ var CacheService = class _CacheService {
|
|
|
3876
4476
|
_runOomCheck() {
|
|
3877
4477
|
const heap = v82.getHeapStatistics();
|
|
3878
4478
|
const heapUsed = heap.used_heap_size / heap.heap_size_limit;
|
|
3879
|
-
const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? process.memoryUsage().rss / this._cgroupMemoryLimit : 0;
|
|
4479
|
+
const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? (readCgroupMemoryUsage() ?? process.memoryUsage().rss) / this._cgroupMemoryLimit : 0;
|
|
3880
4480
|
const used = Math.max(heapUsed, cgroupUsed);
|
|
3881
4481
|
if (used >= this.opts.oomHeapThreshold) {
|
|
3882
|
-
|
|
4482
|
+
this._suppressSpills = cgroupUsed >= this.opts.oomHeapThreshold;
|
|
4483
|
+
let evicted;
|
|
4484
|
+
try {
|
|
4485
|
+
evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
|
|
4486
|
+
} finally {
|
|
4487
|
+
this._suppressSpills = false;
|
|
4488
|
+
}
|
|
3883
4489
|
this.counters.oomEvictions++;
|
|
3884
4490
|
this.counters.oomLastAt = Date.now();
|
|
3885
4491
|
this.logger.warn("tricache OOM guard: emergency L1 eviction", {
|
|
@@ -4115,9 +4721,13 @@ var CacheService = class _CacheService {
|
|
|
4115
4721
|
admissionPolicy: this.opts.l1AdmissionPolicy,
|
|
4116
4722
|
codec: this.codec,
|
|
4117
4723
|
diskSpill: (key, entry) => {
|
|
4118
|
-
if (this._diskDisabled) return;
|
|
4724
|
+
if (this._diskDisabled || this._suppressSpills) return;
|
|
4725
|
+
if (this._pendingSpillCount >= (this.opts.diskMaxPendingWrites ?? 512)) return;
|
|
4726
|
+
const epoch = this._getKeyMutationEpoch(key);
|
|
4727
|
+
this._pendingSpillCount++;
|
|
4119
4728
|
setImmediate(() => {
|
|
4120
|
-
|
|
4729
|
+
this._pendingSpillCount--;
|
|
4730
|
+
if (!this._destroyed && this._getKeyMutationEpoch(key) === epoch) void this.disk.save(key, entry);
|
|
4121
4731
|
});
|
|
4122
4732
|
},
|
|
4123
4733
|
onEviction: (key, reason) => {
|
|
@@ -4196,7 +4806,7 @@ var CacheService = class _CacheService {
|
|
|
4196
4806
|
this.instanceId = crypto2.randomBytes(8).toString("hex");
|
|
4197
4807
|
this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
|
|
4198
4808
|
this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
|
|
4199
|
-
this.initBackplane();
|
|
4809
|
+
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 }));
|
|
4200
4810
|
const startupPromises = [];
|
|
4201
4811
|
if (this.opts.compression === "zstd") {
|
|
4202
4812
|
startupPromises.push(initZstd().then(() => void 0));
|
|
@@ -4207,9 +4817,8 @@ var CacheService = class _CacheService {
|
|
|
4207
4817
|
if (this.opts.warmKeys) {
|
|
4208
4818
|
startupPromises.push(this.warmFromL2(this.opts.warmKeys).then(() => void 0));
|
|
4209
4819
|
}
|
|
4210
|
-
|
|
4211
|
-
|
|
4212
|
-
}
|
|
4820
|
+
const backplaneReady = this.opts.remoteSnapshot || this.opts.warmKeys ? Promise.all(startupPromises).then(startBackplane) : startBackplane();
|
|
4821
|
+
this._readyPromise = Promise.all([...startupPromises, backplaneReady]).then(() => void 0);
|
|
4213
4822
|
if (this.opts.meter) {
|
|
4214
4823
|
this._initOtelMetrics(this.opts.meter);
|
|
4215
4824
|
const otel = this._otelMetrics;
|
|
@@ -4222,7 +4831,10 @@ var CacheService = class _CacheService {
|
|
|
4222
4831
|
if (typeof prop === "string" && typeof value === "number" && typeof oldVal === "number") {
|
|
4223
4832
|
const diff = value - oldVal;
|
|
4224
4833
|
if (diff > 0 && otel[prop]) {
|
|
4225
|
-
|
|
4834
|
+
try {
|
|
4835
|
+
otel[prop].add(diff, nsAttr);
|
|
4836
|
+
} catch {
|
|
4837
|
+
}
|
|
4226
4838
|
}
|
|
4227
4839
|
}
|
|
4228
4840
|
return ok;
|
|
@@ -4314,7 +4926,7 @@ var CacheService = class _CacheService {
|
|
|
4314
4926
|
return g[key];
|
|
4315
4927
|
}
|
|
4316
4928
|
const existing = g[key];
|
|
4317
|
-
const diff = _CacheService.optionsDiff(options ?? {}, existing.
|
|
4929
|
+
const diff = _CacheService.optionsDiff(options ?? {}, existing.opts);
|
|
4318
4930
|
if (diff.length > 0) {
|
|
4319
4931
|
existing.bumpSingletonDivergence();
|
|
4320
4932
|
const msg = `tricache: singleton already initialised for namespace '${existing.options.namespace || "(default)"}' \u2014 ignoring divergent options: ${diff.join(", ")}`;
|
|
@@ -4348,7 +4960,13 @@ var CacheService = class _CacheService {
|
|
|
4348
4960
|
"instanceName",
|
|
4349
4961
|
"invalidationBackplane",
|
|
4350
4962
|
"awaitInvalidationBackplane",
|
|
4351
|
-
"lockFailClosed"
|
|
4963
|
+
"lockFailClosed",
|
|
4964
|
+
"tagStrategy",
|
|
4965
|
+
"cloneStrategy",
|
|
4966
|
+
"compression",
|
|
4967
|
+
"backplaneMode",
|
|
4968
|
+
"redisProtocol",
|
|
4969
|
+
"failClosed"
|
|
4352
4970
|
];
|
|
4353
4971
|
/** Returns the names of options that differ between `a` and the live `b`. */
|
|
4354
4972
|
static optionsDiff(a, b) {
|
|
@@ -4366,12 +4984,12 @@ var CacheService = class _CacheService {
|
|
|
4366
4984
|
bumpSingletonDivergence() {
|
|
4367
4985
|
this.counters.singletonDivergences++;
|
|
4368
4986
|
}
|
|
4369
|
-
/**
|
|
4987
|
+
/** Sanitized diagnostic view; retain the original options/adapters to reuse configuration. */
|
|
4370
4988
|
get options() {
|
|
4371
4989
|
const o = this.opts;
|
|
4372
4990
|
return {
|
|
4373
4991
|
namespace: o.namespace,
|
|
4374
|
-
logger: o.logger,
|
|
4992
|
+
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) },
|
|
4375
4993
|
l1MaxBytes: o.l1MaxBytes,
|
|
4376
4994
|
l1MaxEntries: o.l1MaxEntries,
|
|
4377
4995
|
redisHost: o.redisHost,
|
|
@@ -4392,8 +5010,8 @@ var CacheService = class _CacheService {
|
|
|
4392
5010
|
awaitInvalidationBackplane: o.awaitInvalidationBackplane,
|
|
4393
5011
|
lockFailClosed: o.lockFailClosed,
|
|
4394
5012
|
strictSingleton: o.strictSingleton,
|
|
4395
|
-
remoteSnapshot: o.remoteSnapshot,
|
|
4396
|
-
crossRegion: o.crossRegion
|
|
5013
|
+
remoteSnapshot: redactDiagnostics(o.remoteSnapshot),
|
|
5014
|
+
crossRegion: redactDiagnostics(o.crossRegion)
|
|
4397
5015
|
};
|
|
4398
5016
|
}
|
|
4399
5017
|
/**
|
|
@@ -4476,11 +5094,15 @@ var CacheService = class _CacheService {
|
|
|
4476
5094
|
if (this.opts.redisClient && typeof this.opts.redisClient.duplicate === "function") {
|
|
4477
5095
|
return this.opts.redisClient.duplicate();
|
|
4478
5096
|
}
|
|
5097
|
+
if (this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel) {
|
|
5098
|
+
throw new Error("Invalidation backplane requires redisSubClient or a driver supporting duplicate()");
|
|
5099
|
+
}
|
|
4479
5100
|
if (this.opts.redisClusterNodes?.length) {
|
|
4480
5101
|
return new RedisCluster(this.opts.redisClusterNodes, {
|
|
4481
5102
|
redisOptions: {
|
|
4482
5103
|
tls: this.opts.redisTls ? {} : void 0,
|
|
4483
5104
|
connectTimeout: 1e4,
|
|
5105
|
+
commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
|
|
4484
5106
|
maxRetriesPerRequest: null,
|
|
4485
5107
|
...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
|
|
4486
5108
|
}
|
|
@@ -4491,6 +5113,7 @@ var CacheService = class _CacheService {
|
|
|
4491
5113
|
name: this.opts.redisSentinel.name,
|
|
4492
5114
|
tls: this.opts.redisTls ? {} : void 0,
|
|
4493
5115
|
connectTimeout: 1e4,
|
|
5116
|
+
commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
|
|
4494
5117
|
lazyConnect: true,
|
|
4495
5118
|
maxRetriesPerRequest: null,
|
|
4496
5119
|
enableAutoPipelining: false,
|
|
@@ -4503,6 +5126,7 @@ var CacheService = class _CacheService {
|
|
|
4503
5126
|
port: this.opts.redisPort,
|
|
4504
5127
|
tls: this.opts.redisTls ? {} : void 0,
|
|
4505
5128
|
connectTimeout: 1e4,
|
|
5129
|
+
commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
|
|
4506
5130
|
lazyConnect: true,
|
|
4507
5131
|
maxRetriesPerRequest: null,
|
|
4508
5132
|
enableAutoPipelining: false,
|
|
@@ -4512,26 +5136,32 @@ var CacheService = class _CacheService {
|
|
|
4512
5136
|
});
|
|
4513
5137
|
}
|
|
4514
5138
|
}
|
|
4515
|
-
|
|
5139
|
+
_listenBackplane(client, event, listener) {
|
|
5140
|
+
client.on?.(event, listener);
|
|
5141
|
+
this._backplaneDisposers.push(() => client.removeListener?.(event, listener));
|
|
5142
|
+
}
|
|
5143
|
+
async initBackplane() {
|
|
4516
5144
|
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
4517
5145
|
if (this.opts.backplaneMode === "stream") {
|
|
4518
5146
|
if (this.streamClient) return;
|
|
4519
|
-
|
|
5147
|
+
await this._startStreamConsumer();
|
|
4520
5148
|
return;
|
|
4521
5149
|
}
|
|
4522
5150
|
if (this.subClient) return;
|
|
4523
5151
|
const sub = this.createDedicatedRedisClient();
|
|
4524
|
-
|
|
5152
|
+
this.subClient = sub;
|
|
5153
|
+
this._listenBackplane(sub, "error", (e) => {
|
|
4525
5154
|
this._checkAndLogResp3Hint(e);
|
|
4526
5155
|
this.logger.debug("Backplane subscriber error", { error: e.message });
|
|
4527
5156
|
});
|
|
4528
|
-
|
|
5157
|
+
this._listenBackplane(sub, "close", () => {
|
|
5158
|
+
this._backplaneAvailable = false;
|
|
4529
5159
|
if (this._subDisconnectedAt === null) {
|
|
4530
5160
|
this._subDisconnectedAt = Date.now();
|
|
4531
5161
|
this.logger.debug("Backplane: subscriber disconnected", { at: this._subDisconnectedAt });
|
|
4532
5162
|
}
|
|
4533
5163
|
});
|
|
4534
|
-
|
|
5164
|
+
this._listenBackplane(sub, "ready", () => {
|
|
4535
5165
|
if (this._subDisconnectedAt !== null && this.opts.backplaneMaxStalenessMs > 0) {
|
|
4536
5166
|
const gapMs = Date.now() - this._subDisconnectedAt;
|
|
4537
5167
|
if (gapMs > this.opts.backplaneMaxStalenessMs) {
|
|
@@ -4544,52 +5174,119 @@ var CacheService = class _CacheService {
|
|
|
4544
5174
|
}
|
|
4545
5175
|
this._subDisconnectedAt = null;
|
|
4546
5176
|
}
|
|
5177
|
+
if (!this._destroyed) this._backplaneAvailable = true;
|
|
4547
5178
|
});
|
|
4548
5179
|
const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
|
|
4549
5180
|
if (isClusterSharded) {
|
|
4550
|
-
|
|
5181
|
+
this._listenBackplane(sub, "smessage", (_channel, message) => {
|
|
4551
5182
|
this._handleBackplaneMessage(message);
|
|
4552
5183
|
});
|
|
4553
|
-
sub.
|
|
5184
|
+
if (typeof sub.connect === "function" && (sub.isOpen === false || sub.status === "wait")) await sub.connect();
|
|
5185
|
+
await sub.ssubscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: sharded subscribed", {
|
|
4554
5186
|
channel: this.backplaneChannel,
|
|
4555
5187
|
instanceId: this.instanceId
|
|
4556
|
-
})).catch((err) => this.logger.warn("Backplane: sharded subscribe failed", {
|
|
4557
|
-
error: err.message
|
|
4558
5188
|
}));
|
|
4559
5189
|
} else {
|
|
4560
|
-
|
|
5190
|
+
this._listenBackplane(sub, "message", (_channel, message) => {
|
|
4561
5191
|
this._handleBackplaneMessage(message);
|
|
4562
5192
|
});
|
|
4563
|
-
sub.
|
|
5193
|
+
if (typeof sub.connect === "function" && (sub.isOpen === false || sub.status === "wait")) await sub.connect();
|
|
5194
|
+
if (this._destroyed) return;
|
|
5195
|
+
await sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
|
|
4564
5196
|
channel: this.backplaneChannel,
|
|
4565
5197
|
instanceId: this.instanceId
|
|
4566
|
-
})).catch((err) => this.logger.warn("Backplane: subscribe failed", {
|
|
4567
|
-
error: err.message
|
|
4568
5198
|
}));
|
|
4569
5199
|
}
|
|
4570
|
-
this.
|
|
5200
|
+
if (!this._destroyed) this._backplaneAvailable = true;
|
|
5201
|
+
}
|
|
5202
|
+
_resetAfterStreamGap() {
|
|
5203
|
+
this.counters.streamGaps++;
|
|
5204
|
+
this._fenceInvalidation();
|
|
5205
|
+
this.l1.clear();
|
|
5206
|
+
this.tagIndex.clear();
|
|
5207
|
+
this.keyTags.clear();
|
|
5208
|
+
this.tagVersions.clear();
|
|
5209
|
+
this.dependencyIndex.clear();
|
|
5210
|
+
this.keyDependencies.clear();
|
|
5211
|
+
this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, Date.now());
|
|
5212
|
+
this._addPatternTombstone(this.nk("*"));
|
|
5213
|
+
this._lastStreamId = "0-0";
|
|
4571
5214
|
}
|
|
4572
5215
|
async _startStreamConsumer() {
|
|
5216
|
+
this._streamRecovering ||= this._lastStreamId !== "$" && this._lastStreamId !== "0-0";
|
|
4573
5217
|
const sub = this.streamClient ?? this.createDedicatedRedisClient();
|
|
4574
5218
|
this.streamClient = sub;
|
|
5219
|
+
if (typeof sub.xread !== "function") throw new Error("backplaneMode: stream requires a driver supporting XREAD");
|
|
4575
5220
|
if (typeof sub.on === "function") {
|
|
4576
|
-
|
|
4577
|
-
|
|
5221
|
+
this._listenBackplane(sub, "error", (e) => this.logger.debug("Backplane stream consumer error", { error: e.message }));
|
|
5222
|
+
this._listenBackplane(sub, "close", () => {
|
|
5223
|
+
this._streamRecovering = true;
|
|
5224
|
+
this._backplaneAvailable = false;
|
|
4578
5225
|
if (this._subDisconnectedAt === null) {
|
|
4579
5226
|
this._subDisconnectedAt = Date.now();
|
|
4580
5227
|
this.logger.debug("Backplane stream: consumer disconnected", { at: this._subDisconnectedAt });
|
|
4581
5228
|
}
|
|
4582
5229
|
});
|
|
4583
|
-
|
|
5230
|
+
this._listenBackplane(sub, "ready", () => {
|
|
4584
5231
|
if (this._subDisconnectedAt !== null) {
|
|
4585
5232
|
this.logger.debug("Backplane stream: consumer reconnected, resuming stream read", { lastId: this._lastStreamId });
|
|
4586
5233
|
this._subDisconnectedAt = null;
|
|
4587
5234
|
}
|
|
4588
5235
|
});
|
|
4589
5236
|
}
|
|
5237
|
+
const checkGap = async () => {
|
|
5238
|
+
if (this._lastStreamId === "$" || this._lastStreamId === "0-0" || typeof sub.xrange !== "function") return;
|
|
5239
|
+
const first = await sub.xrange(this.backplaneStreamKey, "-", "+", "COUNT", 1);
|
|
5240
|
+
const firstId = first?.[0]?.[0];
|
|
5241
|
+
if (!firstId) return;
|
|
5242
|
+
const [firstMs, firstSequence] = firstId.split("-").map(BigInt);
|
|
5243
|
+
const [lastMs, lastSequence] = this._lastStreamId.split("-").map(BigInt);
|
|
5244
|
+
if (firstMs > lastMs || firstMs === lastMs && firstSequence > lastSequence) this._resetAfterStreamGap();
|
|
5245
|
+
};
|
|
5246
|
+
const apply = (response) => {
|
|
5247
|
+
if (this._destroyed || !response) return;
|
|
5248
|
+
if (this._streamRecovering && response.some(([, entries]) => entries.length > 0)) {
|
|
5249
|
+
this.counters.streamReplays++;
|
|
5250
|
+
this._streamRecovering = false;
|
|
5251
|
+
}
|
|
5252
|
+
for (const [, entries] of response) {
|
|
5253
|
+
for (const [id, fields] of entries) {
|
|
5254
|
+
this._lastStreamId = id;
|
|
5255
|
+
this.counters.streamEntriesReceived++;
|
|
5256
|
+
this._processStreamEntry(fields);
|
|
5257
|
+
}
|
|
5258
|
+
}
|
|
5259
|
+
};
|
|
5260
|
+
let initialized = false;
|
|
5261
|
+
const initialize = async () => {
|
|
5262
|
+
if (typeof sub.connect === "function" && (sub.isOpen === false || sub.status === "wait")) await sub.connect();
|
|
5263
|
+
if (this._destroyed) return;
|
|
5264
|
+
if (this._lastStreamId === "$") {
|
|
5265
|
+
if (this._restoredSnapshot) this._resetAfterStreamGap();
|
|
5266
|
+
else if (typeof sub.xrevrange === "function") {
|
|
5267
|
+
const latest = await sub.xrevrange(this.backplaneStreamKey, "+", "-", "COUNT", 1);
|
|
5268
|
+
this._lastStreamId = latest?.[0]?.[0] ?? "0-0";
|
|
5269
|
+
} else this._lastStreamId = "0-0";
|
|
5270
|
+
}
|
|
5271
|
+
if (typeof sub.xrange === "function") {
|
|
5272
|
+
await checkGap();
|
|
5273
|
+
apply(await sub.xread("STREAMS", this.backplaneStreamKey, this._lastStreamId));
|
|
5274
|
+
}
|
|
5275
|
+
initialized = true;
|
|
5276
|
+
this._backplaneAvailable = true;
|
|
5277
|
+
};
|
|
5278
|
+
try {
|
|
5279
|
+
await initialize();
|
|
5280
|
+
} catch (error) {
|
|
5281
|
+
this._backplaneAvailable = false;
|
|
5282
|
+
this.logger.warn("Backplane stream initialization failed; retrying in consumer loop", { error: error.message });
|
|
5283
|
+
}
|
|
4590
5284
|
const runLoop = async () => {
|
|
4591
5285
|
while (!this._destroyed && !this._redisDisabled) {
|
|
4592
5286
|
try {
|
|
5287
|
+
if (!initialized) await initialize();
|
|
5288
|
+
if (this._destroyed) break;
|
|
5289
|
+
await checkGap();
|
|
4593
5290
|
const res = await sub.xread(
|
|
4594
5291
|
"BLOCK",
|
|
4595
5292
|
this.opts.backplaneStreamBlockMs,
|
|
@@ -4598,19 +5295,10 @@ var CacheService = class _CacheService {
|
|
|
4598
5295
|
this._lastStreamId
|
|
4599
5296
|
);
|
|
4600
5297
|
if (this._destroyed) break;
|
|
5298
|
+
this._backplaneAvailable = true;
|
|
4601
5299
|
if (res && res.length > 0) {
|
|
4602
|
-
|
|
4603
|
-
|
|
4604
|
-
if (this._lastStreamId !== "$") {
|
|
4605
|
-
this.counters.streamReplays++;
|
|
4606
|
-
}
|
|
4607
|
-
for (const [id, fields] of entries) {
|
|
4608
|
-
this._lastStreamId = id;
|
|
4609
|
-
this.counters.streamEntriesReceived++;
|
|
4610
|
-
this._processStreamEntry(fields);
|
|
4611
|
-
}
|
|
4612
|
-
}
|
|
4613
|
-
}
|
|
5300
|
+
apply(res);
|
|
5301
|
+
this._backplaneAvailable = true;
|
|
4614
5302
|
} else {
|
|
4615
5303
|
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
4616
5304
|
}
|
|
@@ -4618,10 +5306,9 @@ var CacheService = class _CacheService {
|
|
|
4618
5306
|
if (this._destroyed) break;
|
|
4619
5307
|
const msg = err.message ?? "";
|
|
4620
5308
|
if (msg.includes("NOGROUP") || msg.includes("smaller than") || msg.includes("trimmed")) {
|
|
4621
|
-
this.
|
|
4622
|
-
this.l1.clear();
|
|
4623
|
-
this._lastStreamId = "$";
|
|
5309
|
+
this._resetAfterStreamGap();
|
|
4624
5310
|
}
|
|
5311
|
+
this._backplaneAvailable = false;
|
|
4625
5312
|
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
4626
5313
|
}
|
|
4627
5314
|
}
|
|
@@ -4650,7 +5337,7 @@ var CacheService = class _CacheService {
|
|
|
4650
5337
|
else if (f === "tagVersion") tagVersionRaw = v;
|
|
4651
5338
|
}
|
|
4652
5339
|
const validOp = op === "del" || op === "del-glob" || op === "tag_incr" || op === "tag_pattern_incr" || op === "tag_pattern_del";
|
|
4653
|
-
if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
|
|
5340
|
+
if (!validOp || typeof key !== "string" || !key || typeof src !== "string" || !src || (op === "del" || op === "del-glob") && this._namespace && !key.startsWith(`${this._namespace}:`)) {
|
|
4654
5341
|
this.logger.warn("Backplane: rejected invalid stream entry", {
|
|
4655
5342
|
op: String(op).slice(0, 40),
|
|
4656
5343
|
key: typeof key === "string" ? key.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(key)
|
|
@@ -4659,8 +5346,8 @@ var CacheService = class _CacheService {
|
|
|
4659
5346
|
}
|
|
4660
5347
|
let tagVersion;
|
|
4661
5348
|
if (tagVersionRaw !== void 0) {
|
|
4662
|
-
const parsed =
|
|
4663
|
-
if (!Number.
|
|
5349
|
+
const parsed = Number(tagVersionRaw);
|
|
5350
|
+
if (!Number.isSafeInteger(parsed) || parsed < 0) {
|
|
4664
5351
|
this.logger.warn("Backplane: rejected stream entry with non-numeric tagVersion", { key });
|
|
4665
5352
|
return;
|
|
4666
5353
|
}
|
|
@@ -4678,16 +5365,10 @@ var CacheService = class _CacheService {
|
|
|
4678
5365
|
this.l1.delete(key);
|
|
4679
5366
|
this._bumpKeyMutation(key);
|
|
4680
5367
|
this.inflight.delete(key);
|
|
4681
|
-
this.
|
|
4682
|
-
setImmediate(() => {
|
|
4683
|
-
try {
|
|
4684
|
-
if (!this._diskDisabled) this.disk.delete(key);
|
|
4685
|
-
} finally {
|
|
4686
|
-
this._pendingDiskDeletes.delete(key);
|
|
4687
|
-
}
|
|
4688
|
-
});
|
|
5368
|
+
this._invalidateDiskKey(key);
|
|
4689
5369
|
this._cascadeDependencies(key);
|
|
4690
5370
|
} else if (op === "del-glob") {
|
|
5371
|
+
this._fenceInvalidation();
|
|
4691
5372
|
this.l1.deletePattern(key);
|
|
4692
5373
|
const pfx = key.endsWith("*") ? key.slice(0, -1) : key;
|
|
4693
5374
|
for (const liveKey of this.l1.liveKeys()) {
|
|
@@ -4701,12 +5382,22 @@ var CacheService = class _CacheService {
|
|
|
4701
5382
|
this.inflight.delete(inflightKey);
|
|
4702
5383
|
}
|
|
4703
5384
|
}
|
|
4704
|
-
this._addPatternTombstone(
|
|
5385
|
+
this._addPatternTombstone(key);
|
|
5386
|
+
this._removePatternFromIndices(key);
|
|
5387
|
+
if (key === this.nk("*")) {
|
|
5388
|
+
this.tagIndex.clear();
|
|
5389
|
+
this.keyTags.clear();
|
|
5390
|
+
this.tagVersions.clear();
|
|
5391
|
+
this.dependencyIndex.clear();
|
|
5392
|
+
this.keyDependencies.clear();
|
|
5393
|
+
}
|
|
4705
5394
|
} else if (op === "tag_incr") {
|
|
5395
|
+
this._fenceInvalidation();
|
|
4706
5396
|
const tag = key;
|
|
4707
5397
|
const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
4708
5398
|
this._setLocalTagVersion(tag, ver, performance.now());
|
|
4709
5399
|
} else if (op === "tag_pattern_incr") {
|
|
5400
|
+
this._fenceInvalidation();
|
|
4710
5401
|
const pattern = key;
|
|
4711
5402
|
const now = performance.now();
|
|
4712
5403
|
for (const [tag, info] of this.tagVersions) {
|
|
@@ -4726,6 +5417,7 @@ var CacheService = class _CacheService {
|
|
|
4726
5417
|
}
|
|
4727
5418
|
}, 0);
|
|
4728
5419
|
} else if (op === "tag_pattern_del") {
|
|
5420
|
+
this._fenceInvalidation();
|
|
4729
5421
|
const pattern = key;
|
|
4730
5422
|
const matchedTagKeys = [];
|
|
4731
5423
|
const prefix = this.nk("_tag_:");
|
|
@@ -4736,14 +5428,7 @@ var CacheService = class _CacheService {
|
|
|
4736
5428
|
for (const k of members) {
|
|
4737
5429
|
this.l1.delete(k);
|
|
4738
5430
|
this._bumpKeyMutation(k);
|
|
4739
|
-
this.
|
|
4740
|
-
setImmediate(() => {
|
|
4741
|
-
try {
|
|
4742
|
-
if (!this._diskDisabled) this.disk.delete(k);
|
|
4743
|
-
} finally {
|
|
4744
|
-
this._pendingDiskDeletes.delete(k);
|
|
4745
|
-
}
|
|
4746
|
-
});
|
|
5431
|
+
this._invalidateDiskKey(k);
|
|
4747
5432
|
}
|
|
4748
5433
|
}
|
|
4749
5434
|
}
|
|
@@ -4774,6 +5459,7 @@ var CacheService = class _CacheService {
|
|
|
4774
5459
|
}
|
|
4775
5460
|
}
|
|
4776
5461
|
async publishInvalidation(op, key, tagVersion, isCrossRegionRelay = false, isExplicitInvalidation = false) {
|
|
5462
|
+
if (this.opts.l2WriteMode === "read-only") return;
|
|
4777
5463
|
if (!isCrossRegionRelay && this.opts.crossRegion) {
|
|
4778
5464
|
const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
|
|
4779
5465
|
if (shouldBroadcast) {
|
|
@@ -4856,13 +5542,13 @@ var CacheService = class _CacheService {
|
|
|
4856
5542
|
timestamp: Date.now(),
|
|
4857
5543
|
namespace: this._namespace || void 0
|
|
4858
5544
|
};
|
|
4859
|
-
this.counters.crossRegionSent++;
|
|
4860
5545
|
await cr.relay.broadcast(event);
|
|
5546
|
+
this.counters.crossRegionSent++;
|
|
4861
5547
|
this.logger.debug("Cross-region invalidation broadcast", { op, key, region: cr.currentRegion });
|
|
4862
5548
|
} catch (err) {
|
|
4863
|
-
this.counters.crossRegionSent = Math.max(0, this.counters.crossRegionSent - 1);
|
|
4864
5549
|
this.counters.crossRegionErrors++;
|
|
4865
5550
|
this.logger.warn("Cross-region invalidation broadcast failed", { error: err.message });
|
|
5551
|
+
if (this.opts.awaitInvalidationBackplane) throw err;
|
|
4866
5552
|
}
|
|
4867
5553
|
}
|
|
4868
5554
|
/**
|
|
@@ -4873,11 +5559,12 @@ var CacheService = class _CacheService {
|
|
|
4873
5559
|
* Returns true if the event was accepted and applied, or false if ignored/deduplicated.
|
|
4874
5560
|
*/
|
|
4875
5561
|
async receiveCrossRegionInvalidation(event) {
|
|
5562
|
+
this._assertActive("receiveCrossRegionInvalidation");
|
|
4876
5563
|
const cr = this.opts.crossRegion;
|
|
4877
5564
|
if (!cr) return false;
|
|
4878
|
-
if (!event
|
|
5565
|
+
if (!isCrossRegionInvalidationEvent(event)) {
|
|
4879
5566
|
this.counters.crossRegionErrors++;
|
|
4880
|
-
this.logger.warn("Cross-region: rejected invalid event payload"
|
|
5567
|
+
this.logger.warn("Cross-region: rejected invalid event payload");
|
|
4881
5568
|
return false;
|
|
4882
5569
|
}
|
|
4883
5570
|
if (event.originRegion === cr.currentRegion) {
|
|
@@ -4888,13 +5575,52 @@ var CacheService = class _CacheService {
|
|
|
4888
5575
|
this.counters.crossRegionDeduplicated++;
|
|
4889
5576
|
return false;
|
|
4890
5577
|
}
|
|
4891
|
-
this._markCrossRegionEventSeen(event.id);
|
|
4892
5578
|
if (event.namespace !== void 0 && event.namespace !== (this._namespace || void 0)) {
|
|
4893
5579
|
return false;
|
|
4894
5580
|
}
|
|
5581
|
+
if ((event.op === "del" || event.op === "del-glob") && this._namespace && !event.key.startsWith(`${this._namespace}:`)) return false;
|
|
5582
|
+
this._markCrossRegionEventSeen(event.id);
|
|
4895
5583
|
this.counters.crossRegionReceived++;
|
|
4896
|
-
this.
|
|
4897
|
-
|
|
5584
|
+
const localTags = /* @__PURE__ */ new Set([...this.tagVersions.keys(), ...[...this.tagIndex.keys()].map((key) => this.unnk(key).replace(/^_tag_:/, ""))]);
|
|
5585
|
+
let version = event.tagVersion;
|
|
5586
|
+
if (event.op === "tag_incr") version = Math.max((this.tagVersions.get(event.key)?.version ?? 0) + 1, version ?? 0);
|
|
5587
|
+
this._applyInvalidationEvent(event.op, event.key, version);
|
|
5588
|
+
try {
|
|
5589
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5590
|
+
const client = await this.getRedis();
|
|
5591
|
+
if (event.op === "del" || event.op === "del-glob") {
|
|
5592
|
+
await this._deleteRedisKeys(client, event.op === "del" ? [event.key] : await this._scanKeys(client, event.key));
|
|
5593
|
+
} else if (event.op === "tag_incr") {
|
|
5594
|
+
version = Number(await client.eval(LUA_RECEIVE_TAG_VERSION, 1, this.nk(`tag_ver:${event.key}`), String(version)));
|
|
5595
|
+
this._setLocalTagVersion(event.key, version);
|
|
5596
|
+
} else {
|
|
5597
|
+
const matched = await this._resolveMatchingTags(event.key, false);
|
|
5598
|
+
for (const tag of localTags) if (matchesTagPattern(event.key, tag)) matched.add(tag);
|
|
5599
|
+
for (const tag of matched) {
|
|
5600
|
+
if (event.op === "tag_pattern_incr") {
|
|
5601
|
+
const floor = this.tagVersions.get(tag)?.version ?? 1;
|
|
5602
|
+
const next = Number(await client.eval(LUA_RECEIVE_TAG_VERSION, 1, this.nk(`tag_ver:${tag}`), String(floor)));
|
|
5603
|
+
this._setLocalTagVersion(tag, next);
|
|
5604
|
+
await this.publishInvalidation("tag_incr", tag, next, true);
|
|
5605
|
+
} else {
|
|
5606
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
5607
|
+
const members = await client.smembers(tagKey);
|
|
5608
|
+
this._removeTagMembersLocal(members);
|
|
5609
|
+
await this._deleteRedisKeys(client, [...members, tagKey]);
|
|
5610
|
+
await Promise.all(members.map((key) => this.publishInvalidation("del", key, void 0, true)));
|
|
5611
|
+
}
|
|
5612
|
+
}
|
|
5613
|
+
}
|
|
5614
|
+
this.cb.onSuccess();
|
|
5615
|
+
}
|
|
5616
|
+
await this.publishInvalidation(event.op, event.key, version, true);
|
|
5617
|
+
} catch (error) {
|
|
5618
|
+
this._seenCrossRegionEvents.delete(event.id);
|
|
5619
|
+
this.counters.crossRegionErrors++;
|
|
5620
|
+
this.logger.warn("Cross-region regional invalidation failed", { error: error.message });
|
|
5621
|
+
if (this.opts.awaitInvalidationBackplane) throw error;
|
|
5622
|
+
return false;
|
|
5623
|
+
}
|
|
4898
5624
|
this.logger.info("Cross-region invalidation applied", {
|
|
4899
5625
|
op: event.op,
|
|
4900
5626
|
key: event.key,
|
|
@@ -4909,10 +5635,10 @@ var CacheService = class _CacheService {
|
|
|
4909
5635
|
const oldestKey = this.tagVersions.keys().next().value;
|
|
4910
5636
|
if (oldestKey !== void 0) this.tagVersions.delete(oldestKey);
|
|
4911
5637
|
}
|
|
4912
|
-
this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
|
|
5638
|
+
this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now, refreshEpoch: this._tagRefreshEpoch });
|
|
4913
5639
|
}
|
|
4914
5640
|
async _isGenerationalEntryStale(tagVersions) {
|
|
4915
|
-
if (
|
|
5641
|
+
if (!tagVersions) return false;
|
|
4916
5642
|
const tags = Object.keys(tagVersions);
|
|
4917
5643
|
if (tags.length === 0) return false;
|
|
4918
5644
|
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
@@ -4925,12 +5651,22 @@ var CacheService = class _CacheService {
|
|
|
4925
5651
|
if (keys.length === 0) return;
|
|
4926
5652
|
const CHUNK_SIZE = 1e3;
|
|
4927
5653
|
if (client instanceof RedisCluster) {
|
|
4928
|
-
|
|
4929
|
-
|
|
4930
|
-
const
|
|
4931
|
-
|
|
4932
|
-
|
|
4933
|
-
|
|
5654
|
+
const groups = /* @__PURE__ */ new Map();
|
|
5655
|
+
for (const key of keys) {
|
|
5656
|
+
const slot = redisHashSlot(key);
|
|
5657
|
+
const master = client.slots?.[slot]?.[0] ?? String(slot);
|
|
5658
|
+
const members = groups.get(master) ?? [];
|
|
5659
|
+
members.push(key);
|
|
5660
|
+
groups.set(master, members);
|
|
5661
|
+
}
|
|
5662
|
+
await Promise.all([...groups.values()].map(async (members) => {
|
|
5663
|
+
for (let offset = 0; offset < members.length; offset += CHUNK_SIZE) {
|
|
5664
|
+
const pipeline = client.pipeline();
|
|
5665
|
+
for (const key of members.slice(offset, offset + CHUNK_SIZE)) pipeline.del(key);
|
|
5666
|
+
const result = await pipeline.exec();
|
|
5667
|
+
if (!result || result.some(([error]) => error)) throw new Error("Redis Cluster delete failed");
|
|
5668
|
+
}
|
|
5669
|
+
}));
|
|
4934
5670
|
return;
|
|
4935
5671
|
}
|
|
4936
5672
|
for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
|
|
@@ -4943,8 +5679,11 @@ var CacheService = class _CacheService {
|
|
|
4943
5679
|
let storedTagVersions = {};
|
|
4944
5680
|
if (hashData.tv) {
|
|
4945
5681
|
try {
|
|
4946
|
-
|
|
5682
|
+
const parsed = JSON.parse(hashData.tv);
|
|
5683
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || Object.values(parsed).some((version) => !Number.isSafeInteger(version) || Number(version) < 0)) return null;
|
|
5684
|
+
storedTagVersions = parsed;
|
|
4947
5685
|
} catch {
|
|
5686
|
+
return null;
|
|
4948
5687
|
}
|
|
4949
5688
|
}
|
|
4950
5689
|
if (await this._isGenerationalEntryStale(storedTagVersions)) {
|
|
@@ -4953,18 +5692,48 @@ var CacheService = class _CacheService {
|
|
|
4953
5692
|
return { stale: true };
|
|
4954
5693
|
}
|
|
4955
5694
|
const value = await this._decryptAndDeserialize(hashData.d);
|
|
4956
|
-
|
|
5695
|
+
const expiresAt = Number(hashData.e);
|
|
5696
|
+
const staleAt = Number(hashData.s);
|
|
5697
|
+
let tags;
|
|
5698
|
+
let dependsOn;
|
|
5699
|
+
try {
|
|
5700
|
+
const parsedTags = hashData.tags ? JSON.parse(hashData.tags) : Object.keys(storedTagVersions);
|
|
5701
|
+
const parsedDependencies = hashData.deps ? JSON.parse(hashData.deps) : void 0;
|
|
5702
|
+
if (Array.isArray(parsedTags) && parsedTags.every((tag) => typeof tag === "string")) tags = parsedTags;
|
|
5703
|
+
if (Array.isArray(parsedDependencies) && parsedDependencies.every((pattern) => typeof pattern === "string")) dependsOn = parsedDependencies;
|
|
5704
|
+
} catch {
|
|
5705
|
+
return null;
|
|
5706
|
+
}
|
|
5707
|
+
return {
|
|
5708
|
+
value,
|
|
5709
|
+
tagVersions: storedTagVersions,
|
|
5710
|
+
stale: false,
|
|
5711
|
+
tags,
|
|
5712
|
+
dependsOn,
|
|
5713
|
+
setAt: Number(hashData.t) || void 0,
|
|
5714
|
+
expiresAt: Number.isFinite(expiresAt) && expiresAt > 0 ? expiresAt : void 0,
|
|
5715
|
+
staleAt: Number.isFinite(staleAt) && staleAt > 0 ? staleAt : void 0
|
|
5716
|
+
};
|
|
4957
5717
|
}
|
|
4958
5718
|
async _readRedisEntry(client, k, allowAutoPipeline = false) {
|
|
5719
|
+
const readStartedAt = Date.now();
|
|
5720
|
+
const read = async (hash) => allowAutoPipeline && this.opts.autoPipeline && this.pipeliner ? this.pipeliner.read(k, hash) : readRedisValue(client, k, hash);
|
|
5721
|
+
const withExpiry = (entry, ttlMs2) => {
|
|
5722
|
+
if (!entry || ttlMs2 === -2 || ttlMs2 === 0) return null;
|
|
5723
|
+
if (ttlMs2 !== void 0 && Number.isFinite(ttlMs2) && ttlMs2 > 0) {
|
|
5724
|
+
entry.expiresAt = Math.min(entry.expiresAt ?? Infinity, readStartedAt + ttlMs2);
|
|
5725
|
+
}
|
|
5726
|
+
return entry.expiresAt !== void 0 && entry.expiresAt <= Date.now() ? null : entry;
|
|
5727
|
+
};
|
|
4959
5728
|
if (this.opts.tagStrategy === "generational" && typeof client.hgetall === "function") {
|
|
4960
5729
|
try {
|
|
4961
|
-
const hashData = await
|
|
5730
|
+
const { raw: hashData, ttlMs: ttlMs2 } = await read(true);
|
|
4962
5731
|
if (typeof hashData === "string") {
|
|
4963
5732
|
const value2 = await this._decryptAndDeserialize(hashData);
|
|
4964
|
-
return { value: value2, stale: false };
|
|
5733
|
+
return withExpiry({ value: value2, stale: false }, ttlMs2);
|
|
4965
5734
|
}
|
|
4966
5735
|
if (hashData && hashData.d) {
|
|
4967
|
-
return await this._parseGenerationalRedisHash(k, hashData);
|
|
5736
|
+
return withExpiry(await this._parseGenerationalRedisHash(k, hashData), ttlMs2);
|
|
4968
5737
|
}
|
|
4969
5738
|
return null;
|
|
4970
5739
|
} catch (err) {
|
|
@@ -4972,28 +5741,163 @@ var CacheService = class _CacheService {
|
|
|
4972
5741
|
if (!msg.includes("WRONGTYPE")) throw err;
|
|
4973
5742
|
}
|
|
4974
5743
|
}
|
|
4975
|
-
const raw
|
|
5744
|
+
const { raw, ttlMs } = await read(false);
|
|
4976
5745
|
if (raw == null) return null;
|
|
5746
|
+
if (typeof raw !== "string") return null;
|
|
4977
5747
|
const value = await this._decryptAndDeserialize(raw);
|
|
4978
|
-
return { value, stale: false };
|
|
5748
|
+
return withExpiry({ value, stale: false }, ttlMs);
|
|
4979
5749
|
}
|
|
4980
5750
|
async _getTagVersion(tag) {
|
|
4981
5751
|
const now = performance.now();
|
|
4982
5752
|
const local = this.tagVersions.get(tag);
|
|
4983
|
-
if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
|
|
5753
|
+
if (local && (local.refreshEpoch ?? 0) === this._tagRefreshEpoch && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
|
|
4984
5754
|
return local.version;
|
|
4985
5755
|
}
|
|
4986
5756
|
if (!this._redisDisabled) {
|
|
4987
5757
|
try {
|
|
4988
5758
|
const client = await this.getRedis();
|
|
4989
5759
|
const raw = await client.get(this.nk(`tag_ver:${tag}`));
|
|
4990
|
-
const
|
|
4991
|
-
|
|
4992
|
-
|
|
5760
|
+
const parsed = raw ? Number(raw) : 0;
|
|
5761
|
+
if (!Number.isSafeInteger(parsed) || parsed < 0) throw new Error("Invalid Redis tag generation");
|
|
5762
|
+
const version2 = Math.max(this.tagVersions.get(tag)?.version ?? 0, parsed);
|
|
5763
|
+
if (this.opts.l2WriteMode === "read-write") {
|
|
5764
|
+
if (raw === null) await client.set(this.nk(`tag_ver:${tag}`), String(version2), "NX");
|
|
5765
|
+
else if (version2 > parsed) await client.eval(LUA_MAX_TAG_VERSION, 1, this.nk(`tag_ver:${tag}`), String(version2));
|
|
5766
|
+
}
|
|
5767
|
+
this._setLocalTagVersion(tag, version2, now);
|
|
5768
|
+
this.cb.onSuccess();
|
|
5769
|
+
return version2;
|
|
4993
5770
|
} catch {
|
|
4994
5771
|
}
|
|
4995
5772
|
}
|
|
4996
|
-
|
|
5773
|
+
const version = this.tagVersions.get(tag)?.version ?? local?.version ?? 0;
|
|
5774
|
+
if (this._redisDisabled) this._setLocalTagVersion(tag, version, now);
|
|
5775
|
+
return version;
|
|
5776
|
+
}
|
|
5777
|
+
async _readRedisBatch(client, keys) {
|
|
5778
|
+
const entries = /* @__PURE__ */ new Map();
|
|
5779
|
+
const groups = /* @__PURE__ */ new Map();
|
|
5780
|
+
for (const key of new Set(keys)) {
|
|
5781
|
+
const group = client instanceof RedisCluster ? client.slots[redisHashSlot(key)]?.[0] ?? String(redisHashSlot(key)) : "single";
|
|
5782
|
+
const members = groups.get(group) ?? [];
|
|
5783
|
+
members.push(key);
|
|
5784
|
+
groups.set(group, members);
|
|
5785
|
+
}
|
|
5786
|
+
await Promise.all([...groups.values()].map(async (members) => {
|
|
5787
|
+
for (let offset = 0; offset < members.length; offset += 1e3) {
|
|
5788
|
+
const chunk = members.slice(offset, offset + 1e3);
|
|
5789
|
+
const pipeline = typeof client.pipeline === "function" ? client.pipeline() : client.multi();
|
|
5790
|
+
const timedScripts = typeof pipeline.eval === "function";
|
|
5791
|
+
const hashes = this.opts.tagStrategy === "generational" && typeof pipeline.hgetall === "function";
|
|
5792
|
+
for (const key of chunk) {
|
|
5793
|
+
if (timedScripts) pipeline.eval(LUA_READ_CACHE_ENTRY, 1, key);
|
|
5794
|
+
else if (hashes) pipeline.hgetall(key);
|
|
5795
|
+
else pipeline.get(key);
|
|
5796
|
+
}
|
|
5797
|
+
const startedAt = Date.now();
|
|
5798
|
+
const start = performance.now();
|
|
5799
|
+
const results = await pipeline.exec();
|
|
5800
|
+
this.watchdog.recordRedis(performance.now() - start);
|
|
5801
|
+
if (!results) throw new Error("Redis batch read aborted");
|
|
5802
|
+
for (let index = 0; index < chunk.length; index++) {
|
|
5803
|
+
try {
|
|
5804
|
+
const tuple = results[index];
|
|
5805
|
+
if (!tuple) continue;
|
|
5806
|
+
let [error, raw] = tuple;
|
|
5807
|
+
let ttl;
|
|
5808
|
+
if (error?.message?.includes("WRONGTYPE")) {
|
|
5809
|
+
const fallback = await this._readRedisEntry(client, chunk[index]);
|
|
5810
|
+
if (fallback && !fallback.stale) entries.set(chunk[index], fallback);
|
|
5811
|
+
continue;
|
|
5812
|
+
}
|
|
5813
|
+
if (error) continue;
|
|
5814
|
+
if (timedScripts) {
|
|
5815
|
+
if (!Array.isArray(raw) || raw[0] === "none") continue;
|
|
5816
|
+
const kind = raw[0];
|
|
5817
|
+
ttl = Number(raw[2]);
|
|
5818
|
+
const payload = raw[1];
|
|
5819
|
+
if (kind === "hash") {
|
|
5820
|
+
if (!Array.isArray(payload) || payload.length % 2 !== 0) continue;
|
|
5821
|
+
raw = Object.fromEntries(Array.from({ length: payload.length / 2 }, (_unused, i) => [String(payload[i * 2]), String(payload[i * 2 + 1])]));
|
|
5822
|
+
} else if (kind === "string") raw = payload;
|
|
5823
|
+
else continue;
|
|
5824
|
+
if (ttl === -2 || ttl === 0) continue;
|
|
5825
|
+
}
|
|
5826
|
+
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;
|
|
5827
|
+
if (!entry || entry.stale) continue;
|
|
5828
|
+
if (ttl !== void 0 && ttl > 0) entry.expiresAt = Math.min(entry.expiresAt ?? Infinity, startedAt + ttl);
|
|
5829
|
+
if (entry.expiresAt !== void 0 && entry.expiresAt <= Date.now()) continue;
|
|
5830
|
+
entries.set(chunk[index], entry);
|
|
5831
|
+
} catch (error) {
|
|
5832
|
+
this.logger.debug("mget: skipping invalid remote entry", { key: chunk[index], error: error.message });
|
|
5833
|
+
}
|
|
5834
|
+
}
|
|
5835
|
+
}
|
|
5836
|
+
}));
|
|
5837
|
+
this.cb.onSuccess();
|
|
5838
|
+
return entries;
|
|
5839
|
+
}
|
|
5840
|
+
_promoteRedisEntry(key, entry, fallbackTtlMs, priority) {
|
|
5841
|
+
const expiresAt = entry.expiresAt ?? Date.now() + fallbackTtlMs;
|
|
5842
|
+
if (expiresAt <= Date.now()) return false;
|
|
5843
|
+
const admitted = this.l1.set(
|
|
5844
|
+
key,
|
|
5845
|
+
entry.value,
|
|
5846
|
+
expiresAt - Date.now(),
|
|
5847
|
+
priority,
|
|
5848
|
+
entry.staleAt,
|
|
5849
|
+
void 0,
|
|
5850
|
+
entry.tagVersions,
|
|
5851
|
+
entry.setAt,
|
|
5852
|
+
entry.tags,
|
|
5853
|
+
entry.dependsOn
|
|
5854
|
+
);
|
|
5855
|
+
if (admitted) this._restoreEntryMetadata(key, { ...entry, expiresAt });
|
|
5856
|
+
return true;
|
|
5857
|
+
}
|
|
5858
|
+
async _readDiskEntry(key, epoch) {
|
|
5859
|
+
if (this._diskDisabled || this._pendingDiskDeletes.has(key) || !this.watchdog.isDiskAllowed()) return null;
|
|
5860
|
+
const start = performance.now();
|
|
5861
|
+
const entry = this.disk.load(key);
|
|
5862
|
+
const elapsed = performance.now() - start;
|
|
5863
|
+
this.watchdog.recordDisk(elapsed);
|
|
5864
|
+
this.watchdog.onCanaryResult(entry !== null, elapsed);
|
|
5865
|
+
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;
|
|
5866
|
+
this.l1.importEntries([{ key, entry }], this.opts.forbiddenSnapshotPrefixes);
|
|
5867
|
+
const hit = this.l1.get(key);
|
|
5868
|
+
const value = hit ? hit.value : entry.isCompressed ? this.codec.decode(entry.data) : JSON.parse(entry.data);
|
|
5869
|
+
this._restoreEntryMetadata(key, entry);
|
|
5870
|
+
return { value, entry };
|
|
5871
|
+
}
|
|
5872
|
+
/** Common write policy and metadata across get/set/revalidation/draining. */
|
|
5873
|
+
async _writeRedisEntry(key, data, expiresAt, setAt, tagVersions, staleAt, tags, dependsOn, canCommit = () => true) {
|
|
5874
|
+
if (this._redisDisabled || this.opts.l2WriteMode !== "read-write" || !canCommit() || this._destroyed) return;
|
|
5875
|
+
const client = await this.getRedis();
|
|
5876
|
+
const stored = await this._serializeAndEncrypt(JSON.stringify(data) ?? "undefined");
|
|
5877
|
+
if (!canCommit() || this._destroyed) return;
|
|
5878
|
+
const useHash = this.opts.tagStrategy === "generational" && (tagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function");
|
|
5879
|
+
const remaining = (useHash ? expiresAt : staleAt ?? expiresAt) - Date.now();
|
|
5880
|
+
if (remaining <= 0) return;
|
|
5881
|
+
const ttl = Math.max(1, Math.ceil(remaining / 1e3));
|
|
5882
|
+
if (useHash) {
|
|
5883
|
+
const transaction = client.multi();
|
|
5884
|
+
transaction.del(key);
|
|
5885
|
+
const hash = { d: stored, t: String(setAt), tv: JSON.stringify(tagVersions ?? {}), e: String(expiresAt) };
|
|
5886
|
+
if (staleAt !== void 0) hash.s = String(staleAt);
|
|
5887
|
+
if (tags?.length) hash.tags = JSON.stringify(tags);
|
|
5888
|
+
if (dependsOn?.length) hash.deps = JSON.stringify(dependsOn);
|
|
5889
|
+
transaction.hset(key, hash);
|
|
5890
|
+
transaction.expire(key, ttl);
|
|
5891
|
+
const result = await transaction.exec();
|
|
5892
|
+
if (!result || result.some(([error]) => error)) throw new Error("Redis cache write transaction failed");
|
|
5893
|
+
} else if (this.opts.autoPipeline && this.pipeliner) {
|
|
5894
|
+
if (typeof client.pttl === "function" && typeof client.set === "function") await this.pipeliner.setpx(key, Math.ceil(remaining), stored);
|
|
5895
|
+
else await this.pipeliner.setex(key, ttl, stored);
|
|
5896
|
+
} else {
|
|
5897
|
+
if (typeof client.pttl === "function" && typeof client.set === "function") await client.set(key, stored, "PX", Math.ceil(remaining));
|
|
5898
|
+
else await client.setex(key, ttl, stored);
|
|
5899
|
+
}
|
|
5900
|
+
this.cb.onSuccess();
|
|
4997
5901
|
}
|
|
4998
5902
|
_deleteIfStale(k, setAtMs) {
|
|
4999
5903
|
this.l1.deleteIfSetBefore(k, setAtMs);
|
|
@@ -5046,7 +5950,7 @@ var CacheService = class _CacheService {
|
|
|
5046
5950
|
} else {
|
|
5047
5951
|
plain = raw;
|
|
5048
5952
|
}
|
|
5049
|
-
return JSON.parse(plain);
|
|
5953
|
+
return plain === "undefined" ? void 0 : JSON.parse(plain);
|
|
5050
5954
|
}
|
|
5051
5955
|
/**
|
|
5052
5956
|
* Scan all keys matching `pattern` across single-node or Cluster clients.
|
|
@@ -5249,7 +6153,12 @@ var CacheService = class _CacheService {
|
|
|
5249
6153
|
try {
|
|
5250
6154
|
const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
|
|
5251
6155
|
if (entries.length === 0) return;
|
|
5252
|
-
const payload = {
|
|
6156
|
+
const payload = {
|
|
6157
|
+
version: SNAPSHOT_VERSION,
|
|
6158
|
+
writtenAt: Date.now(),
|
|
6159
|
+
entries,
|
|
6160
|
+
streamId: this.opts.backplaneMode === "stream" && this._lastStreamId !== "$" ? this._lastStreamId : void 0
|
|
6161
|
+
};
|
|
5253
6162
|
const packed = this.codec.encode(payload);
|
|
5254
6163
|
const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
|
|
5255
6164
|
const dest = altPath ?? this.opts.snapshotPath;
|
|
@@ -5317,6 +6226,9 @@ var CacheService = class _CacheService {
|
|
|
5317
6226
|
return;
|
|
5318
6227
|
}
|
|
5319
6228
|
const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
|
|
6229
|
+
this._restoredSnapshot ||= loaded > 0;
|
|
6230
|
+
if (typeof snapshot.streamId === "string" && /^\d{1,20}-\d{1,20}$/.test(snapshot.streamId)) this._lastStreamId = snapshot.streamId;
|
|
6231
|
+
for (const { key, entry } of snapshot.entries) if (this.l1.has(key)) this._restoreEntryMetadata(key, entry);
|
|
5320
6232
|
this.logger.info("Cache snapshot loaded (L1 is warm)", {
|
|
5321
6233
|
loaded,
|
|
5322
6234
|
total: snapshot.entries.length,
|
|
@@ -5341,7 +6253,12 @@ var CacheService = class _CacheService {
|
|
|
5341
6253
|
try {
|
|
5342
6254
|
const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
|
|
5343
6255
|
if (entries.length === 0) return false;
|
|
5344
|
-
const payload = {
|
|
6256
|
+
const payload = {
|
|
6257
|
+
version: SNAPSHOT_VERSION,
|
|
6258
|
+
writtenAt: Date.now(),
|
|
6259
|
+
entries,
|
|
6260
|
+
streamId: this.opts.backplaneMode === "stream" && this._lastStreamId !== "$" ? this._lastStreamId : void 0
|
|
6261
|
+
};
|
|
5345
6262
|
const packed = this.codec.encode(payload);
|
|
5346
6263
|
let final;
|
|
5347
6264
|
if (this.opts.remoteSnapshot.envelope) {
|
|
@@ -5372,13 +6289,16 @@ var CacheService = class _CacheService {
|
|
|
5372
6289
|
async loadRemoteSnapshot() {
|
|
5373
6290
|
if (!this.opts.remoteSnapshot) return 0;
|
|
5374
6291
|
const maxAgeMs = this.opts.remoteSnapshot.maxAgeMs ?? this.opts.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE;
|
|
6292
|
+
const epoch = this._globalEpoch;
|
|
5375
6293
|
try {
|
|
5376
6294
|
const raw = await this.opts.remoteSnapshot.adapter.get();
|
|
6295
|
+
if (this._destroyed || this._globalEpoch !== epoch) return 0;
|
|
5377
6296
|
if (!raw || raw.length === 0) {
|
|
5378
6297
|
this.logger.debug("Remote snapshot not found or empty \u2014 starting cold");
|
|
5379
6298
|
return 0;
|
|
5380
6299
|
}
|
|
5381
6300
|
const rawBuf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
|
|
6301
|
+
if (rawBuf.length > SNAPSHOT_MAX_FILE_BYTES) throw new Error("Remote snapshot exceeds size limit");
|
|
5382
6302
|
let buf;
|
|
5383
6303
|
try {
|
|
5384
6304
|
if (EnvelopeEncryption.isEnvelope(rawBuf)) {
|
|
@@ -5424,7 +6344,12 @@ var CacheService = class _CacheService {
|
|
|
5424
6344
|
this.logger.warn("Remote snapshot rejected: entries is not an array");
|
|
5425
6345
|
return 0;
|
|
5426
6346
|
}
|
|
5427
|
-
|
|
6347
|
+
if (this._destroyed || this._globalEpoch !== epoch) return 0;
|
|
6348
|
+
const eligible = snapshot.entries.filter((item) => item && !this._keyMutationEpochs.has(item.key));
|
|
6349
|
+
const loaded = this.l1.importEntries(eligible, this.opts.forbiddenSnapshotPrefixes);
|
|
6350
|
+
this._restoredSnapshot ||= loaded > 0;
|
|
6351
|
+
if (typeof snapshot.streamId === "string" && /^\d{1,20}-\d{1,20}$/.test(snapshot.streamId)) this._lastStreamId = snapshot.streamId;
|
|
6352
|
+
for (const { key, entry } of eligible) if (this.l1.has(key)) this._restoreEntryMetadata(key, entry);
|
|
5428
6353
|
this.counters.remoteSnapshotDownloads++;
|
|
5429
6354
|
this.counters.remoteSnapshotLastDownloadedAt = Date.now();
|
|
5430
6355
|
this.logger.info("Remote cache snapshot loaded (L1 hydrated)", {
|
|
@@ -5476,7 +6401,7 @@ var CacheService = class _CacheService {
|
|
|
5476
6401
|
const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
|
|
5477
6402
|
if (isGenerationalStale) {
|
|
5478
6403
|
this._deleteIfStale(k, l1Hit.setAt ?? 0);
|
|
5479
|
-
} else {
|
|
6404
|
+
} else if (!l1Hit.isStale || optSwr > 0) {
|
|
5480
6405
|
if (l1Hit.isStale) {
|
|
5481
6406
|
const swrGraceMs2 = optSwr * 1e3;
|
|
5482
6407
|
if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
|
|
@@ -5539,49 +6464,29 @@ var CacheService = class _CacheService {
|
|
|
5539
6464
|
this.counters.stampedes++;
|
|
5540
6465
|
this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch/read", { cacheKey });
|
|
5541
6466
|
span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
|
|
5542
|
-
return existing;
|
|
6467
|
+
return this._prepareReadValue(await existing);
|
|
5543
6468
|
}
|
|
5544
6469
|
const mutationEpochAtStart = this._getKeyMutationEpoch(k);
|
|
5545
|
-
const executionPromise = (async () => {
|
|
6470
|
+
const executionPromise = Promise.resolve().then(async () => {
|
|
5546
6471
|
try {
|
|
5547
|
-
|
|
5548
|
-
|
|
5549
|
-
|
|
5550
|
-
|
|
5551
|
-
|
|
5552
|
-
|
|
5553
|
-
|
|
5554
|
-
|
|
5555
|
-
|
|
5556
|
-
|
|
5557
|
-
|
|
5558
|
-
|
|
5559
|
-
|
|
5560
|
-
|
|
5561
|
-
|
|
5562
|
-
|
|
5563
|
-
if (isDiskStale) {
|
|
5564
|
-
this.disk.delete(k);
|
|
5565
|
-
} else {
|
|
5566
|
-
const promoted = this.l1.importEntries(
|
|
5567
|
-
[{ key: k, entry: diskHit }],
|
|
5568
|
-
this.opts.forbiddenSnapshotPrefixes
|
|
5569
|
-
);
|
|
5570
|
-
if (promoted > 0) {
|
|
5571
|
-
const l1Check = this.l1.get(k);
|
|
5572
|
-
if (l1Check !== null) {
|
|
5573
|
-
this.counters.diskHits++;
|
|
5574
|
-
this.opts.onHit?.(cacheKey, "disk");
|
|
5575
|
-
this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
|
|
5576
|
-
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
|
|
5577
|
-
if (this.opts.frozen) deepFreeze(l1Check.value);
|
|
5578
|
-
return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
|
|
5579
|
-
}
|
|
5580
|
-
}
|
|
5581
|
-
}
|
|
5582
|
-
}
|
|
5583
|
-
}
|
|
6472
|
+
const diskHit = await this._readDiskEntry(k, mutationEpochAtStart);
|
|
6473
|
+
if (diskHit && (diskHit.entry.staleAt === void 0 || diskHit.entry.staleAt > Date.now() || optSwr > 0)) {
|
|
6474
|
+
this.counters.diskHits++;
|
|
6475
|
+
this.opts.onHit?.(cacheKey, "disk");
|
|
6476
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
|
|
6477
|
+
if (diskHit.entry.staleAt !== void 0 && diskHit.entry.staleAt <= Date.now() && optSwr > 0 && !this.revalidating.has(k)) {
|
|
6478
|
+
this.revalidating.add(k);
|
|
6479
|
+
this.counters.swrRevalidations++;
|
|
6480
|
+
void this._revalidate(
|
|
6481
|
+
k,
|
|
6482
|
+
fetchFn,
|
|
6483
|
+
ttlMs,
|
|
6484
|
+
swrGraceMs,
|
|
6485
|
+
priority,
|
|
6486
|
+
diskHit.entry.tagVersions ?? Object.fromEntries((diskHit.entry.tags ?? []).map((tag) => [tag, 0]))
|
|
6487
|
+
);
|
|
5584
6488
|
}
|
|
6489
|
+
return diskHit.value;
|
|
5585
6490
|
}
|
|
5586
6491
|
if (!this._redisDisabled) {
|
|
5587
6492
|
try {
|
|
@@ -5591,23 +6496,26 @@ var CacheService = class _CacheService {
|
|
|
5591
6496
|
const redisElapsed = performance.now() - redisStart;
|
|
5592
6497
|
this.watchdog.recordRedis(redisElapsed);
|
|
5593
6498
|
this.cb.onSuccess();
|
|
5594
|
-
if (redisHit && !redisHit.stale && redisHit.
|
|
6499
|
+
if (redisHit && !redisHit.stale && (redisHit.staleAt === void 0 || redisHit.staleAt > Date.now() || optSwr > 0)) {
|
|
5595
6500
|
const parsed = redisHit.value;
|
|
5596
6501
|
if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
|
|
5597
6502
|
this.logger.debug("Aborting L2 promotion \u2014 key was mutated or deleted during Redis read", { cacheKey });
|
|
5598
6503
|
span.setAttribute("cache.aborted_mutation_race", true);
|
|
5599
6504
|
const current = this.l1.get(k);
|
|
5600
|
-
const liveVal = current && !current.isStale
|
|
5601
|
-
|
|
5602
|
-
return this.opts.cloneStrategy === "structuredClone" && liveVal != null && typeof liveVal === "object" ? structuredClone(liveVal) : liveVal;
|
|
6505
|
+
const liveVal = current && !current.isStale ? current.value : parsed;
|
|
6506
|
+
return liveVal;
|
|
5603
6507
|
}
|
|
5604
|
-
this.
|
|
6508
|
+
if (!this._promoteRedisEntry(k, redisHit, ttlMs, priority)) throw new Error("Redis entry expired during promotion");
|
|
5605
6509
|
this.counters.l2Hits++;
|
|
5606
6510
|
this.opts.onHit?.(cacheKey, "l2");
|
|
5607
6511
|
this.logger.debug(redisHit.tagVersions ? "L2 hit (Redis hash)" : "L2 hit (Redis)", { cacheKey });
|
|
5608
6512
|
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
5609
|
-
if (
|
|
5610
|
-
|
|
6513
|
+
if (redisHit.staleAt !== void 0 && redisHit.staleAt <= Date.now() && optSwr > 0 && !this.revalidating.has(k)) {
|
|
6514
|
+
this.revalidating.add(k);
|
|
6515
|
+
this.counters.swrRevalidations++;
|
|
6516
|
+
void this._revalidate(k, fetchFn, ttlMs, swrGraceMs, priority, redisHit.tagVersions);
|
|
6517
|
+
}
|
|
6518
|
+
return parsed;
|
|
5611
6519
|
}
|
|
5612
6520
|
} catch (err) {
|
|
5613
6521
|
this.cb.onFailure();
|
|
@@ -5617,6 +6525,7 @@ var CacheService = class _CacheService {
|
|
|
5617
6525
|
span.setAttribute("cache.hit", false).setAttribute("cache.hit_tier", "miss");
|
|
5618
6526
|
this.opts.onMiss?.(cacheKey);
|
|
5619
6527
|
this.counters.fetches++;
|
|
6528
|
+
const tagSnapshot = this.opts.tagStrategy === "generational" && optTags?.length ? Object.fromEntries(await Promise.all(optTags.map(async (tag) => [tag, await this._getTagVersion(tag)]))) : void 0;
|
|
5620
6529
|
const fetchStart = Date.now();
|
|
5621
6530
|
let data;
|
|
5622
6531
|
try {
|
|
@@ -5645,50 +6554,41 @@ var CacheService = class _CacheService {
|
|
|
5645
6554
|
}
|
|
5646
6555
|
const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
|
|
5647
6556
|
const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
|
|
5648
|
-
|
|
6557
|
+
const activeTagVersions = tagSnapshot;
|
|
5649
6558
|
if (optTags?.length) {
|
|
5650
6559
|
if (this.opts.tagStrategy === "generational") {
|
|
5651
|
-
|
|
5652
|
-
activeTagVersions = {};
|
|
5653
|
-
for (let i = 0; i < optTags.length; i++) {
|
|
5654
|
-
activeTagVersions[optTags[i]] = vers[i];
|
|
5655
|
-
}
|
|
6560
|
+
if (await this._isGenerationalEntryStale(tagSnapshot)) return data;
|
|
5656
6561
|
} else {
|
|
5657
|
-
await this._registerTags(k, optTags, Math.ceil(
|
|
6562
|
+
await this._registerTags(k, optTags, Math.ceil(storeTtl / 1e3));
|
|
5658
6563
|
}
|
|
5659
6564
|
}
|
|
5660
6565
|
if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
|
|
5661
6566
|
this.logger.debug("Aborting in-flight cache commit \u2014 key was mutated or deleted during fetch", { cacheKey });
|
|
5662
6567
|
span.setAttribute("cache.aborted_mutation_race", true);
|
|
5663
6568
|
const current = this.l1.get(k);
|
|
5664
|
-
if (current && !current.isStale
|
|
6569
|
+
if (current && !current.isStale) {
|
|
5665
6570
|
const freshVal = current.value;
|
|
5666
|
-
|
|
5667
|
-
return this.opts.cloneStrategy === "structuredClone" && freshVal != null && typeof freshVal === "object" ? structuredClone(freshVal) : freshVal;
|
|
6571
|
+
return freshVal;
|
|
5668
6572
|
}
|
|
5669
|
-
|
|
5670
|
-
return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
|
|
6573
|
+
return data;
|
|
5671
6574
|
}
|
|
5672
6575
|
const writeTs = Date.now();
|
|
5673
|
-
this.
|
|
5674
|
-
|
|
6576
|
+
this._invalidateDiskKey(k);
|
|
6577
|
+
this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs, optTags, opts.dependsOn);
|
|
6578
|
+
this._restoreEntryMetadata(k, { tags: optTags, dependsOn: opts.dependsOn, expiresAt: writeTs + storeTtl });
|
|
6579
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5675
6580
|
try {
|
|
5676
|
-
|
|
5677
|
-
|
|
5678
|
-
|
|
5679
|
-
|
|
5680
|
-
|
|
5681
|
-
|
|
5682
|
-
|
|
5683
|
-
|
|
5684
|
-
|
|
5685
|
-
|
|
5686
|
-
|
|
5687
|
-
tx.expire(k, ttlSec);
|
|
5688
|
-
await tx.exec();
|
|
5689
|
-
} else {
|
|
5690
|
-
await client.setex(k, ttlSec, toStore);
|
|
5691
|
-
}
|
|
6581
|
+
await this._writeRedisEntry(
|
|
6582
|
+
k,
|
|
6583
|
+
data,
|
|
6584
|
+
writeTs + storeTtl,
|
|
6585
|
+
writeTs,
|
|
6586
|
+
activeTagVersions,
|
|
6587
|
+
staleAt,
|
|
6588
|
+
optTags,
|
|
6589
|
+
opts.dependsOn,
|
|
6590
|
+
() => this._getKeyMutationEpoch(k) === mutationEpochAtStart
|
|
6591
|
+
);
|
|
5692
6592
|
this.cb.onSuccess();
|
|
5693
6593
|
this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
|
|
5694
6594
|
} catch {
|
|
@@ -5698,15 +6598,14 @@ var CacheService = class _CacheService {
|
|
|
5698
6598
|
} else {
|
|
5699
6599
|
this.logger.debug("Cached L1", { cacheKey });
|
|
5700
6600
|
}
|
|
5701
|
-
|
|
5702
|
-
return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
|
|
6601
|
+
return data;
|
|
5703
6602
|
} finally {
|
|
5704
|
-
this.inflight.delete(k);
|
|
6603
|
+
if (this.inflight.get(k) === executionPromise) this.inflight.delete(k);
|
|
5705
6604
|
span.end();
|
|
5706
6605
|
}
|
|
5707
|
-
})
|
|
6606
|
+
});
|
|
5708
6607
|
this.inflight.set(k, executionPromise);
|
|
5709
|
-
return executionPromise;
|
|
6608
|
+
return this._prepareReadValue(await executionPromise);
|
|
5710
6609
|
}
|
|
5711
6610
|
/**
|
|
5712
6611
|
* Graceful shutdown flusher for Kubernetes preStop hooks, NestJS onApplicationShutdown,
|
|
@@ -5787,6 +6686,9 @@ var CacheService = class _CacheService {
|
|
|
5787
6686
|
}
|
|
5788
6687
|
async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority, knownTagVersions) {
|
|
5789
6688
|
const startEpoch = this._getKeyMutationEpoch(cacheKey);
|
|
6689
|
+
const previous = this.l1.getEntry(cacheKey);
|
|
6690
|
+
const tags = previous?.tags ?? Object.keys(knownTagVersions ?? {});
|
|
6691
|
+
const dependencies = previous?.dependsOn;
|
|
5790
6692
|
try {
|
|
5791
6693
|
const fetchStart = Date.now();
|
|
5792
6694
|
const data = await fetchFn();
|
|
@@ -5801,14 +6703,14 @@ var CacheService = class _CacheService {
|
|
|
5801
6703
|
const l1Existing = this.l1.get(cacheKey);
|
|
5802
6704
|
const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
|
|
5803
6705
|
if (this.opts.tagStrategy === "generational" && tagVersionsSource) {
|
|
5804
|
-
const
|
|
5805
|
-
const vers = await Promise.all(
|
|
6706
|
+
const tags2 = Object.keys(tagVersionsSource);
|
|
6707
|
+
const vers = await Promise.all(tags2.map((tag) => this._getTagVersion(tag)));
|
|
5806
6708
|
activeTagVersions = {};
|
|
5807
|
-
for (let i = 0; i <
|
|
5808
|
-
activeTagVersions[
|
|
6709
|
+
for (let i = 0; i < tags2.length; i++) {
|
|
6710
|
+
activeTagVersions[tags2[i]] = vers[i];
|
|
5809
6711
|
}
|
|
5810
6712
|
if (knownTagVersions) {
|
|
5811
|
-
for (const t of
|
|
6713
|
+
for (const t of tags2) {
|
|
5812
6714
|
if (knownTagVersions[t] !== void 0 && activeTagVersions[t] !== knownTagVersions[t]) {
|
|
5813
6715
|
this.logger.debug("SWR: aborting revalidation commit \u2014 tag version bumped during revalidation", { cacheKey, tag: t });
|
|
5814
6716
|
return;
|
|
@@ -5821,31 +6723,28 @@ var CacheService = class _CacheService {
|
|
|
5821
6723
|
return;
|
|
5822
6724
|
}
|
|
5823
6725
|
const writeTs = Date.now();
|
|
5824
|
-
this.
|
|
6726
|
+
this._invalidateDiskKey(cacheKey);
|
|
6727
|
+
this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs, tags, dependencies);
|
|
6728
|
+
this._restoreEntryMetadata(cacheKey, { tags, dependsOn: dependencies, expiresAt: writeTs + ttlMs + swrGraceMs });
|
|
5825
6729
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5826
6730
|
try {
|
|
5827
|
-
|
|
5828
|
-
|
|
5829
|
-
|
|
5830
|
-
|
|
5831
|
-
|
|
5832
|
-
|
|
5833
|
-
|
|
5834
|
-
|
|
5835
|
-
|
|
5836
|
-
|
|
5837
|
-
|
|
5838
|
-
tx.expire(cacheKey, ttlSec);
|
|
5839
|
-
await tx.exec();
|
|
5840
|
-
} else {
|
|
5841
|
-
await client.setex(cacheKey, ttlSec, stored);
|
|
5842
|
-
}
|
|
6731
|
+
await this._writeRedisEntry(
|
|
6732
|
+
cacheKey,
|
|
6733
|
+
data,
|
|
6734
|
+
writeTs + ttlMs + swrGraceMs,
|
|
6735
|
+
writeTs,
|
|
6736
|
+
activeTagVersions,
|
|
6737
|
+
staleAt,
|
|
6738
|
+
tags,
|
|
6739
|
+
dependencies,
|
|
6740
|
+
() => this._getKeyMutationEpoch(cacheKey) === startEpoch
|
|
6741
|
+
);
|
|
5843
6742
|
} catch {
|
|
5844
6743
|
}
|
|
5845
6744
|
}
|
|
5846
6745
|
this.logger.debug("SWR: revalidation complete", { cacheKey });
|
|
5847
6746
|
} catch (err) {
|
|
5848
|
-
if (this.opts.staleIfError > 0) {
|
|
6747
|
+
if (this.opts.staleIfError > 0 && this._getKeyMutationEpoch(cacheKey) === startEpoch) {
|
|
5849
6748
|
const additionalMs = this.opts.staleIfError * 1e3;
|
|
5850
6749
|
this.l1.bumpExpiry(cacheKey, additionalMs);
|
|
5851
6750
|
this.logger.debug("SWR: revalidation failed, stale-if-error extending expiry", {
|
|
@@ -5873,12 +6772,16 @@ var CacheService = class _CacheService {
|
|
|
5873
6772
|
const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
|
|
5874
6773
|
const p = priority ?? inferPriority(cacheKey);
|
|
5875
6774
|
const k = this.nk(cacheKey);
|
|
6775
|
+
const existingEntry = this.l1.getEntry(k);
|
|
6776
|
+
const requestedTags = opts?.tags ?? existingEntry?.tags ?? this.keyTags.get(k)?.tags;
|
|
6777
|
+
const requestedDependencies = opts?.dependsOn ?? existingEntry?.dependsOn;
|
|
5876
6778
|
this._bumpKeyMutation(k);
|
|
6779
|
+
const epoch = this._getKeyMutationEpoch(k);
|
|
5877
6780
|
this.inflight.delete(k);
|
|
5878
|
-
this.
|
|
6781
|
+
this._invalidateDiskKey(k);
|
|
5879
6782
|
this.counters.sets++;
|
|
5880
6783
|
let activeTagVersions;
|
|
5881
|
-
const tagsToRegister =
|
|
6784
|
+
const tagsToRegister = requestedTags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(requestedTags, this.opts.tagHierarchyDelimiter) : requestedTags : void 0;
|
|
5882
6785
|
if (tagsToRegister?.length) {
|
|
5883
6786
|
if (this.opts.tagStrategy === "generational") {
|
|
5884
6787
|
const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
|
|
@@ -5887,50 +6790,27 @@ var CacheService = class _CacheService {
|
|
|
5887
6790
|
activeTagVersions[tagsToRegister[i]] = vers[i];
|
|
5888
6791
|
}
|
|
5889
6792
|
} else {
|
|
5890
|
-
await this._registerTags(k, tagsToRegister,
|
|
6793
|
+
await this._registerTags(k, tagsToRegister, effectiveTtlSeconds);
|
|
5891
6794
|
}
|
|
5892
6795
|
}
|
|
6796
|
+
if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return;
|
|
5893
6797
|
const writeTs = Date.now();
|
|
5894
|
-
this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions, writeTs);
|
|
5895
|
-
|
|
5896
|
-
|
|
5897
|
-
if (opts.dependsOn.length > 0) {
|
|
5898
|
-
const nsPatterns = [];
|
|
5899
|
-
for (const pattern of opts.dependsOn) {
|
|
5900
|
-
const nsPattern = this.nk(pattern);
|
|
5901
|
-
nsPatterns.push(nsPattern);
|
|
5902
|
-
let deps = this.dependencyIndex.get(nsPattern);
|
|
5903
|
-
if (!deps) {
|
|
5904
|
-
deps = /* @__PURE__ */ new Set();
|
|
5905
|
-
this.dependencyIndex.set(nsPattern, deps);
|
|
5906
|
-
}
|
|
5907
|
-
deps.add(k);
|
|
5908
|
-
}
|
|
5909
|
-
this.keyDependencies.set(k, nsPatterns);
|
|
5910
|
-
}
|
|
5911
|
-
}
|
|
6798
|
+
this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions, writeTs, tagsToRegister, requestedDependencies);
|
|
6799
|
+
this._rememberTags(k, tagsToRegister ?? [], writeTs + ttlMs);
|
|
6800
|
+
this._registerDependencies(k, requestedDependencies);
|
|
5912
6801
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5913
6802
|
try {
|
|
5914
|
-
|
|
5915
|
-
|
|
5916
|
-
|
|
5917
|
-
|
|
5918
|
-
|
|
5919
|
-
|
|
5920
|
-
|
|
5921
|
-
|
|
5922
|
-
|
|
5923
|
-
|
|
5924
|
-
|
|
5925
|
-
tx.expire(k, ttlSec);
|
|
5926
|
-
await tx.exec();
|
|
5927
|
-
} else {
|
|
5928
|
-
if (this.opts.autoPipeline && this.pipeliner) {
|
|
5929
|
-
await this.pipeliner.setex(k, ttlSec, stored);
|
|
5930
|
-
} else {
|
|
5931
|
-
await client.setex(k, ttlSec, stored);
|
|
5932
|
-
}
|
|
5933
|
-
}
|
|
6803
|
+
await this._writeRedisEntry(
|
|
6804
|
+
k,
|
|
6805
|
+
data,
|
|
6806
|
+
writeTs + ttlMs,
|
|
6807
|
+
writeTs,
|
|
6808
|
+
activeTagVersions,
|
|
6809
|
+
void 0,
|
|
6810
|
+
tagsToRegister,
|
|
6811
|
+
requestedDependencies,
|
|
6812
|
+
() => this._getKeyMutationEpoch(k) === epoch
|
|
6813
|
+
);
|
|
5934
6814
|
this.cb.onSuccess();
|
|
5935
6815
|
} catch (err) {
|
|
5936
6816
|
this.cb.onFailure();
|
|
@@ -5955,27 +6835,10 @@ var CacheService = class _CacheService {
|
|
|
5955
6835
|
* the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
|
|
5956
6836
|
*/
|
|
5957
6837
|
async _registerTags(k, tags, ttlSeconds) {
|
|
5958
|
-
this._removeKeyTags(k);
|
|
5959
6838
|
const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
|
|
5960
6839
|
const expiresAt = Date.now() + effectiveTtl * 1e3;
|
|
5961
|
-
if (this.keyTags.size >= 1e5 && !this.keyTags.has(k)) {
|
|
5962
|
-
this._sweepExpiredMetadata();
|
|
5963
|
-
if (this.keyTags.size >= 1e5) {
|
|
5964
|
-
const oldestKey = this.keyTags.keys().next().value;
|
|
5965
|
-
if (oldestKey !== void 0) this._removeKeyTags(oldestKey);
|
|
5966
|
-
}
|
|
5967
|
-
}
|
|
5968
6840
|
const uniqueTags = Array.from(new Set(tags));
|
|
5969
|
-
|
|
5970
|
-
const tagKey = this.nk(`_tag_:${tag}`);
|
|
5971
|
-
let members = this.tagIndex.get(tagKey);
|
|
5972
|
-
if (!members) {
|
|
5973
|
-
members = /* @__PURE__ */ new Set();
|
|
5974
|
-
this.tagIndex.set(tagKey, members);
|
|
5975
|
-
}
|
|
5976
|
-
members.add(k);
|
|
5977
|
-
}
|
|
5978
|
-
this.keyTags.set(k, { tags: uniqueTags, expiresAt });
|
|
6841
|
+
this._rememberTags(k, uniqueTags, expiresAt);
|
|
5979
6842
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5980
6843
|
try {
|
|
5981
6844
|
const client = await this.getRedis();
|
|
@@ -6008,6 +6871,7 @@ var CacheService = class _CacheService {
|
|
|
6008
6871
|
const k = this.nk(cacheKey);
|
|
6009
6872
|
this.counters.deletes++;
|
|
6010
6873
|
if (isPattern) {
|
|
6874
|
+
this._fenceInvalidation();
|
|
6011
6875
|
const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
|
|
6012
6876
|
for (const liveKey of this.l1.liveKeys()) {
|
|
6013
6877
|
if (liveKey.startsWith(pfx)) {
|
|
@@ -6020,9 +6884,9 @@ var CacheService = class _CacheService {
|
|
|
6020
6884
|
this.inflight.delete(inflightKey);
|
|
6021
6885
|
}
|
|
6022
6886
|
}
|
|
6023
|
-
this._addPatternTombstone(
|
|
6887
|
+
this._addPatternTombstone(k);
|
|
6024
6888
|
this.l1.deletePattern(k);
|
|
6025
|
-
this.
|
|
6889
|
+
this._removePatternFromIndices(k);
|
|
6026
6890
|
for (const ktKey of Array.from(this.keyTags.keys())) {
|
|
6027
6891
|
if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
|
|
6028
6892
|
}
|
|
@@ -6033,14 +6897,7 @@ var CacheService = class _CacheService {
|
|
|
6033
6897
|
this._bumpKeyMutation(k);
|
|
6034
6898
|
this.inflight.delete(k);
|
|
6035
6899
|
this.l1.delete(k);
|
|
6036
|
-
this.
|
|
6037
|
-
setImmediate(() => {
|
|
6038
|
-
try {
|
|
6039
|
-
if (!this._diskDisabled) this.disk.delete(k);
|
|
6040
|
-
} finally {
|
|
6041
|
-
this._pendingDiskDeletes.delete(k);
|
|
6042
|
-
}
|
|
6043
|
-
});
|
|
6900
|
+
this._invalidateDiskKey(k);
|
|
6044
6901
|
this._removeKeyTags(k);
|
|
6045
6902
|
this._cascadeDependencies(k);
|
|
6046
6903
|
this._removeKeyDependencies(k);
|
|
@@ -6097,7 +6954,7 @@ var CacheService = class _CacheService {
|
|
|
6097
6954
|
async increment(cacheKey, ttlSeconds) {
|
|
6098
6955
|
this._assertActive("increment");
|
|
6099
6956
|
const k = this.nk(cacheKey);
|
|
6100
|
-
if (this._redisDisabled) {
|
|
6957
|
+
if (this._redisDisabled || this.opts.l2WriteMode === "read-only") {
|
|
6101
6958
|
if (!this._incrementFallbackWarned) {
|
|
6102
6959
|
this._incrementFallbackWarned = true;
|
|
6103
6960
|
this.logger.warn(
|
|
@@ -6153,6 +7010,7 @@ var CacheService = class _CacheService {
|
|
|
6153
7010
|
this.counters.deletes++;
|
|
6154
7011
|
const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
|
|
6155
7012
|
if (k) {
|
|
7013
|
+
this._fenceInvalidation();
|
|
6156
7014
|
const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
|
|
6157
7015
|
for (const liveKey of this.l1.liveKeys()) {
|
|
6158
7016
|
if (liveKey.startsWith(pfx)) {
|
|
@@ -6165,9 +7023,9 @@ var CacheService = class _CacheService {
|
|
|
6165
7023
|
this.inflight.delete(inflightKey);
|
|
6166
7024
|
}
|
|
6167
7025
|
}
|
|
6168
|
-
this._addPatternTombstone(
|
|
7026
|
+
this._addPatternTombstone(k);
|
|
6169
7027
|
this.l1.deletePattern(k);
|
|
6170
|
-
this.
|
|
7028
|
+
this._removePatternFromIndices(k);
|
|
6171
7029
|
} else {
|
|
6172
7030
|
this._globalEpoch++;
|
|
6173
7031
|
this.inflight.clear();
|
|
@@ -6317,28 +7175,34 @@ var CacheService = class _CacheService {
|
|
|
6317
7175
|
this._assertActive("scan");
|
|
6318
7176
|
const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
|
|
6319
7177
|
this.l1.scan((key, entry, pfx) => {
|
|
6320
|
-
|
|
6321
|
-
fn(key, value, pfx);
|
|
7178
|
+
fn(key, this._prepareReadValue(this.l1.resolveValue(entry)), pfx);
|
|
6322
7179
|
}, prefixLen);
|
|
6323
7180
|
}
|
|
6324
7181
|
/**
|
|
6325
|
-
|
|
7182
|
+
* Extend the TTL of a key in L1 and Redis without fetching.
|
|
6326
7183
|
* Returns `false` if the key is absent or already expired.
|
|
6327
7184
|
*
|
|
6328
7185
|
* @param newTtlSeconds - The new TTL from now, in seconds.
|
|
6329
7186
|
*/
|
|
6330
7187
|
async touch(cacheKey, newTtlSeconds) {
|
|
6331
7188
|
this._assertActive("touch");
|
|
7189
|
+
if (!Number.isFinite(newTtlSeconds) || newTtlSeconds <= 0) throw new Error("touch TTL must be finite and positive");
|
|
6332
7190
|
const k = this.nk(cacheKey);
|
|
7191
|
+
const epoch = this._getKeyMutationEpoch(k);
|
|
6333
7192
|
const hit = this.l1.touch(k, newTtlSeconds * 1e3);
|
|
7193
|
+
const entry = this.l1.getEntry(k);
|
|
6334
7194
|
if (hit) {
|
|
6335
7195
|
const kt = this.keyTags.get(k);
|
|
6336
7196
|
if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1e3;
|
|
6337
7197
|
}
|
|
6338
|
-
if (hit && !this._redisDisabled) {
|
|
7198
|
+
if (hit && !this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
6339
7199
|
try {
|
|
6340
7200
|
const client = await this.getRedis();
|
|
6341
|
-
|
|
7201
|
+
if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return hit;
|
|
7202
|
+
if (entry && typeof client.pttl === "function" && typeof client.eval === "function") {
|
|
7203
|
+
await client.eval(LUA_TOUCH_CACHE_ENTRY, 1, k, String(entry.setAt ?? 0), String(entry.expiresAt), String(Math.ceil(newTtlSeconds * 1e3)));
|
|
7204
|
+
} else await client.expire(k, Math.ceil(newTtlSeconds));
|
|
7205
|
+
this.cb.onSuccess();
|
|
6342
7206
|
} catch {
|
|
6343
7207
|
}
|
|
6344
7208
|
}
|
|
@@ -6360,7 +7224,8 @@ var CacheService = class _CacheService {
|
|
|
6360
7224
|
const now = Date.now();
|
|
6361
7225
|
if (entry.expiresAt <= now) return null;
|
|
6362
7226
|
if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
|
|
6363
|
-
|
|
7227
|
+
if (entry.tagVersions && Object.entries(entry.tagVersions).some(([tag, version]) => (this.tagVersions.get(tag)?.version ?? 0) > version)) return null;
|
|
7228
|
+
return this._prepareReadValue(entry.value !== void 0 ? entry.value : this.codec.decode(entry.data));
|
|
6364
7229
|
}
|
|
6365
7230
|
_prepareReadValue(val) {
|
|
6366
7231
|
if (this.opts.frozen) deepFreeze(val);
|
|
@@ -6377,49 +7242,23 @@ var CacheService = class _CacheService {
|
|
|
6377
7242
|
async peek(cacheKey) {
|
|
6378
7243
|
this._assertActive("peek");
|
|
6379
7244
|
const k = this.nk(cacheKey);
|
|
7245
|
+
const epoch = this._getKeyMutationEpoch(k);
|
|
7246
|
+
this.counters.gets++;
|
|
6380
7247
|
const l1Hit = this.l1.get(k);
|
|
6381
7248
|
if (l1Hit !== null) {
|
|
6382
7249
|
if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
|
|
6383
7250
|
this._deleteIfStale(k, l1Hit.setAt ?? 0);
|
|
6384
7251
|
} else {
|
|
6385
|
-
this.counters.gets++;
|
|
6386
7252
|
this.counters.l1Hits++;
|
|
6387
7253
|
return this._prepareReadValue(l1Hit.value);
|
|
6388
7254
|
}
|
|
6389
7255
|
}
|
|
6390
|
-
|
|
6391
|
-
|
|
6392
|
-
|
|
6393
|
-
|
|
6394
|
-
} catch {
|
|
6395
|
-
}
|
|
6396
|
-
} else if (this.watchdog.isDiskAllowed()) {
|
|
6397
|
-
const diskStart = performance.now();
|
|
6398
|
-
const diskHit = this.disk.load(k);
|
|
6399
|
-
const diskElapsed = performance.now() - diskStart;
|
|
6400
|
-
this.watchdog.recordDisk(diskElapsed);
|
|
6401
|
-
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
6402
|
-
if (diskHit !== null) {
|
|
6403
|
-
if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
|
|
6404
|
-
this.disk.delete(k);
|
|
6405
|
-
} else {
|
|
6406
|
-
const promoted = this.l1.importEntries(
|
|
6407
|
-
[{ key: k, entry: diskHit }],
|
|
6408
|
-
this.opts.forbiddenSnapshotPrefixes
|
|
6409
|
-
);
|
|
6410
|
-
if (promoted > 0) {
|
|
6411
|
-
const l1Check = this.l1.get(k);
|
|
6412
|
-
if (l1Check !== null) {
|
|
6413
|
-
this.counters.gets++;
|
|
6414
|
-
this.counters.diskHits++;
|
|
6415
|
-
return this._prepareReadValue(l1Check.value);
|
|
6416
|
-
}
|
|
6417
|
-
}
|
|
6418
|
-
}
|
|
6419
|
-
}
|
|
6420
|
-
}
|
|
7256
|
+
const diskHit = await this._readDiskEntry(k, epoch);
|
|
7257
|
+
if (diskHit) {
|
|
7258
|
+
this.counters.diskHits++;
|
|
7259
|
+
return this._prepareReadValue(diskHit.value);
|
|
6421
7260
|
}
|
|
6422
|
-
if (!this._redisDisabled
|
|
7261
|
+
if (!this._redisDisabled) {
|
|
6423
7262
|
try {
|
|
6424
7263
|
const client = await this.getRedis();
|
|
6425
7264
|
const redisStart = performance.now();
|
|
@@ -6427,10 +7266,10 @@ var CacheService = class _CacheService {
|
|
|
6427
7266
|
const redisElapsed = performance.now() - redisStart;
|
|
6428
7267
|
this.watchdog.recordRedis(redisElapsed);
|
|
6429
7268
|
this.cb.onSuccess();
|
|
6430
|
-
if (redisHit && !redisHit.stale
|
|
7269
|
+
if (redisHit && !redisHit.stale) {
|
|
6431
7270
|
const parsed = redisHit.value;
|
|
6432
|
-
this.
|
|
6433
|
-
this.
|
|
7271
|
+
if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return null;
|
|
7272
|
+
if (!this._promoteRedisEntry(k, redisHit, 6e4, inferPriority(cacheKey))) return null;
|
|
6434
7273
|
this.counters.l2Hits++;
|
|
6435
7274
|
return this._prepareReadValue(parsed);
|
|
6436
7275
|
}
|
|
@@ -6452,6 +7291,8 @@ var CacheService = class _CacheService {
|
|
|
6452
7291
|
*/
|
|
6453
7292
|
async mget(keys, fetchFn, ttl = 300, priority) {
|
|
6454
7293
|
this._assertActive("mget");
|
|
7294
|
+
this.counters.gets += keys.length;
|
|
7295
|
+
const epochs = new Map(keys.map((key) => [this.nk(key), this._getKeyMutationEpoch(this.nk(key))]));
|
|
6455
7296
|
const span = this._startSpan("tricache.mget");
|
|
6456
7297
|
if (this.opts.tracer) {
|
|
6457
7298
|
span.setAttribute("cache.batch.size", keys.length);
|
|
@@ -6464,7 +7305,7 @@ var CacheService = class _CacheService {
|
|
|
6464
7305
|
for (let i = 0; i < keys.length; i++) {
|
|
6465
7306
|
const k = this.nk(keys[i]);
|
|
6466
7307
|
const entry = this.l1.getEntry(k);
|
|
6467
|
-
if (entry && entry.expiresAt > now) {
|
|
7308
|
+
if (entry && entry.expiresAt > now && (entry.staleAt === void 0 || entry.staleAt > now)) {
|
|
6468
7309
|
if (await this._isGenerationalEntryStale(entry.tagVersions)) {
|
|
6469
7310
|
this._deleteIfStale(k, entry.setAt ?? 0);
|
|
6470
7311
|
missIndexes.push(i);
|
|
@@ -6493,64 +7334,24 @@ var CacheService = class _CacheService {
|
|
|
6493
7334
|
try {
|
|
6494
7335
|
const client = await this.getRedis();
|
|
6495
7336
|
const nsKeys = missKeys.map((k) => this.nk(k));
|
|
6496
|
-
const
|
|
6497
|
-
const useHashPipeline = this.opts.tagStrategy === "generational" && typeof pipeline.hgetall === "function";
|
|
6498
|
-
for (const nk of nsKeys) {
|
|
6499
|
-
if (useHashPipeline) {
|
|
6500
|
-
pipeline.hgetall(nk);
|
|
6501
|
-
} else {
|
|
6502
|
-
pipeline.get(nk);
|
|
6503
|
-
}
|
|
6504
|
-
}
|
|
6505
|
-
const redisStart = performance.now();
|
|
6506
|
-
const raws = await pipeline.exec();
|
|
6507
|
-
const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
|
|
6508
|
-
this.watchdog.recordRedis(redisElapsed);
|
|
6509
|
-
this.cb.onSuccess();
|
|
7337
|
+
const remoteEntries = await this._readRedisBatch(client, nsKeys);
|
|
6510
7338
|
for (let j = 0; j < missKeys.length; j++) {
|
|
6511
|
-
const tuple = raws[j];
|
|
6512
|
-
const err = tuple ? tuple[0] : null;
|
|
6513
|
-
const rawVal = tuple ? tuple[1] : null;
|
|
6514
7339
|
const idx = missIndexes[j];
|
|
6515
7340
|
const k = nsKeys[j];
|
|
6516
|
-
|
|
6517
|
-
|
|
6518
|
-
let hit = false;
|
|
6519
|
-
if (useHashPipeline) {
|
|
6520
|
-
if (err && err.message?.includes("WRONGTYPE")) {
|
|
6521
|
-
const fallbackRaw = await client.get(k);
|
|
6522
|
-
if (fallbackRaw) {
|
|
6523
|
-
parsed = await this._decryptAndDeserialize(fallbackRaw);
|
|
6524
|
-
hit = true;
|
|
6525
|
-
}
|
|
6526
|
-
} else if (!err && typeof rawVal === "string") {
|
|
6527
|
-
parsed = await this._decryptAndDeserialize(rawVal);
|
|
6528
|
-
hit = true;
|
|
6529
|
-
} else if (!err && rawVal && typeof rawVal === "object" && rawVal.d) {
|
|
6530
|
-
const hashHit = await this._parseGenerationalRedisHash(k, rawVal);
|
|
6531
|
-
if (hashHit && !hashHit.stale && hashHit.value !== void 0) {
|
|
6532
|
-
parsed = hashHit.value;
|
|
6533
|
-
tagVersions = hashHit.tagVersions;
|
|
6534
|
-
hit = true;
|
|
6535
|
-
}
|
|
6536
|
-
}
|
|
6537
|
-
} else if (!err && rawVal) {
|
|
6538
|
-
parsed = await this._decryptAndDeserialize(rawVal);
|
|
6539
|
-
hit = true;
|
|
6540
|
-
}
|
|
6541
|
-
if (hit && parsed !== void 0) {
|
|
7341
|
+
const entry = remoteEntries.get(k);
|
|
7342
|
+
if (entry && (entry.staleAt === void 0 || entry.staleAt > Date.now()) && !this._destroyed && this._getKeyMutationEpoch(k) === epochs.get(k)) {
|
|
6542
7343
|
const p = priority ?? inferPriority(missKeys[j]);
|
|
6543
7344
|
const ttlVal = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
|
|
6544
|
-
this.
|
|
7345
|
+
if (!this._promoteRedisEntry(k, entry, this._jitterTtl(ttlVal * 1e3), p)) continue;
|
|
6545
7346
|
this.counters.l2Hits++;
|
|
6546
7347
|
l2HitCount++;
|
|
6547
|
-
result[idx] = this._prepareReadValue(
|
|
7348
|
+
result[idx] = this._prepareReadValue(entry.value);
|
|
6548
7349
|
missIndexes[j] = -1;
|
|
6549
7350
|
missKeys[j] = "";
|
|
6550
7351
|
}
|
|
6551
7352
|
}
|
|
6552
7353
|
const remainingIdx = missIndexes.filter((i) => i >= 0);
|
|
6553
|
-
const remainingKeys = missKeys.filter((
|
|
7354
|
+
const remainingKeys = missKeys.filter((_key, index) => missIndexes[index] >= 0);
|
|
6554
7355
|
missIndexes.length = 0;
|
|
6555
7356
|
missKeys.length = 0;
|
|
6556
7357
|
missIndexes.push(...remainingIdx);
|
|
@@ -6563,62 +7364,64 @@ var CacheService = class _CacheService {
|
|
|
6563
7364
|
if (!this._diskDisabled && missKeys.length > 0) {
|
|
6564
7365
|
for (let j = missKeys.length - 1; j >= 0; j--) {
|
|
6565
7366
|
const k = this.nk(missKeys[j]);
|
|
6566
|
-
|
|
6567
|
-
if (
|
|
6568
|
-
|
|
6569
|
-
|
|
6570
|
-
|
|
6571
|
-
|
|
6572
|
-
continue;
|
|
6573
|
-
}
|
|
6574
|
-
if (!this.watchdog.isDiskAllowed()) continue;
|
|
6575
|
-
const diskStart = performance.now();
|
|
6576
|
-
const diskHit = this.disk.load(k);
|
|
6577
|
-
const diskElapsed = performance.now() - diskStart;
|
|
6578
|
-
this.watchdog.recordDisk(diskElapsed);
|
|
6579
|
-
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
6580
|
-
if (diskHit !== null) {
|
|
6581
|
-
if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
|
|
6582
|
-
this.disk.delete(k);
|
|
6583
|
-
continue;
|
|
6584
|
-
}
|
|
6585
|
-
const promoted = this.l1.importEntries(
|
|
6586
|
-
[{ key: k, entry: diskHit }],
|
|
6587
|
-
this.opts.forbiddenSnapshotPrefixes
|
|
6588
|
-
);
|
|
6589
|
-
if (promoted > 0) {
|
|
6590
|
-
const l1Check = this.l1.get(k);
|
|
6591
|
-
if (l1Check !== null) {
|
|
6592
|
-
this.counters.diskHits++;
|
|
6593
|
-
result[missIndexes[j]] = this._prepareReadValue(l1Check.value);
|
|
6594
|
-
missIndexes.splice(j, 1);
|
|
6595
|
-
missKeys.splice(j, 1);
|
|
6596
|
-
}
|
|
6597
|
-
}
|
|
7367
|
+
const diskHit = await this._readDiskEntry(k, epochs.get(k));
|
|
7368
|
+
if (diskHit && (diskHit.entry.staleAt === void 0 || diskHit.entry.staleAt > Date.now())) {
|
|
7369
|
+
this.counters.diskHits++;
|
|
7370
|
+
result[missIndexes[j]] = this._prepareReadValue(diskHit.value);
|
|
7371
|
+
missIndexes.splice(j, 1);
|
|
7372
|
+
missKeys.splice(j, 1);
|
|
6598
7373
|
}
|
|
6599
7374
|
}
|
|
6600
7375
|
}
|
|
6601
7376
|
if (missKeys.length > 0 && fetchFn) {
|
|
6602
|
-
|
|
6603
|
-
const
|
|
6604
|
-
const isMap = fetched instanceof Map;
|
|
6605
|
-
const setPromises = [];
|
|
7377
|
+
const owned = /* @__PURE__ */ new Map();
|
|
7378
|
+
const waiting = [];
|
|
6606
7379
|
for (let j = 0; j < missKeys.length; j++) {
|
|
6607
|
-
const
|
|
6608
|
-
const
|
|
6609
|
-
|
|
6610
|
-
if (
|
|
6611
|
-
|
|
6612
|
-
|
|
6613
|
-
|
|
6614
|
-
|
|
6615
|
-
|
|
6616
|
-
|
|
6617
|
-
|
|
7380
|
+
const key = missKeys[j];
|
|
7381
|
+
const namespaced = this.nk(key);
|
|
7382
|
+
let promise = this.inflight.get(namespaced);
|
|
7383
|
+
if (!promise) {
|
|
7384
|
+
let resolve;
|
|
7385
|
+
let reject;
|
|
7386
|
+
promise = new Promise((yes, no) => {
|
|
7387
|
+
resolve = yes;
|
|
7388
|
+
reject = no;
|
|
7389
|
+
});
|
|
7390
|
+
owned.set(key, { promise, resolve, reject });
|
|
7391
|
+
this.inflight.set(namespaced, promise);
|
|
7392
|
+
} else {
|
|
7393
|
+
this.counters.stampedes++;
|
|
6618
7394
|
}
|
|
7395
|
+
const index = missIndexes[j];
|
|
7396
|
+
waiting.push(promise.then((value) => {
|
|
7397
|
+
result[index] = this._prepareReadValue(value);
|
|
7398
|
+
}));
|
|
6619
7399
|
}
|
|
6620
|
-
|
|
6621
|
-
|
|
7400
|
+
const settled = Promise.allSettled(waiting);
|
|
7401
|
+
try {
|
|
7402
|
+
if (owned.size > 0) {
|
|
7403
|
+
this.counters.fetches++;
|
|
7404
|
+
const fetched = await fetchFn([...owned.keys()]);
|
|
7405
|
+
await Promise.all([...owned].map(async ([key, entry]) => {
|
|
7406
|
+
const value = fetched instanceof Map ? fetched.get(key) : Object.hasOwn(fetched, key) ? fetched[key] : void 0;
|
|
7407
|
+
if (!this._destroyed && this._getKeyMutationEpoch(this.nk(key)) === epochs.get(this.nk(key))) {
|
|
7408
|
+
const resolvedTtl = value == null && this.opts.notFoundTtl > 0 ? this.opts.notFoundTtl : typeof ttl === "function" ? ttl(key) : ttl;
|
|
7409
|
+
if (value !== void 0 || this.opts.notFoundTtl > 0) await this.set(key, value === void 0 && this.opts.notFoundTtl > 0 ? null : value, resolvedTtl, priority);
|
|
7410
|
+
}
|
|
7411
|
+
entry.resolve(value);
|
|
7412
|
+
}));
|
|
7413
|
+
}
|
|
7414
|
+
const outcomes = await settled;
|
|
7415
|
+
const failed = outcomes.find((outcome) => outcome.status === "rejected");
|
|
7416
|
+
if (failed?.status === "rejected") throw failed.reason;
|
|
7417
|
+
} catch (error) {
|
|
7418
|
+
for (const entry of owned.values()) entry.reject(error);
|
|
7419
|
+
throw error;
|
|
7420
|
+
} finally {
|
|
7421
|
+
for (const [key, entry] of owned) {
|
|
7422
|
+
const namespaced = this.nk(key);
|
|
7423
|
+
if (this.inflight.get(namespaced) === entry.promise) this.inflight.delete(namespaced);
|
|
7424
|
+
}
|
|
6622
7425
|
}
|
|
6623
7426
|
}
|
|
6624
7427
|
if (this.opts.tracer) {
|
|
@@ -6671,7 +7474,7 @@ var CacheService = class _CacheService {
|
|
|
6671
7474
|
try {
|
|
6672
7475
|
await Promise.all(keys.map((key) => {
|
|
6673
7476
|
const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
|
|
6674
|
-
const hasOpts = tags
|
|
7477
|
+
const hasOpts = tags !== void 0 || dependsOn !== void 0;
|
|
6675
7478
|
return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
|
|
6676
7479
|
}));
|
|
6677
7480
|
} catch (err) {
|
|
@@ -6723,26 +7526,21 @@ var CacheService = class _CacheService {
|
|
|
6723
7526
|
try {
|
|
6724
7527
|
const client = await this.getRedis();
|
|
6725
7528
|
const nsPattern = this.nk(pattern);
|
|
6726
|
-
const matchedKeys = await this._scanKeys(client, nsPattern)
|
|
7529
|
+
const matchedKeys = (await this._scanKeys(client, nsPattern)).filter((key) => {
|
|
7530
|
+
const raw = this.unnk(key);
|
|
7531
|
+
return !raw.startsWith("_tag_:") && !raw.startsWith("tag_ver:") && !raw.startsWith("lock:") && key !== this.backplaneStreamKey;
|
|
7532
|
+
});
|
|
6727
7533
|
if (matchedKeys.length === 0) {
|
|
6728
7534
|
this.cb.onSuccess();
|
|
6729
7535
|
return 0;
|
|
6730
7536
|
}
|
|
6731
|
-
const
|
|
6732
|
-
|
|
6733
|
-
const results = await pl.exec();
|
|
6734
|
-
this.cb.onSuccess();
|
|
7537
|
+
const epochs = new Map(matchedKeys.map((key) => [key, this._getKeyMutationEpoch(key)]));
|
|
7538
|
+
const results = await this._readRedisBatch(client, matchedKeys);
|
|
6735
7539
|
let loaded = 0;
|
|
6736
|
-
for (
|
|
6737
|
-
const
|
|
6738
|
-
if (
|
|
6739
|
-
|
|
6740
|
-
const parsed = await this._decryptAndDeserialize(raw);
|
|
6741
|
-
const remainingMs = 10 * 60 * 1e3;
|
|
6742
|
-
this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
|
|
6743
|
-
loaded++;
|
|
6744
|
-
} catch {
|
|
6745
|
-
}
|
|
7540
|
+
for (const key of matchedKeys) {
|
|
7541
|
+
const entry = results.get(key);
|
|
7542
|
+
if (!entry || this._destroyed || this._getKeyMutationEpoch(key) !== epochs.get(key)) continue;
|
|
7543
|
+
if (this._promoteRedisEntry(key, entry, 10 * 60 * 1e3, opts?.priority ?? inferPriority(this.unnk(key))) && this.l1.has(key)) loaded++;
|
|
6746
7544
|
}
|
|
6747
7545
|
this.logger.info("warmFromL2 complete", {
|
|
6748
7546
|
pattern,
|
|
@@ -6829,14 +7627,7 @@ var CacheService = class _CacheService {
|
|
|
6829
7627
|
this._bumpKeyMutation(k);
|
|
6830
7628
|
this._removeKeyTags(k);
|
|
6831
7629
|
this._removeKeyDependencies(k);
|
|
6832
|
-
this.
|
|
6833
|
-
setImmediate(() => {
|
|
6834
|
-
try {
|
|
6835
|
-
if (!this._diskDisabled) this.disk.delete(k);
|
|
6836
|
-
} finally {
|
|
6837
|
-
this._pendingDiskDeletes.delete(k);
|
|
6838
|
-
}
|
|
6839
|
-
});
|
|
7630
|
+
this._invalidateDiskKey(k);
|
|
6840
7631
|
}
|
|
6841
7632
|
}
|
|
6842
7633
|
/**
|
|
@@ -6844,9 +7635,10 @@ var CacheService = class _CacheService {
|
|
|
6844
7635
|
* wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
|
|
6845
7636
|
*/
|
|
6846
7637
|
async _invalidateConcreteTag(tag) {
|
|
7638
|
+
this._fenceInvalidation();
|
|
6847
7639
|
if (this.opts.tagStrategy === "generational") {
|
|
6848
7640
|
let newVer = 1;
|
|
6849
|
-
if (!this._redisDisabled) {
|
|
7641
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
6850
7642
|
try {
|
|
6851
7643
|
const client = await this.getRedis();
|
|
6852
7644
|
newVer = await client.incr(this.nk(`tag_ver:${tag}`));
|
|
@@ -6864,19 +7656,23 @@ var CacheService = class _CacheService {
|
|
|
6864
7656
|
return;
|
|
6865
7657
|
}
|
|
6866
7658
|
const tagKey = this.nk(`_tag_:${tag}`);
|
|
6867
|
-
const members =
|
|
7659
|
+
const members = new Set(this.tagIndex.get(tagKey) ?? []);
|
|
6868
7660
|
this.tagIndex.delete(tagKey);
|
|
6869
7661
|
this._removeTagMembersLocal(members);
|
|
6870
|
-
if (!this._redisDisabled) {
|
|
7662
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
6871
7663
|
try {
|
|
6872
7664
|
const client = await this.getRedis();
|
|
6873
7665
|
const redisMembers = await client.smembers(tagKey);
|
|
7666
|
+
for (const key of redisMembers) members.add(key);
|
|
7667
|
+
this._removeTagMembersLocal(redisMembers);
|
|
6874
7668
|
const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers, tagKey])];
|
|
6875
7669
|
await this._deleteRedisKeys(client, toDelete);
|
|
6876
7670
|
} catch (err) {
|
|
6877
7671
|
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
6878
7672
|
}
|
|
6879
7673
|
}
|
|
7674
|
+
await Promise.all([...members].map((key) => this._publishTagInvalidation("del", key)));
|
|
7675
|
+
await this._publishTagInvalidation("tag_pattern_del", tag);
|
|
6880
7676
|
}
|
|
6881
7677
|
/**
|
|
6882
7678
|
* Executes invalidation for an array of already-resolved concrete tags
|
|
@@ -6888,9 +7684,10 @@ var CacheService = class _CacheService {
|
|
|
6888
7684
|
await this._invalidateConcreteTag(tags[0]);
|
|
6889
7685
|
return;
|
|
6890
7686
|
}
|
|
7687
|
+
this._fenceInvalidation();
|
|
6891
7688
|
if (this.opts.tagStrategy === "generational") {
|
|
6892
7689
|
const now = performance.now();
|
|
6893
|
-
if (!this._redisDisabled) {
|
|
7690
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
6894
7691
|
try {
|
|
6895
7692
|
const client = await this.getRedis();
|
|
6896
7693
|
const pl = client.pipeline();
|
|
@@ -6924,7 +7721,7 @@ var CacheService = class _CacheService {
|
|
|
6924
7721
|
this.tagIndex.delete(tagKey);
|
|
6925
7722
|
}
|
|
6926
7723
|
this._removeTagMembersLocal(allMembers);
|
|
6927
|
-
if (!this._redisDisabled) {
|
|
7724
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
6928
7725
|
try {
|
|
6929
7726
|
const client = await this.getRedis();
|
|
6930
7727
|
const pl = client.pipeline();
|
|
@@ -6935,15 +7732,19 @@ var CacheService = class _CacheService {
|
|
|
6935
7732
|
if (!err && redisMembers) {
|
|
6936
7733
|
for (const k of redisMembers) {
|
|
6937
7734
|
if (!allMembers.has(k)) toDelete.push(k);
|
|
7735
|
+
allMembers.add(k);
|
|
6938
7736
|
}
|
|
6939
7737
|
}
|
|
6940
7738
|
}
|
|
6941
7739
|
const keysToRemove = [...toDelete, ...tagKeys];
|
|
6942
7740
|
await this._deleteRedisKeys(client, keysToRemove);
|
|
7741
|
+
this._removeTagMembersLocal(allMembers);
|
|
6943
7742
|
} catch (err) {
|
|
6944
7743
|
this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
|
|
6945
7744
|
}
|
|
6946
7745
|
}
|
|
7746
|
+
await Promise.all([...allMembers].map((key) => this._publishTagInvalidation("del", key)));
|
|
7747
|
+
for (const tag of tags) await this._publishTagInvalidation("tag_pattern_del", tag);
|
|
6947
7748
|
}
|
|
6948
7749
|
/**
|
|
6949
7750
|
* Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
|
|
@@ -7097,19 +7898,23 @@ var CacheService = class _CacheService {
|
|
|
7097
7898
|
const diskLowSpace = !this._diskDisabled && this.disk.hostVolumeLowSpace;
|
|
7098
7899
|
const circuitOpen = this.cb.isOpen;
|
|
7099
7900
|
const latencyBypass = watchdogTel.bypassActive;
|
|
7100
|
-
const
|
|
7101
|
-
const
|
|
7901
|
+
const backplaneUnavailable = this.opts.invalidationBackplane && !this._redisDisabled && !this._backplaneAvailable;
|
|
7902
|
+
const degraded = this._destroyed || circuitOpen || latencyBypass || diskPruning || diskLowSpace || backplaneUnavailable;
|
|
7903
|
+
const healthy = !this._destroyed && (this.opts.failReadinessOnDegraded ? !degraded : true);
|
|
7102
7904
|
const reasons = [];
|
|
7103
7905
|
if (circuitOpen) reasons.push("redis_circuit_breaker_open");
|
|
7104
7906
|
if (latencyBypass) reasons.push(`disk_latency_bypass_stage_${watchdogTel.bypassStage}`);
|
|
7105
7907
|
if (diskPruning) reasons.push("disk_quota_watermark_pruning_active");
|
|
7106
7908
|
if (diskLowSpace) reasons.push("disk_host_volume_low_space");
|
|
7909
|
+
if (backplaneUnavailable) reasons.push("invalidation_backplane_unavailable");
|
|
7910
|
+
if (this._destroyed) reasons.push("cache_destroyed");
|
|
7107
7911
|
return {
|
|
7108
7912
|
healthy,
|
|
7109
7913
|
degraded,
|
|
7110
7914
|
reasons,
|
|
7111
7915
|
details: {
|
|
7112
|
-
redisConnected: !circuitOpen &&
|
|
7916
|
+
redisConnected: !this._destroyed && !circuitOpen && !!this.redis && (this.redis.status === "ready" || this.redis.isOpen === true),
|
|
7917
|
+
backplaneReady: this._backplaneAvailable,
|
|
7113
7918
|
circuitBreakerState: this.cb.currentState,
|
|
7114
7919
|
diskPruningActive: diskPruning,
|
|
7115
7920
|
diskHostVolumeLowSpace: diskLowSpace,
|
|
@@ -7131,23 +7936,28 @@ var CacheService = class _CacheService {
|
|
|
7131
7936
|
*/
|
|
7132
7937
|
async drainToL2() {
|
|
7133
7938
|
this._assertActive("drainToL2");
|
|
7134
|
-
if (this._redisDisabled) return 0;
|
|
7939
|
+
if (this._redisDisabled || this.opts.l2WriteMode === "read-only") return 0;
|
|
7135
7940
|
try {
|
|
7136
|
-
const client = await this.getRedis();
|
|
7137
7941
|
const entries = this.l1.exportEntries([]);
|
|
7138
|
-
const now = Date.now();
|
|
7139
7942
|
if (entries.length === 0) return 0;
|
|
7140
|
-
|
|
7141
|
-
|
|
7142
|
-
const
|
|
7143
|
-
if (
|
|
7144
|
-
|
|
7145
|
-
|
|
7146
|
-
|
|
7147
|
-
|
|
7148
|
-
|
|
7149
|
-
|
|
7150
|
-
|
|
7943
|
+
let written = 0;
|
|
7944
|
+
await Promise.all(entries.map(async ({ key, entry }) => {
|
|
7945
|
+
const epoch = this._getKeyMutationEpoch(key);
|
|
7946
|
+
if (entry.expiresAt <= Date.now()) return;
|
|
7947
|
+
await this._writeRedisEntry(
|
|
7948
|
+
key,
|
|
7949
|
+
this.l1.resolveValue(entry),
|
|
7950
|
+
entry.expiresAt,
|
|
7951
|
+
entry.setAt ?? Date.now(),
|
|
7952
|
+
entry.tagVersions,
|
|
7953
|
+
entry.staleAt,
|
|
7954
|
+
entry.tags,
|
|
7955
|
+
entry.dependsOn,
|
|
7956
|
+
() => this._getKeyMutationEpoch(key) === epoch
|
|
7957
|
+
);
|
|
7958
|
+
written++;
|
|
7959
|
+
}));
|
|
7960
|
+
return written;
|
|
7151
7961
|
} catch (err) {
|
|
7152
7962
|
this.logger.debug("drainToL2: Redis unavailable", { error: err.message });
|
|
7153
7963
|
return 0;
|
|
@@ -7177,7 +7987,7 @@ var CacheService = class _CacheService {
|
|
|
7177
7987
|
this._assertActive("setIfAbsent");
|
|
7178
7988
|
const k = this.nk(cacheKey);
|
|
7179
7989
|
if (this.l1.has(k)) return false;
|
|
7180
|
-
if (!this._redisDisabled) {
|
|
7990
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
7181
7991
|
try {
|
|
7182
7992
|
const client = await this.getRedis();
|
|
7183
7993
|
const serialized = JSON.stringify(value);
|
|
@@ -7194,7 +8004,7 @@ var CacheService = class _CacheService {
|
|
|
7194
8004
|
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
7195
8005
|
const p = priority ?? inferPriority(cacheKey);
|
|
7196
8006
|
this._bumpKeyMutation(k);
|
|
7197
|
-
this.
|
|
8007
|
+
this._invalidateDiskKey(k);
|
|
7198
8008
|
this.l1.set(k, value, ttlMs, p);
|
|
7199
8009
|
this.counters.sets++;
|
|
7200
8010
|
return true;
|
|
@@ -7221,7 +8031,7 @@ var CacheService = class _CacheService {
|
|
|
7221
8031
|
const token = crypto2.randomUUID();
|
|
7222
8032
|
const deadline = Date.now() + acquireTimeout;
|
|
7223
8033
|
let acquired = false;
|
|
7224
|
-
if (!this._redisDisabled) {
|
|
8034
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
7225
8035
|
let client = null;
|
|
7226
8036
|
try {
|
|
7227
8037
|
client = await this.getRedis();
|
|
@@ -7316,7 +8126,9 @@ var CacheService = class _CacheService {
|
|
|
7316
8126
|
const gDiskFiles = meter.createObservableGauge("tricache.disk.files", { description: "Current L1.5 disk file count" });
|
|
7317
8127
|
const gDiskBytes = meter.createObservableGauge("tricache.disk.bytes", { description: "Current L1.5 disk size in bytes" });
|
|
7318
8128
|
const gBloomFpr = meter.createObservableGauge("tricache.bloom.fpr", { description: "Bloom filter false-positive rate" });
|
|
7319
|
-
|
|
8129
|
+
const observables = [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr];
|
|
8130
|
+
const callback = (observableResult) => {
|
|
8131
|
+
if (this._destroyed) return;
|
|
7320
8132
|
const stats = this.stats();
|
|
7321
8133
|
const l1 = stats.l1;
|
|
7322
8134
|
const disk = stats.disk;
|
|
@@ -7329,7 +8141,9 @@ var CacheService = class _CacheService {
|
|
|
7329
8141
|
observableResult.observe(gDiskFiles, disk.files, attrs);
|
|
7330
8142
|
observableResult.observe(gDiskBytes, disk.sizeKB * 1024, attrs);
|
|
7331
8143
|
observableResult.observe(gBloomFpr, fpr, attrs);
|
|
7332
|
-
}
|
|
8144
|
+
};
|
|
8145
|
+
meter.addBatchObservableCallback(callback, observables);
|
|
8146
|
+
this._otelCleanup = () => meter.removeBatchObservableCallback?.(callback, observables);
|
|
7333
8147
|
} catch (err) {
|
|
7334
8148
|
this.logger.warn("Failed to initialize OpenTelemetry metrics meter", { error: err.message });
|
|
7335
8149
|
}
|
|
@@ -7599,6 +8413,16 @@ var CacheService = class _CacheService {
|
|
|
7599
8413
|
/** Close Redis connections and stop all background timers. */
|
|
7600
8414
|
async destroy() {
|
|
7601
8415
|
this._destroyed = true;
|
|
8416
|
+
this._fenceInvalidation();
|
|
8417
|
+
this._backplaneAvailable = false;
|
|
8418
|
+
this.l1.clear();
|
|
8419
|
+
try {
|
|
8420
|
+
this._otelCleanup?.();
|
|
8421
|
+
} catch {
|
|
8422
|
+
}
|
|
8423
|
+
this._otelCleanup = null;
|
|
8424
|
+
this.tagVersions.clear();
|
|
8425
|
+
for (const dispose of this._backplaneDisposers.splice(0)) dispose();
|
|
7602
8426
|
this._pendingDiskDeletes.clear();
|
|
7603
8427
|
this._keyMutationEpochs.clear();
|
|
7604
8428
|
this.inflight.clear();
|
|
@@ -7628,6 +8452,12 @@ var CacheService = class _CacheService {
|
|
|
7628
8452
|
this._workerPool = null;
|
|
7629
8453
|
}
|
|
7630
8454
|
if (this.subClient) {
|
|
8455
|
+
if (this.opts.redisSubClient) {
|
|
8456
|
+
try {
|
|
8457
|
+
await this.subClient.unsubscribe?.(this.backplaneChannel);
|
|
8458
|
+
} catch {
|
|
8459
|
+
}
|
|
8460
|
+
}
|
|
7631
8461
|
if (!this.opts.redisSubClient) {
|
|
7632
8462
|
try {
|
|
7633
8463
|
this.subClient.disconnect();
|
|
@@ -7637,7 +8467,7 @@ var CacheService = class _CacheService {
|
|
|
7637
8467
|
this.subClient = null;
|
|
7638
8468
|
}
|
|
7639
8469
|
if (this.streamClient) {
|
|
7640
|
-
try {
|
|
8470
|
+
if (!this.opts.redisSubClient) try {
|
|
7641
8471
|
this.streamClient.disconnect();
|
|
7642
8472
|
} catch {
|
|
7643
8473
|
}
|
|
@@ -7676,6 +8506,10 @@ var CacheService = class _CacheService {
|
|
|
7676
8506
|
export {
|
|
7677
8507
|
CacheCodec,
|
|
7678
8508
|
defaultCodec,
|
|
8509
|
+
createHttpMeshRelay,
|
|
8510
|
+
createCustomCrossRegionRelay,
|
|
8511
|
+
createMemoryCrossRegionRelay,
|
|
8512
|
+
createCrossRegionWebhookHandler,
|
|
7679
8513
|
TinyLfuSketch,
|
|
7680
8514
|
WTinyLfuCache,
|
|
7681
8515
|
WTinyLfuPolicy,
|