tricache 0.6.7 → 0.7.1
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/LICENSE +1 -1
- package/README.md +1428 -970
- package/bin/tricache.js +8 -0
- package/dist/cache-service-5GATUYAK.js +7 -0
- package/dist/cache-service-D8tIXmzb.d.ts +1498 -0
- package/dist/chunk-EUGYR7KR.js +4629 -0
- package/dist/chunk-UBSR5UYA.js +0 -0
- package/dist/{chunk-FKY5R3CE.js → chunk-X5AXHPVD.js} +139 -6
- package/dist/cli.cjs +5238 -0
- package/dist/cli.d.ts +11 -0
- package/dist/cli.js +130 -0
- package/dist/drizzle/index.cjs +5218 -0
- package/dist/drizzle/index.d.ts +44 -0
- package/dist/drizzle/index.js +46 -0
- package/dist/http/index.cjs +5374 -0
- package/dist/http/index.d.ts +33 -0
- package/dist/http/index.js +200 -0
- package/dist/index.cjs +1245 -209
- package/dist/index.d.ts +15 -1230
- package/dist/index.js +11 -3705
- package/dist/nestjs/index.cjs +5362 -0
- package/dist/nestjs/index.d.ts +210 -0
- package/dist/nestjs/index.js +250 -0
- package/dist/next/index.cjs +5407 -0
- package/dist/next/index.d.ts +208 -0
- package/dist/next/index.js +297 -0
- package/dist/prisma/index.cjs +123 -0
- package/dist/prisma/index.d.ts +60 -0
- package/dist/prisma/index.js +87 -0
- package/dist/serialize-worker.cjs +190 -15
- package/dist/serialize-worker.js +63 -12
- package/package.json +71 -21
- package/src/cache-service.ts +3294 -2429
- package/src/cli.ts +143 -0
- package/src/compression.ts +56 -0
- package/src/disk-tier.ts +821 -757
- package/src/drizzle/index.ts +86 -0
- package/src/encryption.ts +513 -442
- package/src/http/index.ts +265 -0
- package/src/index.ts +7 -0
- package/src/nestjs/decorators.ts +161 -0
- package/src/nestjs/index.ts +23 -0
- package/src/nestjs/tricache.module.ts +104 -0
- package/src/nestjs/tricache.store.ts +97 -0
- package/src/nestjs/types.ts +79 -0
- package/src/next/cache-handler.ts +268 -0
- package/src/next/index.ts +37 -0
- package/src/next/isr-handler.ts +105 -0
- package/src/next/types.ts +130 -0
- package/src/prisma/index.ts +154 -0
- package/src/serialize-worker.ts +77 -13
- package/src/smart-memory-cache.ts +1026 -1010
- package/src/types.ts +911 -732
- package/src/wasm/bloom-filter-wasm.ts +3 -2
- package/src/worker-pool.ts +156 -42
|
@@ -0,0 +1,4629 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CacheEncryption,
|
|
3
|
+
PREFIX_COMPRESSED,
|
|
4
|
+
PREFIX_ENC_COMPRESSED,
|
|
5
|
+
compressBuffer,
|
|
6
|
+
compressWithHeader,
|
|
7
|
+
consoleLogger,
|
|
8
|
+
decompressBuffer,
|
|
9
|
+
decompressWithHeader
|
|
10
|
+
} from "./chunk-X5AXHPVD.js";
|
|
11
|
+
|
|
12
|
+
// src/cache-service.ts
|
|
13
|
+
import { Redis as RedisClient, Cluster as RedisCluster } from "ioredis";
|
|
14
|
+
import { pack as pack3, unpack as unpack3 } from "msgpackr";
|
|
15
|
+
import crypto2 from "crypto";
|
|
16
|
+
import os2 from "os";
|
|
17
|
+
|
|
18
|
+
// src/worker-pool.ts
|
|
19
|
+
import { Worker } from "worker_threads";
|
|
20
|
+
import { fileURLToPath } from "url";
|
|
21
|
+
import { dirname, join } from "path";
|
|
22
|
+
import os from "os";
|
|
23
|
+
import { existsSync } from "fs";
|
|
24
|
+
var _workerFile;
|
|
25
|
+
var _workerExecArgv = [];
|
|
26
|
+
try {
|
|
27
|
+
const dir = dirname(fileURLToPath(import.meta.url));
|
|
28
|
+
const jsPath = join(dir, "serialize-worker.js");
|
|
29
|
+
const tsPath = join(dir, "serialize-worker.ts");
|
|
30
|
+
if (existsSync(jsPath)) {
|
|
31
|
+
_workerFile = jsPath;
|
|
32
|
+
} else if (existsSync(tsPath)) {
|
|
33
|
+
_workerFile = tsPath;
|
|
34
|
+
_workerExecArgv = ["--import", "tsx"];
|
|
35
|
+
} else {
|
|
36
|
+
_workerFile = jsPath;
|
|
37
|
+
}
|
|
38
|
+
} catch {
|
|
39
|
+
_workerFile = join(__dirname, "serialize-worker.js");
|
|
40
|
+
}
|
|
41
|
+
function getTransferableArrayBuffer(buf) {
|
|
42
|
+
if (buf.buffer instanceof ArrayBuffer) {
|
|
43
|
+
if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) {
|
|
44
|
+
return buf.buffer;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (buf.byteLength >= 131072) {
|
|
48
|
+
const copy = new ArrayBuffer(buf.byteLength);
|
|
49
|
+
new Uint8Array(copy).set(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));
|
|
50
|
+
return copy;
|
|
51
|
+
}
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
var WorkerPool = class {
|
|
55
|
+
workers = [];
|
|
56
|
+
pending = [];
|
|
57
|
+
_nextId = 0;
|
|
58
|
+
_robin = 0;
|
|
59
|
+
_available = false;
|
|
60
|
+
constructor(opts) {
|
|
61
|
+
try {
|
|
62
|
+
const { workers, pending } = this._spawnWorkers(opts);
|
|
63
|
+
this.workers = workers;
|
|
64
|
+
this.pending = pending;
|
|
65
|
+
this._available = true;
|
|
66
|
+
} catch {
|
|
67
|
+
this._destroy();
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
_spawnWorkers(opts) {
|
|
71
|
+
const size = Math.max(1, opts.size ?? Math.min(4, availableCpus()));
|
|
72
|
+
const workerData = {
|
|
73
|
+
keyBase64: opts.keyBase64,
|
|
74
|
+
mode: opts.mode,
|
|
75
|
+
prevKeyBase64: opts.prevKeyBase64 ?? "",
|
|
76
|
+
prevMode: opts.prevMode,
|
|
77
|
+
compression: opts.compression ?? "none",
|
|
78
|
+
compressionThresholdBytes: opts.compressionThresholdBytes ?? 1024
|
|
79
|
+
};
|
|
80
|
+
const workers = [];
|
|
81
|
+
const pendingList = [];
|
|
82
|
+
const createWorker = (index) => {
|
|
83
|
+
const worker = new Worker(_workerFile, {
|
|
84
|
+
workerData,
|
|
85
|
+
execArgv: _workerExecArgv.length > 0 ? _workerExecArgv : void 0
|
|
86
|
+
});
|
|
87
|
+
const pending = pendingList[index] ?? /* @__PURE__ */ new Map();
|
|
88
|
+
if (!pendingList[index]) pendingList[index] = pending;
|
|
89
|
+
worker.on("message", (msg) => {
|
|
90
|
+
const entry = pending.get(msg.id);
|
|
91
|
+
if (!entry) return;
|
|
92
|
+
pending.delete(msg.id);
|
|
93
|
+
if (pending.size === 0) worker.unref();
|
|
94
|
+
if (msg.error !== void 0) {
|
|
95
|
+
entry.reject(new Error(msg.error));
|
|
96
|
+
} else if (msg.result !== void 0) {
|
|
97
|
+
if (typeof msg.result === "string") {
|
|
98
|
+
entry.resolve(msg.result);
|
|
99
|
+
} else {
|
|
100
|
+
entry.resolve(Buffer.from(msg.result.buffer, msg.result.byteOffset, msg.result.byteLength).toString("utf8"));
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
worker.on("error", (err) => {
|
|
105
|
+
for (const [, entry] of pending) entry.reject(err);
|
|
106
|
+
pending.clear();
|
|
107
|
+
worker.unref();
|
|
108
|
+
});
|
|
109
|
+
worker.on("exit", (exitCode) => {
|
|
110
|
+
for (const [, entry] of pending) {
|
|
111
|
+
entry.reject(new Error(`Worker thread exited unexpectedly with code ${exitCode}`));
|
|
112
|
+
}
|
|
113
|
+
pending.clear();
|
|
114
|
+
worker.unref();
|
|
115
|
+
if (this._available && exitCode !== 0 && workers[index] === worker) {
|
|
116
|
+
try {
|
|
117
|
+
workers[index] = createWorker(index);
|
|
118
|
+
} catch {
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
worker.unref();
|
|
123
|
+
return worker;
|
|
124
|
+
};
|
|
125
|
+
for (let i = 0; i < size; i++) {
|
|
126
|
+
const worker = createWorker(i);
|
|
127
|
+
workers.push(worker);
|
|
128
|
+
}
|
|
129
|
+
return { workers, pending: pendingList };
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Gracefully drain in-flight tasks and re-initialize workers with updated key material.
|
|
133
|
+
* Atomically swaps workers so new requests immediately route to new workers,
|
|
134
|
+
* while existing in-flight operations complete on old workers before termination.
|
|
135
|
+
*/
|
|
136
|
+
async drainAndReinit(opts) {
|
|
137
|
+
const { workers: newWorkers, pending: newPending } = this._spawnWorkers(opts);
|
|
138
|
+
const oldWorkers = this.workers;
|
|
139
|
+
const oldPending = this.pending;
|
|
140
|
+
this.workers = newWorkers;
|
|
141
|
+
this.pending = newPending;
|
|
142
|
+
this._robin = 0;
|
|
143
|
+
this._available = true;
|
|
144
|
+
const start = Date.now();
|
|
145
|
+
while (oldPending.some((m) => m.size > 0)) {
|
|
146
|
+
if (Date.now() - start > 5e3) break;
|
|
147
|
+
await new Promise((r) => setTimeout(r, 10));
|
|
148
|
+
}
|
|
149
|
+
for (let i = 0; i < oldWorkers.length; i++) {
|
|
150
|
+
for (const [, entry] of oldPending[i] ?? []) {
|
|
151
|
+
entry.reject(new Error("WorkerPool replaced during key rotation"));
|
|
152
|
+
}
|
|
153
|
+
oldPending[i]?.clear();
|
|
154
|
+
oldWorkers[i]?.terminate().catch(() => {
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
get isAvailable() {
|
|
159
|
+
return this._available;
|
|
160
|
+
}
|
|
161
|
+
/** Encrypt a string or buffer in a worker thread. Returns the encrypted envelope string. */
|
|
162
|
+
encrypt(payload) {
|
|
163
|
+
return this._dispatch("encrypt", payload);
|
|
164
|
+
}
|
|
165
|
+
/** Decrypt an encrypted envelope string or buffer in a worker thread. Returns the original JSON string. */
|
|
166
|
+
decrypt(payload) {
|
|
167
|
+
return this._dispatch("decrypt", payload);
|
|
168
|
+
}
|
|
169
|
+
_dispatch(type, payload) {
|
|
170
|
+
if (!this._available || this.workers.length === 0) {
|
|
171
|
+
return Promise.reject(new Error("WorkerPool is not available"));
|
|
172
|
+
}
|
|
173
|
+
const id = this._nextId++;
|
|
174
|
+
const idx = this._robin;
|
|
175
|
+
const worker = this.workers[idx];
|
|
176
|
+
const pending = this.pending[idx];
|
|
177
|
+
this._robin = (this._robin + 1) % this.workers.length;
|
|
178
|
+
let transferable = null;
|
|
179
|
+
let dataToSend = typeof payload === "string" ? payload : payload;
|
|
180
|
+
if (typeof payload !== "string") {
|
|
181
|
+
transferable = getTransferableArrayBuffer(payload);
|
|
182
|
+
if (transferable) {
|
|
183
|
+
dataToSend = new Uint8Array(transferable);
|
|
184
|
+
}
|
|
185
|
+
} else if (payload.length >= 131072) {
|
|
186
|
+
const buf = Buffer.from(payload, "utf8");
|
|
187
|
+
transferable = getTransferableArrayBuffer(buf);
|
|
188
|
+
if (transferable) {
|
|
189
|
+
dataToSend = new Uint8Array(transferable);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
const transferList = transferable ? [transferable] : [];
|
|
193
|
+
return new Promise((resolve, reject) => {
|
|
194
|
+
pending.set(id, { resolve, reject });
|
|
195
|
+
worker.ref();
|
|
196
|
+
worker.postMessage({ id, type, payload: dataToSend }, transferList);
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
/** Terminate all worker threads. In-flight promises are rejected. */
|
|
200
|
+
async destroy() {
|
|
201
|
+
this._available = false;
|
|
202
|
+
this._destroy();
|
|
203
|
+
}
|
|
204
|
+
_destroy() {
|
|
205
|
+
for (let i = 0; i < this.workers.length; i++) {
|
|
206
|
+
for (const [, entry] of this.pending[i] ?? []) {
|
|
207
|
+
entry.reject(new Error("WorkerPool destroyed"));
|
|
208
|
+
}
|
|
209
|
+
this.pending[i]?.clear();
|
|
210
|
+
this.workers[i]?.terminate().catch(() => {
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
function availableCpus() {
|
|
216
|
+
return os.availableParallelism?.() ?? os.cpus().length;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// src/cache-service.ts
|
|
220
|
+
import v8 from "v8";
|
|
221
|
+
import fs2 from "fs";
|
|
222
|
+
import path2 from "path";
|
|
223
|
+
|
|
224
|
+
// src/smart-memory-cache.ts
|
|
225
|
+
import { pack, unpack } from "msgpackr";
|
|
226
|
+
|
|
227
|
+
// src/wasm/bloom-filter-wasm.ts
|
|
228
|
+
var BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
|
|
229
|
+
var KEY_STAGING_OFFSET = 2e4;
|
|
230
|
+
var MAX_KEY_BYTES = 512;
|
|
231
|
+
var BLOOM_WASM_MODULE = new WebAssembly.Module(Buffer.from(BLOOM_WASM_BASE64, "base64"));
|
|
232
|
+
var WasmBloomFilter = class {
|
|
233
|
+
exports;
|
|
234
|
+
mem;
|
|
235
|
+
stagingTarget;
|
|
236
|
+
encoder = new TextEncoder();
|
|
237
|
+
numBits = 1e5;
|
|
238
|
+
/** Pre-computed — k and numBits are fixed constants; no need to recalculate on every probe. */
|
|
239
|
+
_maxCapacity;
|
|
240
|
+
/** Tracks total add() calls so we know when phantom bits have saturated the filter. */
|
|
241
|
+
_insertionCount = 0;
|
|
242
|
+
constructor() {
|
|
243
|
+
const instance = new WebAssembly.Instance(BLOOM_WASM_MODULE, {});
|
|
244
|
+
this.exports = instance.exports;
|
|
245
|
+
this.mem = new Uint8Array(this.exports.memory.buffer);
|
|
246
|
+
this.stagingTarget = new Uint8Array(this.exports.memory.buffer, KEY_STAGING_OFFSET, MAX_KEY_BYTES);
|
|
247
|
+
const k = 7, p = 0.01;
|
|
248
|
+
this._maxCapacity = Math.floor(-this.numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
|
|
249
|
+
}
|
|
250
|
+
writeKey(key) {
|
|
251
|
+
if (key.length === 0) return 0;
|
|
252
|
+
return this.encoder.encodeInto(key, this.stagingTarget).written;
|
|
253
|
+
}
|
|
254
|
+
add(key) {
|
|
255
|
+
const len = this.writeKey(key);
|
|
256
|
+
if (len === 0) return;
|
|
257
|
+
this.exports.add(KEY_STAGING_OFFSET, len);
|
|
258
|
+
this._insertionCount++;
|
|
259
|
+
}
|
|
260
|
+
mightContain(key) {
|
|
261
|
+
const len = this.writeKey(key);
|
|
262
|
+
if (len === 0) return true;
|
|
263
|
+
return this.exports.mightContain(KEY_STAGING_OFFSET, len) === 1;
|
|
264
|
+
}
|
|
265
|
+
reset() {
|
|
266
|
+
this.exports.reset();
|
|
267
|
+
this._insertionCount = 0;
|
|
268
|
+
}
|
|
269
|
+
rebuild(keys) {
|
|
270
|
+
this.reset();
|
|
271
|
+
for (const key of keys) this.add(key);
|
|
272
|
+
}
|
|
273
|
+
get stats() {
|
|
274
|
+
const bitsSet = this.exports.countBits();
|
|
275
|
+
return { bitsSet, fillFactor: bitsSet / this.numBits };
|
|
276
|
+
}
|
|
277
|
+
/** Number of add() calls since last reset/rebuild. */
|
|
278
|
+
get insertions() {
|
|
279
|
+
return this._insertionCount;
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Maximum safe insertions before false-positive rate exceeds ~1 %.
|
|
283
|
+
* Exact formula for k=7 hash rounds, m=100 000 bits, p=1%:
|
|
284
|
+
* n_max = -m * ln(1 - p^(1/k)) / k ≈ 10 434
|
|
285
|
+
*/
|
|
286
|
+
get maxCapacity() {
|
|
287
|
+
return this._maxCapacity;
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
|
|
291
|
+
// src/smart-memory-cache.ts
|
|
292
|
+
var LARGE_VALUE_BYTES = 16384;
|
|
293
|
+
var EVICTION_BATCH_PERCENT = 0.2;
|
|
294
|
+
var EVICTION_SAMPLE = 16;
|
|
295
|
+
var EVICT_COUNT = Math.max(1, Math.ceil(EVICTION_SAMPLE * EVICTION_BATCH_PERCENT));
|
|
296
|
+
var JsBloomFilter = class {
|
|
297
|
+
bits;
|
|
298
|
+
numBits;
|
|
299
|
+
k;
|
|
300
|
+
/** Pre-computed — numBits and k are constant, no need to recalculate on every probe. */
|
|
301
|
+
_maxCapacity;
|
|
302
|
+
/** Tracks total add() calls so we know when phantom bits have saturated the filter. */
|
|
303
|
+
_insertionCount = 0;
|
|
304
|
+
constructor(numBits = 1e5, k = 7) {
|
|
305
|
+
this.numBits = numBits;
|
|
306
|
+
this.k = k;
|
|
307
|
+
this.bits = Buffer.alloc(Math.ceil(numBits / 8), 0);
|
|
308
|
+
const p = 0.01;
|
|
309
|
+
this._maxCapacity = Math.floor(-numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
|
|
310
|
+
}
|
|
311
|
+
fnv1a32(s) {
|
|
312
|
+
let h = 2166136261;
|
|
313
|
+
for (let i = 0; i < s.length; i++) {
|
|
314
|
+
h ^= s.charCodeAt(i);
|
|
315
|
+
h = Math.imul(h, 16777619) >>> 0;
|
|
316
|
+
}
|
|
317
|
+
return h >>> 0;
|
|
318
|
+
}
|
|
319
|
+
djb2(s) {
|
|
320
|
+
let h = 5381;
|
|
321
|
+
for (let i = 0; i < s.length; i++) h = (h << 5) + h + s.charCodeAt(i) >>> 0;
|
|
322
|
+
return h >>> 0;
|
|
323
|
+
}
|
|
324
|
+
setBit(i) {
|
|
325
|
+
this.bits[i >>> 3] |= 1 << (i & 7);
|
|
326
|
+
}
|
|
327
|
+
getBit(i) {
|
|
328
|
+
return (this.bits[i >>> 3] & 1 << (i & 7)) !== 0;
|
|
329
|
+
}
|
|
330
|
+
add(key) {
|
|
331
|
+
const h1 = this.fnv1a32(key), h2 = this.djb2(key);
|
|
332
|
+
for (let i = 0; i < this.k; i++) this.setBit((h1 + i * h2 >>> 0) % this.numBits);
|
|
333
|
+
this._insertionCount++;
|
|
334
|
+
}
|
|
335
|
+
mightContain(key) {
|
|
336
|
+
const h1 = this.fnv1a32(key), h2 = this.djb2(key);
|
|
337
|
+
for (let i = 0; i < this.k; i++) if (!this.getBit((h1 + i * h2 >>> 0) % this.numBits)) return false;
|
|
338
|
+
return true;
|
|
339
|
+
}
|
|
340
|
+
reset() {
|
|
341
|
+
this.bits.fill(0);
|
|
342
|
+
this._insertionCount = 0;
|
|
343
|
+
}
|
|
344
|
+
rebuild(keys) {
|
|
345
|
+
this.bits.fill(0);
|
|
346
|
+
this._insertionCount = 0;
|
|
347
|
+
for (const k of keys) this.add(k);
|
|
348
|
+
}
|
|
349
|
+
/** Number of add() calls since last reset/rebuild. */
|
|
350
|
+
get insertions() {
|
|
351
|
+
return this._insertionCount;
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* Maximum safe insertions before false-positive rate exceeds ~1 %.
|
|
355
|
+
* Exact formula for the configured k and target p=1 %:
|
|
356
|
+
* n_max = -m * ln(1 - p^(1/k)) / k
|
|
357
|
+
*/
|
|
358
|
+
get maxCapacity() {
|
|
359
|
+
return this._maxCapacity;
|
|
360
|
+
}
|
|
361
|
+
get stats() {
|
|
362
|
+
let bitsSet = 0;
|
|
363
|
+
for (const byte of this.bits) {
|
|
364
|
+
let b = byte;
|
|
365
|
+
while (b) {
|
|
366
|
+
bitsSet++;
|
|
367
|
+
b &= b - 1;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
return { bitsSet, fillFactor: bitsSet / this.numBits };
|
|
371
|
+
}
|
|
372
|
+
};
|
|
373
|
+
function createBloomFilter(logger, maxEntries) {
|
|
374
|
+
const LN2_SQ = Math.LN2 * Math.LN2;
|
|
375
|
+
const optimalBits = Math.ceil(-maxEntries * Math.log(0.01) / LN2_SQ);
|
|
376
|
+
const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / maxEntries)));
|
|
377
|
+
try {
|
|
378
|
+
const wasm = new WasmBloomFilter();
|
|
379
|
+
if (wasm.maxCapacity >= maxEntries) {
|
|
380
|
+
logger.debug("SmartMemoryCache: WASM BloomFilter active");
|
|
381
|
+
return wasm;
|
|
382
|
+
}
|
|
383
|
+
logger.debug("SmartMemoryCache: WASM BloomFilter capacity too small, using sized JS BloomFilter", {
|
|
384
|
+
wasmCapacity: wasm.maxCapacity,
|
|
385
|
+
maxEntries,
|
|
386
|
+
optimalBits
|
|
387
|
+
});
|
|
388
|
+
} catch (err) {
|
|
389
|
+
logger.debug("SmartMemoryCache: WASM unavailable \u2014 using pure-JS BloomFilter", { reason: err.message });
|
|
390
|
+
}
|
|
391
|
+
return new JsBloomFilter(optimalBits, optimalK);
|
|
392
|
+
}
|
|
393
|
+
var SKETCH_ROWS = 4;
|
|
394
|
+
var SKETCH_WIDTH = 512;
|
|
395
|
+
var SKETCH_MASK = SKETCH_WIDTH - 1;
|
|
396
|
+
var SKETCH_DECAY_THRESHOLD = 1e5;
|
|
397
|
+
var CountMinSketch = class {
|
|
398
|
+
table = new Uint16Array(SKETCH_ROWS * SKETCH_WIDTH);
|
|
399
|
+
inserts = 0;
|
|
400
|
+
/** Inline FNV-1a for a string key → 32-bit unsigned integer. */
|
|
401
|
+
fnv32(key) {
|
|
402
|
+
let h = 2166136261;
|
|
403
|
+
for (let i = 0; i < key.length; i++) {
|
|
404
|
+
h ^= key.charCodeAt(i);
|
|
405
|
+
h = Math.imul(h, 16777619) >>> 0;
|
|
406
|
+
}
|
|
407
|
+
return h;
|
|
408
|
+
}
|
|
409
|
+
/** Record one access. Decays all counters when the insertion threshold is crossed. */
|
|
410
|
+
increment(key) {
|
|
411
|
+
const h = this.fnv32(key);
|
|
412
|
+
const h1 = (h ^ h >>> 16) >>> 0;
|
|
413
|
+
const h2 = (Math.imul(h1, 73244475) ^ h1 >>> 16) >>> 0;
|
|
414
|
+
const h3 = (Math.imul(h2, 2142877601) ^ h2 >>> 16) >>> 0;
|
|
415
|
+
const h4 = (Math.imul(h3, 461845907) ^ h3 >>> 16) >>> 0;
|
|
416
|
+
const t = this.table;
|
|
417
|
+
const i0 = h1 & SKETCH_MASK;
|
|
418
|
+
const i1 = SKETCH_WIDTH + (h2 & SKETCH_MASK);
|
|
419
|
+
const i2 = 2 * SKETCH_WIDTH + (h3 & SKETCH_MASK);
|
|
420
|
+
const i3 = 3 * SKETCH_WIDTH + (h4 & SKETCH_MASK);
|
|
421
|
+
if (t[i0] < 65535) t[i0]++;
|
|
422
|
+
if (t[i1] < 65535) t[i1]++;
|
|
423
|
+
if (t[i2] < 65535) t[i2]++;
|
|
424
|
+
if (t[i3] < 65535) t[i3]++;
|
|
425
|
+
if (++this.inserts >= SKETCH_DECAY_THRESHOLD) this.decay();
|
|
426
|
+
}
|
|
427
|
+
/** Minimum-across-rows frequency estimate. */
|
|
428
|
+
estimate(key) {
|
|
429
|
+
const h = this.fnv32(key);
|
|
430
|
+
const h1 = (h ^ h >>> 16) >>> 0;
|
|
431
|
+
const h2 = (Math.imul(h1, 73244475) ^ h1 >>> 16) >>> 0;
|
|
432
|
+
const h3 = (Math.imul(h2, 2142877601) ^ h2 >>> 16) >>> 0;
|
|
433
|
+
const h4 = (Math.imul(h3, 461845907) ^ h3 >>> 16) >>> 0;
|
|
434
|
+
const t = this.table;
|
|
435
|
+
return Math.min(
|
|
436
|
+
t[h1 & SKETCH_MASK],
|
|
437
|
+
t[SKETCH_WIDTH + (h2 & SKETCH_MASK)],
|
|
438
|
+
t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)],
|
|
439
|
+
t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)]
|
|
440
|
+
);
|
|
441
|
+
}
|
|
442
|
+
/** Halve all counters — ages out old frequency so bursts don't hold indefinitely. */
|
|
443
|
+
decay() {
|
|
444
|
+
for (let i = 0; i < this.table.length; i++) this.table[i] >>>= 1;
|
|
445
|
+
this.inserts = 0;
|
|
446
|
+
}
|
|
447
|
+
};
|
|
448
|
+
function globMatchParts(parts, first, last, key) {
|
|
449
|
+
if (first.length > 0 && !key.startsWith(first)) return false;
|
|
450
|
+
if (last.length > 0 && !key.endsWith(last)) return false;
|
|
451
|
+
if (first.length + last.length > key.length) return false;
|
|
452
|
+
let pos = first.length;
|
|
453
|
+
const end = key.length - last.length;
|
|
454
|
+
for (let i = 1; i < parts.length - 1; i++) {
|
|
455
|
+
const seg = parts[i];
|
|
456
|
+
if (seg.length === 0) continue;
|
|
457
|
+
const idx = key.indexOf(seg, pos);
|
|
458
|
+
if (idx === -1 || idx + seg.length > end) return false;
|
|
459
|
+
pos = idx + seg.length;
|
|
460
|
+
}
|
|
461
|
+
return true;
|
|
462
|
+
}
|
|
463
|
+
var SmartMemoryCache = class {
|
|
464
|
+
cache = /* @__PURE__ */ new Map();
|
|
465
|
+
opts;
|
|
466
|
+
bloom;
|
|
467
|
+
/** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
|
|
468
|
+
categoryPrefixes;
|
|
469
|
+
/** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
|
|
470
|
+
sketch = new CountMinSketch();
|
|
471
|
+
totalSize = 0;
|
|
472
|
+
categoryCount = /* @__PURE__ */ new Map();
|
|
473
|
+
categorySize = /* @__PURE__ */ new Map();
|
|
474
|
+
/** Per-category key sets — enables O(catSize) Phase-1 reservoir sampling without an O(N) scan. */
|
|
475
|
+
categoryKeys = /* @__PURE__ */ new Map();
|
|
476
|
+
// ── Observability counters ──────────────────────────────────────────────────────
|
|
477
|
+
bloomChecks = 0;
|
|
478
|
+
bloomFalsePos = 0;
|
|
479
|
+
compressions = 0;
|
|
480
|
+
categoryHits = /* @__PURE__ */ new Map();
|
|
481
|
+
/** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
|
|
482
|
+
_bloomDirtyCount = 0;
|
|
483
|
+
/**
|
|
484
|
+
* Pre-allocated eviction candidate pools — reused across every smartEvict() call to
|
|
485
|
+
* eliminate per-call heap pressure. Each slot holds a mutable {key, score} record
|
|
486
|
+
* that is overwritten in-place rather than replaced with a new object literal.
|
|
487
|
+
* Safe because JS is single-threaded: smartEvict() completes synchronously before
|
|
488
|
+
* any other code can observe the pool state.
|
|
489
|
+
*/
|
|
490
|
+
_evictPool = Array.from({ length: EVICTION_SAMPLE }, () => ({ key: "", score: 0 }));
|
|
491
|
+
_evictGPool = Array.from({ length: EVICTION_SAMPLE }, () => ({ key: "", score: 0 }));
|
|
492
|
+
constructor(opts, existing) {
|
|
493
|
+
this.opts = opts;
|
|
494
|
+
this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
|
|
495
|
+
this.categoryPrefixes = Object.keys(opts.categories).filter((k) => k !== "default");
|
|
496
|
+
if (existing) {
|
|
497
|
+
for (const [k, v] of existing) this.cache.set(k, v);
|
|
498
|
+
this.recalculateStats();
|
|
499
|
+
for (const key of this.cache.keys()) this.bloom.add(key);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
// ── Internal helpers ──────────────────────────────────────────────────────
|
|
503
|
+
recalculateStats() {
|
|
504
|
+
this.totalSize = 0;
|
|
505
|
+
this.categoryCount.clear();
|
|
506
|
+
this.categorySize.clear();
|
|
507
|
+
this.categoryKeys.clear();
|
|
508
|
+
for (const [key, entry] of this.cache) {
|
|
509
|
+
this.totalSize += entry.size;
|
|
510
|
+
const cat = this.getCategory(key);
|
|
511
|
+
this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
|
|
512
|
+
this.categorySize.set(cat, (this.categorySize.get(cat) ?? 0) + entry.size);
|
|
513
|
+
let ks = this.categoryKeys.get(cat);
|
|
514
|
+
if (!ks) {
|
|
515
|
+
ks = /* @__PURE__ */ new Set();
|
|
516
|
+
this.categoryKeys.set(cat, ks);
|
|
517
|
+
}
|
|
518
|
+
ks.add(key);
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
getCategory(key) {
|
|
522
|
+
for (const prefix of this.categoryPrefixes) {
|
|
523
|
+
if (key.startsWith(prefix)) return prefix;
|
|
524
|
+
}
|
|
525
|
+
return "default";
|
|
526
|
+
}
|
|
527
|
+
getCategoryLimit(cat) {
|
|
528
|
+
return this.opts.categories[cat] ?? this.opts.categories["default"] ?? { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 };
|
|
529
|
+
}
|
|
530
|
+
_delete(key, reason = "manual") {
|
|
531
|
+
const entry = this.cache.get(key);
|
|
532
|
+
if (!entry) return false;
|
|
533
|
+
const cat = this.getCategory(key);
|
|
534
|
+
this.totalSize -= entry.size;
|
|
535
|
+
this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
|
|
536
|
+
this.categorySize.set(cat, (this.categorySize.get(cat) ?? entry.size) - entry.size);
|
|
537
|
+
this.categoryKeys.get(cat)?.delete(key);
|
|
538
|
+
this._bloomDirtyCount++;
|
|
539
|
+
const deleted = this.cache.delete(key);
|
|
540
|
+
if (deleted && this.opts.onEviction) {
|
|
541
|
+
try {
|
|
542
|
+
this.opts.onEviction(key, reason);
|
|
543
|
+
} catch {
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
return deleted;
|
|
547
|
+
}
|
|
548
|
+
ensureCapacity(category, neededSize) {
|
|
549
|
+
const lim = this.getCategoryLimit(category);
|
|
550
|
+
const catCnt = this.categoryCount.get(category) ?? 0;
|
|
551
|
+
const catSz = this.categorySize.get(category) ?? 0;
|
|
552
|
+
let catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
|
|
553
|
+
let glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
|
|
554
|
+
if (!catOvf && !glbOvf) {
|
|
555
|
+
const wm = this.opts.evictionWatermark ?? 0.9;
|
|
556
|
+
const entryWatermark = this.cache.size >= Math.floor(this.opts.maxEntries * wm);
|
|
557
|
+
const byteWatermark = this.totalSize + neededSize >= Math.floor(this.opts.maxBytes * wm);
|
|
558
|
+
if (entryWatermark || byteWatermark) {
|
|
559
|
+
this.smartEvict(category, false);
|
|
560
|
+
}
|
|
561
|
+
return;
|
|
562
|
+
}
|
|
563
|
+
const MAX_EVICT_PASSES = 64;
|
|
564
|
+
let passes = 0;
|
|
565
|
+
do {
|
|
566
|
+
this.smartEvict(category, catOvf);
|
|
567
|
+
const lim2 = this.getCategoryLimit(category);
|
|
568
|
+
const catCnt2 = this.categoryCount.get(category) ?? 0;
|
|
569
|
+
const catSz2 = this.categorySize.get(category) ?? 0;
|
|
570
|
+
catOvf = catCnt2 >= lim2.maxEntries || catSz2 + neededSize > lim2.maxSizeBytes;
|
|
571
|
+
glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
|
|
572
|
+
passes++;
|
|
573
|
+
} while ((catOvf || glbOvf) && passes < MAX_EVICT_PASSES);
|
|
574
|
+
}
|
|
575
|
+
score(entry, catBonus, now, key) {
|
|
576
|
+
const age = now - entry.lastAccess;
|
|
577
|
+
const ttl = Math.max(0, entry.expiresAt - now);
|
|
578
|
+
const freq = Math.min(Math.max(entry.hits, this.sketch.estimate(key)), 100);
|
|
579
|
+
return entry.priority * 1e3 + freq * 10 + ttl / 6e4 - age / 6e4 - catBonus;
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* Rebuild the bloom filter when phantom bits from deleted/expired keys have
|
|
583
|
+
* saturated the filter past its ~1 % FP capacity.
|
|
584
|
+
*
|
|
585
|
+
* Trigger: (insertions − live entries) > maxCapacity
|
|
586
|
+
*
|
|
587
|
+
* Using the phantom count (insertions − cache.size) instead of raw insertions
|
|
588
|
+
* prevents an O(cache.size) rebuild from re-firing on every set() when the
|
|
589
|
+
* cache holds more entries than the filter's rated capacity — which would
|
|
590
|
+
* stall the write path entirely.
|
|
591
|
+
*
|
|
592
|
+
* After rebuild: insertions = cache.size → phantoms = 0 → no immediate re-trigger.
|
|
593
|
+
*/
|
|
594
|
+
maybeRebuildBloom() {
|
|
595
|
+
const dirtyThreshold = Math.max(256, Math.min(this.bloom.maxCapacity >>> 2, Math.ceil(this.opts.maxEntries * 0.05)));
|
|
596
|
+
if (this._bloomDirtyCount > dirtyThreshold || this.bloom.insertions - this.cache.size > this.bloom.maxCapacity) {
|
|
597
|
+
this.bloom.rebuild(this.cache.keys());
|
|
598
|
+
this._bloomDirtyCount = 0;
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
smartEvict(targetCat, catOvf) {
|
|
602
|
+
const now = Date.now();
|
|
603
|
+
const pool = this._evictPool;
|
|
604
|
+
const gPool = this._evictGPool;
|
|
605
|
+
let poolLen = 0;
|
|
606
|
+
if (catOvf) {
|
|
607
|
+
const catKeySet = this.categoryKeys.get(targetCat);
|
|
608
|
+
if (catKeySet) {
|
|
609
|
+
let catSeen = 0;
|
|
610
|
+
for (const key of catKeySet) {
|
|
611
|
+
const entry = this.cache.get(key);
|
|
612
|
+
if (!entry || entry.priority === 4 && entry.expiresAt > now) continue;
|
|
613
|
+
catSeen++;
|
|
614
|
+
const s = this.score(entry, 100, now, key);
|
|
615
|
+
if (poolLen < EVICT_COUNT) {
|
|
616
|
+
pool[poolLen].key = key;
|
|
617
|
+
pool[poolLen].score = s;
|
|
618
|
+
poolLen++;
|
|
619
|
+
} else {
|
|
620
|
+
const j = Math.floor(Math.random() * catSeen);
|
|
621
|
+
if (j < EVICT_COUNT) {
|
|
622
|
+
pool[j].key = key;
|
|
623
|
+
pool[j].score = s;
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
if (poolLen < EVICT_COUNT) {
|
|
630
|
+
const remaining = EVICTION_SAMPLE - poolLen;
|
|
631
|
+
let globalSeen = 0;
|
|
632
|
+
let gLen = 0;
|
|
633
|
+
for (const [key, entry] of this.cache) {
|
|
634
|
+
if (entry.priority === 4 && entry.expiresAt > now) continue;
|
|
635
|
+
if (catOvf && this.getCategory(key) === targetCat) continue;
|
|
636
|
+
globalSeen++;
|
|
637
|
+
const s = this.score(entry, 0, now, key);
|
|
638
|
+
if (gLen < remaining) {
|
|
639
|
+
gPool[gLen].key = key;
|
|
640
|
+
gPool[gLen].score = s;
|
|
641
|
+
gLen++;
|
|
642
|
+
} else {
|
|
643
|
+
const j = Math.floor(Math.random() * globalSeen);
|
|
644
|
+
if (j < remaining) {
|
|
645
|
+
gPool[j].key = key;
|
|
646
|
+
gPool[j].score = s;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
for (let i = 0; i < gLen; i++) {
|
|
651
|
+
pool[poolLen].key = gPool[i].key;
|
|
652
|
+
pool[poolLen].score = gPool[i].score;
|
|
653
|
+
poolLen++;
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
if (poolLen === 0) return;
|
|
657
|
+
for (let i = 1; i < poolLen; i++) {
|
|
658
|
+
const sk = pool[i].key, ss = pool[i].score;
|
|
659
|
+
let j = i - 1;
|
|
660
|
+
while (j >= 0 && pool[j].score > ss) {
|
|
661
|
+
pool[j + 1].key = pool[j].key;
|
|
662
|
+
pool[j + 1].score = pool[j].score;
|
|
663
|
+
j--;
|
|
664
|
+
}
|
|
665
|
+
pool[j + 1].key = sk;
|
|
666
|
+
pool[j + 1].score = ss;
|
|
667
|
+
}
|
|
668
|
+
const toEvict = Math.min(EVICT_COUNT, poolLen);
|
|
669
|
+
for (let i = 0; i < toEvict; i++) {
|
|
670
|
+
const key = pool[i].key;
|
|
671
|
+
const entry = this.cache.get(key);
|
|
672
|
+
if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
|
|
673
|
+
this._delete(key, "capacity");
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
// ── Public API ────────────────────────────────────────────────────────────
|
|
677
|
+
get(key) {
|
|
678
|
+
this.bloomChecks++;
|
|
679
|
+
if (!this.bloom.mightContain(key)) return null;
|
|
680
|
+
const entry = this.cache.get(key);
|
|
681
|
+
if (!entry) {
|
|
682
|
+
this.bloomFalsePos++;
|
|
683
|
+
return null;
|
|
684
|
+
}
|
|
685
|
+
const now = Date.now();
|
|
686
|
+
if (entry.expiresAt < now) {
|
|
687
|
+
this._delete(key, "ttl");
|
|
688
|
+
return null;
|
|
689
|
+
}
|
|
690
|
+
entry.hits++;
|
|
691
|
+
entry.lastAccess = now;
|
|
692
|
+
if ((entry.hits & 3) === 0) this.sketch.increment(key);
|
|
693
|
+
const value = entry.value !== void 0 ? entry.value : unpack(entry.data);
|
|
694
|
+
const hit = {
|
|
695
|
+
value,
|
|
696
|
+
isStale: entry.staleAt !== void 0 && now > entry.staleAt,
|
|
697
|
+
expiresAt: entry.expiresAt,
|
|
698
|
+
ttlMs: entry.ttlMs,
|
|
699
|
+
delta: entry.delta,
|
|
700
|
+
fetchedAt: now,
|
|
701
|
+
tagVersions: entry.tagVersions,
|
|
702
|
+
setAt: entry.setAt
|
|
703
|
+
};
|
|
704
|
+
return hit;
|
|
705
|
+
}
|
|
706
|
+
set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
|
|
707
|
+
const packed = pack(data);
|
|
708
|
+
const size = packed.byteLength;
|
|
709
|
+
this.compressions++;
|
|
710
|
+
this.sketch.increment(key);
|
|
711
|
+
const cat = this.getCategory(key);
|
|
712
|
+
const lim = this.getCategoryLimit(cat);
|
|
713
|
+
if (size > lim.maxSizeBytes * 0.5) {
|
|
714
|
+
this.opts.logger.debug("SmartMemoryCache: entry too large, skipping", { key, sizeBytes: size });
|
|
715
|
+
return;
|
|
716
|
+
}
|
|
717
|
+
const existingEntry = this.cache.get(key);
|
|
718
|
+
if (existingEntry) {
|
|
719
|
+
this.totalSize -= existingEntry.size;
|
|
720
|
+
this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
|
|
721
|
+
this.categorySize.set(cat, (this.categorySize.get(cat) ?? existingEntry.size) - existingEntry.size);
|
|
722
|
+
this.cache.delete(key);
|
|
723
|
+
}
|
|
724
|
+
this.ensureCapacity(cat, size);
|
|
725
|
+
const now = Date.now();
|
|
726
|
+
const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
|
|
727
|
+
this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: now, tagVersions });
|
|
728
|
+
if (!existingEntry) this.bloom.add(key);
|
|
729
|
+
this.maybeRebuildBloom();
|
|
730
|
+
this.totalSize += size;
|
|
731
|
+
this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
|
|
732
|
+
this.categorySize.set(cat, (this.categorySize.get(cat) ?? 0) + size);
|
|
733
|
+
let ks = this.categoryKeys.get(cat);
|
|
734
|
+
if (!ks) {
|
|
735
|
+
ks = /* @__PURE__ */ new Set();
|
|
736
|
+
this.categoryKeys.set(cat, ks);
|
|
737
|
+
}
|
|
738
|
+
ks.add(key);
|
|
739
|
+
}
|
|
740
|
+
delete(key) {
|
|
741
|
+
const deleted = this._delete(key, "manual");
|
|
742
|
+
if (deleted) this.maybeRebuildBloom();
|
|
743
|
+
return deleted;
|
|
744
|
+
}
|
|
745
|
+
keysMatchingPattern(pattern) {
|
|
746
|
+
if (!pattern.includes("*")) return this.cache.has(pattern) ? [pattern] : [];
|
|
747
|
+
if (pattern.endsWith("*") && pattern.indexOf("*") === pattern.length - 1) {
|
|
748
|
+
const prefix = pattern.slice(0, -1);
|
|
749
|
+
const catKeys = this.categoryKeys.get(prefix);
|
|
750
|
+
if (catKeys !== void 0) return Array.from(catKeys);
|
|
751
|
+
}
|
|
752
|
+
const firstStar = pattern.indexOf("*");
|
|
753
|
+
if (firstStar === pattern.lastIndexOf("*")) {
|
|
754
|
+
const prefix = pattern.slice(0, firstStar);
|
|
755
|
+
const suffix = pattern.slice(firstStar + 1);
|
|
756
|
+
const minLen = prefix.length + suffix.length;
|
|
757
|
+
const out2 = [];
|
|
758
|
+
for (const k of this.cache.keys()) {
|
|
759
|
+
if (k.length >= minLen && k.startsWith(prefix) && k.endsWith(suffix)) out2.push(k);
|
|
760
|
+
}
|
|
761
|
+
return out2;
|
|
762
|
+
}
|
|
763
|
+
const parts = pattern.split("*");
|
|
764
|
+
const first = parts[0];
|
|
765
|
+
const last = parts[parts.length - 1];
|
|
766
|
+
const out = [];
|
|
767
|
+
for (const k of this.cache.keys()) if (globMatchParts(parts, first, last, k)) out.push(k);
|
|
768
|
+
return out;
|
|
769
|
+
}
|
|
770
|
+
deletePattern(pattern) {
|
|
771
|
+
let n = 0;
|
|
772
|
+
for (const key of this.keysMatchingPattern(pattern)) if (this._delete(key, "manual")) n++;
|
|
773
|
+
if (n > 0) this.maybeRebuildBloom();
|
|
774
|
+
return n;
|
|
775
|
+
}
|
|
776
|
+
/** Flush all entries, or only those whose key starts with `prefix`. */
|
|
777
|
+
clear(prefix) {
|
|
778
|
+
if (prefix) {
|
|
779
|
+
const pattern = prefix.includes("*") ? prefix : `${prefix}*`;
|
|
780
|
+
return this.deletePattern(pattern);
|
|
781
|
+
}
|
|
782
|
+
const count = this.cache.size;
|
|
783
|
+
this.cache.clear();
|
|
784
|
+
this.totalSize = 0;
|
|
785
|
+
this.categoryCount.clear();
|
|
786
|
+
this.categorySize.clear();
|
|
787
|
+
this.categoryKeys.clear();
|
|
788
|
+
this.categoryHits.clear();
|
|
789
|
+
this.bloom.reset();
|
|
790
|
+
this._bloomDirtyCount = 0;
|
|
791
|
+
return count;
|
|
792
|
+
}
|
|
793
|
+
/**
|
|
794
|
+
* Evict entries that violate current category or global limits.
|
|
795
|
+
* Returns the number of entries evicted.
|
|
796
|
+
*/
|
|
797
|
+
rebalance() {
|
|
798
|
+
const now = Date.now();
|
|
799
|
+
let evicted = 0;
|
|
800
|
+
for (const [cat, limit] of Object.entries(this.opts.categories)) {
|
|
801
|
+
const catKeys = this.categoryKeys.get(cat);
|
|
802
|
+
if (!catKeys || catKeys.size === 0) continue;
|
|
803
|
+
let catCnt = this.categoryCount.get(cat) ?? 0;
|
|
804
|
+
let catSz = this.categorySize.get(cat) ?? 0;
|
|
805
|
+
if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes) continue;
|
|
806
|
+
const candidates = [];
|
|
807
|
+
for (const key of catKeys) {
|
|
808
|
+
const entry = this.cache.get(key);
|
|
809
|
+
if (!entry) continue;
|
|
810
|
+
if (entry.priority === 4 && entry.expiresAt > now) continue;
|
|
811
|
+
candidates.push({ key, score: this.score(entry, 0, now, key) });
|
|
812
|
+
}
|
|
813
|
+
candidates.sort((a, b) => a.score - b.score);
|
|
814
|
+
for (const { key } of candidates) {
|
|
815
|
+
catCnt = this.categoryCount.get(cat) ?? 0;
|
|
816
|
+
catSz = this.categorySize.get(cat) ?? 0;
|
|
817
|
+
if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes) break;
|
|
818
|
+
const entry = this.cache.get(key);
|
|
819
|
+
if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
|
|
820
|
+
this._delete(key, "rebalance");
|
|
821
|
+
evicted++;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
while (this.cache.size > this.opts.maxEntries || this.totalSize > this.opts.maxBytes) {
|
|
825
|
+
const before = this.cache.size;
|
|
826
|
+
this.smartEvict("default", false);
|
|
827
|
+
if (this.cache.size >= before) break;
|
|
828
|
+
evicted += before - this.cache.size;
|
|
829
|
+
}
|
|
830
|
+
if (evicted > 0) this.maybeRebuildBloom();
|
|
831
|
+
return evicted;
|
|
832
|
+
}
|
|
833
|
+
/**
|
|
834
|
+
* Return remaining TTL in seconds for a key in L1, or null if absent/expired.
|
|
835
|
+
* Only reflects L1 state — does not query Redis or disk.
|
|
836
|
+
*/
|
|
837
|
+
ttl(key) {
|
|
838
|
+
const entry = this.cache.get(key);
|
|
839
|
+
if (!entry) return null;
|
|
840
|
+
const remaining = entry.expiresAt - Date.now();
|
|
841
|
+
return remaining > 0 ? Math.ceil(remaining / 1e3) : null;
|
|
842
|
+
}
|
|
843
|
+
/**
|
|
844
|
+
* Forcibly evict the coldest `pct` fraction of non-CRITICAL L1 entries,
|
|
845
|
+
* spilling each to L1.5 disk. Called by the OOM guard when heap pressure
|
|
846
|
+
* exceeds the configured threshold.
|
|
847
|
+
*
|
|
848
|
+
* @param pct - Fraction to evict (0–1), e.g. 0.2 = 20 %
|
|
849
|
+
* @returns Number of entries evicted
|
|
850
|
+
*/
|
|
851
|
+
evictPercentage(pct) {
|
|
852
|
+
if (pct <= 0 || this.cache.size === 0) return 0;
|
|
853
|
+
const now = Date.now();
|
|
854
|
+
const candidates = [];
|
|
855
|
+
for (const [key, entry] of this.cache) {
|
|
856
|
+
if (entry.priority === 4 && entry.expiresAt > now) continue;
|
|
857
|
+
candidates.push({ key, score: this.score(entry, 0, now, key) });
|
|
858
|
+
}
|
|
859
|
+
candidates.sort((a, b) => a.score - b.score);
|
|
860
|
+
const count = Math.max(1, Math.ceil(candidates.length * pct));
|
|
861
|
+
let evicted = 0;
|
|
862
|
+
for (const { key } of candidates.slice(0, count)) {
|
|
863
|
+
const entry = this.cache.get(key);
|
|
864
|
+
if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
|
|
865
|
+
this._delete(key, "oom");
|
|
866
|
+
evicted++;
|
|
867
|
+
}
|
|
868
|
+
return evicted;
|
|
869
|
+
}
|
|
870
|
+
cleanup() {
|
|
871
|
+
const now = Date.now();
|
|
872
|
+
let cleaned = 0;
|
|
873
|
+
for (const [key, entry] of this.cache) if (entry.expiresAt < now) {
|
|
874
|
+
this._delete(key, "ttl");
|
|
875
|
+
cleaned++;
|
|
876
|
+
}
|
|
877
|
+
if (cleaned > 0) {
|
|
878
|
+
this.bloom.rebuild(this.cache.keys());
|
|
879
|
+
this._bloomDirtyCount = 0;
|
|
880
|
+
}
|
|
881
|
+
return cleaned;
|
|
882
|
+
}
|
|
883
|
+
/**
|
|
884
|
+
* Evict all non-CRITICAL L1 entries that were written before `cutoffMs`.
|
|
885
|
+
*
|
|
886
|
+
* Called by the backplane staleness fence when the Pub/Sub subscriber
|
|
887
|
+
* reconnects after a disconnect gap that exceeded `backplaneMaxStalenessMs`.
|
|
888
|
+
* Entries written before the disconnect started may have been invalidated by
|
|
889
|
+
* peers while the backplane was down; evicting them forces a controlled
|
|
890
|
+
* cold-start re-fetch from L2 rather than serving silently stale data.
|
|
891
|
+
*
|
|
892
|
+
* Write-time is read from `entry.setAt` (set by `SmartMemoryCache.set()` since v0.7.0).
|
|
893
|
+
* Older snapshot entries without `setAt` fall back to approximating via `expiresAt - ttlMs`;
|
|
894
|
+
* entries with neither field are treated as potentially stale and evicted conservatively.
|
|
895
|
+
*
|
|
896
|
+
* @param cutoffMs - Unix timestamp in milliseconds; entries written before
|
|
897
|
+
* this time are evicted.
|
|
898
|
+
* @returns Number of entries evicted.
|
|
899
|
+
*/
|
|
900
|
+
evictSetBefore(cutoffMs) {
|
|
901
|
+
let evicted = 0;
|
|
902
|
+
for (const [key, entry] of this.cache) {
|
|
903
|
+
if (entry.priority === 4 && entry.expiresAt > Date.now()) continue;
|
|
904
|
+
const setAt = entry.setAt ?? (entry.ttlMs != null ? entry.expiresAt - entry.ttlMs : 0);
|
|
905
|
+
if (setAt < cutoffMs) {
|
|
906
|
+
this._delete(key, "manual");
|
|
907
|
+
evicted++;
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
if (evicted > 0) {
|
|
911
|
+
this.bloom.rebuild(this.cache.keys());
|
|
912
|
+
this._bloomDirtyCount = 0;
|
|
913
|
+
}
|
|
914
|
+
return evicted;
|
|
915
|
+
}
|
|
916
|
+
/**
|
|
917
|
+
* Delete a key only if its write timestamp (`setAt`) is <= `cutoffMs`.
|
|
918
|
+
* Used for concurrency-safe compare-and-delete on stale generational reads,
|
|
919
|
+
* guaranteeing that a newer value written by a concurrent revalidation is never wiped out.
|
|
920
|
+
*/
|
|
921
|
+
deleteIfSetBefore(key, cutoffMs) {
|
|
922
|
+
const entry = this.cache.get(key);
|
|
923
|
+
if (!entry) return false;
|
|
924
|
+
const setAt = entry.setAt ?? (entry.ttlMs != null ? entry.expiresAt - entry.ttlMs : 0);
|
|
925
|
+
if (setAt <= cutoffMs) {
|
|
926
|
+
const deleted = this._delete(key, "manual");
|
|
927
|
+
if (deleted) this.maybeRebuildBloom();
|
|
928
|
+
return deleted;
|
|
929
|
+
}
|
|
930
|
+
return false;
|
|
931
|
+
}
|
|
932
|
+
exportEntries(forbiddenPrefixes) {
|
|
933
|
+
const now = Date.now();
|
|
934
|
+
const out = [];
|
|
935
|
+
for (const [key, entry] of this.cache) {
|
|
936
|
+
if (entry.expiresAt <= now) continue;
|
|
937
|
+
if (entry.priority === 4) continue;
|
|
938
|
+
if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
|
|
939
|
+
out.push({ key, entry: { ...entry } });
|
|
940
|
+
}
|
|
941
|
+
return out;
|
|
942
|
+
}
|
|
943
|
+
importEntries(entries, forbiddenPrefixes) {
|
|
944
|
+
const now = Date.now();
|
|
945
|
+
let loaded = 0;
|
|
946
|
+
for (const { key, entry } of entries) {
|
|
947
|
+
if (entry.expiresAt <= now) continue;
|
|
948
|
+
if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
|
|
949
|
+
if (this.cache.has(key)) continue;
|
|
950
|
+
const rawData = entry.data;
|
|
951
|
+
const data = !entry.isCompressed ? pack(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
|
|
952
|
+
const value = entry.size <= LARGE_VALUE_BYTES ? unpack(data) : void 0;
|
|
953
|
+
this.cache.set(key, { ...entry, data, value, isCompressed: true });
|
|
954
|
+
this.bloom.add(key);
|
|
955
|
+
loaded++;
|
|
956
|
+
}
|
|
957
|
+
this.recalculateStats();
|
|
958
|
+
return loaded;
|
|
959
|
+
}
|
|
960
|
+
// ── Iterators ─────────────────────────────────────────────────────────────
|
|
961
|
+
/**
|
|
962
|
+
* Lazily yields every [key, entry] pair whose TTL has not yet expired.
|
|
963
|
+
* Expired entries that are still in the Map (awaiting background cleanup)
|
|
964
|
+
* are silently skipped.
|
|
965
|
+
*/
|
|
966
|
+
*liveEntries() {
|
|
967
|
+
const now = Date.now();
|
|
968
|
+
for (const [key, entry] of this.cache) {
|
|
969
|
+
if (entry.expiresAt > now) yield [key, entry];
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
/**
|
|
973
|
+
* Non-generator bulk scan over all live entries.
|
|
974
|
+
*
|
|
975
|
+
* Faster than the generator-based iterators for bulk operations because:
|
|
976
|
+
* - No generator state-machine overhead (no yield/resume suspend points).
|
|
977
|
+
* - No per-entry tuple allocation (compare `liveEntries()` which yields `[key, entry]`).
|
|
978
|
+
* - The same Map call-site is used by a single plain `for` loop instead of being
|
|
979
|
+
* shared across three competing generator functions, giving V8's IC a cleaner
|
|
980
|
+
* monomorphic profile for this path.
|
|
981
|
+
*
|
|
982
|
+
* The callback receives the raw (namespaced) key and a `prefixLen` offset so the
|
|
983
|
+
* caller can call `key.slice(prefixLen)` only when it actually needs the stripped
|
|
984
|
+
* key, avoiding the allocation entirely for callers that don't.
|
|
985
|
+
*
|
|
986
|
+
* @param fn Called once per live entry.
|
|
987
|
+
* @param prefixLen Number of bytes to skip to reach the un-namespaced portion of the key.
|
|
988
|
+
* Pass 0 when no namespace is configured.
|
|
989
|
+
*/
|
|
990
|
+
scan(fn, prefixLen) {
|
|
991
|
+
const now = Date.now();
|
|
992
|
+
for (const [key, entry] of this.cache) {
|
|
993
|
+
if (entry.expiresAt > now) fn(key, entry, prefixLen);
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
/**
|
|
997
|
+
* Yields only the keys of live entries — no intermediate tuple allocation.
|
|
998
|
+
* Use this instead of liveEntries() when you only need keys.
|
|
999
|
+
*/
|
|
1000
|
+
*liveKeys() {
|
|
1001
|
+
const now = Date.now();
|
|
1002
|
+
for (const [key, entry] of this.cache) {
|
|
1003
|
+
if (entry.expiresAt > now) yield key;
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
/**
|
|
1007
|
+
* Yields only the resolved values of live entries.
|
|
1008
|
+
* Iterates Map.values() so the key is never loaded into the yielded path.
|
|
1009
|
+
* Returns the deserialized value — identical semantics to get() but without bloom/hit tracking.
|
|
1010
|
+
*/
|
|
1011
|
+
*liveValues() {
|
|
1012
|
+
const now = Date.now();
|
|
1013
|
+
for (const entry of this.cache.values()) {
|
|
1014
|
+
if (entry.expiresAt > now)
|
|
1015
|
+
yield this.resolveValue(entry);
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
/**
|
|
1019
|
+
* Returns the deserialized value for an entry, unpacking from the msgpackr buffer
|
|
1020
|
+
* if the live object was not cached (large-entry optimisation or disk-restored entry).
|
|
1021
|
+
*/
|
|
1022
|
+
resolveValue(entry) {
|
|
1023
|
+
return entry.value !== void 0 ? entry.value : unpack(entry.data);
|
|
1024
|
+
}
|
|
1025
|
+
// ── Stats ─────────────────────────────────────────────────────────────────
|
|
1026
|
+
get size() {
|
|
1027
|
+
return this.cache.size;
|
|
1028
|
+
}
|
|
1029
|
+
get memoryUsage() {
|
|
1030
|
+
return this.totalSize;
|
|
1031
|
+
}
|
|
1032
|
+
getStats() {
|
|
1033
|
+
const categories = {};
|
|
1034
|
+
for (const [cat, cnt] of this.categoryCount) {
|
|
1035
|
+
categories[cat] = { entries: cnt, hits: this.categoryHits.get(cat) ?? 0 };
|
|
1036
|
+
}
|
|
1037
|
+
return {
|
|
1038
|
+
entries: this.cache.size,
|
|
1039
|
+
sizeBytes: this.totalSize,
|
|
1040
|
+
sizeKB: Math.round(this.totalSize / 1024),
|
|
1041
|
+
categories,
|
|
1042
|
+
bloom: {
|
|
1043
|
+
checks: this.bloomChecks,
|
|
1044
|
+
falsePositives: this.bloomFalsePos
|
|
1045
|
+
},
|
|
1046
|
+
compression: {
|
|
1047
|
+
compressed: this.compressions,
|
|
1048
|
+
uncompressed: 0,
|
|
1049
|
+
// all entries are now msgpackr-packed
|
|
1050
|
+
bytesSaved: 0
|
|
1051
|
+
// no longer tracked (unified format removes the split path)
|
|
1052
|
+
}
|
|
1053
|
+
};
|
|
1054
|
+
}
|
|
1055
|
+
/**
|
|
1056
|
+
* Return the raw cache entry for a key, or `undefined` if absent/expired.
|
|
1057
|
+
* Does NOT count as a hit or perform SWR logic.
|
|
1058
|
+
*/
|
|
1059
|
+
getEntry(key) {
|
|
1060
|
+
const entry = this.cache.get(key);
|
|
1061
|
+
if (!entry) return void 0;
|
|
1062
|
+
if (entry.expiresAt <= Date.now()) return void 0;
|
|
1063
|
+
return entry;
|
|
1064
|
+
}
|
|
1065
|
+
/**
|
|
1066
|
+
* Return true if the key exists in L1 and has not expired.
|
|
1067
|
+
* Uses the bloom filter as a fast negative check.
|
|
1068
|
+
*/
|
|
1069
|
+
has(key) {
|
|
1070
|
+
if (!this.bloom.mightContain(key)) return false;
|
|
1071
|
+
const entry = this.cache.get(key);
|
|
1072
|
+
if (!entry) return false;
|
|
1073
|
+
if (entry.expiresAt <= Date.now()) {
|
|
1074
|
+
this._delete(key, "ttl");
|
|
1075
|
+
return false;
|
|
1076
|
+
}
|
|
1077
|
+
return true;
|
|
1078
|
+
}
|
|
1079
|
+
/**
|
|
1080
|
+
* Extend the TTL of an existing key. Returns `false` if the key is absent or expired.
|
|
1081
|
+
* @param newTtlMs - New TTL from now, in milliseconds.
|
|
1082
|
+
*/
|
|
1083
|
+
touch(key, newTtlMs) {
|
|
1084
|
+
const entry = this.cache.get(key);
|
|
1085
|
+
if (!entry) return false;
|
|
1086
|
+
const now = Date.now();
|
|
1087
|
+
if (entry.expiresAt <= now) {
|
|
1088
|
+
this._delete(key, "ttl");
|
|
1089
|
+
return false;
|
|
1090
|
+
}
|
|
1091
|
+
entry.expiresAt = now + newTtlMs;
|
|
1092
|
+
return true;
|
|
1093
|
+
}
|
|
1094
|
+
/**
|
|
1095
|
+
* Add additional milliseconds to a key's existing expiry (for stale-if-error).
|
|
1096
|
+
* Returns `false` if the key is absent or already expired.
|
|
1097
|
+
*/
|
|
1098
|
+
bumpExpiry(key, additionalMs) {
|
|
1099
|
+
const entry = this.cache.get(key);
|
|
1100
|
+
if (!entry) return false;
|
|
1101
|
+
if (entry.expiresAt <= Date.now()) return false;
|
|
1102
|
+
entry.expiresAt += additionalMs;
|
|
1103
|
+
return true;
|
|
1104
|
+
}
|
|
1105
|
+
bloomMightContain(key) {
|
|
1106
|
+
return this.bloom.mightContain(key);
|
|
1107
|
+
}
|
|
1108
|
+
bloomStats() {
|
|
1109
|
+
return this.bloom.stats;
|
|
1110
|
+
}
|
|
1111
|
+
/**
|
|
1112
|
+
* Return the top-N live L1 keys by historical access frequency (Count-Min Sketch estimate).
|
|
1113
|
+
* Includes evicted-then-readmitted keys whose sketch frequency exceeds their current hit count.
|
|
1114
|
+
* Useful for diagnosing which keys are driving cache pressure.
|
|
1115
|
+
*
|
|
1116
|
+
* @param n - Maximum number of entries to return. Default: 10.
|
|
1117
|
+
*/
|
|
1118
|
+
hotKeys(n) {
|
|
1119
|
+
const now = Date.now();
|
|
1120
|
+
const out = [];
|
|
1121
|
+
for (const [key, entry] of this.cache) {
|
|
1122
|
+
if (entry.expiresAt <= now) continue;
|
|
1123
|
+
out.push({ key, hits: this.sketch.estimate(key), sizeBytes: entry.size });
|
|
1124
|
+
}
|
|
1125
|
+
out.sort((a, b) => b.hits - a.hits);
|
|
1126
|
+
return out.slice(0, n);
|
|
1127
|
+
}
|
|
1128
|
+
};
|
|
1129
|
+
|
|
1130
|
+
// src/disk-tier.ts
|
|
1131
|
+
import fs from "fs";
|
|
1132
|
+
import path from "path";
|
|
1133
|
+
import crypto from "crypto";
|
|
1134
|
+
import { pack as pack2, unpack as unpack2 } from "msgpackr";
|
|
1135
|
+
var _SqliteDB = null;
|
|
1136
|
+
try {
|
|
1137
|
+
const sqlite = process.getBuiltinModule("node:sqlite");
|
|
1138
|
+
_SqliteDB = sqlite?.DatabaseSync ?? null;
|
|
1139
|
+
} catch {
|
|
1140
|
+
}
|
|
1141
|
+
var DISK_MAGIC = Buffer.from([68, 84, 73, 69, 82, 86, 49, 0]);
|
|
1142
|
+
var DISK_MAGIC_V2 = Buffer.from([68, 84, 73, 69, 82, 86, 50, 0]);
|
|
1143
|
+
var V2_HEADER_LEN = 16;
|
|
1144
|
+
var DISK_TIER_VERSION = 1;
|
|
1145
|
+
var DiskTier = class {
|
|
1146
|
+
opts;
|
|
1147
|
+
dirReady = false;
|
|
1148
|
+
diskUsageBytes = 0;
|
|
1149
|
+
usageCounted = false;
|
|
1150
|
+
fileCount = 0;
|
|
1151
|
+
// maintained in-memory; avoids walkCacheFiles() in stats
|
|
1152
|
+
/** Next bucket index (0–255) for the staggered janitor wheel. */
|
|
1153
|
+
_nextJanitorBucket = 0;
|
|
1154
|
+
// ── SQLite metadata index (optional, requires node:sqlite) ───────────────
|
|
1155
|
+
_db = null;
|
|
1156
|
+
_stmtInsert = null;
|
|
1157
|
+
// INSERT OR REPLACE
|
|
1158
|
+
_stmtSelect = null;
|
|
1159
|
+
// SELECT by key_hash
|
|
1160
|
+
_stmtDelete = null;
|
|
1161
|
+
// DELETE by key_hash
|
|
1162
|
+
_stmtExpire = null;
|
|
1163
|
+
// SELECT expired rows
|
|
1164
|
+
_stmtDelExp = null;
|
|
1165
|
+
// DELETE expired rows
|
|
1166
|
+
_stmtStats = null;
|
|
1167
|
+
// COUNT + SUM(size)
|
|
1168
|
+
constructor(opts) {
|
|
1169
|
+
this.opts = opts;
|
|
1170
|
+
}
|
|
1171
|
+
// ── Helpers ───────────────────────────────────────────────────────────────
|
|
1172
|
+
ensureDir() {
|
|
1173
|
+
if (this.dirReady) return;
|
|
1174
|
+
try {
|
|
1175
|
+
fs.mkdirSync(this.opts.dir, { recursive: true, mode: 448 });
|
|
1176
|
+
this.dirReady = true;
|
|
1177
|
+
this._initSqlite();
|
|
1178
|
+
} catch (err) {
|
|
1179
|
+
this.opts.logger.warn("DiskTier: cannot create cache dir", { dir: this.opts.dir, error: err.message });
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
/**
|
|
1183
|
+
* Initialise the SQLite metadata index. Called once after the cache directory
|
|
1184
|
+
* is confirmed to exist. On any failure the instance silently falls back to
|
|
1185
|
+
* file-only mode — all public methods handle `this._db === null`.
|
|
1186
|
+
*
|
|
1187
|
+
* Schema:
|
|
1188
|
+
* meta(key_hash TEXT PK, file_path TEXT, expires_at INT, size INT)
|
|
1189
|
+
* idx_expires on (expires_at) — makes WHERE expires_at <= ? O(log n).
|
|
1190
|
+
*
|
|
1191
|
+
* WAL + synchronous=NORMAL: durable enough for a cache (a crash loses at
|
|
1192
|
+
* most one WAL frame — acceptable data loss for an L1.5 spill store).
|
|
1193
|
+
*/
|
|
1194
|
+
_initSqlite() {
|
|
1195
|
+
if (!_SqliteDB) return;
|
|
1196
|
+
try {
|
|
1197
|
+
const dbPath = path.join(this.opts.dir, "meta.db");
|
|
1198
|
+
this._db = new _SqliteDB(dbPath);
|
|
1199
|
+
this._db.exec(`
|
|
1200
|
+
PRAGMA journal_mode = WAL;
|
|
1201
|
+
PRAGMA synchronous = NORMAL;
|
|
1202
|
+
PRAGMA temp_store = MEMORY;
|
|
1203
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
1204
|
+
key_hash TEXT PRIMARY KEY,
|
|
1205
|
+
file_path TEXT NOT NULL,
|
|
1206
|
+
expires_at INTEGER NOT NULL,
|
|
1207
|
+
size INTEGER NOT NULL DEFAULT 0
|
|
1208
|
+
);
|
|
1209
|
+
CREATE INDEX IF NOT EXISTS idx_expires ON meta (expires_at);
|
|
1210
|
+
`);
|
|
1211
|
+
this._stmtInsert = this._db.prepare(
|
|
1212
|
+
"INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size) VALUES (?,?,?,?)"
|
|
1213
|
+
);
|
|
1214
|
+
this._stmtSelect = this._db.prepare(
|
|
1215
|
+
"SELECT file_path, expires_at FROM meta WHERE key_hash = ?"
|
|
1216
|
+
);
|
|
1217
|
+
this._stmtDelete = this._db.prepare("DELETE FROM meta WHERE key_hash = ?");
|
|
1218
|
+
this._stmtExpire = this._db.prepare(
|
|
1219
|
+
"SELECT key_hash, file_path, size FROM meta WHERE expires_at <= ?"
|
|
1220
|
+
);
|
|
1221
|
+
this._stmtDelExp = this._db.prepare("DELETE FROM meta WHERE expires_at <= ?");
|
|
1222
|
+
this._stmtStats = this._db.prepare(
|
|
1223
|
+
"SELECT COUNT(*) AS cnt, COALESCE(SUM(size), 0) AS bytes FROM meta"
|
|
1224
|
+
);
|
|
1225
|
+
const row = this._stmtStats.get();
|
|
1226
|
+
this.fileCount = row.cnt;
|
|
1227
|
+
this.diskUsageBytes = row.bytes;
|
|
1228
|
+
this.usageCounted = true;
|
|
1229
|
+
this.opts.logger.debug("DiskTier: SQLite index ready", { entries: row.cnt });
|
|
1230
|
+
} catch (err) {
|
|
1231
|
+
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
|
|
1232
|
+
this.opts.logger.warn("DiskTier: SQLite init failed, using file-only mode", {
|
|
1233
|
+
error: err.message
|
|
1234
|
+
});
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
ensureUsageCounted() {
|
|
1238
|
+
if (this.usageCounted) return;
|
|
1239
|
+
this.usageCounted = true;
|
|
1240
|
+
if (this._db) return;
|
|
1241
|
+
try {
|
|
1242
|
+
this.ensureDir();
|
|
1243
|
+
let total = 0;
|
|
1244
|
+
const files = this.walkCacheFiles();
|
|
1245
|
+
this.fileCount = files.length;
|
|
1246
|
+
for (const filePath of files) {
|
|
1247
|
+
try {
|
|
1248
|
+
total += fs.statSync(filePath).size;
|
|
1249
|
+
} catch {
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
this.diskUsageBytes = total;
|
|
1253
|
+
} catch {
|
|
1254
|
+
this.diskUsageBytes = 0;
|
|
1255
|
+
this.fileCount = 0;
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
/**
|
|
1259
|
+
* SHA-256 hex digest of a key (pure CPU, no I/O).
|
|
1260
|
+
* Kept separate from path construction so callers can find files by prefix
|
|
1261
|
+
* without knowing which filename generation was used when the file was written.
|
|
1262
|
+
*/
|
|
1263
|
+
keyToHash(key) {
|
|
1264
|
+
return crypto.createHash("sha256").update(key, "utf8").digest("hex");
|
|
1265
|
+
}
|
|
1266
|
+
/**
|
|
1267
|
+
* Build the write path for a NEW file (V3 generation).
|
|
1268
|
+
* Encoding expiresAt in the filename lets purgeNextBucket() skip live entries
|
|
1269
|
+
* with zero file I/O — after readdirSync() it only needs a string parse.
|
|
1270
|
+
*
|
|
1271
|
+
* {dir}/{hash[0..1]}/{hash}_{expiresAt-hex-12}
|
|
1272
|
+
* e.g. {dir}/e3/e3b0c442…abcd_018f7c3b5a00
|
|
1273
|
+
*
|
|
1274
|
+
* 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
|
|
1275
|
+
*/
|
|
1276
|
+
hashToWritePath(hash, expiresAt) {
|
|
1277
|
+
return path.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiresAt.toString(16).padStart(12, "0")}`);
|
|
1278
|
+
}
|
|
1279
|
+
/**
|
|
1280
|
+
* Find the on-disk file for a key hash, handling all filename generations:
|
|
1281
|
+
* V3 (current): "{hash}_{expiresHex12}" — 77 chars
|
|
1282
|
+
* V1/V2 (older): "{hash}" — 64 chars, no suffix
|
|
1283
|
+
* Returns null when the bucket dir does not exist or the key is absent.
|
|
1284
|
+
*/
|
|
1285
|
+
findFilePath(hash) {
|
|
1286
|
+
const bucketPath = path.join(this.opts.dir, hash.slice(0, 2));
|
|
1287
|
+
let files;
|
|
1288
|
+
try {
|
|
1289
|
+
files = fs.readdirSync(bucketPath);
|
|
1290
|
+
} catch {
|
|
1291
|
+
return null;
|
|
1292
|
+
}
|
|
1293
|
+
let match;
|
|
1294
|
+
for (const f of files) {
|
|
1295
|
+
if ((f === hash || f.startsWith(hash + "_")) && (!match || f > match)) match = f;
|
|
1296
|
+
}
|
|
1297
|
+
if (!match) return null;
|
|
1298
|
+
return path.join(bucketPath, match);
|
|
1299
|
+
}
|
|
1300
|
+
/**
|
|
1301
|
+
* Recursively list all cache file paths across the 2-level sharded subdirs.
|
|
1302
|
+
* Top-level entries that are not directories are skipped (e.g. stale flat
|
|
1303
|
+
* files written by older versions).
|
|
1304
|
+
*/
|
|
1305
|
+
walkCacheFiles() {
|
|
1306
|
+
const results = [];
|
|
1307
|
+
let topEntries;
|
|
1308
|
+
try {
|
|
1309
|
+
topEntries = fs.readdirSync(this.opts.dir);
|
|
1310
|
+
} catch {
|
|
1311
|
+
return results;
|
|
1312
|
+
}
|
|
1313
|
+
for (const top of topEntries) {
|
|
1314
|
+
const topPath = path.join(this.opts.dir, top);
|
|
1315
|
+
try {
|
|
1316
|
+
if (!fs.statSync(topPath).isDirectory()) continue;
|
|
1317
|
+
for (const file of fs.readdirSync(topPath)) {
|
|
1318
|
+
results.push(path.join(topPath, file));
|
|
1319
|
+
}
|
|
1320
|
+
} catch {
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1323
|
+
return results;
|
|
1324
|
+
}
|
|
1325
|
+
isForbidden(key) {
|
|
1326
|
+
return this.opts.forbiddenPrefixes.some((p) => key.startsWith(p));
|
|
1327
|
+
}
|
|
1328
|
+
encrypt(data) {
|
|
1329
|
+
if (!this.opts.encryption) return data;
|
|
1330
|
+
return Buffer.concat([DISK_MAGIC, this.opts.encryption.encryptBuffer(data)]);
|
|
1331
|
+
}
|
|
1332
|
+
decrypt(data) {
|
|
1333
|
+
const mLen = DISK_MAGIC.length;
|
|
1334
|
+
if (data.length < mLen || !data.subarray(0, mLen).equals(DISK_MAGIC)) return data;
|
|
1335
|
+
if (!this.opts.encryption) throw new Error("DiskTier: entry is encrypted but no encryption configured");
|
|
1336
|
+
return this.opts.encryption.decryptBuffer(data.subarray(mLen));
|
|
1337
|
+
}
|
|
1338
|
+
/**
|
|
1339
|
+
* V2 encryption — returns the mode-aware encrypted payload (no magic prefix; the
|
|
1340
|
+
* magic + plaintext expiresAt live in the outer 16-byte header written by `save`).
|
|
1341
|
+
* Returns the buffer unchanged when no encryption instance is configured.
|
|
1342
|
+
*/
|
|
1343
|
+
encryptV2(data) {
|
|
1344
|
+
if (!this.opts.encryption) return data;
|
|
1345
|
+
return this.opts.encryption.encryptBuffer(data);
|
|
1346
|
+
}
|
|
1347
|
+
/**
|
|
1348
|
+
* V2 decryption — inner payload after stripping the 16-byte header.
|
|
1349
|
+
* When an encryption instance is configured the format is the mode-aware
|
|
1350
|
+
* CacheEncryption blob (IV|TAG|CT for GCM, IV|CT for CTR, key⊕data for XOR);
|
|
1351
|
+
* without one the payload is raw msgpack.
|
|
1352
|
+
*/
|
|
1353
|
+
decryptV2(inner) {
|
|
1354
|
+
if (!this.opts.encryption) return inner;
|
|
1355
|
+
return this.opts.encryption.decryptBuffer(inner);
|
|
1356
|
+
}
|
|
1357
|
+
// ── Public API ────────────────────────────────────────────────────────────
|
|
1358
|
+
/**
|
|
1359
|
+
* Spill an evicted L1 entry to disk.
|
|
1360
|
+
*
|
|
1361
|
+
* Returns a Promise that resolves when the file is durably written. Callers
|
|
1362
|
+
* that treat the spill as fire-and-forget should do:
|
|
1363
|
+
* `void disk.save(key, entry)`
|
|
1364
|
+
*
|
|
1365
|
+
* Implementation notes:
|
|
1366
|
+
* - pack() + AES-256-GCM encrypt run synchronously — both are pure CPU,
|
|
1367
|
+
* sub-millisecond for entries up to diskEntryMaxBytes, and do not block
|
|
1368
|
+
* on any external resource.
|
|
1369
|
+
* - The actual write syscall (mkdir + writeFile) is async via fs.promises,
|
|
1370
|
+
* so the Node.js event loop is never stalled waiting for disk I/O.
|
|
1371
|
+
*/
|
|
1372
|
+
async save(key, entry) {
|
|
1373
|
+
if (this.isForbidden(key)) return;
|
|
1374
|
+
if (entry.expiresAt <= Date.now()) return;
|
|
1375
|
+
this.ensureDir();
|
|
1376
|
+
if (!this.dirReady) return;
|
|
1377
|
+
this.ensureUsageCounted();
|
|
1378
|
+
if (this.diskUsageBytes >= this.opts.maxBytes) return;
|
|
1379
|
+
let final;
|
|
1380
|
+
try {
|
|
1381
|
+
const payload = {
|
|
1382
|
+
version: DISK_TIER_VERSION,
|
|
1383
|
+
key,
|
|
1384
|
+
entry: {
|
|
1385
|
+
...entry,
|
|
1386
|
+
data: entry.data instanceof Uint8Array ? Buffer.from(entry.data) : entry.data
|
|
1387
|
+
},
|
|
1388
|
+
writtenAt: Date.now()
|
|
1389
|
+
};
|
|
1390
|
+
const packed = pack2(payload);
|
|
1391
|
+
if (packed.length > this.opts.entryMaxBytes) return;
|
|
1392
|
+
let toEncrypt = packed;
|
|
1393
|
+
if (this.opts.compression && this.opts.compression !== "none" && packed.length > (this.opts.compressionThresholdBytes ?? 1024)) {
|
|
1394
|
+
toEncrypt = compressWithHeader(packed, this.opts.compression);
|
|
1395
|
+
}
|
|
1396
|
+
const header = Buffer.allocUnsafe(V2_HEADER_LEN);
|
|
1397
|
+
DISK_MAGIC_V2.copy(header, 0);
|
|
1398
|
+
header.writeBigUInt64LE(BigInt(entry.expiresAt), 8);
|
|
1399
|
+
final = Buffer.concat([header, this.encryptV2(toEncrypt)]);
|
|
1400
|
+
} catch (err) {
|
|
1401
|
+
this.opts.logger.debug("DiskTier: pack/encrypt failed", { key: key.slice(0, 50), error: err.message });
|
|
1402
|
+
return;
|
|
1403
|
+
}
|
|
1404
|
+
const hash = this.keyToHash(key);
|
|
1405
|
+
const filePath = this.hashToWritePath(hash, entry.expiresAt);
|
|
1406
|
+
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
1407
|
+
this.diskUsageBytes += final.length;
|
|
1408
|
+
this.fileCount++;
|
|
1409
|
+
try {
|
|
1410
|
+
await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
|
|
1411
|
+
await fs.promises.writeFile(tmpPath, final, { mode: 384 });
|
|
1412
|
+
try {
|
|
1413
|
+
await fs.promises.rename(tmpPath, filePath);
|
|
1414
|
+
} catch (renameErr) {
|
|
1415
|
+
const code = renameErr?.code;
|
|
1416
|
+
if (code === "EBUSY" || code === "EPERM") {
|
|
1417
|
+
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
1418
|
+
await fs.promises.rename(tmpPath, filePath);
|
|
1419
|
+
} else {
|
|
1420
|
+
throw renameErr;
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1423
|
+
if (this._db) {
|
|
1424
|
+
this._stmtInsert.run(hash, filePath, entry.expiresAt, final.length);
|
|
1425
|
+
}
|
|
1426
|
+
this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
|
|
1427
|
+
} catch (err) {
|
|
1428
|
+
try {
|
|
1429
|
+
await fs.promises.unlink(tmpPath);
|
|
1430
|
+
} catch {
|
|
1431
|
+
}
|
|
1432
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
|
|
1433
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1434
|
+
if (this._db) try {
|
|
1435
|
+
this._stmtDelete.run(hash);
|
|
1436
|
+
} catch {
|
|
1437
|
+
}
|
|
1438
|
+
this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
/** Load a key from disk, or return null on miss/expiry/corruption. */
|
|
1442
|
+
load(key) {
|
|
1443
|
+
if (this.isForbidden(key)) return null;
|
|
1444
|
+
this.ensureDir();
|
|
1445
|
+
if (!this.dirReady) return null;
|
|
1446
|
+
const hash = this.keyToHash(key);
|
|
1447
|
+
let filePath;
|
|
1448
|
+
if (this._db) {
|
|
1449
|
+
const row = this._stmtSelect.get(hash);
|
|
1450
|
+
if (!row) return null;
|
|
1451
|
+
if (row.expires_at <= Date.now()) {
|
|
1452
|
+
this._stmtDelete.run(hash);
|
|
1453
|
+
try {
|
|
1454
|
+
const sz = fs.statSync(row.file_path).size;
|
|
1455
|
+
fs.unlinkSync(row.file_path);
|
|
1456
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
1457
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1458
|
+
} catch {
|
|
1459
|
+
}
|
|
1460
|
+
return null;
|
|
1461
|
+
}
|
|
1462
|
+
filePath = row.file_path;
|
|
1463
|
+
} else {
|
|
1464
|
+
filePath = this.findFilePath(hash);
|
|
1465
|
+
if (!filePath) return null;
|
|
1466
|
+
}
|
|
1467
|
+
try {
|
|
1468
|
+
if (!this._db) {
|
|
1469
|
+
const filename = path.basename(filePath);
|
|
1470
|
+
if (filename.length === 77 && filename[64] === "_") {
|
|
1471
|
+
const expiresAt = parseInt(filename.slice(65), 16);
|
|
1472
|
+
if (expiresAt <= Date.now()) {
|
|
1473
|
+
try {
|
|
1474
|
+
const sz = fs.statSync(filePath).size;
|
|
1475
|
+
fs.unlinkSync(filePath);
|
|
1476
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
1477
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1478
|
+
} catch {
|
|
1479
|
+
}
|
|
1480
|
+
return null;
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
}
|
|
1484
|
+
const stat = fs.statSync(filePath);
|
|
1485
|
+
if (stat.size > this.opts.entryMaxBytes) {
|
|
1486
|
+
fs.unlinkSync(filePath);
|
|
1487
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1488
|
+
if (this._db) this._stmtDelete.run(hash);
|
|
1489
|
+
return null;
|
|
1490
|
+
}
|
|
1491
|
+
const raw = fs.readFileSync(filePath);
|
|
1492
|
+
try {
|
|
1493
|
+
fs.unlinkSync(filePath);
|
|
1494
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1495
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1496
|
+
} catch {
|
|
1497
|
+
}
|
|
1498
|
+
if (this._db) this._stmtDelete.run(hash);
|
|
1499
|
+
let decrypted;
|
|
1500
|
+
if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
|
|
1501
|
+
const expiresAt = Number(raw.readBigUInt64LE(8));
|
|
1502
|
+
if (expiresAt <= Date.now()) return null;
|
|
1503
|
+
try {
|
|
1504
|
+
decrypted = this.decryptV2(raw.subarray(V2_HEADER_LEN));
|
|
1505
|
+
} catch {
|
|
1506
|
+
return null;
|
|
1507
|
+
}
|
|
1508
|
+
} else {
|
|
1509
|
+
try {
|
|
1510
|
+
decrypted = this.decrypt(raw);
|
|
1511
|
+
} catch {
|
|
1512
|
+
return null;
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
const uncompressed = decompressWithHeader(decrypted, this.opts.compression ?? "brotli");
|
|
1516
|
+
const payload = unpack2(uncompressed);
|
|
1517
|
+
if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
|
|
1518
|
+
if (payload.entry.expiresAt <= Date.now()) return null;
|
|
1519
|
+
const entry = payload.entry;
|
|
1520
|
+
if (entry.data instanceof Uint8Array) entry.data = Buffer.from(entry.data);
|
|
1521
|
+
this.opts.logger.debug("DiskTier: hit (\u2192L1)", { key: key.slice(0, 50), ageMs: Date.now() - payload.writtenAt });
|
|
1522
|
+
return entry;
|
|
1523
|
+
} catch (err) {
|
|
1524
|
+
if (this._db) try {
|
|
1525
|
+
this._stmtDelete.run(hash);
|
|
1526
|
+
} catch {
|
|
1527
|
+
}
|
|
1528
|
+
this.opts.logger.debug("DiskTier: load failed", { key: key.slice(0, 50), error: err.message });
|
|
1529
|
+
return null;
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
/** Explicitly delete a key from disk (cache invalidation). */
|
|
1533
|
+
delete(key) {
|
|
1534
|
+
const hash = this.keyToHash(key);
|
|
1535
|
+
let filePath;
|
|
1536
|
+
if (this._db) {
|
|
1537
|
+
const row = this._stmtSelect.get(hash);
|
|
1538
|
+
filePath = row?.file_path ?? null;
|
|
1539
|
+
this._stmtDelete.run(hash);
|
|
1540
|
+
} else {
|
|
1541
|
+
filePath = this.findFilePath(hash);
|
|
1542
|
+
}
|
|
1543
|
+
if (!filePath) return;
|
|
1544
|
+
try {
|
|
1545
|
+
const stat = fs.statSync(filePath);
|
|
1546
|
+
fs.unlinkSync(filePath);
|
|
1547
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1548
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1549
|
+
} catch {
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
/** Purge all expired entries. Returns number deleted. */
|
|
1553
|
+
purgeExpired() {
|
|
1554
|
+
this.ensureDir();
|
|
1555
|
+
if (!this.dirReady) return 0;
|
|
1556
|
+
if (this._db) {
|
|
1557
|
+
const now2 = Date.now();
|
|
1558
|
+
const expired = this._stmtExpire.all(now2);
|
|
1559
|
+
for (const row of expired) {
|
|
1560
|
+
try {
|
|
1561
|
+
fs.unlinkSync(row.file_path);
|
|
1562
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
|
|
1563
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1564
|
+
} catch {
|
|
1565
|
+
}
|
|
1566
|
+
}
|
|
1567
|
+
if (expired.length > 0) this._stmtDelExp.run(now2);
|
|
1568
|
+
return expired.length;
|
|
1569
|
+
}
|
|
1570
|
+
const now = Date.now();
|
|
1571
|
+
let purged = 0;
|
|
1572
|
+
const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
|
|
1573
|
+
for (const filePath of this.walkCacheFiles()) {
|
|
1574
|
+
const filename = path.basename(filePath);
|
|
1575
|
+
if (filename.endsWith(".tmp")) {
|
|
1576
|
+
try {
|
|
1577
|
+
const stat = fs.statSync(filePath);
|
|
1578
|
+
if (now - stat.mtimeMs > 5 * 60 * 1e3) {
|
|
1579
|
+
fs.unlinkSync(filePath);
|
|
1580
|
+
purged++;
|
|
1581
|
+
}
|
|
1582
|
+
} catch {
|
|
1583
|
+
}
|
|
1584
|
+
continue;
|
|
1585
|
+
}
|
|
1586
|
+
if (filename.length === 77 && filename[64] === "_") {
|
|
1587
|
+
const expiresAt = parseInt(filename.slice(65), 16);
|
|
1588
|
+
if (expiresAt <= now) {
|
|
1589
|
+
try {
|
|
1590
|
+
const sz = fs.statSync(filePath).size;
|
|
1591
|
+
fs.unlinkSync(filePath);
|
|
1592
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
1593
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1594
|
+
purged++;
|
|
1595
|
+
} catch {
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
continue;
|
|
1599
|
+
}
|
|
1600
|
+
let fd = -1;
|
|
1601
|
+
try {
|
|
1602
|
+
fd = fs.openSync(filePath, "r");
|
|
1603
|
+
const bytesRead = fs.readSync(fd, headerBuf, 0, V2_HEADER_LEN, 0);
|
|
1604
|
+
fs.closeSync(fd);
|
|
1605
|
+
fd = -1;
|
|
1606
|
+
if (bytesRead === V2_HEADER_LEN && headerBuf.subarray(0, 8).equals(DISK_MAGIC_V2)) {
|
|
1607
|
+
const expiresAt = Number(headerBuf.readBigUInt64LE(8));
|
|
1608
|
+
if (expiresAt <= now) {
|
|
1609
|
+
try {
|
|
1610
|
+
const sz = fs.statSync(filePath).size;
|
|
1611
|
+
fs.unlinkSync(filePath);
|
|
1612
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
1613
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1614
|
+
purged++;
|
|
1615
|
+
} catch {
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
continue;
|
|
1619
|
+
}
|
|
1620
|
+
const stat = fs.statSync(filePath);
|
|
1621
|
+
if (stat.size > this.opts.entryMaxBytes) {
|
|
1622
|
+
fs.unlinkSync(filePath);
|
|
1623
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1624
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1625
|
+
purged++;
|
|
1626
|
+
continue;
|
|
1627
|
+
}
|
|
1628
|
+
const raw = fs.readFileSync(filePath);
|
|
1629
|
+
let dec;
|
|
1630
|
+
try {
|
|
1631
|
+
dec = this.decrypt(raw);
|
|
1632
|
+
} catch {
|
|
1633
|
+
fs.unlinkSync(filePath);
|
|
1634
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1635
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1636
|
+
purged++;
|
|
1637
|
+
continue;
|
|
1638
|
+
}
|
|
1639
|
+
const payload = unpack2(dec);
|
|
1640
|
+
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
1641
|
+
fs.unlinkSync(filePath);
|
|
1642
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1643
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1644
|
+
purged++;
|
|
1645
|
+
}
|
|
1646
|
+
} catch {
|
|
1647
|
+
} finally {
|
|
1648
|
+
if (fd >= 0) try {
|
|
1649
|
+
fs.closeSync(fd);
|
|
1650
|
+
} catch {
|
|
1651
|
+
}
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
return purged;
|
|
1655
|
+
}
|
|
1656
|
+
/**
|
|
1657
|
+
* Purge expired entries. Two modes depending on availability of SQLite:
|
|
1658
|
+
*
|
|
1659
|
+
* SQLite mode (Node 24 / Node 22 + --experimental-sqlite):
|
|
1660
|
+
* One indexed query (`WHERE expires_at <= now`) replaces the entire bucket
|
|
1661
|
+
* wheel. All expired entries are found and deleted in a single pass — the
|
|
1662
|
+
* 128-minute stagger is no longer necessary. `_nextJanitorBucket` is still
|
|
1663
|
+
* incremented so tests that inspect the counter continue to work.
|
|
1664
|
+
*
|
|
1665
|
+
* File-only fallback:
|
|
1666
|
+
* Original staggered bucket wheel — purges exactly one of 256 subdirectory
|
|
1667
|
+
* buckets per call, spreading the O(fileCount) work across 256 ticks.
|
|
1668
|
+
*
|
|
1669
|
+
* Returns the number of entries deleted in this tick.
|
|
1670
|
+
*/
|
|
1671
|
+
purgeNextBucket() {
|
|
1672
|
+
this.ensureDir();
|
|
1673
|
+
if (!this.dirReady) return 0;
|
|
1674
|
+
this._nextJanitorBucket = (this._nextJanitorBucket + 1) % 256;
|
|
1675
|
+
if (this._db) {
|
|
1676
|
+
const now2 = Date.now();
|
|
1677
|
+
const expired = this._stmtExpire.all(now2);
|
|
1678
|
+
for (const row of expired) {
|
|
1679
|
+
try {
|
|
1680
|
+
fs.unlinkSync(row.file_path);
|
|
1681
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
|
|
1682
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1683
|
+
} catch {
|
|
1684
|
+
}
|
|
1685
|
+
}
|
|
1686
|
+
if (expired.length > 0) this._stmtDelExp.run(now2);
|
|
1687
|
+
const orphanBucket = (this._nextJanitorBucket - 1 + 256) % 256;
|
|
1688
|
+
const orphanBucketP = path.join(this.opts.dir, orphanBucket.toString(16).padStart(2, "0"));
|
|
1689
|
+
let orphanFiles;
|
|
1690
|
+
try {
|
|
1691
|
+
orphanFiles = fs.readdirSync(orphanBucketP);
|
|
1692
|
+
} catch {
|
|
1693
|
+
return expired.length;
|
|
1694
|
+
}
|
|
1695
|
+
for (const file of orphanFiles) {
|
|
1696
|
+
if (file.endsWith(".tmp")) {
|
|
1697
|
+
const fp = path.join(orphanBucketP, file);
|
|
1698
|
+
try {
|
|
1699
|
+
const stat = fs.statSync(fp);
|
|
1700
|
+
if (now2 - stat.mtimeMs > 5 * 60 * 1e3) {
|
|
1701
|
+
fs.unlinkSync(fp);
|
|
1702
|
+
}
|
|
1703
|
+
} catch {
|
|
1704
|
+
}
|
|
1705
|
+
continue;
|
|
1706
|
+
}
|
|
1707
|
+
if (file.length === 77 && file[64] === "_") {
|
|
1708
|
+
const expiresAt = parseInt(file.slice(65), 16);
|
|
1709
|
+
if (expiresAt <= now2) {
|
|
1710
|
+
const fp = path.join(orphanBucketP, file);
|
|
1711
|
+
try {
|
|
1712
|
+
const sz = fs.statSync(fp).size;
|
|
1713
|
+
fs.unlinkSync(fp);
|
|
1714
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
1715
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1716
|
+
} catch {
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
}
|
|
1720
|
+
}
|
|
1721
|
+
return expired.length;
|
|
1722
|
+
}
|
|
1723
|
+
const bucket = (this._nextJanitorBucket - 1 + 256) % 256;
|
|
1724
|
+
const bucketHex = bucket.toString(16).padStart(2, "0");
|
|
1725
|
+
const bucketPath = path.join(this.opts.dir, bucketHex);
|
|
1726
|
+
let files;
|
|
1727
|
+
try {
|
|
1728
|
+
files = fs.readdirSync(bucketPath);
|
|
1729
|
+
} catch {
|
|
1730
|
+
return 0;
|
|
1731
|
+
}
|
|
1732
|
+
const now = Date.now();
|
|
1733
|
+
let purged = 0;
|
|
1734
|
+
const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
|
|
1735
|
+
for (const file of files) {
|
|
1736
|
+
if (file.endsWith(".tmp")) {
|
|
1737
|
+
const fp = path.join(bucketPath, file);
|
|
1738
|
+
try {
|
|
1739
|
+
const stat = fs.statSync(fp);
|
|
1740
|
+
if (now - stat.mtimeMs > 5 * 60 * 1e3) {
|
|
1741
|
+
fs.unlinkSync(fp);
|
|
1742
|
+
purged++;
|
|
1743
|
+
}
|
|
1744
|
+
} catch {
|
|
1745
|
+
}
|
|
1746
|
+
continue;
|
|
1747
|
+
}
|
|
1748
|
+
if (file.length === 77 && file[64] === "_") {
|
|
1749
|
+
const expiresAt = parseInt(file.slice(65), 16);
|
|
1750
|
+
if (expiresAt <= now) {
|
|
1751
|
+
const filePath2 = path.join(bucketPath, file);
|
|
1752
|
+
try {
|
|
1753
|
+
const sz = fs.statSync(filePath2).size;
|
|
1754
|
+
fs.unlinkSync(filePath2);
|
|
1755
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
1756
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1757
|
+
purged++;
|
|
1758
|
+
} catch {
|
|
1759
|
+
}
|
|
1760
|
+
}
|
|
1761
|
+
continue;
|
|
1762
|
+
}
|
|
1763
|
+
const filePath = path.join(bucketPath, file);
|
|
1764
|
+
let fd = -1;
|
|
1765
|
+
try {
|
|
1766
|
+
fd = fs.openSync(filePath, "r");
|
|
1767
|
+
const bytesRead = fs.readSync(fd, headerBuf, 0, V2_HEADER_LEN, 0);
|
|
1768
|
+
fs.closeSync(fd);
|
|
1769
|
+
fd = -1;
|
|
1770
|
+
if (bytesRead === V2_HEADER_LEN && headerBuf.subarray(0, 8).equals(DISK_MAGIC_V2)) {
|
|
1771
|
+
const expiresAt = Number(headerBuf.readBigUInt64LE(8));
|
|
1772
|
+
if (expiresAt <= now) {
|
|
1773
|
+
try {
|
|
1774
|
+
const sz = fs.statSync(filePath).size;
|
|
1775
|
+
fs.unlinkSync(filePath);
|
|
1776
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
1777
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1778
|
+
purged++;
|
|
1779
|
+
} catch {
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
1782
|
+
continue;
|
|
1783
|
+
}
|
|
1784
|
+
const stat = fs.statSync(filePath);
|
|
1785
|
+
if (stat.size > this.opts.entryMaxBytes) {
|
|
1786
|
+
fs.unlinkSync(filePath);
|
|
1787
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1788
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1789
|
+
purged++;
|
|
1790
|
+
continue;
|
|
1791
|
+
}
|
|
1792
|
+
const raw = fs.readFileSync(filePath);
|
|
1793
|
+
let dec;
|
|
1794
|
+
try {
|
|
1795
|
+
dec = this.decrypt(raw);
|
|
1796
|
+
} catch {
|
|
1797
|
+
fs.unlinkSync(filePath);
|
|
1798
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1799
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1800
|
+
purged++;
|
|
1801
|
+
continue;
|
|
1802
|
+
}
|
|
1803
|
+
const payload = unpack2(dec);
|
|
1804
|
+
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
1805
|
+
fs.unlinkSync(filePath);
|
|
1806
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1807
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1808
|
+
purged++;
|
|
1809
|
+
}
|
|
1810
|
+
} catch {
|
|
1811
|
+
} finally {
|
|
1812
|
+
if (fd >= 0) try {
|
|
1813
|
+
fs.closeSync(fd);
|
|
1814
|
+
} catch {
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
return purged;
|
|
1819
|
+
}
|
|
1820
|
+
/** Delete every file in the disk cache. Returns the count deleted. */
|
|
1821
|
+
clear() {
|
|
1822
|
+
this.ensureDir();
|
|
1823
|
+
if (!this.dirReady) return 0;
|
|
1824
|
+
let cleared = 0;
|
|
1825
|
+
for (const filePath of this.walkCacheFiles()) {
|
|
1826
|
+
try {
|
|
1827
|
+
const stat = fs.statSync(filePath);
|
|
1828
|
+
fs.unlinkSync(filePath);
|
|
1829
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1830
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1831
|
+
cleared++;
|
|
1832
|
+
} catch {
|
|
1833
|
+
}
|
|
1834
|
+
}
|
|
1835
|
+
if (this._db) {
|
|
1836
|
+
this._db.exec("DELETE FROM meta");
|
|
1837
|
+
this.diskUsageBytes = 0;
|
|
1838
|
+
this.fileCount = 0;
|
|
1839
|
+
}
|
|
1840
|
+
return cleared;
|
|
1841
|
+
}
|
|
1842
|
+
get stats() {
|
|
1843
|
+
if (this._db) {
|
|
1844
|
+
const row = this._stmtStats.get();
|
|
1845
|
+
this.fileCount = row.cnt;
|
|
1846
|
+
this.diskUsageBytes = row.bytes;
|
|
1847
|
+
}
|
|
1848
|
+
return { files: this.fileCount, sizeKB: Math.round(this.diskUsageBytes / 1024), maxKB: Math.round(this.opts.maxBytes / 1024) };
|
|
1849
|
+
}
|
|
1850
|
+
/** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
|
|
1851
|
+
get indexMode() {
|
|
1852
|
+
return this._db ? "sqlite" : "file-only";
|
|
1853
|
+
}
|
|
1854
|
+
/** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
|
|
1855
|
+
close() {
|
|
1856
|
+
if (this._db) {
|
|
1857
|
+
try {
|
|
1858
|
+
this._db.close();
|
|
1859
|
+
} catch {
|
|
1860
|
+
}
|
|
1861
|
+
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
|
|
1862
|
+
}
|
|
1863
|
+
}
|
|
1864
|
+
};
|
|
1865
|
+
|
|
1866
|
+
// src/cache-service.ts
|
|
1867
|
+
var LUA_COMPARE_AND_DELETE = `
|
|
1868
|
+
local currentTs = redis.call('HGET', KEYS[1], 't')
|
|
1869
|
+
if currentTs and currentTs == ARGV[1] then
|
|
1870
|
+
return redis.call('DEL', KEYS[1])
|
|
1871
|
+
end
|
|
1872
|
+
return 0
|
|
1873
|
+
`;
|
|
1874
|
+
var SNAPSHOT_VERSION = 1;
|
|
1875
|
+
var DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
|
|
1876
|
+
var INDEFINITE_TTL_SECONDS = 31536e3;
|
|
1877
|
+
var SNAPSHOT_MAX_FILE_BYTES = 220 * 1024 * 1024;
|
|
1878
|
+
var DEFAULT_CATEGORY_LIMITS = {
|
|
1879
|
+
"default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
|
|
1880
|
+
};
|
|
1881
|
+
var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
|
|
1882
|
+
var DEFAULT_COUNTER_TTL_SECONDS = 60;
|
|
1883
|
+
var GLOB_REGEX_CACHE_MAX = 256;
|
|
1884
|
+
var globRegexCache = /* @__PURE__ */ new Map();
|
|
1885
|
+
function getGlobRegex(pattern) {
|
|
1886
|
+
let re = globRegexCache.get(pattern);
|
|
1887
|
+
if (re) {
|
|
1888
|
+
globRegexCache.delete(pattern);
|
|
1889
|
+
globRegexCache.set(pattern, re);
|
|
1890
|
+
return re;
|
|
1891
|
+
}
|
|
1892
|
+
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*+/g, ".*");
|
|
1893
|
+
re = new RegExp("^" + escaped + "$");
|
|
1894
|
+
if (globRegexCache.size >= GLOB_REGEX_CACHE_MAX) {
|
|
1895
|
+
const oldestKey = globRegexCache.keys().next().value;
|
|
1896
|
+
if (oldestKey !== void 0) globRegexCache.delete(oldestKey);
|
|
1897
|
+
}
|
|
1898
|
+
globRegexCache.set(pattern, re);
|
|
1899
|
+
return re;
|
|
1900
|
+
}
|
|
1901
|
+
var L2CircuitBreaker = class {
|
|
1902
|
+
constructor(threshold, cooldownMs) {
|
|
1903
|
+
this.threshold = threshold;
|
|
1904
|
+
this.cooldownMs = cooldownMs;
|
|
1905
|
+
}
|
|
1906
|
+
threshold;
|
|
1907
|
+
cooldownMs;
|
|
1908
|
+
state = 0 /* CLOSED */;
|
|
1909
|
+
failures = 0;
|
|
1910
|
+
openedAt = 0;
|
|
1911
|
+
/** True while the single permitted HALF_OPEN probe is in flight. */
|
|
1912
|
+
probing = false;
|
|
1913
|
+
/**
|
|
1914
|
+
* Call before each Redis attempt. Returns false when the circuit is open.
|
|
1915
|
+
* In HALF_OPEN, only ONE probe is permitted at a time — concurrent callers
|
|
1916
|
+
* arriving while a probe is outstanding are rejected (return false) so a
|
|
1917
|
+
* recovering Redis node is not stampeded.
|
|
1918
|
+
*/
|
|
1919
|
+
isAllowed() {
|
|
1920
|
+
if (this.state === 0 /* CLOSED */) return true;
|
|
1921
|
+
if (this.state === 2 /* HALF_OPEN */) {
|
|
1922
|
+
if (this.probing) return false;
|
|
1923
|
+
this.probing = true;
|
|
1924
|
+
return true;
|
|
1925
|
+
}
|
|
1926
|
+
if (Date.now() - this.openedAt >= this.cooldownMs) {
|
|
1927
|
+
this.state = 2 /* HALF_OPEN */;
|
|
1928
|
+
this.probing = true;
|
|
1929
|
+
return true;
|
|
1930
|
+
}
|
|
1931
|
+
return false;
|
|
1932
|
+
}
|
|
1933
|
+
/** Call on Redis success. */
|
|
1934
|
+
onSuccess() {
|
|
1935
|
+
this.failures = 0;
|
|
1936
|
+
this.probing = false;
|
|
1937
|
+
this.state = 0 /* CLOSED */;
|
|
1938
|
+
}
|
|
1939
|
+
/** Call on Redis failure. */
|
|
1940
|
+
onFailure() {
|
|
1941
|
+
this.failures++;
|
|
1942
|
+
this.probing = false;
|
|
1943
|
+
if (this.state === 2 /* HALF_OPEN */ || this.failures >= this.threshold) {
|
|
1944
|
+
this.state = 1 /* OPEN */;
|
|
1945
|
+
this.openedAt = Date.now();
|
|
1946
|
+
this.failures = 0;
|
|
1947
|
+
}
|
|
1948
|
+
}
|
|
1949
|
+
get isOpen() {
|
|
1950
|
+
return this.state === 1 /* OPEN */;
|
|
1951
|
+
}
|
|
1952
|
+
get currentState() {
|
|
1953
|
+
return this.state === 0 /* CLOSED */ ? "closed" : this.state === 1 /* OPEN */ ? "open" : "half_open";
|
|
1954
|
+
}
|
|
1955
|
+
};
|
|
1956
|
+
function deepFreeze(obj) {
|
|
1957
|
+
if (obj === null || typeof obj !== "object" || Object.isFrozen(obj)) return obj;
|
|
1958
|
+
Object.freeze(obj);
|
|
1959
|
+
for (const v of Object.values(obj)) deepFreeze(v);
|
|
1960
|
+
return obj;
|
|
1961
|
+
}
|
|
1962
|
+
var LatencyTracker = class {
|
|
1963
|
+
samples;
|
|
1964
|
+
maxKeys;
|
|
1965
|
+
bufs = /* @__PURE__ */ new Map();
|
|
1966
|
+
meta = /* @__PURE__ */ new Map();
|
|
1967
|
+
/** Shared sort buffer — safe to reuse because JS is single-threaded. */
|
|
1968
|
+
scratch;
|
|
1969
|
+
constructor(samples, maxKeys) {
|
|
1970
|
+
this.samples = samples;
|
|
1971
|
+
this.maxKeys = maxKeys;
|
|
1972
|
+
this.scratch = new Float64Array(samples);
|
|
1973
|
+
}
|
|
1974
|
+
record(key, deltaMs) {
|
|
1975
|
+
let buf = this.bufs.get(key);
|
|
1976
|
+
let m = this.meta.get(key);
|
|
1977
|
+
if (buf === void 0) {
|
|
1978
|
+
if (this.bufs.size >= this.maxKeys) {
|
|
1979
|
+
const oldest = this.bufs.keys().next().value;
|
|
1980
|
+
this.bufs.delete(oldest);
|
|
1981
|
+
this.meta.delete(oldest);
|
|
1982
|
+
}
|
|
1983
|
+
buf = new Float64Array(this.samples);
|
|
1984
|
+
m = { head: 0, count: 0, p95: 0, dirty: false };
|
|
1985
|
+
this.bufs.set(key, buf);
|
|
1986
|
+
this.meta.set(key, m);
|
|
1987
|
+
}
|
|
1988
|
+
buf[m.head] = deltaMs;
|
|
1989
|
+
m.head = (m.head + 1) % this.samples;
|
|
1990
|
+
if (m.count < this.samples) m.count++;
|
|
1991
|
+
m.dirty = true;
|
|
1992
|
+
}
|
|
1993
|
+
/**
|
|
1994
|
+
* Recomputes the p95 for the given key into `m.p95` and clears `m.dirty`.
|
|
1995
|
+
* Uses the shared scratch buffer — no heap allocation.
|
|
1996
|
+
*/
|
|
1997
|
+
_computeP95(buf, m) {
|
|
1998
|
+
const n = m.count;
|
|
1999
|
+
this.scratch.set(buf.subarray(0, n));
|
|
2000
|
+
const view = this.scratch.subarray(0, n);
|
|
2001
|
+
view.sort();
|
|
2002
|
+
m.p95 = view[Math.ceil(n * 0.95) - 1];
|
|
2003
|
+
m.dirty = false;
|
|
2004
|
+
}
|
|
2005
|
+
/**
|
|
2006
|
+
* Returns the p95 fetch latency for `key` in milliseconds, or `null` when
|
|
2007
|
+
* fewer than 5 samples have been collected (not enough data yet).
|
|
2008
|
+
* Uses a dirty-flag cache — sort only runs when a new sample was recorded.
|
|
2009
|
+
*/
|
|
2010
|
+
p95(key) {
|
|
2011
|
+
const buf = this.bufs.get(key);
|
|
2012
|
+
const m = this.meta.get(key);
|
|
2013
|
+
if (!buf || !m || m.count < 5) return null;
|
|
2014
|
+
if (m.dirty) this._computeP95(buf, m);
|
|
2015
|
+
return m.p95;
|
|
2016
|
+
}
|
|
2017
|
+
get trackedKeys() {
|
|
2018
|
+
return this.bufs.size;
|
|
2019
|
+
}
|
|
2020
|
+
/**
|
|
2021
|
+
* Top-20 slowest keys by p95, sorted descending.
|
|
2022
|
+
* Keys with < 5 samples are excluded (not enough data for a reliable p95).
|
|
2023
|
+
*
|
|
2024
|
+
* Only dirty keys (those with new samples since the last call) pay the sort
|
|
2025
|
+
* cost. Keys whose p95 is already cached are O(1) reads — so repeated
|
|
2026
|
+
* metrics() calls with no intervening fetches are essentially free.
|
|
2027
|
+
*/
|
|
2028
|
+
snapshot(prefixLen, multiplierSec, minMs, maxMs) {
|
|
2029
|
+
const out = [];
|
|
2030
|
+
for (const [key, buf] of this.bufs) {
|
|
2031
|
+
const m = this.meta.get(key);
|
|
2032
|
+
if (m.count < 5) continue;
|
|
2033
|
+
if (m.dirty) this._computeP95(buf, m);
|
|
2034
|
+
const p95 = m.p95;
|
|
2035
|
+
const adaptedMs = Math.max(minMs, Math.min(maxMs, Math.round(p95 * multiplierSec * 1e3)));
|
|
2036
|
+
out.push({
|
|
2037
|
+
key: prefixLen > 0 ? key.slice(prefixLen) : key,
|
|
2038
|
+
p95Ms: Math.round(p95),
|
|
2039
|
+
adaptedTtlSec: Math.round(adaptedMs / 1e3)
|
|
2040
|
+
});
|
|
2041
|
+
}
|
|
2042
|
+
return out.sort((a, b) => b.p95Ms - a.p95Ms).slice(0, 20);
|
|
2043
|
+
}
|
|
2044
|
+
};
|
|
2045
|
+
function inferPriority(cacheKey) {
|
|
2046
|
+
if (cacheKey.includes("auth:") || cacheKey.includes("session:")) return 4 /* CRITICAL */;
|
|
2047
|
+
if (cacheKey.includes("user:") || cacheKey.includes("org:") || cacheKey.includes("profile:")) return 3 /* HIGH */;
|
|
2048
|
+
if (cacheKey.includes("analytics:") || cacheKey.includes("report:") || cacheKey.includes("stats:")) return 1 /* LOW */;
|
|
2049
|
+
return 2 /* NORMAL */;
|
|
2050
|
+
}
|
|
2051
|
+
var GLOBAL_KEY = "__tricache_instance__";
|
|
2052
|
+
function detectServerlessRuntime() {
|
|
2053
|
+
if (process.env["AWS_LAMBDA_FUNCTION_NAME"]) return "AWS Lambda";
|
|
2054
|
+
if (process.env["K_SERVICE"]) return "Google Cloud Run";
|
|
2055
|
+
if (process.env["FUNCTION_TARGET"]) return "Google Cloud Functions";
|
|
2056
|
+
if (process.env["WEBSITE_INSTANCE_ID"]) return "Azure Functions";
|
|
2057
|
+
if (process.env["FLY_APP_NAME"]) return "Fly.io";
|
|
2058
|
+
if (process.env["RAILWAY_ENVIRONMENT"]) return "Railway";
|
|
2059
|
+
if (process.env["VERCEL"]) return "Vercel";
|
|
2060
|
+
return null;
|
|
2061
|
+
}
|
|
2062
|
+
var CacheService = class _CacheService {
|
|
2063
|
+
logger;
|
|
2064
|
+
enc;
|
|
2065
|
+
l1;
|
|
2066
|
+
disk;
|
|
2067
|
+
/** When true, all disk-tier and snapshot operations are skipped. */
|
|
2068
|
+
_diskDisabled = false;
|
|
2069
|
+
/** Worker pool for off-main-thread AES-GCM (null when workerThreads is false or unavailable). */
|
|
2070
|
+
_workerPool = null;
|
|
2071
|
+
opts;
|
|
2072
|
+
/** Pre-computed once — opts.namespace never changes after construction. */
|
|
2073
|
+
_namespace;
|
|
2074
|
+
/** Pre-computed once — disableRedis and redisHost never change after construction. */
|
|
2075
|
+
_redisDisabled;
|
|
2076
|
+
inflight = /* @__PURE__ */ new Map();
|
|
2077
|
+
revalidating = /* @__PURE__ */ new Set();
|
|
2078
|
+
_l1Counters = /* @__PURE__ */ new Map();
|
|
2079
|
+
/** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
|
|
2080
|
+
tagIndex = /* @__PURE__ */ new Map();
|
|
2081
|
+
/** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
|
|
2082
|
+
tagVersions = /* @__PURE__ */ new Map();
|
|
2083
|
+
/**
|
|
2084
|
+
* Dependency index: source glob pattern → Set of namespaced dependent keys.
|
|
2085
|
+
* When an exact-key delete matches a registered pattern, all dependents are cascaded.
|
|
2086
|
+
*/
|
|
2087
|
+
dependencyIndex = /* @__PURE__ */ new Map();
|
|
2088
|
+
redis = null;
|
|
2089
|
+
redisConnecting = null;
|
|
2090
|
+
cb;
|
|
2091
|
+
/** In-process mutex lock map for single-process environments or Redis outages. */
|
|
2092
|
+
_localLocks = /* @__PURE__ */ new Map();
|
|
2093
|
+
/** Active OpenTelemetry monotonic counters. */
|
|
2094
|
+
_otelMetrics = {};
|
|
2095
|
+
snapshotLoaded = false;
|
|
2096
|
+
_readyPromise = Promise.resolve();
|
|
2097
|
+
cleanupInterval = null;
|
|
2098
|
+
diskJanitorInterval = null;
|
|
2099
|
+
oomInterval = null;
|
|
2100
|
+
metricsInterval = null;
|
|
2101
|
+
_shutdownHandler = null;
|
|
2102
|
+
latencyTracker = null;
|
|
2103
|
+
instanceId;
|
|
2104
|
+
backplaneChannel;
|
|
2105
|
+
backplaneStreamKey;
|
|
2106
|
+
subClient = null;
|
|
2107
|
+
streamClient = null;
|
|
2108
|
+
_lastStreamId = "$";
|
|
2109
|
+
_destroyed = false;
|
|
2110
|
+
/** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
|
|
2111
|
+
_subDisconnectedAt = null;
|
|
2112
|
+
counters = {
|
|
2113
|
+
gets: 0,
|
|
2114
|
+
l1Hits: 0,
|
|
2115
|
+
diskHits: 0,
|
|
2116
|
+
l2Hits: 0,
|
|
2117
|
+
fetches: 0,
|
|
2118
|
+
stampedes: 0,
|
|
2119
|
+
sets: 0,
|
|
2120
|
+
deletes: 0,
|
|
2121
|
+
swrRevalidations: 0,
|
|
2122
|
+
invSent: 0,
|
|
2123
|
+
invReceived: 0,
|
|
2124
|
+
invSkipped: 0,
|
|
2125
|
+
streamEntriesReceived: 0,
|
|
2126
|
+
streamReplays: 0,
|
|
2127
|
+
streamGaps: 0,
|
|
2128
|
+
oomEvictions: 0,
|
|
2129
|
+
oomLastAt: null,
|
|
2130
|
+
/** Times `increment()` hit a Redis error (fail-open by default, or fail-closed re-throw). */
|
|
2131
|
+
counterErrors: 0,
|
|
2132
|
+
/** Times a later `create(ns)` call passed options differing from the live singleton. */
|
|
2133
|
+
singletonDivergences: 0,
|
|
2134
|
+
startedAt: Date.now(),
|
|
2135
|
+
bloomChecks: 0,
|
|
2136
|
+
bloomFalsePositives: 0
|
|
2137
|
+
};
|
|
2138
|
+
/** One-time guard so the in-process increment() fallback warning fires only once. */
|
|
2139
|
+
_incrementFallbackWarned = false;
|
|
2140
|
+
// ── Constructor (use CacheService.create() for the recommended singleton) ──
|
|
2141
|
+
constructor(options = {}) {
|
|
2142
|
+
const logger = options.logger ?? consoleLogger;
|
|
2143
|
+
this.logger = logger;
|
|
2144
|
+
const ns = options.namespace?.trim() ?? "";
|
|
2145
|
+
const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
|
|
2146
|
+
this.enc = new CacheEncryption(
|
|
2147
|
+
encKeyRaw,
|
|
2148
|
+
logger,
|
|
2149
|
+
options.encryptionMode,
|
|
2150
|
+
options.previousEncryptionKey,
|
|
2151
|
+
options.previousEncryptionMode,
|
|
2152
|
+
{ strictKeyValidation: options.strictKeyValidation ?? false }
|
|
2153
|
+
);
|
|
2154
|
+
const rawForbidden = options.forbiddenSnapshotPrefixes ?? [...DEFAULT_FORBIDDEN_PREFIXES];
|
|
2155
|
+
const forbiddenPrefixes = ns ? rawForbidden.map((p) => `${ns}:${p}`) : rawForbidden;
|
|
2156
|
+
this.opts = {
|
|
2157
|
+
namespace: ns,
|
|
2158
|
+
logger,
|
|
2159
|
+
l1MaxBytes: options.l1MaxBytes ?? 200 * 1024 * 1024,
|
|
2160
|
+
l1MaxEntries: options.l1MaxEntries ?? 2e3,
|
|
2161
|
+
categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...options.categoryLimits },
|
|
2162
|
+
forbiddenSnapshotPrefixes: forbiddenPrefixes,
|
|
2163
|
+
// Namespace-isolated defaults: separate dir / snapshot per namespace so
|
|
2164
|
+
// two instances with different namespaces never share cache files.
|
|
2165
|
+
diskCacheDir: options.diskCacheDir ?? path2.join(
|
|
2166
|
+
os2.tmpdir(),
|
|
2167
|
+
ns ? `tricache-disk-${ns}` : "tricache-disk"
|
|
2168
|
+
),
|
|
2169
|
+
diskMaxBytes: options.diskMaxBytes ?? 500 * 1024 * 1024,
|
|
2170
|
+
diskEntryMaxBytes: options.diskEntryMaxBytes ?? 10 * 1024 * 1024,
|
|
2171
|
+
redisHost: options.redisHost ?? process.env.REDIS_HOST ?? "",
|
|
2172
|
+
redisPort: options.redisPort ?? 6379,
|
|
2173
|
+
redisTls: options.redisTls ?? process.env.NODE_ENV === "production",
|
|
2174
|
+
disableRedis: options.disableRedis ?? (() => {
|
|
2175
|
+
const explicitConfig = Boolean(
|
|
2176
|
+
options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
|
|
2177
|
+
);
|
|
2178
|
+
return !explicitConfig && process.env.NODE_ENV !== "production";
|
|
2179
|
+
})(),
|
|
2180
|
+
encryptionKey: encKeyRaw,
|
|
2181
|
+
encryptionMode: options.encryptionMode,
|
|
2182
|
+
snapshotPath: options.snapshotPath ?? path2.join(
|
|
2183
|
+
os2.tmpdir(),
|
|
2184
|
+
ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
|
|
2185
|
+
),
|
|
2186
|
+
snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
|
|
2187
|
+
invalidationBackplane: options.invalidationBackplane ?? true,
|
|
2188
|
+
oomProtection: options.oomProtection ?? true,
|
|
2189
|
+
oomHeapThreshold: options.oomHeapThreshold ?? 0.85,
|
|
2190
|
+
oomCheckIntervalMs: options.oomCheckIntervalMs ?? 1e4,
|
|
2191
|
+
oomEvictPercent: options.oomEvictPercent ?? 0.2,
|
|
2192
|
+
onMetrics: options.onMetrics,
|
|
2193
|
+
metricsIntervalMs: options.metricsIntervalMs ?? 6e4,
|
|
2194
|
+
staleIfError: options.staleIfError ?? 0,
|
|
2195
|
+
l2WriteMode: options.l2WriteMode ?? "read-write",
|
|
2196
|
+
instanceName: options.instanceName ?? "",
|
|
2197
|
+
l1EvictionWatermark: Math.min(Math.max(options.l1EvictionWatermark ?? 0.9, 0), 1),
|
|
2198
|
+
ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
|
|
2199
|
+
tracer: options.tracer,
|
|
2200
|
+
meter: options.meter,
|
|
2201
|
+
notFoundTtl: options.notFoundTtl ?? 0,
|
|
2202
|
+
warmKeys: options.warmKeys,
|
|
2203
|
+
onHit: options.onHit,
|
|
2204
|
+
onMiss: options.onMiss,
|
|
2205
|
+
frozen: options.frozen ?? false,
|
|
2206
|
+
adaptiveTtl: options.adaptiveTtl ?? false,
|
|
2207
|
+
adaptiveTtlMinMs: (options.adaptiveTtlMin ?? 10) * 1e3,
|
|
2208
|
+
adaptiveTtlMaxMs: (options.adaptiveTtlMax ?? 86400) * 1e3,
|
|
2209
|
+
adaptiveTtlMultiplier: options.adaptiveTtlMultiplier ?? 20,
|
|
2210
|
+
workerThreads: options.workerThreads ?? false,
|
|
2211
|
+
workerThresholdBytes: options.workerThresholdBytes ?? 131072,
|
|
2212
|
+
// 128 KB
|
|
2213
|
+
workerPoolSize: options.workerPoolSize ?? 0,
|
|
2214
|
+
// 0 = auto (min(4, cpus))
|
|
2215
|
+
backplaneMaxStalenessMs: options.backplaneMaxStalenessMs ?? 5e3,
|
|
2216
|
+
disableDisk: options.disableDisk ?? false,
|
|
2217
|
+
redisClusterNodes: options.redisClusterNodes,
|
|
2218
|
+
redisSentinel: options.redisSentinel,
|
|
2219
|
+
redisProtocol: options.redisProtocol,
|
|
2220
|
+
useShardedPubSub: options.useShardedPubSub ?? false,
|
|
2221
|
+
compression: options.compression ?? "none",
|
|
2222
|
+
compressionThresholdBytes: options.compressionThresholdBytes ?? 1024,
|
|
2223
|
+
strictSingleton: options.strictSingleton ?? false,
|
|
2224
|
+
failClosed: options.failClosed ?? false,
|
|
2225
|
+
tagStrategy: options.tagStrategy ?? "set",
|
|
2226
|
+
tagVersionTtlMs: options.tagVersionTtlMs ?? 5e3,
|
|
2227
|
+
cloneStrategy: options.cloneStrategy ?? "none",
|
|
2228
|
+
backplaneMode: options.backplaneMode ?? "pubsub",
|
|
2229
|
+
backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
|
|
2230
|
+
backplaneStreamBlockMs: options.backplaneStreamBlockMs ?? 2e3,
|
|
2231
|
+
backplaneStreamKey: options.backplaneStreamKey
|
|
2232
|
+
};
|
|
2233
|
+
const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
|
|
2234
|
+
const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
|
|
2235
|
+
this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
|
|
2236
|
+
if (this.opts.adaptiveTtl) {
|
|
2237
|
+
const samples = options.adaptiveTtlSamples ?? 32;
|
|
2238
|
+
const maxKeys = options.adaptiveTtlMaxKeys ?? 5e3;
|
|
2239
|
+
this.latencyTracker = new LatencyTracker(samples, maxKeys);
|
|
2240
|
+
}
|
|
2241
|
+
let diskDisabled = this.opts.disableDisk;
|
|
2242
|
+
if (options.disableDisk === void 0) {
|
|
2243
|
+
const serverless = detectServerlessRuntime();
|
|
2244
|
+
if (serverless !== null) {
|
|
2245
|
+
diskDisabled = true;
|
|
2246
|
+
logger.warn("tricache: disk tier auto-disabled (ephemeral filesystem detected)", {
|
|
2247
|
+
runtime: serverless,
|
|
2248
|
+
hint: "Set disableDisk: false to override, or disableDisk: true to silence this warning"
|
|
2249
|
+
});
|
|
2250
|
+
}
|
|
2251
|
+
} else if (diskDisabled) {
|
|
2252
|
+
logger.info("tricache: disk tier explicitly disabled (disableDisk: true)");
|
|
2253
|
+
}
|
|
2254
|
+
this._diskDisabled = diskDisabled;
|
|
2255
|
+
this.disk = new DiskTier({
|
|
2256
|
+
dir: this.opts.diskCacheDir,
|
|
2257
|
+
maxBytes: this.opts.diskMaxBytes,
|
|
2258
|
+
entryMaxBytes: this.opts.diskEntryMaxBytes,
|
|
2259
|
+
forbiddenPrefixes,
|
|
2260
|
+
encryption: this.enc.isEnabled ? this.enc : null,
|
|
2261
|
+
compression: this.opts.compression,
|
|
2262
|
+
compressionThresholdBytes: this.opts.compressionThresholdBytes,
|
|
2263
|
+
logger
|
|
2264
|
+
});
|
|
2265
|
+
this._namespace = ns;
|
|
2266
|
+
this._redisDisabled = this.opts.disableRedis || !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
|
|
2267
|
+
this.l1 = new SmartMemoryCache({
|
|
2268
|
+
maxBytes: this.opts.l1MaxBytes,
|
|
2269
|
+
maxEntries: this.opts.l1MaxEntries,
|
|
2270
|
+
categories: this.opts.categoryLimits,
|
|
2271
|
+
evictionWatermark: this.opts.l1EvictionWatermark,
|
|
2272
|
+
diskSpill: (key, entry) => {
|
|
2273
|
+
if (this._diskDisabled) return;
|
|
2274
|
+
setImmediate(() => {
|
|
2275
|
+
void this.disk.save(key, entry);
|
|
2276
|
+
});
|
|
2277
|
+
},
|
|
2278
|
+
onEviction: options.onEviction,
|
|
2279
|
+
logger
|
|
2280
|
+
});
|
|
2281
|
+
if (!this.snapshotLoaded) {
|
|
2282
|
+
this.snapshotLoaded = true;
|
|
2283
|
+
if (!this._diskDisabled) this.loadSnapshot();
|
|
2284
|
+
}
|
|
2285
|
+
this._shutdownHandler = () => {
|
|
2286
|
+
if (!this._diskDisabled) this.writeSnapshot();
|
|
2287
|
+
};
|
|
2288
|
+
process.once("SIGTERM", this._shutdownHandler);
|
|
2289
|
+
process.once("SIGINT", this._shutdownHandler);
|
|
2290
|
+
if (this.opts.workerThreads) {
|
|
2291
|
+
try {
|
|
2292
|
+
const encRef = this.enc.toWorkerInit();
|
|
2293
|
+
this._workerPool = new WorkerPool({
|
|
2294
|
+
keyBase64: encRef.keyBase64,
|
|
2295
|
+
mode: encRef.mode,
|
|
2296
|
+
prevKeyBase64: encRef.prevKeyBase64,
|
|
2297
|
+
prevMode: encRef.prevMode,
|
|
2298
|
+
compression: this.opts.compression,
|
|
2299
|
+
compressionThresholdBytes: this.opts.compressionThresholdBytes,
|
|
2300
|
+
size: this.opts.workerPoolSize || void 0
|
|
2301
|
+
});
|
|
2302
|
+
if (this._workerPool.isAvailable) {
|
|
2303
|
+
logger.info("tricache: worker-thread encryption pool active", {
|
|
2304
|
+
threshold: `${this.opts.workerThresholdBytes / 1024} KB`
|
|
2305
|
+
});
|
|
2306
|
+
} else {
|
|
2307
|
+
this._workerPool = null;
|
|
2308
|
+
logger.warn("tricache: worker-thread pool requested but unavailable; using main-thread crypto");
|
|
2309
|
+
}
|
|
2310
|
+
} catch {
|
|
2311
|
+
this._workerPool = null;
|
|
2312
|
+
logger.warn("tricache: worker-thread pool init failed; using main-thread crypto");
|
|
2313
|
+
}
|
|
2314
|
+
}
|
|
2315
|
+
this.cleanupInterval = setInterval(() => {
|
|
2316
|
+
const cleaned = this.l1.cleanup();
|
|
2317
|
+
if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
|
|
2318
|
+
}, 5 * 60 * 1e3);
|
|
2319
|
+
if (this.cleanupInterval.unref) this.cleanupInterval.unref();
|
|
2320
|
+
if (!this._diskDisabled) {
|
|
2321
|
+
this.diskJanitorInterval = setInterval(() => {
|
|
2322
|
+
const purged = this.disk.purgeNextBucket();
|
|
2323
|
+
if (purged > 0) this.logger.debug("Disk janitor tick", { purged });
|
|
2324
|
+
}, 3e4);
|
|
2325
|
+
if (this.diskJanitorInterval.unref) this.diskJanitorInterval.unref();
|
|
2326
|
+
}
|
|
2327
|
+
if (this.opts.oomProtection) {
|
|
2328
|
+
this.oomInterval = setInterval(() => {
|
|
2329
|
+
const heap = v8.getHeapStatistics();
|
|
2330
|
+
const used = heap.used_heap_size / heap.heap_size_limit;
|
|
2331
|
+
if (used >= this.opts.oomHeapThreshold) {
|
|
2332
|
+
const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
|
|
2333
|
+
this.counters.oomEvictions++;
|
|
2334
|
+
this.counters.oomLastAt = Date.now();
|
|
2335
|
+
this.logger.warn("tricache OOM guard: emergency L1 eviction", {
|
|
2336
|
+
heapUsedPct: Math.round(used * 100),
|
|
2337
|
+
threshold: Math.round(this.opts.oomHeapThreshold * 100),
|
|
2338
|
+
evicted
|
|
2339
|
+
});
|
|
2340
|
+
}
|
|
2341
|
+
}, this.opts.oomCheckIntervalMs);
|
|
2342
|
+
if (this.oomInterval.unref) this.oomInterval.unref();
|
|
2343
|
+
}
|
|
2344
|
+
if (this.opts.onMetrics && this.opts.metricsIntervalMs > 0) {
|
|
2345
|
+
this.metricsInterval = setInterval(() => {
|
|
2346
|
+
try {
|
|
2347
|
+
this.opts.onMetrics(this.metrics());
|
|
2348
|
+
} catch {
|
|
2349
|
+
}
|
|
2350
|
+
}, this.opts.metricsIntervalMs);
|
|
2351
|
+
if (this.metricsInterval.unref) this.metricsInterval.unref();
|
|
2352
|
+
}
|
|
2353
|
+
this.instanceId = crypto2.randomBytes(8).toString("hex");
|
|
2354
|
+
this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
|
|
2355
|
+
this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
|
|
2356
|
+
this.initBackplane();
|
|
2357
|
+
if (this.opts.warmKeys) {
|
|
2358
|
+
this._readyPromise = this.warmFromL2(this.opts.warmKeys).then(() => void 0);
|
|
2359
|
+
}
|
|
2360
|
+
if (this.opts.meter) {
|
|
2361
|
+
this._initOtelMetrics(this.opts.meter);
|
|
2362
|
+
const otel = this._otelMetrics;
|
|
2363
|
+
const nsAttr = this._namespace ? { namespace: this._namespace } : void 0;
|
|
2364
|
+
const targetCounters = this.counters;
|
|
2365
|
+
this.counters = new Proxy(targetCounters, {
|
|
2366
|
+
set(target, prop, value, receiver) {
|
|
2367
|
+
const oldVal = target[prop];
|
|
2368
|
+
const ok = Reflect.set(target, prop, value, receiver);
|
|
2369
|
+
if (typeof prop === "string" && typeof value === "number" && typeof oldVal === "number") {
|
|
2370
|
+
const diff = value - oldVal;
|
|
2371
|
+
if (diff > 0 && otel[prop]) {
|
|
2372
|
+
otel[prop].add(diff, nsAttr);
|
|
2373
|
+
}
|
|
2374
|
+
}
|
|
2375
|
+
return ok;
|
|
2376
|
+
}
|
|
2377
|
+
});
|
|
2378
|
+
}
|
|
2379
|
+
}
|
|
2380
|
+
// ── Singleton factory ─────────────────────────────────────────────────────
|
|
2381
|
+
/**
|
|
2382
|
+
* Get (or create) the process-level singleton CacheService instance.
|
|
2383
|
+
*
|
|
2384
|
+
* Options are only applied on first call — subsequent calls return the
|
|
2385
|
+
* existing instance regardless of options passed. When the new options differ
|
|
2386
|
+
* from what the existing singleton was built with, this is a silent no-op by
|
|
2387
|
+
* default; set `strictSingleton: true` to throw instead, or watch the
|
|
2388
|
+
* `singletonDivergences` metric for detection.
|
|
2389
|
+
*
|
|
2390
|
+
* When `namespace` is set the singleton is keyed by namespace, so two calls
|
|
2391
|
+
* with different namespaces return independent instances.
|
|
2392
|
+
*/
|
|
2393
|
+
static create(options) {
|
|
2394
|
+
const g = globalThis;
|
|
2395
|
+
const key = _CacheService.globalKey(options);
|
|
2396
|
+
if (!g[key]) {
|
|
2397
|
+
g[key] = new _CacheService(options);
|
|
2398
|
+
return g[key];
|
|
2399
|
+
}
|
|
2400
|
+
const existing = g[key];
|
|
2401
|
+
const diff = _CacheService.optionsDiff(options ?? {}, existing.options);
|
|
2402
|
+
if (diff.length > 0) {
|
|
2403
|
+
existing.bumpSingletonDivergence();
|
|
2404
|
+
const msg = `tricache: singleton already initialised for namespace '${existing.options.namespace || "(default)"}' \u2014 ignoring divergent options: ${diff.join(", ")}`;
|
|
2405
|
+
if (existing.options.strictSingleton) {
|
|
2406
|
+
throw new Error(`strictSingleton: ${msg}`);
|
|
2407
|
+
}
|
|
2408
|
+
(existing.options.logger ?? consoleLogger).warn(msg, { divergentOptions: diff });
|
|
2409
|
+
}
|
|
2410
|
+
return existing;
|
|
2411
|
+
}
|
|
2412
|
+
/**
|
|
2413
|
+
* Keys that, if set differently on a later `create()` call, represent a
|
|
2414
|
+
* meaningful configuration divergence worth flagging (security/correctness
|
|
2415
|
+
* relevant — not cosmetic, e.g. log level).
|
|
2416
|
+
*/
|
|
2417
|
+
static DIVERGENT_KEYS = [
|
|
2418
|
+
"redisHost",
|
|
2419
|
+
"redisPort",
|
|
2420
|
+
"redisTls",
|
|
2421
|
+
"disableRedis",
|
|
2422
|
+
"redisClusterNodes",
|
|
2423
|
+
"redisSentinel",
|
|
2424
|
+
"encryptionKey",
|
|
2425
|
+
"encryptionMode",
|
|
2426
|
+
"l1MaxBytes",
|
|
2427
|
+
"l1MaxEntries",
|
|
2428
|
+
"namespace",
|
|
2429
|
+
"frozen",
|
|
2430
|
+
"adaptiveTtl",
|
|
2431
|
+
"l2WriteMode",
|
|
2432
|
+
"instanceName",
|
|
2433
|
+
"invalidationBackplane"
|
|
2434
|
+
];
|
|
2435
|
+
/** Returns the names of options that differ between `a` and the live `b`. */
|
|
2436
|
+
static optionsDiff(a, b) {
|
|
2437
|
+
const out = [];
|
|
2438
|
+
for (const k of _CacheService.DIVERGENT_KEYS) {
|
|
2439
|
+
const av = a[k];
|
|
2440
|
+
const bv = b[k];
|
|
2441
|
+
if (av === void 0) continue;
|
|
2442
|
+
const same = JSON.stringify(av) === JSON.stringify(bv) || k === "encryptionKey" && av === bv;
|
|
2443
|
+
if (!same) out.push(String(k));
|
|
2444
|
+
}
|
|
2445
|
+
return out;
|
|
2446
|
+
}
|
|
2447
|
+
/** Increment the singleton-divergence counter (surfaced in `metrics()`). */
|
|
2448
|
+
bumpSingletonDivergence() {
|
|
2449
|
+
this.counters.singletonDivergences++;
|
|
2450
|
+
}
|
|
2451
|
+
/** Read-only view of the options the singleton was constructed with. */
|
|
2452
|
+
get options() {
|
|
2453
|
+
const o = this.opts;
|
|
2454
|
+
return {
|
|
2455
|
+
namespace: o.namespace,
|
|
2456
|
+
logger: o.logger,
|
|
2457
|
+
l1MaxBytes: o.l1MaxBytes,
|
|
2458
|
+
l1MaxEntries: o.l1MaxEntries,
|
|
2459
|
+
redisHost: o.redisHost,
|
|
2460
|
+
redisPort: o.redisPort,
|
|
2461
|
+
redisTls: o.redisTls,
|
|
2462
|
+
disableRedis: this._redisDisabled,
|
|
2463
|
+
redisClusterNodes: o.redisClusterNodes,
|
|
2464
|
+
redisSentinel: o.redisSentinel,
|
|
2465
|
+
// Never surface key material through diagnostics — a JSON.stringify of
|
|
2466
|
+
// this object previously leaked the raw encryption key.
|
|
2467
|
+
encryptionKey: o.encryptionKey ? "[REDACTED]" : void 0,
|
|
2468
|
+
encryptionMode: o.encryptionMode,
|
|
2469
|
+
l2WriteMode: o.l2WriteMode,
|
|
2470
|
+
instanceName: o.instanceName,
|
|
2471
|
+
frozen: o.frozen,
|
|
2472
|
+
adaptiveTtl: o.adaptiveTtl,
|
|
2473
|
+
invalidationBackplane: o.invalidationBackplane,
|
|
2474
|
+
strictSingleton: o.strictSingleton
|
|
2475
|
+
};
|
|
2476
|
+
}
|
|
2477
|
+
/**
|
|
2478
|
+
* Async factory — accepts a Promise that resolves to CacheOptions.
|
|
2479
|
+
* Useful when config is fetched from a secret store at startup.
|
|
2480
|
+
*
|
|
2481
|
+
* @example
|
|
2482
|
+
* const cache = await CacheService.createAsync(fetchSecrets());
|
|
2483
|
+
*/
|
|
2484
|
+
static async createAsync(options) {
|
|
2485
|
+
const resolved = await options;
|
|
2486
|
+
return _CacheService.create(resolved);
|
|
2487
|
+
}
|
|
2488
|
+
/** Replace the singleton (useful in tests). */
|
|
2489
|
+
static reset(options) {
|
|
2490
|
+
const g = globalThis;
|
|
2491
|
+
const key = _CacheService.globalKey(options);
|
|
2492
|
+
const existing = g[key];
|
|
2493
|
+
if (existing) existing.destroy();
|
|
2494
|
+
g[key] = new _CacheService(options);
|
|
2495
|
+
return g[key];
|
|
2496
|
+
}
|
|
2497
|
+
/** Derive the globalThis key for a given set of options. */
|
|
2498
|
+
static globalKey(options) {
|
|
2499
|
+
const ns = options?.namespace?.trim() ?? "";
|
|
2500
|
+
return ns ? `__tricache_${ns}__` : GLOBAL_KEY;
|
|
2501
|
+
}
|
|
2502
|
+
// ── Redis connection ──────────────────────────────────────────────────────
|
|
2503
|
+
/**
|
|
2504
|
+
* Prepend the configured namespace to a raw cache key.
|
|
2505
|
+
* Returns the key unchanged when namespace is empty.
|
|
2506
|
+
*
|
|
2507
|
+
* This is the only place the namespace prefix is applied — callers always
|
|
2508
|
+
* receive and provide un-prefixed keys in the public API.
|
|
2509
|
+
*/
|
|
2510
|
+
nk(key) {
|
|
2511
|
+
return this._namespace ? `${this._namespace}:${key}` : key;
|
|
2512
|
+
}
|
|
2513
|
+
/** Strip the instance namespace prefix from a namespaced key (inverse of `nk`). */
|
|
2514
|
+
unnk(key) {
|
|
2515
|
+
return this._namespace ? key.slice(this._namespace.length + 1) : key;
|
|
2516
|
+
}
|
|
2517
|
+
/** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
|
|
2518
|
+
_jitterTtl(ttlMs) {
|
|
2519
|
+
const j = this.opts.ttlJitterFactor;
|
|
2520
|
+
if (j === 0) return ttlMs;
|
|
2521
|
+
const rand = crypto2.randomInt(0, 1e5) / 5e4 - 1;
|
|
2522
|
+
return Math.round(ttlMs * (1 + rand * j));
|
|
2523
|
+
}
|
|
2524
|
+
/** Shared no-op span for the common case where no tracer is configured.
|
|
2525
|
+
* Using a singleton avoids allocating a fresh object literal on every get/set/delete call. */
|
|
2526
|
+
static _nullSpan = {
|
|
2527
|
+
setAttribute() {
|
|
2528
|
+
return this;
|
|
2529
|
+
},
|
|
2530
|
+
setStatus() {
|
|
2531
|
+
return this;
|
|
2532
|
+
},
|
|
2533
|
+
end() {
|
|
2534
|
+
}
|
|
2535
|
+
};
|
|
2536
|
+
/** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
|
|
2537
|
+
_startSpan(name) {
|
|
2538
|
+
if (this.opts.tracer) return this.opts.tracer.startSpan(name);
|
|
2539
|
+
return _CacheService._nullSpan;
|
|
2540
|
+
}
|
|
2541
|
+
createDedicatedRedisClient() {
|
|
2542
|
+
if (this.opts.redisClusterNodes?.length) {
|
|
2543
|
+
return new RedisCluster(this.opts.redisClusterNodes, {
|
|
2544
|
+
redisOptions: {
|
|
2545
|
+
tls: this.opts.redisTls ? {} : void 0,
|
|
2546
|
+
connectTimeout: 1e4,
|
|
2547
|
+
maxRetriesPerRequest: null,
|
|
2548
|
+
...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
|
|
2549
|
+
}
|
|
2550
|
+
});
|
|
2551
|
+
} else if (this.opts.redisSentinel) {
|
|
2552
|
+
return new RedisClient({
|
|
2553
|
+
sentinels: this.opts.redisSentinel.sentinels,
|
|
2554
|
+
name: this.opts.redisSentinel.name,
|
|
2555
|
+
tls: this.opts.redisTls ? {} : void 0,
|
|
2556
|
+
connectTimeout: 1e4,
|
|
2557
|
+
lazyConnect: true,
|
|
2558
|
+
maxRetriesPerRequest: null,
|
|
2559
|
+
enableAutoPipelining: false,
|
|
2560
|
+
retryStrategy: (times) => Math.min(times * 50, 2e3),
|
|
2561
|
+
...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
|
|
2562
|
+
});
|
|
2563
|
+
} else {
|
|
2564
|
+
return new RedisClient({
|
|
2565
|
+
host: this.opts.redisHost,
|
|
2566
|
+
port: this.opts.redisPort,
|
|
2567
|
+
tls: this.opts.redisTls ? {} : void 0,
|
|
2568
|
+
connectTimeout: 1e4,
|
|
2569
|
+
lazyConnect: true,
|
|
2570
|
+
maxRetriesPerRequest: null,
|
|
2571
|
+
enableAutoPipelining: false,
|
|
2572
|
+
family: 4,
|
|
2573
|
+
retryStrategy: (times) => Math.min(times * 50, 2e3),
|
|
2574
|
+
...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
|
|
2575
|
+
});
|
|
2576
|
+
}
|
|
2577
|
+
}
|
|
2578
|
+
initBackplane() {
|
|
2579
|
+
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
2580
|
+
if (this.opts.backplaneMode === "stream") {
|
|
2581
|
+
if (this.streamClient) return;
|
|
2582
|
+
void this._startStreamConsumer();
|
|
2583
|
+
return;
|
|
2584
|
+
}
|
|
2585
|
+
if (this.subClient) return;
|
|
2586
|
+
const sub = this.createDedicatedRedisClient();
|
|
2587
|
+
sub.on("error", (e) => {
|
|
2588
|
+
this._checkAndLogResp3Hint(e);
|
|
2589
|
+
this.logger.debug("Backplane subscriber error", { error: e.message });
|
|
2590
|
+
});
|
|
2591
|
+
sub.on("close", () => {
|
|
2592
|
+
if (this._subDisconnectedAt === null) {
|
|
2593
|
+
this._subDisconnectedAt = Date.now();
|
|
2594
|
+
this.logger.debug("Backplane: subscriber disconnected", { at: this._subDisconnectedAt });
|
|
2595
|
+
}
|
|
2596
|
+
});
|
|
2597
|
+
sub.on("ready", () => {
|
|
2598
|
+
if (this._subDisconnectedAt !== null && this.opts.backplaneMaxStalenessMs > 0) {
|
|
2599
|
+
const gapMs = Date.now() - this._subDisconnectedAt;
|
|
2600
|
+
if (gapMs > this.opts.backplaneMaxStalenessMs) {
|
|
2601
|
+
const evicted = this.l1.evictSetBefore(this._subDisconnectedAt);
|
|
2602
|
+
this.logger.warn("Backplane: reconnect after gap \u2014 flushed potentially stale L1 entries", {
|
|
2603
|
+
gapMs,
|
|
2604
|
+
evicted,
|
|
2605
|
+
hint: "Increase backplaneMaxStalenessMs or set to 0 to disable the fence"
|
|
2606
|
+
});
|
|
2607
|
+
}
|
|
2608
|
+
this._subDisconnectedAt = null;
|
|
2609
|
+
}
|
|
2610
|
+
});
|
|
2611
|
+
const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
|
|
2612
|
+
if (isClusterSharded) {
|
|
2613
|
+
sub.on("smessage", (_channel, message) => {
|
|
2614
|
+
this._handleBackplaneMessage(message);
|
|
2615
|
+
});
|
|
2616
|
+
sub.ssubscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: sharded subscribed", {
|
|
2617
|
+
channel: this.backplaneChannel,
|
|
2618
|
+
instanceId: this.instanceId
|
|
2619
|
+
})).catch((err) => this.logger.warn("Backplane: sharded subscribe failed", {
|
|
2620
|
+
error: err.message
|
|
2621
|
+
}));
|
|
2622
|
+
} else {
|
|
2623
|
+
sub.on("message", (_channel, message) => {
|
|
2624
|
+
this._handleBackplaneMessage(message);
|
|
2625
|
+
});
|
|
2626
|
+
sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
|
|
2627
|
+
channel: this.backplaneChannel,
|
|
2628
|
+
instanceId: this.instanceId
|
|
2629
|
+
})).catch((err) => this.logger.warn("Backplane: subscribe failed", {
|
|
2630
|
+
error: err.message
|
|
2631
|
+
}));
|
|
2632
|
+
}
|
|
2633
|
+
this.subClient = sub;
|
|
2634
|
+
}
|
|
2635
|
+
async _startStreamConsumer() {
|
|
2636
|
+
const sub = this.streamClient ?? this.createDedicatedRedisClient();
|
|
2637
|
+
this.streamClient = sub;
|
|
2638
|
+
if (typeof sub.on === "function") {
|
|
2639
|
+
sub.on("error", (e) => this.logger.debug("Backplane stream consumer error", { error: e.message }));
|
|
2640
|
+
sub.on("close", () => {
|
|
2641
|
+
if (this._subDisconnectedAt === null) {
|
|
2642
|
+
this._subDisconnectedAt = Date.now();
|
|
2643
|
+
this.logger.debug("Backplane stream: consumer disconnected", { at: this._subDisconnectedAt });
|
|
2644
|
+
}
|
|
2645
|
+
});
|
|
2646
|
+
sub.on("ready", () => {
|
|
2647
|
+
if (this._subDisconnectedAt !== null) {
|
|
2648
|
+
this.logger.debug("Backplane stream: consumer reconnected, resuming stream read", { lastId: this._lastStreamId });
|
|
2649
|
+
this._subDisconnectedAt = null;
|
|
2650
|
+
}
|
|
2651
|
+
});
|
|
2652
|
+
}
|
|
2653
|
+
const runLoop = async () => {
|
|
2654
|
+
while (!this._destroyed && !this._redisDisabled) {
|
|
2655
|
+
try {
|
|
2656
|
+
const res = await sub.xread(
|
|
2657
|
+
"BLOCK",
|
|
2658
|
+
this.opts.backplaneStreamBlockMs,
|
|
2659
|
+
"STREAMS",
|
|
2660
|
+
this.backplaneStreamKey,
|
|
2661
|
+
this._lastStreamId
|
|
2662
|
+
);
|
|
2663
|
+
if (this._destroyed) break;
|
|
2664
|
+
if (res && res.length > 0) {
|
|
2665
|
+
for (const [, entries] of res) {
|
|
2666
|
+
if (entries.length > 0) {
|
|
2667
|
+
if (this._lastStreamId !== "$") {
|
|
2668
|
+
this.counters.streamReplays++;
|
|
2669
|
+
}
|
|
2670
|
+
for (const [id, fields] of entries) {
|
|
2671
|
+
this._lastStreamId = id;
|
|
2672
|
+
this.counters.streamEntriesReceived++;
|
|
2673
|
+
this._processStreamEntry(fields);
|
|
2674
|
+
}
|
|
2675
|
+
}
|
|
2676
|
+
}
|
|
2677
|
+
} else {
|
|
2678
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
2679
|
+
}
|
|
2680
|
+
} catch (err) {
|
|
2681
|
+
if (this._destroyed) break;
|
|
2682
|
+
const msg = err.message ?? "";
|
|
2683
|
+
if (msg.includes("NOGROUP") || msg.includes("smaller than") || msg.includes("trimmed")) {
|
|
2684
|
+
this.counters.streamGaps++;
|
|
2685
|
+
this.l1.clear();
|
|
2686
|
+
this._lastStreamId = "$";
|
|
2687
|
+
}
|
|
2688
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
2689
|
+
}
|
|
2690
|
+
}
|
|
2691
|
+
};
|
|
2692
|
+
void runLoop();
|
|
2693
|
+
}
|
|
2694
|
+
/**
|
|
2695
|
+
* Validate + apply one XREAD stream entry. `fields` is the flat ioredis
|
|
2696
|
+
* shape [name, value, name, value, …]. Mirrors the schema rules of the
|
|
2697
|
+
* pubsub path (`_handleBackplaneMessage`): op must be a known operation,
|
|
2698
|
+
* key/src must be non-empty strings, tagVersion must parse to a finite
|
|
2699
|
+
* number. Invalid entries are logged and dropped — never applied.
|
|
2700
|
+
*/
|
|
2701
|
+
/** @internal Exposed for testing. */
|
|
2702
|
+
_processStreamEntry(fields) {
|
|
2703
|
+
let op = "";
|
|
2704
|
+
let key = "";
|
|
2705
|
+
let src = "";
|
|
2706
|
+
let tagVersionRaw;
|
|
2707
|
+
for (let i = 0; i + 1 < fields.length; i += 2) {
|
|
2708
|
+
const f = fields[i];
|
|
2709
|
+
const v = fields[i + 1];
|
|
2710
|
+
if (f === "op") op = v;
|
|
2711
|
+
else if (f === "key") key = v;
|
|
2712
|
+
else if (f === "src") src = v;
|
|
2713
|
+
else if (f === "tagVersion") tagVersionRaw = v;
|
|
2714
|
+
}
|
|
2715
|
+
const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
|
|
2716
|
+
if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
|
|
2717
|
+
this.logger.warn("Backplane: rejected invalid stream entry", {
|
|
2718
|
+
op: String(op).slice(0, 40),
|
|
2719
|
+
key: typeof key === "string" ? key.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(key)
|
|
2720
|
+
});
|
|
2721
|
+
return;
|
|
2722
|
+
}
|
|
2723
|
+
let tagVersion;
|
|
2724
|
+
if (tagVersionRaw !== void 0) {
|
|
2725
|
+
const parsed = parseInt(tagVersionRaw, 10);
|
|
2726
|
+
if (!Number.isFinite(parsed)) {
|
|
2727
|
+
this.logger.warn("Backplane: rejected stream entry with non-numeric tagVersion", { key });
|
|
2728
|
+
return;
|
|
2729
|
+
}
|
|
2730
|
+
tagVersion = parsed;
|
|
2731
|
+
}
|
|
2732
|
+
if (src === this.instanceId) {
|
|
2733
|
+
this.counters.invSkipped++;
|
|
2734
|
+
return;
|
|
2735
|
+
}
|
|
2736
|
+
this.counters.invReceived++;
|
|
2737
|
+
this._applyInvalidationEvent(op, key, tagVersion);
|
|
2738
|
+
}
|
|
2739
|
+
_applyInvalidationEvent(op, key, tagVersion) {
|
|
2740
|
+
if (op === "del") {
|
|
2741
|
+
this.l1.delete(key);
|
|
2742
|
+
setImmediate(() => {
|
|
2743
|
+
if (!this._diskDisabled) this.disk.delete(key);
|
|
2744
|
+
});
|
|
2745
|
+
this._cascadeDependencies(key);
|
|
2746
|
+
} else if (op === "del-glob") {
|
|
2747
|
+
this.l1.deletePattern(key);
|
|
2748
|
+
} else if (op === "tag_incr") {
|
|
2749
|
+
const tag = key;
|
|
2750
|
+
const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
2751
|
+
this._setLocalTagVersion(tag, ver, Date.now());
|
|
2752
|
+
}
|
|
2753
|
+
this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
|
|
2754
|
+
}
|
|
2755
|
+
/** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
|
|
2756
|
+
_handleBackplaneMessage(message) {
|
|
2757
|
+
try {
|
|
2758
|
+
const msg = JSON.parse(message);
|
|
2759
|
+
if (!msg || typeof msg !== "object" || Array.isArray(msg) || typeof msg.src !== "string" || typeof msg.key !== "string" || msg.op !== "del" && msg.op !== "del-glob" && msg.op !== "tag_incr") {
|
|
2760
|
+
this.logger.warn("Backplane: rejected invalid pubsub message format", {
|
|
2761
|
+
raw: typeof message === "string" ? message.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(message)
|
|
2762
|
+
});
|
|
2763
|
+
return;
|
|
2764
|
+
}
|
|
2765
|
+
if (msg.src === this.instanceId) {
|
|
2766
|
+
this.counters.invSkipped++;
|
|
2767
|
+
return;
|
|
2768
|
+
}
|
|
2769
|
+
this.counters.invReceived++;
|
|
2770
|
+
this._applyInvalidationEvent(msg.op, msg.key, typeof msg.tagVersion === "number" ? msg.tagVersion : void 0);
|
|
2771
|
+
} catch {
|
|
2772
|
+
this.logger.warn("Backplane: malformed message JSON parse failed");
|
|
2773
|
+
}
|
|
2774
|
+
}
|
|
2775
|
+
async publishInvalidation(op, key, tagVersion) {
|
|
2776
|
+
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
2777
|
+
try {
|
|
2778
|
+
const client = await this.getRedis();
|
|
2779
|
+
if (this.opts.backplaneMode === "stream") {
|
|
2780
|
+
const args = [
|
|
2781
|
+
this.backplaneStreamKey,
|
|
2782
|
+
"MAXLEN",
|
|
2783
|
+
"~",
|
|
2784
|
+
String(this.opts.backplaneStreamMaxLen),
|
|
2785
|
+
"*",
|
|
2786
|
+
"op",
|
|
2787
|
+
op,
|
|
2788
|
+
"key",
|
|
2789
|
+
key,
|
|
2790
|
+
"src",
|
|
2791
|
+
this.instanceId
|
|
2792
|
+
];
|
|
2793
|
+
if (typeof tagVersion === "number") {
|
|
2794
|
+
args.push("tagVersion", String(tagVersion));
|
|
2795
|
+
}
|
|
2796
|
+
await client.xadd(...args);
|
|
2797
|
+
this.counters.invSent++;
|
|
2798
|
+
return;
|
|
2799
|
+
}
|
|
2800
|
+
const payload = JSON.stringify({ op, key, src: this.instanceId, tagVersion });
|
|
2801
|
+
const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
|
|
2802
|
+
if (isClusterSharded && typeof client.spublish === "function") {
|
|
2803
|
+
await client.spublish(
|
|
2804
|
+
this.backplaneChannel,
|
|
2805
|
+
payload
|
|
2806
|
+
);
|
|
2807
|
+
} else {
|
|
2808
|
+
await client.publish(
|
|
2809
|
+
this.backplaneChannel,
|
|
2810
|
+
payload
|
|
2811
|
+
);
|
|
2812
|
+
}
|
|
2813
|
+
this.counters.invSent++;
|
|
2814
|
+
} catch {
|
|
2815
|
+
}
|
|
2816
|
+
}
|
|
2817
|
+
_setLocalTagVersion(tag, version, now = Date.now()) {
|
|
2818
|
+
const existing = this.tagVersions.get(tag)?.version ?? 0;
|
|
2819
|
+
const finalVersion = Math.max(existing, version);
|
|
2820
|
+
if (this.tagVersions.size >= 1e4 && !this.tagVersions.has(tag)) {
|
|
2821
|
+
const oldestKey = this.tagVersions.keys().next().value;
|
|
2822
|
+
if (oldestKey !== void 0) this.tagVersions.delete(oldestKey);
|
|
2823
|
+
}
|
|
2824
|
+
this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
|
|
2825
|
+
}
|
|
2826
|
+
async _getTagVersion(tag) {
|
|
2827
|
+
const now = Date.now();
|
|
2828
|
+
const local = this.tagVersions.get(tag);
|
|
2829
|
+
if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
|
|
2830
|
+
return local.version;
|
|
2831
|
+
}
|
|
2832
|
+
if (!this._redisDisabled) {
|
|
2833
|
+
try {
|
|
2834
|
+
const client = await this.getRedis();
|
|
2835
|
+
const raw = await client.get(this.nk(`tag_ver:${tag}`));
|
|
2836
|
+
const version = raw ? parseInt(raw, 10) : 0;
|
|
2837
|
+
this._setLocalTagVersion(tag, version, now);
|
|
2838
|
+
return version;
|
|
2839
|
+
} catch {
|
|
2840
|
+
}
|
|
2841
|
+
}
|
|
2842
|
+
return local?.version ?? 0;
|
|
2843
|
+
}
|
|
2844
|
+
_deleteIfStale(k, setAtMs) {
|
|
2845
|
+
this.l1.deleteIfSetBefore(k, setAtMs);
|
|
2846
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
2847
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
2848
|
+
void this.getRedis().then((client) => {
|
|
2849
|
+
return client.eval(LUA_COMPARE_AND_DELETE, 1, k, String(setAtMs));
|
|
2850
|
+
}).catch(() => {
|
|
2851
|
+
});
|
|
2852
|
+
}
|
|
2853
|
+
}
|
|
2854
|
+
/**
|
|
2855
|
+
* Serialize payload for L2 Redis storage applying compression and encryption as configured.
|
|
2856
|
+
* Offloads to worker thread if pool is active and payload exceeds threshold.
|
|
2857
|
+
*/
|
|
2858
|
+
async _serializeAndEncrypt(serialized) {
|
|
2859
|
+
const isCompressed = this.opts.compression && this.opts.compression !== "none" && serialized.length > this.opts.compressionThresholdBytes;
|
|
2860
|
+
if (this._workerPool && (this.enc.isEnabled || isCompressed) && serialized.length > this.opts.workerThresholdBytes) {
|
|
2861
|
+
return this._workerPool.encrypt(serialized);
|
|
2862
|
+
}
|
|
2863
|
+
if (isCompressed) {
|
|
2864
|
+
const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression);
|
|
2865
|
+
if (this.enc.isEnabled) {
|
|
2866
|
+
const encrypted = this.enc.encryptBuffer(compressed);
|
|
2867
|
+
return PREFIX_ENC_COMPRESSED + encrypted.toString("base64");
|
|
2868
|
+
}
|
|
2869
|
+
return PREFIX_COMPRESSED + compressed.toString("base64");
|
|
2870
|
+
}
|
|
2871
|
+
return this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
|
|
2872
|
+
}
|
|
2873
|
+
/**
|
|
2874
|
+
* Deserialize raw L2 Redis entry applying decryption and decompression as needed.
|
|
2875
|
+
* Offloads to worker thread if pool is active and payload exceeds threshold.
|
|
2876
|
+
*/
|
|
2877
|
+
async _decryptAndDeserialize(raw) {
|
|
2878
|
+
let plain;
|
|
2879
|
+
if (this._workerPool && raw.length > this.opts.workerThresholdBytes) {
|
|
2880
|
+
plain = await this._workerPool.decrypt(raw);
|
|
2881
|
+
} else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
|
|
2882
|
+
const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), "base64");
|
|
2883
|
+
const decBuf = this.enc.decryptBuffer(encBuf);
|
|
2884
|
+
const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
|
|
2885
|
+
plain = decompressed.toString("utf8");
|
|
2886
|
+
} else if (raw.startsWith(PREFIX_COMPRESSED)) {
|
|
2887
|
+
const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), "base64");
|
|
2888
|
+
const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
|
|
2889
|
+
plain = decompressed.toString("utf8");
|
|
2890
|
+
} else if (raw.startsWith("enc:v1:") || this.enc.isEnabled) {
|
|
2891
|
+
plain = this.enc.decrypt(raw);
|
|
2892
|
+
} else {
|
|
2893
|
+
plain = raw;
|
|
2894
|
+
}
|
|
2895
|
+
return JSON.parse(plain);
|
|
2896
|
+
}
|
|
2897
|
+
/**
|
|
2898
|
+
* Scan all keys matching `pattern` across single-node or Cluster clients.
|
|
2899
|
+
* For Cluster, iterates every master node independently (SCAN is node-local).
|
|
2900
|
+
*/
|
|
2901
|
+
async _scanKeys(client, pattern) {
|
|
2902
|
+
const keys = [];
|
|
2903
|
+
if (client instanceof RedisCluster) {
|
|
2904
|
+
const masters = client.nodes("master");
|
|
2905
|
+
await Promise.all(masters.map(
|
|
2906
|
+
(node) => new Promise((resolve, reject) => {
|
|
2907
|
+
const stream = node.scanStream({ match: pattern, count: 100 });
|
|
2908
|
+
stream.on("data", (chunk) => keys.push(...chunk));
|
|
2909
|
+
stream.on("end", resolve);
|
|
2910
|
+
stream.on("error", reject);
|
|
2911
|
+
})
|
|
2912
|
+
));
|
|
2913
|
+
} else {
|
|
2914
|
+
await new Promise((resolve, reject) => {
|
|
2915
|
+
const stream = client.scanStream({ match: pattern, count: 100 });
|
|
2916
|
+
stream.on("data", (chunk) => keys.push(...chunk));
|
|
2917
|
+
stream.on("end", resolve);
|
|
2918
|
+
stream.on("error", reject);
|
|
2919
|
+
});
|
|
2920
|
+
}
|
|
2921
|
+
return keys;
|
|
2922
|
+
}
|
|
2923
|
+
_checkAndLogResp3Hint(err) {
|
|
2924
|
+
const msg = err?.message || "";
|
|
2925
|
+
if (!this.opts.redisProtocol && (msg.includes("unknown command") || msg.includes("HELLO") || msg.includes("protocol error") || msg.includes("ProtocolError") || msg.includes("Connection is closed"))) {
|
|
2926
|
+
this.logger.warn(
|
|
2927
|
+
"Redis connection/protocol error detected. If your Redis endpoint or proxy (e.g. Twemproxy, Envoy, older ElastiCache) does not support RESP3, set redisProtocol: 2 in CacheOptions to force RESP2 compatibility.",
|
|
2928
|
+
{ hint: "redisProtocol: 2", originalError: msg }
|
|
2929
|
+
);
|
|
2930
|
+
}
|
|
2931
|
+
}
|
|
2932
|
+
async getRedis() {
|
|
2933
|
+
if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
|
|
2934
|
+
if (this.redis) return this.redis;
|
|
2935
|
+
if (this.redisConnecting) return this.redisConnecting;
|
|
2936
|
+
this.redisConnecting = (async () => {
|
|
2937
|
+
try {
|
|
2938
|
+
let client;
|
|
2939
|
+
if (this.opts.redisClusterNodes?.length) {
|
|
2940
|
+
client = new RedisCluster(this.opts.redisClusterNodes, {
|
|
2941
|
+
redisOptions: {
|
|
2942
|
+
tls: this.opts.redisTls ? {} : void 0,
|
|
2943
|
+
connectTimeout: 1e4,
|
|
2944
|
+
maxRetriesPerRequest: 3,
|
|
2945
|
+
keepAlive: 3e4,
|
|
2946
|
+
...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
|
|
2947
|
+
},
|
|
2948
|
+
enableAutoPipelining: true,
|
|
2949
|
+
retryDelayOnClusterDown: 200,
|
|
2950
|
+
retryDelayOnFailover: 1e3
|
|
2951
|
+
});
|
|
2952
|
+
client.on("connect", () => this.logger.info("Redis Cluster connected"));
|
|
2953
|
+
client.on("error", (e) => {
|
|
2954
|
+
this._checkAndLogResp3Hint(e);
|
|
2955
|
+
this.logger.error("Redis Cluster error", {}, e);
|
|
2956
|
+
});
|
|
2957
|
+
client.on("reconnecting", () => this.logger.debug("Redis Cluster reconnecting"));
|
|
2958
|
+
} else if (this.opts.redisSentinel) {
|
|
2959
|
+
client = new RedisClient({
|
|
2960
|
+
sentinels: this.opts.redisSentinel.sentinels,
|
|
2961
|
+
name: this.opts.redisSentinel.name,
|
|
2962
|
+
tls: this.opts.redisTls ? {} : void 0,
|
|
2963
|
+
connectTimeout: 1e4,
|
|
2964
|
+
lazyConnect: false,
|
|
2965
|
+
maxRetriesPerRequest: 3,
|
|
2966
|
+
enableAutoPipelining: true,
|
|
2967
|
+
keepAlive: 3e4,
|
|
2968
|
+
retryStrategy: (times) => Math.min(times * 50, 2e3),
|
|
2969
|
+
...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
|
|
2970
|
+
});
|
|
2971
|
+
client.on("connect", () => this.logger.info("Redis Sentinel connected", { name: this.opts.redisSentinel.name }));
|
|
2972
|
+
client.on("error", (e) => {
|
|
2973
|
+
this._checkAndLogResp3Hint(e);
|
|
2974
|
+
this.logger.error("Redis Sentinel error", { name: this.opts.redisSentinel.name }, e);
|
|
2975
|
+
});
|
|
2976
|
+
client.on("reconnecting", () => this.logger.debug("Redis Sentinel reconnecting"));
|
|
2977
|
+
} else {
|
|
2978
|
+
client = new RedisClient({
|
|
2979
|
+
host: this.opts.redisHost,
|
|
2980
|
+
port: this.opts.redisPort,
|
|
2981
|
+
tls: this.opts.redisTls ? {} : void 0,
|
|
2982
|
+
connectTimeout: 1e4,
|
|
2983
|
+
lazyConnect: false,
|
|
2984
|
+
maxRetriesPerRequest: 3,
|
|
2985
|
+
enableAutoPipelining: true,
|
|
2986
|
+
keepAlive: 3e4,
|
|
2987
|
+
family: 4,
|
|
2988
|
+
retryStrategy: (times) => Math.min(times * 50, 2e3),
|
|
2989
|
+
...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
|
|
2990
|
+
});
|
|
2991
|
+
client.on("connect", () => this.logger.info("Redis connected", { host: this.opts.redisHost }));
|
|
2992
|
+
client.on("error", (e) => {
|
|
2993
|
+
this._checkAndLogResp3Hint(e);
|
|
2994
|
+
this.logger.error("Redis error", { host: this.opts.redisHost }, e);
|
|
2995
|
+
});
|
|
2996
|
+
client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
|
|
2997
|
+
}
|
|
2998
|
+
await new Promise((resolve, reject) => {
|
|
2999
|
+
client.once("ready", resolve);
|
|
3000
|
+
client.once("error", (e) => {
|
|
3001
|
+
this._checkAndLogResp3Hint(e);
|
|
3002
|
+
reject(e);
|
|
3003
|
+
});
|
|
3004
|
+
setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
|
|
3005
|
+
});
|
|
3006
|
+
this.cb.onSuccess();
|
|
3007
|
+
this.redis = client;
|
|
3008
|
+
this.redisConnecting = null;
|
|
3009
|
+
return client;
|
|
3010
|
+
} catch (err) {
|
|
3011
|
+
this.cb.onFailure();
|
|
3012
|
+
this.redisConnecting = null;
|
|
3013
|
+
this._checkAndLogResp3Hint(err);
|
|
3014
|
+
throw err;
|
|
3015
|
+
}
|
|
3016
|
+
})();
|
|
3017
|
+
return this.redisConnecting;
|
|
3018
|
+
}
|
|
3019
|
+
// ── Snapshot (cold-start persistence) ────────────────────────────────────
|
|
3020
|
+
writeSnapshot(altPath) {
|
|
3021
|
+
try {
|
|
3022
|
+
const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
|
|
3023
|
+
if (entries.length === 0) return;
|
|
3024
|
+
const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
|
|
3025
|
+
const packed = pack3(payload);
|
|
3026
|
+
const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
|
|
3027
|
+
const dest = altPath ?? this.opts.snapshotPath;
|
|
3028
|
+
fs2.mkdirSync(path2.dirname(dest), { recursive: true });
|
|
3029
|
+
fs2.writeFileSync(dest, final, { mode: 384 });
|
|
3030
|
+
this.logger.info("Cache snapshot written", {
|
|
3031
|
+
path: dest,
|
|
3032
|
+
entries: entries.length,
|
|
3033
|
+
sizeKB: Math.round(final.length / 1024),
|
|
3034
|
+
encrypted: this.enc.isEnabled
|
|
3035
|
+
});
|
|
3036
|
+
} catch (err) {
|
|
3037
|
+
this.logger.warn("Cache snapshot write failed", { error: err.message });
|
|
3038
|
+
}
|
|
3039
|
+
}
|
|
3040
|
+
loadSnapshot() {
|
|
3041
|
+
const snapshotPath = this.opts.snapshotPath;
|
|
3042
|
+
try {
|
|
3043
|
+
if (!fs2.existsSync(snapshotPath)) return;
|
|
3044
|
+
const stat = fs2.statSync(snapshotPath);
|
|
3045
|
+
if (stat.size > SNAPSHOT_MAX_FILE_BYTES) {
|
|
3046
|
+
this.logger.warn("Snapshot rejected: exceeds size limit", { sizeBytes: stat.size });
|
|
3047
|
+
fs2.unlinkSync(snapshotPath);
|
|
3048
|
+
return;
|
|
3049
|
+
}
|
|
3050
|
+
const raw = fs2.readFileSync(snapshotPath);
|
|
3051
|
+
fs2.unlinkSync(snapshotPath);
|
|
3052
|
+
let buf;
|
|
3053
|
+
try {
|
|
3054
|
+
buf = this.enc.decryptBuffer(raw);
|
|
3055
|
+
} catch (e) {
|
|
3056
|
+
this.logger.warn("Snapshot rejected: decryption failed", { error: e.message });
|
|
3057
|
+
return;
|
|
3058
|
+
}
|
|
3059
|
+
const snapshot = unpack3(buf);
|
|
3060
|
+
if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
|
|
3061
|
+
this.logger.warn("Snapshot rejected: version mismatch", { got: snapshot?.version });
|
|
3062
|
+
return;
|
|
3063
|
+
}
|
|
3064
|
+
const ageMs = Date.now() - (snapshot.writtenAt ?? 0);
|
|
3065
|
+
if (ageMs > this.opts.snapshotMaxAgeMs || ageMs < 0) {
|
|
3066
|
+
this.logger.warn("Snapshot rejected: too old", { ageMinutes: Math.round(ageMs / 6e4) });
|
|
3067
|
+
return;
|
|
3068
|
+
}
|
|
3069
|
+
if (!Array.isArray(snapshot.entries)) {
|
|
3070
|
+
this.logger.warn("Snapshot rejected: entries is not an array");
|
|
3071
|
+
return;
|
|
3072
|
+
}
|
|
3073
|
+
const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
|
|
3074
|
+
this.logger.info("Cache snapshot loaded (L1 is warm)", {
|
|
3075
|
+
loaded,
|
|
3076
|
+
total: snapshot.entries.length,
|
|
3077
|
+
sizeKB: this.l1.getStats().sizeKB
|
|
3078
|
+
});
|
|
3079
|
+
} catch (err) {
|
|
3080
|
+
this.logger.warn("Snapshot load failed \u2014 starting cold", { error: err.message });
|
|
3081
|
+
try {
|
|
3082
|
+
fs2.unlinkSync(snapshotPath);
|
|
3083
|
+
} catch {
|
|
3084
|
+
}
|
|
3085
|
+
}
|
|
3086
|
+
}
|
|
3087
|
+
// ── Core get (L1 → L1.5 → L2 → fetch) ───────────────────────────────────
|
|
3088
|
+
/**
|
|
3089
|
+
* Get a value from cache, or fetch and cache it.
|
|
3090
|
+
*
|
|
3091
|
+
* @param cacheKey - Unique key identifying this value
|
|
3092
|
+
* @param fetchFn - Called on a cache miss; its return value is cached and returned
|
|
3093
|
+
* @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
|
|
3094
|
+
* @param opts.priority - Override the auto-inferred eviction priority
|
|
3095
|
+
* @param opts.swr - Stale-While-Revalidate grace seconds.
|
|
3096
|
+
* @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
|
|
3097
|
+
* is triggered proactively while the caller still receives the
|
|
3098
|
+
* cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
|
|
3099
|
+
* Requires `fetchFn` to be stable across calls.
|
|
3100
|
+
* @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
|
|
3101
|
+
* recompute more aggressively before expiry. Typical range: 0.5–2.
|
|
3102
|
+
* Complementary to refreshAhead — uses recompute cost (delta) to
|
|
3103
|
+
* decide probabilistically rather than at a fixed threshold.
|
|
3104
|
+
* @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
|
|
3105
|
+
* Caches negative lookups to avoid repeated DB hits for missing keys.
|
|
3106
|
+
*/
|
|
3107
|
+
async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
|
|
3108
|
+
const span = this._startSpan("tricache.get");
|
|
3109
|
+
if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
3110
|
+
const k = this.nk(cacheKey);
|
|
3111
|
+
this.counters.gets++;
|
|
3112
|
+
const optSwr = opts.swr ?? 0;
|
|
3113
|
+
const optPriority = opts.priority;
|
|
3114
|
+
const optRefreshAhead = opts.refreshAhead;
|
|
3115
|
+
const optXfetchBeta = opts.xfetchBeta;
|
|
3116
|
+
const optNotFoundTtl = opts.notFoundTtl;
|
|
3117
|
+
const optTags = opts.tags;
|
|
3118
|
+
const l1Hit = this.l1.get(k);
|
|
3119
|
+
if (l1Hit !== null) {
|
|
3120
|
+
let isGenerationalStale = false;
|
|
3121
|
+
if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
|
|
3122
|
+
for (const [tag, entryVer] of Object.entries(l1Hit.tagVersions)) {
|
|
3123
|
+
const currentVer = await this._getTagVersion(tag);
|
|
3124
|
+
if (currentVer > entryVer) {
|
|
3125
|
+
isGenerationalStale = true;
|
|
3126
|
+
break;
|
|
3127
|
+
}
|
|
3128
|
+
}
|
|
3129
|
+
}
|
|
3130
|
+
if (isGenerationalStale) {
|
|
3131
|
+
this._deleteIfStale(k, l1Hit.setAt ?? 0);
|
|
3132
|
+
} else {
|
|
3133
|
+
if (l1Hit.isStale) {
|
|
3134
|
+
const swrGraceMs2 = optSwr * 1e3;
|
|
3135
|
+
if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
|
|
3136
|
+
const priority2 = optPriority ?? inferPriority(cacheKey);
|
|
3137
|
+
this.revalidating.add(k);
|
|
3138
|
+
void this._revalidate(k, fetchFn, ttlSeconds * 1e3, swrGraceMs2, priority2);
|
|
3139
|
+
this.counters.swrRevalidations++;
|
|
3140
|
+
this.logger.debug("SWR: serving stale, revalidating", { cacheKey });
|
|
3141
|
+
} else {
|
|
3142
|
+
this.logger.debug("L1 hit");
|
|
3143
|
+
}
|
|
3144
|
+
} else {
|
|
3145
|
+
this.logger.debug("L1 hit");
|
|
3146
|
+
const ra = optRefreshAhead;
|
|
3147
|
+
const xb = optXfetchBeta;
|
|
3148
|
+
if (ra || xb) {
|
|
3149
|
+
const now = l1Hit.fetchedAt ?? Date.now();
|
|
3150
|
+
const remaining = l1Hit.expiresAt - now;
|
|
3151
|
+
const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1e3;
|
|
3152
|
+
const shouldRefreshAhead = ra ? remaining <= entryTtl * (1 - ra) : false;
|
|
3153
|
+
const shouldXFetch = xb && l1Hit.delta != null ? remaining <= l1Hit.delta * xb * -Math.log(Math.random()) : false;
|
|
3154
|
+
if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
|
|
3155
|
+
const priority2 = optPriority ?? inferPriority(cacheKey);
|
|
3156
|
+
this.revalidating.add(k);
|
|
3157
|
+
void this._revalidate(k, fetchFn, entryTtl, optSwr * 1e3, priority2);
|
|
3158
|
+
this.counters.swrRevalidations++;
|
|
3159
|
+
this.logger.debug(
|
|
3160
|
+
shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
|
|
3161
|
+
{ cacheKey, remainingMs: remaining, ttlMs: entryTtl }
|
|
3162
|
+
);
|
|
3163
|
+
}
|
|
3164
|
+
}
|
|
3165
|
+
}
|
|
3166
|
+
this.counters.l1Hits++;
|
|
3167
|
+
this.opts.onHit?.(cacheKey, "l1");
|
|
3168
|
+
if (this.opts.frozen) deepFreeze(l1Hit.value);
|
|
3169
|
+
span.setAttribute("cache.hit", "l1").end();
|
|
3170
|
+
return this.opts.cloneStrategy === "structuredClone" && l1Hit.value != null && typeof l1Hit.value === "object" ? structuredClone(l1Hit.value) : l1Hit.value;
|
|
3171
|
+
}
|
|
3172
|
+
}
|
|
3173
|
+
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
3174
|
+
const swrGraceMs = optSwr * 1e3;
|
|
3175
|
+
const priority = optPriority ?? inferPriority(cacheKey);
|
|
3176
|
+
if (!this._redisDisabled) {
|
|
3177
|
+
try {
|
|
3178
|
+
const client = await this.getRedis();
|
|
3179
|
+
if (this.opts.tagStrategy === "generational") {
|
|
3180
|
+
const hashData = await client.hgetall(k);
|
|
3181
|
+
this.cb.onSuccess();
|
|
3182
|
+
if (hashData && hashData.d) {
|
|
3183
|
+
let isStale = false;
|
|
3184
|
+
let storedTagVersions = {};
|
|
3185
|
+
if (hashData.tv) {
|
|
3186
|
+
try {
|
|
3187
|
+
storedTagVersions = JSON.parse(hashData.tv);
|
|
3188
|
+
} catch {
|
|
3189
|
+
}
|
|
3190
|
+
}
|
|
3191
|
+
for (const [tag, entryVer] of Object.entries(storedTagVersions)) {
|
|
3192
|
+
const currentVer = await this._getTagVersion(tag);
|
|
3193
|
+
if (currentVer > entryVer) {
|
|
3194
|
+
isStale = true;
|
|
3195
|
+
break;
|
|
3196
|
+
}
|
|
3197
|
+
}
|
|
3198
|
+
if (isStale) {
|
|
3199
|
+
const setAtMs = parseInt(hashData.t, 10) || 0;
|
|
3200
|
+
this._deleteIfStale(k, setAtMs);
|
|
3201
|
+
} else {
|
|
3202
|
+
const parsed = await this._decryptAndDeserialize(hashData.d);
|
|
3203
|
+
this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
|
|
3204
|
+
this.counters.l2Hits++;
|
|
3205
|
+
this.opts.onHit?.(cacheKey, "l2");
|
|
3206
|
+
this.logger.debug("L2 hit (Redis hash)", { cacheKey });
|
|
3207
|
+
span.setAttribute("cache.hit", "l2").end();
|
|
3208
|
+
if (this.opts.frozen) deepFreeze(parsed);
|
|
3209
|
+
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
3210
|
+
}
|
|
3211
|
+
}
|
|
3212
|
+
} else {
|
|
3213
|
+
const raw = await client.get(k);
|
|
3214
|
+
this.cb.onSuccess();
|
|
3215
|
+
if (raw) {
|
|
3216
|
+
const parsed = await this._decryptAndDeserialize(raw);
|
|
3217
|
+
this.l1.set(k, parsed, ttlMs, priority);
|
|
3218
|
+
this.counters.l2Hits++;
|
|
3219
|
+
this.opts.onHit?.(cacheKey, "l2");
|
|
3220
|
+
this.logger.debug("L2 hit (Redis)", { cacheKey });
|
|
3221
|
+
span.setAttribute("cache.hit", "l2").end();
|
|
3222
|
+
if (this.opts.frozen) deepFreeze(parsed);
|
|
3223
|
+
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
3224
|
+
}
|
|
3225
|
+
}
|
|
3226
|
+
} catch (err) {
|
|
3227
|
+
this.cb.onFailure();
|
|
3228
|
+
this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
|
|
3229
|
+
}
|
|
3230
|
+
}
|
|
3231
|
+
if (!this._diskDisabled) {
|
|
3232
|
+
const diskHit = this.disk.load(k);
|
|
3233
|
+
if (diskHit !== null) {
|
|
3234
|
+
let isDiskStale = false;
|
|
3235
|
+
if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
|
|
3236
|
+
for (const [tag, entryVer] of Object.entries(diskHit.tagVersions)) {
|
|
3237
|
+
const currentVer = await this._getTagVersion(tag);
|
|
3238
|
+
if (currentVer > entryVer) {
|
|
3239
|
+
isDiskStale = true;
|
|
3240
|
+
break;
|
|
3241
|
+
}
|
|
3242
|
+
}
|
|
3243
|
+
}
|
|
3244
|
+
if (isDiskStale) {
|
|
3245
|
+
this.disk.delete(k);
|
|
3246
|
+
} else {
|
|
3247
|
+
const promoted = this.l1.importEntries(
|
|
3248
|
+
[{ key: k, entry: diskHit }],
|
|
3249
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
3250
|
+
);
|
|
3251
|
+
if (promoted > 0) {
|
|
3252
|
+
const l1Check = this.l1.get(k);
|
|
3253
|
+
if (l1Check !== null) {
|
|
3254
|
+
this.counters.diskHits++;
|
|
3255
|
+
this.opts.onHit?.(cacheKey, "disk");
|
|
3256
|
+
this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
|
|
3257
|
+
span.setAttribute("cache.hit", "disk").end();
|
|
3258
|
+
if (this.opts.frozen) deepFreeze(l1Check.value);
|
|
3259
|
+
return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
|
|
3260
|
+
}
|
|
3261
|
+
}
|
|
3262
|
+
}
|
|
3263
|
+
}
|
|
3264
|
+
}
|
|
3265
|
+
span.setAttribute("cache.hit", "miss");
|
|
3266
|
+
this.opts.onMiss?.(cacheKey);
|
|
3267
|
+
const existing = this.inflight.get(k);
|
|
3268
|
+
if (existing) {
|
|
3269
|
+
this.counters.stampedes++;
|
|
3270
|
+
this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch", { cacheKey });
|
|
3271
|
+
span.end();
|
|
3272
|
+
return existing;
|
|
3273
|
+
}
|
|
3274
|
+
const fetchPromise = (async () => {
|
|
3275
|
+
try {
|
|
3276
|
+
this.counters.fetches++;
|
|
3277
|
+
const fetchStart = Date.now();
|
|
3278
|
+
const data = await fetchFn();
|
|
3279
|
+
const delta = Date.now() - fetchStart;
|
|
3280
|
+
const notFoundTtlMs = (optNotFoundTtl ?? this.opts.notFoundTtl) * 1e3;
|
|
3281
|
+
let effectiveTtl = data == null && notFoundTtlMs > 0 ? notFoundTtlMs : ttlMs;
|
|
3282
|
+
if (this.latencyTracker && data != null) {
|
|
3283
|
+
this.latencyTracker.record(k, delta);
|
|
3284
|
+
const p95 = this.latencyTracker.p95(k);
|
|
3285
|
+
if (p95 !== null) {
|
|
3286
|
+
const adaptedMs = Math.round(p95 * this.opts.adaptiveTtlMultiplier * 1e3);
|
|
3287
|
+
effectiveTtl = Math.max(
|
|
3288
|
+
this.opts.adaptiveTtlMinMs,
|
|
3289
|
+
Math.min(this.opts.adaptiveTtlMaxMs, adaptedMs)
|
|
3290
|
+
);
|
|
3291
|
+
}
|
|
3292
|
+
}
|
|
3293
|
+
const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
|
|
3294
|
+
const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
|
|
3295
|
+
let activeTagVersions;
|
|
3296
|
+
if (optTags?.length) {
|
|
3297
|
+
if (this.opts.tagStrategy === "generational") {
|
|
3298
|
+
activeTagVersions = {};
|
|
3299
|
+
for (const tag of optTags) {
|
|
3300
|
+
activeTagVersions[tag] = await this._getTagVersion(tag);
|
|
3301
|
+
}
|
|
3302
|
+
} else {
|
|
3303
|
+
await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
|
|
3304
|
+
}
|
|
3305
|
+
}
|
|
3306
|
+
this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
|
|
3307
|
+
if (!this._redisDisabled) {
|
|
3308
|
+
try {
|
|
3309
|
+
const client = await this.getRedis();
|
|
3310
|
+
const serialized = JSON.stringify(data);
|
|
3311
|
+
const toStore = await this._serializeAndEncrypt(serialized);
|
|
3312
|
+
const ttlSec = Math.ceil(effectiveTtl / 1e3);
|
|
3313
|
+
if (this.opts.tagStrategy === "generational" && activeTagVersions) {
|
|
3314
|
+
const now = Date.now();
|
|
3315
|
+
const tx = client.multi();
|
|
3316
|
+
tx.hset(k, {
|
|
3317
|
+
d: toStore,
|
|
3318
|
+
t: String(now),
|
|
3319
|
+
tv: JSON.stringify(activeTagVersions)
|
|
3320
|
+
});
|
|
3321
|
+
tx.expire(k, ttlSec);
|
|
3322
|
+
await tx.exec();
|
|
3323
|
+
} else {
|
|
3324
|
+
await client.setex(k, ttlSec, toStore);
|
|
3325
|
+
}
|
|
3326
|
+
this.cb.onSuccess();
|
|
3327
|
+
this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
|
|
3328
|
+
} catch {
|
|
3329
|
+
this.cb.onFailure();
|
|
3330
|
+
this.logger.debug("Cached L1 only (Redis unavailable)", { cacheKey });
|
|
3331
|
+
}
|
|
3332
|
+
} else {
|
|
3333
|
+
this.logger.debug("Cached L1", { cacheKey });
|
|
3334
|
+
}
|
|
3335
|
+
if (this.opts.frozen) deepFreeze(data);
|
|
3336
|
+
return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
|
|
3337
|
+
} finally {
|
|
3338
|
+
this.inflight.delete(k);
|
|
3339
|
+
span.end();
|
|
3340
|
+
}
|
|
3341
|
+
})();
|
|
3342
|
+
this.inflight.set(k, fetchPromise);
|
|
3343
|
+
return fetchPromise;
|
|
3344
|
+
}
|
|
3345
|
+
/**
|
|
3346
|
+
* Universal fetch-and-cache wrapper with an ergonomic options object.
|
|
3347
|
+
*
|
|
3348
|
+
* Drop-in ergonomic alternative to `get()` matching developer expectations
|
|
3349
|
+
* from `cache-manager` and `keyv`.
|
|
3350
|
+
*
|
|
3351
|
+
* @param cacheKey - Unique cache key.
|
|
3352
|
+
* @param fetchFn - Executed on a cache miss to retrieve fresh data.
|
|
3353
|
+
* @param options - Optional configuration object (TTL, SWR, tags, priority, etc.).
|
|
3354
|
+
*
|
|
3355
|
+
* @example
|
|
3356
|
+
* const user = await cache.wrap(`user:${id}`, () => db.user.findUnique({ where: { id } }), {
|
|
3357
|
+
* ttl: 300,
|
|
3358
|
+
* swr: 60,
|
|
3359
|
+
* tags: ['users'],
|
|
3360
|
+
* });
|
|
3361
|
+
*/
|
|
3362
|
+
wrap(cacheKey, fetchFn, options) {
|
|
3363
|
+
const ttl = options?.ttl ?? 300;
|
|
3364
|
+
return this.get(cacheKey, fetchFn, ttl, options);
|
|
3365
|
+
}
|
|
3366
|
+
async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
|
|
3367
|
+
try {
|
|
3368
|
+
const fetchStart = Date.now();
|
|
3369
|
+
const data = await fetchFn();
|
|
3370
|
+
const delta = Date.now() - fetchStart;
|
|
3371
|
+
const staleAt = Date.now() + ttlMs;
|
|
3372
|
+
if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
|
|
3373
|
+
let activeTagVersions;
|
|
3374
|
+
const l1Existing = this.l1.get(cacheKey);
|
|
3375
|
+
if (this.opts.tagStrategy === "generational" && l1Existing?.tagVersions) {
|
|
3376
|
+
activeTagVersions = {};
|
|
3377
|
+
for (const tag of Object.keys(l1Existing.tagVersions)) {
|
|
3378
|
+
activeTagVersions[tag] = await this._getTagVersion(tag);
|
|
3379
|
+
}
|
|
3380
|
+
}
|
|
3381
|
+
this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
|
|
3382
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
3383
|
+
try {
|
|
3384
|
+
const client = await this.getRedis();
|
|
3385
|
+
const s = JSON.stringify(data);
|
|
3386
|
+
const stored = await this._serializeAndEncrypt(s);
|
|
3387
|
+
const ttlSec = Math.ceil(ttlMs / 1e3);
|
|
3388
|
+
if (this.opts.tagStrategy === "generational" && activeTagVersions) {
|
|
3389
|
+
const now = Date.now();
|
|
3390
|
+
const tx = client.multi();
|
|
3391
|
+
tx.hset(cacheKey, {
|
|
3392
|
+
d: stored,
|
|
3393
|
+
t: String(now),
|
|
3394
|
+
tv: JSON.stringify(activeTagVersions)
|
|
3395
|
+
});
|
|
3396
|
+
tx.expire(cacheKey, ttlSec);
|
|
3397
|
+
await tx.exec();
|
|
3398
|
+
} else {
|
|
3399
|
+
await client.setex(cacheKey, ttlSec, stored);
|
|
3400
|
+
}
|
|
3401
|
+
} catch {
|
|
3402
|
+
}
|
|
3403
|
+
}
|
|
3404
|
+
this.logger.debug("SWR: revalidation complete", { cacheKey });
|
|
3405
|
+
} catch (err) {
|
|
3406
|
+
if (this.opts.staleIfError > 0) {
|
|
3407
|
+
const additionalMs = this.opts.staleIfError * 1e3;
|
|
3408
|
+
this.l1.bumpExpiry(cacheKey, additionalMs);
|
|
3409
|
+
this.logger.debug("SWR: revalidation failed, stale-if-error extending expiry", {
|
|
3410
|
+
cacheKey,
|
|
3411
|
+
staleIfErrorSecs: this.opts.staleIfError
|
|
3412
|
+
});
|
|
3413
|
+
} else {
|
|
3414
|
+
this.logger.debug("SWR: revalidation failed", { cacheKey, error: err.message });
|
|
3415
|
+
}
|
|
3416
|
+
} finally {
|
|
3417
|
+
this.revalidating.delete(cacheKey);
|
|
3418
|
+
}
|
|
3419
|
+
}
|
|
3420
|
+
// ── Explicit set / delete ─────────────────────────────────────────────────
|
|
3421
|
+
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
3422
|
+
async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
|
|
3423
|
+
const span = this._startSpan("tricache.set");
|
|
3424
|
+
if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
3425
|
+
const effectiveTtlSeconds = ttlSeconds > 0 ? ttlSeconds : ttlSeconds === 0 ? INDEFINITE_TTL_SECONDS : ttlSeconds;
|
|
3426
|
+
const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
|
|
3427
|
+
const p = priority ?? inferPriority(cacheKey);
|
|
3428
|
+
const k = this.nk(cacheKey);
|
|
3429
|
+
this.counters.sets++;
|
|
3430
|
+
let activeTagVersions;
|
|
3431
|
+
if (opts?.tags?.length) {
|
|
3432
|
+
if (this.opts.tagStrategy === "generational") {
|
|
3433
|
+
activeTagVersions = {};
|
|
3434
|
+
for (const tag of opts.tags) {
|
|
3435
|
+
activeTagVersions[tag] = await this._getTagVersion(tag);
|
|
3436
|
+
}
|
|
3437
|
+
} else {
|
|
3438
|
+
await this._registerTags(k, opts.tags, ttlSeconds);
|
|
3439
|
+
}
|
|
3440
|
+
}
|
|
3441
|
+
this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
|
|
3442
|
+
if (opts?.dependsOn?.length) {
|
|
3443
|
+
for (const pattern of opts.dependsOn) {
|
|
3444
|
+
const nsPattern = this.nk(pattern);
|
|
3445
|
+
let deps = this.dependencyIndex.get(nsPattern);
|
|
3446
|
+
if (!deps) {
|
|
3447
|
+
deps = /* @__PURE__ */ new Set();
|
|
3448
|
+
this.dependencyIndex.set(nsPattern, deps);
|
|
3449
|
+
}
|
|
3450
|
+
deps.add(k);
|
|
3451
|
+
}
|
|
3452
|
+
}
|
|
3453
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
3454
|
+
try {
|
|
3455
|
+
const client = await this.getRedis();
|
|
3456
|
+
const s = JSON.stringify(data);
|
|
3457
|
+
const stored = await this._serializeAndEncrypt(s);
|
|
3458
|
+
const ttlSec = Math.ceil(ttlMs / 1e3);
|
|
3459
|
+
if (this.opts.tagStrategy === "generational" && activeTagVersions) {
|
|
3460
|
+
const now = Date.now();
|
|
3461
|
+
const tx = client.multi();
|
|
3462
|
+
tx.hset(k, {
|
|
3463
|
+
d: stored,
|
|
3464
|
+
t: String(now),
|
|
3465
|
+
tv: JSON.stringify(activeTagVersions)
|
|
3466
|
+
});
|
|
3467
|
+
tx.expire(k, ttlSec);
|
|
3468
|
+
await tx.exec();
|
|
3469
|
+
} else {
|
|
3470
|
+
await client.setex(k, ttlSec, stored);
|
|
3471
|
+
}
|
|
3472
|
+
this.cb.onSuccess();
|
|
3473
|
+
} catch (err) {
|
|
3474
|
+
this.cb.onFailure();
|
|
3475
|
+
this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
|
|
3476
|
+
}
|
|
3477
|
+
}
|
|
3478
|
+
void this.publishInvalidation("del", k);
|
|
3479
|
+
span.end();
|
|
3480
|
+
}
|
|
3481
|
+
/**
|
|
3482
|
+
* Register tags for a cache key in the in-process index and (if Redis is enabled) in
|
|
3483
|
+
* the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
|
|
3484
|
+
*/
|
|
3485
|
+
async _registerTags(k, tags, ttlSeconds) {
|
|
3486
|
+
for (const tag of tags) {
|
|
3487
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
3488
|
+
let members = this.tagIndex.get(tagKey);
|
|
3489
|
+
if (!members) {
|
|
3490
|
+
members = /* @__PURE__ */ new Set();
|
|
3491
|
+
this.tagIndex.set(tagKey, members);
|
|
3492
|
+
}
|
|
3493
|
+
members.add(k);
|
|
3494
|
+
}
|
|
3495
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
3496
|
+
try {
|
|
3497
|
+
const client = await this.getRedis();
|
|
3498
|
+
const pl = client.pipeline();
|
|
3499
|
+
for (const tag of tags) {
|
|
3500
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
3501
|
+
pl.sadd(tagKey, k);
|
|
3502
|
+
pl.expire(tagKey, ttlSeconds + 3600);
|
|
3503
|
+
}
|
|
3504
|
+
await pl.exec();
|
|
3505
|
+
this.cb.onSuccess();
|
|
3506
|
+
} catch {
|
|
3507
|
+
this.cb.onFailure();
|
|
3508
|
+
}
|
|
3509
|
+
}
|
|
3510
|
+
}
|
|
3511
|
+
/**
|
|
3512
|
+
* Delete one key or a glob pattern (supports `*` wildcard).
|
|
3513
|
+
*
|
|
3514
|
+
* @example
|
|
3515
|
+
* await cache.delete('user:abc:profile'); // exact key
|
|
3516
|
+
* await cache.delete('user:abc:*'); // all keys for user abc
|
|
3517
|
+
*/
|
|
3518
|
+
async delete(cacheKey) {
|
|
3519
|
+
const span = this._startSpan("tricache.delete");
|
|
3520
|
+
if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
3521
|
+
const isPattern = cacheKey.includes("*");
|
|
3522
|
+
const k = this.nk(cacheKey);
|
|
3523
|
+
this.counters.deletes++;
|
|
3524
|
+
if (isPattern) {
|
|
3525
|
+
this.l1.deletePattern(k);
|
|
3526
|
+
} else {
|
|
3527
|
+
this.l1.delete(k);
|
|
3528
|
+
setImmediate(() => {
|
|
3529
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
3530
|
+
});
|
|
3531
|
+
this._cascadeDependencies(k);
|
|
3532
|
+
for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
|
|
3533
|
+
}
|
|
3534
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
3535
|
+
try {
|
|
3536
|
+
const client = await this.getRedis();
|
|
3537
|
+
if (isPattern) {
|
|
3538
|
+
const keys = await this._scanKeys(client, k);
|
|
3539
|
+
if (keys.length > 0) await client.del(...keys);
|
|
3540
|
+
} else {
|
|
3541
|
+
await client.del(k);
|
|
3542
|
+
}
|
|
3543
|
+
this.cb.onSuccess();
|
|
3544
|
+
} catch (err) {
|
|
3545
|
+
this.cb.onFailure();
|
|
3546
|
+
this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
|
|
3547
|
+
}
|
|
3548
|
+
}
|
|
3549
|
+
void this.publishInvalidation(isPattern ? "del-glob" : "del", k);
|
|
3550
|
+
span.end();
|
|
3551
|
+
}
|
|
3552
|
+
// ── Counter (distributed rate limiting) ──────────────────────────────────
|
|
3553
|
+
/**
|
|
3554
|
+
* Distributed counter.
|
|
3555
|
+
*
|
|
3556
|
+
* When Redis is active, atomically increments the key via `INCR` and returns
|
|
3557
|
+
* the new (fleet-wide) value. On a Redis error it increments `counters.errors`
|
|
3558
|
+
* and, by default, fails OPEN — returning `0` so a caller's
|
|
3559
|
+
* `if (count > LIMIT) reject()` guard does NOT reject during an outage. Set
|
|
3560
|
+
* `failClosed: true` to re-throw the error instead, enforcing the limit even
|
|
3561
|
+
* when Redis is unavailable.
|
|
3562
|
+
*
|
|
3563
|
+
* When Redis is disabled (or `disableRedis: true`), this maintains an
|
|
3564
|
+
* IN-PROCESS counter with the same TTL semantics so dev/test rate-limiting
|
|
3565
|
+
* works locally. The returned value is the local count (1, 2, 3, …), NOT 0 —
|
|
3566
|
+
* a one-time warning is logged because rate-limiting is then per-instance, not
|
|
3567
|
+
* fleet-wide.
|
|
3568
|
+
*/
|
|
3569
|
+
async increment(cacheKey, ttlSeconds) {
|
|
3570
|
+
const k = this.nk(cacheKey);
|
|
3571
|
+
if (this._redisDisabled) {
|
|
3572
|
+
if (!this._incrementFallbackWarned) {
|
|
3573
|
+
this._incrementFallbackWarned = true;
|
|
3574
|
+
this.logger.warn(
|
|
3575
|
+
"tricache: increment() using in-process counter \u2014 rate limiting is NOT fleet-wide (Redis disabled)",
|
|
3576
|
+
{ cacheKey }
|
|
3577
|
+
);
|
|
3578
|
+
}
|
|
3579
|
+
const now = Date.now();
|
|
3580
|
+
const ttlMs = (ttlSeconds ?? DEFAULT_COUNTER_TTL_SECONDS) * 1e3;
|
|
3581
|
+
const entry = this._l1Counters.get(k);
|
|
3582
|
+
if (entry && entry.expiresAt > now) {
|
|
3583
|
+
entry.value++;
|
|
3584
|
+
return entry.value;
|
|
3585
|
+
}
|
|
3586
|
+
this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
|
|
3587
|
+
return 1;
|
|
3588
|
+
}
|
|
3589
|
+
try {
|
|
3590
|
+
const client = await this.getRedis();
|
|
3591
|
+
const count = await client.incr(k);
|
|
3592
|
+
if (count === 1 && ttlSeconds) await client.expire(k, ttlSeconds);
|
|
3593
|
+
return count;
|
|
3594
|
+
} catch (err) {
|
|
3595
|
+
this.counters.counterErrors++;
|
|
3596
|
+
this.cb.onFailure();
|
|
3597
|
+
this.logger.error("increment: Redis error", { cacheKey }, err);
|
|
3598
|
+
if (this.opts.failClosed) throw err;
|
|
3599
|
+
return 0;
|
|
3600
|
+
}
|
|
3601
|
+
}
|
|
3602
|
+
// ── Clear / Rebalance / TTL ────────────────────────────────────────────────
|
|
3603
|
+
/**
|
|
3604
|
+
* Flush all cached entries, or only those whose key starts with `prefix`.
|
|
3605
|
+
*
|
|
3606
|
+
* @example
|
|
3607
|
+
* await cache.clear(); // flush everything
|
|
3608
|
+
* await cache.clear('user:abc'); // flush all keys for one user
|
|
3609
|
+
*/
|
|
3610
|
+
async clear(prefix) {
|
|
3611
|
+
this.counters.deletes++;
|
|
3612
|
+
const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
|
|
3613
|
+
if (k) {
|
|
3614
|
+
this.l1.deletePattern(k);
|
|
3615
|
+
} else {
|
|
3616
|
+
this.l1.clear();
|
|
3617
|
+
if (!this._diskDisabled) this.disk.clear();
|
|
3618
|
+
this._l1Counters.clear();
|
|
3619
|
+
this.tagIndex.clear();
|
|
3620
|
+
this.tagVersions.clear();
|
|
3621
|
+
}
|
|
3622
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
3623
|
+
try {
|
|
3624
|
+
const client = await this.getRedis();
|
|
3625
|
+
const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
|
|
3626
|
+
const keys = await this._scanKeys(client, pattern);
|
|
3627
|
+
if (keys.length > 0) await client.del(...keys);
|
|
3628
|
+
} catch (err) {
|
|
3629
|
+
this.logger.debug("clear: Redis unavailable", { error: err.message });
|
|
3630
|
+
}
|
|
3631
|
+
}
|
|
3632
|
+
void this.publishInvalidation(
|
|
3633
|
+
"del-glob",
|
|
3634
|
+
k ?? (this._namespace ? `${this._namespace}:*` : "*")
|
|
3635
|
+
);
|
|
3636
|
+
}
|
|
3637
|
+
/**
|
|
3638
|
+
* Evict L1 entries that violate the current category or global capacity limits.
|
|
3639
|
+
* Useful after a write burst or after adding stricter `categoryLimits`.
|
|
3640
|
+
* Returns the number of entries evicted.
|
|
3641
|
+
*/
|
|
3642
|
+
rebalance() {
|
|
3643
|
+
return this.l1.rebalance();
|
|
3644
|
+
}
|
|
3645
|
+
/**
|
|
3646
|
+
* Return the remaining TTL in seconds for a key currently in L1.
|
|
3647
|
+
* Returns null if the key is absent from L1 or has already expired.
|
|
3648
|
+
* Only reflects L1 state — does not query Redis or disk.
|
|
3649
|
+
*/
|
|
3650
|
+
ttl(cacheKey) {
|
|
3651
|
+
return this.l1.ttl(this.nk(cacheKey));
|
|
3652
|
+
}
|
|
3653
|
+
/**
|
|
3654
|
+
* Return true if the key exists in L1 and has not expired.
|
|
3655
|
+
* Bloom-filter fast path — no fetch, no disk or Redis round-trip.
|
|
3656
|
+
*/
|
|
3657
|
+
has(cacheKey) {
|
|
3658
|
+
return this.l1.has(this.nk(cacheKey));
|
|
3659
|
+
}
|
|
3660
|
+
// ── Iteration ─────────────────────────────────────────────────────────────
|
|
3661
|
+
/**
|
|
3662
|
+
* Lazily yield every non-expired L1 key, stripped of its namespace prefix.
|
|
3663
|
+
*
|
|
3664
|
+
* @example
|
|
3665
|
+
* for (const key of cache.keys()) console.log(key);
|
|
3666
|
+
*/
|
|
3667
|
+
*keys() {
|
|
3668
|
+
const prefix = this._namespace ? this._namespace + ":" : "";
|
|
3669
|
+
for (const key of this.l1.liveKeys()) {
|
|
3670
|
+
if (prefix && !key.startsWith(prefix)) continue;
|
|
3671
|
+
yield prefix ? key.slice(prefix.length) : key;
|
|
3672
|
+
}
|
|
3673
|
+
}
|
|
3674
|
+
/**
|
|
3675
|
+
* Lazily yield every non-expired L1 value.
|
|
3676
|
+
* Each value is the cached (pre-deserialized) JS object — no unpack overhead.
|
|
3677
|
+
*
|
|
3678
|
+
* @example
|
|
3679
|
+
* for (const val of cache.values<User>()) console.log(val.id);
|
|
3680
|
+
*/
|
|
3681
|
+
*values() {
|
|
3682
|
+
const prefix = this._namespace ? this._namespace + ":" : "";
|
|
3683
|
+
if (!prefix) {
|
|
3684
|
+
yield* this.l1.liveValues();
|
|
3685
|
+
} else {
|
|
3686
|
+
for (const [key, entry] of this.l1.liveEntries()) {
|
|
3687
|
+
if (!key.startsWith(prefix)) continue;
|
|
3688
|
+
yield this.l1.resolveValue(entry);
|
|
3689
|
+
}
|
|
3690
|
+
}
|
|
3691
|
+
}
|
|
3692
|
+
/**
|
|
3693
|
+
* Lazily yield every non-expired L1 [key, value] pair.
|
|
3694
|
+
* Keys are stripped of their namespace prefix.
|
|
3695
|
+
*
|
|
3696
|
+
* @example
|
|
3697
|
+
* for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
|
|
3698
|
+
*/
|
|
3699
|
+
*entries() {
|
|
3700
|
+
const prefix = this._namespace ? this._namespace + ":" : "";
|
|
3701
|
+
for (const [key, entry] of this.l1.liveEntries()) {
|
|
3702
|
+
if (prefix && !key.startsWith(prefix)) continue;
|
|
3703
|
+
yield [prefix ? key.slice(prefix.length) : key, this.l1.resolveValue(entry)];
|
|
3704
|
+
}
|
|
3705
|
+
}
|
|
3706
|
+
/**
|
|
3707
|
+
* High-throughput bulk scan over all live L1 entries.
|
|
3708
|
+
*
|
|
3709
|
+
* Compared with `entries()` this avoids generator frame overhead, per-entry
|
|
3710
|
+
* `[key, value]` tuple allocation, and the `key.slice()` allocation when the
|
|
3711
|
+
* caller uses the `offset` parameter instead of pre-slicing.
|
|
3712
|
+
*
|
|
3713
|
+
* ```typescript
|
|
3714
|
+
* // Zero extra string allocations — use rawKey + offset directly:
|
|
3715
|
+
* cache.scan((rawKey, value, offset) => {
|
|
3716
|
+
* const key = rawKey.slice(offset); // allocate only if needed
|
|
3717
|
+
* sync(key, value as User);
|
|
3718
|
+
* });
|
|
3719
|
+
* ```
|
|
3720
|
+
*
|
|
3721
|
+
* @param fn Called once per live L1 entry.
|
|
3722
|
+
* `rawKey` — key with namespace prefix still attached.
|
|
3723
|
+
* `value` — deserialized cached value.
|
|
3724
|
+
* `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
|
|
3725
|
+
*/
|
|
3726
|
+
scan(fn) {
|
|
3727
|
+
const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
|
|
3728
|
+
this.l1.scan((key, entry, pfx) => {
|
|
3729
|
+
const value = entry.value !== void 0 ? entry.value : entry.data;
|
|
3730
|
+
fn(key, value, pfx);
|
|
3731
|
+
}, prefixLen);
|
|
3732
|
+
}
|
|
3733
|
+
/**
|
|
3734
|
+
* Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
|
|
3735
|
+
* Returns `false` if the key is absent or already expired.
|
|
3736
|
+
*
|
|
3737
|
+
* @param newTtlSeconds - The new TTL from now, in seconds.
|
|
3738
|
+
*/
|
|
3739
|
+
async touch(cacheKey, newTtlSeconds) {
|
|
3740
|
+
const k = this.nk(cacheKey);
|
|
3741
|
+
const hit = this.l1.touch(k, newTtlSeconds * 1e3);
|
|
3742
|
+
if (hit && !this._redisDisabled) {
|
|
3743
|
+
try {
|
|
3744
|
+
const client = await this.getRedis();
|
|
3745
|
+
void client.expire(k, newTtlSeconds);
|
|
3746
|
+
} catch {
|
|
3747
|
+
}
|
|
3748
|
+
}
|
|
3749
|
+
return hit;
|
|
3750
|
+
}
|
|
3751
|
+
/**
|
|
3752
|
+
* Return the cached value from L1 **only if it is fresh** (not in the SWR grace window).
|
|
3753
|
+
* Returns `null` when the key is absent, expired, or stale — without triggering a fetch.
|
|
3754
|
+
*
|
|
3755
|
+
* @example
|
|
3756
|
+
* const fresh = cache.getIfFresh('user:123');
|
|
3757
|
+
* if (fresh !== null) return fresh; // serve from L1, no network hop
|
|
3758
|
+
*/
|
|
3759
|
+
getIfFresh(cacheKey) {
|
|
3760
|
+
const k = this.nk(cacheKey);
|
|
3761
|
+
const entry = this.l1.getEntry(k);
|
|
3762
|
+
if (!entry) return null;
|
|
3763
|
+
const now = Date.now();
|
|
3764
|
+
if (entry.expiresAt <= now) return null;
|
|
3765
|
+
if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
|
|
3766
|
+
return entry.value !== void 0 ? entry.value : unpack3(entry.data);
|
|
3767
|
+
}
|
|
3768
|
+
/**
|
|
3769
|
+
* Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
|
|
3770
|
+
* Returns the cached value if found and valid, or `null` if absent / expired.
|
|
3771
|
+
* Does not write dummy entries on misses or trigger side-effects.
|
|
3772
|
+
*
|
|
3773
|
+
* @example
|
|
3774
|
+
* const val = await cache.peek<User>('user:123');
|
|
3775
|
+
*/
|
|
3776
|
+
async peek(cacheKey) {
|
|
3777
|
+
const k = this.nk(cacheKey);
|
|
3778
|
+
const l1Hit = this.l1.get(k);
|
|
3779
|
+
if (l1Hit !== null) {
|
|
3780
|
+
this.counters.gets++;
|
|
3781
|
+
this.counters.l1Hits++;
|
|
3782
|
+
const val = l1Hit.value;
|
|
3783
|
+
if (this.opts.frozen) deepFreeze(val);
|
|
3784
|
+
return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
|
|
3785
|
+
}
|
|
3786
|
+
if (!this._diskDisabled) {
|
|
3787
|
+
const diskHit = this.disk.load(k);
|
|
3788
|
+
if (diskHit !== null) {
|
|
3789
|
+
const promoted = this.l1.importEntries(
|
|
3790
|
+
[{ key: k, entry: diskHit }],
|
|
3791
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
3792
|
+
);
|
|
3793
|
+
if (promoted > 0) {
|
|
3794
|
+
const l1Check = this.l1.get(k);
|
|
3795
|
+
if (l1Check !== null) {
|
|
3796
|
+
this.counters.gets++;
|
|
3797
|
+
this.counters.diskHits++;
|
|
3798
|
+
const val = l1Check.value;
|
|
3799
|
+
if (this.opts.frozen) deepFreeze(val);
|
|
3800
|
+
return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
|
|
3801
|
+
}
|
|
3802
|
+
}
|
|
3803
|
+
}
|
|
3804
|
+
}
|
|
3805
|
+
if (!this._redisDisabled && !this.cb.isOpen) {
|
|
3806
|
+
try {
|
|
3807
|
+
const client = await this.getRedis();
|
|
3808
|
+
const raw = await client.get(k);
|
|
3809
|
+
if (raw !== null) {
|
|
3810
|
+
const parsed = await this._decryptAndDeserialize(raw);
|
|
3811
|
+
this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
|
|
3812
|
+
this.counters.gets++;
|
|
3813
|
+
this.counters.l2Hits++;
|
|
3814
|
+
this.cb.onSuccess();
|
|
3815
|
+
if (this.opts.frozen) deepFreeze(parsed);
|
|
3816
|
+
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
3817
|
+
}
|
|
3818
|
+
} catch (err) {
|
|
3819
|
+
this.cb.onFailure();
|
|
3820
|
+
this.logger.debug("peek: Redis read failed", { cacheKey, error: err.message });
|
|
3821
|
+
}
|
|
3822
|
+
}
|
|
3823
|
+
return null;
|
|
3824
|
+
}
|
|
3825
|
+
/**
|
|
3826
|
+
* Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
|
|
3827
|
+
* Preserves input ordering. Uses inflight coalescing per key.
|
|
3828
|
+
*
|
|
3829
|
+
* @param keys - Array of cache keys.
|
|
3830
|
+
* @param fetchFn - Called with only the keys that missed L1.
|
|
3831
|
+
* @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
|
|
3832
|
+
* `(key) => number` so heterogeneous TTLs can be batched in one call.
|
|
3833
|
+
*/
|
|
3834
|
+
async mget(keys, fetchFn, ttl = 300, priority) {
|
|
3835
|
+
const result = Array.from({ length: keys.length });
|
|
3836
|
+
const missIndexes = [];
|
|
3837
|
+
const missKeys = [];
|
|
3838
|
+
for (let i = 0; i < keys.length; i++) {
|
|
3839
|
+
const k = this.nk(keys[i]);
|
|
3840
|
+
const entry = this.l1.getEntry(k);
|
|
3841
|
+
if (entry && entry.expiresAt > Date.now()) {
|
|
3842
|
+
result[i] = entry.value !== void 0 ? entry.value : unpack3(entry.data);
|
|
3843
|
+
this.counters.l1Hits++;
|
|
3844
|
+
} else {
|
|
3845
|
+
missIndexes.push(i);
|
|
3846
|
+
missKeys.push(keys[i]);
|
|
3847
|
+
}
|
|
3848
|
+
}
|
|
3849
|
+
if (missKeys.length === 0) return result;
|
|
3850
|
+
if (!this._redisDisabled) {
|
|
3851
|
+
try {
|
|
3852
|
+
const client = await this.getRedis();
|
|
3853
|
+
const nsKeys = missKeys.map((k) => this.nk(k));
|
|
3854
|
+
const pipeline = client.multi();
|
|
3855
|
+
for (const nk of nsKeys) pipeline.get(nk);
|
|
3856
|
+
const raws = await pipeline.exec();
|
|
3857
|
+
this.cb.onSuccess();
|
|
3858
|
+
for (let j = 0; j < missKeys.length; j++) {
|
|
3859
|
+
const raw = raws[j] ? raws[j][1] : null;
|
|
3860
|
+
const idx = missIndexes[j];
|
|
3861
|
+
if (raw) {
|
|
3862
|
+
const parsed = await this._decryptAndDeserialize(raw);
|
|
3863
|
+
const k = nsKeys[j];
|
|
3864
|
+
const p = priority ?? inferPriority(missKeys[j]);
|
|
3865
|
+
this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
|
|
3866
|
+
this.counters.l2Hits++;
|
|
3867
|
+
result[idx] = parsed;
|
|
3868
|
+
missIndexes[j] = -1;
|
|
3869
|
+
missKeys[j] = "";
|
|
3870
|
+
}
|
|
3871
|
+
}
|
|
3872
|
+
const remainingIdx = missIndexes.filter((i) => i >= 0);
|
|
3873
|
+
const remainingKeys = missKeys.filter((k) => k !== "");
|
|
3874
|
+
missIndexes.length = 0;
|
|
3875
|
+
missKeys.length = 0;
|
|
3876
|
+
missIndexes.push(...remainingIdx);
|
|
3877
|
+
missKeys.push(...remainingKeys);
|
|
3878
|
+
if (missKeys.length === 0) return result;
|
|
3879
|
+
} catch (err) {
|
|
3880
|
+
this.cb.onFailure();
|
|
3881
|
+
this.logger.debug("mget: Redis unavailable, continuing to disk/fetch", { error: err.message });
|
|
3882
|
+
}
|
|
3883
|
+
}
|
|
3884
|
+
if (!this._diskDisabled) {
|
|
3885
|
+
for (let j = missKeys.length - 1; j >= 0; j--) {
|
|
3886
|
+
const k = this.nk(missKeys[j]);
|
|
3887
|
+
const diskHit = this.disk.load(k);
|
|
3888
|
+
if (diskHit !== null) {
|
|
3889
|
+
const promoted = this.l1.importEntries(
|
|
3890
|
+
[{ key: k, entry: diskHit }],
|
|
3891
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
3892
|
+
);
|
|
3893
|
+
if (promoted > 0) {
|
|
3894
|
+
const l1Check = this.l1.get(k);
|
|
3895
|
+
if (l1Check !== null) {
|
|
3896
|
+
this.counters.diskHits++;
|
|
3897
|
+
result[missIndexes[j]] = l1Check.value;
|
|
3898
|
+
missIndexes.splice(j, 1);
|
|
3899
|
+
missKeys.splice(j, 1);
|
|
3900
|
+
}
|
|
3901
|
+
}
|
|
3902
|
+
}
|
|
3903
|
+
}
|
|
3904
|
+
if (missKeys.length === 0) return result;
|
|
3905
|
+
}
|
|
3906
|
+
if (missKeys.length > 0) {
|
|
3907
|
+
this.counters.fetches++;
|
|
3908
|
+
const fetched = await fetchFn(missKeys);
|
|
3909
|
+
for (let j = 0; j < missKeys.length; j++) {
|
|
3910
|
+
const v = fetched[missKeys[j]];
|
|
3911
|
+
result[missIndexes[j]] = v;
|
|
3912
|
+
if (v !== void 0) {
|
|
3913
|
+
const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
|
|
3914
|
+
await this.set(missKeys[j], v, resolvedTtl, priority);
|
|
3915
|
+
}
|
|
3916
|
+
}
|
|
3917
|
+
}
|
|
3918
|
+
return result;
|
|
3919
|
+
}
|
|
3920
|
+
/**
|
|
3921
|
+
* Returns a Promise that resolves once the cache is fully initialised and any
|
|
3922
|
+
* startup warming configured via `warmKeys` has completed.
|
|
3923
|
+
*
|
|
3924
|
+
* Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once
|
|
3925
|
+
* `warmFromL2(warmKeys)` finishes — ideal for k8s readiness probes.
|
|
3926
|
+
*
|
|
3927
|
+
* @example
|
|
3928
|
+
* const cache = CacheService.create({ warmKeys: 'user:*' });
|
|
3929
|
+
* await cache.ready(); // gate traffic until warm
|
|
3930
|
+
*/
|
|
3931
|
+
ready() {
|
|
3932
|
+
return this._readyPromise;
|
|
3933
|
+
}
|
|
3934
|
+
/**
|
|
3935
|
+
* Batch write — set multiple entries in a single call.
|
|
3936
|
+
* TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
|
|
3937
|
+
*
|
|
3938
|
+
* @example
|
|
3939
|
+
* await cache.mset({
|
|
3940
|
+
* 'user:1': { value: { name: 'Alice' }, ttl: 300 },
|
|
3941
|
+
* 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
|
|
3942
|
+
* });
|
|
3943
|
+
*/
|
|
3944
|
+
async mset(entries) {
|
|
3945
|
+
const keys = Object.keys(entries);
|
|
3946
|
+
await Promise.all(keys.map((key) => {
|
|
3947
|
+
const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
|
|
3948
|
+
const hasOpts = tags?.length || dependsOn?.length;
|
|
3949
|
+
return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
|
|
3950
|
+
}));
|
|
3951
|
+
}
|
|
3952
|
+
/**
|
|
3953
|
+
* Batch delete — delete multiple exact keys in a single call.
|
|
3954
|
+
* Glob patterns are not supported; use `delete('prefix:*')` for patterns.
|
|
3955
|
+
*
|
|
3956
|
+
* @example
|
|
3957
|
+
* await cache.mdel(['user:1', 'user:2', 'user:3']);
|
|
3958
|
+
*/
|
|
3959
|
+
async mdel(keys) {
|
|
3960
|
+
await Promise.all(keys.map((k) => this.delete(k)));
|
|
3961
|
+
}
|
|
3962
|
+
/**
|
|
3963
|
+
* Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
|
|
3964
|
+
* pulling them into L1. Useful on startup to eliminate cold-start penalty when
|
|
3965
|
+
* the local snapshot is unavailable or too stale.
|
|
3966
|
+
*
|
|
3967
|
+
* Returns the number of keys loaded into L1.
|
|
3968
|
+
*
|
|
3969
|
+
* @example
|
|
3970
|
+
* // In your startup hook (e.g. ECS task, k8s readiness probe):
|
|
3971
|
+
* const loaded = await cache.warmFromL2('org:*');
|
|
3972
|
+
* console.log(`Warmed ${loaded} keys from Redis`);
|
|
3973
|
+
*/
|
|
3974
|
+
async warmFromL2(pattern, opts) {
|
|
3975
|
+
if (this._redisDisabled) return 0;
|
|
3976
|
+
try {
|
|
3977
|
+
const client = await this.getRedis();
|
|
3978
|
+
const nsPattern = this.nk(pattern);
|
|
3979
|
+
const matchedKeys = await this._scanKeys(client, nsPattern);
|
|
3980
|
+
if (matchedKeys.length === 0) {
|
|
3981
|
+
this.cb.onSuccess();
|
|
3982
|
+
return 0;
|
|
3983
|
+
}
|
|
3984
|
+
const pl = client.pipeline();
|
|
3985
|
+
for (const k of matchedKeys) pl.get(k);
|
|
3986
|
+
const results = await pl.exec();
|
|
3987
|
+
this.cb.onSuccess();
|
|
3988
|
+
let loaded = 0;
|
|
3989
|
+
const now = Date.now();
|
|
3990
|
+
for (let i = 0; i < matchedKeys.length; i++) {
|
|
3991
|
+
const [err, raw] = results[i];
|
|
3992
|
+
if (err || raw == null) continue;
|
|
3993
|
+
try {
|
|
3994
|
+
const parsed = await this._decryptAndDeserialize(raw);
|
|
3995
|
+
const remainingMs = 10 * 60 * 1e3;
|
|
3996
|
+
this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
|
|
3997
|
+
loaded++;
|
|
3998
|
+
} catch {
|
|
3999
|
+
}
|
|
4000
|
+
}
|
|
4001
|
+
void now;
|
|
4002
|
+
this.logger.info("warmFromL2 complete", {
|
|
4003
|
+
pattern,
|
|
4004
|
+
matched: matchedKeys.length,
|
|
4005
|
+
loaded
|
|
4006
|
+
});
|
|
4007
|
+
return loaded;
|
|
4008
|
+
} catch (err) {
|
|
4009
|
+
this.cb.onFailure();
|
|
4010
|
+
this.logger.debug("warmFromL2: Redis unavailable", { error: err.message });
|
|
4011
|
+
return 0;
|
|
4012
|
+
}
|
|
4013
|
+
}
|
|
4014
|
+
/**
|
|
4015
|
+
* Invalidate all keys associated with a tag.
|
|
4016
|
+
* Deletes from L1, disk, and Redis (both the keyed values and the tag set).
|
|
4017
|
+
*
|
|
4018
|
+
* @example
|
|
4019
|
+
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
4020
|
+
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
4021
|
+
*/
|
|
4022
|
+
async invalidateTag(tag) {
|
|
4023
|
+
if (this.opts.tagStrategy === "generational") {
|
|
4024
|
+
let newVer = 1;
|
|
4025
|
+
if (!this._redisDisabled) {
|
|
4026
|
+
try {
|
|
4027
|
+
const client = await this.getRedis();
|
|
4028
|
+
newVer = await client.incr(this.nk(`tag_ver:${tag}`));
|
|
4029
|
+
} catch (err) {
|
|
4030
|
+
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
4031
|
+
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
4032
|
+
newVer = current + 1;
|
|
4033
|
+
}
|
|
4034
|
+
} else {
|
|
4035
|
+
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
4036
|
+
newVer = current + 1;
|
|
4037
|
+
}
|
|
4038
|
+
this._setLocalTagVersion(tag, newVer, Date.now());
|
|
4039
|
+
void this.publishInvalidation("tag_incr", tag, newVer);
|
|
4040
|
+
return;
|
|
4041
|
+
}
|
|
4042
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
4043
|
+
const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
|
|
4044
|
+
for (const k of members) {
|
|
4045
|
+
this.l1.delete(k);
|
|
4046
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
4047
|
+
}
|
|
4048
|
+
this.tagIndex.delete(tagKey);
|
|
4049
|
+
if (!this._redisDisabled) {
|
|
4050
|
+
try {
|
|
4051
|
+
const client = await this.getRedis();
|
|
4052
|
+
const redisMembers = await client.smembers(tagKey);
|
|
4053
|
+
const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
|
|
4054
|
+
if (toDelete.length > 0) {
|
|
4055
|
+
await client.del(...toDelete, tagKey);
|
|
4056
|
+
} else {
|
|
4057
|
+
await client.del(tagKey);
|
|
4058
|
+
}
|
|
4059
|
+
} catch (err) {
|
|
4060
|
+
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
4061
|
+
}
|
|
4062
|
+
}
|
|
4063
|
+
}
|
|
4064
|
+
/**
|
|
4065
|
+
* Invalidate all keys associated with any of the given tags in a single operation.
|
|
4066
|
+
* Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
|
|
4067
|
+
* reducing latency when invalidating several related tags together.
|
|
4068
|
+
*
|
|
4069
|
+
* Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
|
|
4070
|
+
* synchronously before the Redis round-trip.
|
|
4071
|
+
*
|
|
4072
|
+
* @example
|
|
4073
|
+
* // Instead of three serial round-trips:
|
|
4074
|
+
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
|
|
4075
|
+
*/
|
|
4076
|
+
async invalidateTags(tags) {
|
|
4077
|
+
if (tags.length === 0) return;
|
|
4078
|
+
if (tags.length === 1) {
|
|
4079
|
+
await this.invalidateTag(tags[0]);
|
|
4080
|
+
return;
|
|
4081
|
+
}
|
|
4082
|
+
if (this.opts.tagStrategy === "generational") {
|
|
4083
|
+
const now = Date.now();
|
|
4084
|
+
if (!this._redisDisabled) {
|
|
4085
|
+
try {
|
|
4086
|
+
const client = await this.getRedis();
|
|
4087
|
+
const pl = client.pipeline();
|
|
4088
|
+
for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
|
|
4089
|
+
const results = await pl.exec();
|
|
4090
|
+
for (let i = 0; i < tags.length; i++) {
|
|
4091
|
+
const [err, newVer] = results[i] ?? [null, null];
|
|
4092
|
+
const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
|
|
4093
|
+
this._setLocalTagVersion(tags[i], ver, now);
|
|
4094
|
+
void this.publishInvalidation("tag_incr", tags[i], ver);
|
|
4095
|
+
}
|
|
4096
|
+
return;
|
|
4097
|
+
} catch (err) {
|
|
4098
|
+
this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
|
|
4099
|
+
}
|
|
4100
|
+
}
|
|
4101
|
+
for (const tag of tags) {
|
|
4102
|
+
const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
4103
|
+
this._setLocalTagVersion(tag, ver, now);
|
|
4104
|
+
void this.publishInvalidation("tag_incr", tag, ver);
|
|
4105
|
+
}
|
|
4106
|
+
return;
|
|
4107
|
+
}
|
|
4108
|
+
const tagKeys = [];
|
|
4109
|
+
const allMembers = /* @__PURE__ */ new Set();
|
|
4110
|
+
for (const tag of tags) {
|
|
4111
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
4112
|
+
tagKeys.push(tagKey);
|
|
4113
|
+
const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
|
|
4114
|
+
for (const k of members) allMembers.add(k);
|
|
4115
|
+
this.tagIndex.delete(tagKey);
|
|
4116
|
+
}
|
|
4117
|
+
for (const k of allMembers) {
|
|
4118
|
+
this.l1.delete(k);
|
|
4119
|
+
this.disk.delete(k);
|
|
4120
|
+
}
|
|
4121
|
+
if (!this._redisDisabled) {
|
|
4122
|
+
try {
|
|
4123
|
+
const client = await this.getRedis();
|
|
4124
|
+
const pl = client.pipeline();
|
|
4125
|
+
for (const tagKey of tagKeys) pl.smembers(tagKey);
|
|
4126
|
+
const smResults = await pl.exec();
|
|
4127
|
+
const toDelete = [...allMembers];
|
|
4128
|
+
for (const [err, redisMembers] of smResults) {
|
|
4129
|
+
if (!err && redisMembers) {
|
|
4130
|
+
for (const k of redisMembers) {
|
|
4131
|
+
if (!allMembers.has(k)) toDelete.push(k);
|
|
4132
|
+
}
|
|
4133
|
+
}
|
|
4134
|
+
}
|
|
4135
|
+
const keysToRemove = [...toDelete, ...tagKeys];
|
|
4136
|
+
if (keysToRemove.length > 0) await client.del(...keysToRemove);
|
|
4137
|
+
} catch (err) {
|
|
4138
|
+
this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
|
|
4139
|
+
}
|
|
4140
|
+
}
|
|
4141
|
+
}
|
|
4142
|
+
/**
|
|
4143
|
+
* Get the current generational tag version for a tag (synced with Redis when due).
|
|
4144
|
+
*/
|
|
4145
|
+
async getTagVersion(tag) {
|
|
4146
|
+
return this._getTagVersion(tag);
|
|
4147
|
+
}
|
|
4148
|
+
/**
|
|
4149
|
+
* Measure L1 / disk / Redis latency.
|
|
4150
|
+
* Useful for health checks and dashboards.
|
|
4151
|
+
*
|
|
4152
|
+
* @returns `{ l1, disk, l2 }` latencies in milliseconds.
|
|
4153
|
+
* `l2` is `null` when Redis is disabled.
|
|
4154
|
+
*/
|
|
4155
|
+
async ping() {
|
|
4156
|
+
const t0 = Date.now();
|
|
4157
|
+
this.l1.has("__ping__");
|
|
4158
|
+
const l1 = Date.now() - t0;
|
|
4159
|
+
const t1 = Date.now();
|
|
4160
|
+
void this.disk.stats;
|
|
4161
|
+
const disk = Date.now() - t1;
|
|
4162
|
+
let l2 = null;
|
|
4163
|
+
if (!this._redisDisabled) {
|
|
4164
|
+
try {
|
|
4165
|
+
const client = await this.getRedis();
|
|
4166
|
+
const t2 = Date.now();
|
|
4167
|
+
await client.ping();
|
|
4168
|
+
l2 = Date.now() - t2;
|
|
4169
|
+
} catch {
|
|
4170
|
+
l2 = null;
|
|
4171
|
+
}
|
|
4172
|
+
}
|
|
4173
|
+
return { l1, disk, l2 };
|
|
4174
|
+
}
|
|
4175
|
+
/**
|
|
4176
|
+
* Export all live L1 entries to Redis via a single pipeline.
|
|
4177
|
+
* Useful for warming a new Redis instance or for zero-downtime failover.
|
|
4178
|
+
* Returns the number of keys written.
|
|
4179
|
+
*/
|
|
4180
|
+
async drainToL2() {
|
|
4181
|
+
if (this._redisDisabled) return 0;
|
|
4182
|
+
try {
|
|
4183
|
+
const client = await this.getRedis();
|
|
4184
|
+
const entries = this.l1.exportEntries([]);
|
|
4185
|
+
const now = Date.now();
|
|
4186
|
+
if (entries.length === 0) return 0;
|
|
4187
|
+
const pl = client.pipeline();
|
|
4188
|
+
for (const { key, entry } of entries) {
|
|
4189
|
+
const remainingMs = entry.expiresAt - now;
|
|
4190
|
+
if (remainingMs <= 0) continue;
|
|
4191
|
+
const ttlSecs = Math.max(1, Math.ceil(remainingMs / 1e3));
|
|
4192
|
+
const s = JSON.stringify(entry.value);
|
|
4193
|
+
const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
|
|
4194
|
+
pl.setex(key, ttlSecs, stored);
|
|
4195
|
+
}
|
|
4196
|
+
await pl.exec();
|
|
4197
|
+
return entries.length;
|
|
4198
|
+
} catch (err) {
|
|
4199
|
+
this.logger.debug("drainToL2: Redis unavailable", { error: err.message });
|
|
4200
|
+
return 0;
|
|
4201
|
+
}
|
|
4202
|
+
}
|
|
4203
|
+
// ── Stats ─────────────────────────────────────────────────────────────
|
|
4204
|
+
stats() {
|
|
4205
|
+
return {
|
|
4206
|
+
l1: this.l1.getStats(),
|
|
4207
|
+
disk: this.disk.stats
|
|
4208
|
+
};
|
|
4209
|
+
}
|
|
4210
|
+
// ── Conditional write ─────────────────────────────────────────────────
|
|
4211
|
+
/**
|
|
4212
|
+
* Write `value` only if the key is not already cached.
|
|
4213
|
+
* Returns `true` if the write happened, `false` if the key already existed.
|
|
4214
|
+
*
|
|
4215
|
+
* When Redis is available, atomicity is guaranteed via `SET NX EX` so this
|
|
4216
|
+
* is safe to use for idempotency keys and "first writer wins" patterns across
|
|
4217
|
+
* multiple instances. L1 is populated on success.
|
|
4218
|
+
*
|
|
4219
|
+
* @example
|
|
4220
|
+
* const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
|
|
4221
|
+
* if (!claimed) return res.status(409).json({ error: 'duplicate request' });
|
|
4222
|
+
*/
|
|
4223
|
+
async setIfAbsent(cacheKey, value, ttlSeconds = 300, priority) {
|
|
4224
|
+
const k = this.nk(cacheKey);
|
|
4225
|
+
if (this.l1.has(k)) return false;
|
|
4226
|
+
if (!this._redisDisabled) {
|
|
4227
|
+
try {
|
|
4228
|
+
const client = await this.getRedis();
|
|
4229
|
+
const serialized = JSON.stringify(value);
|
|
4230
|
+
const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
|
|
4231
|
+
const result = await client.set(k, toStore, "EX", ttlSeconds, "NX");
|
|
4232
|
+
this.cb.onSuccess();
|
|
4233
|
+
if (result === null) return false;
|
|
4234
|
+
} catch (err) {
|
|
4235
|
+
this.cb.onFailure();
|
|
4236
|
+
this.logger.debug("setIfAbsent: Redis unavailable, falling back to L1 check", { cacheKey, error: err.message });
|
|
4237
|
+
if (this.l1.has(k)) return false;
|
|
4238
|
+
}
|
|
4239
|
+
}
|
|
4240
|
+
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
4241
|
+
const p = priority ?? inferPriority(cacheKey);
|
|
4242
|
+
this.l1.set(k, value, ttlMs, p);
|
|
4243
|
+
this.counters.sets++;
|
|
4244
|
+
return true;
|
|
4245
|
+
}
|
|
4246
|
+
// ── Distributed / In-Process Mutex Lock ───────────────────────────────────
|
|
4247
|
+
/**
|
|
4248
|
+
* Acquire a distributed (or in-process) mutual exclusion lock on `resourceKey`,
|
|
4249
|
+
* execute `fn`, and automatically release the lock on completion or error.
|
|
4250
|
+
*
|
|
4251
|
+
* When Redis is connected, uses `SET lock:<key> <token> NX EX <ttl>` with
|
|
4252
|
+
* safe Lua token release (`if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end`).
|
|
4253
|
+
* When Redis is disabled, uses an in-process promise-chain mutex to ensure thread-safety.
|
|
4254
|
+
*
|
|
4255
|
+
* @param resourceKey Unique lock name / resource identifier (e.g. `'cron:nightly-sync'`).
|
|
4256
|
+
* @param fn Task to run exclusively while holding the lock.
|
|
4257
|
+
* @param options TTL, acquire timeout, and retry polling intervals.
|
|
4258
|
+
*/
|
|
4259
|
+
async lock(resourceKey, fn, options) {
|
|
4260
|
+
const ttlSeconds = Math.max(1, options?.ttl ?? 30);
|
|
4261
|
+
const acquireTimeout = Math.max(0, options?.acquireTimeout ?? 5e3);
|
|
4262
|
+
const retryInterval = Math.max(10, options?.retryInterval ?? 100);
|
|
4263
|
+
const lockKey = this.nk(`lock:${resourceKey}`);
|
|
4264
|
+
const token = crypto2.randomUUID();
|
|
4265
|
+
const deadline = Date.now() + acquireTimeout;
|
|
4266
|
+
let acquired = false;
|
|
4267
|
+
if (!this._redisDisabled) {
|
|
4268
|
+
let client = null;
|
|
4269
|
+
try {
|
|
4270
|
+
client = await this.getRedis();
|
|
4271
|
+
while (Date.now() <= deadline) {
|
|
4272
|
+
const res = await client.set(lockKey, token, "EX", ttlSeconds, "NX");
|
|
4273
|
+
if (res === "OK") {
|
|
4274
|
+
acquired = true;
|
|
4275
|
+
break;
|
|
4276
|
+
}
|
|
4277
|
+
const remaining = deadline - Date.now();
|
|
4278
|
+
if (remaining <= 0) break;
|
|
4279
|
+
await new Promise((r) => setTimeout(r, Math.min(retryInterval, remaining)));
|
|
4280
|
+
}
|
|
4281
|
+
if (!acquired) {
|
|
4282
|
+
throw new Error(`Failed to acquire lock for resource "${resourceKey}" within ${acquireTimeout}ms`);
|
|
4283
|
+
}
|
|
4284
|
+
} catch (err) {
|
|
4285
|
+
if (err.message.startsWith("Failed to acquire lock")) throw err;
|
|
4286
|
+
this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
|
|
4287
|
+
resourceKey,
|
|
4288
|
+
error: err.message
|
|
4289
|
+
});
|
|
4290
|
+
client = null;
|
|
4291
|
+
}
|
|
4292
|
+
if (client !== null && acquired) {
|
|
4293
|
+
try {
|
|
4294
|
+
return await fn();
|
|
4295
|
+
} finally {
|
|
4296
|
+
try {
|
|
4297
|
+
const LUA_RELEASE_LOCK = `
|
|
4298
|
+
if redis.call("get", KEYS[1]) == ARGV[1] then
|
|
4299
|
+
return redis.call("del", KEYS[1])
|
|
4300
|
+
else
|
|
4301
|
+
return 0
|
|
4302
|
+
end
|
|
4303
|
+
`;
|
|
4304
|
+
await client.eval(LUA_RELEASE_LOCK, 1, lockKey, token);
|
|
4305
|
+
} catch {
|
|
4306
|
+
}
|
|
4307
|
+
}
|
|
4308
|
+
}
|
|
4309
|
+
}
|
|
4310
|
+
let unlock = () => {
|
|
4311
|
+
};
|
|
4312
|
+
const lockPromise = new Promise((resolve) => {
|
|
4313
|
+
unlock = resolve;
|
|
4314
|
+
});
|
|
4315
|
+
while (Date.now() <= deadline) {
|
|
4316
|
+
const existing = this._localLocks.get(lockKey);
|
|
4317
|
+
if (!existing) {
|
|
4318
|
+
this._localLocks.set(lockKey, lockPromise);
|
|
4319
|
+
acquired = true;
|
|
4320
|
+
break;
|
|
4321
|
+
}
|
|
4322
|
+
const remaining = deadline - Date.now();
|
|
4323
|
+
if (remaining <= 0) break;
|
|
4324
|
+
await Promise.race([
|
|
4325
|
+
existing,
|
|
4326
|
+
new Promise((r) => setTimeout(r, Math.min(retryInterval, remaining)))
|
|
4327
|
+
]);
|
|
4328
|
+
}
|
|
4329
|
+
if (!acquired) {
|
|
4330
|
+
throw new Error(`Failed to acquire lock for resource "${resourceKey}" within ${acquireTimeout}ms`);
|
|
4331
|
+
}
|
|
4332
|
+
try {
|
|
4333
|
+
return await fn();
|
|
4334
|
+
} finally {
|
|
4335
|
+
unlock();
|
|
4336
|
+
if (this._localLocks.get(lockKey) === lockPromise) {
|
|
4337
|
+
this._localLocks.delete(lockKey);
|
|
4338
|
+
}
|
|
4339
|
+
}
|
|
4340
|
+
}
|
|
4341
|
+
// ── OpenTelemetry Metrics Integration ──────────────────────────────────────
|
|
4342
|
+
_initOtelMetrics(meter) {
|
|
4343
|
+
try {
|
|
4344
|
+
this._otelMetrics.gets = meter.createCounter("tricache.gets.total", { description: "Total cache get operations" });
|
|
4345
|
+
this._otelMetrics.l1Hits = meter.createCounter("tricache.l1.hits", { description: "L1 RAM cache hits" });
|
|
4346
|
+
this._otelMetrics.l2Hits = meter.createCounter("tricache.l2.hits", { description: "L2 Redis cache hits" });
|
|
4347
|
+
this._otelMetrics.diskHits = meter.createCounter("tricache.disk.hits", { description: "L1.5 disk cache hits" });
|
|
4348
|
+
this._otelMetrics.fetches = meter.createCounter("tricache.fetches", { description: "Cache miss fetch calls" });
|
|
4349
|
+
this._otelMetrics.stampedes = meter.createCounter("tricache.stampedes.prevented", { description: "Coalesced duplicate inflight requests" });
|
|
4350
|
+
this._otelMetrics.sets = meter.createCounter("tricache.sets.total", { description: "Total set operations" });
|
|
4351
|
+
this._otelMetrics.deletes = meter.createCounter("tricache.deletes.total", { description: "Total delete operations" });
|
|
4352
|
+
this._otelMetrics.swrRevalidations = meter.createCounter("tricache.swr.revalidations", { description: "SWR background revalidations" });
|
|
4353
|
+
const gL1Entries = meter.createObservableGauge("tricache.l1.entries", { description: "Current L1 entry count" });
|
|
4354
|
+
const gL1Bytes = meter.createObservableGauge("tricache.l1.bytes", { description: "Current L1 memory usage in bytes" });
|
|
4355
|
+
const gDiskFiles = meter.createObservableGauge("tricache.disk.files", { description: "Current L1.5 disk file count" });
|
|
4356
|
+
const gDiskBytes = meter.createObservableGauge("tricache.disk.bytes", { description: "Current L1.5 disk size in bytes" });
|
|
4357
|
+
const gBloomFpr = meter.createObservableGauge("tricache.bloom.fpr", { description: "Bloom filter false-positive rate" });
|
|
4358
|
+
meter.addBatchObservableCallback((observableResult) => {
|
|
4359
|
+
const stats = this.stats();
|
|
4360
|
+
const l1 = stats.l1;
|
|
4361
|
+
const disk = stats.disk;
|
|
4362
|
+
const checks = this.counters.bloomChecks;
|
|
4363
|
+
const fps = this.counters.bloomFalsePositives;
|
|
4364
|
+
const fpr = checks > 0 ? fps / checks : 0;
|
|
4365
|
+
const attrs = this._namespace ? { namespace: this._namespace } : void 0;
|
|
4366
|
+
observableResult.observe(gL1Entries, l1.entries, attrs);
|
|
4367
|
+
observableResult.observe(gL1Bytes, l1.sizeBytes, attrs);
|
|
4368
|
+
observableResult.observe(gDiskFiles, disk.files, attrs);
|
|
4369
|
+
observableResult.observe(gDiskBytes, disk.sizeKB * 1024, attrs);
|
|
4370
|
+
observableResult.observe(gBloomFpr, fpr, attrs);
|
|
4371
|
+
}, [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr]);
|
|
4372
|
+
} catch (err) {
|
|
4373
|
+
this.logger.warn("Failed to initialize OpenTelemetry metrics meter", { error: err.message });
|
|
4374
|
+
}
|
|
4375
|
+
}
|
|
4376
|
+
// ── Hot key introspection ─────────────────────────────────────────────
|
|
4377
|
+
/**
|
|
4378
|
+
* Return the top-N live L1 keys by historical access frequency.
|
|
4379
|
+
* Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
|
|
4380
|
+
* whose historical frequency exceeds their current in-memory hit count.
|
|
4381
|
+
*
|
|
4382
|
+
* Useful for diagnosing what is driving L1 pressure without any extra data
|
|
4383
|
+
* collection overhead.
|
|
4384
|
+
*
|
|
4385
|
+
* @param n - Maximum number of keys to return. Default: 10.
|
|
4386
|
+
*
|
|
4387
|
+
* @example
|
|
4388
|
+
* cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
|
|
4389
|
+
* console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
|
|
4390
|
+
*/
|
|
4391
|
+
hotKeys(n = 10) {
|
|
4392
|
+
const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
|
|
4393
|
+
return this.l1.hotKeys(n).map(({ key, hits, sizeBytes }) => ({
|
|
4394
|
+
key: prefixLen > 0 ? key.slice(prefixLen) : key,
|
|
4395
|
+
hits,
|
|
4396
|
+
sizeBytes
|
|
4397
|
+
}));
|
|
4398
|
+
}
|
|
4399
|
+
// ── Dependency cascade helpers ────────────────────────────────────────
|
|
4400
|
+
/**
|
|
4401
|
+
* Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
|
|
4402
|
+
* pattern that may contain `*` wildcards).
|
|
4403
|
+
*/
|
|
4404
|
+
_matchesGlob(key, pattern) {
|
|
4405
|
+
if (!pattern.includes("*")) return key === pattern;
|
|
4406
|
+
return getGlobRegex(pattern).test(key);
|
|
4407
|
+
}
|
|
4408
|
+
/**
|
|
4409
|
+
* When an exact key `deletedKey` is removed, cascade to every dependent key
|
|
4410
|
+
* that was registered via `dependsOn` and whose source pattern matches.
|
|
4411
|
+
* Transitive dependencies are traversed with cycle protection via a visited Set.
|
|
4412
|
+
*/
|
|
4413
|
+
_cascadeDependencies(deletedKey, visited = /* @__PURE__ */ new Set()) {
|
|
4414
|
+
if (visited.has(deletedKey)) return;
|
|
4415
|
+
visited.add(deletedKey);
|
|
4416
|
+
for (const [pattern, dependents] of this.dependencyIndex) {
|
|
4417
|
+
if (!this._matchesGlob(deletedKey, pattern)) continue;
|
|
4418
|
+
for (const dep of dependents) {
|
|
4419
|
+
if (visited.has(dep)) continue;
|
|
4420
|
+
this.l1.delete(dep);
|
|
4421
|
+
if (!this._diskDisabled) this.disk.delete(dep);
|
|
4422
|
+
void this.publishInvalidation("del", dep);
|
|
4423
|
+
this.logger.debug("Dependency cascade: invalidated dependent key", {
|
|
4424
|
+
trigger: deletedKey.slice(0, 60),
|
|
4425
|
+
dependent: dep.slice(0, 60)
|
|
4426
|
+
});
|
|
4427
|
+
this._cascadeDependencies(dep, visited);
|
|
4428
|
+
}
|
|
4429
|
+
}
|
|
4430
|
+
}
|
|
4431
|
+
// ── Observability ──────────────────────────────────────────────────────────────────
|
|
4432
|
+
/** Return a full metrics snapshot. */
|
|
4433
|
+
metrics() {
|
|
4434
|
+
const c = this.counters;
|
|
4435
|
+
const l1s = this.l1.getStats();
|
|
4436
|
+
const div = (n, d) => d > 0 ? n / d : 0;
|
|
4437
|
+
return {
|
|
4438
|
+
namespace: this.opts.namespace,
|
|
4439
|
+
uptimeMs: Date.now() - c.startedAt,
|
|
4440
|
+
gets: {
|
|
4441
|
+
total: c.gets,
|
|
4442
|
+
l1Hits: c.l1Hits,
|
|
4443
|
+
l1HitRate: div(c.l1Hits, c.gets),
|
|
4444
|
+
diskHits: c.diskHits,
|
|
4445
|
+
diskHitRate: div(c.diskHits, c.gets),
|
|
4446
|
+
l2Hits: c.l2Hits,
|
|
4447
|
+
l2HitRate: div(c.l2Hits, c.gets),
|
|
4448
|
+
fetches: c.fetches,
|
|
4449
|
+
fetchRate: div(c.fetches, c.gets),
|
|
4450
|
+
stampedePrevented: c.stampedes
|
|
4451
|
+
},
|
|
4452
|
+
sets: { total: c.sets },
|
|
4453
|
+
deletes: { total: c.deletes },
|
|
4454
|
+
revalidations: { total: c.swrRevalidations },
|
|
4455
|
+
counters: {
|
|
4456
|
+
errors: c.counterErrors,
|
|
4457
|
+
singletonDivergences: c.singletonDivergences
|
|
4458
|
+
},
|
|
4459
|
+
bloom: {
|
|
4460
|
+
checksTotal: l1s.bloom.checks,
|
|
4461
|
+
falsePositives: l1s.bloom.falsePositives,
|
|
4462
|
+
falsePositiveRate: div(l1s.bloom.falsePositives, l1s.bloom.checks)
|
|
4463
|
+
},
|
|
4464
|
+
compression: {
|
|
4465
|
+
entriesCompressed: l1s.compression.compressed,
|
|
4466
|
+
entriesUncompressed: l1s.compression.uncompressed,
|
|
4467
|
+
bytesSaved: l1s.compression.bytesSaved
|
|
4468
|
+
},
|
|
4469
|
+
backplane: {
|
|
4470
|
+
enabled: this.opts.invalidationBackplane && !this._redisDisabled,
|
|
4471
|
+
mode: this.opts.backplaneMode,
|
|
4472
|
+
sent: c.invSent,
|
|
4473
|
+
received: c.invReceived,
|
|
4474
|
+
skipped: c.invSkipped,
|
|
4475
|
+
streamEntriesReceived: c.streamEntriesReceived,
|
|
4476
|
+
streamReplays: c.streamReplays,
|
|
4477
|
+
streamGaps: c.streamGaps
|
|
4478
|
+
},
|
|
4479
|
+
l2CircuitBreaker: {
|
|
4480
|
+
state: this.cb.currentState
|
|
4481
|
+
},
|
|
4482
|
+
oom: {
|
|
4483
|
+
enabled: this.opts.oomProtection,
|
|
4484
|
+
evictions: c.oomEvictions,
|
|
4485
|
+
lastTriggeredAt: c.oomLastAt
|
|
4486
|
+
},
|
|
4487
|
+
l1: {
|
|
4488
|
+
entries: l1s.entries,
|
|
4489
|
+
sizeBytes: this.l1.memoryUsage,
|
|
4490
|
+
maxBytes: this.opts.l1MaxBytes
|
|
4491
|
+
},
|
|
4492
|
+
disk: { ...this.disk.stats, disabled: this._diskDisabled },
|
|
4493
|
+
...this.latencyTracker && {
|
|
4494
|
+
adaptiveTtl: {
|
|
4495
|
+
enabled: true,
|
|
4496
|
+
trackedKeys: this.latencyTracker.trackedKeys,
|
|
4497
|
+
slowestKeys: this.latencyTracker.snapshot(
|
|
4498
|
+
this._namespace ? this._namespace.length + 1 : 0,
|
|
4499
|
+
// strip "namespace:" prefix
|
|
4500
|
+
this.opts.adaptiveTtlMultiplier,
|
|
4501
|
+
this.opts.adaptiveTtlMinMs,
|
|
4502
|
+
this.opts.adaptiveTtlMaxMs
|
|
4503
|
+
)
|
|
4504
|
+
}
|
|
4505
|
+
}
|
|
4506
|
+
};
|
|
4507
|
+
}
|
|
4508
|
+
/**
|
|
4509
|
+
* Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
|
|
4510
|
+
* Paste the result into your `/metrics` endpoint.
|
|
4511
|
+
*
|
|
4512
|
+
* @param m - Snapshot returned by `cache.metrics()`
|
|
4513
|
+
* @param prefix - Metric name prefix. Default: `"tricache"`
|
|
4514
|
+
*/
|
|
4515
|
+
static toPrometheusText(m, prefix = "tricache", instanceName) {
|
|
4516
|
+
const parts = [];
|
|
4517
|
+
if (m.namespace) parts.push(`namespace="${m.namespace}"`);
|
|
4518
|
+
if (instanceName) parts.push(`instance="${instanceName}"`);
|
|
4519
|
+
const lbl = parts.length ? `{${parts.join(",")}}` : "";
|
|
4520
|
+
const lines = [];
|
|
4521
|
+
const counter = (name, val, help) => {
|
|
4522
|
+
lines.push(`# HELP ${prefix}_${name}_total ${help}`);
|
|
4523
|
+
lines.push(`# TYPE ${prefix}_${name}_total counter`);
|
|
4524
|
+
lines.push(`${prefix}_${name}_total${lbl} ${val}`);
|
|
4525
|
+
};
|
|
4526
|
+
const gauge = (name, val, help) => {
|
|
4527
|
+
lines.push(`# HELP ${prefix}_${name} ${help}`);
|
|
4528
|
+
lines.push(`# TYPE ${prefix}_${name} gauge`);
|
|
4529
|
+
lines.push(`${prefix}_${name}${lbl} ${val}`);
|
|
4530
|
+
};
|
|
4531
|
+
counter("gets", m.gets.total, "Total get() calls");
|
|
4532
|
+
counter("l1_hits", m.gets.l1Hits, "L1 RAM cache hits");
|
|
4533
|
+
counter("disk_hits", m.gets.diskHits, "L1.5 disk tier hits");
|
|
4534
|
+
counter("l2_hits", m.gets.l2Hits, "L2 Redis hits");
|
|
4535
|
+
counter("fetches", m.gets.fetches, "fetchFn calls (cache misses)");
|
|
4536
|
+
counter("stampedes_prevented", m.gets.stampedePrevented, "Coalesced duplicate inflight requests");
|
|
4537
|
+
counter("sets", m.sets.total, "Total set() calls");
|
|
4538
|
+
counter("deletes", m.deletes.total, "Total delete() calls");
|
|
4539
|
+
counter("swr_revalidations", m.revalidations.total, "Stale-While-Revalidate background refreshes");
|
|
4540
|
+
gauge("l1_hit_rate", m.gets.l1HitRate, "Fraction of gets served from L1 RAM (0-1)");
|
|
4541
|
+
gauge("disk_hit_rate", m.gets.diskHitRate, "Fraction of gets served from disk (0-1)");
|
|
4542
|
+
gauge("l2_hit_rate", m.gets.l2HitRate, "Fraction of gets served from Redis (0-1)");
|
|
4543
|
+
gauge("fetch_rate", m.gets.fetchRate, "Fraction of gets calling fetchFn (0-1)");
|
|
4544
|
+
gauge("l1_entries", m.l1.entries, "Current L1 entry count");
|
|
4545
|
+
gauge("l1_size_bytes", m.l1.sizeBytes, "Current L1 used bytes");
|
|
4546
|
+
gauge("disk_files", m.disk.files, "Current L1.5 disk file count");
|
|
4547
|
+
gauge(
|
|
4548
|
+
"bloom_false_positive_rate",
|
|
4549
|
+
m.bloom.falsePositiveRate,
|
|
4550
|
+
"Bloom filter false-positive rate; increase capacity if > 0.01"
|
|
4551
|
+
);
|
|
4552
|
+
gauge(
|
|
4553
|
+
"compression_bytes_saved",
|
|
4554
|
+
m.compression.bytesSaved,
|
|
4555
|
+
"Approximate bytes saved by msgpackr compression"
|
|
4556
|
+
);
|
|
4557
|
+
if (m.backplane.enabled) {
|
|
4558
|
+
counter("backplane_sent", m.backplane.sent, "Invalidation messages sent via Pub/Sub");
|
|
4559
|
+
counter("backplane_received", m.backplane.received, "Invalidation messages received from peers");
|
|
4560
|
+
}
|
|
4561
|
+
if (m.oom.enabled) {
|
|
4562
|
+
counter(
|
|
4563
|
+
"oom_evictions",
|
|
4564
|
+
m.oom.evictions,
|
|
4565
|
+
"Emergency L1 eviction rounds triggered by heap pressure"
|
|
4566
|
+
);
|
|
4567
|
+
}
|
|
4568
|
+
return lines.join("\n");
|
|
4569
|
+
}
|
|
4570
|
+
// ── Lifecycle ────────────────────────────────────────────────────────────
|
|
4571
|
+
/**
|
|
4572
|
+
* Dynamically rotate the active encryption key at runtime without restarting.
|
|
4573
|
+
* Installs the new key as primary for all subsequent writes, while preserving
|
|
4574
|
+
* the previous key for seamless fallback decryption of existing cache entries.
|
|
4575
|
+
*/
|
|
4576
|
+
async rotateEncryptionKey(newKeyBase64, newMode) {
|
|
4577
|
+
this.enc.rotateKey(newKeyBase64, newMode);
|
|
4578
|
+
if (this._workerPool) {
|
|
4579
|
+
await this._workerPool.drainAndReinit(this.enc.toWorkerInit());
|
|
4580
|
+
}
|
|
4581
|
+
this.logger.info("tricache: encryption key rotated dynamically", { mode: this.enc.mode });
|
|
4582
|
+
}
|
|
4583
|
+
/** Close Redis connections and stop all background timers. */
|
|
4584
|
+
async destroy() {
|
|
4585
|
+
this._destroyed = true;
|
|
4586
|
+
if (this.cleanupInterval) clearInterval(this.cleanupInterval);
|
|
4587
|
+
if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
|
|
4588
|
+
if (this.oomInterval) clearInterval(this.oomInterval);
|
|
4589
|
+
if (this.metricsInterval) clearInterval(this.metricsInterval);
|
|
4590
|
+
if (this._shutdownHandler) {
|
|
4591
|
+
process.off("SIGTERM", this._shutdownHandler);
|
|
4592
|
+
process.off("SIGINT", this._shutdownHandler);
|
|
4593
|
+
this._shutdownHandler = null;
|
|
4594
|
+
}
|
|
4595
|
+
if (this._workerPool) {
|
|
4596
|
+
await this._workerPool.destroy();
|
|
4597
|
+
this._workerPool = null;
|
|
4598
|
+
}
|
|
4599
|
+
if (this.subClient) {
|
|
4600
|
+
try {
|
|
4601
|
+
this.subClient.disconnect();
|
|
4602
|
+
} catch {
|
|
4603
|
+
}
|
|
4604
|
+
this.subClient = null;
|
|
4605
|
+
}
|
|
4606
|
+
if (this.streamClient) {
|
|
4607
|
+
try {
|
|
4608
|
+
this.streamClient.disconnect();
|
|
4609
|
+
} catch {
|
|
4610
|
+
}
|
|
4611
|
+
this.streamClient = null;
|
|
4612
|
+
}
|
|
4613
|
+
if (this.redis) {
|
|
4614
|
+
try {
|
|
4615
|
+
await this.redis.disconnect();
|
|
4616
|
+
} catch {
|
|
4617
|
+
}
|
|
4618
|
+
this.redis = null;
|
|
4619
|
+
}
|
|
4620
|
+
if (!this._diskDisabled) this.disk.close();
|
|
4621
|
+
}
|
|
4622
|
+
};
|
|
4623
|
+
|
|
4624
|
+
export {
|
|
4625
|
+
WasmBloomFilter,
|
|
4626
|
+
SmartMemoryCache,
|
|
4627
|
+
DiskTier,
|
|
4628
|
+
CacheService
|
|
4629
|
+
};
|