tricache 0.7.1 → 0.9.0
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 +21 -21
- package/README.md +89 -1371
- package/dashboards/prometheus-scrape.yml +18 -0
- package/dashboards/tricache-alerts.yaml +54 -0
- package/dashboards/tricache-grafana.json +548 -0
- package/dist/cache-service-DVvroyqA.d.ts +886 -0
- package/dist/cache-service-KI5ACF3F.js +12 -0
- package/dist/chunk-7RV5ZVBB.js +1023 -0
- package/dist/chunk-BQRURGGD.js +60 -0
- package/dist/chunk-IITRFWHY.js +196 -0
- package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
- package/dist/{chunk-EUGYR7KR.js → chunk-PL5J3ZNT.js} +3184 -514
- package/dist/chunk-QNU7B43J.js +687 -0
- package/dist/chunk-UGD4VEPD.js +138 -0
- package/dist/chunk-XZL45ABR.js +108 -0
- package/dist/cli.cjs +3122 -495
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +121 -5
- package/dist/dashboard/index.cjs +1065 -0
- package/dist/dashboard/index.d.ts +183 -0
- package/dist/dashboard/index.js +22 -0
- package/dist/drizzle/index.cjs +2846 -494
- package/dist/drizzle/index.d.ts +3 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +1559 -0
- package/dist/edge/index.d.ts +127 -0
- package/dist/edge/index.js +1109 -0
- package/dist/hono/index.cjs +7760 -0
- package/dist/hono/index.d.ts +91 -0
- package/dist/hono/index.js +185 -0
- package/dist/hono-VA9A1m0I.d.ts +371 -0
- package/dist/http/index.cjs +3281 -587
- package/dist/http/index.d.ts +85 -23
- package/dist/http/index.js +176 -78
- package/dist/index.cjs +7212 -2505
- package/dist/index.d.ts +547 -30
- package/dist/index.js +104 -5
- package/dist/murmur3-CMGw9PbV.d.ts +98 -0
- package/dist/nestjs/index.cjs +2787 -487
- package/dist/nestjs/index.d.ts +3 -1
- package/dist/nestjs/index.js +6 -3
- package/dist/next/index.cjs +2804 -501
- package/dist/next/index.d.ts +4 -2
- package/dist/next/index.js +14 -10
- package/dist/prisma/index.d.ts +3 -1
- package/dist/serialize-worker.cjs +5 -4
- package/dist/serialize-worker.js +1 -1
- package/dist/{cache-service-D8tIXmzb.d.ts → types-B_QkVwJ7.d.ts} +622 -662
- package/dist/utils-CEsU_Z0s.d.ts +27 -0
- package/package.json +48 -10
- package/src/adapters/auto-pipeliner.ts +206 -0
- package/src/adapters/node-redis.ts +370 -0
- package/src/cache-service.ts +1619 -415
- package/src/cli.ts +137 -2
- package/src/codec.ts +72 -0
- package/src/cross-region.ts +245 -0
- package/src/dashboard/handler.ts +392 -0
- package/src/dashboard/html.ts +594 -0
- package/src/dashboard/index.ts +195 -0
- package/src/dashboard/types.ts +96 -0
- package/src/disk-tier.ts +449 -47
- package/src/drizzle/index.ts +86 -86
- package/src/edge/adapters/cloudflare-do.ts +130 -0
- package/src/edge/adapters/cloudflare-kv.ts +115 -0
- package/src/edge/adapters/upstash.ts +143 -0
- package/src/edge/cache.ts +797 -0
- package/src/edge/crypto.ts +182 -0
- package/src/edge/hono.ts +284 -0
- package/src/edge/index.ts +37 -0
- package/src/edge/types.ts +230 -0
- package/src/edge/utils/base64.ts +63 -0
- package/src/edge/utils/murmur3.ts +179 -0
- package/src/encryption.ts +127 -5
- package/src/hono/index.ts +316 -0
- package/src/http/express.ts +195 -0
- package/src/http/fastify.ts +260 -0
- package/src/http/index.ts +44 -258
- package/src/http/utils.ts +92 -0
- package/src/index.ts +149 -47
- package/src/ipc-telemetry.ts +509 -0
- package/src/latency-watchdog.ts +282 -0
- package/src/nestjs/decorators.ts +161 -161
- package/src/nestjs/index.ts +23 -23
- package/src/nestjs/tricache.module.ts +104 -104
- package/src/nestjs/tricache.store.ts +97 -97
- package/src/nestjs/types.ts +79 -79
- package/src/next/cache-handler.ts +12 -9
- package/src/next/index.ts +37 -37
- package/src/next/isr-handler.ts +105 -105
- package/src/next/types.ts +130 -130
- package/src/remote-snapshot.ts +153 -0
- package/src/serialize-worker.ts +120 -120
- package/src/sigv4-snapshot-adapter.ts +260 -0
- package/src/smart-memory-cache.ts +91 -8
- package/src/types.ts +315 -2
- package/src/utils/cgroup.ts +100 -0
- package/src/utils/tracing.ts +54 -0
- package/src/wasm/bloom-filter-wasm.ts +109 -102
- package/src/worker-pool.ts +299 -299
- package/src/wtiny-lfu.ts +624 -0
- package/dist/cache-service-5GATUYAK.js +0 -7
- package/dist/chunk-UBSR5UYA.js +0 -0
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
CacheEncryption,
|
|
3
|
+
EnvelopeEncryption,
|
|
3
4
|
PREFIX_COMPRESSED,
|
|
4
5
|
PREFIX_ENC_COMPRESSED,
|
|
5
6
|
compressBuffer,
|
|
@@ -7,13 +8,50 @@ import {
|
|
|
7
8
|
consoleLogger,
|
|
8
9
|
decompressBuffer,
|
|
9
10
|
decompressWithHeader
|
|
10
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-LJ5QJB5O.js";
|
|
12
|
+
import {
|
|
13
|
+
WasmBloomFilter
|
|
14
|
+
} from "./chunk-XZL45ABR.js";
|
|
11
15
|
|
|
12
16
|
// src/cache-service.ts
|
|
13
17
|
import { Redis as RedisClient, Cluster as RedisCluster } from "ioredis";
|
|
14
|
-
|
|
18
|
+
|
|
19
|
+
// src/codec.ts
|
|
20
|
+
import { Packr } from "msgpackr";
|
|
21
|
+
var CacheCodec = class {
|
|
22
|
+
packr;
|
|
23
|
+
constructor(options) {
|
|
24
|
+
const packrOptions = {
|
|
25
|
+
useToJSON: options?.useToJSON ?? true,
|
|
26
|
+
useRecords: options?.useRecords ?? true,
|
|
27
|
+
moreTypes: options?.moreTypes ?? true,
|
|
28
|
+
mapsAsObjects: options?.mapsAsObjects ?? true
|
|
29
|
+
};
|
|
30
|
+
this.packr = new Packr(packrOptions);
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Serializes a JavaScript value to a binary MessagePack Buffer.
|
|
34
|
+
*/
|
|
35
|
+
encode(data) {
|
|
36
|
+
const packed = this.packr.pack(data);
|
|
37
|
+
return Buffer.isBuffer(packed) ? packed : Buffer.from(packed.buffer, packed.byteOffset, packed.byteLength);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Deserializes a binary MessagePack Buffer or Uint8Array back to a JavaScript value.
|
|
41
|
+
*/
|
|
42
|
+
decode(data) {
|
|
43
|
+
return this.packr.unpack(data);
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
var defaultCodec = new CacheCodec({
|
|
47
|
+
useToJSON: true,
|
|
48
|
+
useRecords: true,
|
|
49
|
+
moreTypes: true
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
// src/cache-service.ts
|
|
15
53
|
import crypto2 from "crypto";
|
|
16
|
-
import
|
|
54
|
+
import os3 from "os";
|
|
17
55
|
|
|
18
56
|
// src/worker-pool.ts
|
|
19
57
|
import { Worker } from "worker_threads";
|
|
@@ -217,74 +255,444 @@ function availableCpus() {
|
|
|
217
255
|
}
|
|
218
256
|
|
|
219
257
|
// src/cache-service.ts
|
|
220
|
-
import
|
|
221
|
-
import
|
|
222
|
-
import
|
|
223
|
-
|
|
224
|
-
// src/smart-memory-cache.ts
|
|
225
|
-
import { pack, unpack } from "msgpackr";
|
|
258
|
+
import v82 from "v8";
|
|
259
|
+
import fs4 from "fs";
|
|
260
|
+
import path3 from "path";
|
|
226
261
|
|
|
227
|
-
// src/
|
|
228
|
-
var
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
writeKey(key) {
|
|
251
|
-
if (key.length === 0) return 0;
|
|
252
|
-
return this.encoder.encodeInto(key, this.stagingTarget).written;
|
|
262
|
+
// src/wtiny-lfu.ts
|
|
263
|
+
var TinyLfuSketch = class {
|
|
264
|
+
rows = 4;
|
|
265
|
+
width;
|
|
266
|
+
mask;
|
|
267
|
+
table;
|
|
268
|
+
insertions = 0;
|
|
269
|
+
decayThreshold;
|
|
270
|
+
constructor(width = 1024, decayThreshold) {
|
|
271
|
+
let w = 1;
|
|
272
|
+
while (w < width) w <<= 1;
|
|
273
|
+
this.width = w;
|
|
274
|
+
this.mask = w - 1;
|
|
275
|
+
this.table = new Uint16Array(this.rows * this.width);
|
|
276
|
+
this.decayThreshold = decayThreshold ?? width * 16;
|
|
277
|
+
}
|
|
278
|
+
hash(key) {
|
|
279
|
+
let h = 2166136261;
|
|
280
|
+
for (let i = 0; i < key.length; i++) {
|
|
281
|
+
h ^= key.charCodeAt(i);
|
|
282
|
+
h = Math.imul(h, 16777619) >>> 0;
|
|
283
|
+
}
|
|
284
|
+
return h;
|
|
253
285
|
}
|
|
254
|
-
|
|
255
|
-
const
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
286
|
+
increment(key) {
|
|
287
|
+
const h = this.hash(key);
|
|
288
|
+
const h1 = (h ^ h >>> 16) >>> 0;
|
|
289
|
+
const h2 = (Math.imul(h1, 73244475) ^ h1 >>> 16) >>> 0;
|
|
290
|
+
const h3 = (Math.imul(h2, 2142877601) ^ h2 >>> 16) >>> 0;
|
|
291
|
+
const h4 = (Math.imul(h3, 461845907) ^ h3 >>> 16) >>> 0;
|
|
292
|
+
const t = this.table;
|
|
293
|
+
const w = this.width;
|
|
294
|
+
const i0 = h1 & this.mask;
|
|
295
|
+
const i1 = w + (h2 & this.mask);
|
|
296
|
+
const i2 = 2 * w + (h3 & this.mask);
|
|
297
|
+
const i3 = 3 * w + (h4 & this.mask);
|
|
298
|
+
if (t[i0] < 65535) t[i0]++;
|
|
299
|
+
if (t[i1] < 65535) t[i1]++;
|
|
300
|
+
if (t[i2] < 65535) t[i2]++;
|
|
301
|
+
if (t[i3] < 65535) t[i3]++;
|
|
302
|
+
if (++this.insertions >= this.decayThreshold) {
|
|
303
|
+
this.decay();
|
|
304
|
+
}
|
|
259
305
|
}
|
|
260
|
-
|
|
261
|
-
const
|
|
262
|
-
|
|
263
|
-
|
|
306
|
+
estimate(key) {
|
|
307
|
+
const h = this.hash(key);
|
|
308
|
+
const h1 = (h ^ h >>> 16) >>> 0;
|
|
309
|
+
const h2 = (Math.imul(h1, 73244475) ^ h1 >>> 16) >>> 0;
|
|
310
|
+
const h3 = (Math.imul(h2, 2142877601) ^ h2 >>> 16) >>> 0;
|
|
311
|
+
const h4 = (Math.imul(h3, 461845907) ^ h3 >>> 16) >>> 0;
|
|
312
|
+
const t = this.table;
|
|
313
|
+
const w = this.width;
|
|
314
|
+
return Math.min(
|
|
315
|
+
t[h1 & this.mask],
|
|
316
|
+
t[w + (h2 & this.mask)],
|
|
317
|
+
t[2 * w + (h3 & this.mask)],
|
|
318
|
+
t[3 * w + (h4 & this.mask)]
|
|
319
|
+
);
|
|
264
320
|
}
|
|
265
|
-
|
|
266
|
-
this.
|
|
267
|
-
|
|
321
|
+
decay() {
|
|
322
|
+
for (let i = 0; i < this.table.length; i++) {
|
|
323
|
+
this.table[i] >>>= 1;
|
|
324
|
+
}
|
|
325
|
+
this.insertions = 0;
|
|
268
326
|
}
|
|
269
|
-
|
|
270
|
-
this.
|
|
271
|
-
|
|
327
|
+
clear() {
|
|
328
|
+
this.table.fill(0);
|
|
329
|
+
this.insertions = 0;
|
|
272
330
|
}
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
331
|
+
};
|
|
332
|
+
var WTinyLfuCache = class {
|
|
333
|
+
maxTotal;
|
|
334
|
+
maxWindow;
|
|
335
|
+
maxProtected;
|
|
336
|
+
maxProbation;
|
|
337
|
+
// Segments (Map preserves insertion order: oldest is first key, MRU is last key)
|
|
338
|
+
window = /* @__PURE__ */ new Map();
|
|
339
|
+
probation = /* @__PURE__ */ new Map();
|
|
340
|
+
protected_ = /* @__PURE__ */ new Map();
|
|
341
|
+
// TinyLFU Frequency Sketch
|
|
342
|
+
sketch;
|
|
343
|
+
// Telemetry metrics
|
|
344
|
+
hitCount = 0;
|
|
345
|
+
missCount = 0;
|
|
346
|
+
admissionCount = 0;
|
|
347
|
+
rejectionCount = 0;
|
|
348
|
+
promotionCount = 0;
|
|
349
|
+
demotionCount = 0;
|
|
350
|
+
constructor(options) {
|
|
351
|
+
this.maxTotal = Math.max(2, options.capacity);
|
|
352
|
+
const winPercent = options.windowPercent ?? 0.01;
|
|
353
|
+
this.maxWindow = Math.max(1, Math.floor(this.maxTotal * winPercent));
|
|
354
|
+
const mainCapacity = Math.max(1, this.maxTotal - this.maxWindow);
|
|
355
|
+
const protPercent = options.protectedPercent ?? 0.8;
|
|
356
|
+
this.maxProtected = Math.max(1, Math.floor(mainCapacity * protPercent));
|
|
357
|
+
this.maxProbation = Math.max(1, mainCapacity - this.maxProtected);
|
|
358
|
+
this.sketch = new TinyLfuSketch(options.sketchWidth ?? 1024);
|
|
359
|
+
}
|
|
360
|
+
get capacity() {
|
|
361
|
+
return this.maxTotal;
|
|
276
362
|
}
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
363
|
+
get size() {
|
|
364
|
+
return this.window.size + this.probation.size + this.protected_.size;
|
|
365
|
+
}
|
|
366
|
+
keyToString(key) {
|
|
367
|
+
return typeof key === "string" ? key : String(key);
|
|
280
368
|
}
|
|
281
369
|
/**
|
|
282
|
-
*
|
|
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
|
|
370
|
+
* Retrieves an entry and performs W-TinyLFU access promotion.
|
|
285
371
|
*/
|
|
286
|
-
get
|
|
287
|
-
|
|
372
|
+
get(key) {
|
|
373
|
+
const keyStr = this.keyToString(key);
|
|
374
|
+
this.sketch.increment(keyStr);
|
|
375
|
+
if (this.window.has(key)) {
|
|
376
|
+
const val = this.window.get(key);
|
|
377
|
+
this.window.delete(key);
|
|
378
|
+
this.window.set(key, val);
|
|
379
|
+
this.hitCount++;
|
|
380
|
+
return val;
|
|
381
|
+
}
|
|
382
|
+
if (this.protected_.has(key)) {
|
|
383
|
+
const val = this.protected_.get(key);
|
|
384
|
+
this.protected_.delete(key);
|
|
385
|
+
this.protected_.set(key, val);
|
|
386
|
+
this.hitCount++;
|
|
387
|
+
return val;
|
|
388
|
+
}
|
|
389
|
+
if (this.probation.has(key)) {
|
|
390
|
+
const val = this.probation.get(key);
|
|
391
|
+
this.probation.delete(key);
|
|
392
|
+
this.promotionCount++;
|
|
393
|
+
this.protected_.set(key, val);
|
|
394
|
+
if (this.protected_.size > this.maxProtected) {
|
|
395
|
+
const oldestProtKey = this.protected_.keys().next().value;
|
|
396
|
+
const oldestProtVal = this.protected_.get(oldestProtKey);
|
|
397
|
+
this.protected_.delete(oldestProtKey);
|
|
398
|
+
this.probation.set(oldestProtKey, oldestProtVal);
|
|
399
|
+
this.demotionCount++;
|
|
400
|
+
}
|
|
401
|
+
this.hitCount++;
|
|
402
|
+
return val;
|
|
403
|
+
}
|
|
404
|
+
this.missCount++;
|
|
405
|
+
return void 0;
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Returns true if key exists in any segment without updating access frequency.
|
|
409
|
+
*/
|
|
410
|
+
has(key) {
|
|
411
|
+
return this.window.has(key) || this.probation.has(key) || this.protected_.has(key);
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Puts an entry into the cache using W-TinyLFU admission policies.
|
|
415
|
+
*/
|
|
416
|
+
set(key, value) {
|
|
417
|
+
const keyStr = this.keyToString(key);
|
|
418
|
+
this.sketch.increment(keyStr);
|
|
419
|
+
const result = {};
|
|
420
|
+
if (this.window.has(key)) {
|
|
421
|
+
this.window.delete(key);
|
|
422
|
+
this.window.set(key, value);
|
|
423
|
+
return result;
|
|
424
|
+
}
|
|
425
|
+
if (this.protected_.has(key)) {
|
|
426
|
+
this.protected_.delete(key);
|
|
427
|
+
this.protected_.set(key, value);
|
|
428
|
+
return result;
|
|
429
|
+
}
|
|
430
|
+
if (this.probation.has(key)) {
|
|
431
|
+
this.probation.delete(key);
|
|
432
|
+
this.probation.set(key, value);
|
|
433
|
+
return result;
|
|
434
|
+
}
|
|
435
|
+
this.window.set(key, value);
|
|
436
|
+
if (this.window.size <= this.maxWindow) {
|
|
437
|
+
this.admissionCount++;
|
|
438
|
+
return result;
|
|
439
|
+
}
|
|
440
|
+
const candKey = this.window.keys().next().value;
|
|
441
|
+
const candVal = this.window.get(candKey);
|
|
442
|
+
this.window.delete(candKey);
|
|
443
|
+
if (this.probation.size + this.protected_.size < this.maxProbation + this.maxProtected) {
|
|
444
|
+
this.probation.set(candKey, candVal);
|
|
445
|
+
this.admissionCount++;
|
|
446
|
+
return result;
|
|
447
|
+
}
|
|
448
|
+
let victimKey;
|
|
449
|
+
let victimVal;
|
|
450
|
+
let victimSegment;
|
|
451
|
+
if (this.probation.size > 0) {
|
|
452
|
+
victimKey = this.probation.keys().next().value;
|
|
453
|
+
victimVal = this.probation.get(victimKey);
|
|
454
|
+
victimSegment = "probation";
|
|
455
|
+
} else {
|
|
456
|
+
victimKey = this.protected_.keys().next().value;
|
|
457
|
+
victimVal = this.protected_.get(victimKey);
|
|
458
|
+
victimSegment = "protected";
|
|
459
|
+
}
|
|
460
|
+
const candFreq = this.sketch.estimate(this.keyToString(candKey));
|
|
461
|
+
const victimFreq = this.sketch.estimate(this.keyToString(victimKey));
|
|
462
|
+
if (candFreq > victimFreq) {
|
|
463
|
+
if (victimSegment === "probation") {
|
|
464
|
+
this.probation.delete(victimKey);
|
|
465
|
+
} else {
|
|
466
|
+
this.protected_.delete(victimKey);
|
|
467
|
+
}
|
|
468
|
+
this.probation.set(candKey, candVal);
|
|
469
|
+
this.admissionCount++;
|
|
470
|
+
result.evicted = { key: victimKey, value: victimVal, segment: victimSegment };
|
|
471
|
+
} else {
|
|
472
|
+
this.rejectionCount++;
|
|
473
|
+
result.rejected = { key: candKey, value: candVal, segment: "window" };
|
|
474
|
+
}
|
|
475
|
+
return result;
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* Removes a key from whichever segment it resides in.
|
|
479
|
+
*/
|
|
480
|
+
delete(key) {
|
|
481
|
+
return this.window.delete(key) || this.probation.delete(key) || this.protected_.delete(key);
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Resets all segments, sketch, and metrics.
|
|
485
|
+
*/
|
|
486
|
+
clear() {
|
|
487
|
+
this.window.clear();
|
|
488
|
+
this.probation.clear();
|
|
489
|
+
this.protected_.clear();
|
|
490
|
+
this.sketch.clear();
|
|
491
|
+
this.hitCount = 0;
|
|
492
|
+
this.missCount = 0;
|
|
493
|
+
this.admissionCount = 0;
|
|
494
|
+
this.rejectionCount = 0;
|
|
495
|
+
this.promotionCount = 0;
|
|
496
|
+
this.demotionCount = 0;
|
|
497
|
+
}
|
|
498
|
+
/**
|
|
499
|
+
* Returns current telemetry and hit-ratio stats.
|
|
500
|
+
*/
|
|
501
|
+
stats() {
|
|
502
|
+
const totalRequests = this.hitCount + this.missCount;
|
|
503
|
+
return {
|
|
504
|
+
capacity: this.maxTotal,
|
|
505
|
+
size: this.size,
|
|
506
|
+
windowSize: this.window.size,
|
|
507
|
+
probationSize: this.probation.size,
|
|
508
|
+
protectedSize: this.protected_.size,
|
|
509
|
+
hits: this.hitCount,
|
|
510
|
+
misses: this.missCount,
|
|
511
|
+
hitRate: totalRequests > 0 ? this.hitCount / totalRequests : 0,
|
|
512
|
+
admissions: this.admissionCount,
|
|
513
|
+
rejections: this.rejectionCount,
|
|
514
|
+
promotions: this.promotionCount,
|
|
515
|
+
demotions: this.demotionCount
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
getStats() {
|
|
519
|
+
return this.stats();
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* Returns an iterator of all keys currently in the cache.
|
|
523
|
+
*/
|
|
524
|
+
*keys() {
|
|
525
|
+
yield* this.window.keys();
|
|
526
|
+
yield* this.probation.keys();
|
|
527
|
+
yield* this.protected_.keys();
|
|
528
|
+
}
|
|
529
|
+
/**
|
|
530
|
+
* Returns an iterator of all entries currently in the cache.
|
|
531
|
+
*/
|
|
532
|
+
*entries() {
|
|
533
|
+
yield* this.window.entries();
|
|
534
|
+
yield* this.probation.entries();
|
|
535
|
+
yield* this.protected_.entries();
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* Returns segment membership for a key ('window', 'probation', 'protected', or null).
|
|
539
|
+
*/
|
|
540
|
+
getSegment(key) {
|
|
541
|
+
if (this.window.has(key)) return "window";
|
|
542
|
+
if (this.probation.has(key)) return "probation";
|
|
543
|
+
if (this.protected_.has(key)) return "protected";
|
|
544
|
+
return null;
|
|
545
|
+
}
|
|
546
|
+
};
|
|
547
|
+
var WTinyLfuPolicy = class {
|
|
548
|
+
constructor(capacity, sketch, windowPercent = 0.01, protectedPercent = 0.8) {
|
|
549
|
+
this.sketch = sketch;
|
|
550
|
+
this.maxTotal = Math.max(2, capacity);
|
|
551
|
+
this.maxWindow = Math.max(1, Math.floor(this.maxTotal * windowPercent));
|
|
552
|
+
const mainCapacity = Math.max(1, this.maxTotal - this.maxWindow);
|
|
553
|
+
this.maxProtected = Math.max(1, Math.floor(mainCapacity * protectedPercent));
|
|
554
|
+
this.maxProbation = Math.max(1, mainCapacity - this.maxProtected);
|
|
555
|
+
}
|
|
556
|
+
sketch;
|
|
557
|
+
maxTotal;
|
|
558
|
+
maxWindow;
|
|
559
|
+
maxProtected;
|
|
560
|
+
maxProbation;
|
|
561
|
+
window = /* @__PURE__ */ new Set();
|
|
562
|
+
probation = /* @__PURE__ */ new Set();
|
|
563
|
+
protected_ = /* @__PURE__ */ new Set();
|
|
564
|
+
// Telemetry metrics
|
|
565
|
+
hitCount = 0;
|
|
566
|
+
missCount = 0;
|
|
567
|
+
admissionCount = 0;
|
|
568
|
+
rejectionCount = 0;
|
|
569
|
+
promotionCount = 0;
|
|
570
|
+
demotionCount = 0;
|
|
571
|
+
get windowSize() {
|
|
572
|
+
return this.window.size;
|
|
573
|
+
}
|
|
574
|
+
get probationSize() {
|
|
575
|
+
return this.probation.size;
|
|
576
|
+
}
|
|
577
|
+
get protectedSize() {
|
|
578
|
+
return this.protected_.size;
|
|
579
|
+
}
|
|
580
|
+
onAccess(key) {
|
|
581
|
+
if (this.window.has(key)) {
|
|
582
|
+
this.window.delete(key);
|
|
583
|
+
this.window.add(key);
|
|
584
|
+
this.hitCount++;
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
if (this.protected_.has(key)) {
|
|
588
|
+
this.protected_.delete(key);
|
|
589
|
+
this.protected_.add(key);
|
|
590
|
+
this.hitCount++;
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
if (this.probation.has(key)) {
|
|
594
|
+
this.probation.delete(key);
|
|
595
|
+
this.protected_.add(key);
|
|
596
|
+
this.promotionCount++;
|
|
597
|
+
this.hitCount++;
|
|
598
|
+
if (this.protected_.size > this.maxProtected) {
|
|
599
|
+
const oldestProtKey = this.protected_.values().next().value;
|
|
600
|
+
this.protected_.delete(oldestProtKey);
|
|
601
|
+
this.probation.add(oldestProtKey);
|
|
602
|
+
this.demotionCount++;
|
|
603
|
+
}
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
606
|
+
this.missCount++;
|
|
607
|
+
}
|
|
608
|
+
onSet(key, isUpdate) {
|
|
609
|
+
if (isUpdate) {
|
|
610
|
+
if (this.window.has(key)) {
|
|
611
|
+
this.window.delete(key);
|
|
612
|
+
this.window.add(key);
|
|
613
|
+
} else if (this.protected_.has(key)) {
|
|
614
|
+
this.protected_.delete(key);
|
|
615
|
+
this.protected_.add(key);
|
|
616
|
+
} else if (this.probation.has(key)) {
|
|
617
|
+
this.probation.delete(key);
|
|
618
|
+
this.probation.add(key);
|
|
619
|
+
}
|
|
620
|
+
return { admit: true };
|
|
621
|
+
}
|
|
622
|
+
this.window.add(key);
|
|
623
|
+
if (this.window.size <= this.maxWindow) {
|
|
624
|
+
this.admissionCount++;
|
|
625
|
+
return { admit: true };
|
|
626
|
+
}
|
|
627
|
+
const candKey = this.window.values().next().value;
|
|
628
|
+
this.window.delete(candKey);
|
|
629
|
+
if (this.probation.size + this.protected_.size < this.maxProbation + this.maxProtected) {
|
|
630
|
+
this.probation.add(candKey);
|
|
631
|
+
this.admissionCount++;
|
|
632
|
+
return { admit: true };
|
|
633
|
+
}
|
|
634
|
+
let victimKey;
|
|
635
|
+
let victimIsProbation = true;
|
|
636
|
+
if (this.probation.size > 0) {
|
|
637
|
+
victimKey = this.probation.values().next().value;
|
|
638
|
+
} else {
|
|
639
|
+
victimKey = this.protected_.values().next().value;
|
|
640
|
+
victimIsProbation = false;
|
|
641
|
+
}
|
|
642
|
+
const candFreq = this.sketch.estimate(candKey);
|
|
643
|
+
const victimFreq = this.sketch.estimate(victimKey);
|
|
644
|
+
if (candFreq > victimFreq) {
|
|
645
|
+
if (victimIsProbation) {
|
|
646
|
+
this.probation.delete(victimKey);
|
|
647
|
+
} else {
|
|
648
|
+
this.protected_.delete(victimKey);
|
|
649
|
+
}
|
|
650
|
+
this.probation.add(candKey);
|
|
651
|
+
this.admissionCount++;
|
|
652
|
+
return { admit: true, evictKey: victimKey, candidateKey: candKey };
|
|
653
|
+
} else {
|
|
654
|
+
this.rejectionCount++;
|
|
655
|
+
return { admit: false, candidateKey: candKey };
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
onDelete(key) {
|
|
659
|
+
this.window.delete(key);
|
|
660
|
+
this.probation.delete(key);
|
|
661
|
+
this.protected_.delete(key);
|
|
662
|
+
}
|
|
663
|
+
clear() {
|
|
664
|
+
this.window.clear();
|
|
665
|
+
this.probation.clear();
|
|
666
|
+
this.protected_.clear();
|
|
667
|
+
this.hitCount = 0;
|
|
668
|
+
this.missCount = 0;
|
|
669
|
+
this.admissionCount = 0;
|
|
670
|
+
this.rejectionCount = 0;
|
|
671
|
+
this.promotionCount = 0;
|
|
672
|
+
this.demotionCount = 0;
|
|
673
|
+
}
|
|
674
|
+
getStats() {
|
|
675
|
+
const totalRequests = this.hitCount + this.missCount;
|
|
676
|
+
return {
|
|
677
|
+
capacity: this.maxTotal,
|
|
678
|
+
size: this.window.size + this.probation.size + this.protected_.size,
|
|
679
|
+
windowSize: this.window.size,
|
|
680
|
+
probationSize: this.probation.size,
|
|
681
|
+
protectedSize: this.protected_.size,
|
|
682
|
+
hits: this.hitCount,
|
|
683
|
+
misses: this.missCount,
|
|
684
|
+
hitRate: totalRequests > 0 ? this.hitCount / totalRequests : 0,
|
|
685
|
+
admissions: this.admissionCount,
|
|
686
|
+
rejections: this.rejectionCount,
|
|
687
|
+
promotions: this.promotionCount,
|
|
688
|
+
demotions: this.demotionCount
|
|
689
|
+
};
|
|
690
|
+
}
|
|
691
|
+
getSegment(key) {
|
|
692
|
+
if (this.window.has(key)) return "window";
|
|
693
|
+
if (this.probation.has(key)) return "probation";
|
|
694
|
+
if (this.protected_.has(key)) return "protected";
|
|
695
|
+
return null;
|
|
288
696
|
}
|
|
289
697
|
};
|
|
290
698
|
|
|
@@ -463,11 +871,13 @@ function globMatchParts(parts, first, last, key) {
|
|
|
463
871
|
var SmartMemoryCache = class {
|
|
464
872
|
cache = /* @__PURE__ */ new Map();
|
|
465
873
|
opts;
|
|
874
|
+
codec;
|
|
466
875
|
bloom;
|
|
467
876
|
/** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
|
|
468
877
|
categoryPrefixes;
|
|
469
878
|
/** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
|
|
470
879
|
sketch = new CountMinSketch();
|
|
880
|
+
wtinyPolicy;
|
|
471
881
|
totalSize = 0;
|
|
472
882
|
categoryCount = /* @__PURE__ */ new Map();
|
|
473
883
|
categorySize = /* @__PURE__ */ new Map();
|
|
@@ -491,8 +901,12 @@ var SmartMemoryCache = class {
|
|
|
491
901
|
_evictGPool = Array.from({ length: EVICTION_SAMPLE }, () => ({ key: "", score: 0 }));
|
|
492
902
|
constructor(opts, existing) {
|
|
493
903
|
this.opts = opts;
|
|
904
|
+
this.codec = opts.codec ?? defaultCodec;
|
|
494
905
|
this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
|
|
495
906
|
this.categoryPrefixes = Object.keys(opts.categories).filter((k) => k !== "default");
|
|
907
|
+
if (opts.admissionPolicy === "wtinylfu") {
|
|
908
|
+
this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch);
|
|
909
|
+
}
|
|
496
910
|
if (existing) {
|
|
497
911
|
for (const [k, v] of existing) this.cache.set(k, v);
|
|
498
912
|
this.recalculateStats();
|
|
@@ -505,6 +919,12 @@ var SmartMemoryCache = class {
|
|
|
505
919
|
this.categoryCount.clear();
|
|
506
920
|
this.categorySize.clear();
|
|
507
921
|
this.categoryKeys.clear();
|
|
922
|
+
if (this.wtinyPolicy) {
|
|
923
|
+
this.wtinyPolicy.clear();
|
|
924
|
+
for (const key of this.cache.keys()) {
|
|
925
|
+
this.wtinyPolicy.onSet(key, false);
|
|
926
|
+
}
|
|
927
|
+
}
|
|
508
928
|
for (const [key, entry] of this.cache) {
|
|
509
929
|
this.totalSize += entry.size;
|
|
510
930
|
const cat = this.getCategory(key);
|
|
@@ -530,6 +950,7 @@ var SmartMemoryCache = class {
|
|
|
530
950
|
_delete(key, reason = "manual") {
|
|
531
951
|
const entry = this.cache.get(key);
|
|
532
952
|
if (!entry) return false;
|
|
953
|
+
this.wtinyPolicy?.onDelete(key);
|
|
533
954
|
const cat = this.getCategory(key);
|
|
534
955
|
this.totalSize -= entry.size;
|
|
535
956
|
this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
|
|
@@ -690,7 +1111,8 @@ var SmartMemoryCache = class {
|
|
|
690
1111
|
entry.hits++;
|
|
691
1112
|
entry.lastAccess = now;
|
|
692
1113
|
if ((entry.hits & 3) === 0) this.sketch.increment(key);
|
|
693
|
-
|
|
1114
|
+
this.wtinyPolicy?.onAccess(key);
|
|
1115
|
+
const value = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
694
1116
|
const hit = {
|
|
695
1117
|
value,
|
|
696
1118
|
isStale: entry.staleAt !== void 0 && now > entry.staleAt,
|
|
@@ -704,7 +1126,7 @@ var SmartMemoryCache = class {
|
|
|
704
1126
|
return hit;
|
|
705
1127
|
}
|
|
706
1128
|
set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
|
|
707
|
-
const packed =
|
|
1129
|
+
const packed = this.codec.encode(data);
|
|
708
1130
|
const size = packed.byteLength;
|
|
709
1131
|
this.compressions++;
|
|
710
1132
|
this.sketch.increment(key);
|
|
@@ -721,7 +1143,51 @@ var SmartMemoryCache = class {
|
|
|
721
1143
|
this.categorySize.set(cat, (this.categorySize.get(cat) ?? existingEntry.size) - existingEntry.size);
|
|
722
1144
|
this.cache.delete(key);
|
|
723
1145
|
}
|
|
724
|
-
this.
|
|
1146
|
+
if (this.wtinyPolicy) {
|
|
1147
|
+
const decision = this.wtinyPolicy.onSet(key, Boolean(existingEntry));
|
|
1148
|
+
if (!decision.admit) {
|
|
1149
|
+
if (decision.candidateKey === key) {
|
|
1150
|
+
if (this.opts.diskSpill) {
|
|
1151
|
+
const now2 = Date.now();
|
|
1152
|
+
const liveValue2 = size <= LARGE_VALUE_BYTES ? data : void 0;
|
|
1153
|
+
this.opts.diskSpill(key, {
|
|
1154
|
+
data: packed,
|
|
1155
|
+
value: liveValue2,
|
|
1156
|
+
isCompressed: true,
|
|
1157
|
+
expiresAt: now2 + ttlMs,
|
|
1158
|
+
staleAt,
|
|
1159
|
+
size,
|
|
1160
|
+
hits: 1,
|
|
1161
|
+
lastAccess: now2,
|
|
1162
|
+
priority,
|
|
1163
|
+
ttlMs,
|
|
1164
|
+
delta,
|
|
1165
|
+
setAt: now2,
|
|
1166
|
+
tagVersions
|
|
1167
|
+
});
|
|
1168
|
+
}
|
|
1169
|
+
return;
|
|
1170
|
+
} else if (decision.candidateKey) {
|
|
1171
|
+
const candEntry = this.cache.get(decision.candidateKey);
|
|
1172
|
+
if (candEntry && this.opts.diskSpill) {
|
|
1173
|
+
this.opts.diskSpill(decision.candidateKey, candEntry);
|
|
1174
|
+
}
|
|
1175
|
+
this._delete(decision.candidateKey, "capacity");
|
|
1176
|
+
}
|
|
1177
|
+
} else if (decision.evictKey) {
|
|
1178
|
+
const victimEntry = this.cache.get(decision.evictKey);
|
|
1179
|
+
if (victimEntry && this.opts.diskSpill) {
|
|
1180
|
+
this.opts.diskSpill(decision.evictKey, victimEntry);
|
|
1181
|
+
}
|
|
1182
|
+
this._delete(decision.evictKey, "capacity");
|
|
1183
|
+
}
|
|
1184
|
+
const catSz = this.categorySize.get(cat) ?? 0;
|
|
1185
|
+
if (catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
|
|
1186
|
+
this.ensureCapacity(cat, size);
|
|
1187
|
+
}
|
|
1188
|
+
} else {
|
|
1189
|
+
this.ensureCapacity(cat, size);
|
|
1190
|
+
}
|
|
725
1191
|
const now = Date.now();
|
|
726
1192
|
const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
|
|
727
1193
|
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 });
|
|
@@ -781,6 +1247,7 @@ var SmartMemoryCache = class {
|
|
|
781
1247
|
}
|
|
782
1248
|
const count = this.cache.size;
|
|
783
1249
|
this.cache.clear();
|
|
1250
|
+
this.wtinyPolicy?.clear();
|
|
784
1251
|
this.totalSize = 0;
|
|
785
1252
|
this.categoryCount.clear();
|
|
786
1253
|
this.categorySize.clear();
|
|
@@ -948,8 +1415,8 @@ var SmartMemoryCache = class {
|
|
|
948
1415
|
if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
|
|
949
1416
|
if (this.cache.has(key)) continue;
|
|
950
1417
|
const rawData = entry.data;
|
|
951
|
-
const data = !entry.isCompressed ?
|
|
952
|
-
const value = entry.size <= LARGE_VALUE_BYTES ?
|
|
1418
|
+
const data = !entry.isCompressed ? this.codec.encode(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
|
|
1419
|
+
const value = entry.size <= LARGE_VALUE_BYTES ? this.codec.decode(data) : void 0;
|
|
953
1420
|
this.cache.set(key, { ...entry, data, value, isCompressed: true });
|
|
954
1421
|
this.bloom.add(key);
|
|
955
1422
|
loaded++;
|
|
@@ -1020,7 +1487,7 @@ var SmartMemoryCache = class {
|
|
|
1020
1487
|
* if the live object was not cached (large-entry optimisation or disk-restored entry).
|
|
1021
1488
|
*/
|
|
1022
1489
|
resolveValue(entry) {
|
|
1023
|
-
return entry.value !== void 0 ? entry.value :
|
|
1490
|
+
return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
1024
1491
|
}
|
|
1025
1492
|
// ── Stats ─────────────────────────────────────────────────────────────────
|
|
1026
1493
|
get size() {
|
|
@@ -1125,25 +1592,160 @@ var SmartMemoryCache = class {
|
|
|
1125
1592
|
out.sort((a, b) => b.hits - a.hits);
|
|
1126
1593
|
return out.slice(0, n);
|
|
1127
1594
|
}
|
|
1595
|
+
/**
|
|
1596
|
+
* Return real-time metrics and telemetry for the Window TinyLFU admission policy.
|
|
1597
|
+
* Returns `undefined` when running under default adaptive eviction.
|
|
1598
|
+
*/
|
|
1599
|
+
getWTinyLfuStats() {
|
|
1600
|
+
return this.wtinyPolicy?.getStats();
|
|
1601
|
+
}
|
|
1128
1602
|
};
|
|
1129
1603
|
|
|
1130
1604
|
// src/disk-tier.ts
|
|
1131
1605
|
import fs from "fs";
|
|
1132
1606
|
import path from "path";
|
|
1133
1607
|
import crypto from "crypto";
|
|
1134
|
-
import
|
|
1608
|
+
import os2 from "os";
|
|
1609
|
+
var BoundedDiskQueue = class {
|
|
1610
|
+
constructor(maxConcurrent = Math.min(4, Math.max(1, Math.floor((os2?.availableParallelism?.() ?? 4) / 4))), maxPending = 512, writeTimeoutMs = 500, failureThreshold = 5, cooldownMs = 5e3) {
|
|
1611
|
+
this.maxConcurrent = maxConcurrent;
|
|
1612
|
+
this.maxPending = maxPending;
|
|
1613
|
+
this.writeTimeoutMs = writeTimeoutMs;
|
|
1614
|
+
this.failureThreshold = failureThreshold;
|
|
1615
|
+
this.cooldownMs = cooldownMs;
|
|
1616
|
+
}
|
|
1617
|
+
maxConcurrent;
|
|
1618
|
+
maxPending;
|
|
1619
|
+
writeTimeoutMs;
|
|
1620
|
+
failureThreshold;
|
|
1621
|
+
cooldownMs;
|
|
1622
|
+
active = 0;
|
|
1623
|
+
queue = [];
|
|
1624
|
+
spillsDropped = 0;
|
|
1625
|
+
consecutiveFailures = 0;
|
|
1626
|
+
circuitState = "closed";
|
|
1627
|
+
lastStateChangeMonotonic = performance.now();
|
|
1628
|
+
async schedule(task) {
|
|
1629
|
+
const now = performance.now();
|
|
1630
|
+
if (this.circuitState === "open") {
|
|
1631
|
+
if (now - this.lastStateChangeMonotonic > this.cooldownMs) {
|
|
1632
|
+
this.circuitState = "half-open";
|
|
1633
|
+
this.lastStateChangeMonotonic = now;
|
|
1634
|
+
} else {
|
|
1635
|
+
this.spillsDropped++;
|
|
1636
|
+
return null;
|
|
1637
|
+
}
|
|
1638
|
+
}
|
|
1639
|
+
if (this.circuitState === "half-open" && this.active > 0) {
|
|
1640
|
+
this.spillsDropped++;
|
|
1641
|
+
return null;
|
|
1642
|
+
}
|
|
1643
|
+
if (this.queue.length >= this.maxPending) {
|
|
1644
|
+
this.spillsDropped++;
|
|
1645
|
+
return null;
|
|
1646
|
+
}
|
|
1647
|
+
if (this.active >= this.maxConcurrent) {
|
|
1648
|
+
await new Promise((resolve) => this.queue.push(resolve));
|
|
1649
|
+
}
|
|
1650
|
+
this.active++;
|
|
1651
|
+
let timeoutId = null;
|
|
1652
|
+
try {
|
|
1653
|
+
const result = await Promise.race([
|
|
1654
|
+
task(),
|
|
1655
|
+
new Promise((_, reject) => {
|
|
1656
|
+
timeoutId = setTimeout(
|
|
1657
|
+
() => reject(new Error(`Disk write exceeded timeout of ${this.writeTimeoutMs}ms`)),
|
|
1658
|
+
this.writeTimeoutMs
|
|
1659
|
+
);
|
|
1660
|
+
})
|
|
1661
|
+
]);
|
|
1662
|
+
this.consecutiveFailures = 0;
|
|
1663
|
+
if (this.circuitState === "half-open") {
|
|
1664
|
+
this.circuitState = "closed";
|
|
1665
|
+
this.lastStateChangeMonotonic = performance.now();
|
|
1666
|
+
}
|
|
1667
|
+
return result;
|
|
1668
|
+
} catch {
|
|
1669
|
+
this.consecutiveFailures++;
|
|
1670
|
+
if (this.consecutiveFailures >= this.failureThreshold || this.circuitState === "half-open") {
|
|
1671
|
+
this.circuitState = "open";
|
|
1672
|
+
this.lastStateChangeMonotonic = performance.now();
|
|
1673
|
+
}
|
|
1674
|
+
this.spillsDropped++;
|
|
1675
|
+
return null;
|
|
1676
|
+
} finally {
|
|
1677
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
1678
|
+
this.active--;
|
|
1679
|
+
const next = this.queue.shift();
|
|
1680
|
+
if (next) next();
|
|
1681
|
+
}
|
|
1682
|
+
}
|
|
1683
|
+
getStats() {
|
|
1684
|
+
return {
|
|
1685
|
+
activeWrites: this.active,
|
|
1686
|
+
pendingWrites: this.queue.length,
|
|
1687
|
+
spillsDropped: this.spillsDropped,
|
|
1688
|
+
circuitState: this.circuitState,
|
|
1689
|
+
lastTripTimestamp: this.lastStateChangeMonotonic
|
|
1690
|
+
};
|
|
1691
|
+
}
|
|
1692
|
+
reset() {
|
|
1693
|
+
this.consecutiveFailures = 0;
|
|
1694
|
+
this.circuitState = "closed";
|
|
1695
|
+
this.lastStateChangeMonotonic = performance.now();
|
|
1696
|
+
}
|
|
1697
|
+
};
|
|
1135
1698
|
var _SqliteDB = null;
|
|
1136
1699
|
try {
|
|
1137
|
-
const
|
|
1138
|
-
|
|
1700
|
+
const proc = process;
|
|
1701
|
+
if (typeof proc.getBuiltinModule === "function") {
|
|
1702
|
+
const sqlite = proc.getBuiltinModule("node:sqlite");
|
|
1703
|
+
_SqliteDB = sqlite?.DatabaseSync ?? null;
|
|
1704
|
+
}
|
|
1139
1705
|
} catch {
|
|
1140
1706
|
}
|
|
1141
1707
|
var DISK_MAGIC = Buffer.from([68, 84, 73, 69, 82, 86, 49, 0]);
|
|
1142
1708
|
var DISK_MAGIC_V2 = Buffer.from([68, 84, 73, 69, 82, 86, 50, 0]);
|
|
1143
1709
|
var V2_HEADER_LEN = 16;
|
|
1144
1710
|
var DISK_TIER_VERSION = 1;
|
|
1711
|
+
function resolveDefaultDiskDir(namespace, logger) {
|
|
1712
|
+
const ns = namespace?.trim() ?? "";
|
|
1713
|
+
const nsDir = ns ? `tricache-disk-${ns}` : "tricache-disk";
|
|
1714
|
+
if (process.platform === "linux") {
|
|
1715
|
+
const shmPath = "/dev/shm";
|
|
1716
|
+
try {
|
|
1717
|
+
fs.accessSync(shmPath, fs.constants.W_OK | fs.constants.R_OK);
|
|
1718
|
+
if (typeof fs.statfsSync === "function") {
|
|
1719
|
+
const stats = fs.statfsSync(shmPath);
|
|
1720
|
+
const totalBytes = Number(stats.blocks) * Number(stats.bsize);
|
|
1721
|
+
const freeBytes = Number(stats.bavail) * Number(stats.bsize);
|
|
1722
|
+
if (totalBytes >= 256 * 1024 * 1024 && freeBytes >= 128 * 1024 * 1024) {
|
|
1723
|
+
const targetDir = path.join(shmPath, nsDir);
|
|
1724
|
+
logger?.info?.("DiskTier: Targeting Linux /dev/shm tmpfs for off-heap storage", {
|
|
1725
|
+
path: targetDir,
|
|
1726
|
+
totalBytes,
|
|
1727
|
+
freeBytes
|
|
1728
|
+
});
|
|
1729
|
+
return { dir: targetDir, isShm: true };
|
|
1730
|
+
} else {
|
|
1731
|
+
logger?.info?.("DiskTier: /dev/shm capacity or free space insufficient (<256MB total or <128MB free); falling back to tmpdir", {
|
|
1732
|
+
totalBytes,
|
|
1733
|
+
freeBytes
|
|
1734
|
+
});
|
|
1735
|
+
}
|
|
1736
|
+
}
|
|
1737
|
+
} catch (err) {
|
|
1738
|
+
logger?.debug?.("DiskTier: /dev/shm not usable, falling back to tmpdir", {
|
|
1739
|
+
error: err.message
|
|
1740
|
+
});
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
return { dir: path.join(os2.tmpdir(), nsDir), isShm: false };
|
|
1744
|
+
}
|
|
1145
1745
|
var DiskTier = class {
|
|
1146
1746
|
opts;
|
|
1747
|
+
codec;
|
|
1748
|
+
diskQueue;
|
|
1147
1749
|
dirReady = false;
|
|
1148
1750
|
diskUsageBytes = 0;
|
|
1149
1751
|
usageCounted = false;
|
|
@@ -1151,6 +1753,14 @@ var DiskTier = class {
|
|
|
1151
1753
|
// maintained in-memory; avoids walkCacheFiles() in stats
|
|
1152
1754
|
/** Next bucket index (0–255) for the staggered janitor wheel. */
|
|
1153
1755
|
_nextJanitorBucket = 0;
|
|
1756
|
+
// ── High-watermark pruning & host volume health state ─────────────────────
|
|
1757
|
+
_isPruning = false;
|
|
1758
|
+
_pruneRounds = 0;
|
|
1759
|
+
_entriesPruned = 0;
|
|
1760
|
+
_spillsShedTotal = 0;
|
|
1761
|
+
_hostVolumeLowSpace = false;
|
|
1762
|
+
_hostVolumeLowSpacePauses = 0;
|
|
1763
|
+
_writeCounter = 0;
|
|
1154
1764
|
// ── SQLite metadata index (optional, requires node:sqlite) ───────────────
|
|
1155
1765
|
_db = null;
|
|
1156
1766
|
_stmtInsert = null;
|
|
@@ -1165,8 +1775,19 @@ var DiskTier = class {
|
|
|
1165
1775
|
// DELETE expired rows
|
|
1166
1776
|
_stmtStats = null;
|
|
1167
1777
|
// COUNT + SUM(size)
|
|
1778
|
+
_stmtPruneChunk = null;
|
|
1779
|
+
// SELECT chunk for watermark pruning
|
|
1168
1780
|
constructor(opts) {
|
|
1169
1781
|
this.opts = opts;
|
|
1782
|
+
this.codec = opts.codec ?? defaultCodec;
|
|
1783
|
+
const defaultConcurrent = Math.min(4, Math.max(1, Math.floor((os2?.availableParallelism?.() ?? 4) / 4)));
|
|
1784
|
+
this.diskQueue = new BoundedDiskQueue(
|
|
1785
|
+
opts.diskMaxConcurrentWrites ?? defaultConcurrent,
|
|
1786
|
+
opts.diskMaxPendingWrites ?? 512,
|
|
1787
|
+
opts.diskWriteTimeoutMs ?? 500,
|
|
1788
|
+
opts.diskCircuitBreakerThreshold ?? 5,
|
|
1789
|
+
opts.diskCircuitBreakerCooldownMs ?? 5e3
|
|
1790
|
+
);
|
|
1170
1791
|
}
|
|
1171
1792
|
// ── Helpers ───────────────────────────────────────────────────────────────
|
|
1172
1793
|
ensureDir() {
|
|
@@ -1201,15 +1822,30 @@ var DiskTier = class {
|
|
|
1201
1822
|
PRAGMA synchronous = NORMAL;
|
|
1202
1823
|
PRAGMA temp_store = MEMORY;
|
|
1203
1824
|
CREATE TABLE IF NOT EXISTS meta (
|
|
1204
|
-
key_hash
|
|
1205
|
-
file_path
|
|
1206
|
-
expires_at
|
|
1207
|
-
size
|
|
1825
|
+
key_hash TEXT PRIMARY KEY,
|
|
1826
|
+
file_path TEXT NOT NULL,
|
|
1827
|
+
expires_at INTEGER NOT NULL,
|
|
1828
|
+
size INTEGER NOT NULL DEFAULT 0,
|
|
1829
|
+
priority INTEGER NOT NULL DEFAULT 2,
|
|
1830
|
+
last_accessed_at INTEGER NOT NULL DEFAULT 0
|
|
1208
1831
|
);
|
|
1209
1832
|
CREATE INDEX IF NOT EXISTS idx_expires ON meta (expires_at);
|
|
1833
|
+
CREATE INDEX IF NOT EXISTS idx_priority_access ON meta (priority ASC, last_accessed_at ASC);
|
|
1210
1834
|
`);
|
|
1835
|
+
try {
|
|
1836
|
+
this._db.exec("ALTER TABLE meta ADD COLUMN priority INTEGER NOT NULL DEFAULT 2;");
|
|
1837
|
+
} catch {
|
|
1838
|
+
}
|
|
1839
|
+
try {
|
|
1840
|
+
this._db.exec("ALTER TABLE meta ADD COLUMN last_accessed_at INTEGER NOT NULL DEFAULT 0;");
|
|
1841
|
+
} catch {
|
|
1842
|
+
}
|
|
1843
|
+
try {
|
|
1844
|
+
this._db.exec("CREATE INDEX IF NOT EXISTS idx_priority_access ON meta (priority ASC, last_accessed_at ASC);");
|
|
1845
|
+
} catch {
|
|
1846
|
+
}
|
|
1211
1847
|
this._stmtInsert = this._db.prepare(
|
|
1212
|
-
"INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size) VALUES (
|
|
1848
|
+
"INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size, priority, last_accessed_at) VALUES (?,?,?,?,?,?)"
|
|
1213
1849
|
);
|
|
1214
1850
|
this._stmtSelect = this._db.prepare(
|
|
1215
1851
|
"SELECT file_path, expires_at FROM meta WHERE key_hash = ?"
|
|
@@ -1222,13 +1858,16 @@ var DiskTier = class {
|
|
|
1222
1858
|
this._stmtStats = this._db.prepare(
|
|
1223
1859
|
"SELECT COUNT(*) AS cnt, COALESCE(SUM(size), 0) AS bytes FROM meta"
|
|
1224
1860
|
);
|
|
1861
|
+
this._stmtPruneChunk = this._db.prepare(
|
|
1862
|
+
"SELECT key_hash, file_path, size FROM meta ORDER BY priority ASC, last_accessed_at ASC LIMIT 500"
|
|
1863
|
+
);
|
|
1225
1864
|
const row = this._stmtStats.get();
|
|
1226
1865
|
this.fileCount = row.cnt;
|
|
1227
1866
|
this.diskUsageBytes = row.bytes;
|
|
1228
1867
|
this.usageCounted = true;
|
|
1229
1868
|
this.opts.logger.debug("DiskTier: SQLite index ready", { entries: row.cnt });
|
|
1230
1869
|
} catch (err) {
|
|
1231
|
-
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
|
|
1870
|
+
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = this._stmtPruneChunk = null;
|
|
1232
1871
|
this.opts.logger.warn("DiskTier: SQLite init failed, using file-only mode", {
|
|
1233
1872
|
error: err.message
|
|
1234
1873
|
});
|
|
@@ -1323,7 +1962,7 @@ var DiskTier = class {
|
|
|
1323
1962
|
return results;
|
|
1324
1963
|
}
|
|
1325
1964
|
isForbidden(key) {
|
|
1326
|
-
return this.opts.forbiddenPrefixes
|
|
1965
|
+
return this.opts.forbiddenPrefixes?.some((p) => key.startsWith(p)) ?? false;
|
|
1327
1966
|
}
|
|
1328
1967
|
encrypt(data) {
|
|
1329
1968
|
if (!this.opts.encryption) return data;
|
|
@@ -1375,7 +2014,16 @@ var DiskTier = class {
|
|
|
1375
2014
|
this.ensureDir();
|
|
1376
2015
|
if (!this.dirReady) return;
|
|
1377
2016
|
this.ensureUsageCounted();
|
|
1378
|
-
if (this.
|
|
2017
|
+
if (++this._writeCounter % 2e3 === 0) {
|
|
2018
|
+
this.checkHostVolumeHealth();
|
|
2019
|
+
}
|
|
2020
|
+
if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes >= this.opts.maxBytes) {
|
|
2021
|
+
this._spillsShedTotal++;
|
|
2022
|
+
return;
|
|
2023
|
+
}
|
|
2024
|
+
if (this.diskUsageBytes >= this.opts.maxBytes * 0.8 && !this._isPruning) {
|
|
2025
|
+
void this.triggerChunkedPrune();
|
|
2026
|
+
}
|
|
1379
2027
|
let final;
|
|
1380
2028
|
try {
|
|
1381
2029
|
const payload = {
|
|
@@ -1387,7 +2035,7 @@ var DiskTier = class {
|
|
|
1387
2035
|
},
|
|
1388
2036
|
writtenAt: Date.now()
|
|
1389
2037
|
};
|
|
1390
|
-
const packed =
|
|
2038
|
+
const packed = this.codec.encode(payload);
|
|
1391
2039
|
if (packed.length > this.opts.entryMaxBytes) return;
|
|
1392
2040
|
let toEncrypt = packed;
|
|
1393
2041
|
if (this.opts.compression && this.opts.compression !== "none" && packed.length > (this.opts.compressionThresholdBytes ?? 1024)) {
|
|
@@ -1403,39 +2051,52 @@ var DiskTier = class {
|
|
|
1403
2051
|
}
|
|
1404
2052
|
const hash = this.keyToHash(key);
|
|
1405
2053
|
const filePath = this.hashToWritePath(hash, entry.expiresAt);
|
|
1406
|
-
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${
|
|
2054
|
+
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${crypto.randomBytes(6).toString("hex")}.tmp`;
|
|
1407
2055
|
this.diskUsageBytes += final.length;
|
|
1408
2056
|
this.fileCount++;
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
2057
|
+
if (this.diskUsageBytes >= this.opts.maxBytes * 0.8 && !this._isPruning) {
|
|
2058
|
+
void this.triggerChunkedPrune();
|
|
2059
|
+
}
|
|
2060
|
+
const result = await this.diskQueue.schedule(async () => {
|
|
1412
2061
|
try {
|
|
1413
|
-
await fs.promises.
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
if (code === "EBUSY" || code === "EPERM") {
|
|
1417
|
-
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
2062
|
+
await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
|
|
2063
|
+
await fs.promises.writeFile(tmpPath, final, { mode: 384 });
|
|
2064
|
+
try {
|
|
1418
2065
|
await fs.promises.rename(tmpPath, filePath);
|
|
1419
|
-
}
|
|
1420
|
-
|
|
2066
|
+
} catch (renameErr) {
|
|
2067
|
+
const code = renameErr?.code;
|
|
2068
|
+
if (code === "EBUSY" || code === "EPERM") {
|
|
2069
|
+
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
2070
|
+
await fs.promises.rename(tmpPath, filePath);
|
|
2071
|
+
} else {
|
|
2072
|
+
throw renameErr;
|
|
2073
|
+
}
|
|
1421
2074
|
}
|
|
2075
|
+
if (this._db) {
|
|
2076
|
+
const priority = typeof entry.priority === "number" ? entry.priority : 2;
|
|
2077
|
+
const lastAccess = typeof entry.lastAccess === "number" ? entry.lastAccess : Date.now();
|
|
2078
|
+
this._stmtInsert.run(hash, filePath, entry.expiresAt, final.length, priority, lastAccess);
|
|
2079
|
+
}
|
|
2080
|
+
this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
|
|
2081
|
+
return true;
|
|
2082
|
+
} catch (err) {
|
|
2083
|
+
try {
|
|
2084
|
+
await fs.promises.unlink(tmpPath);
|
|
2085
|
+
} catch {
|
|
2086
|
+
}
|
|
2087
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
|
|
2088
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2089
|
+
if (this._db) try {
|
|
2090
|
+
this._stmtDelete.run(hash);
|
|
2091
|
+
} catch {
|
|
2092
|
+
}
|
|
2093
|
+
this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
|
|
2094
|
+
throw err;
|
|
1422
2095
|
}
|
|
1423
|
-
|
|
1424
|
-
|
|
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
|
-
}
|
|
2096
|
+
});
|
|
2097
|
+
if (result === null) {
|
|
1432
2098
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
|
|
1433
2099
|
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
2100
|
}
|
|
1440
2101
|
}
|
|
1441
2102
|
/** Load a key from disk, or return null on miss/expiry/corruption. */
|
|
@@ -1513,7 +2174,7 @@ var DiskTier = class {
|
|
|
1513
2174
|
}
|
|
1514
2175
|
}
|
|
1515
2176
|
const uncompressed = decompressWithHeader(decrypted, this.opts.compression ?? "brotli");
|
|
1516
|
-
const payload =
|
|
2177
|
+
const payload = this.codec.decode(uncompressed);
|
|
1517
2178
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
|
|
1518
2179
|
if (payload.entry.expiresAt <= Date.now()) return null;
|
|
1519
2180
|
const entry = payload.entry;
|
|
@@ -1636,7 +2297,7 @@ var DiskTier = class {
|
|
|
1636
2297
|
purged++;
|
|
1637
2298
|
continue;
|
|
1638
2299
|
}
|
|
1639
|
-
const payload =
|
|
2300
|
+
const payload = this.codec.decode(dec);
|
|
1640
2301
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
1641
2302
|
fs.unlinkSync(filePath);
|
|
1642
2303
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
@@ -1800,7 +2461,7 @@ var DiskTier = class {
|
|
|
1800
2461
|
purged++;
|
|
1801
2462
|
continue;
|
|
1802
2463
|
}
|
|
1803
|
-
const payload =
|
|
2464
|
+
const payload = this.codec.decode(dec);
|
|
1804
2465
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
1805
2466
|
fs.unlinkSync(filePath);
|
|
1806
2467
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
@@ -1839,30 +2500,936 @@ var DiskTier = class {
|
|
|
1839
2500
|
}
|
|
1840
2501
|
return cleared;
|
|
1841
2502
|
}
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
2503
|
+
/**
|
|
2504
|
+
* Proactively checks host volume free space via statfsSync.
|
|
2505
|
+
* If free space on the volume drops below 10%, pauses spills to prevent
|
|
2506
|
+
* Kubernetes pod eviction (DiskPressure / EphemeralStorageExceeded).
|
|
2507
|
+
*/
|
|
2508
|
+
checkHostVolumeHealth() {
|
|
2509
|
+
try {
|
|
2510
|
+
if (typeof fs.statfsSync === "function") {
|
|
2511
|
+
const stats = fs.statfsSync(this.opts.dir);
|
|
2512
|
+
const total = Number(stats.blocks);
|
|
2513
|
+
const avail = Number(stats.bavail);
|
|
2514
|
+
if (total > 0) {
|
|
2515
|
+
const freeRatio = avail / total;
|
|
2516
|
+
if (freeRatio < 0.1) {
|
|
2517
|
+
if (!this._hostVolumeLowSpace) {
|
|
2518
|
+
this._hostVolumeLowSpace = true;
|
|
2519
|
+
this._hostVolumeLowSpacePauses++;
|
|
2520
|
+
this.opts.logger.warn(
|
|
2521
|
+
"DiskTier: host volume has <10% free space. Pausing disk cache spills to prevent Kubernetes eviction.",
|
|
2522
|
+
{ dir: this.opts.dir, freePct: Number((freeRatio * 100).toFixed(1)) }
|
|
2523
|
+
);
|
|
2524
|
+
}
|
|
2525
|
+
return false;
|
|
2526
|
+
} else if (this._hostVolumeLowSpace) {
|
|
2527
|
+
this._hostVolumeLowSpace = false;
|
|
2528
|
+
this.opts.logger.info(
|
|
2529
|
+
"DiskTier: host volume space recovered (>=10% free). Resuming disk cache spills.",
|
|
2530
|
+
{ dir: this.opts.dir, freePct: Number((freeRatio * 100).toFixed(1)) }
|
|
2531
|
+
);
|
|
2532
|
+
return true;
|
|
2533
|
+
}
|
|
2534
|
+
}
|
|
2535
|
+
}
|
|
2536
|
+
} catch {
|
|
1847
2537
|
}
|
|
1848
|
-
return
|
|
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";
|
|
2538
|
+
return true;
|
|
1853
2539
|
}
|
|
1854
|
-
/**
|
|
2540
|
+
/**
|
|
2541
|
+
* Non-blocking chunked pruning:
|
|
2542
|
+
* Evicts oldest entries in 500-entry chunks down to 60% watermark,
|
|
2543
|
+
* yielding to the event loop via setImmediate between chunks.
|
|
2544
|
+
*/
|
|
2545
|
+
async triggerChunkedPrune() {
|
|
2546
|
+
if (this._isPruning) return 0;
|
|
2547
|
+
this._isPruning = true;
|
|
2548
|
+
this._pruneRounds++;
|
|
2549
|
+
let prunedInThisRound = 0;
|
|
2550
|
+
try {
|
|
2551
|
+
this.ensureUsageCounted();
|
|
2552
|
+
const targetBytes = Math.floor(this.opts.maxBytes * 0.6);
|
|
2553
|
+
if (this._db && this._stmtPruneChunk) {
|
|
2554
|
+
while (this.diskUsageBytes > targetBytes) {
|
|
2555
|
+
const rows = this._stmtPruneChunk.all();
|
|
2556
|
+
if (!rows || rows.length === 0) break;
|
|
2557
|
+
for (const row of rows) {
|
|
2558
|
+
try {
|
|
2559
|
+
fs.unlinkSync(row.file_path);
|
|
2560
|
+
} catch {
|
|
2561
|
+
}
|
|
2562
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
|
|
2563
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2564
|
+
this._entriesPruned++;
|
|
2565
|
+
prunedInThisRound++;
|
|
2566
|
+
try {
|
|
2567
|
+
this._stmtDelete.run(row.key_hash);
|
|
2568
|
+
} catch {
|
|
2569
|
+
}
|
|
2570
|
+
if (this.diskUsageBytes <= targetBytes) break;
|
|
2571
|
+
}
|
|
2572
|
+
if (this.diskUsageBytes > targetBytes) {
|
|
2573
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
2574
|
+
}
|
|
2575
|
+
}
|
|
2576
|
+
} else {
|
|
2577
|
+
while (this.diskUsageBytes > targetBytes) {
|
|
2578
|
+
const files = this.walkCacheFiles();
|
|
2579
|
+
if (files.length === 0) break;
|
|
2580
|
+
const chunk = files.slice(0, 500);
|
|
2581
|
+
for (const filePath of chunk) {
|
|
2582
|
+
try {
|
|
2583
|
+
const stat = fs.statSync(filePath);
|
|
2584
|
+
fs.unlinkSync(filePath);
|
|
2585
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
2586
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2587
|
+
this._entriesPruned++;
|
|
2588
|
+
prunedInThisRound++;
|
|
2589
|
+
} catch {
|
|
2590
|
+
}
|
|
2591
|
+
if (this.diskUsageBytes <= targetBytes) break;
|
|
2592
|
+
}
|
|
2593
|
+
if (this.diskUsageBytes > targetBytes) {
|
|
2594
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
2595
|
+
}
|
|
2596
|
+
}
|
|
2597
|
+
}
|
|
2598
|
+
} finally {
|
|
2599
|
+
this._isPruning = false;
|
|
2600
|
+
}
|
|
2601
|
+
return prunedInThisRound;
|
|
2602
|
+
}
|
|
2603
|
+
get isPruning() {
|
|
2604
|
+
return this._isPruning;
|
|
2605
|
+
}
|
|
2606
|
+
get hostVolumeLowSpace() {
|
|
2607
|
+
return this._hostVolumeLowSpace;
|
|
2608
|
+
}
|
|
2609
|
+
get spillsShedTotal() {
|
|
2610
|
+
return this._spillsShedTotal;
|
|
2611
|
+
}
|
|
2612
|
+
getPruningStats() {
|
|
2613
|
+
return {
|
|
2614
|
+
active: this._isPruning,
|
|
2615
|
+
pruneRounds: this._pruneRounds,
|
|
2616
|
+
entriesPruned: this._entriesPruned,
|
|
2617
|
+
spillsShedTotal: this._spillsShedTotal,
|
|
2618
|
+
hostVolumeLowSpacePauses: this._hostVolumeLowSpacePauses
|
|
2619
|
+
};
|
|
2620
|
+
}
|
|
2621
|
+
get stats() {
|
|
2622
|
+
if (this._db) {
|
|
2623
|
+
const row = this._stmtStats.get();
|
|
2624
|
+
this.fileCount = row.cnt;
|
|
2625
|
+
this.diskUsageBytes = row.bytes;
|
|
2626
|
+
}
|
|
2627
|
+
return {
|
|
2628
|
+
files: this.fileCount,
|
|
2629
|
+
sizeKB: Math.round(this.diskUsageBytes / 1024),
|
|
2630
|
+
maxKB: Math.round(this.opts.maxBytes / 1024),
|
|
2631
|
+
backpressure: this.diskQueue.getStats(),
|
|
2632
|
+
pruning: this.getPruningStats()
|
|
2633
|
+
};
|
|
2634
|
+
}
|
|
2635
|
+
/** Direct access to the bounded write queue for chaos diagnostics and canary controls. */
|
|
2636
|
+
get backpressure() {
|
|
2637
|
+
return this.diskQueue;
|
|
2638
|
+
}
|
|
2639
|
+
/** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
|
|
2640
|
+
get indexMode() {
|
|
2641
|
+
return this._db ? "sqlite" : "file-only";
|
|
2642
|
+
}
|
|
2643
|
+
/** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
|
|
1855
2644
|
close() {
|
|
1856
2645
|
if (this._db) {
|
|
1857
2646
|
try {
|
|
1858
2647
|
this._db.close();
|
|
1859
2648
|
} catch {
|
|
1860
2649
|
}
|
|
1861
|
-
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
|
|
2650
|
+
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = this._stmtPruneChunk = null;
|
|
1862
2651
|
}
|
|
1863
2652
|
}
|
|
1864
2653
|
};
|
|
1865
2654
|
|
|
2655
|
+
// src/latency-watchdog.ts
|
|
2656
|
+
var TierLatencyWatchdog = class {
|
|
2657
|
+
enabled;
|
|
2658
|
+
minDiskBypassMs;
|
|
2659
|
+
bypassRatio;
|
|
2660
|
+
cooldownMs;
|
|
2661
|
+
redisCutoffMs;
|
|
2662
|
+
redisRecoveryFloorMs;
|
|
2663
|
+
minSamples;
|
|
2664
|
+
disableRedis;
|
|
2665
|
+
// Zero-allocation rolling ring buffers
|
|
2666
|
+
diskRing = new Float32Array(32);
|
|
2667
|
+
redisRing = new Float32Array(32);
|
|
2668
|
+
scratch = new Float32Array(32);
|
|
2669
|
+
diskIdx = 0;
|
|
2670
|
+
redisIdx = 0;
|
|
2671
|
+
diskCount = 0;
|
|
2672
|
+
redisCount = 0;
|
|
2673
|
+
// Cached amortized p95 values
|
|
2674
|
+
cachedDiskP95 = 0;
|
|
2675
|
+
cachedRedisP95 = 0;
|
|
2676
|
+
// State machine & control-theory flags
|
|
2677
|
+
stage = 0;
|
|
2678
|
+
redisDampened = false;
|
|
2679
|
+
// Asymmetric hysteresis latch
|
|
2680
|
+
redisRecoveryConsecutiveSamples = 0;
|
|
2681
|
+
bypassedUntilMonotonic = 0;
|
|
2682
|
+
canaryInFlight = false;
|
|
2683
|
+
bypassedTotal = 0;
|
|
2684
|
+
constructor(options = {}) {
|
|
2685
|
+
this.enabled = options.enabled ?? true;
|
|
2686
|
+
this.minDiskBypassMs = options.minDiskBypassMs ?? 10;
|
|
2687
|
+
this.bypassRatio = options.bypassRatio ?? 1.5;
|
|
2688
|
+
this.cooldownMs = options.cooldownMs ?? 3e4;
|
|
2689
|
+
this.redisCutoffMs = options.redisCutoffMs ?? 15;
|
|
2690
|
+
this.redisRecoveryFloorMs = options.redisRecoveryFloorMs ?? 10;
|
|
2691
|
+
this.minSamples = options.minSamples ?? 16;
|
|
2692
|
+
this.disableRedis = options.disableRedis ?? false;
|
|
2693
|
+
}
|
|
2694
|
+
setDisableRedis(disabled) {
|
|
2695
|
+
this.disableRedis = disabled;
|
|
2696
|
+
if (disabled) {
|
|
2697
|
+
this.stage = 0;
|
|
2698
|
+
this.bypassedUntilMonotonic = 0;
|
|
2699
|
+
this.canaryInFlight = false;
|
|
2700
|
+
this.redisRecoveryConsecutiveSamples = 0;
|
|
2701
|
+
}
|
|
2702
|
+
}
|
|
2703
|
+
/**
|
|
2704
|
+
* Record disk read duration in milliseconds (zero-allocation hot path).
|
|
2705
|
+
*/
|
|
2706
|
+
recordDisk(ms) {
|
|
2707
|
+
if (!this.enabled) return;
|
|
2708
|
+
this.diskRing[this.diskIdx++ & 31] = ms;
|
|
2709
|
+
this.diskCount++;
|
|
2710
|
+
if ((this.diskIdx & 31) === 0) {
|
|
2711
|
+
this.recalculateP95();
|
|
2712
|
+
}
|
|
2713
|
+
}
|
|
2714
|
+
/**
|
|
2715
|
+
* Record Redis read duration in milliseconds (zero-allocation hot path).
|
|
2716
|
+
*/
|
|
2717
|
+
recordRedis(ms) {
|
|
2718
|
+
if (!this.enabled || this.disableRedis) return;
|
|
2719
|
+
this.redisRing[this.redisIdx++ & 31] = ms;
|
|
2720
|
+
this.redisCount++;
|
|
2721
|
+
if (ms <= this.redisRecoveryFloorMs) {
|
|
2722
|
+
this.redisRecoveryConsecutiveSamples++;
|
|
2723
|
+
} else {
|
|
2724
|
+
this.redisRecoveryConsecutiveSamples = 0;
|
|
2725
|
+
}
|
|
2726
|
+
if ((this.redisIdx & 31) === 0) {
|
|
2727
|
+
this.recalculateP95();
|
|
2728
|
+
}
|
|
2729
|
+
}
|
|
2730
|
+
recalculateP95() {
|
|
2731
|
+
if (this.diskCount >= this.minSamples) {
|
|
2732
|
+
this.cachedDiskP95 = this.computeP95(this.diskRing, Math.min(this.diskCount, 32));
|
|
2733
|
+
}
|
|
2734
|
+
if (this.redisCount >= this.minSamples) {
|
|
2735
|
+
this.cachedRedisP95 = this.computeP95(this.redisRing, Math.min(this.redisCount, 32));
|
|
2736
|
+
}
|
|
2737
|
+
this.evaluateControlLoop();
|
|
2738
|
+
}
|
|
2739
|
+
computeP95(ring, count) {
|
|
2740
|
+
for (let i = 0; i < count; i++) {
|
|
2741
|
+
this.scratch[i] = ring[i];
|
|
2742
|
+
}
|
|
2743
|
+
this.scratch.subarray(0, count).sort();
|
|
2744
|
+
const rank = Math.min(count - 1, Math.max(0, Math.floor((count - 1) * 0.95)));
|
|
2745
|
+
return this.scratch[rank];
|
|
2746
|
+
}
|
|
2747
|
+
/**
|
|
2748
|
+
* Core Control Loop:
|
|
2749
|
+
* - Evaluates asymmetric hysteresis on Redis circuit.
|
|
2750
|
+
* - Assigns graduated stage (0, 1, 2, 3) with anti-synchronicity jitter.
|
|
2751
|
+
*/
|
|
2752
|
+
evaluateControlLoop() {
|
|
2753
|
+
if (this.disableRedis) {
|
|
2754
|
+
this.stage = 0;
|
|
2755
|
+
return;
|
|
2756
|
+
}
|
|
2757
|
+
if (this.cachedRedisP95 >= this.redisCutoffMs) {
|
|
2758
|
+
this.redisDampened = true;
|
|
2759
|
+
} else if (this.redisDampened && this.cachedRedisP95 <= this.redisRecoveryFloorMs && this.redisRecoveryConsecutiveSamples >= this.minSamples) {
|
|
2760
|
+
this.redisDampened = false;
|
|
2761
|
+
}
|
|
2762
|
+
if (this.redisDampened) {
|
|
2763
|
+
this.stage = 0;
|
|
2764
|
+
return;
|
|
2765
|
+
}
|
|
2766
|
+
if (this.diskCount < this.minSamples || this.redisCount < this.minSamples) {
|
|
2767
|
+
return;
|
|
2768
|
+
}
|
|
2769
|
+
const diskP95 = this.cachedDiskP95;
|
|
2770
|
+
const redisP95 = Math.max(0.1, this.cachedRedisP95);
|
|
2771
|
+
if (diskP95 >= 50) {
|
|
2772
|
+
if (this.stage !== 3) {
|
|
2773
|
+
this.stage = 3;
|
|
2774
|
+
this.bypassedUntilMonotonic = performance.now() + this.calculateJitteredCooldown();
|
|
2775
|
+
this.bypassedTotal++;
|
|
2776
|
+
}
|
|
2777
|
+
} else if (diskP95 >= this.minDiskBypassMs * 2.5 && diskP95 >= redisP95 * (this.bypassRatio * 1.5)) {
|
|
2778
|
+
if (this.stage !== 2) {
|
|
2779
|
+
this.stage = 2;
|
|
2780
|
+
this.bypassedTotal++;
|
|
2781
|
+
}
|
|
2782
|
+
} else if (diskP95 >= this.minDiskBypassMs && diskP95 >= redisP95 * this.bypassRatio) {
|
|
2783
|
+
if (this.stage !== 1) {
|
|
2784
|
+
this.stage = 1;
|
|
2785
|
+
this.bypassedTotal++;
|
|
2786
|
+
}
|
|
2787
|
+
} else {
|
|
2788
|
+
this.stage = 0;
|
|
2789
|
+
this.bypassedUntilMonotonic = 0;
|
|
2790
|
+
this.canaryInFlight = false;
|
|
2791
|
+
}
|
|
2792
|
+
}
|
|
2793
|
+
calculateJitteredCooldown() {
|
|
2794
|
+
const jitterFactor = 0.7 + Math.random() * 0.6;
|
|
2795
|
+
return this.cooldownMs * jitterFactor;
|
|
2796
|
+
}
|
|
2797
|
+
/**
|
|
2798
|
+
* Determine whether a read is permitted to check the disk tier.
|
|
2799
|
+
*
|
|
2800
|
+
* In Stage 1 and 2, sheds traffic probabilistically.
|
|
2801
|
+
* In Stage 3, blocks all reads except for a single canary probe once cooldown expires.
|
|
2802
|
+
*
|
|
2803
|
+
* @param randomOverride Optional seeded random number [0, 1) for deterministic unit testing.
|
|
2804
|
+
*/
|
|
2805
|
+
isDiskAllowed(randomOverride) {
|
|
2806
|
+
if (!this.enabled || this.disableRedis) return true;
|
|
2807
|
+
if (this.stage === 0) return true;
|
|
2808
|
+
const rand = randomOverride !== void 0 ? randomOverride : Math.random();
|
|
2809
|
+
if (this.stage === 1) {
|
|
2810
|
+
return rand > 0.25;
|
|
2811
|
+
}
|
|
2812
|
+
if (this.stage === 2) {
|
|
2813
|
+
return rand > 0.75;
|
|
2814
|
+
}
|
|
2815
|
+
const now = performance.now();
|
|
2816
|
+
if (now < this.bypassedUntilMonotonic) {
|
|
2817
|
+
return false;
|
|
2818
|
+
}
|
|
2819
|
+
if (!this.canaryInFlight) {
|
|
2820
|
+
this.canaryInFlight = true;
|
|
2821
|
+
return true;
|
|
2822
|
+
}
|
|
2823
|
+
return false;
|
|
2824
|
+
}
|
|
2825
|
+
/**
|
|
2826
|
+
* Callback invoked when the single canary read probe completes.
|
|
2827
|
+
*/
|
|
2828
|
+
onCanaryResult(success, elapsedMs) {
|
|
2829
|
+
if (!this.canaryInFlight) return;
|
|
2830
|
+
this.canaryInFlight = false;
|
|
2831
|
+
if (success && elapsedMs < this.minDiskBypassMs) {
|
|
2832
|
+
this.stage = 0;
|
|
2833
|
+
this.bypassedUntilMonotonic = 0;
|
|
2834
|
+
this.recordDisk(elapsedMs);
|
|
2835
|
+
} else {
|
|
2836
|
+
this.bypassedUntilMonotonic = performance.now() + this.calculateJitteredCooldown();
|
|
2837
|
+
this.bypassedTotal++;
|
|
2838
|
+
}
|
|
2839
|
+
}
|
|
2840
|
+
getTelemetry() {
|
|
2841
|
+
return {
|
|
2842
|
+
bypassActive: this.stage > 0,
|
|
2843
|
+
bypassStage: this.stage,
|
|
2844
|
+
diskP95Ms: Number(this.cachedDiskP95.toFixed(2)),
|
|
2845
|
+
redisP95Ms: Number(this.cachedRedisP95.toFixed(2)),
|
|
2846
|
+
redisDampened: this.redisDampened,
|
|
2847
|
+
bypassedTotal: this.bypassedTotal
|
|
2848
|
+
};
|
|
2849
|
+
}
|
|
2850
|
+
};
|
|
2851
|
+
|
|
2852
|
+
// src/utils/cgroup.ts
|
|
2853
|
+
import fs2 from "fs";
|
|
2854
|
+
import v8 from "v8";
|
|
2855
|
+
var UNBOUNDED_CGROUP_THRESHOLD = 9e18;
|
|
2856
|
+
var DEFAULT_AUTONOMOUS_L1_CEILING_BYTES = 512 * 1024 * 1024;
|
|
2857
|
+
var MIN_AUTONOMOUS_L1_FLOOR_BYTES = 16 * 1024 * 1024;
|
|
2858
|
+
function readCgroupMemoryLimit() {
|
|
2859
|
+
if (process.platform !== "linux") {
|
|
2860
|
+
return Infinity;
|
|
2861
|
+
}
|
|
2862
|
+
try {
|
|
2863
|
+
if (fs2.existsSync("/sys/fs/cgroup/memory.max")) {
|
|
2864
|
+
const raw = fs2.readFileSync("/sys/fs/cgroup/memory.max", "utf8").trim();
|
|
2865
|
+
if (raw === "max") {
|
|
2866
|
+
return Infinity;
|
|
2867
|
+
}
|
|
2868
|
+
const bytes = parseInt(raw, 10);
|
|
2869
|
+
if (Number.isFinite(bytes) && bytes > 0 && bytes < UNBOUNDED_CGROUP_THRESHOLD) {
|
|
2870
|
+
return bytes;
|
|
2871
|
+
}
|
|
2872
|
+
}
|
|
2873
|
+
} catch {
|
|
2874
|
+
}
|
|
2875
|
+
try {
|
|
2876
|
+
if (fs2.existsSync("/sys/fs/cgroup/memory/memory.limit_in_bytes")) {
|
|
2877
|
+
const raw = fs2.readFileSync("/sys/fs/cgroup/memory/memory.limit_in_bytes", "utf8").trim();
|
|
2878
|
+
const bytes = parseInt(raw, 10);
|
|
2879
|
+
if (Number.isFinite(bytes) && bytes > 0 && bytes < UNBOUNDED_CGROUP_THRESHOLD) {
|
|
2880
|
+
return bytes;
|
|
2881
|
+
}
|
|
2882
|
+
}
|
|
2883
|
+
} catch {
|
|
2884
|
+
}
|
|
2885
|
+
return Infinity;
|
|
2886
|
+
}
|
|
2887
|
+
function getV8HeapLimit() {
|
|
2888
|
+
try {
|
|
2889
|
+
const stats = v8.getHeapStatistics();
|
|
2890
|
+
if (stats && Number.isFinite(stats.heap_size_limit) && stats.heap_size_limit > 0) {
|
|
2891
|
+
return stats.heap_size_limit;
|
|
2892
|
+
}
|
|
2893
|
+
} catch {
|
|
2894
|
+
}
|
|
2895
|
+
return Infinity;
|
|
2896
|
+
}
|
|
2897
|
+
function resolveAutonomousL1MaxBytes(options) {
|
|
2898
|
+
const cgroup = options?.cgroupLimit !== void 0 ? options.cgroupLimit : readCgroupMemoryLimit();
|
|
2899
|
+
const v8Limit = options?.v8HeapLimit !== void 0 ? options.v8HeapLimit : getV8HeapLimit();
|
|
2900
|
+
const ceiling = options?.defaultCeilingBytes ?? DEFAULT_AUTONOMOUS_L1_CEILING_BYTES;
|
|
2901
|
+
const cgroupCap = Number.isFinite(cgroup) && cgroup > 0 ? cgroup * 0.4 : Infinity;
|
|
2902
|
+
const v8Cap = Number.isFinite(v8Limit) && v8Limit > 0 ? v8Limit * 0.5 : Infinity;
|
|
2903
|
+
const resolved = Math.min(cgroupCap, v8Cap, ceiling);
|
|
2904
|
+
if (!Number.isFinite(resolved) || resolved <= 0) {
|
|
2905
|
+
return ceiling;
|
|
2906
|
+
}
|
|
2907
|
+
return Math.max(MIN_AUTONOMOUS_L1_FLOOR_BYTES, Math.floor(resolved));
|
|
2908
|
+
}
|
|
2909
|
+
|
|
2910
|
+
// src/adapters/auto-pipeliner.ts
|
|
2911
|
+
var AutoPipeliner = class {
|
|
2912
|
+
constructor(client, options) {
|
|
2913
|
+
this.client = client;
|
|
2914
|
+
this.maxBatchSize = options?.maxBatchSize ?? 100;
|
|
2915
|
+
this.enabled = options?.enabled ?? true;
|
|
2916
|
+
}
|
|
2917
|
+
client;
|
|
2918
|
+
maxBatchSize;
|
|
2919
|
+
enabled;
|
|
2920
|
+
queue = [];
|
|
2921
|
+
scheduled = false;
|
|
2922
|
+
inFlight = false;
|
|
2923
|
+
statsInternal = {
|
|
2924
|
+
batchesDispatched: 0,
|
|
2925
|
+
operationsBatched: 0
|
|
2926
|
+
};
|
|
2927
|
+
get stats() {
|
|
2928
|
+
return {
|
|
2929
|
+
batchesDispatched: this.statsInternal.batchesDispatched,
|
|
2930
|
+
operationsBatched: this.statsInternal.operationsBatched,
|
|
2931
|
+
pendingQueueSize: this.queue.length
|
|
2932
|
+
};
|
|
2933
|
+
}
|
|
2934
|
+
async get(key) {
|
|
2935
|
+
if (!this.enabled || !this.supportsPipelines()) {
|
|
2936
|
+
return this.client.get(key);
|
|
2937
|
+
}
|
|
2938
|
+
return new Promise((resolve, reject) => {
|
|
2939
|
+
this.enqueue({ type: "get", key, resolve, reject });
|
|
2940
|
+
});
|
|
2941
|
+
}
|
|
2942
|
+
async setex(key, seconds, value) {
|
|
2943
|
+
if (!this.enabled || !this.supportsPipelines()) {
|
|
2944
|
+
if (typeof this.client.setex === "function") {
|
|
2945
|
+
await this.client.setex(key, seconds, value);
|
|
2946
|
+
} else {
|
|
2947
|
+
await this.client.set(key, value, "EX", seconds);
|
|
2948
|
+
}
|
|
2949
|
+
return;
|
|
2950
|
+
}
|
|
2951
|
+
return new Promise((resolve, reject) => {
|
|
2952
|
+
this.enqueue({ type: "setex", key, seconds, value, resolve, reject });
|
|
2953
|
+
});
|
|
2954
|
+
}
|
|
2955
|
+
async del(...keys) {
|
|
2956
|
+
if (keys.length === 0) return 0;
|
|
2957
|
+
if (!this.enabled || !this.supportsPipelines()) {
|
|
2958
|
+
return this.client.del(...keys);
|
|
2959
|
+
}
|
|
2960
|
+
return new Promise((resolve, reject) => {
|
|
2961
|
+
this.enqueue({ type: "del", keys, resolve, reject });
|
|
2962
|
+
});
|
|
2963
|
+
}
|
|
2964
|
+
supportsPipelines() {
|
|
2965
|
+
return Boolean(
|
|
2966
|
+
typeof this.client?.pipeline === "function" || typeof this.client?.multi === "function"
|
|
2967
|
+
);
|
|
2968
|
+
}
|
|
2969
|
+
enqueue(op) {
|
|
2970
|
+
this.queue.push(op);
|
|
2971
|
+
if (this.queue.length >= this.maxBatchSize) {
|
|
2972
|
+
void this.flush();
|
|
2973
|
+
return;
|
|
2974
|
+
}
|
|
2975
|
+
if (!this.scheduled) {
|
|
2976
|
+
this.scheduled = true;
|
|
2977
|
+
queueMicrotask(() => {
|
|
2978
|
+
this.scheduled = false;
|
|
2979
|
+
void this.flush();
|
|
2980
|
+
});
|
|
2981
|
+
}
|
|
2982
|
+
}
|
|
2983
|
+
async flush() {
|
|
2984
|
+
if (this.queue.length === 0) return;
|
|
2985
|
+
const batch = this.queue;
|
|
2986
|
+
this.queue = [];
|
|
2987
|
+
this.scheduled = false;
|
|
2988
|
+
this.statsInternal.batchesDispatched++;
|
|
2989
|
+
this.statsInternal.operationsBatched += batch.length;
|
|
2990
|
+
const pipe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
|
|
2991
|
+
for (const op of batch) {
|
|
2992
|
+
switch (op.type) {
|
|
2993
|
+
case "get":
|
|
2994
|
+
pipe.get(op.key);
|
|
2995
|
+
break;
|
|
2996
|
+
case "setex":
|
|
2997
|
+
pipe.setex(op.key, op.seconds, op.value);
|
|
2998
|
+
break;
|
|
2999
|
+
case "del":
|
|
3000
|
+
pipe.del(...op.keys);
|
|
3001
|
+
break;
|
|
3002
|
+
}
|
|
3003
|
+
}
|
|
3004
|
+
try {
|
|
3005
|
+
const results = await pipe.exec();
|
|
3006
|
+
if (!results) {
|
|
3007
|
+
for (const op of batch) {
|
|
3008
|
+
if (op.type === "get") op.resolve(null);
|
|
3009
|
+
else if (op.type === "del") op.resolve(0);
|
|
3010
|
+
else op.resolve();
|
|
3011
|
+
}
|
|
3012
|
+
return;
|
|
3013
|
+
}
|
|
3014
|
+
for (let i = 0; i < batch.length; i++) {
|
|
3015
|
+
const op = batch[i];
|
|
3016
|
+
const resTuple = results[i];
|
|
3017
|
+
if (!resTuple) {
|
|
3018
|
+
if (op.type === "get") op.resolve(null);
|
|
3019
|
+
else if (op.type === "del") op.resolve(0);
|
|
3020
|
+
else op.resolve();
|
|
3021
|
+
continue;
|
|
3022
|
+
}
|
|
3023
|
+
const [err, val] = resTuple;
|
|
3024
|
+
if (err) {
|
|
3025
|
+
op.reject(err instanceof Error ? err : new Error(String(err)));
|
|
3026
|
+
} else {
|
|
3027
|
+
if (op.type === "get") {
|
|
3028
|
+
op.resolve(val != null ? String(val) : null);
|
|
3029
|
+
} else if (op.type === "del") {
|
|
3030
|
+
op.resolve(typeof val === "number" ? val : Number(val) || 0);
|
|
3031
|
+
} else {
|
|
3032
|
+
op.resolve();
|
|
3033
|
+
}
|
|
3034
|
+
}
|
|
3035
|
+
}
|
|
3036
|
+
} catch (err) {
|
|
3037
|
+
for (const op of batch) {
|
|
3038
|
+
op.reject(err instanceof Error ? err : new Error(String(err)));
|
|
3039
|
+
}
|
|
3040
|
+
}
|
|
3041
|
+
}
|
|
3042
|
+
};
|
|
3043
|
+
|
|
3044
|
+
// src/ipc-telemetry.ts
|
|
3045
|
+
import net from "net";
|
|
3046
|
+
import fs3 from "fs";
|
|
3047
|
+
import path2 from "path";
|
|
3048
|
+
function resolveIpcSocketPath(id = process.pid) {
|
|
3049
|
+
if (process.platform === "win32") {
|
|
3050
|
+
return `\\\\.\\pipe\\tricache-${id}`;
|
|
3051
|
+
}
|
|
3052
|
+
const dir = process.env.TMPDIR || "/tmp";
|
|
3053
|
+
return path2.join(dir, `tricache-${id}.sock`);
|
|
3054
|
+
}
|
|
3055
|
+
var IpcTelemetryServer = class {
|
|
3056
|
+
constructor(cache, customSocketPath) {
|
|
3057
|
+
this.cache = cache;
|
|
3058
|
+
this.socketPath = customSocketPath || resolveIpcSocketPath();
|
|
3059
|
+
}
|
|
3060
|
+
cache;
|
|
3061
|
+
server = null;
|
|
3062
|
+
socketPath;
|
|
3063
|
+
_closed = false;
|
|
3064
|
+
_exitHandler = null;
|
|
3065
|
+
_sigintHandler = null;
|
|
3066
|
+
_sigtermHandler = null;
|
|
3067
|
+
/**
|
|
3068
|
+
* Start listening on the IPC socket / pipe.
|
|
3069
|
+
*/
|
|
3070
|
+
async start() {
|
|
3071
|
+
if (this.server && this.server.listening) return;
|
|
3072
|
+
if (process.platform !== "win32" && fs3.existsSync(this.socketPath)) {
|
|
3073
|
+
await new Promise((resolve) => {
|
|
3074
|
+
const testSocket = net.createConnection(this.socketPath);
|
|
3075
|
+
testSocket.once("connect", () => {
|
|
3076
|
+
testSocket.destroy();
|
|
3077
|
+
resolve();
|
|
3078
|
+
});
|
|
3079
|
+
testSocket.once("error", () => {
|
|
3080
|
+
testSocket.destroy();
|
|
3081
|
+
try {
|
|
3082
|
+
fs3.unlinkSync(this.socketPath);
|
|
3083
|
+
} catch {
|
|
3084
|
+
}
|
|
3085
|
+
resolve();
|
|
3086
|
+
});
|
|
3087
|
+
});
|
|
3088
|
+
}
|
|
3089
|
+
this.server = net.createServer((socket) => {
|
|
3090
|
+
let buffer = "";
|
|
3091
|
+
socket.on("data", (chunk) => {
|
|
3092
|
+
buffer += chunk.toString("utf8");
|
|
3093
|
+
let newlineIndex;
|
|
3094
|
+
while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
|
|
3095
|
+
const line = buffer.slice(0, newlineIndex).trim();
|
|
3096
|
+
buffer = buffer.slice(newlineIndex + 1);
|
|
3097
|
+
if (!line) continue;
|
|
3098
|
+
setImmediate(() => {
|
|
3099
|
+
if (socket.destroyed) return;
|
|
3100
|
+
try {
|
|
3101
|
+
let cmd = line;
|
|
3102
|
+
try {
|
|
3103
|
+
const parsed = JSON.parse(line);
|
|
3104
|
+
if (parsed && typeof parsed.cmd === "string") {
|
|
3105
|
+
cmd = parsed.cmd;
|
|
3106
|
+
}
|
|
3107
|
+
} catch {
|
|
3108
|
+
}
|
|
3109
|
+
if (cmd === "PING") {
|
|
3110
|
+
socket.write(JSON.stringify({ pong: true, timestamp: Date.now() }) + "\n");
|
|
3111
|
+
return;
|
|
3112
|
+
}
|
|
3113
|
+
if (cmd === "GET_METRICS" || cmd === "INSPECT") {
|
|
3114
|
+
const payload = this.getSnapshot();
|
|
3115
|
+
const serialized = JSON.stringify(payload) + "\n";
|
|
3116
|
+
socket.write(serialized);
|
|
3117
|
+
return;
|
|
3118
|
+
}
|
|
3119
|
+
socket.write(JSON.stringify({ error: `Unknown command: ${cmd}` }) + "\n");
|
|
3120
|
+
} catch (err) {
|
|
3121
|
+
if (!socket.destroyed) {
|
|
3122
|
+
socket.write(JSON.stringify({ error: err.message }) + "\n");
|
|
3123
|
+
}
|
|
3124
|
+
}
|
|
3125
|
+
});
|
|
3126
|
+
}
|
|
3127
|
+
});
|
|
3128
|
+
socket.on("error", () => {
|
|
3129
|
+
});
|
|
3130
|
+
});
|
|
3131
|
+
await new Promise((resolve, reject) => {
|
|
3132
|
+
this.server.once("error", reject);
|
|
3133
|
+
this.server.listen(this.socketPath, () => {
|
|
3134
|
+
this.server.removeListener("error", reject);
|
|
3135
|
+
resolve();
|
|
3136
|
+
});
|
|
3137
|
+
});
|
|
3138
|
+
this._exitHandler = () => this._unlinkSocket();
|
|
3139
|
+
this._sigintHandler = () => {
|
|
3140
|
+
this._unlinkSocket();
|
|
3141
|
+
process.exit(0);
|
|
3142
|
+
};
|
|
3143
|
+
this._sigtermHandler = () => {
|
|
3144
|
+
this._unlinkSocket();
|
|
3145
|
+
process.exit(0);
|
|
3146
|
+
};
|
|
3147
|
+
process.once("exit", this._exitHandler);
|
|
3148
|
+
process.once("SIGINT", this._sigintHandler);
|
|
3149
|
+
process.once("SIGTERM", this._sigtermHandler);
|
|
3150
|
+
}
|
|
3151
|
+
/**
|
|
3152
|
+
* Build a complete telemetry snapshot from the underlying cache provider.
|
|
3153
|
+
*/
|
|
3154
|
+
getSnapshot() {
|
|
3155
|
+
const metrics = this.cache.metrics();
|
|
3156
|
+
const stats = typeof this.cache.stats === "function" ? this.cache.stats() : void 0;
|
|
3157
|
+
const hotKeys = typeof this.cache.hotKeys === "function" ? this.cache.hotKeys(10) : void 0;
|
|
3158
|
+
const health = typeof this.cache.health === "function" ? this.cache.health() : void 0;
|
|
3159
|
+
const l1MaxBytes = this.cache.options?.l1MaxBytes ?? metrics.l1?.maxBytes;
|
|
3160
|
+
return {
|
|
3161
|
+
pid: process.pid,
|
|
3162
|
+
uptimeMs: metrics.uptimeMs,
|
|
3163
|
+
timestamp: Date.now(),
|
|
3164
|
+
namespace: this.cache.options?.namespace || metrics.namespace,
|
|
3165
|
+
l1MaxBytes,
|
|
3166
|
+
metrics,
|
|
3167
|
+
stats,
|
|
3168
|
+
hotKeys,
|
|
3169
|
+
health
|
|
3170
|
+
};
|
|
3171
|
+
}
|
|
3172
|
+
_unlinkSocket() {
|
|
3173
|
+
if (this._closed) return;
|
|
3174
|
+
this._closed = true;
|
|
3175
|
+
try {
|
|
3176
|
+
this.server?.close();
|
|
3177
|
+
} catch {
|
|
3178
|
+
}
|
|
3179
|
+
if (process.platform !== "win32") {
|
|
3180
|
+
try {
|
|
3181
|
+
if (fs3.existsSync(this.socketPath)) {
|
|
3182
|
+
fs3.unlinkSync(this.socketPath);
|
|
3183
|
+
}
|
|
3184
|
+
} catch {
|
|
3185
|
+
}
|
|
3186
|
+
}
|
|
3187
|
+
}
|
|
3188
|
+
/**
|
|
3189
|
+
* Gracefully close the IPC telemetry server and clean up handlers and sockets.
|
|
3190
|
+
*/
|
|
3191
|
+
async close() {
|
|
3192
|
+
if (this._exitHandler) {
|
|
3193
|
+
process.removeListener("exit", this._exitHandler);
|
|
3194
|
+
this._exitHandler = null;
|
|
3195
|
+
}
|
|
3196
|
+
if (this._sigintHandler) {
|
|
3197
|
+
process.removeListener("SIGINT", this._sigintHandler);
|
|
3198
|
+
this._sigintHandler = null;
|
|
3199
|
+
}
|
|
3200
|
+
if (this._sigtermHandler) {
|
|
3201
|
+
process.removeListener("SIGTERM", this._sigtermHandler);
|
|
3202
|
+
this._sigtermHandler = null;
|
|
3203
|
+
}
|
|
3204
|
+
this._unlinkSocket();
|
|
3205
|
+
return new Promise((resolve) => {
|
|
3206
|
+
if (!this.server || !this.server.listening) {
|
|
3207
|
+
resolve();
|
|
3208
|
+
return;
|
|
3209
|
+
}
|
|
3210
|
+
this.server.close(() => resolve());
|
|
3211
|
+
});
|
|
3212
|
+
}
|
|
3213
|
+
get isListening() {
|
|
3214
|
+
return Boolean(this.server && this.server.listening);
|
|
3215
|
+
}
|
|
3216
|
+
};
|
|
3217
|
+
var IpcTelemetryClient = class {
|
|
3218
|
+
socketPath;
|
|
3219
|
+
constructor(socketPath) {
|
|
3220
|
+
this.socketPath = socketPath || resolveIpcSocketPath();
|
|
3221
|
+
}
|
|
3222
|
+
/**
|
|
3223
|
+
* Fetch a live metrics snapshot from the IPC server.
|
|
3224
|
+
*/
|
|
3225
|
+
async getMetrics(timeoutMs = 3e3) {
|
|
3226
|
+
return new Promise((resolve, reject) => {
|
|
3227
|
+
const socket = net.createConnection(this.socketPath);
|
|
3228
|
+
let buffer = "";
|
|
3229
|
+
let timer = setTimeout(() => {
|
|
3230
|
+
socket.destroy();
|
|
3231
|
+
reject(new Error(`IPC connection timeout (${timeoutMs}ms) to ${this.socketPath}`));
|
|
3232
|
+
}, timeoutMs);
|
|
3233
|
+
socket.once("connect", () => {
|
|
3234
|
+
socket.write("GET_METRICS\n");
|
|
3235
|
+
});
|
|
3236
|
+
socket.on("data", (chunk) => {
|
|
3237
|
+
buffer += chunk.toString("utf8");
|
|
3238
|
+
const newlineIdx = buffer.indexOf("\n");
|
|
3239
|
+
if (newlineIdx !== -1) {
|
|
3240
|
+
if (timer) {
|
|
3241
|
+
clearTimeout(timer);
|
|
3242
|
+
timer = null;
|
|
3243
|
+
}
|
|
3244
|
+
const line = buffer.slice(0, newlineIdx).trim();
|
|
3245
|
+
socket.end();
|
|
3246
|
+
try {
|
|
3247
|
+
const data = JSON.parse(line);
|
|
3248
|
+
if (data.error) {
|
|
3249
|
+
reject(new Error(data.error));
|
|
3250
|
+
} else {
|
|
3251
|
+
resolve(data);
|
|
3252
|
+
}
|
|
3253
|
+
} catch (e) {
|
|
3254
|
+
reject(new Error(`Failed to parse IPC payload: ${e.message}`));
|
|
3255
|
+
}
|
|
3256
|
+
}
|
|
3257
|
+
});
|
|
3258
|
+
socket.once("error", (err) => {
|
|
3259
|
+
if (timer) {
|
|
3260
|
+
clearTimeout(timer);
|
|
3261
|
+
timer = null;
|
|
3262
|
+
}
|
|
3263
|
+
reject(err);
|
|
3264
|
+
});
|
|
3265
|
+
});
|
|
3266
|
+
}
|
|
3267
|
+
/**
|
|
3268
|
+
* Send a ping over the IPC bridge and measure round-trip latency.
|
|
3269
|
+
*/
|
|
3270
|
+
async ping(timeoutMs = 1e3) {
|
|
3271
|
+
const start = Date.now();
|
|
3272
|
+
return new Promise((resolve, reject) => {
|
|
3273
|
+
const socket = net.createConnection(this.socketPath);
|
|
3274
|
+
let timer = setTimeout(() => {
|
|
3275
|
+
socket.destroy();
|
|
3276
|
+
reject(new Error(`IPC ping timeout (${timeoutMs}ms)`));
|
|
3277
|
+
}, timeoutMs);
|
|
3278
|
+
socket.once("connect", () => {
|
|
3279
|
+
socket.write("PING\n");
|
|
3280
|
+
});
|
|
3281
|
+
socket.on("data", () => {
|
|
3282
|
+
if (timer) {
|
|
3283
|
+
clearTimeout(timer);
|
|
3284
|
+
timer = null;
|
|
3285
|
+
}
|
|
3286
|
+
socket.end();
|
|
3287
|
+
resolve(Date.now() - start);
|
|
3288
|
+
});
|
|
3289
|
+
socket.once("error", (err) => {
|
|
3290
|
+
if (timer) {
|
|
3291
|
+
clearTimeout(timer);
|
|
3292
|
+
timer = null;
|
|
3293
|
+
}
|
|
3294
|
+
reject(err);
|
|
3295
|
+
});
|
|
3296
|
+
});
|
|
3297
|
+
}
|
|
3298
|
+
};
|
|
3299
|
+
async function findActiveSockets() {
|
|
3300
|
+
const active = [];
|
|
3301
|
+
if (process.platform === "win32") {
|
|
3302
|
+
const currentPipe = resolveIpcSocketPath(process.pid);
|
|
3303
|
+
const client = new IpcTelemetryClient(currentPipe);
|
|
3304
|
+
try {
|
|
3305
|
+
await client.ping(100);
|
|
3306
|
+
active.push(currentPipe);
|
|
3307
|
+
} catch {
|
|
3308
|
+
}
|
|
3309
|
+
try {
|
|
3310
|
+
const { execFileSync } = await import("child_process");
|
|
3311
|
+
const stdout = execFileSync(
|
|
3312
|
+
"powershell.exe",
|
|
3313
|
+
["-NoProfile", "-NonInteractive", "-Command", '[System.IO.Directory]::GetFiles("\\\\.\\pipe\\") | Where-Object { $_ -like "*tricache-*" }'],
|
|
3314
|
+
{ timeout: 1500, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }
|
|
3315
|
+
);
|
|
3316
|
+
const candidates = stdout.split(/\r?\n/).map((name) => name.trim()).filter((name) => name.length > 0 && !active.includes(name));
|
|
3317
|
+
await Promise.all(
|
|
3318
|
+
candidates.map(async (pipePath) => {
|
|
3319
|
+
const testClient = new IpcTelemetryClient(pipePath);
|
|
3320
|
+
try {
|
|
3321
|
+
await testClient.ping(100);
|
|
3322
|
+
active.push(pipePath);
|
|
3323
|
+
} catch {
|
|
3324
|
+
}
|
|
3325
|
+
})
|
|
3326
|
+
);
|
|
3327
|
+
} catch {
|
|
3328
|
+
}
|
|
3329
|
+
return active;
|
|
3330
|
+
}
|
|
3331
|
+
const dir = process.env.TMPDIR || "/tmp";
|
|
3332
|
+
try {
|
|
3333
|
+
if (!fs3.existsSync(dir)) return active;
|
|
3334
|
+
const entries = fs3.readdirSync(dir);
|
|
3335
|
+
const candidates = entries.filter((name) => name.startsWith("tricache-") && name.endsWith(".sock")).map((name) => path2.join(dir, name));
|
|
3336
|
+
await Promise.all(
|
|
3337
|
+
candidates.map(async (sockPath) => {
|
|
3338
|
+
const client = new IpcTelemetryClient(sockPath);
|
|
3339
|
+
try {
|
|
3340
|
+
await client.ping(100);
|
|
3341
|
+
active.push(sockPath);
|
|
3342
|
+
} catch {
|
|
3343
|
+
}
|
|
3344
|
+
})
|
|
3345
|
+
);
|
|
3346
|
+
} catch {
|
|
3347
|
+
}
|
|
3348
|
+
return active;
|
|
3349
|
+
}
|
|
3350
|
+
function renderProgressBar(ratio, width = 18) {
|
|
3351
|
+
const clamped = Math.max(0, Math.min(1, isNaN(ratio) ? 0 : ratio));
|
|
3352
|
+
const filled = Math.round(clamped * width);
|
|
3353
|
+
const empty = width - filled;
|
|
3354
|
+
return "\u2588".repeat(filled) + "\u2591".repeat(empty);
|
|
3355
|
+
}
|
|
3356
|
+
function formatBytes(bytes) {
|
|
3357
|
+
if (!bytes || isNaN(bytes) || bytes < 0) return "0 B";
|
|
3358
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
3359
|
+
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
|
3360
|
+
if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
3361
|
+
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
|
|
3362
|
+
}
|
|
3363
|
+
function formatNumber(n) {
|
|
3364
|
+
return (n ?? 0).toLocaleString();
|
|
3365
|
+
}
|
|
3366
|
+
function formatDuration(ms) {
|
|
3367
|
+
if (ms < 1e3) return `${ms}ms`;
|
|
3368
|
+
const s = Math.floor(ms / 1e3);
|
|
3369
|
+
if (s < 60) return `${s}s`;
|
|
3370
|
+
const m = Math.floor(s / 60);
|
|
3371
|
+
const remS = s % 60;
|
|
3372
|
+
if (m < 60) return `${m}m ${remS}s`;
|
|
3373
|
+
const h = Math.floor(m / 60);
|
|
3374
|
+
const remM = m % 60;
|
|
3375
|
+
return `${h}h ${remM}m`;
|
|
3376
|
+
}
|
|
3377
|
+
function renderTopDashboard(payload) {
|
|
3378
|
+
const m = payload.metrics;
|
|
3379
|
+
const gets = m.gets;
|
|
3380
|
+
const l1Max = payload.l1MaxBytes || 200 * 1024 * 1024;
|
|
3381
|
+
const l1Used = m.l1.sizeBytes;
|
|
3382
|
+
const l1Pct = l1Max > 0 ? l1Used / l1Max : 0;
|
|
3383
|
+
const uptime = formatDuration(payload.uptimeMs);
|
|
3384
|
+
const ns = payload.namespace || "(default)";
|
|
3385
|
+
const pct = (r) => `${((r || 0) * 100).toFixed(1)}%`;
|
|
3386
|
+
const lines = [];
|
|
3387
|
+
lines.push("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557");
|
|
3388
|
+
lines.push(`\u2551 TriCache Monitor [PID: ${String(payload.pid).padEnd(6)}] Uptime: ${uptime.padEnd(8)} Namespace: ${ns.padEnd(16)}\u2551`);
|
|
3389
|
+
lines.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563");
|
|
3390
|
+
lines.push(`\u2551 Hit Ratios & Tier Breakdown (Total Gets: ${formatNumber(gets.total).padEnd(12)}) \u2551`);
|
|
3391
|
+
lines.push(`\u2551 L1 (RAM): [${renderProgressBar(gets.l1HitRate)}] ${pct(gets.l1HitRate).padStart(6)} (${formatNumber(gets.l1Hits).padStart(8)} hits) \u2551`);
|
|
3392
|
+
lines.push(`\u2551 L1.5(Disk): [${renderProgressBar(gets.diskHitRate)}] ${pct(gets.diskHitRate).padStart(6)} (${formatNumber(gets.diskHits).padStart(8)} hits) \u2551`);
|
|
3393
|
+
lines.push(`\u2551 L2 (Redis): [${renderProgressBar(gets.l2HitRate)}] ${pct(gets.l2HitRate).padStart(6)} (${formatNumber(gets.l2Hits).padStart(8)} hits) \u2551`);
|
|
3394
|
+
lines.push(`\u2551 Misses: [${renderProgressBar(gets.fetchRate)}] ${pct(gets.fetchRate).padStart(6)} (${formatNumber(gets.fetches).padStart(8)} fetches) \u2551`);
|
|
3395
|
+
lines.push(`\u2551 Stampedes Saved: ${formatNumber(gets.stampedePrevented).padEnd(8)} coalesced concurrent requests \u2551`);
|
|
3396
|
+
lines.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563");
|
|
3397
|
+
lines.push(`\u2551 Memory & Storage Headroom \u2551`);
|
|
3398
|
+
lines.push(`\u2551 L1 Memory: [${renderProgressBar(l1Pct)}] ${formatBytes(l1Used).padStart(8)} / ${formatBytes(l1Max).padEnd(8)} (${formatNumber(m.l1.entries).padStart(6)} entries) \u2551`);
|
|
3399
|
+
const diskFiles = m.disk?.files ?? 0;
|
|
3400
|
+
const diskKB = m.disk?.sizeKB ?? 0;
|
|
3401
|
+
const diskMaxKB = m.disk?.maxKB ?? 0;
|
|
3402
|
+
lines.push(`\u2551 Disk Spill: ${formatBytes(diskKB * 1024).padStart(8)} / ${formatBytes(diskMaxKB * 1024).padEnd(8)} (${formatNumber(diskFiles).padStart(6)} files) \u2551`);
|
|
3403
|
+
lines.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563");
|
|
3404
|
+
lines.push(`\u2551 Protection & Health Diagnostics \u2551`);
|
|
3405
|
+
const watchdog = m.disk?.latencyWatchdog;
|
|
3406
|
+
const bypassStage = watchdog ? `Stage ${watchdog.bypassStage} (${watchdog.bypassActive ? "ACTIVE" : "Normal"})` : "Stage 0 (Normal)";
|
|
3407
|
+
const cbState = m.l2CircuitBreaker?.state || "closed";
|
|
3408
|
+
lines.push(`\u2551 Watchdog: ${bypassStage.padEnd(20)} L2 Circuit Breaker: ${cbState.padEnd(20)}\u2551`);
|
|
3409
|
+
if (watchdog) {
|
|
3410
|
+
const diskP95 = `${watchdog.diskP95Ms.toFixed(2)}ms`;
|
|
3411
|
+
const redisP95 = `${watchdog.redisP95Ms.toFixed(2)}ms`;
|
|
3412
|
+
lines.push(`\u2551 Disk p95: ${diskP95.padEnd(10)} Redis p95: ${redisP95.padEnd(10)} Bypassed: ${formatNumber(watchdog.bypassedTotal).padEnd(16)}\u2551`);
|
|
3413
|
+
}
|
|
3414
|
+
const oomEvict = m.oom?.evictions ?? 0;
|
|
3415
|
+
lines.push(`\u2551 OOM Evictions: ${formatNumber(oomEvict).padEnd(6)} SWR Revalidations: ${formatNumber(m.revalidations?.total ?? 0).padEnd(14)} \u2551`);
|
|
3416
|
+
lines.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563");
|
|
3417
|
+
lines.push(`\u2551 \u{1F525} Top Hot Keys (Count-Min Sketch) \u2551`);
|
|
3418
|
+
if (!payload.hotKeys || payload.hotKeys.length === 0) {
|
|
3419
|
+
lines.push("\u2551 (no hot keys recorded yet) \u2551");
|
|
3420
|
+
} else {
|
|
3421
|
+
payload.hotKeys.slice(0, 5).forEach(({ key, hits, sizeBytes }, idx) => {
|
|
3422
|
+
const displayKey = key.length > 34 ? `${key.slice(0, 31)}...` : key;
|
|
3423
|
+
const hitStr = `${formatNumber(hits)} hits`;
|
|
3424
|
+
const sizeStr = formatBytes(sizeBytes);
|
|
3425
|
+
const row = ` ${idx + 1}. ${displayKey.padEnd(36)} ${hitStr.padStart(14)} (${sizeStr})`;
|
|
3426
|
+
lines.push(`\u2551${row.padEnd(86)}\u2551`);
|
|
3427
|
+
});
|
|
3428
|
+
}
|
|
3429
|
+
lines.push("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D");
|
|
3430
|
+
return lines.join("\n");
|
|
3431
|
+
}
|
|
3432
|
+
|
|
1866
3433
|
// src/cache-service.ts
|
|
1867
3434
|
var LUA_COMPARE_AND_DELETE = `
|
|
1868
3435
|
local currentTs = redis.call('HGET', KEYS[1], 't')
|
|
@@ -1907,7 +3474,7 @@ var L2CircuitBreaker = class {
|
|
|
1907
3474
|
cooldownMs;
|
|
1908
3475
|
state = 0 /* CLOSED */;
|
|
1909
3476
|
failures = 0;
|
|
1910
|
-
openedAt =
|
|
3477
|
+
openedAt = performance.now();
|
|
1911
3478
|
/** True while the single permitted HALF_OPEN probe is in flight. */
|
|
1912
3479
|
probing = false;
|
|
1913
3480
|
/**
|
|
@@ -1923,7 +3490,8 @@ var L2CircuitBreaker = class {
|
|
|
1923
3490
|
this.probing = true;
|
|
1924
3491
|
return true;
|
|
1925
3492
|
}
|
|
1926
|
-
|
|
3493
|
+
const now = this.openedAt > 1e12 ? Date.now() : performance.now();
|
|
3494
|
+
if (now - this.openedAt >= this.cooldownMs) {
|
|
1927
3495
|
this.state = 2 /* HALF_OPEN */;
|
|
1928
3496
|
this.probing = true;
|
|
1929
3497
|
return true;
|
|
@@ -1942,7 +3510,7 @@ var L2CircuitBreaker = class {
|
|
|
1942
3510
|
this.probing = false;
|
|
1943
3511
|
if (this.state === 2 /* HALF_OPEN */ || this.failures >= this.threshold) {
|
|
1944
3512
|
this.state = 1 /* OPEN */;
|
|
1945
|
-
this.openedAt =
|
|
3513
|
+
this.openedAt = performance.now();
|
|
1946
3514
|
this.failures = 0;
|
|
1947
3515
|
}
|
|
1948
3516
|
}
|
|
@@ -2059,9 +3627,86 @@ function detectServerlessRuntime() {
|
|
|
2059
3627
|
if (process.env["VERCEL"]) return "Vercel";
|
|
2060
3628
|
return null;
|
|
2061
3629
|
}
|
|
3630
|
+
var ProcessTerminationBus = class {
|
|
3631
|
+
static instances = /* @__PURE__ */ new Set();
|
|
3632
|
+
static registered = false;
|
|
3633
|
+
static sigtermHandler = null;
|
|
3634
|
+
static sigintHandler = null;
|
|
3635
|
+
static register(instance) {
|
|
3636
|
+
this.instances.add(instance);
|
|
3637
|
+
if (!this.registered) {
|
|
3638
|
+
this.registered = true;
|
|
3639
|
+
this.sigtermHandler = () => {
|
|
3640
|
+
for (const inst of this.instances) {
|
|
3641
|
+
try {
|
|
3642
|
+
inst._triggerShutdown();
|
|
3643
|
+
} catch {
|
|
3644
|
+
}
|
|
3645
|
+
}
|
|
3646
|
+
};
|
|
3647
|
+
this.sigintHandler = () => {
|
|
3648
|
+
for (const inst of this.instances) {
|
|
3649
|
+
try {
|
|
3650
|
+
inst._triggerShutdown();
|
|
3651
|
+
} catch {
|
|
3652
|
+
}
|
|
3653
|
+
}
|
|
3654
|
+
};
|
|
3655
|
+
process.on("SIGTERM", this.sigtermHandler);
|
|
3656
|
+
process.on("SIGINT", this.sigintHandler);
|
|
3657
|
+
}
|
|
3658
|
+
}
|
|
3659
|
+
static unregister(instance) {
|
|
3660
|
+
this.instances.delete(instance);
|
|
3661
|
+
if (this.instances.size === 0 && this.registered) {
|
|
3662
|
+
if (this.sigtermHandler) process.removeListener("SIGTERM", this.sigtermHandler);
|
|
3663
|
+
if (this.sigintHandler) process.removeListener("SIGINT", this.sigintHandler);
|
|
3664
|
+
this.sigtermHandler = null;
|
|
3665
|
+
this.sigintHandler = null;
|
|
3666
|
+
this.registered = false;
|
|
3667
|
+
}
|
|
3668
|
+
}
|
|
3669
|
+
/**
|
|
3670
|
+
* Flushes snapshots across all active registered cache instances concurrently.
|
|
3671
|
+
* Awaits both local disk and remote cloud snapshot uploads with timeout protection.
|
|
3672
|
+
*
|
|
3673
|
+
* @param timeoutMs Timeout in milliseconds per instance before aborting slow flushes. Default: 8000ms.
|
|
3674
|
+
*/
|
|
3675
|
+
static async flushAll(timeoutMs = 8e3) {
|
|
3676
|
+
if (this.instances.size === 0) return;
|
|
3677
|
+
const tasks = Array.from(this.instances).map((inst) => inst.flushSnapshotOnShutdown(timeoutMs));
|
|
3678
|
+
await Promise.allSettled(tasks);
|
|
3679
|
+
}
|
|
3680
|
+
/** For testing diagnostics and assertions */
|
|
3681
|
+
static get size() {
|
|
3682
|
+
return this.instances.size;
|
|
3683
|
+
}
|
|
3684
|
+
static get isRegistered() {
|
|
3685
|
+
return this.registered;
|
|
3686
|
+
}
|
|
3687
|
+
};
|
|
3688
|
+
function isPlainObject(item) {
|
|
3689
|
+
return typeof item === "object" && item !== null && item.constructor === Object;
|
|
3690
|
+
}
|
|
3691
|
+
function deepMergeOptions(base, overrides) {
|
|
3692
|
+
if (!overrides) return { ...base };
|
|
3693
|
+
const output = { ...base };
|
|
3694
|
+
for (const key of Object.keys(overrides)) {
|
|
3695
|
+
const sourceVal = overrides[key];
|
|
3696
|
+
if (sourceVal === void 0) continue;
|
|
3697
|
+
const targetVal = output[key];
|
|
3698
|
+
if (isPlainObject(targetVal) && isPlainObject(sourceVal)) {
|
|
3699
|
+
output[key] = deepMergeOptions(targetVal, sourceVal);
|
|
3700
|
+
} else {
|
|
3701
|
+
output[key] = sourceVal;
|
|
3702
|
+
}
|
|
3703
|
+
}
|
|
3704
|
+
return output;
|
|
3705
|
+
}
|
|
2062
3706
|
var CacheService = class _CacheService {
|
|
2063
3707
|
logger;
|
|
2064
3708
|
enc;
|
|
3709
|
+
codec;
|
|
2065
3710
|
l1;
|
|
2066
3711
|
disk;
|
|
2067
3712
|
/** When true, all disk-tier and snapshot operations are skipped. */
|
|
@@ -2073,6 +3718,8 @@ var CacheService = class _CacheService {
|
|
|
2073
3718
|
_namespace;
|
|
2074
3719
|
/** Pre-computed once — disableRedis and redisHost never change after construction. */
|
|
2075
3720
|
_redisDisabled;
|
|
3721
|
+
watchdog;
|
|
3722
|
+
pipeliner = null;
|
|
2076
3723
|
inflight = /* @__PURE__ */ new Map();
|
|
2077
3724
|
revalidating = /* @__PURE__ */ new Set();
|
|
2078
3725
|
_l1Counters = /* @__PURE__ */ new Map();
|
|
@@ -2098,6 +3745,7 @@ var CacheService = class _CacheService {
|
|
|
2098
3745
|
diskJanitorInterval = null;
|
|
2099
3746
|
oomInterval = null;
|
|
2100
3747
|
metricsInterval = null;
|
|
3748
|
+
remoteSnapshotInterval = null;
|
|
2101
3749
|
_shutdownHandler = null;
|
|
2102
3750
|
latencyTracker = null;
|
|
2103
3751
|
instanceId;
|
|
@@ -2107,8 +3755,57 @@ var CacheService = class _CacheService {
|
|
|
2107
3755
|
streamClient = null;
|
|
2108
3756
|
_lastStreamId = "$";
|
|
2109
3757
|
_destroyed = false;
|
|
3758
|
+
_pendingDiskDeletes = /* @__PURE__ */ new Set();
|
|
3759
|
+
_globalEpoch = 0;
|
|
3760
|
+
_keyMutationEpochs = /* @__PURE__ */ new Map();
|
|
3761
|
+
/**
|
|
3762
|
+
* Pattern tombstones for disk tier.
|
|
3763
|
+
* Files in the disk tier are keyed by SHA-256 of namespacedKey.
|
|
3764
|
+
* Wildcard pattern deletes cannot scan the filesystem synchronously, so we maintain
|
|
3765
|
+
* pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
|
|
3766
|
+
*/
|
|
3767
|
+
_patternTombstones = [];
|
|
3768
|
+
_addPatternTombstone(prefix) {
|
|
3769
|
+
const now = Date.now();
|
|
3770
|
+
while (this._patternTombstones.length > 0 && now - this._patternTombstones[0].createdAt > 36e5) {
|
|
3771
|
+
this._patternTombstones.shift();
|
|
3772
|
+
}
|
|
3773
|
+
if (this._patternTombstones.length >= 2e3) {
|
|
3774
|
+
this._patternTombstones.shift();
|
|
3775
|
+
}
|
|
3776
|
+
this._patternTombstones.push({ prefix, createdAt: now });
|
|
3777
|
+
}
|
|
3778
|
+
_isTombstonedByPattern(namespacedKey) {
|
|
3779
|
+
if (this._patternTombstones.length === 0) return false;
|
|
3780
|
+
for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
|
|
3781
|
+
if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
|
|
3782
|
+
return true;
|
|
3783
|
+
}
|
|
3784
|
+
}
|
|
3785
|
+
return false;
|
|
3786
|
+
}
|
|
3787
|
+
_assertActive(operation) {
|
|
3788
|
+
if (this._destroyed) {
|
|
3789
|
+
throw new Error(`TriCacheError: Cannot perform '${operation}' on a destroyed CacheService instance (namespace: '${this._namespace || "(default)"}').`);
|
|
3790
|
+
}
|
|
3791
|
+
}
|
|
3792
|
+
_bumpKeyMutation(namespacedKey) {
|
|
3793
|
+
const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
|
|
3794
|
+
this._keyMutationEpochs.set(namespacedKey, next);
|
|
3795
|
+
if (this._keyMutationEpochs.size > 5e4) {
|
|
3796
|
+
const oldest = this._keyMutationEpochs.keys().next().value;
|
|
3797
|
+
if (oldest !== void 0) this._keyMutationEpochs.delete(oldest);
|
|
3798
|
+
}
|
|
3799
|
+
return next;
|
|
3800
|
+
}
|
|
3801
|
+
_getKeyMutationEpoch(namespacedKey) {
|
|
3802
|
+
return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
|
|
3803
|
+
}
|
|
3804
|
+
_ipcServer;
|
|
2110
3805
|
/** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
|
|
2111
3806
|
_subDisconnectedAt = null;
|
|
3807
|
+
/** Deduplication ring buffer for incoming and outgoing cross-region invalidations (loop prevention) */
|
|
3808
|
+
_seenCrossRegionEvents = /* @__PURE__ */ new Map();
|
|
2112
3809
|
counters = {
|
|
2113
3810
|
gets: 0,
|
|
2114
3811
|
l1Hits: 0,
|
|
@@ -2133,7 +3830,16 @@ var CacheService = class _CacheService {
|
|
|
2133
3830
|
singletonDivergences: 0,
|
|
2134
3831
|
startedAt: Date.now(),
|
|
2135
3832
|
bloomChecks: 0,
|
|
2136
|
-
bloomFalsePositives: 0
|
|
3833
|
+
bloomFalsePositives: 0,
|
|
3834
|
+
remoteSnapshotUploads: 0,
|
|
3835
|
+
remoteSnapshotDownloads: 0,
|
|
3836
|
+
remoteSnapshotErrors: 0,
|
|
3837
|
+
remoteSnapshotLastUploadedAt: null,
|
|
3838
|
+
remoteSnapshotLastDownloadedAt: null,
|
|
3839
|
+
crossRegionSent: 0,
|
|
3840
|
+
crossRegionReceived: 0,
|
|
3841
|
+
crossRegionDeduplicated: 0,
|
|
3842
|
+
crossRegionErrors: 0
|
|
2137
3843
|
};
|
|
2138
3844
|
/** One-time guard so the in-process increment() fallback warning fires only once. */
|
|
2139
3845
|
_incrementFallbackWarned = false;
|
|
@@ -2156,16 +3862,14 @@ var CacheService = class _CacheService {
|
|
|
2156
3862
|
this.opts = {
|
|
2157
3863
|
namespace: ns,
|
|
2158
3864
|
logger,
|
|
2159
|
-
l1MaxBytes: options.l1MaxBytes ??
|
|
3865
|
+
l1MaxBytes: options.l1MaxBytes ?? resolveAutonomousL1MaxBytes(),
|
|
2160
3866
|
l1MaxEntries: options.l1MaxEntries ?? 2e3,
|
|
2161
3867
|
categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...options.categoryLimits },
|
|
2162
3868
|
forbiddenSnapshotPrefixes: forbiddenPrefixes,
|
|
2163
3869
|
// Namespace-isolated defaults: separate dir / snapshot per namespace so
|
|
2164
3870
|
// two instances with different namespaces never share cache files.
|
|
2165
|
-
|
|
2166
|
-
|
|
2167
|
-
ns ? `tricache-disk-${ns}` : "tricache-disk"
|
|
2168
|
-
),
|
|
3871
|
+
// Automatically probes /dev/shm tmpfs on Linux (>=256MB capacity and >=128MB free) for off-heap RAM speed.
|
|
3872
|
+
diskCacheDir: options.diskCacheDir ?? resolveDefaultDiskDir(ns, logger).dir,
|
|
2169
3873
|
diskMaxBytes: options.diskMaxBytes ?? 500 * 1024 * 1024,
|
|
2170
3874
|
diskEntryMaxBytes: options.diskEntryMaxBytes ?? 10 * 1024 * 1024,
|
|
2171
3875
|
redisHost: options.redisHost ?? process.env.REDIS_HOST ?? "",
|
|
@@ -2173,18 +3877,20 @@ var CacheService = class _CacheService {
|
|
|
2173
3877
|
redisTls: options.redisTls ?? process.env.NODE_ENV === "production",
|
|
2174
3878
|
disableRedis: options.disableRedis ?? (() => {
|
|
2175
3879
|
const explicitConfig = Boolean(
|
|
2176
|
-
options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
|
|
3880
|
+
options.redisClient || options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
|
|
2177
3881
|
);
|
|
2178
3882
|
return !explicitConfig && process.env.NODE_ENV !== "production";
|
|
2179
3883
|
})(),
|
|
2180
3884
|
encryptionKey: encKeyRaw,
|
|
2181
3885
|
encryptionMode: options.encryptionMode,
|
|
2182
|
-
snapshotPath: options.snapshotPath ??
|
|
2183
|
-
|
|
3886
|
+
snapshotPath: options.snapshotPath ?? path3.join(
|
|
3887
|
+
os3.tmpdir(),
|
|
2184
3888
|
ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
|
|
2185
3889
|
),
|
|
2186
3890
|
snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
|
|
2187
3891
|
invalidationBackplane: options.invalidationBackplane ?? true,
|
|
3892
|
+
awaitInvalidationBackplane: options.awaitInvalidationBackplane ?? false,
|
|
3893
|
+
lockFailClosed: options.lockFailClosed ?? false,
|
|
2188
3894
|
oomProtection: options.oomProtection ?? true,
|
|
2189
3895
|
oomHeapThreshold: options.oomHeapThreshold ?? 0.85,
|
|
2190
3896
|
oomCheckIntervalMs: options.oomCheckIntervalMs ?? 1e4,
|
|
@@ -2228,8 +3934,35 @@ var CacheService = class _CacheService {
|
|
|
2228
3934
|
backplaneMode: options.backplaneMode ?? "pubsub",
|
|
2229
3935
|
backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
|
|
2230
3936
|
backplaneStreamBlockMs: options.backplaneStreamBlockMs ?? 2e3,
|
|
2231
|
-
backplaneStreamKey: options.backplaneStreamKey
|
|
3937
|
+
backplaneStreamKey: options.backplaneStreamKey,
|
|
3938
|
+
serializeToJSON: options.serializeToJSON ?? true,
|
|
3939
|
+
remoteSnapshot: options.remoteSnapshot,
|
|
3940
|
+
crossRegion: options.crossRegion,
|
|
3941
|
+
redisClient: options.redisClient,
|
|
3942
|
+
redisSubClient: options.redisSubClient,
|
|
3943
|
+
diskMaxConcurrentWrites: options.diskMaxConcurrentWrites,
|
|
3944
|
+
diskMaxPendingWrites: options.diskMaxPendingWrites,
|
|
3945
|
+
diskWriteTimeoutMs: options.diskWriteTimeoutMs,
|
|
3946
|
+
diskCircuitBreakerThreshold: options.diskCircuitBreakerThreshold,
|
|
3947
|
+
diskCircuitBreakerCooldownMs: options.diskCircuitBreakerCooldownMs,
|
|
3948
|
+
redisCommandTimeoutMs: options.redisCommandTimeoutMs,
|
|
3949
|
+
clockSkewToleranceMs: options.clockSkewToleranceMs ?? 250,
|
|
3950
|
+
l1AdmissionPolicy: options.l1AdmissionPolicy,
|
|
3951
|
+
diskLatencyWatchdog: options.diskLatencyWatchdog ?? true,
|
|
3952
|
+
diskLatencyBypassRatio: options.diskLatencyBypassRatio ?? 1.5,
|
|
3953
|
+
diskLatencyBypassMinMs: options.diskLatencyBypassMinMs ?? 10,
|
|
3954
|
+
diskLatencyBypassCooldownMs: options.diskLatencyBypassCooldownMs ?? 3e4,
|
|
3955
|
+
failReadinessOnDegraded: options.failReadinessOnDegraded ?? false,
|
|
3956
|
+
autoPipeline: options.autoPipeline ?? false,
|
|
3957
|
+
maxPipelineBatchSize: options.maxPipelineBatchSize ?? 100,
|
|
3958
|
+
enableIpc: options.enableIpc ?? false,
|
|
3959
|
+
ipcSocketPath: options.ipcSocketPath
|
|
2232
3960
|
};
|
|
3961
|
+
this.codec = new CacheCodec({
|
|
3962
|
+
useToJSON: this.opts.serializeToJSON,
|
|
3963
|
+
useRecords: true,
|
|
3964
|
+
moreTypes: true
|
|
3965
|
+
});
|
|
2233
3966
|
const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
|
|
2234
3967
|
const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
|
|
2235
3968
|
this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
|
|
@@ -2260,15 +3993,33 @@ var CacheService = class _CacheService {
|
|
|
2260
3993
|
encryption: this.enc.isEnabled ? this.enc : null,
|
|
2261
3994
|
compression: this.opts.compression,
|
|
2262
3995
|
compressionThresholdBytes: this.opts.compressionThresholdBytes,
|
|
2263
|
-
logger
|
|
3996
|
+
logger,
|
|
3997
|
+
codec: this.codec,
|
|
3998
|
+
diskMaxConcurrentWrites: this.opts.diskMaxConcurrentWrites,
|
|
3999
|
+
diskMaxPendingWrites: this.opts.diskMaxPendingWrites,
|
|
4000
|
+
diskWriteTimeoutMs: this.opts.diskWriteTimeoutMs,
|
|
4001
|
+
diskCircuitBreakerThreshold: this.opts.diskCircuitBreakerThreshold,
|
|
4002
|
+
diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs
|
|
2264
4003
|
});
|
|
2265
4004
|
this._namespace = ns;
|
|
2266
|
-
this._redisDisabled = this.opts.disableRedis || !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
|
|
4005
|
+
this._redisDisabled = this.opts.disableRedis || !this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
|
|
4006
|
+
this.watchdog = new TierLatencyWatchdog({
|
|
4007
|
+
enabled: options.diskLatencyWatchdog ?? true,
|
|
4008
|
+
minDiskBypassMs: options.diskLatencyBypassMinMs ?? 10,
|
|
4009
|
+
bypassRatio: options.diskLatencyBypassRatio ?? 1.5,
|
|
4010
|
+
cooldownMs: options.diskLatencyBypassCooldownMs ?? 3e4,
|
|
4011
|
+
redisCutoffMs: 15,
|
|
4012
|
+
redisRecoveryFloorMs: 10,
|
|
4013
|
+
minSamples: 16,
|
|
4014
|
+
disableRedis: this._redisDisabled
|
|
4015
|
+
});
|
|
2267
4016
|
this.l1 = new SmartMemoryCache({
|
|
2268
4017
|
maxBytes: this.opts.l1MaxBytes,
|
|
2269
4018
|
maxEntries: this.opts.l1MaxEntries,
|
|
2270
4019
|
categories: this.opts.categoryLimits,
|
|
2271
4020
|
evictionWatermark: this.opts.l1EvictionWatermark,
|
|
4021
|
+
admissionPolicy: this.opts.l1AdmissionPolicy,
|
|
4022
|
+
codec: this.codec,
|
|
2272
4023
|
diskSpill: (key, entry) => {
|
|
2273
4024
|
if (this._diskDisabled) return;
|
|
2274
4025
|
setImmediate(() => {
|
|
@@ -2283,10 +4034,9 @@ var CacheService = class _CacheService {
|
|
|
2283
4034
|
if (!this._diskDisabled) this.loadSnapshot();
|
|
2284
4035
|
}
|
|
2285
4036
|
this._shutdownHandler = () => {
|
|
2286
|
-
|
|
4037
|
+
this._triggerShutdown();
|
|
2287
4038
|
};
|
|
2288
|
-
|
|
2289
|
-
process.once("SIGINT", this._shutdownHandler);
|
|
4039
|
+
ProcessTerminationBus.register(this);
|
|
2290
4040
|
if (this.opts.workerThreads) {
|
|
2291
4041
|
try {
|
|
2292
4042
|
const encRef = this.enc.toWorkerInit();
|
|
@@ -2326,7 +4076,7 @@ var CacheService = class _CacheService {
|
|
|
2326
4076
|
}
|
|
2327
4077
|
if (this.opts.oomProtection) {
|
|
2328
4078
|
this.oomInterval = setInterval(() => {
|
|
2329
|
-
const heap =
|
|
4079
|
+
const heap = v82.getHeapStatistics();
|
|
2330
4080
|
const used = heap.used_heap_size / heap.heap_size_limit;
|
|
2331
4081
|
if (used >= this.opts.oomHeapThreshold) {
|
|
2332
4082
|
const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
|
|
@@ -2350,12 +4100,25 @@ var CacheService = class _CacheService {
|
|
|
2350
4100
|
}, this.opts.metricsIntervalMs);
|
|
2351
4101
|
if (this.metricsInterval.unref) this.metricsInterval.unref();
|
|
2352
4102
|
}
|
|
4103
|
+
if (this.opts.remoteSnapshot?.intervalMs && this.opts.remoteSnapshot.intervalMs > 0) {
|
|
4104
|
+
this.remoteSnapshotInterval = setInterval(() => {
|
|
4105
|
+
void this.writeRemoteSnapshot();
|
|
4106
|
+
}, this.opts.remoteSnapshot.intervalMs);
|
|
4107
|
+
if (this.remoteSnapshotInterval.unref) this.remoteSnapshotInterval.unref();
|
|
4108
|
+
}
|
|
2353
4109
|
this.instanceId = crypto2.randomBytes(8).toString("hex");
|
|
2354
4110
|
this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
|
|
2355
4111
|
this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
|
|
2356
4112
|
this.initBackplane();
|
|
4113
|
+
const startupPromises = [];
|
|
4114
|
+
if (this.opts.remoteSnapshot) {
|
|
4115
|
+
startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
|
|
4116
|
+
}
|
|
2357
4117
|
if (this.opts.warmKeys) {
|
|
2358
|
-
|
|
4118
|
+
startupPromises.push(this.warmFromL2(this.opts.warmKeys).then(() => void 0));
|
|
4119
|
+
}
|
|
4120
|
+
if (startupPromises.length > 0) {
|
|
4121
|
+
this._readyPromise = Promise.all(startupPromises).then(() => void 0);
|
|
2359
4122
|
}
|
|
2360
4123
|
if (this.opts.meter) {
|
|
2361
4124
|
this._initOtelMetrics(this.opts.meter);
|
|
@@ -2376,8 +4139,71 @@ var CacheService = class _CacheService {
|
|
|
2376
4139
|
}
|
|
2377
4140
|
});
|
|
2378
4141
|
}
|
|
4142
|
+
if (this.opts.enableIpc) {
|
|
4143
|
+
this._ipcServer = new IpcTelemetryServer(this, this.opts.ipcSocketPath);
|
|
4144
|
+
this._ipcServer.start().catch((err) => {
|
|
4145
|
+
this.logger.warn("Failed to start IPC telemetry server", { error: err.message });
|
|
4146
|
+
});
|
|
4147
|
+
}
|
|
4148
|
+
}
|
|
4149
|
+
// ── Singleton factory & Presets ───────────────────────────────────────────
|
|
4150
|
+
/**
|
|
4151
|
+
* Pre-configured production presets tailored for specific deployment environments.
|
|
4152
|
+
*
|
|
4153
|
+
* - `'nextjs'`: W-TinyLFU, zero-copy cloneStrategy: 'none' (React 19 RSC stream optimized),
|
|
4154
|
+
* generational tags, and Redis stream backplane.
|
|
4155
|
+
* - `'microservice'`: High-throughput Node.js microservice with W-TinyLFU, Streams backplane,
|
|
4156
|
+
* TTL jitter, and L2 circuit breaking.
|
|
4157
|
+
* - `'serverless'`: Stateless Lambda / Cloud Run isolate with memory-only L1, fast timeouts,
|
|
4158
|
+
* and Pub/Sub backplane.
|
|
4159
|
+
* - `'enterprise-hardened'`: Zero-trust production setup with generational tagging, Streams backplane,
|
|
4160
|
+
* fail-closed rate-limits, strict singleton assertions, and 80% OOM guard.
|
|
4161
|
+
*
|
|
4162
|
+
* @param type The preset identifier ('nextjs' | 'microservice' | 'serverless' | 'enterprise-hardened')
|
|
4163
|
+
* @param overrides Optional configuration overrides merged deeply over preset defaults
|
|
4164
|
+
* @returns Singleton CacheService instance configured according to the preset
|
|
4165
|
+
*/
|
|
4166
|
+
static preset(type, overrides) {
|
|
4167
|
+
const PRESETS = {
|
|
4168
|
+
"nextjs": {
|
|
4169
|
+
l1AdmissionPolicy: "wtinylfu",
|
|
4170
|
+
cloneStrategy: "none",
|
|
4171
|
+
tagStrategy: "generational",
|
|
4172
|
+
tagVersionTtlMs: 2e3,
|
|
4173
|
+
backplaneMode: "stream",
|
|
4174
|
+
staleIfError: 300,
|
|
4175
|
+
compression: "none"
|
|
4176
|
+
},
|
|
4177
|
+
"microservice": {
|
|
4178
|
+
l1AdmissionPolicy: "wtinylfu",
|
|
4179
|
+
backplaneMode: "stream",
|
|
4180
|
+
ttlJitterFactor: 0.15,
|
|
4181
|
+
l2CircuitBreakerThreshold: 5,
|
|
4182
|
+
l2CircuitBreakerCooldownMs: 15e3
|
|
4183
|
+
},
|
|
4184
|
+
"serverless": {
|
|
4185
|
+
disableDisk: true,
|
|
4186
|
+
l1AdmissionPolicy: "wtinylfu",
|
|
4187
|
+
backplaneMode: "pubsub",
|
|
4188
|
+
redisCommandTimeoutMs: 1e3
|
|
4189
|
+
},
|
|
4190
|
+
"enterprise-hardened": {
|
|
4191
|
+
l1AdmissionPolicy: "wtinylfu",
|
|
4192
|
+
tagStrategy: "generational",
|
|
4193
|
+
backplaneMode: "stream",
|
|
4194
|
+
strictSingleton: true,
|
|
4195
|
+
failClosed: true,
|
|
4196
|
+
oomProtection: true,
|
|
4197
|
+
oomHeapThreshold: 0.8
|
|
4198
|
+
}
|
|
4199
|
+
};
|
|
4200
|
+
const base = PRESETS[type];
|
|
4201
|
+
if (!base) {
|
|
4202
|
+
throw new Error(`tricache: unknown preset '${type}'. Supported presets: 'nextjs', 'microservice', 'serverless', 'enterprise-hardened'`);
|
|
4203
|
+
}
|
|
4204
|
+
const merged = deepMergeOptions(base, overrides);
|
|
4205
|
+
return _CacheService.create(merged);
|
|
2379
4206
|
}
|
|
2380
|
-
// ── Singleton factory ─────────────────────────────────────────────────────
|
|
2381
4207
|
/**
|
|
2382
4208
|
* Get (or create) the process-level singleton CacheService instance.
|
|
2383
4209
|
*
|
|
@@ -2430,7 +4256,9 @@ var CacheService = class _CacheService {
|
|
|
2430
4256
|
"adaptiveTtl",
|
|
2431
4257
|
"l2WriteMode",
|
|
2432
4258
|
"instanceName",
|
|
2433
|
-
"invalidationBackplane"
|
|
4259
|
+
"invalidationBackplane",
|
|
4260
|
+
"awaitInvalidationBackplane",
|
|
4261
|
+
"lockFailClosed"
|
|
2434
4262
|
];
|
|
2435
4263
|
/** Returns the names of options that differ between `a` and the live `b`. */
|
|
2436
4264
|
static optionsDiff(a, b) {
|
|
@@ -2471,7 +4299,11 @@ var CacheService = class _CacheService {
|
|
|
2471
4299
|
frozen: o.frozen,
|
|
2472
4300
|
adaptiveTtl: o.adaptiveTtl,
|
|
2473
4301
|
invalidationBackplane: o.invalidationBackplane,
|
|
2474
|
-
|
|
4302
|
+
awaitInvalidationBackplane: o.awaitInvalidationBackplane,
|
|
4303
|
+
lockFailClosed: o.lockFailClosed,
|
|
4304
|
+
strictSingleton: o.strictSingleton,
|
|
4305
|
+
remoteSnapshot: o.remoteSnapshot,
|
|
4306
|
+
crossRegion: o.crossRegion
|
|
2475
4307
|
};
|
|
2476
4308
|
}
|
|
2477
4309
|
/**
|
|
@@ -2530,15 +4362,30 @@ var CacheService = class _CacheService {
|
|
|
2530
4362
|
setStatus() {
|
|
2531
4363
|
return this;
|
|
2532
4364
|
},
|
|
4365
|
+
recordException() {
|
|
4366
|
+
return this;
|
|
4367
|
+
},
|
|
2533
4368
|
end() {
|
|
2534
4369
|
}
|
|
2535
4370
|
};
|
|
2536
4371
|
/** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
|
|
2537
|
-
_startSpan(name) {
|
|
2538
|
-
if (this.opts.tracer)
|
|
4372
|
+
_startSpan(name, links) {
|
|
4373
|
+
if (this.opts.tracer) {
|
|
4374
|
+
const span = this.opts.tracer.startSpan(name, links?.length ? { links } : void 0);
|
|
4375
|
+
if (this.opts.namespace) {
|
|
4376
|
+
span.setAttribute("cache.namespace", this.opts.namespace);
|
|
4377
|
+
}
|
|
4378
|
+
return span;
|
|
4379
|
+
}
|
|
2539
4380
|
return _CacheService._nullSpan;
|
|
2540
4381
|
}
|
|
2541
4382
|
createDedicatedRedisClient() {
|
|
4383
|
+
if (this.opts.redisSubClient) {
|
|
4384
|
+
return this.opts.redisSubClient;
|
|
4385
|
+
}
|
|
4386
|
+
if (this.opts.redisClient && typeof this.opts.redisClient.duplicate === "function") {
|
|
4387
|
+
return this.opts.redisClient.duplicate();
|
|
4388
|
+
}
|
|
2542
4389
|
if (this.opts.redisClusterNodes?.length) {
|
|
2543
4390
|
return new RedisCluster(this.opts.redisClusterNodes, {
|
|
2544
4391
|
redisOptions: {
|
|
@@ -2739,16 +4586,36 @@ var CacheService = class _CacheService {
|
|
|
2739
4586
|
_applyInvalidationEvent(op, key, tagVersion) {
|
|
2740
4587
|
if (op === "del") {
|
|
2741
4588
|
this.l1.delete(key);
|
|
4589
|
+
this._bumpKeyMutation(key);
|
|
4590
|
+
this.inflight.delete(key);
|
|
4591
|
+
this._pendingDiskDeletes.add(key);
|
|
2742
4592
|
setImmediate(() => {
|
|
2743
|
-
|
|
4593
|
+
try {
|
|
4594
|
+
if (!this._diskDisabled) this.disk.delete(key);
|
|
4595
|
+
} finally {
|
|
4596
|
+
this._pendingDiskDeletes.delete(key);
|
|
4597
|
+
}
|
|
2744
4598
|
});
|
|
2745
4599
|
this._cascadeDependencies(key);
|
|
2746
4600
|
} else if (op === "del-glob") {
|
|
2747
4601
|
this.l1.deletePattern(key);
|
|
4602
|
+
const pfx = key.endsWith("*") ? key.slice(0, -1) : key;
|
|
4603
|
+
for (const liveKey of this.l1.liveKeys()) {
|
|
4604
|
+
if (liveKey.startsWith(pfx)) {
|
|
4605
|
+
this._bumpKeyMutation(liveKey);
|
|
4606
|
+
}
|
|
4607
|
+
}
|
|
4608
|
+
for (const inflightKey of Array.from(this.inflight.keys())) {
|
|
4609
|
+
if (inflightKey.startsWith(pfx)) {
|
|
4610
|
+
this._bumpKeyMutation(inflightKey);
|
|
4611
|
+
this.inflight.delete(inflightKey);
|
|
4612
|
+
}
|
|
4613
|
+
}
|
|
4614
|
+
this._addPatternTombstone(pfx);
|
|
2748
4615
|
} else if (op === "tag_incr") {
|
|
2749
4616
|
const tag = key;
|
|
2750
4617
|
const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
2751
|
-
this._setLocalTagVersion(tag, ver,
|
|
4618
|
+
this._setLocalTagVersion(tag, ver, performance.now());
|
|
2752
4619
|
}
|
|
2753
4620
|
this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
|
|
2754
4621
|
}
|
|
@@ -2772,7 +4639,17 @@ var CacheService = class _CacheService {
|
|
|
2772
4639
|
this.logger.warn("Backplane: malformed message JSON parse failed");
|
|
2773
4640
|
}
|
|
2774
4641
|
}
|
|
2775
|
-
async publishInvalidation(op, key, tagVersion) {
|
|
4642
|
+
async publishInvalidation(op, key, tagVersion, isCrossRegionRelay = false, isExplicitInvalidation = false) {
|
|
4643
|
+
if (!isCrossRegionRelay && this.opts.crossRegion) {
|
|
4644
|
+
const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
|
|
4645
|
+
if (shouldBroadcast) {
|
|
4646
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
4647
|
+
await this._broadcastCrossRegion(op, key, tagVersion);
|
|
4648
|
+
} else {
|
|
4649
|
+
void this._broadcastCrossRegion(op, key, tagVersion);
|
|
4650
|
+
}
|
|
4651
|
+
}
|
|
4652
|
+
}
|
|
2776
4653
|
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
2777
4654
|
try {
|
|
2778
4655
|
const client = await this.getRedis();
|
|
@@ -2811,10 +4688,87 @@ var CacheService = class _CacheService {
|
|
|
2811
4688
|
);
|
|
2812
4689
|
}
|
|
2813
4690
|
this.counters.invSent++;
|
|
2814
|
-
} catch {
|
|
4691
|
+
} catch (err) {
|
|
4692
|
+
this.logger.warn("Backplane invalidation publish failed", { op, key, error: err.message });
|
|
4693
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
4694
|
+
throw err;
|
|
4695
|
+
}
|
|
4696
|
+
}
|
|
4697
|
+
}
|
|
4698
|
+
_markCrossRegionEventSeen(id) {
|
|
4699
|
+
const maxDedup = this.opts.crossRegion?.dedupCacheSize ?? 1e4;
|
|
4700
|
+
if (this._seenCrossRegionEvents.size >= maxDedup) {
|
|
4701
|
+
const oldestKey = this._seenCrossRegionEvents.keys().next().value;
|
|
4702
|
+
if (oldestKey !== void 0) this._seenCrossRegionEvents.delete(oldestKey);
|
|
4703
|
+
}
|
|
4704
|
+
this._seenCrossRegionEvents.set(id, Date.now());
|
|
4705
|
+
}
|
|
4706
|
+
_isCrossRegionEventSeen(id) {
|
|
4707
|
+
return this._seenCrossRegionEvents.has(id);
|
|
4708
|
+
}
|
|
4709
|
+
async _broadcastCrossRegion(op, key, tagVersion) {
|
|
4710
|
+
const cr = this.opts.crossRegion;
|
|
4711
|
+
if (!cr) return;
|
|
4712
|
+
try {
|
|
4713
|
+
const eventId = crypto2.randomUUID();
|
|
4714
|
+
this._markCrossRegionEventSeen(eventId);
|
|
4715
|
+
const event = {
|
|
4716
|
+
id: eventId,
|
|
4717
|
+
originRegion: cr.currentRegion,
|
|
4718
|
+
originInstanceId: this.instanceId,
|
|
4719
|
+
op,
|
|
4720
|
+
key,
|
|
4721
|
+
tagVersion,
|
|
4722
|
+
timestamp: Date.now(),
|
|
4723
|
+
namespace: this._namespace || void 0
|
|
4724
|
+
};
|
|
4725
|
+
this.counters.crossRegionSent++;
|
|
4726
|
+
await cr.relay.broadcast(event);
|
|
4727
|
+
this.logger.debug("Cross-region invalidation broadcast", { op, key, region: cr.currentRegion });
|
|
4728
|
+
} catch (err) {
|
|
4729
|
+
this.counters.crossRegionSent = Math.max(0, this.counters.crossRegionSent - 1);
|
|
4730
|
+
this.counters.crossRegionErrors++;
|
|
4731
|
+
this.logger.warn("Cross-region invalidation broadcast failed", { error: err.message });
|
|
4732
|
+
}
|
|
4733
|
+
}
|
|
4734
|
+
/**
|
|
4735
|
+
* Receives an invalidation event from another region (e.g. via HTTP webhook or broker subscriber).
|
|
4736
|
+
* Validates origin, deduplicates to prevent loops, applies locally to L1/disk,
|
|
4737
|
+
* and fans out to the local Redis backplane so all regional peers invalidate as well.
|
|
4738
|
+
*
|
|
4739
|
+
* Returns true if the event was accepted and applied, or false if ignored/deduplicated.
|
|
4740
|
+
*/
|
|
4741
|
+
async receiveCrossRegionInvalidation(event) {
|
|
4742
|
+
const cr = this.opts.crossRegion;
|
|
4743
|
+
if (!cr) return false;
|
|
4744
|
+
if (!event || typeof event !== "object" || !event.id || !event.originRegion || !event.op || !event.key) {
|
|
4745
|
+
this.counters.crossRegionErrors++;
|
|
4746
|
+
this.logger.warn("Cross-region: rejected invalid event payload", { event });
|
|
4747
|
+
return false;
|
|
4748
|
+
}
|
|
4749
|
+
if (event.originRegion === cr.currentRegion) {
|
|
4750
|
+
this.counters.crossRegionDeduplicated++;
|
|
4751
|
+
return false;
|
|
2815
4752
|
}
|
|
4753
|
+
if (this._isCrossRegionEventSeen(event.id)) {
|
|
4754
|
+
this.counters.crossRegionDeduplicated++;
|
|
4755
|
+
return false;
|
|
4756
|
+
}
|
|
4757
|
+
this._markCrossRegionEventSeen(event.id);
|
|
4758
|
+
if (event.namespace !== void 0 && event.namespace !== (this._namespace || void 0)) {
|
|
4759
|
+
return false;
|
|
4760
|
+
}
|
|
4761
|
+
this.counters.crossRegionReceived++;
|
|
4762
|
+
this._applyInvalidationEvent(event.op, event.key, event.tagVersion);
|
|
4763
|
+
void this.publishInvalidation(event.op, event.key, event.tagVersion, true);
|
|
4764
|
+
this.logger.info("Cross-region invalidation applied", {
|
|
4765
|
+
op: event.op,
|
|
4766
|
+
key: event.key,
|
|
4767
|
+
originRegion: event.originRegion
|
|
4768
|
+
});
|
|
4769
|
+
return true;
|
|
2816
4770
|
}
|
|
2817
|
-
_setLocalTagVersion(tag, version, now =
|
|
4771
|
+
_setLocalTagVersion(tag, version, now = performance.now()) {
|
|
2818
4772
|
const existing = this.tagVersions.get(tag)?.version ?? 0;
|
|
2819
4773
|
const finalVersion = Math.max(existing, version);
|
|
2820
4774
|
if (this.tagVersions.size >= 1e4 && !this.tagVersions.has(tag)) {
|
|
@@ -2824,7 +4778,7 @@ var CacheService = class _CacheService {
|
|
|
2824
4778
|
this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
|
|
2825
4779
|
}
|
|
2826
4780
|
async _getTagVersion(tag) {
|
|
2827
|
-
const now =
|
|
4781
|
+
const now = performance.now();
|
|
2828
4782
|
const local = this.tagVersions.get(tag);
|
|
2829
4783
|
if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
|
|
2830
4784
|
return local.version;
|
|
@@ -2910,13 +4864,25 @@ var CacheService = class _CacheService {
|
|
|
2910
4864
|
stream.on("error", reject);
|
|
2911
4865
|
})
|
|
2912
4866
|
));
|
|
2913
|
-
} else {
|
|
4867
|
+
} else if (typeof client.scanStream === "function") {
|
|
2914
4868
|
await new Promise((resolve, reject) => {
|
|
2915
4869
|
const stream = client.scanStream({ match: pattern, count: 100 });
|
|
2916
4870
|
stream.on("data", (chunk) => keys.push(...chunk));
|
|
2917
4871
|
stream.on("end", resolve);
|
|
2918
4872
|
stream.on("error", reject);
|
|
2919
4873
|
});
|
|
4874
|
+
} else if (typeof client.scanIterator === "function") {
|
|
4875
|
+
for await (const key of client.scanIterator({ MATCH: pattern, COUNT: 100 })) {
|
|
4876
|
+
keys.push(key);
|
|
4877
|
+
}
|
|
4878
|
+
} else if (typeof client.scan === "function") {
|
|
4879
|
+
let cursor = "0";
|
|
4880
|
+
do {
|
|
4881
|
+
const res = await client.scan(cursor, "MATCH", pattern, "COUNT", 100);
|
|
4882
|
+
cursor = String(res[0]);
|
|
4883
|
+
const chunk = res[1];
|
|
4884
|
+
if (chunk?.length) keys.push(...chunk);
|
|
4885
|
+
} while (cursor !== "0");
|
|
2920
4886
|
}
|
|
2921
4887
|
return keys;
|
|
2922
4888
|
}
|
|
@@ -2930,9 +4896,23 @@ var CacheService = class _CacheService {
|
|
|
2930
4896
|
}
|
|
2931
4897
|
}
|
|
2932
4898
|
async getRedis() {
|
|
4899
|
+
this._assertActive("getRedis");
|
|
2933
4900
|
if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
|
|
2934
4901
|
if (this.redis) return this.redis;
|
|
2935
4902
|
if (this.redisConnecting) return this.redisConnecting;
|
|
4903
|
+
if (this.opts.redisClient) {
|
|
4904
|
+
const client = this.opts.redisClient;
|
|
4905
|
+
if (typeof client.connect === "function" && client.isOpen === false) {
|
|
4906
|
+
await client.connect();
|
|
4907
|
+
}
|
|
4908
|
+
this.cb.onSuccess();
|
|
4909
|
+
this.redis = client;
|
|
4910
|
+
this.pipeliner = new AutoPipeliner(client, {
|
|
4911
|
+
enabled: this.opts.autoPipeline,
|
|
4912
|
+
maxBatchSize: this.opts.maxPipelineBatchSize
|
|
4913
|
+
});
|
|
4914
|
+
return client;
|
|
4915
|
+
}
|
|
2936
4916
|
this.redisConnecting = (async () => {
|
|
2937
4917
|
try {
|
|
2938
4918
|
let client;
|
|
@@ -2941,6 +4921,7 @@ var CacheService = class _CacheService {
|
|
|
2941
4921
|
redisOptions: {
|
|
2942
4922
|
tls: this.opts.redisTls ? {} : void 0,
|
|
2943
4923
|
connectTimeout: 1e4,
|
|
4924
|
+
commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
|
|
2944
4925
|
maxRetriesPerRequest: 3,
|
|
2945
4926
|
keepAlive: 3e4,
|
|
2946
4927
|
...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
|
|
@@ -2961,6 +4942,7 @@ var CacheService = class _CacheService {
|
|
|
2961
4942
|
name: this.opts.redisSentinel.name,
|
|
2962
4943
|
tls: this.opts.redisTls ? {} : void 0,
|
|
2963
4944
|
connectTimeout: 1e4,
|
|
4945
|
+
commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
|
|
2964
4946
|
lazyConnect: false,
|
|
2965
4947
|
maxRetriesPerRequest: 3,
|
|
2966
4948
|
enableAutoPipelining: true,
|
|
@@ -2980,6 +4962,7 @@ var CacheService = class _CacheService {
|
|
|
2980
4962
|
port: this.opts.redisPort,
|
|
2981
4963
|
tls: this.opts.redisTls ? {} : void 0,
|
|
2982
4964
|
connectTimeout: 1e4,
|
|
4965
|
+
commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
|
|
2983
4966
|
lazyConnect: false,
|
|
2984
4967
|
maxRetriesPerRequest: 3,
|
|
2985
4968
|
enableAutoPipelining: true,
|
|
@@ -3005,6 +4988,10 @@ var CacheService = class _CacheService {
|
|
|
3005
4988
|
});
|
|
3006
4989
|
this.cb.onSuccess();
|
|
3007
4990
|
this.redis = client;
|
|
4991
|
+
this.pipeliner = new AutoPipeliner(client, {
|
|
4992
|
+
enabled: this.opts.autoPipeline,
|
|
4993
|
+
maxBatchSize: this.opts.maxPipelineBatchSize
|
|
4994
|
+
});
|
|
3008
4995
|
this.redisConnecting = null;
|
|
3009
4996
|
return client;
|
|
3010
4997
|
} catch (err) {
|
|
@@ -3017,16 +5004,22 @@ var CacheService = class _CacheService {
|
|
|
3017
5004
|
return this.redisConnecting;
|
|
3018
5005
|
}
|
|
3019
5006
|
// ── Snapshot (cold-start persistence) ────────────────────────────────────
|
|
5007
|
+
/**
|
|
5008
|
+
* Writes the cold-start snapshot to disk.
|
|
5009
|
+
* NOTE: fs.writeFileSync is INTENTIONAL here: this method is invoked during SIGTERM/SIGINT
|
|
5010
|
+
* process termination hooks where asynchronous I/O would risk the Node.js event loop dying or
|
|
5011
|
+
* process.exit() being called before the snapshot is physically written to disk.
|
|
5012
|
+
*/
|
|
3020
5013
|
writeSnapshot(altPath) {
|
|
3021
5014
|
try {
|
|
3022
5015
|
const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
|
|
3023
5016
|
if (entries.length === 0) return;
|
|
3024
5017
|
const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
|
|
3025
|
-
const packed =
|
|
5018
|
+
const packed = this.codec.encode(payload);
|
|
3026
5019
|
const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
|
|
3027
5020
|
const dest = altPath ?? this.opts.snapshotPath;
|
|
3028
|
-
|
|
3029
|
-
|
|
5021
|
+
fs4.mkdirSync(path3.dirname(dest), { recursive: true });
|
|
5022
|
+
fs4.writeFileSync(dest, final, { mode: 384 });
|
|
3030
5023
|
this.logger.info("Cache snapshot written", {
|
|
3031
5024
|
path: dest,
|
|
3032
5025
|
entries: entries.length,
|
|
@@ -3037,18 +5030,24 @@ var CacheService = class _CacheService {
|
|
|
3037
5030
|
this.logger.warn("Cache snapshot write failed", { error: err.message });
|
|
3038
5031
|
}
|
|
3039
5032
|
}
|
|
5033
|
+
/**
|
|
5034
|
+
* Loads cold-start snapshot from disk into L1 memory.
|
|
5035
|
+
* NOTE: fs.readFileSync is INTENTIONAL here: this method is invoked synchronously inside the
|
|
5036
|
+
* CacheService constructor so that the cache is atomically populated before any subsequent
|
|
5037
|
+
* cache.get() or cache.set() operations run, eliminating cold-start race conditions.
|
|
5038
|
+
*/
|
|
3040
5039
|
loadSnapshot() {
|
|
3041
5040
|
const snapshotPath = this.opts.snapshotPath;
|
|
3042
5041
|
try {
|
|
3043
|
-
if (!
|
|
3044
|
-
const stat =
|
|
5042
|
+
if (!fs4.existsSync(snapshotPath)) return;
|
|
5043
|
+
const stat = fs4.statSync(snapshotPath);
|
|
3045
5044
|
if (stat.size > SNAPSHOT_MAX_FILE_BYTES) {
|
|
3046
5045
|
this.logger.warn("Snapshot rejected: exceeds size limit", { sizeBytes: stat.size });
|
|
3047
|
-
|
|
5046
|
+
fs4.unlinkSync(snapshotPath);
|
|
3048
5047
|
return;
|
|
3049
5048
|
}
|
|
3050
|
-
const raw =
|
|
3051
|
-
|
|
5049
|
+
const raw = fs4.readFileSync(snapshotPath);
|
|
5050
|
+
fs4.unlinkSync(snapshotPath);
|
|
3052
5051
|
let buf;
|
|
3053
5052
|
try {
|
|
3054
5053
|
buf = this.enc.decryptBuffer(raw);
|
|
@@ -3056,13 +5055,25 @@ var CacheService = class _CacheService {
|
|
|
3056
5055
|
this.logger.warn("Snapshot rejected: decryption failed", { error: e.message });
|
|
3057
5056
|
return;
|
|
3058
5057
|
}
|
|
3059
|
-
const snapshot =
|
|
5058
|
+
const snapshot = this.codec.decode(buf);
|
|
3060
5059
|
if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
|
|
3061
5060
|
this.logger.warn("Snapshot rejected: version mismatch", { got: snapshot?.version });
|
|
3062
5061
|
return;
|
|
3063
5062
|
}
|
|
3064
|
-
const
|
|
3065
|
-
|
|
5063
|
+
const now = Date.now();
|
|
5064
|
+
const writtenAt = snapshot.writtenAt ?? 0;
|
|
5065
|
+
const tolerance = this.opts.clockSkewToleranceMs ?? 250;
|
|
5066
|
+
if (writtenAt - now > tolerance) {
|
|
5067
|
+
this.logger.warn("Snapshot rejected: timestamp too far in future (exceeds clock skew tolerance)", {
|
|
5068
|
+
writtenAt,
|
|
5069
|
+
now,
|
|
5070
|
+
skewMs: writtenAt - now,
|
|
5071
|
+
tolerance
|
|
5072
|
+
});
|
|
5073
|
+
return;
|
|
5074
|
+
}
|
|
5075
|
+
const ageMs = Math.max(0, now - writtenAt);
|
|
5076
|
+
if (ageMs > this.opts.snapshotMaxAgeMs) {
|
|
3066
5077
|
this.logger.warn("Snapshot rejected: too old", { ageMinutes: Math.round(ageMs / 6e4) });
|
|
3067
5078
|
return;
|
|
3068
5079
|
}
|
|
@@ -3079,11 +5090,120 @@ var CacheService = class _CacheService {
|
|
|
3079
5090
|
} catch (err) {
|
|
3080
5091
|
this.logger.warn("Snapshot load failed \u2014 starting cold", { error: err.message });
|
|
3081
5092
|
try {
|
|
3082
|
-
|
|
5093
|
+
fs4.unlinkSync(snapshotPath);
|
|
3083
5094
|
} catch {
|
|
3084
5095
|
}
|
|
3085
5096
|
}
|
|
3086
5097
|
}
|
|
5098
|
+
// ── Remote Snapshot (cold-start persistence for stateless containers) ───────
|
|
5099
|
+
/**
|
|
5100
|
+
* Persists the cold-start snapshot to remote blob storage (S3, GCS, R2, HTTP).
|
|
5101
|
+
* Can be awaited during graceful application shutdown (e.g. Kubernetes preStop or NestJS shutdown).
|
|
5102
|
+
* Returns true if a snapshot was successfully exported and written; false otherwise.
|
|
5103
|
+
*/
|
|
5104
|
+
async writeRemoteSnapshot() {
|
|
5105
|
+
if (!this.opts.remoteSnapshot) return false;
|
|
5106
|
+
try {
|
|
5107
|
+
const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
|
|
5108
|
+
if (entries.length === 0) return false;
|
|
5109
|
+
const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
|
|
5110
|
+
const packed = this.codec.encode(payload);
|
|
5111
|
+
let final;
|
|
5112
|
+
if (this.opts.remoteSnapshot.envelope) {
|
|
5113
|
+
final = await EnvelopeEncryption.encrypt(packed, this.opts.remoteSnapshot.envelope);
|
|
5114
|
+
} else {
|
|
5115
|
+
final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
|
|
5116
|
+
}
|
|
5117
|
+
await this.opts.remoteSnapshot.adapter.put(final);
|
|
5118
|
+
this.counters.remoteSnapshotUploads++;
|
|
5119
|
+
this.counters.remoteSnapshotLastUploadedAt = Date.now();
|
|
5120
|
+
this.logger.info("Remote cache snapshot uploaded", {
|
|
5121
|
+
entries: entries.length,
|
|
5122
|
+
sizeKB: Math.round(final.length / 1024),
|
|
5123
|
+
encrypted: Boolean(this.opts.remoteSnapshot.envelope || this.enc.isEnabled)
|
|
5124
|
+
});
|
|
5125
|
+
return true;
|
|
5126
|
+
} catch (err) {
|
|
5127
|
+
this.counters.remoteSnapshotErrors++;
|
|
5128
|
+
this.logger.warn("Remote cache snapshot upload failed", { error: err.message });
|
|
5129
|
+
return false;
|
|
5130
|
+
}
|
|
5131
|
+
}
|
|
5132
|
+
/**
|
|
5133
|
+
* Hydrates L1 memory from remote blob storage (S3, GCS, R2, HTTP).
|
|
5134
|
+
* Called automatically during startup (chained into `cache.ready()`).
|
|
5135
|
+
* Returns the number of entries successfully imported.
|
|
5136
|
+
*/
|
|
5137
|
+
async loadRemoteSnapshot() {
|
|
5138
|
+
if (!this.opts.remoteSnapshot) return 0;
|
|
5139
|
+
const maxAgeMs = this.opts.remoteSnapshot.maxAgeMs ?? this.opts.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE;
|
|
5140
|
+
try {
|
|
5141
|
+
const raw = await this.opts.remoteSnapshot.adapter.get();
|
|
5142
|
+
if (!raw || raw.length === 0) {
|
|
5143
|
+
this.logger.debug("Remote snapshot not found or empty \u2014 starting cold");
|
|
5144
|
+
return 0;
|
|
5145
|
+
}
|
|
5146
|
+
const rawBuf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
|
|
5147
|
+
let buf;
|
|
5148
|
+
try {
|
|
5149
|
+
if (EnvelopeEncryption.isEnvelope(rawBuf)) {
|
|
5150
|
+
if (!this.opts.remoteSnapshot.envelope) {
|
|
5151
|
+
throw new Error("Remote snapshot is envelope-encrypted but no envelope options (privateKey or kmsDecrypt) were configured");
|
|
5152
|
+
}
|
|
5153
|
+
buf = await EnvelopeEncryption.decrypt(rawBuf, this.opts.remoteSnapshot.envelope);
|
|
5154
|
+
} else {
|
|
5155
|
+
buf = this.enc.decryptBuffer(rawBuf);
|
|
5156
|
+
}
|
|
5157
|
+
} catch (e) {
|
|
5158
|
+
this.counters.remoteSnapshotErrors++;
|
|
5159
|
+
this.logger.warn("Remote snapshot rejected: decryption failed", { error: e.message });
|
|
5160
|
+
return 0;
|
|
5161
|
+
}
|
|
5162
|
+
const snapshot = this.codec.decode(buf);
|
|
5163
|
+
if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
|
|
5164
|
+
this.counters.remoteSnapshotErrors++;
|
|
5165
|
+
this.logger.warn("Remote snapshot rejected: version mismatch", { got: snapshot?.version });
|
|
5166
|
+
return 0;
|
|
5167
|
+
}
|
|
5168
|
+
const now = Date.now();
|
|
5169
|
+
const writtenAt = snapshot.writtenAt ?? 0;
|
|
5170
|
+
const tolerance = this.opts.clockSkewToleranceMs ?? 250;
|
|
5171
|
+
if (writtenAt - now > tolerance) {
|
|
5172
|
+
this.counters.remoteSnapshotErrors++;
|
|
5173
|
+
this.logger.warn("Remote snapshot rejected: timestamp too far in future (exceeds clock skew tolerance)", {
|
|
5174
|
+
writtenAt,
|
|
5175
|
+
now,
|
|
5176
|
+
skewMs: writtenAt - now,
|
|
5177
|
+
tolerance
|
|
5178
|
+
});
|
|
5179
|
+
return 0;
|
|
5180
|
+
}
|
|
5181
|
+
const ageMs = Math.max(0, now - writtenAt);
|
|
5182
|
+
if (maxAgeMs <= 0 || ageMs > maxAgeMs) {
|
|
5183
|
+
this.counters.remoteSnapshotErrors++;
|
|
5184
|
+
this.logger.warn("Remote snapshot rejected: too old", { ageMinutes: Math.round(ageMs / 6e4) });
|
|
5185
|
+
return 0;
|
|
5186
|
+
}
|
|
5187
|
+
if (!Array.isArray(snapshot.entries)) {
|
|
5188
|
+
this.counters.remoteSnapshotErrors++;
|
|
5189
|
+
this.logger.warn("Remote snapshot rejected: entries is not an array");
|
|
5190
|
+
return 0;
|
|
5191
|
+
}
|
|
5192
|
+
const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
|
|
5193
|
+
this.counters.remoteSnapshotDownloads++;
|
|
5194
|
+
this.counters.remoteSnapshotLastDownloadedAt = Date.now();
|
|
5195
|
+
this.logger.info("Remote cache snapshot loaded (L1 hydrated)", {
|
|
5196
|
+
loaded,
|
|
5197
|
+
total: snapshot.entries.length,
|
|
5198
|
+
sizeKB: this.l1.getStats().sizeKB
|
|
5199
|
+
});
|
|
5200
|
+
return loaded;
|
|
5201
|
+
} catch (err) {
|
|
5202
|
+
this.counters.remoteSnapshotErrors++;
|
|
5203
|
+
this.logger.warn("Remote snapshot load failed \u2014 starting cold", { error: err.message });
|
|
5204
|
+
return 0;
|
|
5205
|
+
}
|
|
5206
|
+
}
|
|
3087
5207
|
// ── Core get (L1 → L1.5 → L2 → fetch) ───────────────────────────────────
|
|
3088
5208
|
/**
|
|
3089
5209
|
* Get a value from cache, or fetch and cache it.
|
|
@@ -3105,6 +5225,7 @@ var CacheService = class _CacheService {
|
|
|
3105
5225
|
* Caches negative lookups to avoid repeated DB hits for missing keys.
|
|
3106
5226
|
*/
|
|
3107
5227
|
async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
|
|
5228
|
+
this._assertActive("get");
|
|
3108
5229
|
const span = this._startSpan("tricache.get");
|
|
3109
5230
|
if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
3110
5231
|
const k = this.nk(cacheKey);
|
|
@@ -3119,9 +5240,10 @@ var CacheService = class _CacheService {
|
|
|
3119
5240
|
if (l1Hit !== null) {
|
|
3120
5241
|
let isGenerationalStale = false;
|
|
3121
5242
|
if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
|
|
3122
|
-
|
|
3123
|
-
|
|
3124
|
-
|
|
5243
|
+
const tags = Object.keys(l1Hit.tagVersions);
|
|
5244
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5245
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5246
|
+
if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
|
|
3125
5247
|
isGenerationalStale = true;
|
|
3126
5248
|
break;
|
|
3127
5249
|
}
|
|
@@ -3135,7 +5257,14 @@ var CacheService = class _CacheService {
|
|
|
3135
5257
|
if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
|
|
3136
5258
|
const priority2 = optPriority ?? inferPriority(cacheKey);
|
|
3137
5259
|
this.revalidating.add(k);
|
|
3138
|
-
void this._revalidate(
|
|
5260
|
+
void this._revalidate(
|
|
5261
|
+
k,
|
|
5262
|
+
fetchFn,
|
|
5263
|
+
ttlSeconds * 1e3,
|
|
5264
|
+
swrGraceMs2,
|
|
5265
|
+
priority2,
|
|
5266
|
+
l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
|
|
5267
|
+
);
|
|
3139
5268
|
this.counters.swrRevalidations++;
|
|
3140
5269
|
this.logger.debug("SWR: serving stale, revalidating", { cacheKey });
|
|
3141
5270
|
} else {
|
|
@@ -3154,7 +5283,14 @@ var CacheService = class _CacheService {
|
|
|
3154
5283
|
if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
|
|
3155
5284
|
const priority2 = optPriority ?? inferPriority(cacheKey);
|
|
3156
5285
|
this.revalidating.add(k);
|
|
3157
|
-
void this._revalidate(
|
|
5286
|
+
void this._revalidate(
|
|
5287
|
+
k,
|
|
5288
|
+
fetchFn,
|
|
5289
|
+
entryTtl,
|
|
5290
|
+
optSwr * 1e3,
|
|
5291
|
+
priority2,
|
|
5292
|
+
l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
|
|
5293
|
+
);
|
|
3158
5294
|
this.counters.swrRevalidations++;
|
|
3159
5295
|
this.logger.debug(
|
|
3160
5296
|
shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
|
|
@@ -3166,116 +5302,148 @@ var CacheService = class _CacheService {
|
|
|
3166
5302
|
this.counters.l1Hits++;
|
|
3167
5303
|
this.opts.onHit?.(cacheKey, "l1");
|
|
3168
5304
|
if (this.opts.frozen) deepFreeze(l1Hit.value);
|
|
3169
|
-
span.setAttribute("cache.hit", "l1").end();
|
|
5305
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "memory").setAttribute("cache.hit_tier", "l1").end();
|
|
3170
5306
|
return this.opts.cloneStrategy === "structuredClone" && l1Hit.value != null && typeof l1Hit.value === "object" ? structuredClone(l1Hit.value) : l1Hit.value;
|
|
3171
5307
|
}
|
|
3172
5308
|
}
|
|
3173
5309
|
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
3174
5310
|
const swrGraceMs = optSwr * 1e3;
|
|
3175
5311
|
const priority = optPriority ?? inferPriority(cacheKey);
|
|
3176
|
-
|
|
5312
|
+
const existing = this.inflight.get(k);
|
|
5313
|
+
if (existing) {
|
|
5314
|
+
this.counters.stampedes++;
|
|
5315
|
+
this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch/read", { cacheKey });
|
|
5316
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
|
|
5317
|
+
return existing;
|
|
5318
|
+
}
|
|
5319
|
+
const mutationEpochAtStart = this._getKeyMutationEpoch(k);
|
|
5320
|
+
const executionPromise = (async () => {
|
|
3177
5321
|
try {
|
|
3178
|
-
|
|
3179
|
-
|
|
3180
|
-
|
|
3181
|
-
|
|
3182
|
-
|
|
3183
|
-
let isStale = false;
|
|
3184
|
-
let storedTagVersions = {};
|
|
3185
|
-
if (hashData.tv) {
|
|
3186
|
-
try {
|
|
3187
|
-
storedTagVersions = JSON.parse(hashData.tv);
|
|
3188
|
-
} catch {
|
|
3189
|
-
}
|
|
5322
|
+
if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
|
|
5323
|
+
if (this._isTombstonedByPattern(k)) {
|
|
5324
|
+
try {
|
|
5325
|
+
this.disk.delete(k);
|
|
5326
|
+
} catch {
|
|
3190
5327
|
}
|
|
3191
|
-
|
|
3192
|
-
|
|
3193
|
-
|
|
3194
|
-
|
|
3195
|
-
|
|
5328
|
+
} else {
|
|
5329
|
+
const isDiskAllowed = this.watchdog.isDiskAllowed();
|
|
5330
|
+
if (isDiskAllowed) {
|
|
5331
|
+
const diskStart = performance.now();
|
|
5332
|
+
const diskHit = this.disk.load(k);
|
|
5333
|
+
const diskElapsed = performance.now() - diskStart;
|
|
5334
|
+
this.watchdog.recordDisk(diskElapsed);
|
|
5335
|
+
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
5336
|
+
if (diskHit !== null) {
|
|
5337
|
+
let isDiskStale = false;
|
|
5338
|
+
if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
|
|
5339
|
+
const tags = Object.keys(diskHit.tagVersions);
|
|
5340
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5341
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5342
|
+
if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
|
|
5343
|
+
isDiskStale = true;
|
|
5344
|
+
break;
|
|
5345
|
+
}
|
|
5346
|
+
}
|
|
5347
|
+
}
|
|
5348
|
+
if (isDiskStale) {
|
|
5349
|
+
this.disk.delete(k);
|
|
5350
|
+
} else {
|
|
5351
|
+
const promoted = this.l1.importEntries(
|
|
5352
|
+
[{ key: k, entry: diskHit }],
|
|
5353
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
5354
|
+
);
|
|
5355
|
+
if (promoted > 0) {
|
|
5356
|
+
const l1Check = this.l1.get(k);
|
|
5357
|
+
if (l1Check !== null) {
|
|
5358
|
+
this.counters.diskHits++;
|
|
5359
|
+
this.opts.onHit?.(cacheKey, "disk");
|
|
5360
|
+
this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
|
|
5361
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
|
|
5362
|
+
if (this.opts.frozen) deepFreeze(l1Check.value);
|
|
5363
|
+
return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
|
|
5364
|
+
}
|
|
5365
|
+
}
|
|
5366
|
+
}
|
|
3196
5367
|
}
|
|
3197
5368
|
}
|
|
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
5369
|
}
|
|
3243
5370
|
}
|
|
3244
|
-
if (
|
|
3245
|
-
|
|
3246
|
-
|
|
3247
|
-
|
|
3248
|
-
|
|
3249
|
-
|
|
3250
|
-
|
|
3251
|
-
|
|
3252
|
-
|
|
3253
|
-
|
|
3254
|
-
|
|
3255
|
-
|
|
3256
|
-
|
|
3257
|
-
|
|
3258
|
-
|
|
3259
|
-
|
|
5371
|
+
if (!this._redisDisabled) {
|
|
5372
|
+
try {
|
|
5373
|
+
const client = await this.getRedis();
|
|
5374
|
+
const redisStart = performance.now();
|
|
5375
|
+
if (this.opts.tagStrategy === "generational") {
|
|
5376
|
+
const hashData = await client.hgetall(k);
|
|
5377
|
+
const redisElapsed = performance.now() - redisStart;
|
|
5378
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
5379
|
+
this.cb.onSuccess();
|
|
5380
|
+
if (hashData && hashData.d) {
|
|
5381
|
+
let isStale = false;
|
|
5382
|
+
let storedTagVersions = {};
|
|
5383
|
+
if (hashData.tv) {
|
|
5384
|
+
try {
|
|
5385
|
+
storedTagVersions = JSON.parse(hashData.tv);
|
|
5386
|
+
} catch {
|
|
5387
|
+
}
|
|
5388
|
+
}
|
|
5389
|
+
const tags = Object.keys(storedTagVersions);
|
|
5390
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5391
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5392
|
+
if (currentVers[i] > storedTagVersions[tags[i]]) {
|
|
5393
|
+
isStale = true;
|
|
5394
|
+
break;
|
|
5395
|
+
}
|
|
5396
|
+
}
|
|
5397
|
+
if (isStale) {
|
|
5398
|
+
const setAtMs = parseInt(hashData.t, 10) || 0;
|
|
5399
|
+
this._deleteIfStale(k, setAtMs);
|
|
5400
|
+
} else {
|
|
5401
|
+
const parsed = await this._decryptAndDeserialize(hashData.d);
|
|
5402
|
+
this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
|
|
5403
|
+
this.counters.l2Hits++;
|
|
5404
|
+
this.opts.onHit?.(cacheKey, "l2");
|
|
5405
|
+
this.logger.debug("L2 hit (Redis hash)", { cacheKey });
|
|
5406
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
5407
|
+
if (this.opts.frozen) deepFreeze(parsed);
|
|
5408
|
+
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
5409
|
+
}
|
|
5410
|
+
}
|
|
5411
|
+
} else {
|
|
5412
|
+
const raw = this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
|
|
5413
|
+
const redisElapsed = performance.now() - redisStart;
|
|
5414
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
5415
|
+
this.cb.onSuccess();
|
|
5416
|
+
if (raw) {
|
|
5417
|
+
const parsed = await this._decryptAndDeserialize(raw);
|
|
5418
|
+
this.l1.set(k, parsed, ttlMs, priority);
|
|
5419
|
+
this.counters.l2Hits++;
|
|
5420
|
+
this.opts.onHit?.(cacheKey, "l2");
|
|
5421
|
+
this.logger.debug("L2 hit (Redis)", { cacheKey });
|
|
5422
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
5423
|
+
if (this.opts.frozen) deepFreeze(parsed);
|
|
5424
|
+
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
5425
|
+
}
|
|
3260
5426
|
}
|
|
5427
|
+
} catch (err) {
|
|
5428
|
+
this.cb.onFailure();
|
|
5429
|
+
this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
|
|
3261
5430
|
}
|
|
3262
5431
|
}
|
|
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 {
|
|
5432
|
+
span.setAttribute("cache.hit", false).setAttribute("cache.hit_tier", "miss");
|
|
5433
|
+
this.opts.onMiss?.(cacheKey);
|
|
3276
5434
|
this.counters.fetches++;
|
|
3277
5435
|
const fetchStart = Date.now();
|
|
3278
|
-
|
|
5436
|
+
let data;
|
|
5437
|
+
try {
|
|
5438
|
+
data = await fetchFn();
|
|
5439
|
+
} catch (fetchErr) {
|
|
5440
|
+
span.setStatus({
|
|
5441
|
+
code: 2,
|
|
5442
|
+
message: fetchErr instanceof Error ? fetchErr.message : String(fetchErr)
|
|
5443
|
+
});
|
|
5444
|
+
span.recordException?.(fetchErr);
|
|
5445
|
+
throw fetchErr;
|
|
5446
|
+
}
|
|
3279
5447
|
const delta = Date.now() - fetchStart;
|
|
3280
5448
|
const notFoundTtlMs = (optNotFoundTtl ?? this.opts.notFoundTtl) * 1e3;
|
|
3281
5449
|
let effectiveTtl = data == null && notFoundTtlMs > 0 ? notFoundTtlMs : ttlMs;
|
|
@@ -3295,14 +5463,27 @@ var CacheService = class _CacheService {
|
|
|
3295
5463
|
let activeTagVersions;
|
|
3296
5464
|
if (optTags?.length) {
|
|
3297
5465
|
if (this.opts.tagStrategy === "generational") {
|
|
5466
|
+
const vers = await Promise.all(optTags.map((tag) => this._getTagVersion(tag)));
|
|
3298
5467
|
activeTagVersions = {};
|
|
3299
|
-
for (
|
|
3300
|
-
activeTagVersions[
|
|
5468
|
+
for (let i = 0; i < optTags.length; i++) {
|
|
5469
|
+
activeTagVersions[optTags[i]] = vers[i];
|
|
3301
5470
|
}
|
|
3302
5471
|
} else {
|
|
3303
5472
|
await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
|
|
3304
5473
|
}
|
|
3305
5474
|
}
|
|
5475
|
+
if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
|
|
5476
|
+
this.logger.debug("Aborting in-flight cache commit \u2014 key was mutated or deleted during fetch", { cacheKey });
|
|
5477
|
+
span.setAttribute("cache.aborted_mutation_race", true);
|
|
5478
|
+
const current = this.l1.get(k);
|
|
5479
|
+
if (current && !current.isStale && current.value !== void 0) {
|
|
5480
|
+
const freshVal = current.value;
|
|
5481
|
+
if (this.opts.frozen) deepFreeze(freshVal);
|
|
5482
|
+
return this.opts.cloneStrategy === "structuredClone" && freshVal != null && typeof freshVal === "object" ? structuredClone(freshVal) : freshVal;
|
|
5483
|
+
}
|
|
5484
|
+
if (this.opts.frozen) deepFreeze(data);
|
|
5485
|
+
return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
|
|
5486
|
+
}
|
|
3306
5487
|
this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
|
|
3307
5488
|
if (!this._redisDisabled) {
|
|
3308
5489
|
try {
|
|
@@ -3339,8 +5520,64 @@ var CacheService = class _CacheService {
|
|
|
3339
5520
|
span.end();
|
|
3340
5521
|
}
|
|
3341
5522
|
})();
|
|
3342
|
-
this.inflight.set(k,
|
|
3343
|
-
return
|
|
5523
|
+
this.inflight.set(k, executionPromise);
|
|
5524
|
+
return executionPromise;
|
|
5525
|
+
}
|
|
5526
|
+
/**
|
|
5527
|
+
* Graceful shutdown flusher for Kubernetes preStop hooks, NestJS onApplicationShutdown,
|
|
5528
|
+
* or manual microservice teardown.
|
|
5529
|
+
*
|
|
5530
|
+
* Flushes both local disk and remote cloud snapshots (S3/R2/GCS), returning a Promise
|
|
5531
|
+
* that resolves when the upload completes or after `timeoutMs` expires.
|
|
5532
|
+
*
|
|
5533
|
+
* @param timeoutMs Maximum time permitted for snapshot persistence before timing out. Default: 8000ms.
|
|
5534
|
+
*/
|
|
5535
|
+
async flushSnapshotOnShutdown(timeoutMs = 8e3) {
|
|
5536
|
+
const flusher = async () => {
|
|
5537
|
+
let localOk = true;
|
|
5538
|
+
let remoteOk = true;
|
|
5539
|
+
if (!this._diskDisabled) {
|
|
5540
|
+
try {
|
|
5541
|
+
this.writeSnapshot();
|
|
5542
|
+
} catch (err) {
|
|
5543
|
+
localOk = false;
|
|
5544
|
+
this.logger.warn("flushSnapshotOnShutdown: disk snapshot write failed", { error: err.message });
|
|
5545
|
+
}
|
|
5546
|
+
}
|
|
5547
|
+
if (this.opts.remoteSnapshot && this.opts.remoteSnapshot.saveOnShutdown !== false) {
|
|
5548
|
+
try {
|
|
5549
|
+
remoteOk = await this.writeRemoteSnapshot();
|
|
5550
|
+
} catch (err) {
|
|
5551
|
+
remoteOk = false;
|
|
5552
|
+
this.logger.warn("flushSnapshotOnShutdown: remote snapshot upload failed", { error: err.message });
|
|
5553
|
+
}
|
|
5554
|
+
}
|
|
5555
|
+
return localOk && remoteOk;
|
|
5556
|
+
};
|
|
5557
|
+
let timer = null;
|
|
5558
|
+
try {
|
|
5559
|
+
return await Promise.race([
|
|
5560
|
+
flusher(),
|
|
5561
|
+
new Promise((resolve) => {
|
|
5562
|
+
timer = setTimeout(() => {
|
|
5563
|
+
this.logger.warn(`flushSnapshotOnShutdown timed out after ${timeoutMs}ms`);
|
|
5564
|
+
resolve(false);
|
|
5565
|
+
}, timeoutMs);
|
|
5566
|
+
if (timer.unref) timer.unref();
|
|
5567
|
+
})
|
|
5568
|
+
]);
|
|
5569
|
+
} finally {
|
|
5570
|
+
if (timer) clearTimeout(timer);
|
|
5571
|
+
}
|
|
5572
|
+
}
|
|
5573
|
+
/**
|
|
5574
|
+
* Internal graceful shutdown trigger invoked by ProcessTerminationBus.
|
|
5575
|
+
*/
|
|
5576
|
+
_triggerShutdown() {
|
|
5577
|
+
if (!this._diskDisabled) this.writeSnapshot();
|
|
5578
|
+
if (this.opts.remoteSnapshot && this.opts.remoteSnapshot.saveOnShutdown !== false) {
|
|
5579
|
+
void this.flushSnapshotOnShutdown();
|
|
5580
|
+
}
|
|
3344
5581
|
}
|
|
3345
5582
|
/**
|
|
3346
5583
|
* Universal fetch-and-cache wrapper with an ergonomic options object.
|
|
@@ -3363,20 +5600,40 @@ var CacheService = class _CacheService {
|
|
|
3363
5600
|
const ttl = options?.ttl ?? 300;
|
|
3364
5601
|
return this.get(cacheKey, fetchFn, ttl, options);
|
|
3365
5602
|
}
|
|
3366
|
-
async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
|
|
5603
|
+
async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority, knownTagVersions) {
|
|
5604
|
+
const startEpoch = this._getKeyMutationEpoch(cacheKey);
|
|
3367
5605
|
try {
|
|
3368
5606
|
const fetchStart = Date.now();
|
|
3369
5607
|
const data = await fetchFn();
|
|
3370
5608
|
const delta = Date.now() - fetchStart;
|
|
3371
5609
|
const staleAt = Date.now() + ttlMs;
|
|
5610
|
+
if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
|
|
5611
|
+
this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during fetch", { cacheKey });
|
|
5612
|
+
return;
|
|
5613
|
+
}
|
|
3372
5614
|
if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
|
|
3373
5615
|
let activeTagVersions;
|
|
3374
5616
|
const l1Existing = this.l1.get(cacheKey);
|
|
3375
|
-
|
|
5617
|
+
const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
|
|
5618
|
+
if (this.opts.tagStrategy === "generational" && tagVersionsSource) {
|
|
5619
|
+
const tags = Object.keys(tagVersionsSource);
|
|
5620
|
+
const vers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
3376
5621
|
activeTagVersions = {};
|
|
3377
|
-
for (
|
|
3378
|
-
activeTagVersions[
|
|
5622
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5623
|
+
activeTagVersions[tags[i]] = vers[i];
|
|
3379
5624
|
}
|
|
5625
|
+
if (knownTagVersions) {
|
|
5626
|
+
for (const t of tags) {
|
|
5627
|
+
if (knownTagVersions[t] !== void 0 && activeTagVersions[t] !== knownTagVersions[t]) {
|
|
5628
|
+
this.logger.debug("SWR: aborting revalidation commit \u2014 tag version bumped during revalidation", { cacheKey, tag: t });
|
|
5629
|
+
return;
|
|
5630
|
+
}
|
|
5631
|
+
}
|
|
5632
|
+
}
|
|
5633
|
+
}
|
|
5634
|
+
if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
|
|
5635
|
+
this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
|
|
5636
|
+
return;
|
|
3380
5637
|
}
|
|
3381
5638
|
this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
|
|
3382
5639
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
@@ -3420,63 +5677,86 @@ var CacheService = class _CacheService {
|
|
|
3420
5677
|
// ── Explicit set / delete ─────────────────────────────────────────────────
|
|
3421
5678
|
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
3422
5679
|
async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
|
|
5680
|
+
this._assertActive("set");
|
|
3423
5681
|
const span = this._startSpan("tricache.set");
|
|
3424
|
-
if (this.opts.tracer)
|
|
3425
|
-
|
|
3426
|
-
|
|
3427
|
-
|
|
3428
|
-
|
|
3429
|
-
|
|
3430
|
-
|
|
3431
|
-
|
|
3432
|
-
|
|
3433
|
-
|
|
3434
|
-
|
|
3435
|
-
|
|
5682
|
+
if (this.opts.tracer) {
|
|
5683
|
+
span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
5684
|
+
span.setAttribute("cache.ttl", ttlSeconds);
|
|
5685
|
+
}
|
|
5686
|
+
try {
|
|
5687
|
+
const effectiveTtlSeconds = ttlSeconds > 0 ? ttlSeconds : ttlSeconds === 0 ? INDEFINITE_TTL_SECONDS : ttlSeconds;
|
|
5688
|
+
const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
|
|
5689
|
+
const p = priority ?? inferPriority(cacheKey);
|
|
5690
|
+
const k = this.nk(cacheKey);
|
|
5691
|
+
this._bumpKeyMutation(k);
|
|
5692
|
+
this.inflight.delete(k);
|
|
5693
|
+
this._pendingDiskDeletes.delete(k);
|
|
5694
|
+
this.counters.sets++;
|
|
5695
|
+
let activeTagVersions;
|
|
5696
|
+
if (opts?.tags?.length) {
|
|
5697
|
+
if (this.opts.tagStrategy === "generational") {
|
|
5698
|
+
const vers = await Promise.all(opts.tags.map((tag) => this._getTagVersion(tag)));
|
|
5699
|
+
activeTagVersions = {};
|
|
5700
|
+
for (let i = 0; i < opts.tags.length; i++) {
|
|
5701
|
+
activeTagVersions[opts.tags[i]] = vers[i];
|
|
5702
|
+
}
|
|
5703
|
+
} else {
|
|
5704
|
+
await this._registerTags(k, opts.tags, ttlSeconds);
|
|
3436
5705
|
}
|
|
3437
|
-
} else {
|
|
3438
|
-
await this._registerTags(k, opts.tags, ttlSeconds);
|
|
3439
5706
|
}
|
|
3440
|
-
|
|
3441
|
-
|
|
3442
|
-
|
|
3443
|
-
|
|
3444
|
-
|
|
3445
|
-
|
|
3446
|
-
|
|
3447
|
-
|
|
3448
|
-
|
|
5707
|
+
this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
|
|
5708
|
+
if (opts?.dependsOn?.length) {
|
|
5709
|
+
for (const pattern of opts.dependsOn) {
|
|
5710
|
+
const nsPattern = this.nk(pattern);
|
|
5711
|
+
let deps = this.dependencyIndex.get(nsPattern);
|
|
5712
|
+
if (!deps) {
|
|
5713
|
+
deps = /* @__PURE__ */ new Set();
|
|
5714
|
+
this.dependencyIndex.set(nsPattern, deps);
|
|
5715
|
+
}
|
|
5716
|
+
deps.add(k);
|
|
3449
5717
|
}
|
|
3450
|
-
deps.add(k);
|
|
3451
5718
|
}
|
|
3452
|
-
|
|
3453
|
-
|
|
3454
|
-
|
|
3455
|
-
|
|
3456
|
-
|
|
3457
|
-
|
|
3458
|
-
|
|
3459
|
-
|
|
3460
|
-
|
|
3461
|
-
|
|
3462
|
-
|
|
3463
|
-
|
|
3464
|
-
|
|
3465
|
-
|
|
3466
|
-
|
|
3467
|
-
|
|
3468
|
-
|
|
3469
|
-
|
|
3470
|
-
|
|
5719
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5720
|
+
try {
|
|
5721
|
+
const client = await this.getRedis();
|
|
5722
|
+
const s = JSON.stringify(data);
|
|
5723
|
+
const stored = await this._serializeAndEncrypt(s);
|
|
5724
|
+
const ttlSec = Math.ceil(ttlMs / 1e3);
|
|
5725
|
+
if (this.opts.tagStrategy === "generational" && activeTagVersions) {
|
|
5726
|
+
const now = Date.now();
|
|
5727
|
+
const tx = client.multi();
|
|
5728
|
+
tx.hset(k, {
|
|
5729
|
+
d: stored,
|
|
5730
|
+
t: String(now),
|
|
5731
|
+
tv: JSON.stringify(activeTagVersions)
|
|
5732
|
+
});
|
|
5733
|
+
tx.expire(k, ttlSec);
|
|
5734
|
+
await tx.exec();
|
|
5735
|
+
} else {
|
|
5736
|
+
if (this.opts.autoPipeline && this.pipeliner) {
|
|
5737
|
+
await this.pipeliner.setex(k, ttlSec, stored);
|
|
5738
|
+
} else {
|
|
5739
|
+
await client.setex(k, ttlSec, stored);
|
|
5740
|
+
}
|
|
5741
|
+
}
|
|
5742
|
+
this.cb.onSuccess();
|
|
5743
|
+
} catch (err) {
|
|
5744
|
+
this.cb.onFailure();
|
|
5745
|
+
this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
|
|
3471
5746
|
}
|
|
3472
|
-
this.cb.onSuccess();
|
|
3473
|
-
} catch (err) {
|
|
3474
|
-
this.cb.onFailure();
|
|
3475
|
-
this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
|
|
3476
5747
|
}
|
|
5748
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
5749
|
+
await this.publishInvalidation("del", k);
|
|
5750
|
+
} else {
|
|
5751
|
+
void this.publishInvalidation("del", k);
|
|
5752
|
+
}
|
|
5753
|
+
} catch (err) {
|
|
5754
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
5755
|
+
span.recordException?.(err);
|
|
5756
|
+
throw err;
|
|
5757
|
+
} finally {
|
|
5758
|
+
span.end();
|
|
3477
5759
|
}
|
|
3478
|
-
void this.publishInvalidation("del", k);
|
|
3479
|
-
span.end();
|
|
3480
5760
|
}
|
|
3481
5761
|
/**
|
|
3482
5762
|
* Register tags for a cache key in the in-process index and (if Redis is enabled) in
|
|
@@ -3516,38 +5796,74 @@ var CacheService = class _CacheService {
|
|
|
3516
5796
|
* await cache.delete('user:abc:*'); // all keys for user abc
|
|
3517
5797
|
*/
|
|
3518
5798
|
async delete(cacheKey) {
|
|
5799
|
+
this._assertActive("delete");
|
|
3519
5800
|
const span = this._startSpan("tricache.delete");
|
|
3520
5801
|
if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
3521
|
-
|
|
3522
|
-
|
|
3523
|
-
|
|
3524
|
-
|
|
3525
|
-
|
|
3526
|
-
|
|
3527
|
-
|
|
3528
|
-
|
|
3529
|
-
|
|
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);
|
|
5802
|
+
try {
|
|
5803
|
+
const isPattern = cacheKey.includes("*");
|
|
5804
|
+
const k = this.nk(cacheKey);
|
|
5805
|
+
this.counters.deletes++;
|
|
5806
|
+
if (isPattern) {
|
|
5807
|
+
const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
|
|
5808
|
+
for (const liveKey of this.l1.liveKeys()) {
|
|
5809
|
+
if (liveKey.startsWith(pfx)) {
|
|
5810
|
+
this._bumpKeyMutation(liveKey);
|
|
5811
|
+
}
|
|
3542
5812
|
}
|
|
3543
|
-
this.
|
|
3544
|
-
|
|
3545
|
-
|
|
3546
|
-
|
|
5813
|
+
for (const inflightKey of Array.from(this.inflight.keys())) {
|
|
5814
|
+
if (inflightKey.startsWith(pfx)) {
|
|
5815
|
+
this._bumpKeyMutation(inflightKey);
|
|
5816
|
+
this.inflight.delete(inflightKey);
|
|
5817
|
+
}
|
|
5818
|
+
}
|
|
5819
|
+
this._addPatternTombstone(pfx);
|
|
5820
|
+
this.l1.deletePattern(k);
|
|
5821
|
+
} else {
|
|
5822
|
+
this._bumpKeyMutation(k);
|
|
5823
|
+
this.inflight.delete(k);
|
|
5824
|
+
this.l1.delete(k);
|
|
5825
|
+
this._pendingDiskDeletes.add(k);
|
|
5826
|
+
setImmediate(() => {
|
|
5827
|
+
try {
|
|
5828
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
5829
|
+
} finally {
|
|
5830
|
+
this._pendingDiskDeletes.delete(k);
|
|
5831
|
+
}
|
|
5832
|
+
});
|
|
5833
|
+
this._cascadeDependencies(k);
|
|
5834
|
+
for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
|
|
5835
|
+
}
|
|
5836
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5837
|
+
try {
|
|
5838
|
+
const client = await this.getRedis();
|
|
5839
|
+
if (isPattern) {
|
|
5840
|
+
const keys = await this._scanKeys(client, k);
|
|
5841
|
+
if (keys.length > 0) await client.del(...keys);
|
|
5842
|
+
} else {
|
|
5843
|
+
if (this.opts.autoPipeline && this.pipeliner) {
|
|
5844
|
+
await this.pipeliner.del(k);
|
|
5845
|
+
} else {
|
|
5846
|
+
await client.del(k);
|
|
5847
|
+
}
|
|
5848
|
+
}
|
|
5849
|
+
this.cb.onSuccess();
|
|
5850
|
+
} catch (err) {
|
|
5851
|
+
this.cb.onFailure();
|
|
5852
|
+
this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
|
|
5853
|
+
}
|
|
5854
|
+
}
|
|
5855
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
5856
|
+
await this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
|
|
5857
|
+
} else {
|
|
5858
|
+
void this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
|
|
3547
5859
|
}
|
|
5860
|
+
} catch (err) {
|
|
5861
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
5862
|
+
span.recordException?.(err);
|
|
5863
|
+
throw err;
|
|
5864
|
+
} finally {
|
|
5865
|
+
span.end();
|
|
3548
5866
|
}
|
|
3549
|
-
void this.publishInvalidation(isPattern ? "del-glob" : "del", k);
|
|
3550
|
-
span.end();
|
|
3551
5867
|
}
|
|
3552
5868
|
// ── Counter (distributed rate limiting) ──────────────────────────────────
|
|
3553
5869
|
/**
|
|
@@ -3567,6 +5883,7 @@ var CacheService = class _CacheService {
|
|
|
3567
5883
|
* fleet-wide.
|
|
3568
5884
|
*/
|
|
3569
5885
|
async increment(cacheKey, ttlSeconds) {
|
|
5886
|
+
this._assertActive("increment");
|
|
3570
5887
|
const k = this.nk(cacheKey);
|
|
3571
5888
|
if (this._redisDisabled) {
|
|
3572
5889
|
if (!this._incrementFallbackWarned) {
|
|
@@ -3608,31 +5925,73 @@ var CacheService = class _CacheService {
|
|
|
3608
5925
|
* await cache.clear('user:abc'); // flush all keys for one user
|
|
3609
5926
|
*/
|
|
3610
5927
|
async clear(prefix) {
|
|
3611
|
-
this.
|
|
3612
|
-
const
|
|
3613
|
-
if (
|
|
3614
|
-
|
|
3615
|
-
|
|
3616
|
-
this.
|
|
3617
|
-
if (
|
|
3618
|
-
|
|
3619
|
-
|
|
3620
|
-
|
|
3621
|
-
|
|
3622
|
-
|
|
3623
|
-
|
|
3624
|
-
const
|
|
3625
|
-
|
|
3626
|
-
|
|
3627
|
-
|
|
3628
|
-
|
|
3629
|
-
|
|
5928
|
+
this._assertActive("clear");
|
|
5929
|
+
const span = this._startSpan("tricache.clear");
|
|
5930
|
+
if (this.opts.tracer) span.setAttribute("cache.prefix", prefix || "*");
|
|
5931
|
+
try {
|
|
5932
|
+
this.counters.deletes++;
|
|
5933
|
+
const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
|
|
5934
|
+
if (k) {
|
|
5935
|
+
const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
|
|
5936
|
+
for (const liveKey of this.l1.liveKeys()) {
|
|
5937
|
+
if (liveKey.startsWith(pfx)) {
|
|
5938
|
+
this._bumpKeyMutation(liveKey);
|
|
5939
|
+
}
|
|
5940
|
+
}
|
|
5941
|
+
for (const inflightKey of Array.from(this.inflight.keys())) {
|
|
5942
|
+
if (inflightKey.startsWith(pfx)) {
|
|
5943
|
+
this._bumpKeyMutation(inflightKey);
|
|
5944
|
+
this.inflight.delete(inflightKey);
|
|
5945
|
+
}
|
|
5946
|
+
}
|
|
5947
|
+
this._addPatternTombstone(pfx);
|
|
5948
|
+
this.l1.deletePattern(k);
|
|
5949
|
+
} else {
|
|
5950
|
+
this._globalEpoch++;
|
|
5951
|
+
this.inflight.clear();
|
|
5952
|
+
this._patternTombstones.length = 0;
|
|
5953
|
+
this.l1.clear();
|
|
5954
|
+
if (!this._diskDisabled) this.disk.clear();
|
|
5955
|
+
this._l1Counters.clear();
|
|
5956
|
+
this.tagIndex.clear();
|
|
5957
|
+
this.tagVersions.clear();
|
|
5958
|
+
this._pendingDiskDeletes.clear();
|
|
5959
|
+
this._keyMutationEpochs.clear();
|
|
5960
|
+
}
|
|
5961
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5962
|
+
try {
|
|
5963
|
+
const client = await this.getRedis();
|
|
5964
|
+
const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
|
|
5965
|
+
const keys = await this._scanKeys(client, pattern);
|
|
5966
|
+
if (keys.length > 0) await client.del(...keys);
|
|
5967
|
+
} catch (err) {
|
|
5968
|
+
this.logger.debug("clear: Redis unavailable", { error: err.message });
|
|
5969
|
+
}
|
|
5970
|
+
}
|
|
5971
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
5972
|
+
await this.publishInvalidation(
|
|
5973
|
+
"del-glob",
|
|
5974
|
+
k ?? (this._namespace ? `${this._namespace}:*` : "*"),
|
|
5975
|
+
void 0,
|
|
5976
|
+
false,
|
|
5977
|
+
true
|
|
5978
|
+
);
|
|
5979
|
+
} else {
|
|
5980
|
+
void this.publishInvalidation(
|
|
5981
|
+
"del-glob",
|
|
5982
|
+
k ?? (this._namespace ? `${this._namespace}:*` : "*"),
|
|
5983
|
+
void 0,
|
|
5984
|
+
false,
|
|
5985
|
+
true
|
|
5986
|
+
);
|
|
3630
5987
|
}
|
|
5988
|
+
} catch (err) {
|
|
5989
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
5990
|
+
span.recordException?.(err);
|
|
5991
|
+
throw err;
|
|
5992
|
+
} finally {
|
|
5993
|
+
span.end();
|
|
3631
5994
|
}
|
|
3632
|
-
void this.publishInvalidation(
|
|
3633
|
-
"del-glob",
|
|
3634
|
-
k ?? (this._namespace ? `${this._namespace}:*` : "*")
|
|
3635
|
-
);
|
|
3636
5995
|
}
|
|
3637
5996
|
/**
|
|
3638
5997
|
* Evict L1 entries that violate the current category or global capacity limits.
|
|
@@ -3640,6 +5999,7 @@ var CacheService = class _CacheService {
|
|
|
3640
5999
|
* Returns the number of entries evicted.
|
|
3641
6000
|
*/
|
|
3642
6001
|
rebalance() {
|
|
6002
|
+
this._assertActive("rebalance");
|
|
3643
6003
|
return this.l1.rebalance();
|
|
3644
6004
|
}
|
|
3645
6005
|
/**
|
|
@@ -3648,6 +6008,7 @@ var CacheService = class _CacheService {
|
|
|
3648
6008
|
* Only reflects L1 state — does not query Redis or disk.
|
|
3649
6009
|
*/
|
|
3650
6010
|
ttl(cacheKey) {
|
|
6011
|
+
this._assertActive("ttl");
|
|
3651
6012
|
return this.l1.ttl(this.nk(cacheKey));
|
|
3652
6013
|
}
|
|
3653
6014
|
/**
|
|
@@ -3655,6 +6016,7 @@ var CacheService = class _CacheService {
|
|
|
3655
6016
|
* Bloom-filter fast path — no fetch, no disk or Redis round-trip.
|
|
3656
6017
|
*/
|
|
3657
6018
|
has(cacheKey) {
|
|
6019
|
+
this._assertActive("has");
|
|
3658
6020
|
return this.l1.has(this.nk(cacheKey));
|
|
3659
6021
|
}
|
|
3660
6022
|
// ── Iteration ─────────────────────────────────────────────────────────────
|
|
@@ -3665,6 +6027,7 @@ var CacheService = class _CacheService {
|
|
|
3665
6027
|
* for (const key of cache.keys()) console.log(key);
|
|
3666
6028
|
*/
|
|
3667
6029
|
*keys() {
|
|
6030
|
+
this._assertActive("keys");
|
|
3668
6031
|
const prefix = this._namespace ? this._namespace + ":" : "";
|
|
3669
6032
|
for (const key of this.l1.liveKeys()) {
|
|
3670
6033
|
if (prefix && !key.startsWith(prefix)) continue;
|
|
@@ -3679,6 +6042,7 @@ var CacheService = class _CacheService {
|
|
|
3679
6042
|
* for (const val of cache.values<User>()) console.log(val.id);
|
|
3680
6043
|
*/
|
|
3681
6044
|
*values() {
|
|
6045
|
+
this._assertActive("values");
|
|
3682
6046
|
const prefix = this._namespace ? this._namespace + ":" : "";
|
|
3683
6047
|
if (!prefix) {
|
|
3684
6048
|
yield* this.l1.liveValues();
|
|
@@ -3697,6 +6061,7 @@ var CacheService = class _CacheService {
|
|
|
3697
6061
|
* for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
|
|
3698
6062
|
*/
|
|
3699
6063
|
*entries() {
|
|
6064
|
+
this._assertActive("entries");
|
|
3700
6065
|
const prefix = this._namespace ? this._namespace + ":" : "";
|
|
3701
6066
|
for (const [key, entry] of this.l1.liveEntries()) {
|
|
3702
6067
|
if (prefix && !key.startsWith(prefix)) continue;
|
|
@@ -3724,6 +6089,7 @@ var CacheService = class _CacheService {
|
|
|
3724
6089
|
* `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
|
|
3725
6090
|
*/
|
|
3726
6091
|
scan(fn) {
|
|
6092
|
+
this._assertActive("scan");
|
|
3727
6093
|
const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
|
|
3728
6094
|
this.l1.scan((key, entry, pfx) => {
|
|
3729
6095
|
const value = entry.value !== void 0 ? entry.value : entry.data;
|
|
@@ -3737,6 +6103,7 @@ var CacheService = class _CacheService {
|
|
|
3737
6103
|
* @param newTtlSeconds - The new TTL from now, in seconds.
|
|
3738
6104
|
*/
|
|
3739
6105
|
async touch(cacheKey, newTtlSeconds) {
|
|
6106
|
+
this._assertActive("touch");
|
|
3740
6107
|
const k = this.nk(cacheKey);
|
|
3741
6108
|
const hit = this.l1.touch(k, newTtlSeconds * 1e3);
|
|
3742
6109
|
if (hit && !this._redisDisabled) {
|
|
@@ -3757,13 +6124,14 @@ var CacheService = class _CacheService {
|
|
|
3757
6124
|
* if (fresh !== null) return fresh; // serve from L1, no network hop
|
|
3758
6125
|
*/
|
|
3759
6126
|
getIfFresh(cacheKey) {
|
|
6127
|
+
this._assertActive("getIfFresh");
|
|
3760
6128
|
const k = this.nk(cacheKey);
|
|
3761
6129
|
const entry = this.l1.getEntry(k);
|
|
3762
6130
|
if (!entry) return null;
|
|
3763
6131
|
const now = Date.now();
|
|
3764
6132
|
if (entry.expiresAt <= now) return null;
|
|
3765
6133
|
if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
|
|
3766
|
-
return entry.value !== void 0 ? entry.value :
|
|
6134
|
+
return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
3767
6135
|
}
|
|
3768
6136
|
/**
|
|
3769
6137
|
* Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
|
|
@@ -3774,6 +6142,7 @@ var CacheService = class _CacheService {
|
|
|
3774
6142
|
* const val = await cache.peek<User>('user:123');
|
|
3775
6143
|
*/
|
|
3776
6144
|
async peek(cacheKey) {
|
|
6145
|
+
this._assertActive("peek");
|
|
3777
6146
|
const k = this.nk(cacheKey);
|
|
3778
6147
|
const l1Hit = this.l1.get(k);
|
|
3779
6148
|
if (l1Hit !== null) {
|
|
@@ -3783,21 +6152,32 @@ var CacheService = class _CacheService {
|
|
|
3783
6152
|
if (this.opts.frozen) deepFreeze(val);
|
|
3784
6153
|
return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
|
|
3785
6154
|
}
|
|
3786
|
-
if (!this._diskDisabled) {
|
|
3787
|
-
|
|
3788
|
-
|
|
3789
|
-
|
|
3790
|
-
|
|
3791
|
-
|
|
3792
|
-
|
|
3793
|
-
|
|
3794
|
-
|
|
3795
|
-
|
|
3796
|
-
|
|
3797
|
-
|
|
3798
|
-
|
|
3799
|
-
|
|
3800
|
-
|
|
6155
|
+
if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
|
|
6156
|
+
if (this._isTombstonedByPattern(k)) {
|
|
6157
|
+
try {
|
|
6158
|
+
this.disk.delete(k);
|
|
6159
|
+
} catch {
|
|
6160
|
+
}
|
|
6161
|
+
} else if (this.watchdog.isDiskAllowed()) {
|
|
6162
|
+
const diskStart = performance.now();
|
|
6163
|
+
const diskHit = this.disk.load(k);
|
|
6164
|
+
const diskElapsed = performance.now() - diskStart;
|
|
6165
|
+
this.watchdog.recordDisk(diskElapsed);
|
|
6166
|
+
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
6167
|
+
if (diskHit !== null) {
|
|
6168
|
+
const promoted = this.l1.importEntries(
|
|
6169
|
+
[{ key: k, entry: diskHit }],
|
|
6170
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
6171
|
+
);
|
|
6172
|
+
if (promoted > 0) {
|
|
6173
|
+
const l1Check = this.l1.get(k);
|
|
6174
|
+
if (l1Check !== null) {
|
|
6175
|
+
this.counters.gets++;
|
|
6176
|
+
this.counters.diskHits++;
|
|
6177
|
+
const val = l1Check.value;
|
|
6178
|
+
if (this.opts.frozen) deepFreeze(val);
|
|
6179
|
+
return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
|
|
6180
|
+
}
|
|
3801
6181
|
}
|
|
3802
6182
|
}
|
|
3803
6183
|
}
|
|
@@ -3805,7 +6185,10 @@ var CacheService = class _CacheService {
|
|
|
3805
6185
|
if (!this._redisDisabled && !this.cb.isOpen) {
|
|
3806
6186
|
try {
|
|
3807
6187
|
const client = await this.getRedis();
|
|
6188
|
+
const redisStart = performance.now();
|
|
3808
6189
|
const raw = await client.get(k);
|
|
6190
|
+
const redisElapsed = performance.now() - redisStart;
|
|
6191
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
3809
6192
|
if (raw !== null) {
|
|
3810
6193
|
const parsed = await this._decryptAndDeserialize(raw);
|
|
3811
6194
|
this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
|
|
@@ -3832,90 +6215,138 @@ var CacheService = class _CacheService {
|
|
|
3832
6215
|
* `(key) => number` so heterogeneous TTLs can be batched in one call.
|
|
3833
6216
|
*/
|
|
3834
6217
|
async mget(keys, fetchFn, ttl = 300, priority) {
|
|
3835
|
-
|
|
3836
|
-
const
|
|
3837
|
-
|
|
3838
|
-
|
|
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
|
-
}
|
|
6218
|
+
this._assertActive("mget");
|
|
6219
|
+
const span = this._startSpan("tricache.mget");
|
|
6220
|
+
if (this.opts.tracer) {
|
|
6221
|
+
span.setAttribute("cache.batch.size", keys.length);
|
|
3848
6222
|
}
|
|
3849
|
-
|
|
3850
|
-
|
|
3851
|
-
|
|
3852
|
-
|
|
3853
|
-
|
|
3854
|
-
const
|
|
3855
|
-
|
|
3856
|
-
|
|
3857
|
-
|
|
3858
|
-
|
|
3859
|
-
|
|
3860
|
-
|
|
3861
|
-
|
|
3862
|
-
|
|
3863
|
-
|
|
3864
|
-
|
|
3865
|
-
|
|
3866
|
-
|
|
3867
|
-
|
|
3868
|
-
|
|
3869
|
-
|
|
6223
|
+
try {
|
|
6224
|
+
const result = Array.from({ length: keys.length });
|
|
6225
|
+
const missIndexes = [];
|
|
6226
|
+
const missKeys = [];
|
|
6227
|
+
for (let i = 0; i < keys.length; i++) {
|
|
6228
|
+
const k = this.nk(keys[i]);
|
|
6229
|
+
const entry = this.l1.getEntry(k);
|
|
6230
|
+
if (entry && entry.expiresAt > Date.now()) {
|
|
6231
|
+
result[i] = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
6232
|
+
this.counters.l1Hits++;
|
|
6233
|
+
} else {
|
|
6234
|
+
missIndexes.push(i);
|
|
6235
|
+
missKeys.push(keys[i]);
|
|
6236
|
+
}
|
|
6237
|
+
}
|
|
6238
|
+
if (missKeys.length === 0) {
|
|
6239
|
+
if (this.opts.tracer) {
|
|
6240
|
+
span.setAttribute("cache.hits", keys.length);
|
|
6241
|
+
span.setAttribute("cache.misses", 0);
|
|
6242
|
+
span.setAttribute("cache.l1_hits", keys.length);
|
|
6243
|
+
span.setAttribute("cache.l2_hits", 0);
|
|
6244
|
+
}
|
|
6245
|
+
return result;
|
|
6246
|
+
}
|
|
6247
|
+
let l2HitCount = 0;
|
|
6248
|
+
if (!this._redisDisabled) {
|
|
6249
|
+
try {
|
|
6250
|
+
const client = await this.getRedis();
|
|
6251
|
+
const nsKeys = missKeys.map((k) => this.nk(k));
|
|
6252
|
+
const pipeline = client.multi();
|
|
6253
|
+
for (const nk of nsKeys) pipeline.get(nk);
|
|
6254
|
+
const redisStart = performance.now();
|
|
6255
|
+
const raws = await pipeline.exec();
|
|
6256
|
+
const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
|
|
6257
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
6258
|
+
this.cb.onSuccess();
|
|
6259
|
+
for (let j = 0; j < missKeys.length; j++) {
|
|
6260
|
+
const raw = raws[j] ? raws[j][1] : null;
|
|
6261
|
+
const idx = missIndexes[j];
|
|
6262
|
+
if (raw) {
|
|
6263
|
+
const parsed = await this._decryptAndDeserialize(raw);
|
|
6264
|
+
const k = nsKeys[j];
|
|
6265
|
+
const p = priority ?? inferPriority(missKeys[j]);
|
|
6266
|
+
this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
|
|
6267
|
+
this.counters.l2Hits++;
|
|
6268
|
+
l2HitCount++;
|
|
6269
|
+
result[idx] = parsed;
|
|
6270
|
+
missIndexes[j] = -1;
|
|
6271
|
+
missKeys[j] = "";
|
|
6272
|
+
}
|
|
3870
6273
|
}
|
|
6274
|
+
const remainingIdx = missIndexes.filter((i) => i >= 0);
|
|
6275
|
+
const remainingKeys = missKeys.filter((k) => k !== "");
|
|
6276
|
+
missIndexes.length = 0;
|
|
6277
|
+
missKeys.length = 0;
|
|
6278
|
+
missIndexes.push(...remainingIdx);
|
|
6279
|
+
missKeys.push(...remainingKeys);
|
|
6280
|
+
} catch (err) {
|
|
6281
|
+
this.cb.onFailure();
|
|
6282
|
+
this.logger.debug("mget: Redis unavailable, continuing to disk/fetch", { error: err.message });
|
|
3871
6283
|
}
|
|
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
6284
|
}
|
|
3883
|
-
|
|
3884
|
-
|
|
3885
|
-
|
|
3886
|
-
|
|
3887
|
-
|
|
3888
|
-
|
|
3889
|
-
|
|
3890
|
-
|
|
3891
|
-
|
|
3892
|
-
|
|
3893
|
-
|
|
3894
|
-
|
|
3895
|
-
|
|
3896
|
-
|
|
3897
|
-
|
|
3898
|
-
|
|
3899
|
-
|
|
6285
|
+
if (!this._diskDisabled && missKeys.length > 0) {
|
|
6286
|
+
for (let j = missKeys.length - 1; j >= 0; j--) {
|
|
6287
|
+
const k = this.nk(missKeys[j]);
|
|
6288
|
+
if (this._pendingDiskDeletes.has(k)) continue;
|
|
6289
|
+
if (this._isTombstonedByPattern(k)) {
|
|
6290
|
+
try {
|
|
6291
|
+
this.disk.delete(k);
|
|
6292
|
+
} catch {
|
|
6293
|
+
}
|
|
6294
|
+
continue;
|
|
6295
|
+
}
|
|
6296
|
+
if (!this.watchdog.isDiskAllowed()) continue;
|
|
6297
|
+
const diskStart = performance.now();
|
|
6298
|
+
const diskHit = this.disk.load(k);
|
|
6299
|
+
const diskElapsed = performance.now() - diskStart;
|
|
6300
|
+
this.watchdog.recordDisk(diskElapsed);
|
|
6301
|
+
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
6302
|
+
if (diskHit !== null) {
|
|
6303
|
+
const promoted = this.l1.importEntries(
|
|
6304
|
+
[{ key: k, entry: diskHit }],
|
|
6305
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
6306
|
+
);
|
|
6307
|
+
if (promoted > 0) {
|
|
6308
|
+
const l1Check = this.l1.get(k);
|
|
6309
|
+
if (l1Check !== null) {
|
|
6310
|
+
this.counters.diskHits++;
|
|
6311
|
+
result[missIndexes[j]] = l1Check.value;
|
|
6312
|
+
missIndexes.splice(j, 1);
|
|
6313
|
+
missKeys.splice(j, 1);
|
|
6314
|
+
}
|
|
3900
6315
|
}
|
|
3901
6316
|
}
|
|
3902
6317
|
}
|
|
3903
6318
|
}
|
|
3904
|
-
if (missKeys.length
|
|
3905
|
-
|
|
3906
|
-
|
|
3907
|
-
|
|
3908
|
-
|
|
3909
|
-
|
|
3910
|
-
|
|
3911
|
-
|
|
3912
|
-
|
|
3913
|
-
|
|
3914
|
-
|
|
6319
|
+
if (missKeys.length > 0) {
|
|
6320
|
+
this.counters.fetches++;
|
|
6321
|
+
const fetched = await fetchFn(missKeys);
|
|
6322
|
+
const setPromises = [];
|
|
6323
|
+
for (let j = 0; j < missKeys.length; j++) {
|
|
6324
|
+
const v = fetched[missKeys[j]];
|
|
6325
|
+
result[missIndexes[j]] = v;
|
|
6326
|
+
if (v !== void 0) {
|
|
6327
|
+
const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
|
|
6328
|
+
setPromises.push(this.set(missKeys[j], v, resolvedTtl, priority));
|
|
6329
|
+
}
|
|
3915
6330
|
}
|
|
6331
|
+
if (setPromises.length > 0) {
|
|
6332
|
+
await Promise.all(setPromises);
|
|
6333
|
+
}
|
|
6334
|
+
}
|
|
6335
|
+
if (this.opts.tracer) {
|
|
6336
|
+
const finalMisses = missKeys.length;
|
|
6337
|
+
const totalHits = keys.length - finalMisses;
|
|
6338
|
+
span.setAttribute("cache.hits", totalHits);
|
|
6339
|
+
span.setAttribute("cache.misses", finalMisses);
|
|
6340
|
+
span.setAttribute("cache.l2_hits", l2HitCount);
|
|
3916
6341
|
}
|
|
6342
|
+
return result;
|
|
6343
|
+
} catch (err) {
|
|
6344
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6345
|
+
span.recordException?.(err);
|
|
6346
|
+
throw err;
|
|
6347
|
+
} finally {
|
|
6348
|
+
span.end();
|
|
3917
6349
|
}
|
|
3918
|
-
return result;
|
|
3919
6350
|
}
|
|
3920
6351
|
/**
|
|
3921
6352
|
* Returns a Promise that resolves once the cache is fully initialised and any
|
|
@@ -3942,12 +6373,25 @@ var CacheService = class _CacheService {
|
|
|
3942
6373
|
* });
|
|
3943
6374
|
*/
|
|
3944
6375
|
async mset(entries) {
|
|
6376
|
+
this._assertActive("mset");
|
|
6377
|
+
const span = this._startSpan("tricache.mset");
|
|
3945
6378
|
const keys = Object.keys(entries);
|
|
3946
|
-
|
|
3947
|
-
|
|
3948
|
-
|
|
3949
|
-
|
|
3950
|
-
|
|
6379
|
+
if (this.opts.tracer) {
|
|
6380
|
+
span.setAttribute("cache.batch.size", keys.length);
|
|
6381
|
+
}
|
|
6382
|
+
try {
|
|
6383
|
+
await Promise.all(keys.map((key) => {
|
|
6384
|
+
const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
|
|
6385
|
+
const hasOpts = tags?.length || dependsOn?.length;
|
|
6386
|
+
return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
|
|
6387
|
+
}));
|
|
6388
|
+
} catch (err) {
|
|
6389
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6390
|
+
span.recordException?.(err);
|
|
6391
|
+
throw err;
|
|
6392
|
+
} finally {
|
|
6393
|
+
span.end();
|
|
6394
|
+
}
|
|
3951
6395
|
}
|
|
3952
6396
|
/**
|
|
3953
6397
|
* Batch delete — delete multiple exact keys in a single call.
|
|
@@ -3957,7 +6401,20 @@ var CacheService = class _CacheService {
|
|
|
3957
6401
|
* await cache.mdel(['user:1', 'user:2', 'user:3']);
|
|
3958
6402
|
*/
|
|
3959
6403
|
async mdel(keys) {
|
|
3960
|
-
|
|
6404
|
+
this._assertActive("mdel");
|
|
6405
|
+
const span = this._startSpan("tricache.mdel");
|
|
6406
|
+
if (this.opts.tracer) {
|
|
6407
|
+
span.setAttribute("cache.batch.size", keys.length);
|
|
6408
|
+
}
|
|
6409
|
+
try {
|
|
6410
|
+
await Promise.all(keys.map((k) => this.delete(k)));
|
|
6411
|
+
} catch (err) {
|
|
6412
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6413
|
+
span.recordException?.(err);
|
|
6414
|
+
throw err;
|
|
6415
|
+
} finally {
|
|
6416
|
+
span.end();
|
|
6417
|
+
}
|
|
3961
6418
|
}
|
|
3962
6419
|
/**
|
|
3963
6420
|
* Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
|
|
@@ -3972,6 +6429,7 @@ var CacheService = class _CacheService {
|
|
|
3972
6429
|
* console.log(`Warmed ${loaded} keys from Redis`);
|
|
3973
6430
|
*/
|
|
3974
6431
|
async warmFromL2(pattern, opts) {
|
|
6432
|
+
this._assertActive("warmFromL2");
|
|
3975
6433
|
if (this._redisDisabled) return 0;
|
|
3976
6434
|
try {
|
|
3977
6435
|
const client = await this.getRedis();
|
|
@@ -3986,7 +6444,6 @@ var CacheService = class _CacheService {
|
|
|
3986
6444
|
const results = await pl.exec();
|
|
3987
6445
|
this.cb.onSuccess();
|
|
3988
6446
|
let loaded = 0;
|
|
3989
|
-
const now = Date.now();
|
|
3990
6447
|
for (let i = 0; i < matchedKeys.length; i++) {
|
|
3991
6448
|
const [err, raw] = results[i];
|
|
3992
6449
|
if (err || raw == null) continue;
|
|
@@ -3998,7 +6455,6 @@ var CacheService = class _CacheService {
|
|
|
3998
6455
|
} catch {
|
|
3999
6456
|
}
|
|
4000
6457
|
}
|
|
4001
|
-
void now;
|
|
4002
6458
|
this.logger.info("warmFromL2 complete", {
|
|
4003
6459
|
pattern,
|
|
4004
6460
|
matched: matchedKeys.length,
|
|
@@ -4020,45 +6476,71 @@ var CacheService = class _CacheService {
|
|
|
4020
6476
|
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
4021
6477
|
*/
|
|
4022
6478
|
async invalidateTag(tag) {
|
|
4023
|
-
|
|
4024
|
-
|
|
6479
|
+
this._assertActive("invalidateTag");
|
|
6480
|
+
const span = this._startSpan("tricache.invalidate_tag");
|
|
6481
|
+
if (this.opts.tracer) {
|
|
6482
|
+
span.setAttribute("cache.tag", tag);
|
|
6483
|
+
span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
|
|
6484
|
+
}
|
|
6485
|
+
try {
|
|
6486
|
+
if (this.opts.tagStrategy === "generational") {
|
|
6487
|
+
let newVer = 1;
|
|
6488
|
+
if (!this._redisDisabled) {
|
|
6489
|
+
try {
|
|
6490
|
+
const client = await this.getRedis();
|
|
6491
|
+
newVer = await client.incr(this.nk(`tag_ver:${tag}`));
|
|
6492
|
+
} catch (err) {
|
|
6493
|
+
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
6494
|
+
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
6495
|
+
newVer = current + 1;
|
|
6496
|
+
}
|
|
6497
|
+
} else {
|
|
6498
|
+
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
6499
|
+
newVer = current + 1;
|
|
6500
|
+
}
|
|
6501
|
+
this._setLocalTagVersion(tag, newVer, performance.now());
|
|
6502
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6503
|
+
await this.publishInvalidation("tag_incr", tag, newVer, false, true);
|
|
6504
|
+
} else {
|
|
6505
|
+
void this.publishInvalidation("tag_incr", tag, newVer, false, true);
|
|
6506
|
+
}
|
|
6507
|
+
return;
|
|
6508
|
+
}
|
|
6509
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
6510
|
+
const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
|
|
6511
|
+
for (const k of members) {
|
|
6512
|
+
this.l1.delete(k);
|
|
6513
|
+
this._bumpKeyMutation(k);
|
|
6514
|
+
this._pendingDiskDeletes.add(k);
|
|
6515
|
+
setImmediate(() => {
|
|
6516
|
+
try {
|
|
6517
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
6518
|
+
} finally {
|
|
6519
|
+
this._pendingDiskDeletes.delete(k);
|
|
6520
|
+
}
|
|
6521
|
+
});
|
|
6522
|
+
}
|
|
6523
|
+
this.tagIndex.delete(tagKey);
|
|
4025
6524
|
if (!this._redisDisabled) {
|
|
4026
6525
|
try {
|
|
4027
6526
|
const client = await this.getRedis();
|
|
4028
|
-
|
|
6527
|
+
const redisMembers = await client.smembers(tagKey);
|
|
6528
|
+
const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
|
|
6529
|
+
if (toDelete.length > 0) {
|
|
6530
|
+
await client.del(...toDelete, tagKey);
|
|
6531
|
+
} else {
|
|
6532
|
+
await client.del(tagKey);
|
|
6533
|
+
}
|
|
4029
6534
|
} catch (err) {
|
|
4030
6535
|
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
6536
|
}
|
|
4059
|
-
} catch (err) {
|
|
4060
|
-
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
4061
6537
|
}
|
|
6538
|
+
} catch (err) {
|
|
6539
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6540
|
+
span.recordException?.(err);
|
|
6541
|
+
throw err;
|
|
6542
|
+
} finally {
|
|
6543
|
+
span.end();
|
|
4062
6544
|
}
|
|
4063
6545
|
}
|
|
4064
6546
|
/**
|
|
@@ -4074,13 +6556,14 @@ var CacheService = class _CacheService {
|
|
|
4074
6556
|
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
|
|
4075
6557
|
*/
|
|
4076
6558
|
async invalidateTags(tags) {
|
|
6559
|
+
this._assertActive("invalidateTags");
|
|
4077
6560
|
if (tags.length === 0) return;
|
|
4078
6561
|
if (tags.length === 1) {
|
|
4079
6562
|
await this.invalidateTag(tags[0]);
|
|
4080
6563
|
return;
|
|
4081
6564
|
}
|
|
4082
6565
|
if (this.opts.tagStrategy === "generational") {
|
|
4083
|
-
const now =
|
|
6566
|
+
const now = performance.now();
|
|
4084
6567
|
if (!this._redisDisabled) {
|
|
4085
6568
|
try {
|
|
4086
6569
|
const client = await this.getRedis();
|
|
@@ -4091,7 +6574,11 @@ var CacheService = class _CacheService {
|
|
|
4091
6574
|
const [err, newVer] = results[i] ?? [null, null];
|
|
4092
6575
|
const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
|
|
4093
6576
|
this._setLocalTagVersion(tags[i], ver, now);
|
|
4094
|
-
|
|
6577
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6578
|
+
await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
|
|
6579
|
+
} else {
|
|
6580
|
+
void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
|
|
6581
|
+
}
|
|
4095
6582
|
}
|
|
4096
6583
|
return;
|
|
4097
6584
|
} catch (err) {
|
|
@@ -4101,7 +6588,11 @@ var CacheService = class _CacheService {
|
|
|
4101
6588
|
for (const tag of tags) {
|
|
4102
6589
|
const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
4103
6590
|
this._setLocalTagVersion(tag, ver, now);
|
|
4104
|
-
|
|
6591
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6592
|
+
await this.publishInvalidation("tag_incr", tag, ver, false, true);
|
|
6593
|
+
} else {
|
|
6594
|
+
void this.publishInvalidation("tag_incr", tag, ver, false, true);
|
|
6595
|
+
}
|
|
4105
6596
|
}
|
|
4106
6597
|
return;
|
|
4107
6598
|
}
|
|
@@ -4116,7 +6607,15 @@ var CacheService = class _CacheService {
|
|
|
4116
6607
|
}
|
|
4117
6608
|
for (const k of allMembers) {
|
|
4118
6609
|
this.l1.delete(k);
|
|
4119
|
-
this.
|
|
6610
|
+
this._bumpKeyMutation(k);
|
|
6611
|
+
this._pendingDiskDeletes.add(k);
|
|
6612
|
+
setImmediate(() => {
|
|
6613
|
+
try {
|
|
6614
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
6615
|
+
} finally {
|
|
6616
|
+
this._pendingDiskDeletes.delete(k);
|
|
6617
|
+
}
|
|
6618
|
+
});
|
|
4120
6619
|
}
|
|
4121
6620
|
if (!this._redisDisabled) {
|
|
4122
6621
|
try {
|
|
@@ -4153,6 +6652,7 @@ var CacheService = class _CacheService {
|
|
|
4153
6652
|
* `l2` is `null` when Redis is disabled.
|
|
4154
6653
|
*/
|
|
4155
6654
|
async ping() {
|
|
6655
|
+
this._assertActive("ping");
|
|
4156
6656
|
const t0 = Date.now();
|
|
4157
6657
|
this.l1.has("__ping__");
|
|
4158
6658
|
const l1 = Date.now() - t0;
|
|
@@ -4172,12 +6672,67 @@ var CacheService = class _CacheService {
|
|
|
4172
6672
|
}
|
|
4173
6673
|
return { l1, disk, l2 };
|
|
4174
6674
|
}
|
|
6675
|
+
/**
|
|
6676
|
+
* Health and readiness diagnostics for container orchestrators (e.g. Kubernetes, ECS, Nomad).
|
|
6677
|
+
*
|
|
6678
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
6679
|
+
* ⚠️ CRITICAL CONTAINER PROBE SEMANTICS (Liveness vs. Readiness):
|
|
6680
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
6681
|
+
* ❌ NEVER bind `degraded` checks or `cache.health()` to your Liveness Probe (/livez, /healthz).
|
|
6682
|
+
* If an SRE hooks degraded status into liveness, a storage-starved or EBS-throttled pod
|
|
6683
|
+
* will be killed by the kubelet, triggering a cluster-wide cascading restart shockwave.
|
|
6684
|
+
* Liveness probes must only check that the event loop / process is alive.
|
|
6685
|
+
*
|
|
6686
|
+
* ✅ BIND degraded checks strictly to your Readiness Probe (/ready, /readyz).
|
|
6687
|
+
* A degraded cache (e.g. EBS latency spike, quota watermark pruning, or open Redis circuit)
|
|
6688
|
+
* can shed traffic at the ingress load balancer while the Node.js process remains
|
|
6689
|
+
* alive to drain in-flight promises and heal its local storage.
|
|
6690
|
+
*
|
|
6691
|
+
* By default, `healthy` remains `true` even when degraded (graceful local degradation).
|
|
6692
|
+
* Set `failReadinessOnDegraded: true` in CacheOptions if you want your Readiness probe
|
|
6693
|
+
* to route ingress traffic away while degraded.
|
|
6694
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
6695
|
+
*/
|
|
6696
|
+
health() {
|
|
6697
|
+
const watchdogTel = this.watchdog.getTelemetry();
|
|
6698
|
+
const diskPruning = !this._diskDisabled && this.disk.isPruning;
|
|
6699
|
+
const diskLowSpace = !this._diskDisabled && this.disk.hostVolumeLowSpace;
|
|
6700
|
+
const circuitOpen = this.cb.isOpen;
|
|
6701
|
+
const latencyBypass = watchdogTel.bypassActive;
|
|
6702
|
+
const degraded = circuitOpen || latencyBypass || diskPruning || diskLowSpace;
|
|
6703
|
+
const healthy = this.opts.failReadinessOnDegraded ? !degraded : true;
|
|
6704
|
+
const reasons = [];
|
|
6705
|
+
if (circuitOpen) reasons.push("redis_circuit_breaker_open");
|
|
6706
|
+
if (latencyBypass) reasons.push(`disk_latency_bypass_stage_${watchdogTel.bypassStage}`);
|
|
6707
|
+
if (diskPruning) reasons.push("disk_quota_watermark_pruning_active");
|
|
6708
|
+
if (diskLowSpace) reasons.push("disk_host_volume_low_space");
|
|
6709
|
+
return {
|
|
6710
|
+
healthy,
|
|
6711
|
+
degraded,
|
|
6712
|
+
reasons,
|
|
6713
|
+
details: {
|
|
6714
|
+
redisConnected: !circuitOpen && !this._redisDisabled,
|
|
6715
|
+
circuitBreakerState: this.cb.currentState,
|
|
6716
|
+
diskPruningActive: diskPruning,
|
|
6717
|
+
diskHostVolumeLowSpace: diskLowSpace,
|
|
6718
|
+
watchdog: watchdogTel
|
|
6719
|
+
}
|
|
6720
|
+
};
|
|
6721
|
+
}
|
|
6722
|
+
/**
|
|
6723
|
+
* Direct access to the internal tier latency watchdog instance.
|
|
6724
|
+
* Used for diagnostics, canary probes, and control-loop tuning.
|
|
6725
|
+
*/
|
|
6726
|
+
getLatencyWatchdog() {
|
|
6727
|
+
return this.watchdog;
|
|
6728
|
+
}
|
|
4175
6729
|
/**
|
|
4176
6730
|
* Export all live L1 entries to Redis via a single pipeline.
|
|
4177
6731
|
* Useful for warming a new Redis instance or for zero-downtime failover.
|
|
4178
6732
|
* Returns the number of keys written.
|
|
4179
6733
|
*/
|
|
4180
6734
|
async drainToL2() {
|
|
6735
|
+
this._assertActive("drainToL2");
|
|
4181
6736
|
if (this._redisDisabled) return 0;
|
|
4182
6737
|
try {
|
|
4183
6738
|
const client = await this.getRedis();
|
|
@@ -4221,6 +6776,7 @@ var CacheService = class _CacheService {
|
|
|
4221
6776
|
* if (!claimed) return res.status(409).json({ error: 'duplicate request' });
|
|
4222
6777
|
*/
|
|
4223
6778
|
async setIfAbsent(cacheKey, value, ttlSeconds = 300, priority) {
|
|
6779
|
+
this._assertActive("setIfAbsent");
|
|
4224
6780
|
const k = this.nk(cacheKey);
|
|
4225
6781
|
if (this.l1.has(k)) return false;
|
|
4226
6782
|
if (!this._redisDisabled) {
|
|
@@ -4239,6 +6795,8 @@ var CacheService = class _CacheService {
|
|
|
4239
6795
|
}
|
|
4240
6796
|
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
4241
6797
|
const p = priority ?? inferPriority(cacheKey);
|
|
6798
|
+
this._bumpKeyMutation(k);
|
|
6799
|
+
this._pendingDiskDeletes.delete(k);
|
|
4242
6800
|
this.l1.set(k, value, ttlMs, p);
|
|
4243
6801
|
this.counters.sets++;
|
|
4244
6802
|
return true;
|
|
@@ -4257,6 +6815,7 @@ var CacheService = class _CacheService {
|
|
|
4257
6815
|
* @param options TTL, acquire timeout, and retry polling intervals.
|
|
4258
6816
|
*/
|
|
4259
6817
|
async lock(resourceKey, fn, options) {
|
|
6818
|
+
this._assertActive("lock");
|
|
4260
6819
|
const ttlSeconds = Math.max(1, options?.ttl ?? 30);
|
|
4261
6820
|
const acquireTimeout = Math.max(0, options?.acquireTimeout ?? 5e3);
|
|
4262
6821
|
const retryInterval = Math.max(10, options?.retryInterval ?? 100);
|
|
@@ -4283,6 +6842,10 @@ var CacheService = class _CacheService {
|
|
|
4283
6842
|
}
|
|
4284
6843
|
} catch (err) {
|
|
4285
6844
|
if (err.message.startsWith("Failed to acquire lock")) throw err;
|
|
6845
|
+
const failClosed = options?.failClosedOnRedisError ?? this.opts.lockFailClosed;
|
|
6846
|
+
if (failClosed) {
|
|
6847
|
+
throw new Error(`Distributed lock acquisition failed for resource "${resourceKey}" due to Redis error: ${err.message}`);
|
|
6848
|
+
}
|
|
4286
6849
|
this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
|
|
4287
6850
|
resourceKey,
|
|
4288
6851
|
error: err.message
|
|
@@ -4419,7 +6982,7 @@ var CacheService = class _CacheService {
|
|
|
4419
6982
|
if (visited.has(dep)) continue;
|
|
4420
6983
|
this.l1.delete(dep);
|
|
4421
6984
|
if (!this._diskDisabled) this.disk.delete(dep);
|
|
4422
|
-
void this.publishInvalidation("del", dep);
|
|
6985
|
+
void this.publishInvalidation("del", dep, void 0, false, true);
|
|
4423
6986
|
this.logger.debug("Dependency cascade: invalidated dependent key", {
|
|
4424
6987
|
trigger: deletedKey.slice(0, 60),
|
|
4425
6988
|
dependent: dep.slice(0, 60)
|
|
@@ -4484,12 +7047,36 @@ var CacheService = class _CacheService {
|
|
|
4484
7047
|
evictions: c.oomEvictions,
|
|
4485
7048
|
lastTriggeredAt: c.oomLastAt
|
|
4486
7049
|
},
|
|
7050
|
+
...this.opts.remoteSnapshot && {
|
|
7051
|
+
remoteSnapshot: {
|
|
7052
|
+
enabled: true,
|
|
7053
|
+
uploads: c.remoteSnapshotUploads,
|
|
7054
|
+
downloads: c.remoteSnapshotDownloads,
|
|
7055
|
+
errors: c.remoteSnapshotErrors,
|
|
7056
|
+
lastUploadedAt: c.remoteSnapshotLastUploadedAt,
|
|
7057
|
+
lastDownloadedAt: c.remoteSnapshotLastDownloadedAt
|
|
7058
|
+
}
|
|
7059
|
+
},
|
|
7060
|
+
...this.opts.crossRegion && {
|
|
7061
|
+
crossRegion: {
|
|
7062
|
+
enabled: true,
|
|
7063
|
+
currentRegion: this.opts.crossRegion.currentRegion,
|
|
7064
|
+
sent: c.crossRegionSent,
|
|
7065
|
+
received: c.crossRegionReceived,
|
|
7066
|
+
deduplicated: c.crossRegionDeduplicated,
|
|
7067
|
+
errors: c.crossRegionErrors
|
|
7068
|
+
}
|
|
7069
|
+
},
|
|
4487
7070
|
l1: {
|
|
4488
7071
|
entries: l1s.entries,
|
|
4489
7072
|
sizeBytes: this.l1.memoryUsage,
|
|
4490
7073
|
maxBytes: this.opts.l1MaxBytes
|
|
4491
7074
|
},
|
|
4492
|
-
disk: {
|
|
7075
|
+
disk: {
|
|
7076
|
+
...this.disk.stats,
|
|
7077
|
+
disabled: this._diskDisabled,
|
|
7078
|
+
latencyWatchdog: this.watchdog.getTelemetry()
|
|
7079
|
+
},
|
|
4493
7080
|
...this.latencyTracker && {
|
|
4494
7081
|
adaptiveTtl: {
|
|
4495
7082
|
enabled: true,
|
|
@@ -4502,9 +7089,16 @@ var CacheService = class _CacheService {
|
|
|
4502
7089
|
this.opts.adaptiveTtlMaxMs
|
|
4503
7090
|
)
|
|
4504
7091
|
}
|
|
7092
|
+
},
|
|
7093
|
+
...this.pipeliner && {
|
|
7094
|
+
pipelining: this.pipeliner.stats
|
|
4505
7095
|
}
|
|
4506
7096
|
};
|
|
4507
7097
|
}
|
|
7098
|
+
/** Return auto-pipelining metrics, or null if pipelining is disabled. */
|
|
7099
|
+
getPipelinerStats() {
|
|
7100
|
+
return this.pipeliner ? this.pipeliner.stats : null;
|
|
7101
|
+
}
|
|
4508
7102
|
/**
|
|
4509
7103
|
* Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
|
|
4510
7104
|
* Paste the result into your `/metrics` endpoint.
|
|
@@ -4544,6 +7138,18 @@ var CacheService = class _CacheService {
|
|
|
4544
7138
|
gauge("l1_entries", m.l1.entries, "Current L1 entry count");
|
|
4545
7139
|
gauge("l1_size_bytes", m.l1.sizeBytes, "Current L1 used bytes");
|
|
4546
7140
|
gauge("disk_files", m.disk.files, "Current L1.5 disk file count");
|
|
7141
|
+
if (m.disk.latencyWatchdog) {
|
|
7142
|
+
gauge("disk_latency_bypass_stage", m.disk.latencyWatchdog.bypassStage, "Disk latency watchdog bypass stage (0: normal, 1: 25%, 2: 75%, 3: 100%)");
|
|
7143
|
+
gauge("disk_p95_ms", m.disk.latencyWatchdog.diskP95Ms, "Disk read p95 latency in ms");
|
|
7144
|
+
gauge("redis_p95_ms", m.disk.latencyWatchdog.redisP95Ms, "Redis read p95 latency in ms");
|
|
7145
|
+
counter("disk_bypassed_events", m.disk.latencyWatchdog.bypassedTotal, "Total disk bypass activation events");
|
|
7146
|
+
}
|
|
7147
|
+
if (m.disk.pruning) {
|
|
7148
|
+
counter("disk_spills_shed", m.disk.pruning.spillsShedTotal, "Total disk spills shed due to pruning or low disk space");
|
|
7149
|
+
counter("disk_prune_rounds", m.disk.pruning.pruneRounds, "Total high-watermark disk prune rounds");
|
|
7150
|
+
counter("disk_entries_pruned", m.disk.pruning.entriesPruned, "Total entries removed by watermark pruning");
|
|
7151
|
+
counter("disk_low_space_pauses", m.disk.pruning.hostVolumeLowSpacePauses, "Total times spills paused due to <10% host volume space");
|
|
7152
|
+
}
|
|
4547
7153
|
gauge(
|
|
4548
7154
|
"bloom_false_positive_rate",
|
|
4549
7155
|
m.bloom.falsePositiveRate,
|
|
@@ -4565,6 +7171,17 @@ var CacheService = class _CacheService {
|
|
|
4565
7171
|
"Emergency L1 eviction rounds triggered by heap pressure"
|
|
4566
7172
|
);
|
|
4567
7173
|
}
|
|
7174
|
+
if (m.remoteSnapshot?.enabled) {
|
|
7175
|
+
counter("remote_snapshot_uploads", m.remoteSnapshot.uploads, "Total remote snapshot uploads");
|
|
7176
|
+
counter("remote_snapshot_downloads", m.remoteSnapshot.downloads, "Total remote snapshot downloads");
|
|
7177
|
+
counter("remote_snapshot_errors", m.remoteSnapshot.errors, "Total remote snapshot errors");
|
|
7178
|
+
}
|
|
7179
|
+
if (m.crossRegion?.enabled) {
|
|
7180
|
+
counter("cross_region_sent", m.crossRegion.sent, "Total cross-region invalidations broadcast");
|
|
7181
|
+
counter("cross_region_received", m.crossRegion.received, "Total cross-region invalidations received");
|
|
7182
|
+
counter("cross_region_deduplicated", m.crossRegion.deduplicated, "Total cross-region invalidations deduplicated or self-filtered");
|
|
7183
|
+
counter("cross_region_errors", m.crossRegion.errors, "Total cross-region relay errors");
|
|
7184
|
+
}
|
|
4568
7185
|
return lines.join("\n");
|
|
4569
7186
|
}
|
|
4570
7187
|
// ── Lifecycle ────────────────────────────────────────────────────────────
|
|
@@ -4574,6 +7191,7 @@ var CacheService = class _CacheService {
|
|
|
4574
7191
|
* the previous key for seamless fallback decryption of existing cache entries.
|
|
4575
7192
|
*/
|
|
4576
7193
|
async rotateEncryptionKey(newKeyBase64, newMode) {
|
|
7194
|
+
this._assertActive("rotateEncryptionKey");
|
|
4577
7195
|
this.enc.rotateKey(newKeyBase64, newMode);
|
|
4578
7196
|
if (this._workerPool) {
|
|
4579
7197
|
await this._workerPool.drainAndReinit(this.enc.toWorkerInit());
|
|
@@ -4583,23 +7201,33 @@ var CacheService = class _CacheService {
|
|
|
4583
7201
|
/** Close Redis connections and stop all background timers. */
|
|
4584
7202
|
async destroy() {
|
|
4585
7203
|
this._destroyed = true;
|
|
7204
|
+
this._pendingDiskDeletes.clear();
|
|
7205
|
+
this._keyMutationEpochs.clear();
|
|
7206
|
+
const g = globalThis;
|
|
7207
|
+
const key = _CacheService.globalKey(this.opts);
|
|
7208
|
+
if (g[key] === this) {
|
|
7209
|
+
delete g[key];
|
|
7210
|
+
}
|
|
4586
7211
|
if (this.cleanupInterval) clearInterval(this.cleanupInterval);
|
|
4587
7212
|
if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
|
|
4588
7213
|
if (this.oomInterval) clearInterval(this.oomInterval);
|
|
4589
7214
|
if (this.metricsInterval) clearInterval(this.metricsInterval);
|
|
4590
|
-
if (this.
|
|
4591
|
-
|
|
4592
|
-
|
|
4593
|
-
this._shutdownHandler = null;
|
|
7215
|
+
if (this.remoteSnapshotInterval) {
|
|
7216
|
+
clearInterval(this.remoteSnapshotInterval);
|
|
7217
|
+
this.remoteSnapshotInterval = null;
|
|
4594
7218
|
}
|
|
7219
|
+
ProcessTerminationBus.unregister(this);
|
|
7220
|
+
this._shutdownHandler = null;
|
|
4595
7221
|
if (this._workerPool) {
|
|
4596
7222
|
await this._workerPool.destroy();
|
|
4597
7223
|
this._workerPool = null;
|
|
4598
7224
|
}
|
|
4599
7225
|
if (this.subClient) {
|
|
4600
|
-
|
|
4601
|
-
|
|
4602
|
-
|
|
7226
|
+
if (!this.opts.redisSubClient) {
|
|
7227
|
+
try {
|
|
7228
|
+
this.subClient.disconnect();
|
|
7229
|
+
} catch {
|
|
7230
|
+
}
|
|
4603
7231
|
}
|
|
4604
7232
|
this.subClient = null;
|
|
4605
7233
|
}
|
|
@@ -4611,19 +7239,61 @@ var CacheService = class _CacheService {
|
|
|
4611
7239
|
this.streamClient = null;
|
|
4612
7240
|
}
|
|
4613
7241
|
if (this.redis) {
|
|
4614
|
-
|
|
4615
|
-
|
|
4616
|
-
|
|
7242
|
+
if (!this.opts.redisClient) {
|
|
7243
|
+
try {
|
|
7244
|
+
await this.redis.disconnect();
|
|
7245
|
+
} catch {
|
|
7246
|
+
}
|
|
4617
7247
|
}
|
|
4618
7248
|
this.redis = null;
|
|
4619
7249
|
}
|
|
7250
|
+
if (this._ipcServer) {
|
|
7251
|
+
await this._ipcServer.close();
|
|
7252
|
+
this._ipcServer = void 0;
|
|
7253
|
+
}
|
|
4620
7254
|
if (!this._diskDisabled) this.disk.close();
|
|
4621
7255
|
}
|
|
7256
|
+
/**
|
|
7257
|
+
* Return the active IPC telemetry server instance, if enabled.
|
|
7258
|
+
*/
|
|
7259
|
+
getIpcServer() {
|
|
7260
|
+
return this._ipcServer;
|
|
7261
|
+
}
|
|
7262
|
+
/**
|
|
7263
|
+
* Return real-time telemetry and metrics for the Window TinyLFU admission policy.
|
|
7264
|
+
* Returns `undefined` if W-TinyLFU admission is not active.
|
|
7265
|
+
*/
|
|
7266
|
+
getWTinyLfuStats() {
|
|
7267
|
+
return this.l1.getWTinyLfuStats();
|
|
7268
|
+
}
|
|
4622
7269
|
};
|
|
4623
7270
|
|
|
4624
7271
|
export {
|
|
4625
|
-
|
|
7272
|
+
CacheCodec,
|
|
7273
|
+
defaultCodec,
|
|
7274
|
+
TinyLfuSketch,
|
|
7275
|
+
WTinyLfuCache,
|
|
7276
|
+
WTinyLfuPolicy,
|
|
4626
7277
|
SmartMemoryCache,
|
|
7278
|
+
resolveDefaultDiskDir,
|
|
4627
7279
|
DiskTier,
|
|
7280
|
+
TierLatencyWatchdog,
|
|
7281
|
+
DEFAULT_AUTONOMOUS_L1_CEILING_BYTES,
|
|
7282
|
+
MIN_AUTONOMOUS_L1_FLOOR_BYTES,
|
|
7283
|
+
readCgroupMemoryLimit,
|
|
7284
|
+
getV8HeapLimit,
|
|
7285
|
+
resolveAutonomousL1MaxBytes,
|
|
7286
|
+
AutoPipeliner,
|
|
7287
|
+
resolveIpcSocketPath,
|
|
7288
|
+
IpcTelemetryServer,
|
|
7289
|
+
IpcTelemetryClient,
|
|
7290
|
+
findActiveSockets,
|
|
7291
|
+
renderProgressBar,
|
|
7292
|
+
formatBytes,
|
|
7293
|
+
formatNumber,
|
|
7294
|
+
formatDuration,
|
|
7295
|
+
renderTopDashboard,
|
|
7296
|
+
ProcessTerminationBus,
|
|
7297
|
+
deepMergeOptions,
|
|
4628
7298
|
CacheService
|
|
4629
7299
|
};
|