tricache 0.7.0 → 0.8.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 +144 -1428
- package/bin/tricache.js +8 -8
- package/dashboards/tricache-alerts.yaml +54 -0
- package/dashboards/tricache-grafana.json +548 -0
- package/dist/cache-service-5MZXFIGK.js +12 -0
- package/dist/cache-service-CyLdpo77.d.ts +871 -0
- package/dist/{chunk-3XQUQBOZ.js → chunk-6PQ5MOWR.js} +2950 -523
- package/dist/chunk-7RV5ZVBB.js +1023 -0
- package/dist/{chunk-PFB5FMEY.js → chunk-LJ5QJB5O.js} +116 -20
- package/dist/chunk-QNU7B43J.js +687 -0
- package/dist/chunk-UGD4VEPD.js +138 -0
- package/dist/chunk-XZL45ABR.js +108 -0
- package/dist/chunk-ZTSWCFYO.js +135 -0
- package/dist/cli.cjs +2894 -518
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +103 -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 +2648 -508
- package/dist/drizzle/index.d.ts +3 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +1498 -0
- package/dist/edge/index.d.ts +127 -0
- package/dist/edge/index.js +1109 -0
- package/dist/hono-DQRS1Xd7.d.ts +370 -0
- package/dist/http/index.cjs +3038 -589
- package/dist/http/index.d.ts +109 -23
- package/dist/http/index.js +238 -62
- package/dist/index.cjs +6962 -2487
- 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 +2586 -498
- package/dist/nestjs/index.d.ts +3 -1
- package/dist/nestjs/index.js +6 -3
- package/dist/next/index.cjs +2633 -519
- package/dist/next/index.d.ts +13 -7
- package/dist/next/index.js +45 -18
- package/dist/prisma/index.cjs +2 -1
- package/dist/prisma/index.d.ts +3 -1
- package/dist/prisma/index.js +2 -1
- package/dist/serialize-worker.cjs +31 -19
- package/dist/serialize-worker.js +1 -1
- package/dist/{cache-service-BblHuF3i.d.ts → types-B6krw64X.d.ts} +605 -646
- package/package.json +37 -7
- package/src/adapters/auto-pipeliner.ts +206 -0
- package/src/adapters/node-redis.ts +370 -0
- package/src/cache-service.ts +4231 -3226
- package/src/cli.ts +261 -143
- package/src/codec.ts +72 -0
- package/src/compression.ts +56 -63
- 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 +1223 -821
- 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 +203 -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 +635 -493
- package/src/http/express.ts +195 -0
- package/src/http/fastify.ts +260 -0
- package/src/http/index.ts +46 -223
- package/src/http/utils.ts +92 -0
- package/src/index.ts +149 -47
- package/src/ipc-telemetry.ts +481 -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 +271 -244
- package/src/next/index.ts +37 -37
- package/src/next/isr-handler.ts +105 -105
- package/src/next/types.ts +130 -130
- package/src/prisma/index.ts +154 -151
- 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 +1109 -1024
- package/src/types.ts +1199 -902
- 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-AJASH5FX.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,79 +255,448 @@ 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
|
|
|
291
699
|
// src/smart-memory-cache.ts
|
|
292
|
-
var _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0, fetchedAt: 0, tagVersions: void 0, setAt: void 0 };
|
|
293
700
|
var LARGE_VALUE_BYTES = 16384;
|
|
294
701
|
var EVICTION_BATCH_PERCENT = 0.2;
|
|
295
702
|
var EVICTION_SAMPLE = 16;
|
|
@@ -464,11 +871,13 @@ function globMatchParts(parts, first, last, key) {
|
|
|
464
871
|
var SmartMemoryCache = class {
|
|
465
872
|
cache = /* @__PURE__ */ new Map();
|
|
466
873
|
opts;
|
|
874
|
+
codec;
|
|
467
875
|
bloom;
|
|
468
876
|
/** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
|
|
469
877
|
categoryPrefixes;
|
|
470
878
|
/** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
|
|
471
879
|
sketch = new CountMinSketch();
|
|
880
|
+
wtinyPolicy;
|
|
472
881
|
totalSize = 0;
|
|
473
882
|
categoryCount = /* @__PURE__ */ new Map();
|
|
474
883
|
categorySize = /* @__PURE__ */ new Map();
|
|
@@ -492,8 +901,12 @@ var SmartMemoryCache = class {
|
|
|
492
901
|
_evictGPool = Array.from({ length: EVICTION_SAMPLE }, () => ({ key: "", score: 0 }));
|
|
493
902
|
constructor(opts, existing) {
|
|
494
903
|
this.opts = opts;
|
|
904
|
+
this.codec = opts.codec ?? defaultCodec;
|
|
495
905
|
this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
|
|
496
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
|
+
}
|
|
497
910
|
if (existing) {
|
|
498
911
|
for (const [k, v] of existing) this.cache.set(k, v);
|
|
499
912
|
this.recalculateStats();
|
|
@@ -506,6 +919,12 @@ var SmartMemoryCache = class {
|
|
|
506
919
|
this.categoryCount.clear();
|
|
507
920
|
this.categorySize.clear();
|
|
508
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
|
+
}
|
|
509
928
|
for (const [key, entry] of this.cache) {
|
|
510
929
|
this.totalSize += entry.size;
|
|
511
930
|
const cat = this.getCategory(key);
|
|
@@ -531,6 +950,7 @@ var SmartMemoryCache = class {
|
|
|
531
950
|
_delete(key, reason = "manual") {
|
|
532
951
|
const entry = this.cache.get(key);
|
|
533
952
|
if (!entry) return false;
|
|
953
|
+
this.wtinyPolicy?.onDelete(key);
|
|
534
954
|
const cat = this.getCategory(key);
|
|
535
955
|
this.totalSize -= entry.size;
|
|
536
956
|
this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
|
|
@@ -691,19 +1111,22 @@ var SmartMemoryCache = class {
|
|
|
691
1111
|
entry.hits++;
|
|
692
1112
|
entry.lastAccess = now;
|
|
693
1113
|
if ((entry.hits & 3) === 0) this.sketch.increment(key);
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
1114
|
+
this.wtinyPolicy?.onAccess(key);
|
|
1115
|
+
const value = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
1116
|
+
const hit = {
|
|
1117
|
+
value,
|
|
1118
|
+
isStale: entry.staleAt !== void 0 && now > entry.staleAt,
|
|
1119
|
+
expiresAt: entry.expiresAt,
|
|
1120
|
+
ttlMs: entry.ttlMs,
|
|
1121
|
+
delta: entry.delta,
|
|
1122
|
+
fetchedAt: now,
|
|
1123
|
+
tagVersions: entry.tagVersions,
|
|
1124
|
+
setAt: entry.setAt
|
|
1125
|
+
};
|
|
1126
|
+
return hit;
|
|
704
1127
|
}
|
|
705
1128
|
set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
|
|
706
|
-
const packed =
|
|
1129
|
+
const packed = this.codec.encode(data);
|
|
707
1130
|
const size = packed.byteLength;
|
|
708
1131
|
this.compressions++;
|
|
709
1132
|
this.sketch.increment(key);
|
|
@@ -720,7 +1143,51 @@ var SmartMemoryCache = class {
|
|
|
720
1143
|
this.categorySize.set(cat, (this.categorySize.get(cat) ?? existingEntry.size) - existingEntry.size);
|
|
721
1144
|
this.cache.delete(key);
|
|
722
1145
|
}
|
|
723
|
-
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
|
+
}
|
|
724
1191
|
const now = Date.now();
|
|
725
1192
|
const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
|
|
726
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 });
|
|
@@ -780,6 +1247,7 @@ var SmartMemoryCache = class {
|
|
|
780
1247
|
}
|
|
781
1248
|
const count = this.cache.size;
|
|
782
1249
|
this.cache.clear();
|
|
1250
|
+
this.wtinyPolicy?.clear();
|
|
783
1251
|
this.totalSize = 0;
|
|
784
1252
|
this.categoryCount.clear();
|
|
785
1253
|
this.categorySize.clear();
|
|
@@ -947,8 +1415,8 @@ var SmartMemoryCache = class {
|
|
|
947
1415
|
if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
|
|
948
1416
|
if (this.cache.has(key)) continue;
|
|
949
1417
|
const rawData = entry.data;
|
|
950
|
-
const data = !entry.isCompressed ?
|
|
951
|
-
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;
|
|
952
1420
|
this.cache.set(key, { ...entry, data, value, isCompressed: true });
|
|
953
1421
|
this.bloom.add(key);
|
|
954
1422
|
loaded++;
|
|
@@ -1019,7 +1487,7 @@ var SmartMemoryCache = class {
|
|
|
1019
1487
|
* if the live object was not cached (large-entry optimisation or disk-restored entry).
|
|
1020
1488
|
*/
|
|
1021
1489
|
resolveValue(entry) {
|
|
1022
|
-
return entry.value !== void 0 ? entry.value :
|
|
1490
|
+
return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
1023
1491
|
}
|
|
1024
1492
|
// ── Stats ─────────────────────────────────────────────────────────────────
|
|
1025
1493
|
get size() {
|
|
@@ -1124,25 +1592,160 @@ var SmartMemoryCache = class {
|
|
|
1124
1592
|
out.sort((a, b) => b.hits - a.hits);
|
|
1125
1593
|
return out.slice(0, n);
|
|
1126
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
|
+
}
|
|
1127
1602
|
};
|
|
1128
1603
|
|
|
1129
1604
|
// src/disk-tier.ts
|
|
1130
1605
|
import fs from "fs";
|
|
1131
1606
|
import path from "path";
|
|
1132
1607
|
import crypto from "crypto";
|
|
1133
|
-
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
|
+
};
|
|
1134
1698
|
var _SqliteDB = null;
|
|
1135
1699
|
try {
|
|
1136
|
-
const
|
|
1137
|
-
|
|
1700
|
+
const proc = process;
|
|
1701
|
+
if (typeof proc.getBuiltinModule === "function") {
|
|
1702
|
+
const sqlite = proc.getBuiltinModule("node:sqlite");
|
|
1703
|
+
_SqliteDB = sqlite?.DatabaseSync ?? null;
|
|
1704
|
+
}
|
|
1138
1705
|
} catch {
|
|
1139
1706
|
}
|
|
1140
1707
|
var DISK_MAGIC = Buffer.from([68, 84, 73, 69, 82, 86, 49, 0]);
|
|
1141
1708
|
var DISK_MAGIC_V2 = Buffer.from([68, 84, 73, 69, 82, 86, 50, 0]);
|
|
1142
1709
|
var V2_HEADER_LEN = 16;
|
|
1143
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
|
+
}
|
|
1144
1745
|
var DiskTier = class {
|
|
1145
1746
|
opts;
|
|
1747
|
+
codec;
|
|
1748
|
+
diskQueue;
|
|
1146
1749
|
dirReady = false;
|
|
1147
1750
|
diskUsageBytes = 0;
|
|
1148
1751
|
usageCounted = false;
|
|
@@ -1150,6 +1753,14 @@ var DiskTier = class {
|
|
|
1150
1753
|
// maintained in-memory; avoids walkCacheFiles() in stats
|
|
1151
1754
|
/** Next bucket index (0–255) for the staggered janitor wheel. */
|
|
1152
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;
|
|
1153
1764
|
// ── SQLite metadata index (optional, requires node:sqlite) ───────────────
|
|
1154
1765
|
_db = null;
|
|
1155
1766
|
_stmtInsert = null;
|
|
@@ -1164,8 +1775,19 @@ var DiskTier = class {
|
|
|
1164
1775
|
// DELETE expired rows
|
|
1165
1776
|
_stmtStats = null;
|
|
1166
1777
|
// COUNT + SUM(size)
|
|
1778
|
+
_stmtPruneChunk = null;
|
|
1779
|
+
// SELECT chunk for watermark pruning
|
|
1167
1780
|
constructor(opts) {
|
|
1168
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
|
+
);
|
|
1169
1791
|
}
|
|
1170
1792
|
// ── Helpers ───────────────────────────────────────────────────────────────
|
|
1171
1793
|
ensureDir() {
|
|
@@ -1200,15 +1822,30 @@ var DiskTier = class {
|
|
|
1200
1822
|
PRAGMA synchronous = NORMAL;
|
|
1201
1823
|
PRAGMA temp_store = MEMORY;
|
|
1202
1824
|
CREATE TABLE IF NOT EXISTS meta (
|
|
1203
|
-
key_hash
|
|
1204
|
-
file_path
|
|
1205
|
-
expires_at
|
|
1206
|
-
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
|
|
1207
1831
|
);
|
|
1208
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);
|
|
1209
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
|
+
}
|
|
1210
1847
|
this._stmtInsert = this._db.prepare(
|
|
1211
|
-
"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 (?,?,?,?,?,?)"
|
|
1212
1849
|
);
|
|
1213
1850
|
this._stmtSelect = this._db.prepare(
|
|
1214
1851
|
"SELECT file_path, expires_at FROM meta WHERE key_hash = ?"
|
|
@@ -1221,13 +1858,16 @@ var DiskTier = class {
|
|
|
1221
1858
|
this._stmtStats = this._db.prepare(
|
|
1222
1859
|
"SELECT COUNT(*) AS cnt, COALESCE(SUM(size), 0) AS bytes FROM meta"
|
|
1223
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
|
+
);
|
|
1224
1864
|
const row = this._stmtStats.get();
|
|
1225
1865
|
this.fileCount = row.cnt;
|
|
1226
1866
|
this.diskUsageBytes = row.bytes;
|
|
1227
1867
|
this.usageCounted = true;
|
|
1228
1868
|
this.opts.logger.debug("DiskTier: SQLite index ready", { entries: row.cnt });
|
|
1229
1869
|
} catch (err) {
|
|
1230
|
-
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;
|
|
1231
1871
|
this.opts.logger.warn("DiskTier: SQLite init failed, using file-only mode", {
|
|
1232
1872
|
error: err.message
|
|
1233
1873
|
});
|
|
@@ -1322,7 +1962,7 @@ var DiskTier = class {
|
|
|
1322
1962
|
return results;
|
|
1323
1963
|
}
|
|
1324
1964
|
isForbidden(key) {
|
|
1325
|
-
return this.opts.forbiddenPrefixes
|
|
1965
|
+
return this.opts.forbiddenPrefixes?.some((p) => key.startsWith(p)) ?? false;
|
|
1326
1966
|
}
|
|
1327
1967
|
encrypt(data) {
|
|
1328
1968
|
if (!this.opts.encryption) return data;
|
|
@@ -1374,7 +2014,16 @@ var DiskTier = class {
|
|
|
1374
2014
|
this.ensureDir();
|
|
1375
2015
|
if (!this.dirReady) return;
|
|
1376
2016
|
this.ensureUsageCounted();
|
|
1377
|
-
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
|
+
}
|
|
1378
2027
|
let final;
|
|
1379
2028
|
try {
|
|
1380
2029
|
const payload = {
|
|
@@ -1386,7 +2035,7 @@ var DiskTier = class {
|
|
|
1386
2035
|
},
|
|
1387
2036
|
writtenAt: Date.now()
|
|
1388
2037
|
};
|
|
1389
|
-
const packed =
|
|
2038
|
+
const packed = this.codec.encode(payload);
|
|
1390
2039
|
if (packed.length > this.opts.entryMaxBytes) return;
|
|
1391
2040
|
let toEncrypt = packed;
|
|
1392
2041
|
if (this.opts.compression && this.opts.compression !== "none" && packed.length > (this.opts.compressionThresholdBytes ?? 1024)) {
|
|
@@ -1402,39 +2051,52 @@ var DiskTier = class {
|
|
|
1402
2051
|
}
|
|
1403
2052
|
const hash = this.keyToHash(key);
|
|
1404
2053
|
const filePath = this.hashToWritePath(hash, entry.expiresAt);
|
|
1405
|
-
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${
|
|
2054
|
+
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${crypto.randomBytes(6).toString("hex")}.tmp`;
|
|
1406
2055
|
this.diskUsageBytes += final.length;
|
|
1407
2056
|
this.fileCount++;
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
2057
|
+
if (this.diskUsageBytes >= this.opts.maxBytes * 0.8 && !this._isPruning) {
|
|
2058
|
+
void this.triggerChunkedPrune();
|
|
2059
|
+
}
|
|
2060
|
+
const result = await this.diskQueue.schedule(async () => {
|
|
1411
2061
|
try {
|
|
1412
|
-
await fs.promises.
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
if (code === "EBUSY" || code === "EPERM") {
|
|
1416
|
-
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 {
|
|
1417
2065
|
await fs.promises.rename(tmpPath, filePath);
|
|
1418
|
-
}
|
|
1419
|
-
|
|
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
|
+
}
|
|
1420
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;
|
|
1421
2095
|
}
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
}
|
|
1425
|
-
this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
|
|
1426
|
-
} catch (err) {
|
|
1427
|
-
try {
|
|
1428
|
-
await fs.promises.unlink(tmpPath);
|
|
1429
|
-
} catch {
|
|
1430
|
-
}
|
|
2096
|
+
});
|
|
2097
|
+
if (result === null) {
|
|
1431
2098
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
|
|
1432
2099
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1433
|
-
if (this._db) try {
|
|
1434
|
-
this._stmtDelete.run(hash);
|
|
1435
|
-
} catch {
|
|
1436
|
-
}
|
|
1437
|
-
this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
|
|
1438
2100
|
}
|
|
1439
2101
|
}
|
|
1440
2102
|
/** Load a key from disk, or return null on miss/expiry/corruption. */
|
|
@@ -1512,7 +2174,7 @@ var DiskTier = class {
|
|
|
1512
2174
|
}
|
|
1513
2175
|
}
|
|
1514
2176
|
const uncompressed = decompressWithHeader(decrypted, this.opts.compression ?? "brotli");
|
|
1515
|
-
const payload =
|
|
2177
|
+
const payload = this.codec.decode(uncompressed);
|
|
1516
2178
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
|
|
1517
2179
|
if (payload.entry.expiresAt <= Date.now()) return null;
|
|
1518
2180
|
const entry = payload.entry;
|
|
@@ -1630,11 +2292,12 @@ var DiskTier = class {
|
|
|
1630
2292
|
dec = this.decrypt(raw);
|
|
1631
2293
|
} catch {
|
|
1632
2294
|
fs.unlinkSync(filePath);
|
|
2295
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1633
2296
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1634
2297
|
purged++;
|
|
1635
2298
|
continue;
|
|
1636
2299
|
}
|
|
1637
|
-
const payload =
|
|
2300
|
+
const payload = this.codec.decode(dec);
|
|
1638
2301
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
1639
2302
|
fs.unlinkSync(filePath);
|
|
1640
2303
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
@@ -1793,11 +2456,12 @@ var DiskTier = class {
|
|
|
1793
2456
|
dec = this.decrypt(raw);
|
|
1794
2457
|
} catch {
|
|
1795
2458
|
fs.unlinkSync(filePath);
|
|
2459
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1796
2460
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1797
2461
|
purged++;
|
|
1798
2462
|
continue;
|
|
1799
2463
|
}
|
|
1800
|
-
const payload =
|
|
2464
|
+
const payload = this.codec.decode(dec);
|
|
1801
2465
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
1802
2466
|
fs.unlinkSync(filePath);
|
|
1803
2467
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
@@ -1836,15 +2500,143 @@ var DiskTier = class {
|
|
|
1836
2500
|
}
|
|
1837
2501
|
return cleared;
|
|
1838
2502
|
}
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
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 {
|
|
1844
2537
|
}
|
|
1845
|
-
return
|
|
2538
|
+
return true;
|
|
1846
2539
|
}
|
|
1847
|
-
/**
|
|
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'). */
|
|
1848
2640
|
get indexMode() {
|
|
1849
2641
|
return this._db ? "sqlite" : "file-only";
|
|
1850
2642
|
}
|
|
@@ -1855,11 +2647,769 @@ var DiskTier = class {
|
|
|
1855
2647
|
this._db.close();
|
|
1856
2648
|
} catch {
|
|
1857
2649
|
}
|
|
1858
|
-
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;
|
|
1859
2651
|
}
|
|
1860
2652
|
}
|
|
1861
2653
|
};
|
|
1862
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
|
+
return active;
|
|
3310
|
+
}
|
|
3311
|
+
const dir = process.env.TMPDIR || "/tmp";
|
|
3312
|
+
try {
|
|
3313
|
+
if (!fs3.existsSync(dir)) return active;
|
|
3314
|
+
const entries = fs3.readdirSync(dir);
|
|
3315
|
+
const candidates = entries.filter((name) => name.startsWith("tricache-") && name.endsWith(".sock")).map((name) => path2.join(dir, name));
|
|
3316
|
+
await Promise.all(
|
|
3317
|
+
candidates.map(async (sockPath) => {
|
|
3318
|
+
const client = new IpcTelemetryClient(sockPath);
|
|
3319
|
+
try {
|
|
3320
|
+
await client.ping(100);
|
|
3321
|
+
active.push(sockPath);
|
|
3322
|
+
} catch {
|
|
3323
|
+
}
|
|
3324
|
+
})
|
|
3325
|
+
);
|
|
3326
|
+
} catch {
|
|
3327
|
+
}
|
|
3328
|
+
return active;
|
|
3329
|
+
}
|
|
3330
|
+
function renderProgressBar(ratio, width = 18) {
|
|
3331
|
+
const clamped = Math.max(0, Math.min(1, isNaN(ratio) ? 0 : ratio));
|
|
3332
|
+
const filled = Math.round(clamped * width);
|
|
3333
|
+
const empty = width - filled;
|
|
3334
|
+
return "\u2588".repeat(filled) + "\u2591".repeat(empty);
|
|
3335
|
+
}
|
|
3336
|
+
function formatBytes(bytes) {
|
|
3337
|
+
if (!bytes || isNaN(bytes) || bytes < 0) return "0 B";
|
|
3338
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
3339
|
+
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
|
3340
|
+
if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
3341
|
+
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
|
|
3342
|
+
}
|
|
3343
|
+
function formatNumber(n) {
|
|
3344
|
+
return (n ?? 0).toLocaleString();
|
|
3345
|
+
}
|
|
3346
|
+
function formatDuration(ms) {
|
|
3347
|
+
if (ms < 1e3) return `${ms}ms`;
|
|
3348
|
+
const s = Math.floor(ms / 1e3);
|
|
3349
|
+
if (s < 60) return `${s}s`;
|
|
3350
|
+
const m = Math.floor(s / 60);
|
|
3351
|
+
const remS = s % 60;
|
|
3352
|
+
if (m < 60) return `${m}m ${remS}s`;
|
|
3353
|
+
const h = Math.floor(m / 60);
|
|
3354
|
+
const remM = m % 60;
|
|
3355
|
+
return `${h}h ${remM}m`;
|
|
3356
|
+
}
|
|
3357
|
+
function renderTopDashboard(payload) {
|
|
3358
|
+
const m = payload.metrics;
|
|
3359
|
+
const gets = m.gets;
|
|
3360
|
+
const l1Max = payload.l1MaxBytes || 200 * 1024 * 1024;
|
|
3361
|
+
const l1Used = m.l1.sizeBytes;
|
|
3362
|
+
const l1Pct = l1Max > 0 ? l1Used / l1Max : 0;
|
|
3363
|
+
const uptime = formatDuration(payload.uptimeMs);
|
|
3364
|
+
const ns = payload.namespace || "(default)";
|
|
3365
|
+
const pct = (r) => `${((r || 0) * 100).toFixed(1)}%`;
|
|
3366
|
+
const lines = [];
|
|
3367
|
+
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");
|
|
3368
|
+
lines.push(`\u2551 TriCache Monitor [PID: ${String(payload.pid).padEnd(6)}] Uptime: ${uptime.padEnd(8)} Namespace: ${ns.padEnd(16)}\u2551`);
|
|
3369
|
+
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");
|
|
3370
|
+
lines.push(`\u2551 Hit Ratios & Tier Breakdown (Total Gets: ${formatNumber(gets.total).padEnd(12)}) \u2551`);
|
|
3371
|
+
lines.push(`\u2551 L1 (RAM): [${renderProgressBar(gets.l1HitRate)}] ${pct(gets.l1HitRate).padStart(6)} (${formatNumber(gets.l1Hits).padStart(8)} hits) \u2551`);
|
|
3372
|
+
lines.push(`\u2551 L1.5(Disk): [${renderProgressBar(gets.diskHitRate)}] ${pct(gets.diskHitRate).padStart(6)} (${formatNumber(gets.diskHits).padStart(8)} hits) \u2551`);
|
|
3373
|
+
lines.push(`\u2551 L2 (Redis): [${renderProgressBar(gets.l2HitRate)}] ${pct(gets.l2HitRate).padStart(6)} (${formatNumber(gets.l2Hits).padStart(8)} hits) \u2551`);
|
|
3374
|
+
lines.push(`\u2551 Misses: [${renderProgressBar(gets.fetchRate)}] ${pct(gets.fetchRate).padStart(6)} (${formatNumber(gets.fetches).padStart(8)} fetches) \u2551`);
|
|
3375
|
+
lines.push(`\u2551 Stampedes Saved: ${formatNumber(gets.stampedePrevented).padEnd(8)} coalesced concurrent requests \u2551`);
|
|
3376
|
+
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");
|
|
3377
|
+
lines.push(`\u2551 Memory & Storage Headroom \u2551`);
|
|
3378
|
+
lines.push(`\u2551 L1 Memory: [${renderProgressBar(l1Pct)}] ${formatBytes(l1Used).padStart(8)} / ${formatBytes(l1Max).padEnd(8)} (${formatNumber(m.l1.entries).padStart(6)} entries) \u2551`);
|
|
3379
|
+
const diskFiles = m.disk?.files ?? 0;
|
|
3380
|
+
const diskKB = m.disk?.sizeKB ?? 0;
|
|
3381
|
+
const diskMaxKB = m.disk?.maxKB ?? 0;
|
|
3382
|
+
lines.push(`\u2551 Disk Spill: ${formatBytes(diskKB * 1024).padStart(8)} / ${formatBytes(diskMaxKB * 1024).padEnd(8)} (${formatNumber(diskFiles).padStart(6)} files) \u2551`);
|
|
3383
|
+
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");
|
|
3384
|
+
lines.push(`\u2551 Protection & Health Diagnostics \u2551`);
|
|
3385
|
+
const watchdog = m.disk?.latencyWatchdog;
|
|
3386
|
+
const bypassStage = watchdog ? `Stage ${watchdog.bypassStage} (${watchdog.bypassActive ? "ACTIVE" : "Normal"})` : "Stage 0 (Normal)";
|
|
3387
|
+
const cbState = m.l2CircuitBreaker?.state || "closed";
|
|
3388
|
+
lines.push(`\u2551 Watchdog: ${bypassStage.padEnd(20)} L2 Circuit Breaker: ${cbState.padEnd(20)}\u2551`);
|
|
3389
|
+
if (watchdog) {
|
|
3390
|
+
const diskP95 = `${watchdog.diskP95Ms.toFixed(2)}ms`;
|
|
3391
|
+
const redisP95 = `${watchdog.redisP95Ms.toFixed(2)}ms`;
|
|
3392
|
+
lines.push(`\u2551 Disk p95: ${diskP95.padEnd(10)} Redis p95: ${redisP95.padEnd(10)} Bypassed: ${formatNumber(watchdog.bypassedTotal).padEnd(16)}\u2551`);
|
|
3393
|
+
}
|
|
3394
|
+
const oomEvict = m.oom?.evictions ?? 0;
|
|
3395
|
+
lines.push(`\u2551 OOM Evictions: ${formatNumber(oomEvict).padEnd(6)} SWR Revalidations: ${formatNumber(m.revalidations?.total ?? 0).padEnd(14)} \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 \u{1F525} Top Hot Keys (Count-Min Sketch) \u2551`);
|
|
3398
|
+
if (!payload.hotKeys || payload.hotKeys.length === 0) {
|
|
3399
|
+
lines.push("\u2551 (no hot keys recorded yet) \u2551");
|
|
3400
|
+
} else {
|
|
3401
|
+
payload.hotKeys.slice(0, 5).forEach(({ key, hits, sizeBytes }, idx) => {
|
|
3402
|
+
const displayKey = key.length > 34 ? `${key.slice(0, 31)}...` : key;
|
|
3403
|
+
const hitStr = `${formatNumber(hits)} hits`;
|
|
3404
|
+
const sizeStr = formatBytes(sizeBytes);
|
|
3405
|
+
const row = ` ${idx + 1}. ${displayKey.padEnd(36)} ${hitStr.padStart(14)} (${sizeStr})`;
|
|
3406
|
+
lines.push(`\u2551${row.padEnd(86)}\u2551`);
|
|
3407
|
+
});
|
|
3408
|
+
}
|
|
3409
|
+
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");
|
|
3410
|
+
return lines.join("\n");
|
|
3411
|
+
}
|
|
3412
|
+
|
|
1863
3413
|
// src/cache-service.ts
|
|
1864
3414
|
var LUA_COMPARE_AND_DELETE = `
|
|
1865
3415
|
local currentTs = redis.call('HGET', KEYS[1], 't')
|
|
@@ -1870,6 +3420,7 @@ return 0
|
|
|
1870
3420
|
`;
|
|
1871
3421
|
var SNAPSHOT_VERSION = 1;
|
|
1872
3422
|
var DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
|
|
3423
|
+
var INDEFINITE_TTL_SECONDS = 31536e3;
|
|
1873
3424
|
var SNAPSHOT_MAX_FILE_BYTES = 220 * 1024 * 1024;
|
|
1874
3425
|
var DEFAULT_CATEGORY_LIMITS = {
|
|
1875
3426
|
"default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
|
|
@@ -1903,7 +3454,7 @@ var L2CircuitBreaker = class {
|
|
|
1903
3454
|
cooldownMs;
|
|
1904
3455
|
state = 0 /* CLOSED */;
|
|
1905
3456
|
failures = 0;
|
|
1906
|
-
openedAt =
|
|
3457
|
+
openedAt = performance.now();
|
|
1907
3458
|
/** True while the single permitted HALF_OPEN probe is in flight. */
|
|
1908
3459
|
probing = false;
|
|
1909
3460
|
/**
|
|
@@ -1919,7 +3470,8 @@ var L2CircuitBreaker = class {
|
|
|
1919
3470
|
this.probing = true;
|
|
1920
3471
|
return true;
|
|
1921
3472
|
}
|
|
1922
|
-
|
|
3473
|
+
const now = this.openedAt > 1e12 ? Date.now() : performance.now();
|
|
3474
|
+
if (now - this.openedAt >= this.cooldownMs) {
|
|
1923
3475
|
this.state = 2 /* HALF_OPEN */;
|
|
1924
3476
|
this.probing = true;
|
|
1925
3477
|
return true;
|
|
@@ -1938,7 +3490,7 @@ var L2CircuitBreaker = class {
|
|
|
1938
3490
|
this.probing = false;
|
|
1939
3491
|
if (this.state === 2 /* HALF_OPEN */ || this.failures >= this.threshold) {
|
|
1940
3492
|
this.state = 1 /* OPEN */;
|
|
1941
|
-
this.openedAt =
|
|
3493
|
+
this.openedAt = performance.now();
|
|
1942
3494
|
this.failures = 0;
|
|
1943
3495
|
}
|
|
1944
3496
|
}
|
|
@@ -2055,9 +3607,86 @@ function detectServerlessRuntime() {
|
|
|
2055
3607
|
if (process.env["VERCEL"]) return "Vercel";
|
|
2056
3608
|
return null;
|
|
2057
3609
|
}
|
|
3610
|
+
var ProcessTerminationBus = class {
|
|
3611
|
+
static instances = /* @__PURE__ */ new Set();
|
|
3612
|
+
static registered = false;
|
|
3613
|
+
static sigtermHandler = null;
|
|
3614
|
+
static sigintHandler = null;
|
|
3615
|
+
static register(instance) {
|
|
3616
|
+
this.instances.add(instance);
|
|
3617
|
+
if (!this.registered) {
|
|
3618
|
+
this.registered = true;
|
|
3619
|
+
this.sigtermHandler = () => {
|
|
3620
|
+
for (const inst of this.instances) {
|
|
3621
|
+
try {
|
|
3622
|
+
inst._triggerShutdown();
|
|
3623
|
+
} catch {
|
|
3624
|
+
}
|
|
3625
|
+
}
|
|
3626
|
+
};
|
|
3627
|
+
this.sigintHandler = () => {
|
|
3628
|
+
for (const inst of this.instances) {
|
|
3629
|
+
try {
|
|
3630
|
+
inst._triggerShutdown();
|
|
3631
|
+
} catch {
|
|
3632
|
+
}
|
|
3633
|
+
}
|
|
3634
|
+
};
|
|
3635
|
+
process.on("SIGTERM", this.sigtermHandler);
|
|
3636
|
+
process.on("SIGINT", this.sigintHandler);
|
|
3637
|
+
}
|
|
3638
|
+
}
|
|
3639
|
+
static unregister(instance) {
|
|
3640
|
+
this.instances.delete(instance);
|
|
3641
|
+
if (this.instances.size === 0 && this.registered) {
|
|
3642
|
+
if (this.sigtermHandler) process.removeListener("SIGTERM", this.sigtermHandler);
|
|
3643
|
+
if (this.sigintHandler) process.removeListener("SIGINT", this.sigintHandler);
|
|
3644
|
+
this.sigtermHandler = null;
|
|
3645
|
+
this.sigintHandler = null;
|
|
3646
|
+
this.registered = false;
|
|
3647
|
+
}
|
|
3648
|
+
}
|
|
3649
|
+
/**
|
|
3650
|
+
* Flushes snapshots across all active registered cache instances concurrently.
|
|
3651
|
+
* Awaits both local disk and remote cloud snapshot uploads with timeout protection.
|
|
3652
|
+
*
|
|
3653
|
+
* @param timeoutMs Timeout in milliseconds per instance before aborting slow flushes. Default: 8000ms.
|
|
3654
|
+
*/
|
|
3655
|
+
static async flushAll(timeoutMs = 8e3) {
|
|
3656
|
+
if (this.instances.size === 0) return;
|
|
3657
|
+
const tasks = Array.from(this.instances).map((inst) => inst.flushSnapshotOnShutdown(timeoutMs));
|
|
3658
|
+
await Promise.allSettled(tasks);
|
|
3659
|
+
}
|
|
3660
|
+
/** For testing diagnostics and assertions */
|
|
3661
|
+
static get size() {
|
|
3662
|
+
return this.instances.size;
|
|
3663
|
+
}
|
|
3664
|
+
static get isRegistered() {
|
|
3665
|
+
return this.registered;
|
|
3666
|
+
}
|
|
3667
|
+
};
|
|
3668
|
+
function isPlainObject(item) {
|
|
3669
|
+
return typeof item === "object" && item !== null && item.constructor === Object;
|
|
3670
|
+
}
|
|
3671
|
+
function deepMergeOptions(base, overrides) {
|
|
3672
|
+
if (!overrides) return { ...base };
|
|
3673
|
+
const output = { ...base };
|
|
3674
|
+
for (const key of Object.keys(overrides)) {
|
|
3675
|
+
const sourceVal = overrides[key];
|
|
3676
|
+
if (sourceVal === void 0) continue;
|
|
3677
|
+
const targetVal = output[key];
|
|
3678
|
+
if (isPlainObject(targetVal) && isPlainObject(sourceVal)) {
|
|
3679
|
+
output[key] = deepMergeOptions(targetVal, sourceVal);
|
|
3680
|
+
} else {
|
|
3681
|
+
output[key] = sourceVal;
|
|
3682
|
+
}
|
|
3683
|
+
}
|
|
3684
|
+
return output;
|
|
3685
|
+
}
|
|
2058
3686
|
var CacheService = class _CacheService {
|
|
2059
3687
|
logger;
|
|
2060
3688
|
enc;
|
|
3689
|
+
codec;
|
|
2061
3690
|
l1;
|
|
2062
3691
|
disk;
|
|
2063
3692
|
/** When true, all disk-tier and snapshot operations are skipped. */
|
|
@@ -2069,6 +3698,8 @@ var CacheService = class _CacheService {
|
|
|
2069
3698
|
_namespace;
|
|
2070
3699
|
/** Pre-computed once — disableRedis and redisHost never change after construction. */
|
|
2071
3700
|
_redisDisabled;
|
|
3701
|
+
watchdog;
|
|
3702
|
+
pipeliner = null;
|
|
2072
3703
|
inflight = /* @__PURE__ */ new Map();
|
|
2073
3704
|
revalidating = /* @__PURE__ */ new Set();
|
|
2074
3705
|
_l1Counters = /* @__PURE__ */ new Map();
|
|
@@ -2094,6 +3725,7 @@ var CacheService = class _CacheService {
|
|
|
2094
3725
|
diskJanitorInterval = null;
|
|
2095
3726
|
oomInterval = null;
|
|
2096
3727
|
metricsInterval = null;
|
|
3728
|
+
remoteSnapshotInterval = null;
|
|
2097
3729
|
_shutdownHandler = null;
|
|
2098
3730
|
latencyTracker = null;
|
|
2099
3731
|
instanceId;
|
|
@@ -2103,8 +3735,11 @@ var CacheService = class _CacheService {
|
|
|
2103
3735
|
streamClient = null;
|
|
2104
3736
|
_lastStreamId = "$";
|
|
2105
3737
|
_destroyed = false;
|
|
3738
|
+
_ipcServer;
|
|
2106
3739
|
/** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
|
|
2107
3740
|
_subDisconnectedAt = null;
|
|
3741
|
+
/** Deduplication ring buffer for incoming and outgoing cross-region invalidations (loop prevention) */
|
|
3742
|
+
_seenCrossRegionEvents = /* @__PURE__ */ new Map();
|
|
2108
3743
|
counters = {
|
|
2109
3744
|
gets: 0,
|
|
2110
3745
|
l1Hits: 0,
|
|
@@ -2129,7 +3764,16 @@ var CacheService = class _CacheService {
|
|
|
2129
3764
|
singletonDivergences: 0,
|
|
2130
3765
|
startedAt: Date.now(),
|
|
2131
3766
|
bloomChecks: 0,
|
|
2132
|
-
bloomFalsePositives: 0
|
|
3767
|
+
bloomFalsePositives: 0,
|
|
3768
|
+
remoteSnapshotUploads: 0,
|
|
3769
|
+
remoteSnapshotDownloads: 0,
|
|
3770
|
+
remoteSnapshotErrors: 0,
|
|
3771
|
+
remoteSnapshotLastUploadedAt: null,
|
|
3772
|
+
remoteSnapshotLastDownloadedAt: null,
|
|
3773
|
+
crossRegionSent: 0,
|
|
3774
|
+
crossRegionReceived: 0,
|
|
3775
|
+
crossRegionDeduplicated: 0,
|
|
3776
|
+
crossRegionErrors: 0
|
|
2133
3777
|
};
|
|
2134
3778
|
/** One-time guard so the in-process increment() fallback warning fires only once. */
|
|
2135
3779
|
_incrementFallbackWarned = false;
|
|
@@ -2144,32 +3788,37 @@ var CacheService = class _CacheService {
|
|
|
2144
3788
|
logger,
|
|
2145
3789
|
options.encryptionMode,
|
|
2146
3790
|
options.previousEncryptionKey,
|
|
2147
|
-
options.previousEncryptionMode
|
|
3791
|
+
options.previousEncryptionMode,
|
|
3792
|
+
{ strictKeyValidation: options.strictKeyValidation ?? false }
|
|
2148
3793
|
);
|
|
2149
3794
|
const rawForbidden = options.forbiddenSnapshotPrefixes ?? [...DEFAULT_FORBIDDEN_PREFIXES];
|
|
2150
3795
|
const forbiddenPrefixes = ns ? rawForbidden.map((p) => `${ns}:${p}`) : rawForbidden;
|
|
2151
3796
|
this.opts = {
|
|
2152
3797
|
namespace: ns,
|
|
2153
3798
|
logger,
|
|
2154
|
-
l1MaxBytes: options.l1MaxBytes ??
|
|
3799
|
+
l1MaxBytes: options.l1MaxBytes ?? resolveAutonomousL1MaxBytes(),
|
|
2155
3800
|
l1MaxEntries: options.l1MaxEntries ?? 2e3,
|
|
2156
3801
|
categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...options.categoryLimits },
|
|
2157
3802
|
forbiddenSnapshotPrefixes: forbiddenPrefixes,
|
|
2158
3803
|
// Namespace-isolated defaults: separate dir / snapshot per namespace so
|
|
2159
3804
|
// two instances with different namespaces never share cache files.
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
ns ? `tricache-disk-${ns}` : "tricache-disk"
|
|
2163
|
-
),
|
|
3805
|
+
// Automatically probes /dev/shm tmpfs on Linux (>=256MB capacity and >=128MB free) for off-heap RAM speed.
|
|
3806
|
+
diskCacheDir: options.diskCacheDir ?? resolveDefaultDiskDir(ns, logger).dir,
|
|
2164
3807
|
diskMaxBytes: options.diskMaxBytes ?? 500 * 1024 * 1024,
|
|
2165
3808
|
diskEntryMaxBytes: options.diskEntryMaxBytes ?? 10 * 1024 * 1024,
|
|
2166
3809
|
redisHost: options.redisHost ?? process.env.REDIS_HOST ?? "",
|
|
2167
3810
|
redisPort: options.redisPort ?? 6379,
|
|
2168
3811
|
redisTls: options.redisTls ?? process.env.NODE_ENV === "production",
|
|
2169
|
-
disableRedis: options.disableRedis ??
|
|
3812
|
+
disableRedis: options.disableRedis ?? (() => {
|
|
3813
|
+
const explicitConfig = Boolean(
|
|
3814
|
+
options.redisClient || options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
|
|
3815
|
+
);
|
|
3816
|
+
return !explicitConfig && process.env.NODE_ENV !== "production";
|
|
3817
|
+
})(),
|
|
2170
3818
|
encryptionKey: encKeyRaw,
|
|
2171
|
-
|
|
2172
|
-
|
|
3819
|
+
encryptionMode: options.encryptionMode,
|
|
3820
|
+
snapshotPath: options.snapshotPath ?? path3.join(
|
|
3821
|
+
os3.tmpdir(),
|
|
2173
3822
|
ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
|
|
2174
3823
|
),
|
|
2175
3824
|
snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
|
|
@@ -2217,8 +3866,35 @@ var CacheService = class _CacheService {
|
|
|
2217
3866
|
backplaneMode: options.backplaneMode ?? "pubsub",
|
|
2218
3867
|
backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
|
|
2219
3868
|
backplaneStreamBlockMs: options.backplaneStreamBlockMs ?? 2e3,
|
|
2220
|
-
backplaneStreamKey: options.backplaneStreamKey
|
|
3869
|
+
backplaneStreamKey: options.backplaneStreamKey,
|
|
3870
|
+
serializeToJSON: options.serializeToJSON ?? true,
|
|
3871
|
+
remoteSnapshot: options.remoteSnapshot,
|
|
3872
|
+
crossRegion: options.crossRegion,
|
|
3873
|
+
redisClient: options.redisClient,
|
|
3874
|
+
redisSubClient: options.redisSubClient,
|
|
3875
|
+
diskMaxConcurrentWrites: options.diskMaxConcurrentWrites,
|
|
3876
|
+
diskMaxPendingWrites: options.diskMaxPendingWrites,
|
|
3877
|
+
diskWriteTimeoutMs: options.diskWriteTimeoutMs,
|
|
3878
|
+
diskCircuitBreakerThreshold: options.diskCircuitBreakerThreshold,
|
|
3879
|
+
diskCircuitBreakerCooldownMs: options.diskCircuitBreakerCooldownMs,
|
|
3880
|
+
redisCommandTimeoutMs: options.redisCommandTimeoutMs,
|
|
3881
|
+
clockSkewToleranceMs: options.clockSkewToleranceMs ?? 250,
|
|
3882
|
+
l1AdmissionPolicy: options.l1AdmissionPolicy,
|
|
3883
|
+
diskLatencyWatchdog: options.diskLatencyWatchdog ?? true,
|
|
3884
|
+
diskLatencyBypassRatio: options.diskLatencyBypassRatio ?? 1.5,
|
|
3885
|
+
diskLatencyBypassMinMs: options.diskLatencyBypassMinMs ?? 10,
|
|
3886
|
+
diskLatencyBypassCooldownMs: options.diskLatencyBypassCooldownMs ?? 3e4,
|
|
3887
|
+
failReadinessOnDegraded: options.failReadinessOnDegraded ?? false,
|
|
3888
|
+
autoPipeline: options.autoPipeline ?? false,
|
|
3889
|
+
maxPipelineBatchSize: options.maxPipelineBatchSize ?? 100,
|
|
3890
|
+
enableIpc: options.enableIpc ?? false,
|
|
3891
|
+
ipcSocketPath: options.ipcSocketPath
|
|
2221
3892
|
};
|
|
3893
|
+
this.codec = new CacheCodec({
|
|
3894
|
+
useToJSON: this.opts.serializeToJSON,
|
|
3895
|
+
useRecords: true,
|
|
3896
|
+
moreTypes: true
|
|
3897
|
+
});
|
|
2222
3898
|
const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
|
|
2223
3899
|
const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
|
|
2224
3900
|
this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
|
|
@@ -2249,15 +3925,33 @@ var CacheService = class _CacheService {
|
|
|
2249
3925
|
encryption: this.enc.isEnabled ? this.enc : null,
|
|
2250
3926
|
compression: this.opts.compression,
|
|
2251
3927
|
compressionThresholdBytes: this.opts.compressionThresholdBytes,
|
|
2252
|
-
logger
|
|
3928
|
+
logger,
|
|
3929
|
+
codec: this.codec,
|
|
3930
|
+
diskMaxConcurrentWrites: this.opts.diskMaxConcurrentWrites,
|
|
3931
|
+
diskMaxPendingWrites: this.opts.diskMaxPendingWrites,
|
|
3932
|
+
diskWriteTimeoutMs: this.opts.diskWriteTimeoutMs,
|
|
3933
|
+
diskCircuitBreakerThreshold: this.opts.diskCircuitBreakerThreshold,
|
|
3934
|
+
diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs
|
|
2253
3935
|
});
|
|
2254
3936
|
this._namespace = ns;
|
|
2255
|
-
this._redisDisabled = this.opts.disableRedis || !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
|
|
3937
|
+
this._redisDisabled = this.opts.disableRedis || !this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
|
|
3938
|
+
this.watchdog = new TierLatencyWatchdog({
|
|
3939
|
+
enabled: options.diskLatencyWatchdog ?? true,
|
|
3940
|
+
minDiskBypassMs: options.diskLatencyBypassMinMs ?? 10,
|
|
3941
|
+
bypassRatio: options.diskLatencyBypassRatio ?? 1.5,
|
|
3942
|
+
cooldownMs: options.diskLatencyBypassCooldownMs ?? 3e4,
|
|
3943
|
+
redisCutoffMs: 15,
|
|
3944
|
+
redisRecoveryFloorMs: 10,
|
|
3945
|
+
minSamples: 16,
|
|
3946
|
+
disableRedis: this._redisDisabled
|
|
3947
|
+
});
|
|
2256
3948
|
this.l1 = new SmartMemoryCache({
|
|
2257
3949
|
maxBytes: this.opts.l1MaxBytes,
|
|
2258
3950
|
maxEntries: this.opts.l1MaxEntries,
|
|
2259
3951
|
categories: this.opts.categoryLimits,
|
|
2260
3952
|
evictionWatermark: this.opts.l1EvictionWatermark,
|
|
3953
|
+
admissionPolicy: this.opts.l1AdmissionPolicy,
|
|
3954
|
+
codec: this.codec,
|
|
2261
3955
|
diskSpill: (key, entry) => {
|
|
2262
3956
|
if (this._diskDisabled) return;
|
|
2263
3957
|
setImmediate(() => {
|
|
@@ -2272,11 +3966,9 @@ var CacheService = class _CacheService {
|
|
|
2272
3966
|
if (!this._diskDisabled) this.loadSnapshot();
|
|
2273
3967
|
}
|
|
2274
3968
|
this._shutdownHandler = () => {
|
|
2275
|
-
|
|
2276
|
-
process.exit(0);
|
|
3969
|
+
this._triggerShutdown();
|
|
2277
3970
|
};
|
|
2278
|
-
|
|
2279
|
-
process.once("SIGINT", this._shutdownHandler);
|
|
3971
|
+
ProcessTerminationBus.register(this);
|
|
2280
3972
|
if (this.opts.workerThreads) {
|
|
2281
3973
|
try {
|
|
2282
3974
|
const encRef = this.enc.toWorkerInit();
|
|
@@ -2316,7 +4008,7 @@ var CacheService = class _CacheService {
|
|
|
2316
4008
|
}
|
|
2317
4009
|
if (this.opts.oomProtection) {
|
|
2318
4010
|
this.oomInterval = setInterval(() => {
|
|
2319
|
-
const heap =
|
|
4011
|
+
const heap = v82.getHeapStatistics();
|
|
2320
4012
|
const used = heap.used_heap_size / heap.heap_size_limit;
|
|
2321
4013
|
if (used >= this.opts.oomHeapThreshold) {
|
|
2322
4014
|
const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
|
|
@@ -2340,12 +4032,25 @@ var CacheService = class _CacheService {
|
|
|
2340
4032
|
}, this.opts.metricsIntervalMs);
|
|
2341
4033
|
if (this.metricsInterval.unref) this.metricsInterval.unref();
|
|
2342
4034
|
}
|
|
4035
|
+
if (this.opts.remoteSnapshot?.intervalMs && this.opts.remoteSnapshot.intervalMs > 0) {
|
|
4036
|
+
this.remoteSnapshotInterval = setInterval(() => {
|
|
4037
|
+
void this.writeRemoteSnapshot();
|
|
4038
|
+
}, this.opts.remoteSnapshot.intervalMs);
|
|
4039
|
+
if (this.remoteSnapshotInterval.unref) this.remoteSnapshotInterval.unref();
|
|
4040
|
+
}
|
|
2343
4041
|
this.instanceId = crypto2.randomBytes(8).toString("hex");
|
|
2344
4042
|
this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
|
|
2345
4043
|
this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
|
|
2346
4044
|
this.initBackplane();
|
|
4045
|
+
const startupPromises = [];
|
|
4046
|
+
if (this.opts.remoteSnapshot) {
|
|
4047
|
+
startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
|
|
4048
|
+
}
|
|
2347
4049
|
if (this.opts.warmKeys) {
|
|
2348
|
-
|
|
4050
|
+
startupPromises.push(this.warmFromL2(this.opts.warmKeys).then(() => void 0));
|
|
4051
|
+
}
|
|
4052
|
+
if (startupPromises.length > 0) {
|
|
4053
|
+
this._readyPromise = Promise.all(startupPromises).then(() => void 0);
|
|
2349
4054
|
}
|
|
2350
4055
|
if (this.opts.meter) {
|
|
2351
4056
|
this._initOtelMetrics(this.opts.meter);
|
|
@@ -2366,8 +4071,71 @@ var CacheService = class _CacheService {
|
|
|
2366
4071
|
}
|
|
2367
4072
|
});
|
|
2368
4073
|
}
|
|
4074
|
+
if (this.opts.enableIpc) {
|
|
4075
|
+
this._ipcServer = new IpcTelemetryServer(this, this.opts.ipcSocketPath);
|
|
4076
|
+
this._ipcServer.start().catch((err) => {
|
|
4077
|
+
this.logger.warn("Failed to start IPC telemetry server", { error: err.message });
|
|
4078
|
+
});
|
|
4079
|
+
}
|
|
4080
|
+
}
|
|
4081
|
+
// ── Singleton factory & Presets ───────────────────────────────────────────
|
|
4082
|
+
/**
|
|
4083
|
+
* Pre-configured production presets tailored for specific deployment environments.
|
|
4084
|
+
*
|
|
4085
|
+
* - `'nextjs'`: W-TinyLFU, zero-copy cloneStrategy: 'none' (React 19 RSC stream optimized),
|
|
4086
|
+
* generational tags, and Redis stream backplane.
|
|
4087
|
+
* - `'microservice'`: High-throughput Node.js microservice with W-TinyLFU, Streams backplane,
|
|
4088
|
+
* TTL jitter, and L2 circuit breaking.
|
|
4089
|
+
* - `'serverless'`: Stateless Lambda / Cloud Run isolate with memory-only L1, fast timeouts,
|
|
4090
|
+
* and Pub/Sub backplane.
|
|
4091
|
+
* - `'enterprise-hardened'`: Zero-trust production setup with generational tagging, Streams backplane,
|
|
4092
|
+
* fail-closed rate-limits, strict singleton assertions, and 80% OOM guard.
|
|
4093
|
+
*
|
|
4094
|
+
* @param type The preset identifier ('nextjs' | 'microservice' | 'serverless' | 'enterprise-hardened')
|
|
4095
|
+
* @param overrides Optional configuration overrides merged deeply over preset defaults
|
|
4096
|
+
* @returns Singleton CacheService instance configured according to the preset
|
|
4097
|
+
*/
|
|
4098
|
+
static preset(type, overrides) {
|
|
4099
|
+
const PRESETS = {
|
|
4100
|
+
"nextjs": {
|
|
4101
|
+
l1AdmissionPolicy: "wtinylfu",
|
|
4102
|
+
cloneStrategy: "none",
|
|
4103
|
+
tagStrategy: "generational",
|
|
4104
|
+
tagVersionTtlMs: 2e3,
|
|
4105
|
+
backplaneMode: "stream",
|
|
4106
|
+
staleIfError: 300,
|
|
4107
|
+
compression: "none"
|
|
4108
|
+
},
|
|
4109
|
+
"microservice": {
|
|
4110
|
+
l1AdmissionPolicy: "wtinylfu",
|
|
4111
|
+
backplaneMode: "stream",
|
|
4112
|
+
ttlJitterFactor: 0.15,
|
|
4113
|
+
l2CircuitBreakerThreshold: 5,
|
|
4114
|
+
l2CircuitBreakerCooldownMs: 15e3
|
|
4115
|
+
},
|
|
4116
|
+
"serverless": {
|
|
4117
|
+
disableDisk: true,
|
|
4118
|
+
l1AdmissionPolicy: "wtinylfu",
|
|
4119
|
+
backplaneMode: "pubsub",
|
|
4120
|
+
redisCommandTimeoutMs: 1e3
|
|
4121
|
+
},
|
|
4122
|
+
"enterprise-hardened": {
|
|
4123
|
+
l1AdmissionPolicy: "wtinylfu",
|
|
4124
|
+
tagStrategy: "generational",
|
|
4125
|
+
backplaneMode: "stream",
|
|
4126
|
+
strictSingleton: true,
|
|
4127
|
+
failClosed: true,
|
|
4128
|
+
oomProtection: true,
|
|
4129
|
+
oomHeapThreshold: 0.8
|
|
4130
|
+
}
|
|
4131
|
+
};
|
|
4132
|
+
const base = PRESETS[type];
|
|
4133
|
+
if (!base) {
|
|
4134
|
+
throw new Error(`tricache: unknown preset '${type}'. Supported presets: 'nextjs', 'microservice', 'serverless', 'enterprise-hardened'`);
|
|
4135
|
+
}
|
|
4136
|
+
const merged = deepMergeOptions(base, overrides);
|
|
4137
|
+
return _CacheService.create(merged);
|
|
2369
4138
|
}
|
|
2370
|
-
// ── Singleton factory ─────────────────────────────────────────────────────
|
|
2371
4139
|
/**
|
|
2372
4140
|
* Get (or create) the process-level singleton CacheService instance.
|
|
2373
4141
|
*
|
|
@@ -2452,13 +4220,18 @@ var CacheService = class _CacheService {
|
|
|
2452
4220
|
disableRedis: this._redisDisabled,
|
|
2453
4221
|
redisClusterNodes: o.redisClusterNodes,
|
|
2454
4222
|
redisSentinel: o.redisSentinel,
|
|
2455
|
-
|
|
4223
|
+
// Never surface key material through diagnostics — a JSON.stringify of
|
|
4224
|
+
// this object previously leaked the raw encryption key.
|
|
4225
|
+
encryptionKey: o.encryptionKey ? "[REDACTED]" : void 0,
|
|
4226
|
+
encryptionMode: o.encryptionMode,
|
|
2456
4227
|
l2WriteMode: o.l2WriteMode,
|
|
2457
4228
|
instanceName: o.instanceName,
|
|
2458
4229
|
frozen: o.frozen,
|
|
2459
4230
|
adaptiveTtl: o.adaptiveTtl,
|
|
2460
4231
|
invalidationBackplane: o.invalidationBackplane,
|
|
2461
|
-
strictSingleton: o.strictSingleton
|
|
4232
|
+
strictSingleton: o.strictSingleton,
|
|
4233
|
+
remoteSnapshot: o.remoteSnapshot,
|
|
4234
|
+
crossRegion: o.crossRegion
|
|
2462
4235
|
};
|
|
2463
4236
|
}
|
|
2464
4237
|
/**
|
|
@@ -2517,15 +4290,30 @@ var CacheService = class _CacheService {
|
|
|
2517
4290
|
setStatus() {
|
|
2518
4291
|
return this;
|
|
2519
4292
|
},
|
|
4293
|
+
recordException() {
|
|
4294
|
+
return this;
|
|
4295
|
+
},
|
|
2520
4296
|
end() {
|
|
2521
4297
|
}
|
|
2522
4298
|
};
|
|
2523
4299
|
/** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
|
|
2524
|
-
_startSpan(name) {
|
|
2525
|
-
if (this.opts.tracer)
|
|
4300
|
+
_startSpan(name, links) {
|
|
4301
|
+
if (this.opts.tracer) {
|
|
4302
|
+
const span = this.opts.tracer.startSpan(name, links?.length ? { links } : void 0);
|
|
4303
|
+
if (this.opts.namespace) {
|
|
4304
|
+
span.setAttribute("cache.namespace", this.opts.namespace);
|
|
4305
|
+
}
|
|
4306
|
+
return span;
|
|
4307
|
+
}
|
|
2526
4308
|
return _CacheService._nullSpan;
|
|
2527
4309
|
}
|
|
2528
4310
|
createDedicatedRedisClient() {
|
|
4311
|
+
if (this.opts.redisSubClient) {
|
|
4312
|
+
return this.opts.redisSubClient;
|
|
4313
|
+
}
|
|
4314
|
+
if (this.opts.redisClient && typeof this.opts.redisClient.duplicate === "function") {
|
|
4315
|
+
return this.opts.redisClient.duplicate();
|
|
4316
|
+
}
|
|
2529
4317
|
if (this.opts.redisClusterNodes?.length) {
|
|
2530
4318
|
return new RedisCluster(this.opts.redisClusterNodes, {
|
|
2531
4319
|
redisOptions: {
|
|
@@ -2657,24 +4445,7 @@ var CacheService = class _CacheService {
|
|
|
2657
4445
|
for (const [id, fields] of entries) {
|
|
2658
4446
|
this._lastStreamId = id;
|
|
2659
4447
|
this.counters.streamEntriesReceived++;
|
|
2660
|
-
|
|
2661
|
-
let key = "";
|
|
2662
|
-
let src = "";
|
|
2663
|
-
let tagVersion;
|
|
2664
|
-
for (let i = 0; i < fields.length; i += 2) {
|
|
2665
|
-
const f = fields[i];
|
|
2666
|
-
const v = fields[i + 1];
|
|
2667
|
-
if (f === "op") op = v;
|
|
2668
|
-
else if (f === "key") key = v;
|
|
2669
|
-
else if (f === "src") src = v;
|
|
2670
|
-
else if (f === "tagVersion") tagVersion = parseInt(v, 10);
|
|
2671
|
-
}
|
|
2672
|
-
if (src === this.instanceId) {
|
|
2673
|
-
this.counters.invSkipped++;
|
|
2674
|
-
continue;
|
|
2675
|
-
}
|
|
2676
|
-
this.counters.invReceived++;
|
|
2677
|
-
this._applyInvalidationEvent(op, key, tagVersion);
|
|
4448
|
+
this._processStreamEntry(fields);
|
|
2678
4449
|
}
|
|
2679
4450
|
}
|
|
2680
4451
|
}
|
|
@@ -2695,6 +4466,51 @@ var CacheService = class _CacheService {
|
|
|
2695
4466
|
};
|
|
2696
4467
|
void runLoop();
|
|
2697
4468
|
}
|
|
4469
|
+
/**
|
|
4470
|
+
* Validate + apply one XREAD stream entry. `fields` is the flat ioredis
|
|
4471
|
+
* shape [name, value, name, value, …]. Mirrors the schema rules of the
|
|
4472
|
+
* pubsub path (`_handleBackplaneMessage`): op must be a known operation,
|
|
4473
|
+
* key/src must be non-empty strings, tagVersion must parse to a finite
|
|
4474
|
+
* number. Invalid entries are logged and dropped — never applied.
|
|
4475
|
+
*/
|
|
4476
|
+
/** @internal Exposed for testing. */
|
|
4477
|
+
_processStreamEntry(fields) {
|
|
4478
|
+
let op = "";
|
|
4479
|
+
let key = "";
|
|
4480
|
+
let src = "";
|
|
4481
|
+
let tagVersionRaw;
|
|
4482
|
+
for (let i = 0; i + 1 < fields.length; i += 2) {
|
|
4483
|
+
const f = fields[i];
|
|
4484
|
+
const v = fields[i + 1];
|
|
4485
|
+
if (f === "op") op = v;
|
|
4486
|
+
else if (f === "key") key = v;
|
|
4487
|
+
else if (f === "src") src = v;
|
|
4488
|
+
else if (f === "tagVersion") tagVersionRaw = v;
|
|
4489
|
+
}
|
|
4490
|
+
const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
|
|
4491
|
+
if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
|
|
4492
|
+
this.logger.warn("Backplane: rejected invalid stream entry", {
|
|
4493
|
+
op: String(op).slice(0, 40),
|
|
4494
|
+
key: typeof key === "string" ? key.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(key)
|
|
4495
|
+
});
|
|
4496
|
+
return;
|
|
4497
|
+
}
|
|
4498
|
+
let tagVersion;
|
|
4499
|
+
if (tagVersionRaw !== void 0) {
|
|
4500
|
+
const parsed = parseInt(tagVersionRaw, 10);
|
|
4501
|
+
if (!Number.isFinite(parsed)) {
|
|
4502
|
+
this.logger.warn("Backplane: rejected stream entry with non-numeric tagVersion", { key });
|
|
4503
|
+
return;
|
|
4504
|
+
}
|
|
4505
|
+
tagVersion = parsed;
|
|
4506
|
+
}
|
|
4507
|
+
if (src === this.instanceId) {
|
|
4508
|
+
this.counters.invSkipped++;
|
|
4509
|
+
return;
|
|
4510
|
+
}
|
|
4511
|
+
this.counters.invReceived++;
|
|
4512
|
+
this._applyInvalidationEvent(op, key, tagVersion);
|
|
4513
|
+
}
|
|
2698
4514
|
_applyInvalidationEvent(op, key, tagVersion) {
|
|
2699
4515
|
if (op === "del") {
|
|
2700
4516
|
this.l1.delete(key);
|
|
@@ -2731,7 +4547,13 @@ var CacheService = class _CacheService {
|
|
|
2731
4547
|
this.logger.warn("Backplane: malformed message JSON parse failed");
|
|
2732
4548
|
}
|
|
2733
4549
|
}
|
|
2734
|
-
async publishInvalidation(op, key, tagVersion) {
|
|
4550
|
+
async publishInvalidation(op, key, tagVersion, isCrossRegionRelay = false, isExplicitInvalidation = false) {
|
|
4551
|
+
if (!isCrossRegionRelay && this.opts.crossRegion) {
|
|
4552
|
+
const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
|
|
4553
|
+
if (shouldBroadcast) {
|
|
4554
|
+
void this._broadcastCrossRegion(op, key, tagVersion);
|
|
4555
|
+
}
|
|
4556
|
+
}
|
|
2735
4557
|
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
2736
4558
|
try {
|
|
2737
4559
|
const client = await this.getRedis();
|
|
@@ -2773,7 +4595,80 @@ var CacheService = class _CacheService {
|
|
|
2773
4595
|
} catch {
|
|
2774
4596
|
}
|
|
2775
4597
|
}
|
|
2776
|
-
|
|
4598
|
+
_markCrossRegionEventSeen(id) {
|
|
4599
|
+
const maxDedup = this.opts.crossRegion?.dedupCacheSize ?? 1e4;
|
|
4600
|
+
if (this._seenCrossRegionEvents.size >= maxDedup) {
|
|
4601
|
+
const oldestKey = this._seenCrossRegionEvents.keys().next().value;
|
|
4602
|
+
if (oldestKey !== void 0) this._seenCrossRegionEvents.delete(oldestKey);
|
|
4603
|
+
}
|
|
4604
|
+
this._seenCrossRegionEvents.set(id, Date.now());
|
|
4605
|
+
}
|
|
4606
|
+
_isCrossRegionEventSeen(id) {
|
|
4607
|
+
return this._seenCrossRegionEvents.has(id);
|
|
4608
|
+
}
|
|
4609
|
+
async _broadcastCrossRegion(op, key, tagVersion) {
|
|
4610
|
+
const cr = this.opts.crossRegion;
|
|
4611
|
+
if (!cr) return;
|
|
4612
|
+
try {
|
|
4613
|
+
const eventId = crypto2.randomUUID();
|
|
4614
|
+
this._markCrossRegionEventSeen(eventId);
|
|
4615
|
+
const event = {
|
|
4616
|
+
id: eventId,
|
|
4617
|
+
originRegion: cr.currentRegion,
|
|
4618
|
+
originInstanceId: this.instanceId,
|
|
4619
|
+
op,
|
|
4620
|
+
key,
|
|
4621
|
+
tagVersion,
|
|
4622
|
+
timestamp: Date.now(),
|
|
4623
|
+
namespace: this._namespace || void 0
|
|
4624
|
+
};
|
|
4625
|
+
this.counters.crossRegionSent++;
|
|
4626
|
+
await cr.relay.broadcast(event);
|
|
4627
|
+
this.logger.debug("Cross-region invalidation broadcast", { op, key, region: cr.currentRegion });
|
|
4628
|
+
} catch (err) {
|
|
4629
|
+
this.counters.crossRegionSent = Math.max(0, this.counters.crossRegionSent - 1);
|
|
4630
|
+
this.counters.crossRegionErrors++;
|
|
4631
|
+
this.logger.warn("Cross-region invalidation broadcast failed", { error: err.message });
|
|
4632
|
+
}
|
|
4633
|
+
}
|
|
4634
|
+
/**
|
|
4635
|
+
* Receives an invalidation event from another region (e.g. via HTTP webhook or broker subscriber).
|
|
4636
|
+
* Validates origin, deduplicates to prevent loops, applies locally to L1/disk,
|
|
4637
|
+
* and fans out to the local Redis backplane so all regional peers invalidate as well.
|
|
4638
|
+
*
|
|
4639
|
+
* Returns true if the event was accepted and applied, or false if ignored/deduplicated.
|
|
4640
|
+
*/
|
|
4641
|
+
async receiveCrossRegionInvalidation(event) {
|
|
4642
|
+
const cr = this.opts.crossRegion;
|
|
4643
|
+
if (!cr) return false;
|
|
4644
|
+
if (!event || typeof event !== "object" || !event.id || !event.originRegion || !event.op || !event.key) {
|
|
4645
|
+
this.counters.crossRegionErrors++;
|
|
4646
|
+
this.logger.warn("Cross-region: rejected invalid event payload", { event });
|
|
4647
|
+
return false;
|
|
4648
|
+
}
|
|
4649
|
+
if (event.originRegion === cr.currentRegion) {
|
|
4650
|
+
this.counters.crossRegionDeduplicated++;
|
|
4651
|
+
return false;
|
|
4652
|
+
}
|
|
4653
|
+
if (this._isCrossRegionEventSeen(event.id)) {
|
|
4654
|
+
this.counters.crossRegionDeduplicated++;
|
|
4655
|
+
return false;
|
|
4656
|
+
}
|
|
4657
|
+
this._markCrossRegionEventSeen(event.id);
|
|
4658
|
+
if (event.namespace !== void 0 && event.namespace !== (this._namespace || void 0)) {
|
|
4659
|
+
return false;
|
|
4660
|
+
}
|
|
4661
|
+
this.counters.crossRegionReceived++;
|
|
4662
|
+
this._applyInvalidationEvent(event.op, event.key, event.tagVersion);
|
|
4663
|
+
void this.publishInvalidation(event.op, event.key, event.tagVersion, true);
|
|
4664
|
+
this.logger.info("Cross-region invalidation applied", {
|
|
4665
|
+
op: event.op,
|
|
4666
|
+
key: event.key,
|
|
4667
|
+
originRegion: event.originRegion
|
|
4668
|
+
});
|
|
4669
|
+
return true;
|
|
4670
|
+
}
|
|
4671
|
+
_setLocalTagVersion(tag, version, now = performance.now()) {
|
|
2777
4672
|
const existing = this.tagVersions.get(tag)?.version ?? 0;
|
|
2778
4673
|
const finalVersion = Math.max(existing, version);
|
|
2779
4674
|
if (this.tagVersions.size >= 1e4 && !this.tagVersions.has(tag)) {
|
|
@@ -2783,7 +4678,7 @@ var CacheService = class _CacheService {
|
|
|
2783
4678
|
this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
|
|
2784
4679
|
}
|
|
2785
4680
|
async _getTagVersion(tag) {
|
|
2786
|
-
const now =
|
|
4681
|
+
const now = performance.now();
|
|
2787
4682
|
const local = this.tagVersions.get(tag);
|
|
2788
4683
|
if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
|
|
2789
4684
|
return local.version;
|
|
@@ -2869,13 +4764,25 @@ var CacheService = class _CacheService {
|
|
|
2869
4764
|
stream.on("error", reject);
|
|
2870
4765
|
})
|
|
2871
4766
|
));
|
|
2872
|
-
} else {
|
|
4767
|
+
} else if (typeof client.scanStream === "function") {
|
|
2873
4768
|
await new Promise((resolve, reject) => {
|
|
2874
4769
|
const stream = client.scanStream({ match: pattern, count: 100 });
|
|
2875
4770
|
stream.on("data", (chunk) => keys.push(...chunk));
|
|
2876
4771
|
stream.on("end", resolve);
|
|
2877
4772
|
stream.on("error", reject);
|
|
2878
4773
|
});
|
|
4774
|
+
} else if (typeof client.scanIterator === "function") {
|
|
4775
|
+
for await (const key of client.scanIterator({ MATCH: pattern, COUNT: 100 })) {
|
|
4776
|
+
keys.push(key);
|
|
4777
|
+
}
|
|
4778
|
+
} else if (typeof client.scan === "function") {
|
|
4779
|
+
let cursor = "0";
|
|
4780
|
+
do {
|
|
4781
|
+
const res = await client.scan(cursor, "MATCH", pattern, "COUNT", 100);
|
|
4782
|
+
cursor = String(res[0]);
|
|
4783
|
+
const chunk = res[1];
|
|
4784
|
+
if (chunk?.length) keys.push(...chunk);
|
|
4785
|
+
} while (cursor !== "0");
|
|
2879
4786
|
}
|
|
2880
4787
|
return keys;
|
|
2881
4788
|
}
|
|
@@ -2892,6 +4799,19 @@ var CacheService = class _CacheService {
|
|
|
2892
4799
|
if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
|
|
2893
4800
|
if (this.redis) return this.redis;
|
|
2894
4801
|
if (this.redisConnecting) return this.redisConnecting;
|
|
4802
|
+
if (this.opts.redisClient) {
|
|
4803
|
+
const client = this.opts.redisClient;
|
|
4804
|
+
if (typeof client.connect === "function" && client.isOpen === false) {
|
|
4805
|
+
await client.connect();
|
|
4806
|
+
}
|
|
4807
|
+
this.cb.onSuccess();
|
|
4808
|
+
this.redis = client;
|
|
4809
|
+
this.pipeliner = new AutoPipeliner(client, {
|
|
4810
|
+
enabled: this.opts.autoPipeline,
|
|
4811
|
+
maxBatchSize: this.opts.maxPipelineBatchSize
|
|
4812
|
+
});
|
|
4813
|
+
return client;
|
|
4814
|
+
}
|
|
2895
4815
|
this.redisConnecting = (async () => {
|
|
2896
4816
|
try {
|
|
2897
4817
|
let client;
|
|
@@ -2900,6 +4820,7 @@ var CacheService = class _CacheService {
|
|
|
2900
4820
|
redisOptions: {
|
|
2901
4821
|
tls: this.opts.redisTls ? {} : void 0,
|
|
2902
4822
|
connectTimeout: 1e4,
|
|
4823
|
+
commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
|
|
2903
4824
|
maxRetriesPerRequest: 3,
|
|
2904
4825
|
keepAlive: 3e4,
|
|
2905
4826
|
...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
|
|
@@ -2920,6 +4841,7 @@ var CacheService = class _CacheService {
|
|
|
2920
4841
|
name: this.opts.redisSentinel.name,
|
|
2921
4842
|
tls: this.opts.redisTls ? {} : void 0,
|
|
2922
4843
|
connectTimeout: 1e4,
|
|
4844
|
+
commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
|
|
2923
4845
|
lazyConnect: false,
|
|
2924
4846
|
maxRetriesPerRequest: 3,
|
|
2925
4847
|
enableAutoPipelining: true,
|
|
@@ -2939,6 +4861,7 @@ var CacheService = class _CacheService {
|
|
|
2939
4861
|
port: this.opts.redisPort,
|
|
2940
4862
|
tls: this.opts.redisTls ? {} : void 0,
|
|
2941
4863
|
connectTimeout: 1e4,
|
|
4864
|
+
commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
|
|
2942
4865
|
lazyConnect: false,
|
|
2943
4866
|
maxRetriesPerRequest: 3,
|
|
2944
4867
|
enableAutoPipelining: true,
|
|
@@ -2964,6 +4887,10 @@ var CacheService = class _CacheService {
|
|
|
2964
4887
|
});
|
|
2965
4888
|
this.cb.onSuccess();
|
|
2966
4889
|
this.redis = client;
|
|
4890
|
+
this.pipeliner = new AutoPipeliner(client, {
|
|
4891
|
+
enabled: this.opts.autoPipeline,
|
|
4892
|
+
maxBatchSize: this.opts.maxPipelineBatchSize
|
|
4893
|
+
});
|
|
2967
4894
|
this.redisConnecting = null;
|
|
2968
4895
|
return client;
|
|
2969
4896
|
} catch (err) {
|
|
@@ -2976,16 +4903,22 @@ var CacheService = class _CacheService {
|
|
|
2976
4903
|
return this.redisConnecting;
|
|
2977
4904
|
}
|
|
2978
4905
|
// ── Snapshot (cold-start persistence) ────────────────────────────────────
|
|
4906
|
+
/**
|
|
4907
|
+
* Writes the cold-start snapshot to disk.
|
|
4908
|
+
* NOTE: fs.writeFileSync is INTENTIONAL here: this method is invoked during SIGTERM/SIGINT
|
|
4909
|
+
* process termination hooks where asynchronous I/O would risk the Node.js event loop dying or
|
|
4910
|
+
* process.exit() being called before the snapshot is physically written to disk.
|
|
4911
|
+
*/
|
|
2979
4912
|
writeSnapshot(altPath) {
|
|
2980
4913
|
try {
|
|
2981
4914
|
const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
|
|
2982
4915
|
if (entries.length === 0) return;
|
|
2983
4916
|
const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
|
|
2984
|
-
const packed =
|
|
4917
|
+
const packed = this.codec.encode(payload);
|
|
2985
4918
|
const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
|
|
2986
4919
|
const dest = altPath ?? this.opts.snapshotPath;
|
|
2987
|
-
|
|
2988
|
-
|
|
4920
|
+
fs4.mkdirSync(path3.dirname(dest), { recursive: true });
|
|
4921
|
+
fs4.writeFileSync(dest, final, { mode: 384 });
|
|
2989
4922
|
this.logger.info("Cache snapshot written", {
|
|
2990
4923
|
path: dest,
|
|
2991
4924
|
entries: entries.length,
|
|
@@ -2996,18 +4929,24 @@ var CacheService = class _CacheService {
|
|
|
2996
4929
|
this.logger.warn("Cache snapshot write failed", { error: err.message });
|
|
2997
4930
|
}
|
|
2998
4931
|
}
|
|
4932
|
+
/**
|
|
4933
|
+
* Loads cold-start snapshot from disk into L1 memory.
|
|
4934
|
+
* NOTE: fs.readFileSync is INTENTIONAL here: this method is invoked synchronously inside the
|
|
4935
|
+
* CacheService constructor so that the cache is atomically populated before any subsequent
|
|
4936
|
+
* cache.get() or cache.set() operations run, eliminating cold-start race conditions.
|
|
4937
|
+
*/
|
|
2999
4938
|
loadSnapshot() {
|
|
3000
4939
|
const snapshotPath = this.opts.snapshotPath;
|
|
3001
4940
|
try {
|
|
3002
|
-
if (!
|
|
3003
|
-
const stat =
|
|
4941
|
+
if (!fs4.existsSync(snapshotPath)) return;
|
|
4942
|
+
const stat = fs4.statSync(snapshotPath);
|
|
3004
4943
|
if (stat.size > SNAPSHOT_MAX_FILE_BYTES) {
|
|
3005
4944
|
this.logger.warn("Snapshot rejected: exceeds size limit", { sizeBytes: stat.size });
|
|
3006
|
-
|
|
4945
|
+
fs4.unlinkSync(snapshotPath);
|
|
3007
4946
|
return;
|
|
3008
4947
|
}
|
|
3009
|
-
const raw =
|
|
3010
|
-
|
|
4948
|
+
const raw = fs4.readFileSync(snapshotPath);
|
|
4949
|
+
fs4.unlinkSync(snapshotPath);
|
|
3011
4950
|
let buf;
|
|
3012
4951
|
try {
|
|
3013
4952
|
buf = this.enc.decryptBuffer(raw);
|
|
@@ -3015,13 +4954,25 @@ var CacheService = class _CacheService {
|
|
|
3015
4954
|
this.logger.warn("Snapshot rejected: decryption failed", { error: e.message });
|
|
3016
4955
|
return;
|
|
3017
4956
|
}
|
|
3018
|
-
const snapshot =
|
|
4957
|
+
const snapshot = this.codec.decode(buf);
|
|
3019
4958
|
if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
|
|
3020
4959
|
this.logger.warn("Snapshot rejected: version mismatch", { got: snapshot?.version });
|
|
3021
4960
|
return;
|
|
3022
4961
|
}
|
|
3023
|
-
const
|
|
3024
|
-
|
|
4962
|
+
const now = Date.now();
|
|
4963
|
+
const writtenAt = snapshot.writtenAt ?? 0;
|
|
4964
|
+
const tolerance = this.opts.clockSkewToleranceMs ?? 250;
|
|
4965
|
+
if (writtenAt - now > tolerance) {
|
|
4966
|
+
this.logger.warn("Snapshot rejected: timestamp too far in future (exceeds clock skew tolerance)", {
|
|
4967
|
+
writtenAt,
|
|
4968
|
+
now,
|
|
4969
|
+
skewMs: writtenAt - now,
|
|
4970
|
+
tolerance
|
|
4971
|
+
});
|
|
4972
|
+
return;
|
|
4973
|
+
}
|
|
4974
|
+
const ageMs = Math.max(0, now - writtenAt);
|
|
4975
|
+
if (ageMs > this.opts.snapshotMaxAgeMs) {
|
|
3025
4976
|
this.logger.warn("Snapshot rejected: too old", { ageMinutes: Math.round(ageMs / 6e4) });
|
|
3026
4977
|
return;
|
|
3027
4978
|
}
|
|
@@ -3038,11 +4989,120 @@ var CacheService = class _CacheService {
|
|
|
3038
4989
|
} catch (err) {
|
|
3039
4990
|
this.logger.warn("Snapshot load failed \u2014 starting cold", { error: err.message });
|
|
3040
4991
|
try {
|
|
3041
|
-
|
|
4992
|
+
fs4.unlinkSync(snapshotPath);
|
|
3042
4993
|
} catch {
|
|
3043
4994
|
}
|
|
3044
4995
|
}
|
|
3045
4996
|
}
|
|
4997
|
+
// ── Remote Snapshot (cold-start persistence for stateless containers) ───────
|
|
4998
|
+
/**
|
|
4999
|
+
* Persists the cold-start snapshot to remote blob storage (S3, GCS, R2, HTTP).
|
|
5000
|
+
* Can be awaited during graceful application shutdown (e.g. Kubernetes preStop or NestJS shutdown).
|
|
5001
|
+
* Returns true if a snapshot was successfully exported and written; false otherwise.
|
|
5002
|
+
*/
|
|
5003
|
+
async writeRemoteSnapshot() {
|
|
5004
|
+
if (!this.opts.remoteSnapshot) return false;
|
|
5005
|
+
try {
|
|
5006
|
+
const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
|
|
5007
|
+
if (entries.length === 0) return false;
|
|
5008
|
+
const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
|
|
5009
|
+
const packed = this.codec.encode(payload);
|
|
5010
|
+
let final;
|
|
5011
|
+
if (this.opts.remoteSnapshot.envelope) {
|
|
5012
|
+
final = await EnvelopeEncryption.encrypt(packed, this.opts.remoteSnapshot.envelope);
|
|
5013
|
+
} else {
|
|
5014
|
+
final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
|
|
5015
|
+
}
|
|
5016
|
+
await this.opts.remoteSnapshot.adapter.put(final);
|
|
5017
|
+
this.counters.remoteSnapshotUploads++;
|
|
5018
|
+
this.counters.remoteSnapshotLastUploadedAt = Date.now();
|
|
5019
|
+
this.logger.info("Remote cache snapshot uploaded", {
|
|
5020
|
+
entries: entries.length,
|
|
5021
|
+
sizeKB: Math.round(final.length / 1024),
|
|
5022
|
+
encrypted: Boolean(this.opts.remoteSnapshot.envelope || this.enc.isEnabled)
|
|
5023
|
+
});
|
|
5024
|
+
return true;
|
|
5025
|
+
} catch (err) {
|
|
5026
|
+
this.counters.remoteSnapshotErrors++;
|
|
5027
|
+
this.logger.warn("Remote cache snapshot upload failed", { error: err.message });
|
|
5028
|
+
return false;
|
|
5029
|
+
}
|
|
5030
|
+
}
|
|
5031
|
+
/**
|
|
5032
|
+
* Hydrates L1 memory from remote blob storage (S3, GCS, R2, HTTP).
|
|
5033
|
+
* Called automatically during startup (chained into `cache.ready()`).
|
|
5034
|
+
* Returns the number of entries successfully imported.
|
|
5035
|
+
*/
|
|
5036
|
+
async loadRemoteSnapshot() {
|
|
5037
|
+
if (!this.opts.remoteSnapshot) return 0;
|
|
5038
|
+
const maxAgeMs = this.opts.remoteSnapshot.maxAgeMs ?? this.opts.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE;
|
|
5039
|
+
try {
|
|
5040
|
+
const raw = await this.opts.remoteSnapshot.adapter.get();
|
|
5041
|
+
if (!raw || raw.length === 0) {
|
|
5042
|
+
this.logger.debug("Remote snapshot not found or empty \u2014 starting cold");
|
|
5043
|
+
return 0;
|
|
5044
|
+
}
|
|
5045
|
+
const rawBuf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
|
|
5046
|
+
let buf;
|
|
5047
|
+
try {
|
|
5048
|
+
if (EnvelopeEncryption.isEnvelope(rawBuf)) {
|
|
5049
|
+
if (!this.opts.remoteSnapshot.envelope) {
|
|
5050
|
+
throw new Error("Remote snapshot is envelope-encrypted but no envelope options (privateKey or kmsDecrypt) were configured");
|
|
5051
|
+
}
|
|
5052
|
+
buf = await EnvelopeEncryption.decrypt(rawBuf, this.opts.remoteSnapshot.envelope);
|
|
5053
|
+
} else {
|
|
5054
|
+
buf = this.enc.decryptBuffer(rawBuf);
|
|
5055
|
+
}
|
|
5056
|
+
} catch (e) {
|
|
5057
|
+
this.counters.remoteSnapshotErrors++;
|
|
5058
|
+
this.logger.warn("Remote snapshot rejected: decryption failed", { error: e.message });
|
|
5059
|
+
return 0;
|
|
5060
|
+
}
|
|
5061
|
+
const snapshot = this.codec.decode(buf);
|
|
5062
|
+
if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
|
|
5063
|
+
this.counters.remoteSnapshotErrors++;
|
|
5064
|
+
this.logger.warn("Remote snapshot rejected: version mismatch", { got: snapshot?.version });
|
|
5065
|
+
return 0;
|
|
5066
|
+
}
|
|
5067
|
+
const now = Date.now();
|
|
5068
|
+
const writtenAt = snapshot.writtenAt ?? 0;
|
|
5069
|
+
const tolerance = this.opts.clockSkewToleranceMs ?? 250;
|
|
5070
|
+
if (writtenAt - now > tolerance) {
|
|
5071
|
+
this.counters.remoteSnapshotErrors++;
|
|
5072
|
+
this.logger.warn("Remote snapshot rejected: timestamp too far in future (exceeds clock skew tolerance)", {
|
|
5073
|
+
writtenAt,
|
|
5074
|
+
now,
|
|
5075
|
+
skewMs: writtenAt - now,
|
|
5076
|
+
tolerance
|
|
5077
|
+
});
|
|
5078
|
+
return 0;
|
|
5079
|
+
}
|
|
5080
|
+
const ageMs = Math.max(0, now - writtenAt);
|
|
5081
|
+
if (maxAgeMs <= 0 || ageMs > maxAgeMs) {
|
|
5082
|
+
this.counters.remoteSnapshotErrors++;
|
|
5083
|
+
this.logger.warn("Remote snapshot rejected: too old", { ageMinutes: Math.round(ageMs / 6e4) });
|
|
5084
|
+
return 0;
|
|
5085
|
+
}
|
|
5086
|
+
if (!Array.isArray(snapshot.entries)) {
|
|
5087
|
+
this.counters.remoteSnapshotErrors++;
|
|
5088
|
+
this.logger.warn("Remote snapshot rejected: entries is not an array");
|
|
5089
|
+
return 0;
|
|
5090
|
+
}
|
|
5091
|
+
const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
|
|
5092
|
+
this.counters.remoteSnapshotDownloads++;
|
|
5093
|
+
this.counters.remoteSnapshotLastDownloadedAt = Date.now();
|
|
5094
|
+
this.logger.info("Remote cache snapshot loaded (L1 hydrated)", {
|
|
5095
|
+
loaded,
|
|
5096
|
+
total: snapshot.entries.length,
|
|
5097
|
+
sizeKB: this.l1.getStats().sizeKB
|
|
5098
|
+
});
|
|
5099
|
+
return loaded;
|
|
5100
|
+
} catch (err) {
|
|
5101
|
+
this.counters.remoteSnapshotErrors++;
|
|
5102
|
+
this.logger.warn("Remote snapshot load failed \u2014 starting cold", { error: err.message });
|
|
5103
|
+
return 0;
|
|
5104
|
+
}
|
|
5105
|
+
}
|
|
3046
5106
|
// ── Core get (L1 → L1.5 → L2 → fetch) ───────────────────────────────────
|
|
3047
5107
|
/**
|
|
3048
5108
|
* Get a value from cache, or fetch and cache it.
|
|
@@ -3078,9 +5138,10 @@ var CacheService = class _CacheService {
|
|
|
3078
5138
|
if (l1Hit !== null) {
|
|
3079
5139
|
let isGenerationalStale = false;
|
|
3080
5140
|
if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
|
|
3081
|
-
|
|
3082
|
-
|
|
3083
|
-
|
|
5141
|
+
const tags = Object.keys(l1Hit.tagVersions);
|
|
5142
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5143
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5144
|
+
if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
|
|
3084
5145
|
isGenerationalStale = true;
|
|
3085
5146
|
break;
|
|
3086
5147
|
}
|
|
@@ -3125,116 +5186,140 @@ var CacheService = class _CacheService {
|
|
|
3125
5186
|
this.counters.l1Hits++;
|
|
3126
5187
|
this.opts.onHit?.(cacheKey, "l1");
|
|
3127
5188
|
if (this.opts.frozen) deepFreeze(l1Hit.value);
|
|
3128
|
-
span.setAttribute("cache.hit", "l1").end();
|
|
5189
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "memory").setAttribute("cache.hit_tier", "l1").end();
|
|
3129
5190
|
return this.opts.cloneStrategy === "structuredClone" && l1Hit.value != null && typeof l1Hit.value === "object" ? structuredClone(l1Hit.value) : l1Hit.value;
|
|
3130
5191
|
}
|
|
3131
5192
|
}
|
|
3132
5193
|
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
3133
5194
|
const swrGraceMs = optSwr * 1e3;
|
|
3134
5195
|
const priority = optPriority ?? inferPriority(cacheKey);
|
|
3135
|
-
|
|
5196
|
+
const existing = this.inflight.get(k);
|
|
5197
|
+
if (existing) {
|
|
5198
|
+
this.counters.stampedes++;
|
|
5199
|
+
this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch/read", { cacheKey });
|
|
5200
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
|
|
5201
|
+
return existing;
|
|
5202
|
+
}
|
|
5203
|
+
const executionPromise = (async () => {
|
|
3136
5204
|
try {
|
|
3137
|
-
|
|
3138
|
-
|
|
3139
|
-
|
|
3140
|
-
|
|
3141
|
-
|
|
3142
|
-
|
|
3143
|
-
|
|
3144
|
-
|
|
3145
|
-
|
|
3146
|
-
|
|
3147
|
-
|
|
5205
|
+
if (!this._diskDisabled) {
|
|
5206
|
+
const isDiskAllowed = this.watchdog.isDiskAllowed();
|
|
5207
|
+
if (isDiskAllowed) {
|
|
5208
|
+
const diskStart = performance.now();
|
|
5209
|
+
const diskHit = this.disk.load(k);
|
|
5210
|
+
const diskElapsed = performance.now() - diskStart;
|
|
5211
|
+
this.watchdog.recordDisk(diskElapsed);
|
|
5212
|
+
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
5213
|
+
if (diskHit !== null) {
|
|
5214
|
+
let isDiskStale = false;
|
|
5215
|
+
if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
|
|
5216
|
+
const tags = Object.keys(diskHit.tagVersions);
|
|
5217
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5218
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5219
|
+
if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
|
|
5220
|
+
isDiskStale = true;
|
|
5221
|
+
break;
|
|
5222
|
+
}
|
|
5223
|
+
}
|
|
3148
5224
|
}
|
|
3149
|
-
|
|
3150
|
-
|
|
3151
|
-
|
|
3152
|
-
|
|
3153
|
-
|
|
3154
|
-
|
|
5225
|
+
if (isDiskStale) {
|
|
5226
|
+
this.disk.delete(k);
|
|
5227
|
+
} else {
|
|
5228
|
+
const promoted = this.l1.importEntries(
|
|
5229
|
+
[{ key: k, entry: diskHit }],
|
|
5230
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
5231
|
+
);
|
|
5232
|
+
if (promoted > 0) {
|
|
5233
|
+
const l1Check = this.l1.get(k);
|
|
5234
|
+
if (l1Check !== null) {
|
|
5235
|
+
this.counters.diskHits++;
|
|
5236
|
+
this.opts.onHit?.(cacheKey, "disk");
|
|
5237
|
+
this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
|
|
5238
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
|
|
5239
|
+
if (this.opts.frozen) deepFreeze(l1Check.value);
|
|
5240
|
+
return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
|
|
5241
|
+
}
|
|
5242
|
+
}
|
|
3155
5243
|
}
|
|
3156
5244
|
}
|
|
3157
|
-
if (isStale) {
|
|
3158
|
-
const setAtMs = parseInt(hashData.t, 10) || 0;
|
|
3159
|
-
this._deleteIfStale(k, setAtMs);
|
|
3160
|
-
} else {
|
|
3161
|
-
const parsed = await this._decryptAndDeserialize(hashData.d);
|
|
3162
|
-
this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
|
|
3163
|
-
this.counters.l2Hits++;
|
|
3164
|
-
this.opts.onHit?.(cacheKey, "l2");
|
|
3165
|
-
this.logger.debug("L2 hit (Redis hash)", { cacheKey });
|
|
3166
|
-
span.setAttribute("cache.hit", "l2").end();
|
|
3167
|
-
if (this.opts.frozen) deepFreeze(parsed);
|
|
3168
|
-
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
3169
|
-
}
|
|
3170
|
-
}
|
|
3171
|
-
} else {
|
|
3172
|
-
const raw = await client.get(k);
|
|
3173
|
-
this.cb.onSuccess();
|
|
3174
|
-
if (raw) {
|
|
3175
|
-
const parsed = await this._decryptAndDeserialize(raw);
|
|
3176
|
-
this.l1.set(k, parsed, ttlMs, priority);
|
|
3177
|
-
this.counters.l2Hits++;
|
|
3178
|
-
this.opts.onHit?.(cacheKey, "l2");
|
|
3179
|
-
this.logger.debug("L2 hit (Redis)", { cacheKey });
|
|
3180
|
-
span.setAttribute("cache.hit", "l2").end();
|
|
3181
|
-
if (this.opts.frozen) deepFreeze(parsed);
|
|
3182
|
-
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
3183
5245
|
}
|
|
3184
5246
|
}
|
|
3185
|
-
|
|
3186
|
-
|
|
3187
|
-
|
|
3188
|
-
|
|
3189
|
-
|
|
3190
|
-
|
|
3191
|
-
|
|
3192
|
-
|
|
3193
|
-
|
|
3194
|
-
|
|
3195
|
-
|
|
3196
|
-
|
|
3197
|
-
|
|
3198
|
-
|
|
3199
|
-
|
|
3200
|
-
|
|
3201
|
-
|
|
3202
|
-
|
|
3203
|
-
|
|
3204
|
-
|
|
3205
|
-
|
|
3206
|
-
|
|
3207
|
-
|
|
3208
|
-
|
|
3209
|
-
|
|
3210
|
-
|
|
3211
|
-
|
|
3212
|
-
|
|
3213
|
-
|
|
3214
|
-
|
|
3215
|
-
|
|
3216
|
-
|
|
3217
|
-
|
|
3218
|
-
|
|
5247
|
+
if (!this._redisDisabled) {
|
|
5248
|
+
try {
|
|
5249
|
+
const client = await this.getRedis();
|
|
5250
|
+
const redisStart = performance.now();
|
|
5251
|
+
if (this.opts.tagStrategy === "generational") {
|
|
5252
|
+
const hashData = await client.hgetall(k);
|
|
5253
|
+
const redisElapsed = performance.now() - redisStart;
|
|
5254
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
5255
|
+
this.cb.onSuccess();
|
|
5256
|
+
if (hashData && hashData.d) {
|
|
5257
|
+
let isStale = false;
|
|
5258
|
+
let storedTagVersions = {};
|
|
5259
|
+
if (hashData.tv) {
|
|
5260
|
+
try {
|
|
5261
|
+
storedTagVersions = JSON.parse(hashData.tv);
|
|
5262
|
+
} catch {
|
|
5263
|
+
}
|
|
5264
|
+
}
|
|
5265
|
+
const tags = Object.keys(storedTagVersions);
|
|
5266
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5267
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5268
|
+
if (currentVers[i] > storedTagVersions[tags[i]]) {
|
|
5269
|
+
isStale = true;
|
|
5270
|
+
break;
|
|
5271
|
+
}
|
|
5272
|
+
}
|
|
5273
|
+
if (isStale) {
|
|
5274
|
+
const setAtMs = parseInt(hashData.t, 10) || 0;
|
|
5275
|
+
this._deleteIfStale(k, setAtMs);
|
|
5276
|
+
} else {
|
|
5277
|
+
const parsed = await this._decryptAndDeserialize(hashData.d);
|
|
5278
|
+
this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
|
|
5279
|
+
this.counters.l2Hits++;
|
|
5280
|
+
this.opts.onHit?.(cacheKey, "l2");
|
|
5281
|
+
this.logger.debug("L2 hit (Redis hash)", { cacheKey });
|
|
5282
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
5283
|
+
if (this.opts.frozen) deepFreeze(parsed);
|
|
5284
|
+
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
5285
|
+
}
|
|
5286
|
+
}
|
|
5287
|
+
} else {
|
|
5288
|
+
const raw = this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
|
|
5289
|
+
const redisElapsed = performance.now() - redisStart;
|
|
5290
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
5291
|
+
this.cb.onSuccess();
|
|
5292
|
+
if (raw) {
|
|
5293
|
+
const parsed = await this._decryptAndDeserialize(raw);
|
|
5294
|
+
this.l1.set(k, parsed, ttlMs, priority);
|
|
5295
|
+
this.counters.l2Hits++;
|
|
5296
|
+
this.opts.onHit?.(cacheKey, "l2");
|
|
5297
|
+
this.logger.debug("L2 hit (Redis)", { cacheKey });
|
|
5298
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
5299
|
+
if (this.opts.frozen) deepFreeze(parsed);
|
|
5300
|
+
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
5301
|
+
}
|
|
3219
5302
|
}
|
|
5303
|
+
} catch (err) {
|
|
5304
|
+
this.cb.onFailure();
|
|
5305
|
+
this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
|
|
3220
5306
|
}
|
|
3221
5307
|
}
|
|
3222
|
-
|
|
3223
|
-
|
|
3224
|
-
span.setAttribute("cache.hit", "miss");
|
|
3225
|
-
this.opts.onMiss?.(cacheKey);
|
|
3226
|
-
const existing = this.inflight.get(k);
|
|
3227
|
-
if (existing) {
|
|
3228
|
-
this.counters.stampedes++;
|
|
3229
|
-
this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch", { cacheKey });
|
|
3230
|
-
span.end();
|
|
3231
|
-
return existing;
|
|
3232
|
-
}
|
|
3233
|
-
const fetchPromise = (async () => {
|
|
3234
|
-
try {
|
|
5308
|
+
span.setAttribute("cache.hit", false).setAttribute("cache.hit_tier", "miss");
|
|
5309
|
+
this.opts.onMiss?.(cacheKey);
|
|
3235
5310
|
this.counters.fetches++;
|
|
3236
5311
|
const fetchStart = Date.now();
|
|
3237
|
-
|
|
5312
|
+
let data;
|
|
5313
|
+
try {
|
|
5314
|
+
data = await fetchFn();
|
|
5315
|
+
} catch (fetchErr) {
|
|
5316
|
+
span.setStatus({
|
|
5317
|
+
code: 2,
|
|
5318
|
+
message: fetchErr instanceof Error ? fetchErr.message : String(fetchErr)
|
|
5319
|
+
});
|
|
5320
|
+
span.recordException?.(fetchErr);
|
|
5321
|
+
throw fetchErr;
|
|
5322
|
+
}
|
|
3238
5323
|
const delta = Date.now() - fetchStart;
|
|
3239
5324
|
const notFoundTtlMs = (optNotFoundTtl ?? this.opts.notFoundTtl) * 1e3;
|
|
3240
5325
|
let effectiveTtl = data == null && notFoundTtlMs > 0 ? notFoundTtlMs : ttlMs;
|
|
@@ -3254,9 +5339,10 @@ var CacheService = class _CacheService {
|
|
|
3254
5339
|
let activeTagVersions;
|
|
3255
5340
|
if (optTags?.length) {
|
|
3256
5341
|
if (this.opts.tagStrategy === "generational") {
|
|
5342
|
+
const vers = await Promise.all(optTags.map((tag) => this._getTagVersion(tag)));
|
|
3257
5343
|
activeTagVersions = {};
|
|
3258
|
-
for (
|
|
3259
|
-
activeTagVersions[
|
|
5344
|
+
for (let i = 0; i < optTags.length; i++) {
|
|
5345
|
+
activeTagVersions[optTags[i]] = vers[i];
|
|
3260
5346
|
}
|
|
3261
5347
|
} else {
|
|
3262
5348
|
await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
|
|
@@ -3298,8 +5384,64 @@ var CacheService = class _CacheService {
|
|
|
3298
5384
|
span.end();
|
|
3299
5385
|
}
|
|
3300
5386
|
})();
|
|
3301
|
-
this.inflight.set(k,
|
|
3302
|
-
return
|
|
5387
|
+
this.inflight.set(k, executionPromise);
|
|
5388
|
+
return executionPromise;
|
|
5389
|
+
}
|
|
5390
|
+
/**
|
|
5391
|
+
* Graceful shutdown flusher for Kubernetes preStop hooks, NestJS onApplicationShutdown,
|
|
5392
|
+
* or manual microservice teardown.
|
|
5393
|
+
*
|
|
5394
|
+
* Flushes both local disk and remote cloud snapshots (S3/R2/GCS), returning a Promise
|
|
5395
|
+
* that resolves when the upload completes or after `timeoutMs` expires.
|
|
5396
|
+
*
|
|
5397
|
+
* @param timeoutMs Maximum time permitted for snapshot persistence before timing out. Default: 8000ms.
|
|
5398
|
+
*/
|
|
5399
|
+
async flushSnapshotOnShutdown(timeoutMs = 8e3) {
|
|
5400
|
+
const flusher = async () => {
|
|
5401
|
+
let localOk = true;
|
|
5402
|
+
let remoteOk = true;
|
|
5403
|
+
if (!this._diskDisabled) {
|
|
5404
|
+
try {
|
|
5405
|
+
this.writeSnapshot();
|
|
5406
|
+
} catch (err) {
|
|
5407
|
+
localOk = false;
|
|
5408
|
+
this.logger.warn("flushSnapshotOnShutdown: disk snapshot write failed", { error: err.message });
|
|
5409
|
+
}
|
|
5410
|
+
}
|
|
5411
|
+
if (this.opts.remoteSnapshot && this.opts.remoteSnapshot.saveOnShutdown !== false) {
|
|
5412
|
+
try {
|
|
5413
|
+
remoteOk = await this.writeRemoteSnapshot();
|
|
5414
|
+
} catch (err) {
|
|
5415
|
+
remoteOk = false;
|
|
5416
|
+
this.logger.warn("flushSnapshotOnShutdown: remote snapshot upload failed", { error: err.message });
|
|
5417
|
+
}
|
|
5418
|
+
}
|
|
5419
|
+
return localOk && remoteOk;
|
|
5420
|
+
};
|
|
5421
|
+
let timer = null;
|
|
5422
|
+
try {
|
|
5423
|
+
return await Promise.race([
|
|
5424
|
+
flusher(),
|
|
5425
|
+
new Promise((resolve) => {
|
|
5426
|
+
timer = setTimeout(() => {
|
|
5427
|
+
this.logger.warn(`flushSnapshotOnShutdown timed out after ${timeoutMs}ms`);
|
|
5428
|
+
resolve(false);
|
|
5429
|
+
}, timeoutMs);
|
|
5430
|
+
if (timer.unref) timer.unref();
|
|
5431
|
+
})
|
|
5432
|
+
]);
|
|
5433
|
+
} finally {
|
|
5434
|
+
if (timer) clearTimeout(timer);
|
|
5435
|
+
}
|
|
5436
|
+
}
|
|
5437
|
+
/**
|
|
5438
|
+
* Internal graceful shutdown trigger invoked by ProcessTerminationBus.
|
|
5439
|
+
*/
|
|
5440
|
+
_triggerShutdown() {
|
|
5441
|
+
if (!this._diskDisabled) this.writeSnapshot();
|
|
5442
|
+
if (this.opts.remoteSnapshot && this.opts.remoteSnapshot.saveOnShutdown !== false) {
|
|
5443
|
+
void this.flushSnapshotOnShutdown();
|
|
5444
|
+
}
|
|
3303
5445
|
}
|
|
3304
5446
|
/**
|
|
3305
5447
|
* Universal fetch-and-cache wrapper with an ergonomic options object.
|
|
@@ -3332,9 +5474,11 @@ var CacheService = class _CacheService {
|
|
|
3332
5474
|
let activeTagVersions;
|
|
3333
5475
|
const l1Existing = this.l1.get(cacheKey);
|
|
3334
5476
|
if (this.opts.tagStrategy === "generational" && l1Existing?.tagVersions) {
|
|
5477
|
+
const tags = Object.keys(l1Existing.tagVersions);
|
|
5478
|
+
const vers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
3335
5479
|
activeTagVersions = {};
|
|
3336
|
-
for (
|
|
3337
|
-
activeTagVersions[
|
|
5480
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5481
|
+
activeTagVersions[tags[i]] = vers[i];
|
|
3338
5482
|
}
|
|
3339
5483
|
}
|
|
3340
5484
|
this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
|
|
@@ -3380,61 +5524,77 @@ var CacheService = class _CacheService {
|
|
|
3380
5524
|
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
3381
5525
|
async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
|
|
3382
5526
|
const span = this._startSpan("tricache.set");
|
|
3383
|
-
if (this.opts.tracer)
|
|
3384
|
-
|
|
3385
|
-
|
|
3386
|
-
|
|
3387
|
-
|
|
3388
|
-
|
|
3389
|
-
|
|
3390
|
-
|
|
3391
|
-
|
|
3392
|
-
|
|
3393
|
-
|
|
5527
|
+
if (this.opts.tracer) {
|
|
5528
|
+
span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
5529
|
+
span.setAttribute("cache.ttl", ttlSeconds);
|
|
5530
|
+
}
|
|
5531
|
+
try {
|
|
5532
|
+
const effectiveTtlSeconds = ttlSeconds > 0 ? ttlSeconds : ttlSeconds === 0 ? INDEFINITE_TTL_SECONDS : ttlSeconds;
|
|
5533
|
+
const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
|
|
5534
|
+
const p = priority ?? inferPriority(cacheKey);
|
|
5535
|
+
const k = this.nk(cacheKey);
|
|
5536
|
+
this.counters.sets++;
|
|
5537
|
+
let activeTagVersions;
|
|
5538
|
+
if (opts?.tags?.length) {
|
|
5539
|
+
if (this.opts.tagStrategy === "generational") {
|
|
5540
|
+
const vers = await Promise.all(opts.tags.map((tag) => this._getTagVersion(tag)));
|
|
5541
|
+
activeTagVersions = {};
|
|
5542
|
+
for (let i = 0; i < opts.tags.length; i++) {
|
|
5543
|
+
activeTagVersions[opts.tags[i]] = vers[i];
|
|
5544
|
+
}
|
|
5545
|
+
} else {
|
|
5546
|
+
await this._registerTags(k, opts.tags, ttlSeconds);
|
|
3394
5547
|
}
|
|
3395
|
-
} else {
|
|
3396
|
-
await this._registerTags(k, opts.tags, ttlSeconds);
|
|
3397
5548
|
}
|
|
3398
|
-
|
|
3399
|
-
|
|
3400
|
-
|
|
3401
|
-
|
|
3402
|
-
|
|
3403
|
-
|
|
3404
|
-
|
|
3405
|
-
|
|
3406
|
-
|
|
5549
|
+
this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
|
|
5550
|
+
if (opts?.dependsOn?.length) {
|
|
5551
|
+
for (const pattern of opts.dependsOn) {
|
|
5552
|
+
const nsPattern = this.nk(pattern);
|
|
5553
|
+
let deps = this.dependencyIndex.get(nsPattern);
|
|
5554
|
+
if (!deps) {
|
|
5555
|
+
deps = /* @__PURE__ */ new Set();
|
|
5556
|
+
this.dependencyIndex.set(nsPattern, deps);
|
|
5557
|
+
}
|
|
5558
|
+
deps.add(k);
|
|
3407
5559
|
}
|
|
3408
|
-
deps.add(k);
|
|
3409
5560
|
}
|
|
3410
|
-
|
|
3411
|
-
|
|
3412
|
-
|
|
3413
|
-
|
|
3414
|
-
|
|
3415
|
-
|
|
3416
|
-
|
|
3417
|
-
|
|
3418
|
-
|
|
3419
|
-
|
|
3420
|
-
|
|
3421
|
-
|
|
3422
|
-
|
|
3423
|
-
|
|
3424
|
-
|
|
3425
|
-
|
|
3426
|
-
|
|
3427
|
-
|
|
3428
|
-
|
|
5561
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5562
|
+
try {
|
|
5563
|
+
const client = await this.getRedis();
|
|
5564
|
+
const s = JSON.stringify(data);
|
|
5565
|
+
const stored = await this._serializeAndEncrypt(s);
|
|
5566
|
+
const ttlSec = Math.ceil(ttlMs / 1e3);
|
|
5567
|
+
if (this.opts.tagStrategy === "generational" && activeTagVersions) {
|
|
5568
|
+
const now = Date.now();
|
|
5569
|
+
const tx = client.multi();
|
|
5570
|
+
tx.hset(k, {
|
|
5571
|
+
d: stored,
|
|
5572
|
+
t: String(now),
|
|
5573
|
+
tv: JSON.stringify(activeTagVersions)
|
|
5574
|
+
});
|
|
5575
|
+
tx.expire(k, ttlSec);
|
|
5576
|
+
await tx.exec();
|
|
5577
|
+
} else {
|
|
5578
|
+
if (this.opts.autoPipeline && this.pipeliner) {
|
|
5579
|
+
await this.pipeliner.setex(k, ttlSec, stored);
|
|
5580
|
+
} else {
|
|
5581
|
+
await client.setex(k, ttlSec, stored);
|
|
5582
|
+
}
|
|
5583
|
+
}
|
|
5584
|
+
this.cb.onSuccess();
|
|
5585
|
+
} catch (err) {
|
|
5586
|
+
this.cb.onFailure();
|
|
5587
|
+
this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
|
|
3429
5588
|
}
|
|
3430
|
-
this.cb.onSuccess();
|
|
3431
|
-
} catch (err) {
|
|
3432
|
-
this.cb.onFailure();
|
|
3433
|
-
this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
|
|
3434
5589
|
}
|
|
5590
|
+
void this.publishInvalidation("del", k);
|
|
5591
|
+
} catch (err) {
|
|
5592
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
5593
|
+
span.recordException?.(err);
|
|
5594
|
+
throw err;
|
|
5595
|
+
} finally {
|
|
5596
|
+
span.end();
|
|
3435
5597
|
}
|
|
3436
|
-
void this.publishInvalidation("del", k);
|
|
3437
|
-
span.end();
|
|
3438
5598
|
}
|
|
3439
5599
|
/**
|
|
3440
5600
|
* Register tags for a cache key in the in-process index and (if Redis is enabled) in
|
|
@@ -3476,36 +5636,47 @@ var CacheService = class _CacheService {
|
|
|
3476
5636
|
async delete(cacheKey) {
|
|
3477
5637
|
const span = this._startSpan("tricache.delete");
|
|
3478
5638
|
if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
3479
|
-
|
|
3480
|
-
|
|
3481
|
-
|
|
3482
|
-
|
|
3483
|
-
|
|
3484
|
-
|
|
3485
|
-
|
|
3486
|
-
|
|
3487
|
-
|
|
3488
|
-
|
|
3489
|
-
|
|
3490
|
-
|
|
3491
|
-
|
|
3492
|
-
|
|
3493
|
-
|
|
3494
|
-
|
|
3495
|
-
|
|
3496
|
-
|
|
3497
|
-
|
|
3498
|
-
|
|
3499
|
-
|
|
5639
|
+
try {
|
|
5640
|
+
const isPattern = cacheKey.includes("*");
|
|
5641
|
+
const k = this.nk(cacheKey);
|
|
5642
|
+
this.counters.deletes++;
|
|
5643
|
+
if (isPattern) {
|
|
5644
|
+
this.l1.deletePattern(k);
|
|
5645
|
+
} else {
|
|
5646
|
+
this.l1.delete(k);
|
|
5647
|
+
setImmediate(() => {
|
|
5648
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
5649
|
+
});
|
|
5650
|
+
this._cascadeDependencies(k);
|
|
5651
|
+
for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
|
|
5652
|
+
}
|
|
5653
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5654
|
+
try {
|
|
5655
|
+
const client = await this.getRedis();
|
|
5656
|
+
if (isPattern) {
|
|
5657
|
+
const keys = await this._scanKeys(client, k);
|
|
5658
|
+
if (keys.length > 0) await client.del(...keys);
|
|
5659
|
+
} else {
|
|
5660
|
+
if (this.opts.autoPipeline && this.pipeliner) {
|
|
5661
|
+
await this.pipeliner.del(k);
|
|
5662
|
+
} else {
|
|
5663
|
+
await client.del(k);
|
|
5664
|
+
}
|
|
5665
|
+
}
|
|
5666
|
+
this.cb.onSuccess();
|
|
5667
|
+
} catch (err) {
|
|
5668
|
+
this.cb.onFailure();
|
|
5669
|
+
this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
|
|
3500
5670
|
}
|
|
3501
|
-
this.cb.onSuccess();
|
|
3502
|
-
} catch (err) {
|
|
3503
|
-
this.cb.onFailure();
|
|
3504
|
-
this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
|
|
3505
5671
|
}
|
|
5672
|
+
void this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
|
|
5673
|
+
} catch (err) {
|
|
5674
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
5675
|
+
span.recordException?.(err);
|
|
5676
|
+
throw err;
|
|
5677
|
+
} finally {
|
|
5678
|
+
span.end();
|
|
3506
5679
|
}
|
|
3507
|
-
void this.publishInvalidation(isPattern ? "del-glob" : "del", k);
|
|
3508
|
-
span.end();
|
|
3509
5680
|
}
|
|
3510
5681
|
// ── Counter (distributed rate limiting) ──────────────────────────────────
|
|
3511
5682
|
/**
|
|
@@ -3566,31 +5737,44 @@ var CacheService = class _CacheService {
|
|
|
3566
5737
|
* await cache.clear('user:abc'); // flush all keys for one user
|
|
3567
5738
|
*/
|
|
3568
5739
|
async clear(prefix) {
|
|
3569
|
-
this.
|
|
3570
|
-
|
|
3571
|
-
|
|
3572
|
-
this.
|
|
3573
|
-
|
|
3574
|
-
|
|
3575
|
-
|
|
3576
|
-
|
|
3577
|
-
|
|
3578
|
-
|
|
3579
|
-
|
|
3580
|
-
|
|
3581
|
-
|
|
3582
|
-
const client = await this.getRedis();
|
|
3583
|
-
const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
|
|
3584
|
-
const keys = await this._scanKeys(client, pattern);
|
|
3585
|
-
if (keys.length > 0) await client.del(...keys);
|
|
3586
|
-
} catch (err) {
|
|
3587
|
-
this.logger.debug("clear: Redis unavailable", { error: err.message });
|
|
5740
|
+
const span = this._startSpan("tricache.clear");
|
|
5741
|
+
if (this.opts.tracer) span.setAttribute("cache.prefix", prefix || "*");
|
|
5742
|
+
try {
|
|
5743
|
+
this.counters.deletes++;
|
|
5744
|
+
const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
|
|
5745
|
+
if (k) {
|
|
5746
|
+
this.l1.deletePattern(k);
|
|
5747
|
+
} else {
|
|
5748
|
+
this.l1.clear();
|
|
5749
|
+
if (!this._diskDisabled) this.disk.clear();
|
|
5750
|
+
this._l1Counters.clear();
|
|
5751
|
+
this.tagIndex.clear();
|
|
5752
|
+
this.tagVersions.clear();
|
|
3588
5753
|
}
|
|
5754
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5755
|
+
try {
|
|
5756
|
+
const client = await this.getRedis();
|
|
5757
|
+
const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
|
|
5758
|
+
const keys = await this._scanKeys(client, pattern);
|
|
5759
|
+
if (keys.length > 0) await client.del(...keys);
|
|
5760
|
+
} catch (err) {
|
|
5761
|
+
this.logger.debug("clear: Redis unavailable", { error: err.message });
|
|
5762
|
+
}
|
|
5763
|
+
}
|
|
5764
|
+
void this.publishInvalidation(
|
|
5765
|
+
"del-glob",
|
|
5766
|
+
k ?? (this._namespace ? `${this._namespace}:*` : "*"),
|
|
5767
|
+
void 0,
|
|
5768
|
+
false,
|
|
5769
|
+
true
|
|
5770
|
+
);
|
|
5771
|
+
} catch (err) {
|
|
5772
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
5773
|
+
span.recordException?.(err);
|
|
5774
|
+
throw err;
|
|
5775
|
+
} finally {
|
|
5776
|
+
span.end();
|
|
3589
5777
|
}
|
|
3590
|
-
void this.publishInvalidation(
|
|
3591
|
-
"del-glob",
|
|
3592
|
-
k ?? (this._namespace ? `${this._namespace}:*` : "*")
|
|
3593
|
-
);
|
|
3594
5778
|
}
|
|
3595
5779
|
/**
|
|
3596
5780
|
* Evict L1 entries that violate the current category or global capacity limits.
|
|
@@ -3721,7 +5905,7 @@ var CacheService = class _CacheService {
|
|
|
3721
5905
|
const now = Date.now();
|
|
3722
5906
|
if (entry.expiresAt <= now) return null;
|
|
3723
5907
|
if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
|
|
3724
|
-
return entry.value !== void 0 ? entry.value :
|
|
5908
|
+
return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
3725
5909
|
}
|
|
3726
5910
|
/**
|
|
3727
5911
|
* Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
|
|
@@ -3741,8 +5925,12 @@ var CacheService = class _CacheService {
|
|
|
3741
5925
|
if (this.opts.frozen) deepFreeze(val);
|
|
3742
5926
|
return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
|
|
3743
5927
|
}
|
|
3744
|
-
if (!this._diskDisabled) {
|
|
5928
|
+
if (!this._diskDisabled && this.watchdog.isDiskAllowed()) {
|
|
5929
|
+
const diskStart = performance.now();
|
|
3745
5930
|
const diskHit = this.disk.load(k);
|
|
5931
|
+
const diskElapsed = performance.now() - diskStart;
|
|
5932
|
+
this.watchdog.recordDisk(diskElapsed);
|
|
5933
|
+
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
3746
5934
|
if (diskHit !== null) {
|
|
3747
5935
|
const promoted = this.l1.importEntries(
|
|
3748
5936
|
[{ key: k, entry: diskHit }],
|
|
@@ -3763,7 +5951,10 @@ var CacheService = class _CacheService {
|
|
|
3763
5951
|
if (!this._redisDisabled && !this.cb.isOpen) {
|
|
3764
5952
|
try {
|
|
3765
5953
|
const client = await this.getRedis();
|
|
5954
|
+
const redisStart = performance.now();
|
|
3766
5955
|
const raw = await client.get(k);
|
|
5956
|
+
const redisElapsed = performance.now() - redisStart;
|
|
5957
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
3767
5958
|
if (raw !== null) {
|
|
3768
5959
|
const parsed = await this._decryptAndDeserialize(raw);
|
|
3769
5960
|
this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
|
|
@@ -3790,90 +5981,129 @@ var CacheService = class _CacheService {
|
|
|
3790
5981
|
* `(key) => number` so heterogeneous TTLs can be batched in one call.
|
|
3791
5982
|
*/
|
|
3792
5983
|
async mget(keys, fetchFn, ttl = 300, priority) {
|
|
3793
|
-
const
|
|
3794
|
-
|
|
3795
|
-
|
|
3796
|
-
for (let i = 0; i < keys.length; i++) {
|
|
3797
|
-
const k = this.nk(keys[i]);
|
|
3798
|
-
const entry = this.l1.getEntry(k);
|
|
3799
|
-
if (entry && entry.expiresAt > Date.now()) {
|
|
3800
|
-
result[i] = entry.value !== void 0 ? entry.value : unpack3(entry.data);
|
|
3801
|
-
this.counters.l1Hits++;
|
|
3802
|
-
} else {
|
|
3803
|
-
missIndexes.push(i);
|
|
3804
|
-
missKeys.push(keys[i]);
|
|
3805
|
-
}
|
|
5984
|
+
const span = this._startSpan("tricache.mget");
|
|
5985
|
+
if (this.opts.tracer) {
|
|
5986
|
+
span.setAttribute("cache.batch.size", keys.length);
|
|
3806
5987
|
}
|
|
3807
|
-
|
|
3808
|
-
|
|
3809
|
-
|
|
3810
|
-
|
|
3811
|
-
|
|
3812
|
-
const
|
|
3813
|
-
|
|
3814
|
-
|
|
3815
|
-
|
|
3816
|
-
|
|
3817
|
-
|
|
3818
|
-
|
|
3819
|
-
|
|
3820
|
-
|
|
3821
|
-
|
|
3822
|
-
|
|
3823
|
-
|
|
3824
|
-
|
|
3825
|
-
|
|
3826
|
-
|
|
3827
|
-
|
|
5988
|
+
try {
|
|
5989
|
+
const result = Array.from({ length: keys.length });
|
|
5990
|
+
const missIndexes = [];
|
|
5991
|
+
const missKeys = [];
|
|
5992
|
+
for (let i = 0; i < keys.length; i++) {
|
|
5993
|
+
const k = this.nk(keys[i]);
|
|
5994
|
+
const entry = this.l1.getEntry(k);
|
|
5995
|
+
if (entry && entry.expiresAt > Date.now()) {
|
|
5996
|
+
result[i] = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
5997
|
+
this.counters.l1Hits++;
|
|
5998
|
+
} else {
|
|
5999
|
+
missIndexes.push(i);
|
|
6000
|
+
missKeys.push(keys[i]);
|
|
6001
|
+
}
|
|
6002
|
+
}
|
|
6003
|
+
if (missKeys.length === 0) {
|
|
6004
|
+
if (this.opts.tracer) {
|
|
6005
|
+
span.setAttribute("cache.hits", keys.length);
|
|
6006
|
+
span.setAttribute("cache.misses", 0);
|
|
6007
|
+
span.setAttribute("cache.l1_hits", keys.length);
|
|
6008
|
+
span.setAttribute("cache.l2_hits", 0);
|
|
6009
|
+
}
|
|
6010
|
+
return result;
|
|
6011
|
+
}
|
|
6012
|
+
let l2HitCount = 0;
|
|
6013
|
+
if (!this._redisDisabled) {
|
|
6014
|
+
try {
|
|
6015
|
+
const client = await this.getRedis();
|
|
6016
|
+
const nsKeys = missKeys.map((k) => this.nk(k));
|
|
6017
|
+
const pipeline = client.multi();
|
|
6018
|
+
for (const nk of nsKeys) pipeline.get(nk);
|
|
6019
|
+
const redisStart = performance.now();
|
|
6020
|
+
const raws = await pipeline.exec();
|
|
6021
|
+
const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
|
|
6022
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
6023
|
+
this.cb.onSuccess();
|
|
6024
|
+
for (let j = 0; j < missKeys.length; j++) {
|
|
6025
|
+
const raw = raws[j] ? raws[j][1] : null;
|
|
6026
|
+
const idx = missIndexes[j];
|
|
6027
|
+
if (raw) {
|
|
6028
|
+
const parsed = await this._decryptAndDeserialize(raw);
|
|
6029
|
+
const k = nsKeys[j];
|
|
6030
|
+
const p = priority ?? inferPriority(missKeys[j]);
|
|
6031
|
+
this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
|
|
6032
|
+
this.counters.l2Hits++;
|
|
6033
|
+
l2HitCount++;
|
|
6034
|
+
result[idx] = parsed;
|
|
6035
|
+
missIndexes[j] = -1;
|
|
6036
|
+
missKeys[j] = "";
|
|
6037
|
+
}
|
|
3828
6038
|
}
|
|
6039
|
+
const remainingIdx = missIndexes.filter((i) => i >= 0);
|
|
6040
|
+
const remainingKeys = missKeys.filter((k) => k !== "");
|
|
6041
|
+
missIndexes.length = 0;
|
|
6042
|
+
missKeys.length = 0;
|
|
6043
|
+
missIndexes.push(...remainingIdx);
|
|
6044
|
+
missKeys.push(...remainingKeys);
|
|
6045
|
+
} catch (err) {
|
|
6046
|
+
this.cb.onFailure();
|
|
6047
|
+
this.logger.debug("mget: Redis unavailable, continuing to disk/fetch", { error: err.message });
|
|
3829
6048
|
}
|
|
3830
|
-
const remainingIdx = missIndexes.filter((i) => i >= 0);
|
|
3831
|
-
const remainingKeys = missKeys.filter((k) => k !== "");
|
|
3832
|
-
missIndexes.length = 0;
|
|
3833
|
-
missKeys.length = 0;
|
|
3834
|
-
missIndexes.push(...remainingIdx);
|
|
3835
|
-
missKeys.push(...remainingKeys);
|
|
3836
|
-
if (missKeys.length === 0) return result;
|
|
3837
|
-
} catch (err) {
|
|
3838
|
-
this.cb.onFailure();
|
|
3839
|
-
this.logger.debug("mget: Redis unavailable, continuing to disk/fetch", { error: err.message });
|
|
3840
6049
|
}
|
|
3841
|
-
|
|
3842
|
-
|
|
3843
|
-
|
|
3844
|
-
|
|
3845
|
-
|
|
3846
|
-
|
|
3847
|
-
const
|
|
3848
|
-
|
|
3849
|
-
|
|
3850
|
-
)
|
|
3851
|
-
|
|
3852
|
-
|
|
3853
|
-
|
|
3854
|
-
|
|
3855
|
-
|
|
3856
|
-
|
|
3857
|
-
|
|
6050
|
+
if (!this._diskDisabled && missKeys.length > 0) {
|
|
6051
|
+
for (let j = missKeys.length - 1; j >= 0; j--) {
|
|
6052
|
+
if (!this.watchdog.isDiskAllowed()) continue;
|
|
6053
|
+
const k = this.nk(missKeys[j]);
|
|
6054
|
+
const diskStart = performance.now();
|
|
6055
|
+
const diskHit = this.disk.load(k);
|
|
6056
|
+
const diskElapsed = performance.now() - diskStart;
|
|
6057
|
+
this.watchdog.recordDisk(diskElapsed);
|
|
6058
|
+
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
6059
|
+
if (diskHit !== null) {
|
|
6060
|
+
const promoted = this.l1.importEntries(
|
|
6061
|
+
[{ key: k, entry: diskHit }],
|
|
6062
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
6063
|
+
);
|
|
6064
|
+
if (promoted > 0) {
|
|
6065
|
+
const l1Check = this.l1.get(k);
|
|
6066
|
+
if (l1Check !== null) {
|
|
6067
|
+
this.counters.diskHits++;
|
|
6068
|
+
result[missIndexes[j]] = l1Check.value;
|
|
6069
|
+
missIndexes.splice(j, 1);
|
|
6070
|
+
missKeys.splice(j, 1);
|
|
6071
|
+
}
|
|
3858
6072
|
}
|
|
3859
6073
|
}
|
|
3860
6074
|
}
|
|
3861
6075
|
}
|
|
3862
|
-
if (missKeys.length
|
|
3863
|
-
|
|
3864
|
-
|
|
3865
|
-
|
|
3866
|
-
|
|
3867
|
-
|
|
3868
|
-
|
|
3869
|
-
|
|
3870
|
-
|
|
3871
|
-
|
|
3872
|
-
|
|
6076
|
+
if (missKeys.length > 0) {
|
|
6077
|
+
this.counters.fetches++;
|
|
6078
|
+
const fetched = await fetchFn(missKeys);
|
|
6079
|
+
const setPromises = [];
|
|
6080
|
+
for (let j = 0; j < missKeys.length; j++) {
|
|
6081
|
+
const v = fetched[missKeys[j]];
|
|
6082
|
+
result[missIndexes[j]] = v;
|
|
6083
|
+
if (v !== void 0) {
|
|
6084
|
+
const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
|
|
6085
|
+
setPromises.push(this.set(missKeys[j], v, resolvedTtl, priority));
|
|
6086
|
+
}
|
|
3873
6087
|
}
|
|
6088
|
+
if (setPromises.length > 0) {
|
|
6089
|
+
await Promise.all(setPromises);
|
|
6090
|
+
}
|
|
6091
|
+
}
|
|
6092
|
+
if (this.opts.tracer) {
|
|
6093
|
+
const finalMisses = missKeys.length;
|
|
6094
|
+
const totalHits = keys.length - finalMisses;
|
|
6095
|
+
span.setAttribute("cache.hits", totalHits);
|
|
6096
|
+
span.setAttribute("cache.misses", finalMisses);
|
|
6097
|
+
span.setAttribute("cache.l2_hits", l2HitCount);
|
|
3874
6098
|
}
|
|
6099
|
+
return result;
|
|
6100
|
+
} catch (err) {
|
|
6101
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6102
|
+
span.recordException?.(err);
|
|
6103
|
+
throw err;
|
|
6104
|
+
} finally {
|
|
6105
|
+
span.end();
|
|
3875
6106
|
}
|
|
3876
|
-
return result;
|
|
3877
6107
|
}
|
|
3878
6108
|
/**
|
|
3879
6109
|
* Returns a Promise that resolves once the cache is fully initialised and any
|
|
@@ -3900,12 +6130,24 @@ var CacheService = class _CacheService {
|
|
|
3900
6130
|
* });
|
|
3901
6131
|
*/
|
|
3902
6132
|
async mset(entries) {
|
|
6133
|
+
const span = this._startSpan("tricache.mset");
|
|
3903
6134
|
const keys = Object.keys(entries);
|
|
3904
|
-
|
|
3905
|
-
|
|
3906
|
-
|
|
3907
|
-
|
|
3908
|
-
|
|
6135
|
+
if (this.opts.tracer) {
|
|
6136
|
+
span.setAttribute("cache.batch.size", keys.length);
|
|
6137
|
+
}
|
|
6138
|
+
try {
|
|
6139
|
+
await Promise.all(keys.map((key) => {
|
|
6140
|
+
const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
|
|
6141
|
+
const hasOpts = tags?.length || dependsOn?.length;
|
|
6142
|
+
return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
|
|
6143
|
+
}));
|
|
6144
|
+
} catch (err) {
|
|
6145
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6146
|
+
span.recordException?.(err);
|
|
6147
|
+
throw err;
|
|
6148
|
+
} finally {
|
|
6149
|
+
span.end();
|
|
6150
|
+
}
|
|
3909
6151
|
}
|
|
3910
6152
|
/**
|
|
3911
6153
|
* Batch delete — delete multiple exact keys in a single call.
|
|
@@ -3915,7 +6157,19 @@ var CacheService = class _CacheService {
|
|
|
3915
6157
|
* await cache.mdel(['user:1', 'user:2', 'user:3']);
|
|
3916
6158
|
*/
|
|
3917
6159
|
async mdel(keys) {
|
|
3918
|
-
|
|
6160
|
+
const span = this._startSpan("tricache.mdel");
|
|
6161
|
+
if (this.opts.tracer) {
|
|
6162
|
+
span.setAttribute("cache.batch.size", keys.length);
|
|
6163
|
+
}
|
|
6164
|
+
try {
|
|
6165
|
+
await Promise.all(keys.map((k) => this.delete(k)));
|
|
6166
|
+
} catch (err) {
|
|
6167
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6168
|
+
span.recordException?.(err);
|
|
6169
|
+
throw err;
|
|
6170
|
+
} finally {
|
|
6171
|
+
span.end();
|
|
6172
|
+
}
|
|
3919
6173
|
}
|
|
3920
6174
|
/**
|
|
3921
6175
|
* Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
|
|
@@ -3944,7 +6198,6 @@ var CacheService = class _CacheService {
|
|
|
3944
6198
|
const results = await pl.exec();
|
|
3945
6199
|
this.cb.onSuccess();
|
|
3946
6200
|
let loaded = 0;
|
|
3947
|
-
const now = Date.now();
|
|
3948
6201
|
for (let i = 0; i < matchedKeys.length; i++) {
|
|
3949
6202
|
const [err, raw] = results[i];
|
|
3950
6203
|
if (err || raw == null) continue;
|
|
@@ -3956,7 +6209,6 @@ var CacheService = class _CacheService {
|
|
|
3956
6209
|
} catch {
|
|
3957
6210
|
}
|
|
3958
6211
|
}
|
|
3959
|
-
void now;
|
|
3960
6212
|
this.logger.info("warmFromL2 complete", {
|
|
3961
6213
|
pattern,
|
|
3962
6214
|
matched: matchedKeys.length,
|
|
@@ -3978,45 +6230,58 @@ var CacheService = class _CacheService {
|
|
|
3978
6230
|
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
3979
6231
|
*/
|
|
3980
6232
|
async invalidateTag(tag) {
|
|
3981
|
-
|
|
3982
|
-
|
|
6233
|
+
const span = this._startSpan("tricache.invalidate_tag");
|
|
6234
|
+
if (this.opts.tracer) {
|
|
6235
|
+
span.setAttribute("cache.tag", tag);
|
|
6236
|
+
span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
|
|
6237
|
+
}
|
|
6238
|
+
try {
|
|
6239
|
+
if (this.opts.tagStrategy === "generational") {
|
|
6240
|
+
let newVer = 1;
|
|
6241
|
+
if (!this._redisDisabled) {
|
|
6242
|
+
try {
|
|
6243
|
+
const client = await this.getRedis();
|
|
6244
|
+
newVer = await client.incr(this.nk(`tag_ver:${tag}`));
|
|
6245
|
+
} catch (err) {
|
|
6246
|
+
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
6247
|
+
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
6248
|
+
newVer = current + 1;
|
|
6249
|
+
}
|
|
6250
|
+
} else {
|
|
6251
|
+
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
6252
|
+
newVer = current + 1;
|
|
6253
|
+
}
|
|
6254
|
+
this._setLocalTagVersion(tag, newVer, Date.now());
|
|
6255
|
+
void this.publishInvalidation("tag_incr", tag, newVer, false, true);
|
|
6256
|
+
return;
|
|
6257
|
+
}
|
|
6258
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
6259
|
+
const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
|
|
6260
|
+
for (const k of members) {
|
|
6261
|
+
this.l1.delete(k);
|
|
6262
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
6263
|
+
}
|
|
6264
|
+
this.tagIndex.delete(tagKey);
|
|
3983
6265
|
if (!this._redisDisabled) {
|
|
3984
6266
|
try {
|
|
3985
6267
|
const client = await this.getRedis();
|
|
3986
|
-
|
|
6268
|
+
const redisMembers = await client.smembers(tagKey);
|
|
6269
|
+
const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
|
|
6270
|
+
if (toDelete.length > 0) {
|
|
6271
|
+
await client.del(...toDelete, tagKey);
|
|
6272
|
+
} else {
|
|
6273
|
+
await client.del(tagKey);
|
|
6274
|
+
}
|
|
3987
6275
|
} catch (err) {
|
|
3988
6276
|
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
3989
|
-
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
3990
|
-
newVer = current + 1;
|
|
3991
|
-
}
|
|
3992
|
-
} else {
|
|
3993
|
-
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
3994
|
-
newVer = current + 1;
|
|
3995
|
-
}
|
|
3996
|
-
this._setLocalTagVersion(tag, newVer, Date.now());
|
|
3997
|
-
void this.publishInvalidation("tag_incr", tag, newVer);
|
|
3998
|
-
return;
|
|
3999
|
-
}
|
|
4000
|
-
const tagKey = this.nk(`_tag_:${tag}`);
|
|
4001
|
-
const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
|
|
4002
|
-
for (const k of members) {
|
|
4003
|
-
this.l1.delete(k);
|
|
4004
|
-
if (!this._diskDisabled) this.disk.delete(k);
|
|
4005
|
-
}
|
|
4006
|
-
this.tagIndex.delete(tagKey);
|
|
4007
|
-
if (!this._redisDisabled) {
|
|
4008
|
-
try {
|
|
4009
|
-
const client = await this.getRedis();
|
|
4010
|
-
const redisMembers = await client.smembers(tagKey);
|
|
4011
|
-
const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
|
|
4012
|
-
if (toDelete.length > 0) {
|
|
4013
|
-
await client.del(...toDelete, tagKey);
|
|
4014
|
-
} else {
|
|
4015
|
-
await client.del(tagKey);
|
|
4016
6277
|
}
|
|
4017
|
-
} catch (err) {
|
|
4018
|
-
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
4019
6278
|
}
|
|
6279
|
+
} catch (err) {
|
|
6280
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6281
|
+
span.recordException?.(err);
|
|
6282
|
+
throw err;
|
|
6283
|
+
} finally {
|
|
6284
|
+
span.end();
|
|
4020
6285
|
}
|
|
4021
6286
|
}
|
|
4022
6287
|
/**
|
|
@@ -4049,7 +6314,7 @@ var CacheService = class _CacheService {
|
|
|
4049
6314
|
const [err, newVer] = results[i] ?? [null, null];
|
|
4050
6315
|
const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
|
|
4051
6316
|
this._setLocalTagVersion(tags[i], ver, now);
|
|
4052
|
-
void this.publishInvalidation("tag_incr", tags[i], ver);
|
|
6317
|
+
void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
|
|
4053
6318
|
}
|
|
4054
6319
|
return;
|
|
4055
6320
|
} catch (err) {
|
|
@@ -4059,7 +6324,7 @@ var CacheService = class _CacheService {
|
|
|
4059
6324
|
for (const tag of tags) {
|
|
4060
6325
|
const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
4061
6326
|
this._setLocalTagVersion(tag, ver, now);
|
|
4062
|
-
void this.publishInvalidation("tag_incr", tag, ver);
|
|
6327
|
+
void this.publishInvalidation("tag_incr", tag, ver, false, true);
|
|
4063
6328
|
}
|
|
4064
6329
|
return;
|
|
4065
6330
|
}
|
|
@@ -4130,6 +6395,60 @@ var CacheService = class _CacheService {
|
|
|
4130
6395
|
}
|
|
4131
6396
|
return { l1, disk, l2 };
|
|
4132
6397
|
}
|
|
6398
|
+
/**
|
|
6399
|
+
* Health and readiness diagnostics for container orchestrators (e.g. Kubernetes, ECS, Nomad).
|
|
6400
|
+
*
|
|
6401
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
6402
|
+
* ⚠️ CRITICAL CONTAINER PROBE SEMANTICS (Liveness vs. Readiness):
|
|
6403
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
6404
|
+
* ❌ NEVER bind `degraded` checks or `cache.health()` to your Liveness Probe (/livez, /healthz).
|
|
6405
|
+
* If an SRE hooks degraded status into liveness, a storage-starved or EBS-throttled pod
|
|
6406
|
+
* will be killed by the kubelet, triggering a cluster-wide cascading restart shockwave.
|
|
6407
|
+
* Liveness probes must only check that the event loop / process is alive.
|
|
6408
|
+
*
|
|
6409
|
+
* ✅ BIND degraded checks strictly to your Readiness Probe (/ready, /readyz).
|
|
6410
|
+
* A degraded cache (e.g. EBS latency spike, quota watermark pruning, or open Redis circuit)
|
|
6411
|
+
* can shed traffic at the ingress load balancer while the Node.js process remains
|
|
6412
|
+
* alive to drain in-flight promises and heal its local storage.
|
|
6413
|
+
*
|
|
6414
|
+
* By default, `healthy` remains `true` even when degraded (graceful local degradation).
|
|
6415
|
+
* Set `failReadinessOnDegraded: true` in CacheOptions if you want your Readiness probe
|
|
6416
|
+
* to route ingress traffic away while degraded.
|
|
6417
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
6418
|
+
*/
|
|
6419
|
+
health() {
|
|
6420
|
+
const watchdogTel = this.watchdog.getTelemetry();
|
|
6421
|
+
const diskPruning = !this._diskDisabled && this.disk.isPruning;
|
|
6422
|
+
const diskLowSpace = !this._diskDisabled && this.disk.hostVolumeLowSpace;
|
|
6423
|
+
const circuitOpen = this.cb.isOpen;
|
|
6424
|
+
const latencyBypass = watchdogTel.bypassActive;
|
|
6425
|
+
const degraded = circuitOpen || latencyBypass || diskPruning || diskLowSpace;
|
|
6426
|
+
const healthy = this.opts.failReadinessOnDegraded ? !degraded : true;
|
|
6427
|
+
const reasons = [];
|
|
6428
|
+
if (circuitOpen) reasons.push("redis_circuit_breaker_open");
|
|
6429
|
+
if (latencyBypass) reasons.push(`disk_latency_bypass_stage_${watchdogTel.bypassStage}`);
|
|
6430
|
+
if (diskPruning) reasons.push("disk_quota_watermark_pruning_active");
|
|
6431
|
+
if (diskLowSpace) reasons.push("disk_host_volume_low_space");
|
|
6432
|
+
return {
|
|
6433
|
+
healthy,
|
|
6434
|
+
degraded,
|
|
6435
|
+
reasons,
|
|
6436
|
+
details: {
|
|
6437
|
+
redisConnected: !circuitOpen && !this._redisDisabled,
|
|
6438
|
+
circuitBreakerState: this.cb.currentState,
|
|
6439
|
+
diskPruningActive: diskPruning,
|
|
6440
|
+
diskHostVolumeLowSpace: diskLowSpace,
|
|
6441
|
+
watchdog: watchdogTel
|
|
6442
|
+
}
|
|
6443
|
+
};
|
|
6444
|
+
}
|
|
6445
|
+
/**
|
|
6446
|
+
* Direct access to the internal tier latency watchdog instance.
|
|
6447
|
+
* Used for diagnostics, canary probes, and control-loop tuning.
|
|
6448
|
+
*/
|
|
6449
|
+
getLatencyWatchdog() {
|
|
6450
|
+
return this.watchdog;
|
|
6451
|
+
}
|
|
4133
6452
|
/**
|
|
4134
6453
|
* Export all live L1 entries to Redis via a single pipeline.
|
|
4135
6454
|
* Useful for warming a new Redis instance or for zero-downtime failover.
|
|
@@ -4223,8 +6542,9 @@ var CacheService = class _CacheService {
|
|
|
4223
6542
|
const deadline = Date.now() + acquireTimeout;
|
|
4224
6543
|
let acquired = false;
|
|
4225
6544
|
if (!this._redisDisabled) {
|
|
6545
|
+
let client = null;
|
|
4226
6546
|
try {
|
|
4227
|
-
|
|
6547
|
+
client = await this.getRedis();
|
|
4228
6548
|
while (Date.now() <= deadline) {
|
|
4229
6549
|
const res = await client.set(lockKey, token, "EX", ttlSeconds, "NX");
|
|
4230
6550
|
if (res === "OK") {
|
|
@@ -4238,6 +6558,15 @@ var CacheService = class _CacheService {
|
|
|
4238
6558
|
if (!acquired) {
|
|
4239
6559
|
throw new Error(`Failed to acquire lock for resource "${resourceKey}" within ${acquireTimeout}ms`);
|
|
4240
6560
|
}
|
|
6561
|
+
} catch (err) {
|
|
6562
|
+
if (err.message.startsWith("Failed to acquire lock")) throw err;
|
|
6563
|
+
this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
|
|
6564
|
+
resourceKey,
|
|
6565
|
+
error: err.message
|
|
6566
|
+
});
|
|
6567
|
+
client = null;
|
|
6568
|
+
}
|
|
6569
|
+
if (client !== null && acquired) {
|
|
4241
6570
|
try {
|
|
4242
6571
|
return await fn();
|
|
4243
6572
|
} finally {
|
|
@@ -4253,12 +6582,6 @@ var CacheService = class _CacheService {
|
|
|
4253
6582
|
} catch {
|
|
4254
6583
|
}
|
|
4255
6584
|
}
|
|
4256
|
-
} catch (err) {
|
|
4257
|
-
if (err.message.startsWith("Failed to acquire lock")) throw err;
|
|
4258
|
-
this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
|
|
4259
|
-
resourceKey,
|
|
4260
|
-
error: err.message
|
|
4261
|
-
});
|
|
4262
6585
|
}
|
|
4263
6586
|
}
|
|
4264
6587
|
let unlock = () => {
|
|
@@ -4373,7 +6696,7 @@ var CacheService = class _CacheService {
|
|
|
4373
6696
|
if (visited.has(dep)) continue;
|
|
4374
6697
|
this.l1.delete(dep);
|
|
4375
6698
|
if (!this._diskDisabled) this.disk.delete(dep);
|
|
4376
|
-
void this.publishInvalidation("del", dep);
|
|
6699
|
+
void this.publishInvalidation("del", dep, void 0, false, true);
|
|
4377
6700
|
this.logger.debug("Dependency cascade: invalidated dependent key", {
|
|
4378
6701
|
trigger: deletedKey.slice(0, 60),
|
|
4379
6702
|
dependent: dep.slice(0, 60)
|
|
@@ -4438,12 +6761,36 @@ var CacheService = class _CacheService {
|
|
|
4438
6761
|
evictions: c.oomEvictions,
|
|
4439
6762
|
lastTriggeredAt: c.oomLastAt
|
|
4440
6763
|
},
|
|
6764
|
+
...this.opts.remoteSnapshot && {
|
|
6765
|
+
remoteSnapshot: {
|
|
6766
|
+
enabled: true,
|
|
6767
|
+
uploads: c.remoteSnapshotUploads,
|
|
6768
|
+
downloads: c.remoteSnapshotDownloads,
|
|
6769
|
+
errors: c.remoteSnapshotErrors,
|
|
6770
|
+
lastUploadedAt: c.remoteSnapshotLastUploadedAt,
|
|
6771
|
+
lastDownloadedAt: c.remoteSnapshotLastDownloadedAt
|
|
6772
|
+
}
|
|
6773
|
+
},
|
|
6774
|
+
...this.opts.crossRegion && {
|
|
6775
|
+
crossRegion: {
|
|
6776
|
+
enabled: true,
|
|
6777
|
+
currentRegion: this.opts.crossRegion.currentRegion,
|
|
6778
|
+
sent: c.crossRegionSent,
|
|
6779
|
+
received: c.crossRegionReceived,
|
|
6780
|
+
deduplicated: c.crossRegionDeduplicated,
|
|
6781
|
+
errors: c.crossRegionErrors
|
|
6782
|
+
}
|
|
6783
|
+
},
|
|
4441
6784
|
l1: {
|
|
4442
6785
|
entries: l1s.entries,
|
|
4443
6786
|
sizeBytes: this.l1.memoryUsage,
|
|
4444
6787
|
maxBytes: this.opts.l1MaxBytes
|
|
4445
6788
|
},
|
|
4446
|
-
disk: {
|
|
6789
|
+
disk: {
|
|
6790
|
+
...this.disk.stats,
|
|
6791
|
+
disabled: this._diskDisabled,
|
|
6792
|
+
latencyWatchdog: this.watchdog.getTelemetry()
|
|
6793
|
+
},
|
|
4447
6794
|
...this.latencyTracker && {
|
|
4448
6795
|
adaptiveTtl: {
|
|
4449
6796
|
enabled: true,
|
|
@@ -4456,9 +6803,16 @@ var CacheService = class _CacheService {
|
|
|
4456
6803
|
this.opts.adaptiveTtlMaxMs
|
|
4457
6804
|
)
|
|
4458
6805
|
}
|
|
6806
|
+
},
|
|
6807
|
+
...this.pipeliner && {
|
|
6808
|
+
pipelining: this.pipeliner.stats
|
|
4459
6809
|
}
|
|
4460
6810
|
};
|
|
4461
6811
|
}
|
|
6812
|
+
/** Return auto-pipelining metrics, or null if pipelining is disabled. */
|
|
6813
|
+
getPipelinerStats() {
|
|
6814
|
+
return this.pipeliner ? this.pipeliner.stats : null;
|
|
6815
|
+
}
|
|
4462
6816
|
/**
|
|
4463
6817
|
* Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
|
|
4464
6818
|
* Paste the result into your `/metrics` endpoint.
|
|
@@ -4498,6 +6852,18 @@ var CacheService = class _CacheService {
|
|
|
4498
6852
|
gauge("l1_entries", m.l1.entries, "Current L1 entry count");
|
|
4499
6853
|
gauge("l1_size_bytes", m.l1.sizeBytes, "Current L1 used bytes");
|
|
4500
6854
|
gauge("disk_files", m.disk.files, "Current L1.5 disk file count");
|
|
6855
|
+
if (m.disk.latencyWatchdog) {
|
|
6856
|
+
gauge("disk_latency_bypass_stage", m.disk.latencyWatchdog.bypassStage, "Disk latency watchdog bypass stage (0: normal, 1: 25%, 2: 75%, 3: 100%)");
|
|
6857
|
+
gauge("disk_p95_ms", m.disk.latencyWatchdog.diskP95Ms, "Disk read p95 latency in ms");
|
|
6858
|
+
gauge("redis_p95_ms", m.disk.latencyWatchdog.redisP95Ms, "Redis read p95 latency in ms");
|
|
6859
|
+
counter("disk_bypassed_events", m.disk.latencyWatchdog.bypassedTotal, "Total disk bypass activation events");
|
|
6860
|
+
}
|
|
6861
|
+
if (m.disk.pruning) {
|
|
6862
|
+
counter("disk_spills_shed", m.disk.pruning.spillsShedTotal, "Total disk spills shed due to pruning or low disk space");
|
|
6863
|
+
counter("disk_prune_rounds", m.disk.pruning.pruneRounds, "Total high-watermark disk prune rounds");
|
|
6864
|
+
counter("disk_entries_pruned", m.disk.pruning.entriesPruned, "Total entries removed by watermark pruning");
|
|
6865
|
+
counter("disk_low_space_pauses", m.disk.pruning.hostVolumeLowSpacePauses, "Total times spills paused due to <10% host volume space");
|
|
6866
|
+
}
|
|
4501
6867
|
gauge(
|
|
4502
6868
|
"bloom_false_positive_rate",
|
|
4503
6869
|
m.bloom.falsePositiveRate,
|
|
@@ -4519,6 +6885,17 @@ var CacheService = class _CacheService {
|
|
|
4519
6885
|
"Emergency L1 eviction rounds triggered by heap pressure"
|
|
4520
6886
|
);
|
|
4521
6887
|
}
|
|
6888
|
+
if (m.remoteSnapshot?.enabled) {
|
|
6889
|
+
counter("remote_snapshot_uploads", m.remoteSnapshot.uploads, "Total remote snapshot uploads");
|
|
6890
|
+
counter("remote_snapshot_downloads", m.remoteSnapshot.downloads, "Total remote snapshot downloads");
|
|
6891
|
+
counter("remote_snapshot_errors", m.remoteSnapshot.errors, "Total remote snapshot errors");
|
|
6892
|
+
}
|
|
6893
|
+
if (m.crossRegion?.enabled) {
|
|
6894
|
+
counter("cross_region_sent", m.crossRegion.sent, "Total cross-region invalidations broadcast");
|
|
6895
|
+
counter("cross_region_received", m.crossRegion.received, "Total cross-region invalidations received");
|
|
6896
|
+
counter("cross_region_deduplicated", m.crossRegion.deduplicated, "Total cross-region invalidations deduplicated or self-filtered");
|
|
6897
|
+
counter("cross_region_errors", m.crossRegion.errors, "Total cross-region relay errors");
|
|
6898
|
+
}
|
|
4522
6899
|
return lines.join("\n");
|
|
4523
6900
|
}
|
|
4524
6901
|
// ── Lifecycle ────────────────────────────────────────────────────────────
|
|
@@ -4537,23 +6914,31 @@ var CacheService = class _CacheService {
|
|
|
4537
6914
|
/** Close Redis connections and stop all background timers. */
|
|
4538
6915
|
async destroy() {
|
|
4539
6916
|
this._destroyed = true;
|
|
6917
|
+
const g = globalThis;
|
|
6918
|
+
const key = _CacheService.globalKey(this.opts);
|
|
6919
|
+
if (g[key] === this) {
|
|
6920
|
+
delete g[key];
|
|
6921
|
+
}
|
|
4540
6922
|
if (this.cleanupInterval) clearInterval(this.cleanupInterval);
|
|
4541
6923
|
if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
|
|
4542
6924
|
if (this.oomInterval) clearInterval(this.oomInterval);
|
|
4543
6925
|
if (this.metricsInterval) clearInterval(this.metricsInterval);
|
|
4544
|
-
if (this.
|
|
4545
|
-
|
|
4546
|
-
|
|
4547
|
-
this._shutdownHandler = null;
|
|
6926
|
+
if (this.remoteSnapshotInterval) {
|
|
6927
|
+
clearInterval(this.remoteSnapshotInterval);
|
|
6928
|
+
this.remoteSnapshotInterval = null;
|
|
4548
6929
|
}
|
|
6930
|
+
ProcessTerminationBus.unregister(this);
|
|
6931
|
+
this._shutdownHandler = null;
|
|
4549
6932
|
if (this._workerPool) {
|
|
4550
6933
|
await this._workerPool.destroy();
|
|
4551
6934
|
this._workerPool = null;
|
|
4552
6935
|
}
|
|
4553
6936
|
if (this.subClient) {
|
|
4554
|
-
|
|
4555
|
-
|
|
4556
|
-
|
|
6937
|
+
if (!this.opts.redisSubClient) {
|
|
6938
|
+
try {
|
|
6939
|
+
this.subClient.disconnect();
|
|
6940
|
+
} catch {
|
|
6941
|
+
}
|
|
4557
6942
|
}
|
|
4558
6943
|
this.subClient = null;
|
|
4559
6944
|
}
|
|
@@ -4565,19 +6950,61 @@ var CacheService = class _CacheService {
|
|
|
4565
6950
|
this.streamClient = null;
|
|
4566
6951
|
}
|
|
4567
6952
|
if (this.redis) {
|
|
4568
|
-
|
|
4569
|
-
|
|
4570
|
-
|
|
6953
|
+
if (!this.opts.redisClient) {
|
|
6954
|
+
try {
|
|
6955
|
+
await this.redis.disconnect();
|
|
6956
|
+
} catch {
|
|
6957
|
+
}
|
|
4571
6958
|
}
|
|
4572
6959
|
this.redis = null;
|
|
4573
6960
|
}
|
|
6961
|
+
if (this._ipcServer) {
|
|
6962
|
+
await this._ipcServer.close();
|
|
6963
|
+
this._ipcServer = void 0;
|
|
6964
|
+
}
|
|
4574
6965
|
if (!this._diskDisabled) this.disk.close();
|
|
4575
6966
|
}
|
|
6967
|
+
/**
|
|
6968
|
+
* Return the active IPC telemetry server instance, if enabled.
|
|
6969
|
+
*/
|
|
6970
|
+
getIpcServer() {
|
|
6971
|
+
return this._ipcServer;
|
|
6972
|
+
}
|
|
6973
|
+
/**
|
|
6974
|
+
* Return real-time telemetry and metrics for the Window TinyLFU admission policy.
|
|
6975
|
+
* Returns `undefined` if W-TinyLFU admission is not active.
|
|
6976
|
+
*/
|
|
6977
|
+
getWTinyLfuStats() {
|
|
6978
|
+
return this.l1.getWTinyLfuStats();
|
|
6979
|
+
}
|
|
4576
6980
|
};
|
|
4577
6981
|
|
|
4578
6982
|
export {
|
|
4579
|
-
|
|
6983
|
+
CacheCodec,
|
|
6984
|
+
defaultCodec,
|
|
6985
|
+
TinyLfuSketch,
|
|
6986
|
+
WTinyLfuCache,
|
|
6987
|
+
WTinyLfuPolicy,
|
|
4580
6988
|
SmartMemoryCache,
|
|
6989
|
+
resolveDefaultDiskDir,
|
|
4581
6990
|
DiskTier,
|
|
6991
|
+
TierLatencyWatchdog,
|
|
6992
|
+
DEFAULT_AUTONOMOUS_L1_CEILING_BYTES,
|
|
6993
|
+
MIN_AUTONOMOUS_L1_FLOOR_BYTES,
|
|
6994
|
+
readCgroupMemoryLimit,
|
|
6995
|
+
getV8HeapLimit,
|
|
6996
|
+
resolveAutonomousL1MaxBytes,
|
|
6997
|
+
AutoPipeliner,
|
|
6998
|
+
resolveIpcSocketPath,
|
|
6999
|
+
IpcTelemetryServer,
|
|
7000
|
+
IpcTelemetryClient,
|
|
7001
|
+
findActiveSockets,
|
|
7002
|
+
renderProgressBar,
|
|
7003
|
+
formatBytes,
|
|
7004
|
+
formatNumber,
|
|
7005
|
+
formatDuration,
|
|
7006
|
+
renderTopDashboard,
|
|
7007
|
+
ProcessTerminationBus,
|
|
7008
|
+
deepMergeOptions,
|
|
4582
7009
|
CacheService
|
|
4583
7010
|
};
|