tricache 0.5.1 → 0.6.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/README.md +133 -0
- package/dist/chunk-F24NEZGQ.js +342 -0
- package/dist/index.cjs +938 -217
- package/dist/index.d.cts +248 -6
- package/dist/index.d.ts +248 -6
- package/dist/index.js +845 -452
- package/dist/serialize-worker.cjs +366 -0
- package/dist/serialize-worker.d.cts +2 -0
- package/dist/serialize-worker.d.ts +2 -0
- package/dist/serialize-worker.js +35 -0
- package/package.json +6 -6
- package/src/cache-service.ts +510 -109
- package/src/disk-tier.ts +244 -28
- package/src/encryption.ts +47 -22
- package/src/serialize-worker.ts +56 -0
- package/src/smart-memory-cache.ts +105 -31
- package/src/types.ts +179 -1
- package/src/worker-pool.ts +190 -0
package/dist/index.cjs
CHANGED
|
@@ -45,8 +45,128 @@ var import_ioredis = require("ioredis");
|
|
|
45
45
|
var import_msgpackr3 = require("msgpackr");
|
|
46
46
|
var import_crypto3 = __toESM(require("crypto"), 1);
|
|
47
47
|
var import_os = __toESM(require("os"), 1);
|
|
48
|
-
|
|
49
|
-
|
|
48
|
+
|
|
49
|
+
// src/worker-pool.ts
|
|
50
|
+
var import_worker_threads = require("worker_threads");
|
|
51
|
+
var import_url = require("url");
|
|
52
|
+
var import_path = require("path");
|
|
53
|
+
var import_fs = require("fs");
|
|
54
|
+
var import_meta = {};
|
|
55
|
+
var _workerFile;
|
|
56
|
+
var _workerExecArgv = [];
|
|
57
|
+
try {
|
|
58
|
+
const dir = (0, import_path.dirname)((0, import_url.fileURLToPath)(import_meta.url));
|
|
59
|
+
const jsPath = (0, import_path.join)(dir, "serialize-worker.js");
|
|
60
|
+
const tsPath = (0, import_path.join)(dir, "serialize-worker.ts");
|
|
61
|
+
if ((0, import_fs.existsSync)(jsPath)) {
|
|
62
|
+
_workerFile = jsPath;
|
|
63
|
+
} else if ((0, import_fs.existsSync)(tsPath)) {
|
|
64
|
+
_workerFile = tsPath;
|
|
65
|
+
_workerExecArgv = ["--import", "tsx"];
|
|
66
|
+
} else {
|
|
67
|
+
_workerFile = jsPath;
|
|
68
|
+
}
|
|
69
|
+
} catch {
|
|
70
|
+
_workerFile = (0, import_path.join)(__dirname, "serialize-worker.js");
|
|
71
|
+
}
|
|
72
|
+
var WorkerPool = class {
|
|
73
|
+
workers = [];
|
|
74
|
+
pending = [];
|
|
75
|
+
_nextId = 0;
|
|
76
|
+
_robin = 0;
|
|
77
|
+
_available = false;
|
|
78
|
+
constructor(opts) {
|
|
79
|
+
const size = Math.max(1, opts.size ?? Math.min(4, availableCpus()));
|
|
80
|
+
const workerData = {
|
|
81
|
+
keyBase64: opts.keyBase64,
|
|
82
|
+
mode: opts.mode,
|
|
83
|
+
prevKeyBase64: opts.prevKeyBase64 ?? "",
|
|
84
|
+
prevMode: opts.prevMode
|
|
85
|
+
};
|
|
86
|
+
try {
|
|
87
|
+
for (let i = 0; i < size; i++) {
|
|
88
|
+
const worker = new import_worker_threads.Worker(_workerFile, {
|
|
89
|
+
workerData,
|
|
90
|
+
execArgv: _workerExecArgv.length > 0 ? _workerExecArgv : void 0
|
|
91
|
+
});
|
|
92
|
+
const pending = /* @__PURE__ */ new Map();
|
|
93
|
+
worker.on("message", (msg) => {
|
|
94
|
+
const entry = pending.get(msg.id);
|
|
95
|
+
if (!entry) return;
|
|
96
|
+
pending.delete(msg.id);
|
|
97
|
+
if (pending.size === 0) worker.unref();
|
|
98
|
+
if (msg.error !== void 0) {
|
|
99
|
+
entry.reject(new Error(msg.error));
|
|
100
|
+
} else {
|
|
101
|
+
entry.resolve(msg.result);
|
|
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.unref();
|
|
110
|
+
this.workers.push(worker);
|
|
111
|
+
this.pending.push(pending);
|
|
112
|
+
}
|
|
113
|
+
this._available = true;
|
|
114
|
+
} catch {
|
|
115
|
+
this._destroy();
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
get isAvailable() {
|
|
119
|
+
return this._available;
|
|
120
|
+
}
|
|
121
|
+
/** Encrypt a JSON string in a worker thread. Returns the same encrypted envelope string as CacheEncryption.encrypt(). */
|
|
122
|
+
encrypt(payload) {
|
|
123
|
+
return this._dispatch("encrypt", payload);
|
|
124
|
+
}
|
|
125
|
+
/** Decrypt an encrypted envelope string in a worker thread. Returns the original JSON string. */
|
|
126
|
+
decrypt(payload) {
|
|
127
|
+
return this._dispatch("decrypt", payload);
|
|
128
|
+
}
|
|
129
|
+
_dispatch(type, payload) {
|
|
130
|
+
const id = this._nextId++;
|
|
131
|
+
const idx = this._robin;
|
|
132
|
+
const worker = this.workers[idx];
|
|
133
|
+
const pending = this.pending[idx];
|
|
134
|
+
this._robin = (this._robin + 1) % this.workers.length;
|
|
135
|
+
return new Promise((resolve, reject) => {
|
|
136
|
+
pending.set(id, { resolve, reject });
|
|
137
|
+
worker.ref();
|
|
138
|
+
worker.postMessage({ id, type, payload });
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
/** Terminate all worker threads. In-flight promises are rejected. */
|
|
142
|
+
async destroy() {
|
|
143
|
+
this._available = false;
|
|
144
|
+
this._destroy();
|
|
145
|
+
}
|
|
146
|
+
_destroy() {
|
|
147
|
+
for (let i = 0; i < this.workers.length; i++) {
|
|
148
|
+
for (const [, entry] of this.pending[i] ?? []) {
|
|
149
|
+
entry.reject(new Error("WorkerPool destroyed"));
|
|
150
|
+
}
|
|
151
|
+
this.pending[i]?.clear();
|
|
152
|
+
this.workers[i]?.terminate().catch(() => {
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
function availableCpus() {
|
|
158
|
+
try {
|
|
159
|
+
const os2 = require("os");
|
|
160
|
+
return os2.availableParallelism?.() ?? os2.cpus().length;
|
|
161
|
+
} catch {
|
|
162
|
+
return 2;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// src/cache-service.ts
|
|
167
|
+
var import_node_v8 = __toESM(require("v8"), 1);
|
|
168
|
+
var import_fs3 = __toESM(require("fs"), 1);
|
|
169
|
+
var import_path3 = __toESM(require("path"), 1);
|
|
50
170
|
|
|
51
171
|
// src/types.ts
|
|
52
172
|
var consoleLogger = {
|
|
@@ -81,8 +201,12 @@ var PREFIX_CTR = "ctr:v1:";
|
|
|
81
201
|
var IV_POOL_COUNT = 64;
|
|
82
202
|
var CacheEncryption = class {
|
|
83
203
|
_key = null;
|
|
204
|
+
// raw bytes — used only for XOR
|
|
205
|
+
_keyObj = null;
|
|
206
|
+
// parsed KeyObject — used for all AES modes
|
|
84
207
|
_mode;
|
|
85
208
|
_prevKey = null;
|
|
209
|
+
_prevKeyObj = null;
|
|
86
210
|
_prevMode = "aes-256-gcm";
|
|
87
211
|
// Pre-allocated GCM IV pool — 12-byte IVs (96-bit, NIST recommended).
|
|
88
212
|
_ivPool = Buffer.allocUnsafe(IV_BYTES * IV_POOL_COUNT);
|
|
@@ -167,6 +291,16 @@ var CacheEncryption = class {
|
|
|
167
291
|
throw new Error("XOR key must be at least 1 byte");
|
|
168
292
|
}
|
|
169
293
|
this._key = buf;
|
|
294
|
+
if (mode !== "xor") {
|
|
295
|
+
this._keyObj = (0, import_crypto.createSecretKey)(buf);
|
|
296
|
+
const _wc = (0, import_crypto.createCipheriv)(
|
|
297
|
+
mode,
|
|
298
|
+
this._keyObj,
|
|
299
|
+
Buffer.alloc(mode === "aes-128-ctr" ? CTR_IV_BYTES : IV_BYTES)
|
|
300
|
+
);
|
|
301
|
+
_wc.update(Buffer.alloc(0));
|
|
302
|
+
_wc.final();
|
|
303
|
+
}
|
|
170
304
|
if (mode === "xor") {
|
|
171
305
|
logger.warn(
|
|
172
306
|
"Cache obfuscation enabled (XOR). WARNING: XOR is NOT cryptographic \u2014 use only for dev or non-sensitive data."
|
|
@@ -181,6 +315,16 @@ var CacheEncryption = class {
|
|
|
181
315
|
try {
|
|
182
316
|
this._prevMode = previousMode ?? mode;
|
|
183
317
|
this._prevKey = Buffer.from(previousKeyBase64, "base64");
|
|
318
|
+
if (this._prevMode !== "xor") {
|
|
319
|
+
this._prevKeyObj = (0, import_crypto.createSecretKey)(this._prevKey);
|
|
320
|
+
const _wc = (0, import_crypto.createCipheriv)(
|
|
321
|
+
this._prevMode,
|
|
322
|
+
this._prevKeyObj,
|
|
323
|
+
Buffer.alloc(this._prevMode === "aes-128-ctr" ? CTR_IV_BYTES : IV_BYTES)
|
|
324
|
+
);
|
|
325
|
+
_wc.update(Buffer.alloc(0));
|
|
326
|
+
_wc.final();
|
|
327
|
+
}
|
|
184
328
|
logger.debug("Previous encryption key loaded for key rotation fallback");
|
|
185
329
|
} catch (err) {
|
|
186
330
|
logger.warn("Invalid previousEncryptionKey \u2014 rotation fallback disabled", { error: err.message });
|
|
@@ -204,7 +348,7 @@ var CacheEncryption = class {
|
|
|
204
348
|
}
|
|
205
349
|
if (this._mode === "aes-128-ctr") {
|
|
206
350
|
const iv2 = this._nextCtrIV();
|
|
207
|
-
const c2 = (0, import_crypto.createCipheriv)("aes-128-ctr", this.
|
|
351
|
+
const c2 = (0, import_crypto.createCipheriv)("aes-128-ctr", this._keyObj, iv2);
|
|
208
352
|
const enc2 = c2.update(plaintext, "utf8");
|
|
209
353
|
const fin = c2.final();
|
|
210
354
|
const out2 = Buffer.allocUnsafe(CTR_IV_BYTES + enc2.length + fin.length);
|
|
@@ -216,7 +360,7 @@ var CacheEncryption = class {
|
|
|
216
360
|
const algo = this._mode === "aes-128-gcm" ? "aes-128-gcm" : "aes-256-gcm";
|
|
217
361
|
const prefix = this._mode === "aes-128-gcm" ? PREFIX_128 : PREFIX_256;
|
|
218
362
|
const iv = this._nextIV();
|
|
219
|
-
const c = (0, import_crypto.createCipheriv)(algo, this.
|
|
363
|
+
const c = (0, import_crypto.createCipheriv)(algo, this._keyObj, iv);
|
|
220
364
|
const enc = c.update(plaintext, "utf8");
|
|
221
365
|
c.final();
|
|
222
366
|
const out = Buffer.allocUnsafe(IV_BYTES + TAG_BYTES + enc.length);
|
|
@@ -232,18 +376,18 @@ var CacheEncryption = class {
|
|
|
232
376
|
*/
|
|
233
377
|
decrypt(value) {
|
|
234
378
|
try {
|
|
235
|
-
return this._decryptWithKey(value, this._key, this._mode);
|
|
379
|
+
return this._decryptWithKey(value, this._key, this._keyObj, this._mode);
|
|
236
380
|
} catch (primaryErr) {
|
|
237
381
|
if (this._prevKey) {
|
|
238
382
|
try {
|
|
239
|
-
return this._decryptWithKey(value, this._prevKey, this._prevMode);
|
|
383
|
+
return this._decryptWithKey(value, this._prevKey, this._prevKeyObj, this._prevMode);
|
|
240
384
|
} catch {
|
|
241
385
|
}
|
|
242
386
|
}
|
|
243
387
|
throw primaryErr;
|
|
244
388
|
}
|
|
245
389
|
}
|
|
246
|
-
_decryptWithKey(value, key, mode) {
|
|
390
|
+
_decryptWithKey(value, key, keyObj, mode) {
|
|
247
391
|
if (value.startsWith(PREFIX_XOR)) {
|
|
248
392
|
if (!key) throw new Error("Cannot decrypt: encryption key is not set");
|
|
249
393
|
const masked = Buffer.from(value.slice(PREFIX_XOR.length), "base64");
|
|
@@ -254,11 +398,11 @@ var CacheEncryption = class {
|
|
|
254
398
|
return out.toString("utf8");
|
|
255
399
|
}
|
|
256
400
|
if (value.startsWith(PREFIX_CTR)) {
|
|
257
|
-
if (!
|
|
401
|
+
if (!keyObj) throw new Error("Cannot decrypt: encryption key is not set");
|
|
258
402
|
const combined2 = Buffer.from(value.slice(PREFIX_CTR.length), "base64");
|
|
259
403
|
const iv2 = combined2.subarray(0, CTR_IV_BYTES);
|
|
260
404
|
const ct2 = combined2.subarray(CTR_IV_BYTES);
|
|
261
|
-
const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr",
|
|
405
|
+
const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr", keyObj, iv2);
|
|
262
406
|
const plain2 = d2.update(ct2);
|
|
263
407
|
const fin = d2.final();
|
|
264
408
|
return (fin.length > 0 ? Buffer.concat([plain2, fin]) : plain2).toString("utf8");
|
|
@@ -266,19 +410,20 @@ var CacheEncryption = class {
|
|
|
266
410
|
const is256 = value.startsWith(PREFIX_256);
|
|
267
411
|
const is128 = value.startsWith(PREFIX_128);
|
|
268
412
|
if (!is256 && !is128) return value;
|
|
269
|
-
if (!
|
|
413
|
+
if (!keyObj) throw new Error("Cannot decrypt: encryption key is not set");
|
|
270
414
|
const prefix = is128 ? PREFIX_128 : PREFIX_256;
|
|
271
415
|
const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
|
|
272
416
|
const combined = Buffer.from(value.slice(prefix.length), "base64");
|
|
273
417
|
const iv = combined.subarray(0, IV_BYTES);
|
|
274
418
|
const tag = combined.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
|
|
275
419
|
const ct = combined.subarray(IV_BYTES + TAG_BYTES);
|
|
276
|
-
const d = (0, import_crypto.createDecipheriv)(algo,
|
|
420
|
+
const d = (0, import_crypto.createDecipheriv)(algo, keyObj, iv);
|
|
277
421
|
d.setAuthTag(tag);
|
|
278
422
|
const plain = d.update(ct);
|
|
279
423
|
d.final();
|
|
280
424
|
return plain.toString("utf8");
|
|
281
425
|
void mode;
|
|
426
|
+
void key;
|
|
282
427
|
}
|
|
283
428
|
// ── Buffer (disk / snapshot) ──────────────────────────────────────────────
|
|
284
429
|
/** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
|
|
@@ -293,7 +438,7 @@ var CacheEncryption = class {
|
|
|
293
438
|
}
|
|
294
439
|
if (this._mode === "aes-128-ctr") {
|
|
295
440
|
const iv2 = this._nextCtrIV();
|
|
296
|
-
const c2 = (0, import_crypto.createCipheriv)("aes-128-ctr", this.
|
|
441
|
+
const c2 = (0, import_crypto.createCipheriv)("aes-128-ctr", this._keyObj, iv2);
|
|
297
442
|
const enc2 = c2.update(data);
|
|
298
443
|
const fin = c2.final();
|
|
299
444
|
const out2 = Buffer.allocUnsafe(MAGIC_LEN + CTR_IV_BYTES + enc2.length + fin.length);
|
|
@@ -306,7 +451,7 @@ var CacheEncryption = class {
|
|
|
306
451
|
const magic = this._mode === "aes-128-gcm" ? MAGIC_128 : MAGIC_256;
|
|
307
452
|
const algo = this._mode === "aes-128-gcm" ? "aes-128-gcm" : "aes-256-gcm";
|
|
308
453
|
const iv = this._nextIV();
|
|
309
|
-
const c = (0, import_crypto.createCipheriv)(algo, this.
|
|
454
|
+
const c = (0, import_crypto.createCipheriv)(algo, this._keyObj, iv);
|
|
310
455
|
const enc = c.update(data);
|
|
311
456
|
c.final();
|
|
312
457
|
const out = Buffer.allocUnsafe(MAGIC_LEN + IV_BYTES + TAG_BYTES + enc.length);
|
|
@@ -323,18 +468,18 @@ var CacheEncryption = class {
|
|
|
323
468
|
*/
|
|
324
469
|
decryptBuffer(data) {
|
|
325
470
|
try {
|
|
326
|
-
return this._decryptBufferWithKey(data, this._key);
|
|
471
|
+
return this._decryptBufferWithKey(data, this._key, this._keyObj);
|
|
327
472
|
} catch (primaryErr) {
|
|
328
473
|
if (this._prevKey) {
|
|
329
474
|
try {
|
|
330
|
-
return this._decryptBufferWithKey(data, this._prevKey);
|
|
475
|
+
return this._decryptBufferWithKey(data, this._prevKey, this._prevKeyObj);
|
|
331
476
|
} catch {
|
|
332
477
|
}
|
|
333
478
|
}
|
|
334
479
|
throw primaryErr;
|
|
335
480
|
}
|
|
336
481
|
}
|
|
337
|
-
_decryptBufferWithKey(data, key) {
|
|
482
|
+
_decryptBufferWithKey(data, key, keyObj) {
|
|
338
483
|
if (data.length < MAGIC_LEN) return data;
|
|
339
484
|
const magic = data.subarray(0, MAGIC_LEN);
|
|
340
485
|
if (magic.equals(MAGIC_XOR)) {
|
|
@@ -346,10 +491,10 @@ var CacheEncryption = class {
|
|
|
346
491
|
return out;
|
|
347
492
|
}
|
|
348
493
|
if (magic.equals(MAGIC_CTR)) {
|
|
349
|
-
if (!
|
|
494
|
+
if (!keyObj) throw new Error("Cannot decrypt buffer: encryption key is not set");
|
|
350
495
|
const iv2 = data.subarray(MAGIC_LEN, MAGIC_LEN + CTR_IV_BYTES);
|
|
351
496
|
const ct2 = data.subarray(MAGIC_LEN + CTR_IV_BYTES);
|
|
352
|
-
const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr",
|
|
497
|
+
const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr", keyObj, iv2);
|
|
353
498
|
const plain2 = d2.update(ct2);
|
|
354
499
|
const fin = d2.final();
|
|
355
500
|
return fin.length > 0 ? Buffer.concat([plain2, fin]) : plain2;
|
|
@@ -357,12 +502,12 @@ var CacheEncryption = class {
|
|
|
357
502
|
const is256 = magic.equals(MAGIC_256);
|
|
358
503
|
const is128 = magic.equals(MAGIC_128);
|
|
359
504
|
if (!is256 && !is128) return data;
|
|
360
|
-
if (!
|
|
505
|
+
if (!keyObj) throw new Error("Cannot decrypt buffer: encryption key is not set");
|
|
361
506
|
const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
|
|
362
507
|
const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + IV_BYTES);
|
|
363
508
|
const tag = data.subarray(MAGIC_LEN + IV_BYTES, MAGIC_LEN + IV_BYTES + TAG_BYTES);
|
|
364
509
|
const ct = data.subarray(MAGIC_LEN + IV_BYTES + TAG_BYTES);
|
|
365
|
-
const d = (0, import_crypto.createDecipheriv)(algo,
|
|
510
|
+
const d = (0, import_crypto.createDecipheriv)(algo, keyObj, iv);
|
|
366
511
|
d.setAuthTag(tag);
|
|
367
512
|
const plain = d.update(ct);
|
|
368
513
|
d.final();
|
|
@@ -439,6 +584,8 @@ var WasmBloomFilter = class {
|
|
|
439
584
|
// src/smart-memory-cache.ts
|
|
440
585
|
var _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0, fetchedAt: 0 };
|
|
441
586
|
var EVICTION_BATCH_PERCENT = 0.2;
|
|
587
|
+
var EVICTION_SAMPLE = 16;
|
|
588
|
+
var EVICT_COUNT = Math.max(1, Math.ceil(EVICTION_SAMPLE * EVICTION_BATCH_PERCENT));
|
|
442
589
|
var JsBloomFilter = class {
|
|
443
590
|
bits;
|
|
444
591
|
numBits;
|
|
@@ -626,6 +773,15 @@ var SmartMemoryCache = class {
|
|
|
626
773
|
categoryHits = /* @__PURE__ */ new Map();
|
|
627
774
|
/** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
|
|
628
775
|
_bloomDirtyCount = 0;
|
|
776
|
+
/**
|
|
777
|
+
* Pre-allocated eviction candidate pools — reused across every smartEvict() call to
|
|
778
|
+
* eliminate per-call heap pressure. Each slot holds a mutable {key, score} record
|
|
779
|
+
* that is overwritten in-place rather than replaced with a new object literal.
|
|
780
|
+
* Safe because JS is single-threaded: smartEvict() completes synchronously before
|
|
781
|
+
* any other code can observe the pool state.
|
|
782
|
+
*/
|
|
783
|
+
_evictPool = Array.from({ length: EVICTION_SAMPLE }, () => ({ key: "", score: 0 }));
|
|
784
|
+
_evictGPool = Array.from({ length: EVICTION_SAMPLE }, () => ({ key: "", score: 0 }));
|
|
629
785
|
constructor(opts, existing) {
|
|
630
786
|
this.opts = opts;
|
|
631
787
|
this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
|
|
@@ -689,8 +845,9 @@ var SmartMemoryCache = class {
|
|
|
689
845
|
const catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
|
|
690
846
|
const glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
|
|
691
847
|
if (!catOvf && !glbOvf) {
|
|
692
|
-
const
|
|
693
|
-
const
|
|
848
|
+
const wm = this.opts.evictionWatermark ?? 0.9;
|
|
849
|
+
const entryWatermark = this.cache.size >= Math.floor(this.opts.maxEntries * wm);
|
|
850
|
+
const byteWatermark = this.totalSize + neededSize >= Math.floor(this.opts.maxBytes * wm);
|
|
694
851
|
if (entryWatermark || byteWatermark) {
|
|
695
852
|
this.smartEvict(category, false);
|
|
696
853
|
}
|
|
@@ -726,9 +883,9 @@ var SmartMemoryCache = class {
|
|
|
726
883
|
}
|
|
727
884
|
smartEvict(targetCat, catOvf) {
|
|
728
885
|
const now = Date.now();
|
|
729
|
-
const
|
|
730
|
-
const
|
|
731
|
-
|
|
886
|
+
const pool = this._evictPool;
|
|
887
|
+
const gPool = this._evictGPool;
|
|
888
|
+
let poolLen = 0;
|
|
732
889
|
if (catOvf) {
|
|
733
890
|
const catKeySet = this.categoryKeys.get(targetCat);
|
|
734
891
|
if (catKeySet) {
|
|
@@ -738,36 +895,62 @@ var SmartMemoryCache = class {
|
|
|
738
895
|
if (!entry || entry.priority === 4 && entry.expiresAt > now) continue;
|
|
739
896
|
catSeen++;
|
|
740
897
|
const s = this.score(entry, 100, now, key);
|
|
741
|
-
if (
|
|
742
|
-
pool.
|
|
898
|
+
if (poolLen < EVICT_COUNT) {
|
|
899
|
+
pool[poolLen].key = key;
|
|
900
|
+
pool[poolLen].score = s;
|
|
901
|
+
poolLen++;
|
|
743
902
|
} else {
|
|
744
903
|
const j = Math.floor(Math.random() * catSeen);
|
|
745
|
-
if (j <
|
|
904
|
+
if (j < EVICT_COUNT) {
|
|
905
|
+
pool[j].key = key;
|
|
906
|
+
pool[j].score = s;
|
|
907
|
+
}
|
|
746
908
|
}
|
|
747
909
|
}
|
|
748
910
|
}
|
|
749
911
|
}
|
|
750
|
-
if (
|
|
751
|
-
const remaining =
|
|
912
|
+
if (poolLen < EVICT_COUNT) {
|
|
913
|
+
const remaining = EVICTION_SAMPLE - poolLen;
|
|
752
914
|
let globalSeen = 0;
|
|
753
|
-
|
|
915
|
+
let gLen = 0;
|
|
754
916
|
for (const [key, entry] of this.cache) {
|
|
755
917
|
if (entry.priority === 4 && entry.expiresAt > now) continue;
|
|
756
918
|
if (catOvf && this.getCategory(key) === targetCat) continue;
|
|
757
919
|
globalSeen++;
|
|
758
920
|
const s = this.score(entry, 0, now, key);
|
|
759
|
-
if (
|
|
760
|
-
|
|
921
|
+
if (gLen < remaining) {
|
|
922
|
+
gPool[gLen].key = key;
|
|
923
|
+
gPool[gLen].score = s;
|
|
924
|
+
gLen++;
|
|
761
925
|
} else {
|
|
762
926
|
const j = Math.floor(Math.random() * globalSeen);
|
|
763
|
-
if (j < remaining)
|
|
927
|
+
if (j < remaining) {
|
|
928
|
+
gPool[j].key = key;
|
|
929
|
+
gPool[j].score = s;
|
|
930
|
+
}
|
|
764
931
|
}
|
|
765
932
|
}
|
|
766
|
-
|
|
933
|
+
for (let i = 0; i < gLen; i++) {
|
|
934
|
+
pool[poolLen].key = gPool[i].key;
|
|
935
|
+
pool[poolLen].score = gPool[i].score;
|
|
936
|
+
poolLen++;
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
if (poolLen === 0) return;
|
|
940
|
+
for (let i = 1; i < poolLen; i++) {
|
|
941
|
+
const sk = pool[i].key, ss = pool[i].score;
|
|
942
|
+
let j = i - 1;
|
|
943
|
+
while (j >= 0 && pool[j].score > ss) {
|
|
944
|
+
pool[j + 1].key = pool[j].key;
|
|
945
|
+
pool[j + 1].score = pool[j].score;
|
|
946
|
+
j--;
|
|
947
|
+
}
|
|
948
|
+
pool[j + 1].key = sk;
|
|
949
|
+
pool[j + 1].score = ss;
|
|
767
950
|
}
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
951
|
+
const toEvict = Math.min(EVICT_COUNT, poolLen);
|
|
952
|
+
for (let i = 0; i < toEvict; i++) {
|
|
953
|
+
const key = pool[i].key;
|
|
771
954
|
const entry = this.cache.get(key);
|
|
772
955
|
if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
|
|
773
956
|
this._delete(key, "capacity");
|
|
@@ -975,7 +1158,39 @@ var SmartMemoryCache = class {
|
|
|
975
1158
|
}
|
|
976
1159
|
return cleaned;
|
|
977
1160
|
}
|
|
978
|
-
|
|
1161
|
+
/**
|
|
1162
|
+
* Evict all non-CRITICAL L1 entries that were written before `cutoffMs`.
|
|
1163
|
+
*
|
|
1164
|
+
* Called by the backplane staleness fence when the Pub/Sub subscriber
|
|
1165
|
+
* reconnects after a disconnect gap that exceeded `backplaneMaxStalenessMs`.
|
|
1166
|
+
* Entries written before the disconnect started may have been invalidated by
|
|
1167
|
+
* peers while the backplane was down; evicting them forces a controlled
|
|
1168
|
+
* cold-start re-fetch from L2 rather than serving silently stale data.
|
|
1169
|
+
*
|
|
1170
|
+
* Write-time is approximated as `entry.expiresAt - entry.ttlMs`.
|
|
1171
|
+
* Entries with no stored `ttlMs` (e.g. legacy snapshot imports) are evicted
|
|
1172
|
+
* conservatively.
|
|
1173
|
+
*
|
|
1174
|
+
* @param cutoffMs - Unix timestamp in milliseconds; entries written before
|
|
1175
|
+
* this time are evicted.
|
|
1176
|
+
* @returns Number of entries evicted.
|
|
1177
|
+
*/
|
|
1178
|
+
evictSetBefore(cutoffMs) {
|
|
1179
|
+
let evicted = 0;
|
|
1180
|
+
for (const [key, entry] of this.cache) {
|
|
1181
|
+
if (entry.priority === 4 && entry.expiresAt > Date.now()) continue;
|
|
1182
|
+
const setAt = entry.ttlMs != null ? entry.expiresAt - entry.ttlMs : 0;
|
|
1183
|
+
if (setAt < cutoffMs) {
|
|
1184
|
+
this._delete(key, "manual");
|
|
1185
|
+
evicted++;
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
if (evicted > 0) {
|
|
1189
|
+
this.bloom.rebuild(this.cache.keys());
|
|
1190
|
+
this._bloomDirtyCount = 0;
|
|
1191
|
+
}
|
|
1192
|
+
return evicted;
|
|
1193
|
+
}
|
|
979
1194
|
exportEntries(forbiddenPrefixes) {
|
|
980
1195
|
const now = Date.now();
|
|
981
1196
|
const out = [];
|
|
@@ -1169,10 +1384,18 @@ var SmartMemoryCache = class {
|
|
|
1169
1384
|
};
|
|
1170
1385
|
|
|
1171
1386
|
// src/disk-tier.ts
|
|
1172
|
-
var
|
|
1173
|
-
var
|
|
1387
|
+
var import_fs2 = __toESM(require("fs"), 1);
|
|
1388
|
+
var import_path2 = __toESM(require("path"), 1);
|
|
1174
1389
|
var import_crypto2 = __toESM(require("crypto"), 1);
|
|
1390
|
+
var import_module = require("module");
|
|
1175
1391
|
var import_msgpackr2 = require("msgpackr");
|
|
1392
|
+
var import_meta2 = {};
|
|
1393
|
+
var _SqliteDB = null;
|
|
1394
|
+
try {
|
|
1395
|
+
const _req = (0, import_module.createRequire)(import_meta2.url);
|
|
1396
|
+
_SqliteDB = _req("node:sqlite").DatabaseSync;
|
|
1397
|
+
} catch {
|
|
1398
|
+
}
|
|
1176
1399
|
var AES_ALGO = "aes-256-gcm";
|
|
1177
1400
|
var IV_BYTES2 = 12;
|
|
1178
1401
|
var TAG_BYTES2 = 16;
|
|
@@ -1189,6 +1412,20 @@ var DiskTier = class {
|
|
|
1189
1412
|
// maintained in-memory; avoids walkCacheFiles() in stats
|
|
1190
1413
|
/** Next bucket index (0–255) for the staggered janitor wheel. */
|
|
1191
1414
|
_nextJanitorBucket = 0;
|
|
1415
|
+
// ── SQLite metadata index (optional, requires node:sqlite) ───────────────
|
|
1416
|
+
_db = null;
|
|
1417
|
+
_stmtInsert = null;
|
|
1418
|
+
// INSERT OR REPLACE
|
|
1419
|
+
_stmtSelect = null;
|
|
1420
|
+
// SELECT by key_hash
|
|
1421
|
+
_stmtDelete = null;
|
|
1422
|
+
// DELETE by key_hash
|
|
1423
|
+
_stmtExpire = null;
|
|
1424
|
+
// SELECT expired rows
|
|
1425
|
+
_stmtDelExp = null;
|
|
1426
|
+
// DELETE expired rows
|
|
1427
|
+
_stmtStats = null;
|
|
1428
|
+
// COUNT + SUM(size)
|
|
1192
1429
|
constructor(opts) {
|
|
1193
1430
|
this.opts = opts;
|
|
1194
1431
|
}
|
|
@@ -1196,15 +1433,72 @@ var DiskTier = class {
|
|
|
1196
1433
|
ensureDir() {
|
|
1197
1434
|
if (this.dirReady) return;
|
|
1198
1435
|
try {
|
|
1199
|
-
|
|
1436
|
+
import_fs2.default.mkdirSync(this.opts.dir, { recursive: true, mode: 448 });
|
|
1200
1437
|
this.dirReady = true;
|
|
1438
|
+
this._initSqlite();
|
|
1201
1439
|
} catch (err) {
|
|
1202
1440
|
this.opts.logger.warn("DiskTier: cannot create cache dir", { dir: this.opts.dir, error: err.message });
|
|
1203
1441
|
}
|
|
1204
1442
|
}
|
|
1443
|
+
/**
|
|
1444
|
+
* Initialise the SQLite metadata index. Called once after the cache directory
|
|
1445
|
+
* is confirmed to exist. On any failure the instance silently falls back to
|
|
1446
|
+
* file-only mode — all public methods handle `this._db === null`.
|
|
1447
|
+
*
|
|
1448
|
+
* Schema:
|
|
1449
|
+
* meta(key_hash TEXT PK, file_path TEXT, expires_at INT, size INT)
|
|
1450
|
+
* idx_expires on (expires_at) — makes WHERE expires_at <= ? O(log n).
|
|
1451
|
+
*
|
|
1452
|
+
* WAL + synchronous=NORMAL: durable enough for a cache (a crash loses at
|
|
1453
|
+
* most one WAL frame — acceptable data loss for an L1.5 spill store).
|
|
1454
|
+
*/
|
|
1455
|
+
_initSqlite() {
|
|
1456
|
+
if (!_SqliteDB) return;
|
|
1457
|
+
try {
|
|
1458
|
+
const dbPath = import_path2.default.join(this.opts.dir, "meta.db");
|
|
1459
|
+
this._db = new _SqliteDB(dbPath);
|
|
1460
|
+
this._db.exec(`
|
|
1461
|
+
PRAGMA journal_mode = WAL;
|
|
1462
|
+
PRAGMA synchronous = NORMAL;
|
|
1463
|
+
PRAGMA temp_store = MEMORY;
|
|
1464
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
1465
|
+
key_hash TEXT PRIMARY KEY,
|
|
1466
|
+
file_path TEXT NOT NULL,
|
|
1467
|
+
expires_at INTEGER NOT NULL,
|
|
1468
|
+
size INTEGER NOT NULL DEFAULT 0
|
|
1469
|
+
);
|
|
1470
|
+
CREATE INDEX IF NOT EXISTS idx_expires ON meta (expires_at);
|
|
1471
|
+
`);
|
|
1472
|
+
this._stmtInsert = this._db.prepare(
|
|
1473
|
+
"INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size) VALUES (?,?,?,?)"
|
|
1474
|
+
);
|
|
1475
|
+
this._stmtSelect = this._db.prepare(
|
|
1476
|
+
"SELECT file_path, expires_at FROM meta WHERE key_hash = ?"
|
|
1477
|
+
);
|
|
1478
|
+
this._stmtDelete = this._db.prepare("DELETE FROM meta WHERE key_hash = ?");
|
|
1479
|
+
this._stmtExpire = this._db.prepare(
|
|
1480
|
+
"SELECT key_hash, file_path, size FROM meta WHERE expires_at <= ?"
|
|
1481
|
+
);
|
|
1482
|
+
this._stmtDelExp = this._db.prepare("DELETE FROM meta WHERE expires_at <= ?");
|
|
1483
|
+
this._stmtStats = this._db.prepare(
|
|
1484
|
+
"SELECT COUNT(*) AS cnt, COALESCE(SUM(size), 0) AS bytes FROM meta"
|
|
1485
|
+
);
|
|
1486
|
+
const row = this._stmtStats.get();
|
|
1487
|
+
this.fileCount = row.cnt;
|
|
1488
|
+
this.diskUsageBytes = row.bytes;
|
|
1489
|
+
this.usageCounted = true;
|
|
1490
|
+
this.opts.logger.debug("DiskTier: SQLite index ready", { entries: row.cnt });
|
|
1491
|
+
} catch (err) {
|
|
1492
|
+
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
|
|
1493
|
+
this.opts.logger.warn("DiskTier: SQLite init failed, using file-only mode", {
|
|
1494
|
+
error: err.message
|
|
1495
|
+
});
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1205
1498
|
ensureUsageCounted() {
|
|
1206
1499
|
if (this.usageCounted) return;
|
|
1207
1500
|
this.usageCounted = true;
|
|
1501
|
+
if (this._db) return;
|
|
1208
1502
|
try {
|
|
1209
1503
|
this.ensureDir();
|
|
1210
1504
|
let total = 0;
|
|
@@ -1212,7 +1506,7 @@ var DiskTier = class {
|
|
|
1212
1506
|
this.fileCount = files.length;
|
|
1213
1507
|
for (const filePath of files) {
|
|
1214
1508
|
try {
|
|
1215
|
-
total +=
|
|
1509
|
+
total += import_fs2.default.statSync(filePath).size;
|
|
1216
1510
|
} catch {
|
|
1217
1511
|
}
|
|
1218
1512
|
}
|
|
@@ -1241,7 +1535,7 @@ var DiskTier = class {
|
|
|
1241
1535
|
* 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
|
|
1242
1536
|
*/
|
|
1243
1537
|
hashToWritePath(hash, expiresAt) {
|
|
1244
|
-
return
|
|
1538
|
+
return import_path2.default.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiresAt.toString(16).padStart(12, "0")}`);
|
|
1245
1539
|
}
|
|
1246
1540
|
/**
|
|
1247
1541
|
* Find the on-disk file for a key hash, handling all filename generations:
|
|
@@ -1250,10 +1544,10 @@ var DiskTier = class {
|
|
|
1250
1544
|
* Returns null when the bucket dir does not exist or the key is absent.
|
|
1251
1545
|
*/
|
|
1252
1546
|
findFilePath(hash) {
|
|
1253
|
-
const bucketPath =
|
|
1547
|
+
const bucketPath = import_path2.default.join(this.opts.dir, hash.slice(0, 2));
|
|
1254
1548
|
let files;
|
|
1255
1549
|
try {
|
|
1256
|
-
files =
|
|
1550
|
+
files = import_fs2.default.readdirSync(bucketPath);
|
|
1257
1551
|
} catch {
|
|
1258
1552
|
return null;
|
|
1259
1553
|
}
|
|
@@ -1262,7 +1556,7 @@ var DiskTier = class {
|
|
|
1262
1556
|
if ((f === hash || f.startsWith(hash + "_")) && (!match || f > match)) match = f;
|
|
1263
1557
|
}
|
|
1264
1558
|
if (!match) return null;
|
|
1265
|
-
return
|
|
1559
|
+
return import_path2.default.join(bucketPath, match);
|
|
1266
1560
|
}
|
|
1267
1561
|
/**
|
|
1268
1562
|
* Recursively list all cache file paths across the 2-level sharded subdirs.
|
|
@@ -1273,16 +1567,16 @@ var DiskTier = class {
|
|
|
1273
1567
|
const results = [];
|
|
1274
1568
|
let topEntries;
|
|
1275
1569
|
try {
|
|
1276
|
-
topEntries =
|
|
1570
|
+
topEntries = import_fs2.default.readdirSync(this.opts.dir);
|
|
1277
1571
|
} catch {
|
|
1278
1572
|
return results;
|
|
1279
1573
|
}
|
|
1280
1574
|
for (const top of topEntries) {
|
|
1281
|
-
const topPath =
|
|
1575
|
+
const topPath = import_path2.default.join(this.opts.dir, top);
|
|
1282
1576
|
try {
|
|
1283
|
-
if (!
|
|
1284
|
-
for (const file of
|
|
1285
|
-
results.push(
|
|
1577
|
+
if (!import_fs2.default.statSync(topPath).isDirectory()) continue;
|
|
1578
|
+
for (const file of import_fs2.default.readdirSync(topPath)) {
|
|
1579
|
+
results.push(import_path2.default.join(topPath, file));
|
|
1286
1580
|
}
|
|
1287
1581
|
} catch {
|
|
1288
1582
|
}
|
|
@@ -1390,12 +1684,19 @@ var DiskTier = class {
|
|
|
1390
1684
|
this.diskUsageBytes += final.length;
|
|
1391
1685
|
this.fileCount++;
|
|
1392
1686
|
try {
|
|
1393
|
-
await
|
|
1394
|
-
await
|
|
1687
|
+
await import_fs2.default.promises.mkdir(import_path2.default.dirname(filePath), { recursive: true });
|
|
1688
|
+
await import_fs2.default.promises.writeFile(filePath, final, { mode: 384 });
|
|
1689
|
+
if (this._db) {
|
|
1690
|
+
this._stmtInsert.run(hash, filePath, entry.expiresAt, final.length);
|
|
1691
|
+
}
|
|
1395
1692
|
this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
|
|
1396
1693
|
} catch (err) {
|
|
1397
1694
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
|
|
1398
1695
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1696
|
+
if (this._db) try {
|
|
1697
|
+
this._stmtDelete.run(hash);
|
|
1698
|
+
} catch {
|
|
1699
|
+
}
|
|
1399
1700
|
this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
|
|
1400
1701
|
}
|
|
1401
1702
|
}
|
|
@@ -1405,36 +1706,58 @@ var DiskTier = class {
|
|
|
1405
1706
|
this.ensureDir();
|
|
1406
1707
|
if (!this.dirReady) return null;
|
|
1407
1708
|
const hash = this.keyToHash(key);
|
|
1408
|
-
|
|
1409
|
-
if (
|
|
1709
|
+
let filePath;
|
|
1710
|
+
if (this._db) {
|
|
1711
|
+
const row = this._stmtSelect.get(hash);
|
|
1712
|
+
if (!row) return null;
|
|
1713
|
+
if (row.expires_at <= Date.now()) {
|
|
1714
|
+
this._stmtDelete.run(hash);
|
|
1715
|
+
try {
|
|
1716
|
+
const sz = import_fs2.default.statSync(row.file_path).size;
|
|
1717
|
+
import_fs2.default.unlinkSync(row.file_path);
|
|
1718
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
1719
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1720
|
+
} catch {
|
|
1721
|
+
}
|
|
1722
|
+
return null;
|
|
1723
|
+
}
|
|
1724
|
+
filePath = row.file_path;
|
|
1725
|
+
} else {
|
|
1726
|
+
filePath = this.findFilePath(hash);
|
|
1727
|
+
if (!filePath) return null;
|
|
1728
|
+
}
|
|
1410
1729
|
try {
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1730
|
+
if (!this._db) {
|
|
1731
|
+
const filename = import_path2.default.basename(filePath);
|
|
1732
|
+
if (filename.length === 77 && filename[64] === "_") {
|
|
1733
|
+
const expiresAt = parseInt(filename.slice(65), 16);
|
|
1734
|
+
if (expiresAt <= Date.now()) {
|
|
1735
|
+
try {
|
|
1736
|
+
const sz = import_fs2.default.statSync(filePath).size;
|
|
1737
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1738
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
1739
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1740
|
+
} catch {
|
|
1741
|
+
}
|
|
1742
|
+
return null;
|
|
1421
1743
|
}
|
|
1422
|
-
return null;
|
|
1423
1744
|
}
|
|
1424
1745
|
}
|
|
1425
|
-
const stat =
|
|
1746
|
+
const stat = import_fs2.default.statSync(filePath);
|
|
1426
1747
|
if (stat.size > this.opts.entryMaxBytes) {
|
|
1427
|
-
|
|
1748
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1428
1749
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1750
|
+
if (this._db) this._stmtDelete.run(hash);
|
|
1429
1751
|
return null;
|
|
1430
1752
|
}
|
|
1431
|
-
const raw =
|
|
1753
|
+
const raw = import_fs2.default.readFileSync(filePath);
|
|
1432
1754
|
try {
|
|
1433
|
-
|
|
1755
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1434
1756
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1435
1757
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1436
1758
|
} catch {
|
|
1437
1759
|
}
|
|
1760
|
+
if (this._db) this._stmtDelete.run(hash);
|
|
1438
1761
|
let decrypted;
|
|
1439
1762
|
if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
|
|
1440
1763
|
const expiresAt = Number(raw.readBigUInt64LE(8));
|
|
@@ -1459,6 +1782,10 @@ var DiskTier = class {
|
|
|
1459
1782
|
this.opts.logger.debug("DiskTier: hit (\u2192L1)", { key: key.slice(0, 50), ageMs: Date.now() - payload.writtenAt });
|
|
1460
1783
|
return entry;
|
|
1461
1784
|
} catch (err) {
|
|
1785
|
+
if (this._db) try {
|
|
1786
|
+
this._stmtDelete.run(hash);
|
|
1787
|
+
} catch {
|
|
1788
|
+
}
|
|
1462
1789
|
this.opts.logger.debug("DiskTier: load failed", { key: key.slice(0, 50), error: err.message });
|
|
1463
1790
|
return null;
|
|
1464
1791
|
}
|
|
@@ -1466,11 +1793,18 @@ var DiskTier = class {
|
|
|
1466
1793
|
/** Explicitly delete a key from disk (cache invalidation). */
|
|
1467
1794
|
delete(key) {
|
|
1468
1795
|
const hash = this.keyToHash(key);
|
|
1469
|
-
|
|
1796
|
+
let filePath;
|
|
1797
|
+
if (this._db) {
|
|
1798
|
+
const row = this._stmtSelect.get(hash);
|
|
1799
|
+
filePath = row?.file_path ?? null;
|
|
1800
|
+
this._stmtDelete.run(hash);
|
|
1801
|
+
} else {
|
|
1802
|
+
filePath = this.findFilePath(hash);
|
|
1803
|
+
}
|
|
1470
1804
|
if (!filePath) return;
|
|
1471
1805
|
try {
|
|
1472
|
-
const stat =
|
|
1473
|
-
|
|
1806
|
+
const stat = import_fs2.default.statSync(filePath);
|
|
1807
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1474
1808
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1475
1809
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1476
1810
|
} catch {
|
|
@@ -1480,17 +1814,31 @@ var DiskTier = class {
|
|
|
1480
1814
|
purgeExpired() {
|
|
1481
1815
|
this.ensureDir();
|
|
1482
1816
|
if (!this.dirReady) return 0;
|
|
1817
|
+
if (this._db) {
|
|
1818
|
+
const now2 = Date.now();
|
|
1819
|
+
const expired = this._stmtExpire.all(now2);
|
|
1820
|
+
for (const row of expired) {
|
|
1821
|
+
try {
|
|
1822
|
+
import_fs2.default.unlinkSync(row.file_path);
|
|
1823
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
|
|
1824
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1825
|
+
} catch {
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1828
|
+
if (expired.length > 0) this._stmtDelExp.run(now2);
|
|
1829
|
+
return expired.length;
|
|
1830
|
+
}
|
|
1483
1831
|
const now = Date.now();
|
|
1484
1832
|
let purged = 0;
|
|
1485
1833
|
const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
|
|
1486
1834
|
for (const filePath of this.walkCacheFiles()) {
|
|
1487
|
-
const filename =
|
|
1835
|
+
const filename = import_path2.default.basename(filePath);
|
|
1488
1836
|
if (filename.length === 77 && filename[64] === "_") {
|
|
1489
1837
|
const expiresAt = parseInt(filename.slice(65), 16);
|
|
1490
1838
|
if (expiresAt <= now) {
|
|
1491
1839
|
try {
|
|
1492
|
-
const sz =
|
|
1493
|
-
|
|
1840
|
+
const sz = import_fs2.default.statSync(filePath).size;
|
|
1841
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1494
1842
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
1495
1843
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1496
1844
|
purged++;
|
|
@@ -1501,16 +1849,16 @@ var DiskTier = class {
|
|
|
1501
1849
|
}
|
|
1502
1850
|
let fd = -1;
|
|
1503
1851
|
try {
|
|
1504
|
-
fd =
|
|
1505
|
-
const bytesRead =
|
|
1506
|
-
|
|
1852
|
+
fd = import_fs2.default.openSync(filePath, "r");
|
|
1853
|
+
const bytesRead = import_fs2.default.readSync(fd, headerBuf, 0, V2_HEADER_LEN, 0);
|
|
1854
|
+
import_fs2.default.closeSync(fd);
|
|
1507
1855
|
fd = -1;
|
|
1508
1856
|
if (bytesRead === V2_HEADER_LEN && headerBuf.subarray(0, 8).equals(DISK_MAGIC_V2)) {
|
|
1509
1857
|
const expiresAt = Number(headerBuf.readBigUInt64LE(8));
|
|
1510
1858
|
if (expiresAt <= now) {
|
|
1511
1859
|
try {
|
|
1512
|
-
const sz =
|
|
1513
|
-
|
|
1860
|
+
const sz = import_fs2.default.statSync(filePath).size;
|
|
1861
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1514
1862
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
1515
1863
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1516
1864
|
purged++;
|
|
@@ -1519,27 +1867,27 @@ var DiskTier = class {
|
|
|
1519
1867
|
}
|
|
1520
1868
|
continue;
|
|
1521
1869
|
}
|
|
1522
|
-
const stat =
|
|
1870
|
+
const stat = import_fs2.default.statSync(filePath);
|
|
1523
1871
|
if (stat.size > this.opts.entryMaxBytes) {
|
|
1524
|
-
|
|
1872
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1525
1873
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1526
1874
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1527
1875
|
purged++;
|
|
1528
1876
|
continue;
|
|
1529
1877
|
}
|
|
1530
|
-
const raw =
|
|
1878
|
+
const raw = import_fs2.default.readFileSync(filePath);
|
|
1531
1879
|
let dec;
|
|
1532
1880
|
try {
|
|
1533
1881
|
dec = this.decrypt(raw);
|
|
1534
1882
|
} catch {
|
|
1535
|
-
|
|
1883
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1536
1884
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1537
1885
|
purged++;
|
|
1538
1886
|
continue;
|
|
1539
1887
|
}
|
|
1540
1888
|
const payload = (0, import_msgpackr2.unpack)(dec);
|
|
1541
1889
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
1542
|
-
|
|
1890
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1543
1891
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1544
1892
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1545
1893
|
purged++;
|
|
@@ -1547,7 +1895,7 @@ var DiskTier = class {
|
|
|
1547
1895
|
} catch {
|
|
1548
1896
|
} finally {
|
|
1549
1897
|
if (fd >= 0) try {
|
|
1550
|
-
|
|
1898
|
+
import_fs2.default.closeSync(fd);
|
|
1551
1899
|
} catch {
|
|
1552
1900
|
}
|
|
1553
1901
|
}
|
|
@@ -1555,25 +1903,67 @@ var DiskTier = class {
|
|
|
1555
1903
|
return purged;
|
|
1556
1904
|
}
|
|
1557
1905
|
/**
|
|
1558
|
-
* Purge expired entries
|
|
1559
|
-
*
|
|
1560
|
-
*
|
|
1561
|
-
*
|
|
1906
|
+
* Purge expired entries. Two modes depending on availability of SQLite:
|
|
1907
|
+
*
|
|
1908
|
+
* SQLite mode (Node 24 / Node 22 + --experimental-sqlite):
|
|
1909
|
+
* One indexed query (`WHERE expires_at <= now`) replaces the entire bucket
|
|
1910
|
+
* wheel. All expired entries are found and deleted in a single pass — the
|
|
1911
|
+
* 128-minute stagger is no longer necessary. `_nextJanitorBucket` is still
|
|
1912
|
+
* incremented so tests that inspect the counter continue to work.
|
|
1562
1913
|
*
|
|
1563
|
-
*
|
|
1564
|
-
*
|
|
1914
|
+
* File-only fallback:
|
|
1915
|
+
* Original staggered bucket wheel — purges exactly one of 256 subdirectory
|
|
1916
|
+
* buckets per call, spreading the O(fileCount) work across 256 ticks.
|
|
1565
1917
|
*
|
|
1566
1918
|
* Returns the number of entries deleted in this tick.
|
|
1567
1919
|
*/
|
|
1568
1920
|
purgeNextBucket() {
|
|
1569
1921
|
this.ensureDir();
|
|
1570
1922
|
if (!this.dirReady) return 0;
|
|
1571
|
-
const bucket = this._nextJanitorBucket.toString(16).padStart(2, "0");
|
|
1572
1923
|
this._nextJanitorBucket = (this._nextJanitorBucket + 1) % 256;
|
|
1573
|
-
|
|
1924
|
+
if (this._db) {
|
|
1925
|
+
const now2 = Date.now();
|
|
1926
|
+
const expired = this._stmtExpire.all(now2);
|
|
1927
|
+
for (const row of expired) {
|
|
1928
|
+
try {
|
|
1929
|
+
import_fs2.default.unlinkSync(row.file_path);
|
|
1930
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
|
|
1931
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1932
|
+
} catch {
|
|
1933
|
+
}
|
|
1934
|
+
}
|
|
1935
|
+
if (expired.length > 0) this._stmtDelExp.run(now2);
|
|
1936
|
+
const orphanBucket = (this._nextJanitorBucket - 1 + 256) % 256;
|
|
1937
|
+
const orphanBucketP = import_path2.default.join(this.opts.dir, orphanBucket.toString(16).padStart(2, "0"));
|
|
1938
|
+
let orphanFiles;
|
|
1939
|
+
try {
|
|
1940
|
+
orphanFiles = import_fs2.default.readdirSync(orphanBucketP);
|
|
1941
|
+
} catch {
|
|
1942
|
+
return expired.length;
|
|
1943
|
+
}
|
|
1944
|
+
for (const file of orphanFiles) {
|
|
1945
|
+
if (file.length === 77 && file[64] === "_") {
|
|
1946
|
+
const expiresAt = parseInt(file.slice(65), 16);
|
|
1947
|
+
if (expiresAt <= now2) {
|
|
1948
|
+
const fp = import_path2.default.join(orphanBucketP, file);
|
|
1949
|
+
try {
|
|
1950
|
+
const sz = import_fs2.default.statSync(fp).size;
|
|
1951
|
+
import_fs2.default.unlinkSync(fp);
|
|
1952
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
1953
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1954
|
+
} catch {
|
|
1955
|
+
}
|
|
1956
|
+
}
|
|
1957
|
+
}
|
|
1958
|
+
}
|
|
1959
|
+
return expired.length;
|
|
1960
|
+
}
|
|
1961
|
+
const bucket = (this._nextJanitorBucket - 1 + 256) % 256;
|
|
1962
|
+
const bucketHex = bucket.toString(16).padStart(2, "0");
|
|
1963
|
+
const bucketPath = import_path2.default.join(this.opts.dir, bucketHex);
|
|
1574
1964
|
let files;
|
|
1575
1965
|
try {
|
|
1576
|
-
files =
|
|
1966
|
+
files = import_fs2.default.readdirSync(bucketPath);
|
|
1577
1967
|
} catch {
|
|
1578
1968
|
return 0;
|
|
1579
1969
|
}
|
|
@@ -1584,10 +1974,10 @@ var DiskTier = class {
|
|
|
1584
1974
|
if (file.length === 77 && file[64] === "_") {
|
|
1585
1975
|
const expiresAt = parseInt(file.slice(65), 16);
|
|
1586
1976
|
if (expiresAt <= now) {
|
|
1587
|
-
const filePath2 =
|
|
1977
|
+
const filePath2 = import_path2.default.join(bucketPath, file);
|
|
1588
1978
|
try {
|
|
1589
|
-
const sz =
|
|
1590
|
-
|
|
1979
|
+
const sz = import_fs2.default.statSync(filePath2).size;
|
|
1980
|
+
import_fs2.default.unlinkSync(filePath2);
|
|
1591
1981
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
1592
1982
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1593
1983
|
purged++;
|
|
@@ -1596,19 +1986,19 @@ var DiskTier = class {
|
|
|
1596
1986
|
}
|
|
1597
1987
|
continue;
|
|
1598
1988
|
}
|
|
1599
|
-
const filePath =
|
|
1989
|
+
const filePath = import_path2.default.join(bucketPath, file);
|
|
1600
1990
|
let fd = -1;
|
|
1601
1991
|
try {
|
|
1602
|
-
fd =
|
|
1603
|
-
const bytesRead =
|
|
1604
|
-
|
|
1992
|
+
fd = import_fs2.default.openSync(filePath, "r");
|
|
1993
|
+
const bytesRead = import_fs2.default.readSync(fd, headerBuf, 0, V2_HEADER_LEN, 0);
|
|
1994
|
+
import_fs2.default.closeSync(fd);
|
|
1605
1995
|
fd = -1;
|
|
1606
1996
|
if (bytesRead === V2_HEADER_LEN && headerBuf.subarray(0, 8).equals(DISK_MAGIC_V2)) {
|
|
1607
1997
|
const expiresAt = Number(headerBuf.readBigUInt64LE(8));
|
|
1608
1998
|
if (expiresAt <= now) {
|
|
1609
1999
|
try {
|
|
1610
|
-
const sz =
|
|
1611
|
-
|
|
2000
|
+
const sz = import_fs2.default.statSync(filePath).size;
|
|
2001
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1612
2002
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
1613
2003
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1614
2004
|
purged++;
|
|
@@ -1617,27 +2007,27 @@ var DiskTier = class {
|
|
|
1617
2007
|
}
|
|
1618
2008
|
continue;
|
|
1619
2009
|
}
|
|
1620
|
-
const stat =
|
|
2010
|
+
const stat = import_fs2.default.statSync(filePath);
|
|
1621
2011
|
if (stat.size > this.opts.entryMaxBytes) {
|
|
1622
|
-
|
|
2012
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1623
2013
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1624
2014
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1625
2015
|
purged++;
|
|
1626
2016
|
continue;
|
|
1627
2017
|
}
|
|
1628
|
-
const raw =
|
|
2018
|
+
const raw = import_fs2.default.readFileSync(filePath);
|
|
1629
2019
|
let dec;
|
|
1630
2020
|
try {
|
|
1631
2021
|
dec = this.decrypt(raw);
|
|
1632
2022
|
} catch {
|
|
1633
|
-
|
|
2023
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1634
2024
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1635
2025
|
purged++;
|
|
1636
2026
|
continue;
|
|
1637
2027
|
}
|
|
1638
2028
|
const payload = (0, import_msgpackr2.unpack)(dec);
|
|
1639
2029
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
1640
|
-
|
|
2030
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1641
2031
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1642
2032
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1643
2033
|
purged++;
|
|
@@ -1645,7 +2035,7 @@ var DiskTier = class {
|
|
|
1645
2035
|
} catch {
|
|
1646
2036
|
} finally {
|
|
1647
2037
|
if (fd >= 0) try {
|
|
1648
|
-
|
|
2038
|
+
import_fs2.default.closeSync(fd);
|
|
1649
2039
|
} catch {
|
|
1650
2040
|
}
|
|
1651
2041
|
}
|
|
@@ -1659,19 +2049,43 @@ var DiskTier = class {
|
|
|
1659
2049
|
let cleared = 0;
|
|
1660
2050
|
for (const filePath of this.walkCacheFiles()) {
|
|
1661
2051
|
try {
|
|
1662
|
-
const stat =
|
|
1663
|
-
|
|
2052
|
+
const stat = import_fs2.default.statSync(filePath);
|
|
2053
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1664
2054
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1665
2055
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1666
2056
|
cleared++;
|
|
1667
2057
|
} catch {
|
|
1668
2058
|
}
|
|
1669
2059
|
}
|
|
2060
|
+
if (this._db) {
|
|
2061
|
+
this._db.exec("DELETE FROM meta");
|
|
2062
|
+
this.diskUsageBytes = 0;
|
|
2063
|
+
this.fileCount = 0;
|
|
2064
|
+
}
|
|
1670
2065
|
return cleared;
|
|
1671
2066
|
}
|
|
1672
2067
|
get stats() {
|
|
2068
|
+
if (this._db) {
|
|
2069
|
+
const row = this._stmtStats.get();
|
|
2070
|
+
this.fileCount = row.cnt;
|
|
2071
|
+
this.diskUsageBytes = row.bytes;
|
|
2072
|
+
}
|
|
1673
2073
|
return { files: this.fileCount, sizeKB: Math.round(this.diskUsageBytes / 1024), maxKB: Math.round(this.opts.maxBytes / 1024) };
|
|
1674
2074
|
}
|
|
2075
|
+
/** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
|
|
2076
|
+
get indexMode() {
|
|
2077
|
+
return this._db ? "sqlite" : "file-only";
|
|
2078
|
+
}
|
|
2079
|
+
/** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
|
|
2080
|
+
close() {
|
|
2081
|
+
if (this._db) {
|
|
2082
|
+
try {
|
|
2083
|
+
this._db.close();
|
|
2084
|
+
} catch {
|
|
2085
|
+
}
|
|
2086
|
+
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
|
|
2087
|
+
}
|
|
2088
|
+
}
|
|
1675
2089
|
};
|
|
1676
2090
|
|
|
1677
2091
|
// src/cache-service.ts
|
|
@@ -1729,6 +2143,89 @@ function deepFreeze(obj) {
|
|
|
1729
2143
|
for (const v of Object.values(obj)) deepFreeze(v);
|
|
1730
2144
|
return obj;
|
|
1731
2145
|
}
|
|
2146
|
+
var LatencyTracker = class {
|
|
2147
|
+
samples;
|
|
2148
|
+
maxKeys;
|
|
2149
|
+
bufs = /* @__PURE__ */ new Map();
|
|
2150
|
+
meta = /* @__PURE__ */ new Map();
|
|
2151
|
+
/** Shared sort buffer — safe to reuse because JS is single-threaded. */
|
|
2152
|
+
scratch;
|
|
2153
|
+
constructor(samples, maxKeys) {
|
|
2154
|
+
this.samples = samples;
|
|
2155
|
+
this.maxKeys = maxKeys;
|
|
2156
|
+
this.scratch = new Float64Array(samples);
|
|
2157
|
+
}
|
|
2158
|
+
record(key, deltaMs) {
|
|
2159
|
+
let buf = this.bufs.get(key);
|
|
2160
|
+
let m = this.meta.get(key);
|
|
2161
|
+
if (buf === void 0) {
|
|
2162
|
+
if (this.bufs.size >= this.maxKeys) {
|
|
2163
|
+
const oldest = this.bufs.keys().next().value;
|
|
2164
|
+
this.bufs.delete(oldest);
|
|
2165
|
+
this.meta.delete(oldest);
|
|
2166
|
+
}
|
|
2167
|
+
buf = new Float64Array(this.samples);
|
|
2168
|
+
m = { head: 0, count: 0, p95: 0, dirty: false };
|
|
2169
|
+
this.bufs.set(key, buf);
|
|
2170
|
+
this.meta.set(key, m);
|
|
2171
|
+
}
|
|
2172
|
+
buf[m.head] = deltaMs;
|
|
2173
|
+
m.head = (m.head + 1) % this.samples;
|
|
2174
|
+
if (m.count < this.samples) m.count++;
|
|
2175
|
+
m.dirty = true;
|
|
2176
|
+
}
|
|
2177
|
+
/**
|
|
2178
|
+
* Recomputes the p95 for the given key into `m.p95` and clears `m.dirty`.
|
|
2179
|
+
* Uses the shared scratch buffer — no heap allocation.
|
|
2180
|
+
*/
|
|
2181
|
+
_computeP95(buf, m) {
|
|
2182
|
+
const n = m.count;
|
|
2183
|
+
this.scratch.set(buf.subarray(0, n));
|
|
2184
|
+
const view = this.scratch.subarray(0, n);
|
|
2185
|
+
view.sort();
|
|
2186
|
+
m.p95 = view[Math.ceil(n * 0.95) - 1];
|
|
2187
|
+
m.dirty = false;
|
|
2188
|
+
}
|
|
2189
|
+
/**
|
|
2190
|
+
* Returns the p95 fetch latency for `key` in milliseconds, or `null` when
|
|
2191
|
+
* fewer than 5 samples have been collected (not enough data yet).
|
|
2192
|
+
* Uses a dirty-flag cache — sort only runs when a new sample was recorded.
|
|
2193
|
+
*/
|
|
2194
|
+
p95(key) {
|
|
2195
|
+
const buf = this.bufs.get(key);
|
|
2196
|
+
const m = this.meta.get(key);
|
|
2197
|
+
if (!buf || !m || m.count < 5) return null;
|
|
2198
|
+
if (m.dirty) this._computeP95(buf, m);
|
|
2199
|
+
return m.p95;
|
|
2200
|
+
}
|
|
2201
|
+
get trackedKeys() {
|
|
2202
|
+
return this.bufs.size;
|
|
2203
|
+
}
|
|
2204
|
+
/**
|
|
2205
|
+
* Top-20 slowest keys by p95, sorted descending.
|
|
2206
|
+
* Keys with < 5 samples are excluded (not enough data for a reliable p95).
|
|
2207
|
+
*
|
|
2208
|
+
* Only dirty keys (those with new samples since the last call) pay the sort
|
|
2209
|
+
* cost. Keys whose p95 is already cached are O(1) reads — so repeated
|
|
2210
|
+
* metrics() calls with no intervening fetches are essentially free.
|
|
2211
|
+
*/
|
|
2212
|
+
snapshot(prefixLen, multiplierSec, minMs, maxMs) {
|
|
2213
|
+
const out = [];
|
|
2214
|
+
for (const [key, buf] of this.bufs) {
|
|
2215
|
+
const m = this.meta.get(key);
|
|
2216
|
+
if (m.count < 5) continue;
|
|
2217
|
+
if (m.dirty) this._computeP95(buf, m);
|
|
2218
|
+
const p95 = m.p95;
|
|
2219
|
+
const adaptedMs = Math.max(minMs, Math.min(maxMs, Math.round(p95 * multiplierSec * 1e3)));
|
|
2220
|
+
out.push({
|
|
2221
|
+
key: prefixLen > 0 ? key.slice(prefixLen) : key,
|
|
2222
|
+
p95Ms: Math.round(p95),
|
|
2223
|
+
adaptedTtlSec: Math.round(adaptedMs / 1e3)
|
|
2224
|
+
});
|
|
2225
|
+
}
|
|
2226
|
+
return out.sort((a, b) => b.p95Ms - a.p95Ms).slice(0, 20);
|
|
2227
|
+
}
|
|
2228
|
+
};
|
|
1732
2229
|
function inferPriority(cacheKey) {
|
|
1733
2230
|
if (cacheKey.includes("auth:") || cacheKey.includes("session:")) return 4 /* CRITICAL */;
|
|
1734
2231
|
if (cacheKey.includes("user:") || cacheKey.includes("org:") || cacheKey.includes("profile:")) return 3 /* HIGH */;
|
|
@@ -1736,11 +2233,25 @@ function inferPriority(cacheKey) {
|
|
|
1736
2233
|
return 2 /* NORMAL */;
|
|
1737
2234
|
}
|
|
1738
2235
|
var GLOBAL_KEY = "__tricache_instance__";
|
|
2236
|
+
function detectServerlessRuntime() {
|
|
2237
|
+
if (process.env["AWS_LAMBDA_FUNCTION_NAME"]) return "AWS Lambda";
|
|
2238
|
+
if (process.env["K_SERVICE"]) return "Google Cloud Run";
|
|
2239
|
+
if (process.env["FUNCTION_TARGET"]) return "Google Cloud Functions";
|
|
2240
|
+
if (process.env["WEBSITE_INSTANCE_ID"]) return "Azure Functions";
|
|
2241
|
+
if (process.env["FLY_APP_NAME"]) return "Fly.io";
|
|
2242
|
+
if (process.env["RAILWAY_ENVIRONMENT"]) return "Railway";
|
|
2243
|
+
if (process.env["VERCEL"]) return "Vercel";
|
|
2244
|
+
return null;
|
|
2245
|
+
}
|
|
1739
2246
|
var CacheService = class _CacheService {
|
|
1740
2247
|
logger;
|
|
1741
2248
|
enc;
|
|
1742
2249
|
l1;
|
|
1743
2250
|
disk;
|
|
2251
|
+
/** When true, all disk-tier and snapshot operations are skipped. */
|
|
2252
|
+
_diskDisabled = false;
|
|
2253
|
+
/** Worker pool for off-main-thread AES-GCM (null when workerThreads is false or unavailable). */
|
|
2254
|
+
_workerPool = null;
|
|
1744
2255
|
opts;
|
|
1745
2256
|
/** Pre-computed once — opts.namespace never changes after construction. */
|
|
1746
2257
|
_namespace;
|
|
@@ -1766,9 +2277,12 @@ var CacheService = class _CacheService {
|
|
|
1766
2277
|
oomInterval = null;
|
|
1767
2278
|
metricsInterval = null;
|
|
1768
2279
|
_shutdownHandler = null;
|
|
2280
|
+
latencyTracker = null;
|
|
1769
2281
|
instanceId;
|
|
1770
2282
|
backplaneChannel;
|
|
1771
2283
|
subClient = null;
|
|
2284
|
+
/** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
|
|
2285
|
+
_subDisconnectedAt = null;
|
|
1772
2286
|
counters = {
|
|
1773
2287
|
gets: 0,
|
|
1774
2288
|
l1Hits: 0,
|
|
@@ -1810,7 +2324,7 @@ var CacheService = class _CacheService {
|
|
|
1810
2324
|
forbiddenSnapshotPrefixes: forbiddenPrefixes,
|
|
1811
2325
|
// Namespace-isolated defaults: separate dir / snapshot per namespace so
|
|
1812
2326
|
// two instances with different namespaces never share cache files.
|
|
1813
|
-
diskCacheDir: options.diskCacheDir ??
|
|
2327
|
+
diskCacheDir: options.diskCacheDir ?? import_path3.default.join(
|
|
1814
2328
|
import_os.default.tmpdir(),
|
|
1815
2329
|
ns ? `tricache-disk-${ns}` : "tricache-disk"
|
|
1816
2330
|
),
|
|
@@ -1821,7 +2335,7 @@ var CacheService = class _CacheService {
|
|
|
1821
2335
|
redisTls: options.redisTls ?? process.env.NODE_ENV === "production",
|
|
1822
2336
|
disableRedis: options.disableRedis ?? process.env.NODE_ENV !== "production",
|
|
1823
2337
|
encryptionKey: encKeyRaw,
|
|
1824
|
-
snapshotPath: options.snapshotPath ??
|
|
2338
|
+
snapshotPath: options.snapshotPath ?? import_path3.default.join(
|
|
1825
2339
|
import_os.default.tmpdir(),
|
|
1826
2340
|
ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
|
|
1827
2341
|
),
|
|
@@ -1836,17 +2350,50 @@ var CacheService = class _CacheService {
|
|
|
1836
2350
|
staleIfError: options.staleIfError ?? 0,
|
|
1837
2351
|
l2WriteMode: options.l2WriteMode ?? "read-write",
|
|
1838
2352
|
instanceName: options.instanceName ?? "",
|
|
2353
|
+
l1EvictionWatermark: Math.min(Math.max(options.l1EvictionWatermark ?? 0.9, 0), 1),
|
|
1839
2354
|
ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
|
|
1840
2355
|
tracer: options.tracer,
|
|
1841
2356
|
notFoundTtl: options.notFoundTtl ?? 0,
|
|
1842
2357
|
warmKeys: options.warmKeys,
|
|
1843
2358
|
onHit: options.onHit,
|
|
1844
2359
|
onMiss: options.onMiss,
|
|
1845
|
-
frozen: options.frozen ?? false
|
|
2360
|
+
frozen: options.frozen ?? false,
|
|
2361
|
+
adaptiveTtl: options.adaptiveTtl ?? false,
|
|
2362
|
+
adaptiveTtlMinMs: (options.adaptiveTtlMin ?? 10) * 1e3,
|
|
2363
|
+
adaptiveTtlMaxMs: (options.adaptiveTtlMax ?? 86400) * 1e3,
|
|
2364
|
+
adaptiveTtlMultiplier: options.adaptiveTtlMultiplier ?? 20,
|
|
2365
|
+
workerThreads: options.workerThreads ?? false,
|
|
2366
|
+
workerThresholdBytes: options.workerThresholdBytes ?? 131072,
|
|
2367
|
+
// 128 KB
|
|
2368
|
+
workerPoolSize: options.workerPoolSize ?? 0,
|
|
2369
|
+
// 0 = auto (min(4, cpus))
|
|
2370
|
+
backplaneMaxStalenessMs: options.backplaneMaxStalenessMs ?? 5e3,
|
|
2371
|
+
disableDisk: options.disableDisk ?? false,
|
|
2372
|
+
redisClusterNodes: options.redisClusterNodes,
|
|
2373
|
+
redisSentinel: options.redisSentinel
|
|
1846
2374
|
};
|
|
1847
2375
|
const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
|
|
1848
2376
|
const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
|
|
1849
2377
|
this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
|
|
2378
|
+
if (this.opts.adaptiveTtl) {
|
|
2379
|
+
const samples = options.adaptiveTtlSamples ?? 32;
|
|
2380
|
+
const maxKeys = options.adaptiveTtlMaxKeys ?? 5e3;
|
|
2381
|
+
this.latencyTracker = new LatencyTracker(samples, maxKeys);
|
|
2382
|
+
}
|
|
2383
|
+
let diskDisabled = this.opts.disableDisk;
|
|
2384
|
+
if (options.disableDisk === void 0) {
|
|
2385
|
+
const serverless = detectServerlessRuntime();
|
|
2386
|
+
if (serverless !== null) {
|
|
2387
|
+
diskDisabled = true;
|
|
2388
|
+
logger.warn("tricache: disk tier auto-disabled (ephemeral filesystem detected)", {
|
|
2389
|
+
runtime: serverless,
|
|
2390
|
+
hint: "Set disableDisk: false to override, or disableDisk: true to silence this warning"
|
|
2391
|
+
});
|
|
2392
|
+
}
|
|
2393
|
+
} else if (diskDisabled) {
|
|
2394
|
+
logger.info("tricache: disk tier explicitly disabled (disableDisk: true)");
|
|
2395
|
+
}
|
|
2396
|
+
this._diskDisabled = diskDisabled;
|
|
1850
2397
|
this.disk = new DiskTier({
|
|
1851
2398
|
dir: this.opts.diskCacheDir,
|
|
1852
2399
|
maxBytes: this.opts.diskMaxBytes,
|
|
@@ -1856,12 +2403,14 @@ var CacheService = class _CacheService {
|
|
|
1856
2403
|
logger
|
|
1857
2404
|
});
|
|
1858
2405
|
this._namespace = ns;
|
|
1859
|
-
this._redisDisabled = this.opts.disableRedis || !this.opts.redisHost;
|
|
2406
|
+
this._redisDisabled = this.opts.disableRedis || !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
|
|
1860
2407
|
this.l1 = new SmartMemoryCache({
|
|
1861
2408
|
maxBytes: this.opts.l1MaxBytes,
|
|
1862
2409
|
maxEntries: this.opts.l1MaxEntries,
|
|
1863
2410
|
categories: this.opts.categoryLimits,
|
|
2411
|
+
evictionWatermark: this.opts.l1EvictionWatermark,
|
|
1864
2412
|
diskSpill: (key, entry) => {
|
|
2413
|
+
if (this._diskDisabled) return;
|
|
1865
2414
|
setImmediate(() => {
|
|
1866
2415
|
void this.disk.save(key, entry);
|
|
1867
2416
|
});
|
|
@@ -1871,28 +2420,53 @@ var CacheService = class _CacheService {
|
|
|
1871
2420
|
});
|
|
1872
2421
|
if (!this.snapshotLoaded) {
|
|
1873
2422
|
this.snapshotLoaded = true;
|
|
1874
|
-
this.loadSnapshot();
|
|
2423
|
+
if (!this._diskDisabled) this.loadSnapshot();
|
|
1875
2424
|
}
|
|
1876
2425
|
this._shutdownHandler = () => {
|
|
1877
|
-
this.writeSnapshot();
|
|
2426
|
+
if (!this._diskDisabled) this.writeSnapshot();
|
|
1878
2427
|
process.exit(0);
|
|
1879
2428
|
};
|
|
1880
2429
|
process.once("SIGTERM", this._shutdownHandler);
|
|
1881
2430
|
process.once("SIGINT", this._shutdownHandler);
|
|
2431
|
+
if (this.opts.workerThreads && this.enc.isEnabled) {
|
|
2432
|
+
try {
|
|
2433
|
+
const encRef = this.enc;
|
|
2434
|
+
this._workerPool = new WorkerPool({
|
|
2435
|
+
keyBase64: encRef._key ? encRef._key.toString("base64") : "",
|
|
2436
|
+
mode: encRef._mode,
|
|
2437
|
+
prevKeyBase64: encRef._prevKey ? encRef._prevKey.toString("base64") : void 0,
|
|
2438
|
+
prevMode: encRef._prevMode,
|
|
2439
|
+
size: this.opts.workerPoolSize || void 0
|
|
2440
|
+
});
|
|
2441
|
+
if (this._workerPool.isAvailable) {
|
|
2442
|
+
logger.info("tricache: worker-thread encryption pool active", {
|
|
2443
|
+
threshold: `${this.opts.workerThresholdBytes / 1024} KB`
|
|
2444
|
+
});
|
|
2445
|
+
} else {
|
|
2446
|
+
this._workerPool = null;
|
|
2447
|
+
logger.warn("tricache: worker-thread pool requested but unavailable; using main-thread crypto");
|
|
2448
|
+
}
|
|
2449
|
+
} catch {
|
|
2450
|
+
this._workerPool = null;
|
|
2451
|
+
logger.warn("tricache: worker-thread pool init failed; using main-thread crypto");
|
|
2452
|
+
}
|
|
2453
|
+
}
|
|
1882
2454
|
this.cleanupInterval = setInterval(() => {
|
|
1883
2455
|
const cleaned = this.l1.cleanup();
|
|
1884
2456
|
if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
|
|
1885
2457
|
}, 5 * 60 * 1e3);
|
|
1886
2458
|
if (this.cleanupInterval.unref) this.cleanupInterval.unref();
|
|
1887
|
-
this.
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
2459
|
+
if (!this._diskDisabled) {
|
|
2460
|
+
this.diskJanitorInterval = setInterval(() => {
|
|
2461
|
+
const purged = this.disk.purgeNextBucket();
|
|
2462
|
+
if (purged > 0) this.logger.debug("Disk janitor tick", { purged });
|
|
2463
|
+
}, 3e4);
|
|
2464
|
+
if (this.diskJanitorInterval.unref) this.diskJanitorInterval.unref();
|
|
2465
|
+
}
|
|
1892
2466
|
if (this.opts.oomProtection) {
|
|
1893
2467
|
this.oomInterval = setInterval(() => {
|
|
1894
|
-
const
|
|
1895
|
-
const used =
|
|
2468
|
+
const heap = import_node_v8.default.getHeapStatistics();
|
|
2469
|
+
const used = heap.used_heap_size / heap.heap_size_limit;
|
|
1896
2470
|
if (used >= this.opts.oomHeapThreshold) {
|
|
1897
2471
|
const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
|
|
1898
2472
|
this.counters.oomEvictions++;
|
|
@@ -2000,18 +2574,60 @@ var CacheService = class _CacheService {
|
|
|
2000
2574
|
initBackplane() {
|
|
2001
2575
|
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
2002
2576
|
if (this.subClient) return;
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2577
|
+
let sub;
|
|
2578
|
+
if (this.opts.redisClusterNodes?.length) {
|
|
2579
|
+
sub = new import_ioredis.Cluster(this.opts.redisClusterNodes, {
|
|
2580
|
+
redisOptions: {
|
|
2581
|
+
tls: this.opts.redisTls ? {} : void 0,
|
|
2582
|
+
connectTimeout: 1e4,
|
|
2583
|
+
maxRetriesPerRequest: null
|
|
2584
|
+
}
|
|
2585
|
+
});
|
|
2586
|
+
} else if (this.opts.redisSentinel) {
|
|
2587
|
+
sub = new import_ioredis.Redis({
|
|
2588
|
+
sentinels: this.opts.redisSentinel.sentinels,
|
|
2589
|
+
name: this.opts.redisSentinel.name,
|
|
2590
|
+
tls: this.opts.redisTls ? {} : void 0,
|
|
2591
|
+
connectTimeout: 1e4,
|
|
2592
|
+
lazyConnect: true,
|
|
2593
|
+
maxRetriesPerRequest: null,
|
|
2594
|
+
enableAutoPipelining: false,
|
|
2595
|
+
retryStrategy: (times) => Math.min(times * 50, 2e3)
|
|
2596
|
+
});
|
|
2597
|
+
} else {
|
|
2598
|
+
sub = new import_ioredis.Redis({
|
|
2599
|
+
host: this.opts.redisHost,
|
|
2600
|
+
port: this.opts.redisPort,
|
|
2601
|
+
tls: this.opts.redisTls ? {} : void 0,
|
|
2602
|
+
connectTimeout: 1e4,
|
|
2603
|
+
lazyConnect: true,
|
|
2604
|
+
maxRetriesPerRequest: null,
|
|
2605
|
+
enableAutoPipelining: false,
|
|
2606
|
+
family: 4,
|
|
2607
|
+
retryStrategy: (times) => Math.min(times * 50, 2e3)
|
|
2608
|
+
});
|
|
2609
|
+
}
|
|
2014
2610
|
sub.on("error", (e) => this.logger.debug("Backplane subscriber error", { error: e.message }));
|
|
2611
|
+
sub.on("close", () => {
|
|
2612
|
+
if (this._subDisconnectedAt === null) {
|
|
2613
|
+
this._subDisconnectedAt = Date.now();
|
|
2614
|
+
this.logger.debug("Backplane: subscriber disconnected", { at: this._subDisconnectedAt });
|
|
2615
|
+
}
|
|
2616
|
+
});
|
|
2617
|
+
sub.on("ready", () => {
|
|
2618
|
+
if (this._subDisconnectedAt !== null && this.opts.backplaneMaxStalenessMs > 0) {
|
|
2619
|
+
const gapMs = Date.now() - this._subDisconnectedAt;
|
|
2620
|
+
if (gapMs > this.opts.backplaneMaxStalenessMs) {
|
|
2621
|
+
const evicted = this.l1.evictSetBefore(this._subDisconnectedAt);
|
|
2622
|
+
this.logger.warn("Backplane: reconnect after gap \u2014 flushed potentially stale L1 entries", {
|
|
2623
|
+
gapMs,
|
|
2624
|
+
evicted,
|
|
2625
|
+
hint: "Increase backplaneMaxStalenessMs or set to 0 to disable the fence"
|
|
2626
|
+
});
|
|
2627
|
+
}
|
|
2628
|
+
this._subDisconnectedAt = null;
|
|
2629
|
+
}
|
|
2630
|
+
});
|
|
2015
2631
|
sub.on("message", (_channel, message) => {
|
|
2016
2632
|
this._handleBackplaneMessage(message);
|
|
2017
2633
|
});
|
|
@@ -2034,7 +2650,9 @@ var CacheService = class _CacheService {
|
|
|
2034
2650
|
this.counters.invReceived++;
|
|
2035
2651
|
if (msg.op === "del") {
|
|
2036
2652
|
this.l1.delete(msg.key);
|
|
2037
|
-
setImmediate(() =>
|
|
2653
|
+
setImmediate(() => {
|
|
2654
|
+
if (!this._diskDisabled) this.disk.delete(msg.key);
|
|
2655
|
+
});
|
|
2038
2656
|
this._cascadeDependencies(msg.key);
|
|
2039
2657
|
} else if (msg.op === "del-glob") {
|
|
2040
2658
|
this.l1.deletePattern(msg.key);
|
|
@@ -2058,26 +2676,85 @@ var CacheService = class _CacheService {
|
|
|
2058
2676
|
} catch {
|
|
2059
2677
|
}
|
|
2060
2678
|
}
|
|
2679
|
+
/**
|
|
2680
|
+
* Scan all keys matching `pattern` across single-node or Cluster clients.
|
|
2681
|
+
* For Cluster, iterates every master node independently (SCAN is node-local).
|
|
2682
|
+
*/
|
|
2683
|
+
async _scanKeys(client, pattern) {
|
|
2684
|
+
const keys = [];
|
|
2685
|
+
if (client instanceof import_ioredis.Cluster) {
|
|
2686
|
+
const masters = client.nodes("master");
|
|
2687
|
+
await Promise.all(masters.map(
|
|
2688
|
+
(node) => new Promise((resolve, reject) => {
|
|
2689
|
+
const stream = node.scanStream({ match: pattern, count: 100 });
|
|
2690
|
+
stream.on("data", (chunk) => keys.push(...chunk));
|
|
2691
|
+
stream.on("end", resolve);
|
|
2692
|
+
stream.on("error", reject);
|
|
2693
|
+
})
|
|
2694
|
+
));
|
|
2695
|
+
} else {
|
|
2696
|
+
await new Promise((resolve, reject) => {
|
|
2697
|
+
const stream = client.scanStream({ match: pattern, count: 100 });
|
|
2698
|
+
stream.on("data", (chunk) => keys.push(...chunk));
|
|
2699
|
+
stream.on("end", resolve);
|
|
2700
|
+
stream.on("error", reject);
|
|
2701
|
+
});
|
|
2702
|
+
}
|
|
2703
|
+
return keys;
|
|
2704
|
+
}
|
|
2061
2705
|
async getRedis() {
|
|
2062
2706
|
if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
|
|
2063
2707
|
if (this.redisConnecting) return this.redisConnecting;
|
|
2064
2708
|
this.redisConnecting = (async () => {
|
|
2065
2709
|
try {
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2710
|
+
let client;
|
|
2711
|
+
if (this.opts.redisClusterNodes?.length) {
|
|
2712
|
+
client = new import_ioredis.Cluster(this.opts.redisClusterNodes, {
|
|
2713
|
+
redisOptions: {
|
|
2714
|
+
tls: this.opts.redisTls ? {} : void 0,
|
|
2715
|
+
connectTimeout: 1e4,
|
|
2716
|
+
maxRetriesPerRequest: 3,
|
|
2717
|
+
keepAlive: 3e4
|
|
2718
|
+
},
|
|
2719
|
+
enableAutoPipelining: true,
|
|
2720
|
+
retryDelayOnClusterDown: 200,
|
|
2721
|
+
retryDelayOnFailover: 1e3
|
|
2722
|
+
});
|
|
2723
|
+
client.on("connect", () => this.logger.info("Redis Cluster connected"));
|
|
2724
|
+
client.on("error", (e) => this.logger.error("Redis Cluster error", {}, e));
|
|
2725
|
+
client.on("reconnecting", () => this.logger.debug("Redis Cluster reconnecting"));
|
|
2726
|
+
} else if (this.opts.redisSentinel) {
|
|
2727
|
+
client = new import_ioredis.Redis({
|
|
2728
|
+
sentinels: this.opts.redisSentinel.sentinels,
|
|
2729
|
+
name: this.opts.redisSentinel.name,
|
|
2730
|
+
tls: this.opts.redisTls ? {} : void 0,
|
|
2731
|
+
connectTimeout: 1e4,
|
|
2732
|
+
lazyConnect: false,
|
|
2733
|
+
maxRetriesPerRequest: 3,
|
|
2734
|
+
enableAutoPipelining: true,
|
|
2735
|
+
keepAlive: 3e4,
|
|
2736
|
+
retryStrategy: (times) => Math.min(times * 50, 2e3)
|
|
2737
|
+
});
|
|
2738
|
+
client.on("connect", () => this.logger.info("Redis Sentinel connected", { name: this.opts.redisSentinel.name }));
|
|
2739
|
+
client.on("error", (e) => this.logger.error("Redis Sentinel error", { name: this.opts.redisSentinel.name }, e));
|
|
2740
|
+
client.on("reconnecting", () => this.logger.debug("Redis Sentinel reconnecting"));
|
|
2741
|
+
} else {
|
|
2742
|
+
client = new import_ioredis.Redis({
|
|
2743
|
+
host: this.opts.redisHost,
|
|
2744
|
+
port: this.opts.redisPort,
|
|
2745
|
+
tls: this.opts.redisTls ? {} : void 0,
|
|
2746
|
+
connectTimeout: 1e4,
|
|
2747
|
+
lazyConnect: false,
|
|
2748
|
+
maxRetriesPerRequest: 3,
|
|
2749
|
+
enableAutoPipelining: true,
|
|
2750
|
+
keepAlive: 3e4,
|
|
2751
|
+
family: 4,
|
|
2752
|
+
retryStrategy: (times) => Math.min(times * 50, 2e3)
|
|
2753
|
+
});
|
|
2754
|
+
client.on("connect", () => this.logger.info("Redis connected", { host: this.opts.redisHost }));
|
|
2755
|
+
client.on("error", (e) => this.logger.error("Redis error", { host: this.opts.redisHost }, e));
|
|
2756
|
+
client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
|
|
2757
|
+
}
|
|
2081
2758
|
await new Promise((resolve, reject) => {
|
|
2082
2759
|
client.once("ready", resolve);
|
|
2083
2760
|
client.once("error", reject);
|
|
@@ -2104,7 +2781,7 @@ var CacheService = class _CacheService {
|
|
|
2104
2781
|
const packed = (0, import_msgpackr3.pack)(payload);
|
|
2105
2782
|
const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
|
|
2106
2783
|
const dest = altPath ?? this.opts.snapshotPath;
|
|
2107
|
-
|
|
2784
|
+
import_fs3.default.writeFileSync(dest, final, { mode: 384 });
|
|
2108
2785
|
this.logger.info("Cache snapshot written", {
|
|
2109
2786
|
path: dest,
|
|
2110
2787
|
entries: entries.length,
|
|
@@ -2118,15 +2795,15 @@ var CacheService = class _CacheService {
|
|
|
2118
2795
|
loadSnapshot() {
|
|
2119
2796
|
const snapshotPath = this.opts.snapshotPath;
|
|
2120
2797
|
try {
|
|
2121
|
-
if (!
|
|
2122
|
-
const stat =
|
|
2798
|
+
if (!import_fs3.default.existsSync(snapshotPath)) return;
|
|
2799
|
+
const stat = import_fs3.default.statSync(snapshotPath);
|
|
2123
2800
|
if (stat.size > SNAPSHOT_MAX_FILE_BYTES) {
|
|
2124
2801
|
this.logger.warn("Snapshot rejected: exceeds size limit", { sizeBytes: stat.size });
|
|
2125
|
-
|
|
2802
|
+
import_fs3.default.unlinkSync(snapshotPath);
|
|
2126
2803
|
return;
|
|
2127
2804
|
}
|
|
2128
|
-
const raw =
|
|
2129
|
-
|
|
2805
|
+
const raw = import_fs3.default.readFileSync(snapshotPath);
|
|
2806
|
+
import_fs3.default.unlinkSync(snapshotPath);
|
|
2130
2807
|
let buf;
|
|
2131
2808
|
try {
|
|
2132
2809
|
buf = this.enc.decryptBuffer(raw);
|
|
@@ -2157,7 +2834,7 @@ var CacheService = class _CacheService {
|
|
|
2157
2834
|
} catch (err) {
|
|
2158
2835
|
this.logger.warn("Snapshot load failed \u2014 starting cold", { error: err.message });
|
|
2159
2836
|
try {
|
|
2160
|
-
|
|
2837
|
+
import_fs3.default.unlinkSync(snapshotPath);
|
|
2161
2838
|
} catch {
|
|
2162
2839
|
}
|
|
2163
2840
|
}
|
|
@@ -2187,12 +2864,18 @@ var CacheService = class _CacheService {
|
|
|
2187
2864
|
if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
2188
2865
|
const k = this.nk(cacheKey);
|
|
2189
2866
|
this.counters.gets++;
|
|
2867
|
+
const optSwr = opts.swr ?? 0;
|
|
2868
|
+
const optPriority = opts.priority;
|
|
2869
|
+
const optRefreshAhead = opts.refreshAhead;
|
|
2870
|
+
const optXfetchBeta = opts.xfetchBeta;
|
|
2871
|
+
const optNotFoundTtl = opts.notFoundTtl;
|
|
2872
|
+
const optTags = opts.tags;
|
|
2190
2873
|
const l1Hit = this.l1.get(k);
|
|
2191
2874
|
if (l1Hit !== null) {
|
|
2192
2875
|
if (l1Hit.isStale) {
|
|
2193
|
-
const swrGraceMs2 =
|
|
2876
|
+
const swrGraceMs2 = optSwr * 1e3;
|
|
2194
2877
|
if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
|
|
2195
|
-
const priority2 =
|
|
2878
|
+
const priority2 = optPriority ?? inferPriority(cacheKey);
|
|
2196
2879
|
this.revalidating.add(k);
|
|
2197
2880
|
void this._revalidate(k, fetchFn, ttlSeconds * 1e3, swrGraceMs2, priority2);
|
|
2198
2881
|
this.counters.swrRevalidations++;
|
|
@@ -2202,16 +2885,18 @@ var CacheService = class _CacheService {
|
|
|
2202
2885
|
}
|
|
2203
2886
|
} else {
|
|
2204
2887
|
this.logger.debug("L1 hit");
|
|
2205
|
-
|
|
2888
|
+
const ra = optRefreshAhead;
|
|
2889
|
+
const xb = optXfetchBeta;
|
|
2890
|
+
if (ra || xb) {
|
|
2206
2891
|
const now = l1Hit.fetchedAt ?? Date.now();
|
|
2207
2892
|
const remaining = l1Hit.expiresAt - now;
|
|
2208
2893
|
const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1e3;
|
|
2209
|
-
const shouldRefreshAhead =
|
|
2210
|
-
const shouldXFetch =
|
|
2894
|
+
const shouldRefreshAhead = ra ? remaining <= entryTtl * (1 - ra) : false;
|
|
2895
|
+
const shouldXFetch = xb && l1Hit.delta != null ? remaining <= l1Hit.delta * xb * -Math.log(Math.random()) : false;
|
|
2211
2896
|
if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
|
|
2212
|
-
const priority2 =
|
|
2897
|
+
const priority2 = optPriority ?? inferPriority(cacheKey);
|
|
2213
2898
|
this.revalidating.add(k);
|
|
2214
|
-
void this._revalidate(k, fetchFn, entryTtl,
|
|
2899
|
+
void this._revalidate(k, fetchFn, entryTtl, optSwr * 1e3, priority2);
|
|
2215
2900
|
this.counters.swrRevalidations++;
|
|
2216
2901
|
this.logger.debug(
|
|
2217
2902
|
shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
|
|
@@ -2227,15 +2912,20 @@ var CacheService = class _CacheService {
|
|
|
2227
2912
|
return l1Hit.value;
|
|
2228
2913
|
}
|
|
2229
2914
|
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
2230
|
-
const swrGraceMs =
|
|
2231
|
-
const priority =
|
|
2915
|
+
const swrGraceMs = optSwr * 1e3;
|
|
2916
|
+
const priority = optPriority ?? inferPriority(cacheKey);
|
|
2232
2917
|
if (!this._redisDisabled) {
|
|
2233
2918
|
try {
|
|
2234
2919
|
const client = await this.getRedis();
|
|
2235
2920
|
const raw = await client.get(k);
|
|
2236
2921
|
this.cb.onSuccess();
|
|
2237
2922
|
if (raw) {
|
|
2238
|
-
|
|
2923
|
+
let decrypted;
|
|
2924
|
+
if (this._workerPool && this.enc.isEnabled && raw.length > this.opts.workerThresholdBytes) {
|
|
2925
|
+
decrypted = await this._workerPool.decrypt(raw);
|
|
2926
|
+
} else {
|
|
2927
|
+
decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
|
|
2928
|
+
}
|
|
2239
2929
|
const parsed = JSON.parse(decrypted);
|
|
2240
2930
|
this.l1.set(k, parsed, ttlMs, priority);
|
|
2241
2931
|
this.counters.l2Hits++;
|
|
@@ -2249,20 +2939,22 @@ var CacheService = class _CacheService {
|
|
|
2249
2939
|
this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
|
|
2250
2940
|
}
|
|
2251
2941
|
}
|
|
2252
|
-
|
|
2253
|
-
|
|
2254
|
-
|
|
2255
|
-
|
|
2256
|
-
|
|
2257
|
-
|
|
2258
|
-
|
|
2259
|
-
|
|
2260
|
-
|
|
2261
|
-
|
|
2262
|
-
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
|
|
2942
|
+
if (!this._diskDisabled) {
|
|
2943
|
+
const diskHit = this.disk.load(k);
|
|
2944
|
+
if (diskHit !== null) {
|
|
2945
|
+
const promoted = this.l1.importEntries(
|
|
2946
|
+
[{ key: k, entry: diskHit }],
|
|
2947
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
2948
|
+
);
|
|
2949
|
+
if (promoted > 0) {
|
|
2950
|
+
const l1Check = this.l1.get(k);
|
|
2951
|
+
if (l1Check !== null) {
|
|
2952
|
+
this.counters.diskHits++;
|
|
2953
|
+
this.opts.onHit?.(cacheKey, "disk");
|
|
2954
|
+
this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
|
|
2955
|
+
span.setAttribute("cache.hit", "disk").end();
|
|
2956
|
+
return l1Check.value;
|
|
2957
|
+
}
|
|
2266
2958
|
}
|
|
2267
2959
|
}
|
|
2268
2960
|
}
|
|
@@ -2281,17 +2973,33 @@ var CacheService = class _CacheService {
|
|
|
2281
2973
|
const fetchStart = Date.now();
|
|
2282
2974
|
const data = await fetchFn();
|
|
2283
2975
|
const delta = Date.now() - fetchStart;
|
|
2284
|
-
const notFoundTtlMs = (
|
|
2285
|
-
|
|
2976
|
+
const notFoundTtlMs = (optNotFoundTtl ?? this.opts.notFoundTtl) * 1e3;
|
|
2977
|
+
let effectiveTtl = data == null && notFoundTtlMs > 0 ? notFoundTtlMs : ttlMs;
|
|
2978
|
+
if (this.latencyTracker && data != null) {
|
|
2979
|
+
this.latencyTracker.record(k, delta);
|
|
2980
|
+
const p95 = this.latencyTracker.p95(k);
|
|
2981
|
+
if (p95 !== null) {
|
|
2982
|
+
const adaptedMs = Math.round(p95 * this.opts.adaptiveTtlMultiplier * 1e3);
|
|
2983
|
+
effectiveTtl = Math.max(
|
|
2984
|
+
this.opts.adaptiveTtlMinMs,
|
|
2985
|
+
Math.min(this.opts.adaptiveTtlMaxMs, adaptedMs)
|
|
2986
|
+
);
|
|
2987
|
+
}
|
|
2988
|
+
}
|
|
2286
2989
|
const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
|
|
2287
2990
|
const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
|
|
2288
2991
|
this.l1.set(k, data, storeTtl, priority, staleAt, delta);
|
|
2289
|
-
if (
|
|
2992
|
+
if (optTags?.length) await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
|
|
2290
2993
|
if (!this._redisDisabled) {
|
|
2291
2994
|
try {
|
|
2292
2995
|
const client = await this.getRedis();
|
|
2293
2996
|
const serialized = JSON.stringify(data);
|
|
2294
|
-
|
|
2997
|
+
let toStore;
|
|
2998
|
+
if (this._workerPool && this.enc.isEnabled && serialized.length > this.opts.workerThresholdBytes) {
|
|
2999
|
+
toStore = await this._workerPool.encrypt(serialized);
|
|
3000
|
+
} else {
|
|
3001
|
+
toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
|
|
3002
|
+
}
|
|
2295
3003
|
await client.setex(k, Math.ceil(effectiveTtl / 1e3), toStore);
|
|
2296
3004
|
this.cb.onSuccess();
|
|
2297
3005
|
this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
|
|
@@ -2317,12 +3025,18 @@ var CacheService = class _CacheService {
|
|
|
2317
3025
|
const data = await fetchFn();
|
|
2318
3026
|
const delta = Date.now() - fetchStart;
|
|
2319
3027
|
const staleAt = Date.now() + ttlMs;
|
|
3028
|
+
if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
|
|
2320
3029
|
this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta);
|
|
2321
3030
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
2322
3031
|
try {
|
|
2323
3032
|
const client = await this.getRedis();
|
|
2324
3033
|
const s = JSON.stringify(data);
|
|
2325
|
-
|
|
3034
|
+
let stored;
|
|
3035
|
+
if (this._workerPool && this.enc.isEnabled && s.length > this.opts.workerThresholdBytes) {
|
|
3036
|
+
stored = await this._workerPool.encrypt(s);
|
|
3037
|
+
} else {
|
|
3038
|
+
stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
|
|
3039
|
+
}
|
|
2326
3040
|
await client.setex(cacheKey, Math.ceil(ttlMs / 1e3), stored);
|
|
2327
3041
|
} catch {
|
|
2328
3042
|
}
|
|
@@ -2369,7 +3083,12 @@ var CacheService = class _CacheService {
|
|
|
2369
3083
|
try {
|
|
2370
3084
|
const client = await this.getRedis();
|
|
2371
3085
|
const s = JSON.stringify(data);
|
|
2372
|
-
|
|
3086
|
+
let stored;
|
|
3087
|
+
if (this._workerPool && this.enc.isEnabled && s.length > this.opts.workerThresholdBytes) {
|
|
3088
|
+
stored = await this._workerPool.encrypt(s);
|
|
3089
|
+
} else {
|
|
3090
|
+
stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
|
|
3091
|
+
}
|
|
2373
3092
|
await client.setex(k, Math.ceil(ttlMs / 1e3), stored);
|
|
2374
3093
|
this.cb.onSuccess();
|
|
2375
3094
|
} catch (err) {
|
|
@@ -2427,7 +3146,9 @@ var CacheService = class _CacheService {
|
|
|
2427
3146
|
this.l1.deletePattern(k);
|
|
2428
3147
|
} else {
|
|
2429
3148
|
this.l1.delete(k);
|
|
2430
|
-
setImmediate(() =>
|
|
3149
|
+
setImmediate(() => {
|
|
3150
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
3151
|
+
});
|
|
2431
3152
|
this._cascadeDependencies(k);
|
|
2432
3153
|
for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
|
|
2433
3154
|
}
|
|
@@ -2435,13 +3156,7 @@ var CacheService = class _CacheService {
|
|
|
2435
3156
|
try {
|
|
2436
3157
|
const client = await this.getRedis();
|
|
2437
3158
|
if (isPattern) {
|
|
2438
|
-
const
|
|
2439
|
-
const keys = [];
|
|
2440
|
-
await new Promise((resolve, reject) => {
|
|
2441
|
-
stream.on("data", (chunk) => keys.push(...chunk));
|
|
2442
|
-
stream.on("end", resolve);
|
|
2443
|
-
stream.on("error", reject);
|
|
2444
|
-
});
|
|
3159
|
+
const keys = await this._scanKeys(client, k);
|
|
2445
3160
|
if (keys.length > 0) await client.del(...keys);
|
|
2446
3161
|
} else {
|
|
2447
3162
|
await client.del(k);
|
|
@@ -2498,7 +3213,7 @@ var CacheService = class _CacheService {
|
|
|
2498
3213
|
this.l1.deletePattern(k);
|
|
2499
3214
|
} else {
|
|
2500
3215
|
this.l1.clear();
|
|
2501
|
-
this.disk.clear();
|
|
3216
|
+
if (!this._diskDisabled) this.disk.clear();
|
|
2502
3217
|
this._l1Counters.clear();
|
|
2503
3218
|
this.tagIndex.clear();
|
|
2504
3219
|
}
|
|
@@ -2506,13 +3221,7 @@ var CacheService = class _CacheService {
|
|
|
2506
3221
|
try {
|
|
2507
3222
|
const client = await this.getRedis();
|
|
2508
3223
|
const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
|
|
2509
|
-
const
|
|
2510
|
-
const keys = [];
|
|
2511
|
-
await new Promise((resolve, reject) => {
|
|
2512
|
-
stream.on("data", (chunk) => keys.push(...chunk));
|
|
2513
|
-
stream.on("end", resolve);
|
|
2514
|
-
stream.on("error", reject);
|
|
2515
|
-
});
|
|
3224
|
+
const keys = await this._scanKeys(client, pattern);
|
|
2516
3225
|
if (keys.length > 0) await client.del(...keys);
|
|
2517
3226
|
} catch (err) {
|
|
2518
3227
|
this.logger.debug("clear: Redis unavailable", { error: err.message });
|
|
@@ -2740,13 +3449,7 @@ var CacheService = class _CacheService {
|
|
|
2740
3449
|
try {
|
|
2741
3450
|
const client = await this.getRedis();
|
|
2742
3451
|
const nsPattern = this.nk(pattern);
|
|
2743
|
-
const matchedKeys =
|
|
2744
|
-
const stream = client.scanStream({ match: nsPattern, count: 100 });
|
|
2745
|
-
await new Promise((resolve, reject) => {
|
|
2746
|
-
stream.on("data", (chunk) => matchedKeys.push(...chunk));
|
|
2747
|
-
stream.on("end", resolve);
|
|
2748
|
-
stream.on("error", reject);
|
|
2749
|
-
});
|
|
3452
|
+
const matchedKeys = await this._scanKeys(client, nsPattern);
|
|
2750
3453
|
if (matchedKeys.length === 0) {
|
|
2751
3454
|
this.cb.onSuccess();
|
|
2752
3455
|
return 0;
|
|
@@ -2796,7 +3499,7 @@ var CacheService = class _CacheService {
|
|
|
2796
3499
|
const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
|
|
2797
3500
|
for (const k of members) {
|
|
2798
3501
|
this.l1.delete(k);
|
|
2799
|
-
this.disk.delete(k);
|
|
3502
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
2800
3503
|
}
|
|
2801
3504
|
this.tagIndex.delete(tagKey);
|
|
2802
3505
|
if (!this._redisDisabled) {
|
|
@@ -3007,7 +3710,7 @@ var CacheService = class _CacheService {
|
|
|
3007
3710
|
for (const dep of dependents) {
|
|
3008
3711
|
if (dep === deletedKey) continue;
|
|
3009
3712
|
this.l1.delete(dep);
|
|
3010
|
-
this.disk.delete(dep);
|
|
3713
|
+
if (!this._diskDisabled) this.disk.delete(dep);
|
|
3011
3714
|
void this.publishInvalidation("del", dep);
|
|
3012
3715
|
this.logger.debug("Dependency cascade: invalidated dependent key", {
|
|
3013
3716
|
trigger: deletedKey.slice(0, 60),
|
|
@@ -3069,7 +3772,20 @@ var CacheService = class _CacheService {
|
|
|
3069
3772
|
sizeBytes: this.l1.memoryUsage,
|
|
3070
3773
|
maxBytes: this.opts.l1MaxBytes
|
|
3071
3774
|
},
|
|
3072
|
-
disk: this.disk.stats
|
|
3775
|
+
disk: { ...this.disk.stats, disabled: this._diskDisabled },
|
|
3776
|
+
...this.latencyTracker && {
|
|
3777
|
+
adaptiveTtl: {
|
|
3778
|
+
enabled: true,
|
|
3779
|
+
trackedKeys: this.latencyTracker.trackedKeys,
|
|
3780
|
+
slowestKeys: this.latencyTracker.snapshot(
|
|
3781
|
+
this._namespace ? this._namespace.length + 1 : 0,
|
|
3782
|
+
// strip "namespace:" prefix
|
|
3783
|
+
this.opts.adaptiveTtlMultiplier,
|
|
3784
|
+
this.opts.adaptiveTtlMinMs,
|
|
3785
|
+
this.opts.adaptiveTtlMaxMs
|
|
3786
|
+
)
|
|
3787
|
+
}
|
|
3788
|
+
}
|
|
3073
3789
|
};
|
|
3074
3790
|
}
|
|
3075
3791
|
/**
|
|
@@ -3146,6 +3862,10 @@ var CacheService = class _CacheService {
|
|
|
3146
3862
|
process.off("SIGINT", this._shutdownHandler);
|
|
3147
3863
|
this._shutdownHandler = null;
|
|
3148
3864
|
}
|
|
3865
|
+
if (this._workerPool) {
|
|
3866
|
+
await this._workerPool.destroy();
|
|
3867
|
+
this._workerPool = null;
|
|
3868
|
+
}
|
|
3149
3869
|
if (this.subClient) {
|
|
3150
3870
|
try {
|
|
3151
3871
|
await this.subClient.quit();
|
|
@@ -3160,6 +3880,7 @@ var CacheService = class _CacheService {
|
|
|
3160
3880
|
}
|
|
3161
3881
|
this.redis = null;
|
|
3162
3882
|
}
|
|
3883
|
+
if (!this._diskDisabled) this.disk.close();
|
|
3163
3884
|
}
|
|
3164
3885
|
};
|
|
3165
3886
|
// Annotate the CommonJS export names for ESM import in node:
|