tricache 0.7.1 → 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.
Files changed (95) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +87 -1371
  3. package/dashboards/tricache-alerts.yaml +54 -0
  4. package/dashboards/tricache-grafana.json +548 -0
  5. package/dist/cache-service-5MZXFIGK.js +12 -0
  6. package/dist/cache-service-CyLdpo77.d.ts +871 -0
  7. package/dist/{chunk-EUGYR7KR.js → chunk-6PQ5MOWR.js} +2871 -490
  8. package/dist/chunk-7RV5ZVBB.js +1023 -0
  9. package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
  10. package/dist/chunk-QNU7B43J.js +687 -0
  11. package/dist/chunk-UGD4VEPD.js +138 -0
  12. package/dist/chunk-XZL45ABR.js +108 -0
  13. package/dist/chunk-ZTSWCFYO.js +135 -0
  14. package/dist/cli.cjs +2790 -471
  15. package/dist/cli.d.ts +1 -0
  16. package/dist/cli.js +103 -5
  17. package/dist/dashboard/index.cjs +1065 -0
  18. package/dist/dashboard/index.d.ts +183 -0
  19. package/dist/dashboard/index.js +22 -0
  20. package/dist/drizzle/index.cjs +2553 -470
  21. package/dist/drizzle/index.d.ts +3 -1
  22. package/dist/drizzle/index.js +1 -1
  23. package/dist/edge/index.cjs +1498 -0
  24. package/dist/edge/index.d.ts +127 -0
  25. package/dist/edge/index.js +1109 -0
  26. package/dist/hono-DQRS1Xd7.d.ts +370 -0
  27. package/dist/http/index.cjs +2926 -562
  28. package/dist/http/index.d.ts +109 -23
  29. package/dist/http/index.js +220 -72
  30. package/dist/index.cjs +6936 -2518
  31. package/dist/index.d.ts +547 -30
  32. package/dist/index.js +104 -5
  33. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  34. package/dist/nestjs/index.cjs +2494 -463
  35. package/dist/nestjs/index.d.ts +3 -1
  36. package/dist/nestjs/index.js +6 -3
  37. package/dist/next/index.cjs +2517 -483
  38. package/dist/next/index.d.ts +4 -2
  39. package/dist/next/index.js +14 -10
  40. package/dist/prisma/index.d.ts +3 -1
  41. package/dist/serialize-worker.cjs +5 -4
  42. package/dist/serialize-worker.js +1 -1
  43. package/dist/{cache-service-D8tIXmzb.d.ts → types-B6krw64X.d.ts} +596 -659
  44. package/package.json +34 -6
  45. package/src/adapters/auto-pipeliner.ts +206 -0
  46. package/src/adapters/node-redis.ts +370 -0
  47. package/src/cache-service.ts +1339 -402
  48. package/src/cli.ts +120 -2
  49. package/src/codec.ts +72 -0
  50. package/src/cross-region.ts +245 -0
  51. package/src/dashboard/handler.ts +392 -0
  52. package/src/dashboard/html.ts +594 -0
  53. package/src/dashboard/index.ts +195 -0
  54. package/src/dashboard/types.ts +96 -0
  55. package/src/disk-tier.ts +449 -47
  56. package/src/drizzle/index.ts +86 -86
  57. package/src/edge/adapters/cloudflare-do.ts +130 -0
  58. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  59. package/src/edge/adapters/upstash.ts +143 -0
  60. package/src/edge/cache.ts +797 -0
  61. package/src/edge/crypto.ts +182 -0
  62. package/src/edge/hono.ts +203 -0
  63. package/src/edge/index.ts +37 -0
  64. package/src/edge/types.ts +230 -0
  65. package/src/edge/utils/base64.ts +63 -0
  66. package/src/edge/utils/murmur3.ts +179 -0
  67. package/src/encryption.ts +127 -5
  68. package/src/http/express.ts +195 -0
  69. package/src/http/fastify.ts +260 -0
  70. package/src/http/index.ts +39 -258
  71. package/src/http/utils.ts +92 -0
  72. package/src/index.ts +149 -47
  73. package/src/ipc-telemetry.ts +481 -0
  74. package/src/latency-watchdog.ts +282 -0
  75. package/src/nestjs/decorators.ts +161 -161
  76. package/src/nestjs/index.ts +23 -23
  77. package/src/nestjs/tricache.module.ts +104 -104
  78. package/src/nestjs/tricache.store.ts +97 -97
  79. package/src/nestjs/types.ts +79 -79
  80. package/src/next/cache-handler.ts +12 -9
  81. package/src/next/index.ts +37 -37
  82. package/src/next/isr-handler.ts +105 -105
  83. package/src/next/types.ts +130 -130
  84. package/src/remote-snapshot.ts +153 -0
  85. package/src/serialize-worker.ts +120 -120
  86. package/src/sigv4-snapshot-adapter.ts +260 -0
  87. package/src/smart-memory-cache.ts +91 -8
  88. package/src/types.ts +290 -2
  89. package/src/utils/cgroup.ts +100 -0
  90. package/src/utils/tracing.ts +54 -0
  91. package/src/wasm/bloom-filter-wasm.ts +109 -102
  92. package/src/worker-pool.ts +299 -299
  93. package/src/wtiny-lfu.ts +624 -0
  94. package/dist/cache-service-5GATUYAK.js +0 -7
  95. 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-X5AXHPVD.js";
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
- import { pack as pack3, unpack as unpack3 } from "msgpackr";
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 os2 from "os";
54
+ import os3 from "os";
17
55
 
18
56
  // src/worker-pool.ts
19
57
  import { Worker } from "worker_threads";
@@ -217,74 +255,444 @@ function availableCpus() {
217
255
  }
218
256
 
219
257
  // src/cache-service.ts
220
- import v8 from "v8";
221
- import fs2 from "fs";
222
- import path2 from "path";
223
-
224
- // src/smart-memory-cache.ts
225
- import { pack, unpack } from "msgpackr";
258
+ import v82 from "v8";
259
+ import fs4 from "fs";
260
+ import path3 from "path";
226
261
 
227
- // src/wasm/bloom-filter-wasm.ts
228
- var BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
229
- var KEY_STAGING_OFFSET = 2e4;
230
- var MAX_KEY_BYTES = 512;
231
- var BLOOM_WASM_MODULE = new WebAssembly.Module(Buffer.from(BLOOM_WASM_BASE64, "base64"));
232
- var WasmBloomFilter = class {
233
- exports;
234
- mem;
235
- stagingTarget;
236
- encoder = new TextEncoder();
237
- numBits = 1e5;
238
- /** Pre-computed — k and numBits are fixed constants; no need to recalculate on every probe. */
239
- _maxCapacity;
240
- /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
241
- _insertionCount = 0;
242
- constructor() {
243
- const instance = new WebAssembly.Instance(BLOOM_WASM_MODULE, {});
244
- this.exports = instance.exports;
245
- this.mem = new Uint8Array(this.exports.memory.buffer);
246
- this.stagingTarget = new Uint8Array(this.exports.memory.buffer, KEY_STAGING_OFFSET, MAX_KEY_BYTES);
247
- const k = 7, p = 0.01;
248
- this._maxCapacity = Math.floor(-this.numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
249
- }
250
- writeKey(key) {
251
- if (key.length === 0) return 0;
252
- return this.encoder.encodeInto(key, this.stagingTarget).written;
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
- add(key) {
255
- const len = this.writeKey(key);
256
- if (len === 0) return;
257
- this.exports.add(KEY_STAGING_OFFSET, len);
258
- this._insertionCount++;
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
- mightContain(key) {
261
- const len = this.writeKey(key);
262
- if (len === 0) return true;
263
- return this.exports.mightContain(KEY_STAGING_OFFSET, len) === 1;
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
- reset() {
266
- this.exports.reset();
267
- this._insertionCount = 0;
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
- rebuild(keys) {
270
- this.reset();
271
- for (const key of keys) this.add(key);
327
+ clear() {
328
+ this.table.fill(0);
329
+ this.insertions = 0;
272
330
  }
273
- get stats() {
274
- const bitsSet = this.exports.countBits();
275
- return { bitsSet, fillFactor: bitsSet / this.numBits };
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
- /** Number of add() calls since last reset/rebuild. */
278
- get insertions() {
279
- return this._insertionCount;
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
- * Maximum safe insertions before false-positive rate exceeds ~1 %.
283
- * Exact formula for k=7 hash rounds, m=100 000 bits, p=1%:
284
- * n_max = -m * ln(1 - p^(1/k)) / k ≈ 10 434
370
+ * Retrieves an entry and performs W-TinyLFU access promotion.
285
371
  */
286
- get maxCapacity() {
287
- return this._maxCapacity;
372
+ get(key) {
373
+ const keyStr = this.keyToString(key);
374
+ this.sketch.increment(keyStr);
375
+ if (this.window.has(key)) {
376
+ const val = this.window.get(key);
377
+ this.window.delete(key);
378
+ this.window.set(key, val);
379
+ this.hitCount++;
380
+ return val;
381
+ }
382
+ if (this.protected_.has(key)) {
383
+ const val = this.protected_.get(key);
384
+ this.protected_.delete(key);
385
+ this.protected_.set(key, val);
386
+ this.hitCount++;
387
+ return val;
388
+ }
389
+ if (this.probation.has(key)) {
390
+ const val = this.probation.get(key);
391
+ this.probation.delete(key);
392
+ this.promotionCount++;
393
+ this.protected_.set(key, val);
394
+ if (this.protected_.size > this.maxProtected) {
395
+ const oldestProtKey = this.protected_.keys().next().value;
396
+ const oldestProtVal = this.protected_.get(oldestProtKey);
397
+ this.protected_.delete(oldestProtKey);
398
+ this.probation.set(oldestProtKey, oldestProtVal);
399
+ this.demotionCount++;
400
+ }
401
+ this.hitCount++;
402
+ return val;
403
+ }
404
+ this.missCount++;
405
+ return void 0;
406
+ }
407
+ /**
408
+ * Returns true if key exists in any segment without updating access frequency.
409
+ */
410
+ has(key) {
411
+ return this.window.has(key) || this.probation.has(key) || this.protected_.has(key);
412
+ }
413
+ /**
414
+ * Puts an entry into the cache using W-TinyLFU admission policies.
415
+ */
416
+ set(key, value) {
417
+ const keyStr = this.keyToString(key);
418
+ this.sketch.increment(keyStr);
419
+ const result = {};
420
+ if (this.window.has(key)) {
421
+ this.window.delete(key);
422
+ this.window.set(key, value);
423
+ return result;
424
+ }
425
+ if (this.protected_.has(key)) {
426
+ this.protected_.delete(key);
427
+ this.protected_.set(key, value);
428
+ return result;
429
+ }
430
+ if (this.probation.has(key)) {
431
+ this.probation.delete(key);
432
+ this.probation.set(key, value);
433
+ return result;
434
+ }
435
+ this.window.set(key, value);
436
+ if (this.window.size <= this.maxWindow) {
437
+ this.admissionCount++;
438
+ return result;
439
+ }
440
+ const candKey = this.window.keys().next().value;
441
+ const candVal = this.window.get(candKey);
442
+ this.window.delete(candKey);
443
+ if (this.probation.size + this.protected_.size < this.maxProbation + this.maxProtected) {
444
+ this.probation.set(candKey, candVal);
445
+ this.admissionCount++;
446
+ return result;
447
+ }
448
+ let victimKey;
449
+ let victimVal;
450
+ let victimSegment;
451
+ if (this.probation.size > 0) {
452
+ victimKey = this.probation.keys().next().value;
453
+ victimVal = this.probation.get(victimKey);
454
+ victimSegment = "probation";
455
+ } else {
456
+ victimKey = this.protected_.keys().next().value;
457
+ victimVal = this.protected_.get(victimKey);
458
+ victimSegment = "protected";
459
+ }
460
+ const candFreq = this.sketch.estimate(this.keyToString(candKey));
461
+ const victimFreq = this.sketch.estimate(this.keyToString(victimKey));
462
+ if (candFreq > victimFreq) {
463
+ if (victimSegment === "probation") {
464
+ this.probation.delete(victimKey);
465
+ } else {
466
+ this.protected_.delete(victimKey);
467
+ }
468
+ this.probation.set(candKey, candVal);
469
+ this.admissionCount++;
470
+ result.evicted = { key: victimKey, value: victimVal, segment: victimSegment };
471
+ } else {
472
+ this.rejectionCount++;
473
+ result.rejected = { key: candKey, value: candVal, segment: "window" };
474
+ }
475
+ return result;
476
+ }
477
+ /**
478
+ * Removes a key from whichever segment it resides in.
479
+ */
480
+ delete(key) {
481
+ return this.window.delete(key) || this.probation.delete(key) || this.protected_.delete(key);
482
+ }
483
+ /**
484
+ * Resets all segments, sketch, and metrics.
485
+ */
486
+ clear() {
487
+ this.window.clear();
488
+ this.probation.clear();
489
+ this.protected_.clear();
490
+ this.sketch.clear();
491
+ this.hitCount = 0;
492
+ this.missCount = 0;
493
+ this.admissionCount = 0;
494
+ this.rejectionCount = 0;
495
+ this.promotionCount = 0;
496
+ this.demotionCount = 0;
497
+ }
498
+ /**
499
+ * Returns current telemetry and hit-ratio stats.
500
+ */
501
+ stats() {
502
+ const totalRequests = this.hitCount + this.missCount;
503
+ return {
504
+ capacity: this.maxTotal,
505
+ size: this.size,
506
+ windowSize: this.window.size,
507
+ probationSize: this.probation.size,
508
+ protectedSize: this.protected_.size,
509
+ hits: this.hitCount,
510
+ misses: this.missCount,
511
+ hitRate: totalRequests > 0 ? this.hitCount / totalRequests : 0,
512
+ admissions: this.admissionCount,
513
+ rejections: this.rejectionCount,
514
+ promotions: this.promotionCount,
515
+ demotions: this.demotionCount
516
+ };
517
+ }
518
+ getStats() {
519
+ return this.stats();
520
+ }
521
+ /**
522
+ * Returns an iterator of all keys currently in the cache.
523
+ */
524
+ *keys() {
525
+ yield* this.window.keys();
526
+ yield* this.probation.keys();
527
+ yield* this.protected_.keys();
528
+ }
529
+ /**
530
+ * Returns an iterator of all entries currently in the cache.
531
+ */
532
+ *entries() {
533
+ yield* this.window.entries();
534
+ yield* this.probation.entries();
535
+ yield* this.protected_.entries();
536
+ }
537
+ /**
538
+ * Returns segment membership for a key ('window', 'probation', 'protected', or null).
539
+ */
540
+ getSegment(key) {
541
+ if (this.window.has(key)) return "window";
542
+ if (this.probation.has(key)) return "probation";
543
+ if (this.protected_.has(key)) return "protected";
544
+ return null;
545
+ }
546
+ };
547
+ var WTinyLfuPolicy = class {
548
+ constructor(capacity, sketch, windowPercent = 0.01, protectedPercent = 0.8) {
549
+ this.sketch = sketch;
550
+ this.maxTotal = Math.max(2, capacity);
551
+ this.maxWindow = Math.max(1, Math.floor(this.maxTotal * windowPercent));
552
+ const mainCapacity = Math.max(1, this.maxTotal - this.maxWindow);
553
+ this.maxProtected = Math.max(1, Math.floor(mainCapacity * protectedPercent));
554
+ this.maxProbation = Math.max(1, mainCapacity - this.maxProtected);
555
+ }
556
+ sketch;
557
+ maxTotal;
558
+ maxWindow;
559
+ maxProtected;
560
+ maxProbation;
561
+ window = /* @__PURE__ */ new Set();
562
+ probation = /* @__PURE__ */ new Set();
563
+ protected_ = /* @__PURE__ */ new Set();
564
+ // Telemetry metrics
565
+ hitCount = 0;
566
+ missCount = 0;
567
+ admissionCount = 0;
568
+ rejectionCount = 0;
569
+ promotionCount = 0;
570
+ demotionCount = 0;
571
+ get windowSize() {
572
+ return this.window.size;
573
+ }
574
+ get probationSize() {
575
+ return this.probation.size;
576
+ }
577
+ get protectedSize() {
578
+ return this.protected_.size;
579
+ }
580
+ onAccess(key) {
581
+ if (this.window.has(key)) {
582
+ this.window.delete(key);
583
+ this.window.add(key);
584
+ this.hitCount++;
585
+ return;
586
+ }
587
+ if (this.protected_.has(key)) {
588
+ this.protected_.delete(key);
589
+ this.protected_.add(key);
590
+ this.hitCount++;
591
+ return;
592
+ }
593
+ if (this.probation.has(key)) {
594
+ this.probation.delete(key);
595
+ this.protected_.add(key);
596
+ this.promotionCount++;
597
+ this.hitCount++;
598
+ if (this.protected_.size > this.maxProtected) {
599
+ const oldestProtKey = this.protected_.values().next().value;
600
+ this.protected_.delete(oldestProtKey);
601
+ this.probation.add(oldestProtKey);
602
+ this.demotionCount++;
603
+ }
604
+ return;
605
+ }
606
+ this.missCount++;
607
+ }
608
+ onSet(key, isUpdate) {
609
+ if (isUpdate) {
610
+ if (this.window.has(key)) {
611
+ this.window.delete(key);
612
+ this.window.add(key);
613
+ } else if (this.protected_.has(key)) {
614
+ this.protected_.delete(key);
615
+ this.protected_.add(key);
616
+ } else if (this.probation.has(key)) {
617
+ this.probation.delete(key);
618
+ this.probation.add(key);
619
+ }
620
+ return { admit: true };
621
+ }
622
+ this.window.add(key);
623
+ if (this.window.size <= this.maxWindow) {
624
+ this.admissionCount++;
625
+ return { admit: true };
626
+ }
627
+ const candKey = this.window.values().next().value;
628
+ this.window.delete(candKey);
629
+ if (this.probation.size + this.protected_.size < this.maxProbation + this.maxProtected) {
630
+ this.probation.add(candKey);
631
+ this.admissionCount++;
632
+ return { admit: true };
633
+ }
634
+ let victimKey;
635
+ let victimIsProbation = true;
636
+ if (this.probation.size > 0) {
637
+ victimKey = this.probation.values().next().value;
638
+ } else {
639
+ victimKey = this.protected_.values().next().value;
640
+ victimIsProbation = false;
641
+ }
642
+ const candFreq = this.sketch.estimate(candKey);
643
+ const victimFreq = this.sketch.estimate(victimKey);
644
+ if (candFreq > victimFreq) {
645
+ if (victimIsProbation) {
646
+ this.probation.delete(victimKey);
647
+ } else {
648
+ this.protected_.delete(victimKey);
649
+ }
650
+ this.probation.add(candKey);
651
+ this.admissionCount++;
652
+ return { admit: true, evictKey: victimKey, candidateKey: candKey };
653
+ } else {
654
+ this.rejectionCount++;
655
+ return { admit: false, candidateKey: candKey };
656
+ }
657
+ }
658
+ onDelete(key) {
659
+ this.window.delete(key);
660
+ this.probation.delete(key);
661
+ this.protected_.delete(key);
662
+ }
663
+ clear() {
664
+ this.window.clear();
665
+ this.probation.clear();
666
+ this.protected_.clear();
667
+ this.hitCount = 0;
668
+ this.missCount = 0;
669
+ this.admissionCount = 0;
670
+ this.rejectionCount = 0;
671
+ this.promotionCount = 0;
672
+ this.demotionCount = 0;
673
+ }
674
+ getStats() {
675
+ const totalRequests = this.hitCount + this.missCount;
676
+ return {
677
+ capacity: this.maxTotal,
678
+ size: this.window.size + this.probation.size + this.protected_.size,
679
+ windowSize: this.window.size,
680
+ probationSize: this.probation.size,
681
+ protectedSize: this.protected_.size,
682
+ hits: this.hitCount,
683
+ misses: this.missCount,
684
+ hitRate: totalRequests > 0 ? this.hitCount / totalRequests : 0,
685
+ admissions: this.admissionCount,
686
+ rejections: this.rejectionCount,
687
+ promotions: this.promotionCount,
688
+ demotions: this.demotionCount
689
+ };
690
+ }
691
+ getSegment(key) {
692
+ if (this.window.has(key)) return "window";
693
+ if (this.probation.has(key)) return "probation";
694
+ if (this.protected_.has(key)) return "protected";
695
+ return null;
288
696
  }
289
697
  };
290
698
 
@@ -463,11 +871,13 @@ function globMatchParts(parts, first, last, key) {
463
871
  var SmartMemoryCache = class {
464
872
  cache = /* @__PURE__ */ new Map();
465
873
  opts;
874
+ codec;
466
875
  bloom;
467
876
  /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
468
877
  categoryPrefixes;
469
878
  /** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
470
879
  sketch = new CountMinSketch();
880
+ wtinyPolicy;
471
881
  totalSize = 0;
472
882
  categoryCount = /* @__PURE__ */ new Map();
473
883
  categorySize = /* @__PURE__ */ new Map();
@@ -491,8 +901,12 @@ var SmartMemoryCache = class {
491
901
  _evictGPool = Array.from({ length: EVICTION_SAMPLE }, () => ({ key: "", score: 0 }));
492
902
  constructor(opts, existing) {
493
903
  this.opts = opts;
904
+ this.codec = opts.codec ?? defaultCodec;
494
905
  this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
495
906
  this.categoryPrefixes = Object.keys(opts.categories).filter((k) => k !== "default");
907
+ if (opts.admissionPolicy === "wtinylfu") {
908
+ this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch);
909
+ }
496
910
  if (existing) {
497
911
  for (const [k, v] of existing) this.cache.set(k, v);
498
912
  this.recalculateStats();
@@ -505,6 +919,12 @@ var SmartMemoryCache = class {
505
919
  this.categoryCount.clear();
506
920
  this.categorySize.clear();
507
921
  this.categoryKeys.clear();
922
+ if (this.wtinyPolicy) {
923
+ this.wtinyPolicy.clear();
924
+ for (const key of this.cache.keys()) {
925
+ this.wtinyPolicy.onSet(key, false);
926
+ }
927
+ }
508
928
  for (const [key, entry] of this.cache) {
509
929
  this.totalSize += entry.size;
510
930
  const cat = this.getCategory(key);
@@ -530,6 +950,7 @@ var SmartMemoryCache = class {
530
950
  _delete(key, reason = "manual") {
531
951
  const entry = this.cache.get(key);
532
952
  if (!entry) return false;
953
+ this.wtinyPolicy?.onDelete(key);
533
954
  const cat = this.getCategory(key);
534
955
  this.totalSize -= entry.size;
535
956
  this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
@@ -690,7 +1111,8 @@ var SmartMemoryCache = class {
690
1111
  entry.hits++;
691
1112
  entry.lastAccess = now;
692
1113
  if ((entry.hits & 3) === 0) this.sketch.increment(key);
693
- const value = entry.value !== void 0 ? entry.value : unpack(entry.data);
1114
+ this.wtinyPolicy?.onAccess(key);
1115
+ const value = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
694
1116
  const hit = {
695
1117
  value,
696
1118
  isStale: entry.staleAt !== void 0 && now > entry.staleAt,
@@ -704,7 +1126,7 @@ var SmartMemoryCache = class {
704
1126
  return hit;
705
1127
  }
706
1128
  set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
707
- const packed = pack(data);
1129
+ const packed = this.codec.encode(data);
708
1130
  const size = packed.byteLength;
709
1131
  this.compressions++;
710
1132
  this.sketch.increment(key);
@@ -721,7 +1143,51 @@ var SmartMemoryCache = class {
721
1143
  this.categorySize.set(cat, (this.categorySize.get(cat) ?? existingEntry.size) - existingEntry.size);
722
1144
  this.cache.delete(key);
723
1145
  }
724
- this.ensureCapacity(cat, size);
1146
+ if (this.wtinyPolicy) {
1147
+ const decision = this.wtinyPolicy.onSet(key, Boolean(existingEntry));
1148
+ if (!decision.admit) {
1149
+ if (decision.candidateKey === key) {
1150
+ if (this.opts.diskSpill) {
1151
+ const now2 = Date.now();
1152
+ const liveValue2 = size <= LARGE_VALUE_BYTES ? data : void 0;
1153
+ this.opts.diskSpill(key, {
1154
+ data: packed,
1155
+ value: liveValue2,
1156
+ isCompressed: true,
1157
+ expiresAt: now2 + ttlMs,
1158
+ staleAt,
1159
+ size,
1160
+ hits: 1,
1161
+ lastAccess: now2,
1162
+ priority,
1163
+ ttlMs,
1164
+ delta,
1165
+ setAt: now2,
1166
+ tagVersions
1167
+ });
1168
+ }
1169
+ return;
1170
+ } else if (decision.candidateKey) {
1171
+ const candEntry = this.cache.get(decision.candidateKey);
1172
+ if (candEntry && this.opts.diskSpill) {
1173
+ this.opts.diskSpill(decision.candidateKey, candEntry);
1174
+ }
1175
+ this._delete(decision.candidateKey, "capacity");
1176
+ }
1177
+ } else if (decision.evictKey) {
1178
+ const victimEntry = this.cache.get(decision.evictKey);
1179
+ if (victimEntry && this.opts.diskSpill) {
1180
+ this.opts.diskSpill(decision.evictKey, victimEntry);
1181
+ }
1182
+ this._delete(decision.evictKey, "capacity");
1183
+ }
1184
+ const catSz = this.categorySize.get(cat) ?? 0;
1185
+ if (catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
1186
+ this.ensureCapacity(cat, size);
1187
+ }
1188
+ } else {
1189
+ this.ensureCapacity(cat, size);
1190
+ }
725
1191
  const now = Date.now();
726
1192
  const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
727
1193
  this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: now, tagVersions });
@@ -781,6 +1247,7 @@ var SmartMemoryCache = class {
781
1247
  }
782
1248
  const count = this.cache.size;
783
1249
  this.cache.clear();
1250
+ this.wtinyPolicy?.clear();
784
1251
  this.totalSize = 0;
785
1252
  this.categoryCount.clear();
786
1253
  this.categorySize.clear();
@@ -948,8 +1415,8 @@ var SmartMemoryCache = class {
948
1415
  if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
949
1416
  if (this.cache.has(key)) continue;
950
1417
  const rawData = entry.data;
951
- const data = !entry.isCompressed ? pack(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
952
- const value = entry.size <= LARGE_VALUE_BYTES ? unpack(data) : void 0;
1418
+ const data = !entry.isCompressed ? this.codec.encode(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
1419
+ const value = entry.size <= LARGE_VALUE_BYTES ? this.codec.decode(data) : void 0;
953
1420
  this.cache.set(key, { ...entry, data, value, isCompressed: true });
954
1421
  this.bloom.add(key);
955
1422
  loaded++;
@@ -1020,7 +1487,7 @@ var SmartMemoryCache = class {
1020
1487
  * if the live object was not cached (large-entry optimisation or disk-restored entry).
1021
1488
  */
1022
1489
  resolveValue(entry) {
1023
- return entry.value !== void 0 ? entry.value : unpack(entry.data);
1490
+ return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
1024
1491
  }
1025
1492
  // ── Stats ─────────────────────────────────────────────────────────────────
1026
1493
  get size() {
@@ -1125,25 +1592,160 @@ var SmartMemoryCache = class {
1125
1592
  out.sort((a, b) => b.hits - a.hits);
1126
1593
  return out.slice(0, n);
1127
1594
  }
1595
+ /**
1596
+ * Return real-time metrics and telemetry for the Window TinyLFU admission policy.
1597
+ * Returns `undefined` when running under default adaptive eviction.
1598
+ */
1599
+ getWTinyLfuStats() {
1600
+ return this.wtinyPolicy?.getStats();
1601
+ }
1128
1602
  };
1129
1603
 
1130
1604
  // src/disk-tier.ts
1131
1605
  import fs from "fs";
1132
1606
  import path from "path";
1133
1607
  import crypto from "crypto";
1134
- import { pack as pack2, unpack as unpack2 } from "msgpackr";
1608
+ import os2 from "os";
1609
+ var BoundedDiskQueue = class {
1610
+ constructor(maxConcurrent = Math.min(4, Math.max(1, Math.floor((os2?.availableParallelism?.() ?? 4) / 4))), maxPending = 512, writeTimeoutMs = 500, failureThreshold = 5, cooldownMs = 5e3) {
1611
+ this.maxConcurrent = maxConcurrent;
1612
+ this.maxPending = maxPending;
1613
+ this.writeTimeoutMs = writeTimeoutMs;
1614
+ this.failureThreshold = failureThreshold;
1615
+ this.cooldownMs = cooldownMs;
1616
+ }
1617
+ maxConcurrent;
1618
+ maxPending;
1619
+ writeTimeoutMs;
1620
+ failureThreshold;
1621
+ cooldownMs;
1622
+ active = 0;
1623
+ queue = [];
1624
+ spillsDropped = 0;
1625
+ consecutiveFailures = 0;
1626
+ circuitState = "closed";
1627
+ lastStateChangeMonotonic = performance.now();
1628
+ async schedule(task) {
1629
+ const now = performance.now();
1630
+ if (this.circuitState === "open") {
1631
+ if (now - this.lastStateChangeMonotonic > this.cooldownMs) {
1632
+ this.circuitState = "half-open";
1633
+ this.lastStateChangeMonotonic = now;
1634
+ } else {
1635
+ this.spillsDropped++;
1636
+ return null;
1637
+ }
1638
+ }
1639
+ if (this.circuitState === "half-open" && this.active > 0) {
1640
+ this.spillsDropped++;
1641
+ return null;
1642
+ }
1643
+ if (this.queue.length >= this.maxPending) {
1644
+ this.spillsDropped++;
1645
+ return null;
1646
+ }
1647
+ if (this.active >= this.maxConcurrent) {
1648
+ await new Promise((resolve) => this.queue.push(resolve));
1649
+ }
1650
+ this.active++;
1651
+ let timeoutId = null;
1652
+ try {
1653
+ const result = await Promise.race([
1654
+ task(),
1655
+ new Promise((_, reject) => {
1656
+ timeoutId = setTimeout(
1657
+ () => reject(new Error(`Disk write exceeded timeout of ${this.writeTimeoutMs}ms`)),
1658
+ this.writeTimeoutMs
1659
+ );
1660
+ })
1661
+ ]);
1662
+ this.consecutiveFailures = 0;
1663
+ if (this.circuitState === "half-open") {
1664
+ this.circuitState = "closed";
1665
+ this.lastStateChangeMonotonic = performance.now();
1666
+ }
1667
+ return result;
1668
+ } catch {
1669
+ this.consecutiveFailures++;
1670
+ if (this.consecutiveFailures >= this.failureThreshold || this.circuitState === "half-open") {
1671
+ this.circuitState = "open";
1672
+ this.lastStateChangeMonotonic = performance.now();
1673
+ }
1674
+ this.spillsDropped++;
1675
+ return null;
1676
+ } finally {
1677
+ if (timeoutId) clearTimeout(timeoutId);
1678
+ this.active--;
1679
+ const next = this.queue.shift();
1680
+ if (next) next();
1681
+ }
1682
+ }
1683
+ getStats() {
1684
+ return {
1685
+ activeWrites: this.active,
1686
+ pendingWrites: this.queue.length,
1687
+ spillsDropped: this.spillsDropped,
1688
+ circuitState: this.circuitState,
1689
+ lastTripTimestamp: this.lastStateChangeMonotonic
1690
+ };
1691
+ }
1692
+ reset() {
1693
+ this.consecutiveFailures = 0;
1694
+ this.circuitState = "closed";
1695
+ this.lastStateChangeMonotonic = performance.now();
1696
+ }
1697
+ };
1135
1698
  var _SqliteDB = null;
1136
1699
  try {
1137
- const sqlite = process.getBuiltinModule("node:sqlite");
1138
- _SqliteDB = sqlite?.DatabaseSync ?? null;
1700
+ const proc = process;
1701
+ if (typeof proc.getBuiltinModule === "function") {
1702
+ const sqlite = proc.getBuiltinModule("node:sqlite");
1703
+ _SqliteDB = sqlite?.DatabaseSync ?? null;
1704
+ }
1139
1705
  } catch {
1140
1706
  }
1141
1707
  var DISK_MAGIC = Buffer.from([68, 84, 73, 69, 82, 86, 49, 0]);
1142
1708
  var DISK_MAGIC_V2 = Buffer.from([68, 84, 73, 69, 82, 86, 50, 0]);
1143
1709
  var V2_HEADER_LEN = 16;
1144
1710
  var DISK_TIER_VERSION = 1;
1711
+ function resolveDefaultDiskDir(namespace, logger) {
1712
+ const ns = namespace?.trim() ?? "";
1713
+ const nsDir = ns ? `tricache-disk-${ns}` : "tricache-disk";
1714
+ if (process.platform === "linux") {
1715
+ const shmPath = "/dev/shm";
1716
+ try {
1717
+ fs.accessSync(shmPath, fs.constants.W_OK | fs.constants.R_OK);
1718
+ if (typeof fs.statfsSync === "function") {
1719
+ const stats = fs.statfsSync(shmPath);
1720
+ const totalBytes = Number(stats.blocks) * Number(stats.bsize);
1721
+ const freeBytes = Number(stats.bavail) * Number(stats.bsize);
1722
+ if (totalBytes >= 256 * 1024 * 1024 && freeBytes >= 128 * 1024 * 1024) {
1723
+ const targetDir = path.join(shmPath, nsDir);
1724
+ logger?.info?.("DiskTier: Targeting Linux /dev/shm tmpfs for off-heap storage", {
1725
+ path: targetDir,
1726
+ totalBytes,
1727
+ freeBytes
1728
+ });
1729
+ return { dir: targetDir, isShm: true };
1730
+ } else {
1731
+ logger?.info?.("DiskTier: /dev/shm capacity or free space insufficient (<256MB total or <128MB free); falling back to tmpdir", {
1732
+ totalBytes,
1733
+ freeBytes
1734
+ });
1735
+ }
1736
+ }
1737
+ } catch (err) {
1738
+ logger?.debug?.("DiskTier: /dev/shm not usable, falling back to tmpdir", {
1739
+ error: err.message
1740
+ });
1741
+ }
1742
+ }
1743
+ return { dir: path.join(os2.tmpdir(), nsDir), isShm: false };
1744
+ }
1145
1745
  var DiskTier = class {
1146
1746
  opts;
1747
+ codec;
1748
+ diskQueue;
1147
1749
  dirReady = false;
1148
1750
  diskUsageBytes = 0;
1149
1751
  usageCounted = false;
@@ -1151,6 +1753,14 @@ var DiskTier = class {
1151
1753
  // maintained in-memory; avoids walkCacheFiles() in stats
1152
1754
  /** Next bucket index (0–255) for the staggered janitor wheel. */
1153
1755
  _nextJanitorBucket = 0;
1756
+ // ── High-watermark pruning & host volume health state ─────────────────────
1757
+ _isPruning = false;
1758
+ _pruneRounds = 0;
1759
+ _entriesPruned = 0;
1760
+ _spillsShedTotal = 0;
1761
+ _hostVolumeLowSpace = false;
1762
+ _hostVolumeLowSpacePauses = 0;
1763
+ _writeCounter = 0;
1154
1764
  // ── SQLite metadata index (optional, requires node:sqlite) ───────────────
1155
1765
  _db = null;
1156
1766
  _stmtInsert = null;
@@ -1165,8 +1775,19 @@ var DiskTier = class {
1165
1775
  // DELETE expired rows
1166
1776
  _stmtStats = null;
1167
1777
  // COUNT + SUM(size)
1778
+ _stmtPruneChunk = null;
1779
+ // SELECT chunk for watermark pruning
1168
1780
  constructor(opts) {
1169
1781
  this.opts = opts;
1782
+ this.codec = opts.codec ?? defaultCodec;
1783
+ const defaultConcurrent = Math.min(4, Math.max(1, Math.floor((os2?.availableParallelism?.() ?? 4) / 4)));
1784
+ this.diskQueue = new BoundedDiskQueue(
1785
+ opts.diskMaxConcurrentWrites ?? defaultConcurrent,
1786
+ opts.diskMaxPendingWrites ?? 512,
1787
+ opts.diskWriteTimeoutMs ?? 500,
1788
+ opts.diskCircuitBreakerThreshold ?? 5,
1789
+ opts.diskCircuitBreakerCooldownMs ?? 5e3
1790
+ );
1170
1791
  }
1171
1792
  // ── Helpers ───────────────────────────────────────────────────────────────
1172
1793
  ensureDir() {
@@ -1201,15 +1822,30 @@ var DiskTier = class {
1201
1822
  PRAGMA synchronous = NORMAL;
1202
1823
  PRAGMA temp_store = MEMORY;
1203
1824
  CREATE TABLE IF NOT EXISTS meta (
1204
- key_hash TEXT PRIMARY KEY,
1205
- file_path TEXT NOT NULL,
1206
- expires_at INTEGER NOT NULL,
1207
- size INTEGER NOT NULL DEFAULT 0
1825
+ key_hash TEXT PRIMARY KEY,
1826
+ file_path TEXT NOT NULL,
1827
+ expires_at INTEGER NOT NULL,
1828
+ size INTEGER NOT NULL DEFAULT 0,
1829
+ priority INTEGER NOT NULL DEFAULT 2,
1830
+ last_accessed_at INTEGER NOT NULL DEFAULT 0
1208
1831
  );
1209
1832
  CREATE INDEX IF NOT EXISTS idx_expires ON meta (expires_at);
1833
+ CREATE INDEX IF NOT EXISTS idx_priority_access ON meta (priority ASC, last_accessed_at ASC);
1210
1834
  `);
1835
+ try {
1836
+ this._db.exec("ALTER TABLE meta ADD COLUMN priority INTEGER NOT NULL DEFAULT 2;");
1837
+ } catch {
1838
+ }
1839
+ try {
1840
+ this._db.exec("ALTER TABLE meta ADD COLUMN last_accessed_at INTEGER NOT NULL DEFAULT 0;");
1841
+ } catch {
1842
+ }
1843
+ try {
1844
+ this._db.exec("CREATE INDEX IF NOT EXISTS idx_priority_access ON meta (priority ASC, last_accessed_at ASC);");
1845
+ } catch {
1846
+ }
1211
1847
  this._stmtInsert = this._db.prepare(
1212
- "INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size) VALUES (?,?,?,?)"
1848
+ "INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size, priority, last_accessed_at) VALUES (?,?,?,?,?,?)"
1213
1849
  );
1214
1850
  this._stmtSelect = this._db.prepare(
1215
1851
  "SELECT file_path, expires_at FROM meta WHERE key_hash = ?"
@@ -1222,13 +1858,16 @@ var DiskTier = class {
1222
1858
  this._stmtStats = this._db.prepare(
1223
1859
  "SELECT COUNT(*) AS cnt, COALESCE(SUM(size), 0) AS bytes FROM meta"
1224
1860
  );
1861
+ this._stmtPruneChunk = this._db.prepare(
1862
+ "SELECT key_hash, file_path, size FROM meta ORDER BY priority ASC, last_accessed_at ASC LIMIT 500"
1863
+ );
1225
1864
  const row = this._stmtStats.get();
1226
1865
  this.fileCount = row.cnt;
1227
1866
  this.diskUsageBytes = row.bytes;
1228
1867
  this.usageCounted = true;
1229
1868
  this.opts.logger.debug("DiskTier: SQLite index ready", { entries: row.cnt });
1230
1869
  } catch (err) {
1231
- this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
1870
+ this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = this._stmtPruneChunk = null;
1232
1871
  this.opts.logger.warn("DiskTier: SQLite init failed, using file-only mode", {
1233
1872
  error: err.message
1234
1873
  });
@@ -1323,7 +1962,7 @@ var DiskTier = class {
1323
1962
  return results;
1324
1963
  }
1325
1964
  isForbidden(key) {
1326
- return this.opts.forbiddenPrefixes.some((p) => key.startsWith(p));
1965
+ return this.opts.forbiddenPrefixes?.some((p) => key.startsWith(p)) ?? false;
1327
1966
  }
1328
1967
  encrypt(data) {
1329
1968
  if (!this.opts.encryption) return data;
@@ -1375,7 +2014,16 @@ var DiskTier = class {
1375
2014
  this.ensureDir();
1376
2015
  if (!this.dirReady) return;
1377
2016
  this.ensureUsageCounted();
1378
- if (this.diskUsageBytes >= this.opts.maxBytes) return;
2017
+ if (++this._writeCounter % 2e3 === 0) {
2018
+ this.checkHostVolumeHealth();
2019
+ }
2020
+ if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes >= this.opts.maxBytes) {
2021
+ this._spillsShedTotal++;
2022
+ return;
2023
+ }
2024
+ if (this.diskUsageBytes >= this.opts.maxBytes * 0.8 && !this._isPruning) {
2025
+ void this.triggerChunkedPrune();
2026
+ }
1379
2027
  let final;
1380
2028
  try {
1381
2029
  const payload = {
@@ -1387,7 +2035,7 @@ var DiskTier = class {
1387
2035
  },
1388
2036
  writtenAt: Date.now()
1389
2037
  };
1390
- const packed = pack2(payload);
2038
+ const packed = this.codec.encode(payload);
1391
2039
  if (packed.length > this.opts.entryMaxBytes) return;
1392
2040
  let toEncrypt = packed;
1393
2041
  if (this.opts.compression && this.opts.compression !== "none" && packed.length > (this.opts.compressionThresholdBytes ?? 1024)) {
@@ -1403,39 +2051,52 @@ var DiskTier = class {
1403
2051
  }
1404
2052
  const hash = this.keyToHash(key);
1405
2053
  const filePath = this.hashToWritePath(hash, entry.expiresAt);
1406
- const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
2054
+ const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${crypto.randomBytes(6).toString("hex")}.tmp`;
1407
2055
  this.diskUsageBytes += final.length;
1408
2056
  this.fileCount++;
1409
- try {
1410
- await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
1411
- await fs.promises.writeFile(tmpPath, final, { mode: 384 });
2057
+ if (this.diskUsageBytes >= this.opts.maxBytes * 0.8 && !this._isPruning) {
2058
+ void this.triggerChunkedPrune();
2059
+ }
2060
+ const result = await this.diskQueue.schedule(async () => {
1412
2061
  try {
1413
- await fs.promises.rename(tmpPath, filePath);
1414
- } catch (renameErr) {
1415
- const code = renameErr?.code;
1416
- if (code === "EBUSY" || code === "EPERM") {
1417
- await new Promise((resolve) => setTimeout(resolve, 5));
2062
+ await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
2063
+ await fs.promises.writeFile(tmpPath, final, { mode: 384 });
2064
+ try {
1418
2065
  await fs.promises.rename(tmpPath, filePath);
1419
- } else {
1420
- throw renameErr;
2066
+ } catch (renameErr) {
2067
+ const code = renameErr?.code;
2068
+ if (code === "EBUSY" || code === "EPERM") {
2069
+ await new Promise((resolve) => setTimeout(resolve, 5));
2070
+ await fs.promises.rename(tmpPath, filePath);
2071
+ } else {
2072
+ throw renameErr;
2073
+ }
1421
2074
  }
2075
+ if (this._db) {
2076
+ const priority = typeof entry.priority === "number" ? entry.priority : 2;
2077
+ const lastAccess = typeof entry.lastAccess === "number" ? entry.lastAccess : Date.now();
2078
+ this._stmtInsert.run(hash, filePath, entry.expiresAt, final.length, priority, lastAccess);
2079
+ }
2080
+ this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
2081
+ return true;
2082
+ } catch (err) {
2083
+ try {
2084
+ await fs.promises.unlink(tmpPath);
2085
+ } catch {
2086
+ }
2087
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
2088
+ this.fileCount = Math.max(0, this.fileCount - 1);
2089
+ if (this._db) try {
2090
+ this._stmtDelete.run(hash);
2091
+ } catch {
2092
+ }
2093
+ this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
2094
+ throw err;
1422
2095
  }
1423
- if (this._db) {
1424
- this._stmtInsert.run(hash, filePath, entry.expiresAt, final.length);
1425
- }
1426
- this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
1427
- } catch (err) {
1428
- try {
1429
- await fs.promises.unlink(tmpPath);
1430
- } catch {
1431
- }
2096
+ });
2097
+ if (result === null) {
1432
2098
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
1433
2099
  this.fileCount = Math.max(0, this.fileCount - 1);
1434
- if (this._db) try {
1435
- this._stmtDelete.run(hash);
1436
- } catch {
1437
- }
1438
- this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
1439
2100
  }
1440
2101
  }
1441
2102
  /** Load a key from disk, or return null on miss/expiry/corruption. */
@@ -1513,7 +2174,7 @@ var DiskTier = class {
1513
2174
  }
1514
2175
  }
1515
2176
  const uncompressed = decompressWithHeader(decrypted, this.opts.compression ?? "brotli");
1516
- const payload = unpack2(uncompressed);
2177
+ const payload = this.codec.decode(uncompressed);
1517
2178
  if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
1518
2179
  if (payload.entry.expiresAt <= Date.now()) return null;
1519
2180
  const entry = payload.entry;
@@ -1636,7 +2297,7 @@ var DiskTier = class {
1636
2297
  purged++;
1637
2298
  continue;
1638
2299
  }
1639
- const payload = unpack2(dec);
2300
+ const payload = this.codec.decode(dec);
1640
2301
  if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
1641
2302
  fs.unlinkSync(filePath);
1642
2303
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
@@ -1800,7 +2461,7 @@ var DiskTier = class {
1800
2461
  purged++;
1801
2462
  continue;
1802
2463
  }
1803
- const payload = unpack2(dec);
2464
+ const payload = this.codec.decode(dec);
1804
2465
  if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
1805
2466
  fs.unlinkSync(filePath);
1806
2467
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
@@ -1839,29 +2500,915 @@ var DiskTier = class {
1839
2500
  }
1840
2501
  return cleared;
1841
2502
  }
1842
- get stats() {
1843
- if (this._db) {
1844
- const row = this._stmtStats.get();
1845
- this.fileCount = row.cnt;
1846
- this.diskUsageBytes = row.bytes;
2503
+ /**
2504
+ * Proactively checks host volume free space via statfsSync.
2505
+ * If free space on the volume drops below 10%, pauses spills to prevent
2506
+ * Kubernetes pod eviction (DiskPressure / EphemeralStorageExceeded).
2507
+ */
2508
+ checkHostVolumeHealth() {
2509
+ try {
2510
+ if (typeof fs.statfsSync === "function") {
2511
+ const stats = fs.statfsSync(this.opts.dir);
2512
+ const total = Number(stats.blocks);
2513
+ const avail = Number(stats.bavail);
2514
+ if (total > 0) {
2515
+ const freeRatio = avail / total;
2516
+ if (freeRatio < 0.1) {
2517
+ if (!this._hostVolumeLowSpace) {
2518
+ this._hostVolumeLowSpace = true;
2519
+ this._hostVolumeLowSpacePauses++;
2520
+ this.opts.logger.warn(
2521
+ "DiskTier: host volume has <10% free space. Pausing disk cache spills to prevent Kubernetes eviction.",
2522
+ { dir: this.opts.dir, freePct: Number((freeRatio * 100).toFixed(1)) }
2523
+ );
2524
+ }
2525
+ return false;
2526
+ } else if (this._hostVolumeLowSpace) {
2527
+ this._hostVolumeLowSpace = false;
2528
+ this.opts.logger.info(
2529
+ "DiskTier: host volume space recovered (>=10% free). Resuming disk cache spills.",
2530
+ { dir: this.opts.dir, freePct: Number((freeRatio * 100).toFixed(1)) }
2531
+ );
2532
+ return true;
2533
+ }
2534
+ }
2535
+ }
2536
+ } catch {
1847
2537
  }
1848
- return { files: this.fileCount, sizeKB: Math.round(this.diskUsageBytes / 1024), maxKB: Math.round(this.opts.maxBytes / 1024) };
1849
- }
1850
- /** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
1851
- get indexMode() {
1852
- return this._db ? "sqlite" : "file-only";
2538
+ return true;
1853
2539
  }
1854
- /** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
2540
+ /**
2541
+ * Non-blocking chunked pruning:
2542
+ * Evicts oldest entries in 500-entry chunks down to 60% watermark,
2543
+ * yielding to the event loop via setImmediate between chunks.
2544
+ */
2545
+ async triggerChunkedPrune() {
2546
+ if (this._isPruning) return 0;
2547
+ this._isPruning = true;
2548
+ this._pruneRounds++;
2549
+ let prunedInThisRound = 0;
2550
+ try {
2551
+ this.ensureUsageCounted();
2552
+ const targetBytes = Math.floor(this.opts.maxBytes * 0.6);
2553
+ if (this._db && this._stmtPruneChunk) {
2554
+ while (this.diskUsageBytes > targetBytes) {
2555
+ const rows = this._stmtPruneChunk.all();
2556
+ if (!rows || rows.length === 0) break;
2557
+ for (const row of rows) {
2558
+ try {
2559
+ fs.unlinkSync(row.file_path);
2560
+ } catch {
2561
+ }
2562
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
2563
+ this.fileCount = Math.max(0, this.fileCount - 1);
2564
+ this._entriesPruned++;
2565
+ prunedInThisRound++;
2566
+ try {
2567
+ this._stmtDelete.run(row.key_hash);
2568
+ } catch {
2569
+ }
2570
+ if (this.diskUsageBytes <= targetBytes) break;
2571
+ }
2572
+ if (this.diskUsageBytes > targetBytes) {
2573
+ await new Promise((resolve) => setImmediate(resolve));
2574
+ }
2575
+ }
2576
+ } else {
2577
+ while (this.diskUsageBytes > targetBytes) {
2578
+ const files = this.walkCacheFiles();
2579
+ if (files.length === 0) break;
2580
+ const chunk = files.slice(0, 500);
2581
+ for (const filePath of chunk) {
2582
+ try {
2583
+ const stat = fs.statSync(filePath);
2584
+ fs.unlinkSync(filePath);
2585
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
2586
+ this.fileCount = Math.max(0, this.fileCount - 1);
2587
+ this._entriesPruned++;
2588
+ prunedInThisRound++;
2589
+ } catch {
2590
+ }
2591
+ if (this.diskUsageBytes <= targetBytes) break;
2592
+ }
2593
+ if (this.diskUsageBytes > targetBytes) {
2594
+ await new Promise((resolve) => setImmediate(resolve));
2595
+ }
2596
+ }
2597
+ }
2598
+ } finally {
2599
+ this._isPruning = false;
2600
+ }
2601
+ return prunedInThisRound;
2602
+ }
2603
+ get isPruning() {
2604
+ return this._isPruning;
2605
+ }
2606
+ get hostVolumeLowSpace() {
2607
+ return this._hostVolumeLowSpace;
2608
+ }
2609
+ get spillsShedTotal() {
2610
+ return this._spillsShedTotal;
2611
+ }
2612
+ getPruningStats() {
2613
+ return {
2614
+ active: this._isPruning,
2615
+ pruneRounds: this._pruneRounds,
2616
+ entriesPruned: this._entriesPruned,
2617
+ spillsShedTotal: this._spillsShedTotal,
2618
+ hostVolumeLowSpacePauses: this._hostVolumeLowSpacePauses
2619
+ };
2620
+ }
2621
+ get stats() {
2622
+ if (this._db) {
2623
+ const row = this._stmtStats.get();
2624
+ this.fileCount = row.cnt;
2625
+ this.diskUsageBytes = row.bytes;
2626
+ }
2627
+ return {
2628
+ files: this.fileCount,
2629
+ sizeKB: Math.round(this.diskUsageBytes / 1024),
2630
+ maxKB: Math.round(this.opts.maxBytes / 1024),
2631
+ backpressure: this.diskQueue.getStats(),
2632
+ pruning: this.getPruningStats()
2633
+ };
2634
+ }
2635
+ /** Direct access to the bounded write queue for chaos diagnostics and canary controls. */
2636
+ get backpressure() {
2637
+ return this.diskQueue;
2638
+ }
2639
+ /** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
2640
+ get indexMode() {
2641
+ return this._db ? "sqlite" : "file-only";
2642
+ }
2643
+ /** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
1855
2644
  close() {
1856
2645
  if (this._db) {
1857
2646
  try {
1858
2647
  this._db.close();
1859
2648
  } catch {
1860
2649
  }
1861
- this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
2650
+ this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = this._stmtPruneChunk = null;
2651
+ }
2652
+ }
2653
+ };
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;
1862
2701
  }
1863
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
+ }
1864
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
+ }
1865
3412
 
1866
3413
  // src/cache-service.ts
1867
3414
  var LUA_COMPARE_AND_DELETE = `
@@ -1907,7 +3454,7 @@ var L2CircuitBreaker = class {
1907
3454
  cooldownMs;
1908
3455
  state = 0 /* CLOSED */;
1909
3456
  failures = 0;
1910
- openedAt = 0;
3457
+ openedAt = performance.now();
1911
3458
  /** True while the single permitted HALF_OPEN probe is in flight. */
1912
3459
  probing = false;
1913
3460
  /**
@@ -1923,7 +3470,8 @@ var L2CircuitBreaker = class {
1923
3470
  this.probing = true;
1924
3471
  return true;
1925
3472
  }
1926
- if (Date.now() - this.openedAt >= this.cooldownMs) {
3473
+ const now = this.openedAt > 1e12 ? Date.now() : performance.now();
3474
+ if (now - this.openedAt >= this.cooldownMs) {
1927
3475
  this.state = 2 /* HALF_OPEN */;
1928
3476
  this.probing = true;
1929
3477
  return true;
@@ -1942,7 +3490,7 @@ var L2CircuitBreaker = class {
1942
3490
  this.probing = false;
1943
3491
  if (this.state === 2 /* HALF_OPEN */ || this.failures >= this.threshold) {
1944
3492
  this.state = 1 /* OPEN */;
1945
- this.openedAt = Date.now();
3493
+ this.openedAt = performance.now();
1946
3494
  this.failures = 0;
1947
3495
  }
1948
3496
  }
@@ -2059,9 +3607,86 @@ function detectServerlessRuntime() {
2059
3607
  if (process.env["VERCEL"]) return "Vercel";
2060
3608
  return null;
2061
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
+ }
2062
3686
  var CacheService = class _CacheService {
2063
3687
  logger;
2064
3688
  enc;
3689
+ codec;
2065
3690
  l1;
2066
3691
  disk;
2067
3692
  /** When true, all disk-tier and snapshot operations are skipped. */
@@ -2073,6 +3698,8 @@ var CacheService = class _CacheService {
2073
3698
  _namespace;
2074
3699
  /** Pre-computed once — disableRedis and redisHost never change after construction. */
2075
3700
  _redisDisabled;
3701
+ watchdog;
3702
+ pipeliner = null;
2076
3703
  inflight = /* @__PURE__ */ new Map();
2077
3704
  revalidating = /* @__PURE__ */ new Set();
2078
3705
  _l1Counters = /* @__PURE__ */ new Map();
@@ -2098,6 +3725,7 @@ var CacheService = class _CacheService {
2098
3725
  diskJanitorInterval = null;
2099
3726
  oomInterval = null;
2100
3727
  metricsInterval = null;
3728
+ remoteSnapshotInterval = null;
2101
3729
  _shutdownHandler = null;
2102
3730
  latencyTracker = null;
2103
3731
  instanceId;
@@ -2107,8 +3735,11 @@ var CacheService = class _CacheService {
2107
3735
  streamClient = null;
2108
3736
  _lastStreamId = "$";
2109
3737
  _destroyed = false;
3738
+ _ipcServer;
2110
3739
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
2111
3740
  _subDisconnectedAt = null;
3741
+ /** Deduplication ring buffer for incoming and outgoing cross-region invalidations (loop prevention) */
3742
+ _seenCrossRegionEvents = /* @__PURE__ */ new Map();
2112
3743
  counters = {
2113
3744
  gets: 0,
2114
3745
  l1Hits: 0,
@@ -2133,7 +3764,16 @@ var CacheService = class _CacheService {
2133
3764
  singletonDivergences: 0,
2134
3765
  startedAt: Date.now(),
2135
3766
  bloomChecks: 0,
2136
- 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
2137
3777
  };
2138
3778
  /** One-time guard so the in-process increment() fallback warning fires only once. */
2139
3779
  _incrementFallbackWarned = false;
@@ -2156,16 +3796,14 @@ var CacheService = class _CacheService {
2156
3796
  this.opts = {
2157
3797
  namespace: ns,
2158
3798
  logger,
2159
- l1MaxBytes: options.l1MaxBytes ?? 200 * 1024 * 1024,
3799
+ l1MaxBytes: options.l1MaxBytes ?? resolveAutonomousL1MaxBytes(),
2160
3800
  l1MaxEntries: options.l1MaxEntries ?? 2e3,
2161
3801
  categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...options.categoryLimits },
2162
3802
  forbiddenSnapshotPrefixes: forbiddenPrefixes,
2163
3803
  // Namespace-isolated defaults: separate dir / snapshot per namespace so
2164
3804
  // two instances with different namespaces never share cache files.
2165
- diskCacheDir: options.diskCacheDir ?? path2.join(
2166
- os2.tmpdir(),
2167
- ns ? `tricache-disk-${ns}` : "tricache-disk"
2168
- ),
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,
2169
3807
  diskMaxBytes: options.diskMaxBytes ?? 500 * 1024 * 1024,
2170
3808
  diskEntryMaxBytes: options.diskEntryMaxBytes ?? 10 * 1024 * 1024,
2171
3809
  redisHost: options.redisHost ?? process.env.REDIS_HOST ?? "",
@@ -2173,14 +3811,14 @@ var CacheService = class _CacheService {
2173
3811
  redisTls: options.redisTls ?? process.env.NODE_ENV === "production",
2174
3812
  disableRedis: options.disableRedis ?? (() => {
2175
3813
  const explicitConfig = Boolean(
2176
- options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
3814
+ options.redisClient || options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
2177
3815
  );
2178
3816
  return !explicitConfig && process.env.NODE_ENV !== "production";
2179
3817
  })(),
2180
3818
  encryptionKey: encKeyRaw,
2181
3819
  encryptionMode: options.encryptionMode,
2182
- snapshotPath: options.snapshotPath ?? path2.join(
2183
- os2.tmpdir(),
3820
+ snapshotPath: options.snapshotPath ?? path3.join(
3821
+ os3.tmpdir(),
2184
3822
  ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
2185
3823
  ),
2186
3824
  snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
@@ -2228,8 +3866,35 @@ var CacheService = class _CacheService {
2228
3866
  backplaneMode: options.backplaneMode ?? "pubsub",
2229
3867
  backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
2230
3868
  backplaneStreamBlockMs: options.backplaneStreamBlockMs ?? 2e3,
2231
- 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
2232
3892
  };
3893
+ this.codec = new CacheCodec({
3894
+ useToJSON: this.opts.serializeToJSON,
3895
+ useRecords: true,
3896
+ moreTypes: true
3897
+ });
2233
3898
  const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
2234
3899
  const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
2235
3900
  this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
@@ -2260,15 +3925,33 @@ var CacheService = class _CacheService {
2260
3925
  encryption: this.enc.isEnabled ? this.enc : null,
2261
3926
  compression: this.opts.compression,
2262
3927
  compressionThresholdBytes: this.opts.compressionThresholdBytes,
2263
- 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
2264
3935
  });
2265
3936
  this._namespace = ns;
2266
- 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
+ });
2267
3948
  this.l1 = new SmartMemoryCache({
2268
3949
  maxBytes: this.opts.l1MaxBytes,
2269
3950
  maxEntries: this.opts.l1MaxEntries,
2270
3951
  categories: this.opts.categoryLimits,
2271
3952
  evictionWatermark: this.opts.l1EvictionWatermark,
3953
+ admissionPolicy: this.opts.l1AdmissionPolicy,
3954
+ codec: this.codec,
2272
3955
  diskSpill: (key, entry) => {
2273
3956
  if (this._diskDisabled) return;
2274
3957
  setImmediate(() => {
@@ -2283,10 +3966,9 @@ var CacheService = class _CacheService {
2283
3966
  if (!this._diskDisabled) this.loadSnapshot();
2284
3967
  }
2285
3968
  this._shutdownHandler = () => {
2286
- if (!this._diskDisabled) this.writeSnapshot();
3969
+ this._triggerShutdown();
2287
3970
  };
2288
- process.once("SIGTERM", this._shutdownHandler);
2289
- process.once("SIGINT", this._shutdownHandler);
3971
+ ProcessTerminationBus.register(this);
2290
3972
  if (this.opts.workerThreads) {
2291
3973
  try {
2292
3974
  const encRef = this.enc.toWorkerInit();
@@ -2326,7 +4008,7 @@ var CacheService = class _CacheService {
2326
4008
  }
2327
4009
  if (this.opts.oomProtection) {
2328
4010
  this.oomInterval = setInterval(() => {
2329
- const heap = v8.getHeapStatistics();
4011
+ const heap = v82.getHeapStatistics();
2330
4012
  const used = heap.used_heap_size / heap.heap_size_limit;
2331
4013
  if (used >= this.opts.oomHeapThreshold) {
2332
4014
  const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
@@ -2350,12 +4032,25 @@ var CacheService = class _CacheService {
2350
4032
  }, this.opts.metricsIntervalMs);
2351
4033
  if (this.metricsInterval.unref) this.metricsInterval.unref();
2352
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
+ }
2353
4041
  this.instanceId = crypto2.randomBytes(8).toString("hex");
2354
4042
  this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
2355
4043
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
2356
4044
  this.initBackplane();
4045
+ const startupPromises = [];
4046
+ if (this.opts.remoteSnapshot) {
4047
+ startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
4048
+ }
2357
4049
  if (this.opts.warmKeys) {
2358
- this._readyPromise = this.warmFromL2(this.opts.warmKeys).then(() => void 0);
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);
2359
4054
  }
2360
4055
  if (this.opts.meter) {
2361
4056
  this._initOtelMetrics(this.opts.meter);
@@ -2376,8 +4071,71 @@ var CacheService = class _CacheService {
2376
4071
  }
2377
4072
  });
2378
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);
2379
4138
  }
2380
- // ── Singleton factory ─────────────────────────────────────────────────────
2381
4139
  /**
2382
4140
  * Get (or create) the process-level singleton CacheService instance.
2383
4141
  *
@@ -2471,7 +4229,9 @@ var CacheService = class _CacheService {
2471
4229
  frozen: o.frozen,
2472
4230
  adaptiveTtl: o.adaptiveTtl,
2473
4231
  invalidationBackplane: o.invalidationBackplane,
2474
- strictSingleton: o.strictSingleton
4232
+ strictSingleton: o.strictSingleton,
4233
+ remoteSnapshot: o.remoteSnapshot,
4234
+ crossRegion: o.crossRegion
2475
4235
  };
2476
4236
  }
2477
4237
  /**
@@ -2530,15 +4290,30 @@ var CacheService = class _CacheService {
2530
4290
  setStatus() {
2531
4291
  return this;
2532
4292
  },
4293
+ recordException() {
4294
+ return this;
4295
+ },
2533
4296
  end() {
2534
4297
  }
2535
4298
  };
2536
4299
  /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
2537
- _startSpan(name) {
2538
- if (this.opts.tracer) return this.opts.tracer.startSpan(name);
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
+ }
2539
4308
  return _CacheService._nullSpan;
2540
4309
  }
2541
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
+ }
2542
4317
  if (this.opts.redisClusterNodes?.length) {
2543
4318
  return new RedisCluster(this.opts.redisClusterNodes, {
2544
4319
  redisOptions: {
@@ -2772,7 +4547,13 @@ var CacheService = class _CacheService {
2772
4547
  this.logger.warn("Backplane: malformed message JSON parse failed");
2773
4548
  }
2774
4549
  }
2775
- 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
+ }
2776
4557
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
2777
4558
  try {
2778
4559
  const client = await this.getRedis();
@@ -2814,7 +4595,80 @@ var CacheService = class _CacheService {
2814
4595
  } catch {
2815
4596
  }
2816
4597
  }
2817
- _setLocalTagVersion(tag, version, now = Date.now()) {
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()) {
2818
4672
  const existing = this.tagVersions.get(tag)?.version ?? 0;
2819
4673
  const finalVersion = Math.max(existing, version);
2820
4674
  if (this.tagVersions.size >= 1e4 && !this.tagVersions.has(tag)) {
@@ -2824,7 +4678,7 @@ var CacheService = class _CacheService {
2824
4678
  this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
2825
4679
  }
2826
4680
  async _getTagVersion(tag) {
2827
- const now = Date.now();
4681
+ const now = performance.now();
2828
4682
  const local = this.tagVersions.get(tag);
2829
4683
  if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
2830
4684
  return local.version;
@@ -2910,13 +4764,25 @@ var CacheService = class _CacheService {
2910
4764
  stream.on("error", reject);
2911
4765
  })
2912
4766
  ));
2913
- } else {
4767
+ } else if (typeof client.scanStream === "function") {
2914
4768
  await new Promise((resolve, reject) => {
2915
4769
  const stream = client.scanStream({ match: pattern, count: 100 });
2916
4770
  stream.on("data", (chunk) => keys.push(...chunk));
2917
4771
  stream.on("end", resolve);
2918
4772
  stream.on("error", reject);
2919
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");
2920
4786
  }
2921
4787
  return keys;
2922
4788
  }
@@ -2933,6 +4799,19 @@ var CacheService = class _CacheService {
2933
4799
  if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
2934
4800
  if (this.redis) return this.redis;
2935
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
+ }
2936
4815
  this.redisConnecting = (async () => {
2937
4816
  try {
2938
4817
  let client;
@@ -2941,6 +4820,7 @@ var CacheService = class _CacheService {
2941
4820
  redisOptions: {
2942
4821
  tls: this.opts.redisTls ? {} : void 0,
2943
4822
  connectTimeout: 1e4,
4823
+ commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
2944
4824
  maxRetriesPerRequest: 3,
2945
4825
  keepAlive: 3e4,
2946
4826
  ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
@@ -2961,6 +4841,7 @@ var CacheService = class _CacheService {
2961
4841
  name: this.opts.redisSentinel.name,
2962
4842
  tls: this.opts.redisTls ? {} : void 0,
2963
4843
  connectTimeout: 1e4,
4844
+ commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
2964
4845
  lazyConnect: false,
2965
4846
  maxRetriesPerRequest: 3,
2966
4847
  enableAutoPipelining: true,
@@ -2980,6 +4861,7 @@ var CacheService = class _CacheService {
2980
4861
  port: this.opts.redisPort,
2981
4862
  tls: this.opts.redisTls ? {} : void 0,
2982
4863
  connectTimeout: 1e4,
4864
+ commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
2983
4865
  lazyConnect: false,
2984
4866
  maxRetriesPerRequest: 3,
2985
4867
  enableAutoPipelining: true,
@@ -3005,6 +4887,10 @@ var CacheService = class _CacheService {
3005
4887
  });
3006
4888
  this.cb.onSuccess();
3007
4889
  this.redis = client;
4890
+ this.pipeliner = new AutoPipeliner(client, {
4891
+ enabled: this.opts.autoPipeline,
4892
+ maxBatchSize: this.opts.maxPipelineBatchSize
4893
+ });
3008
4894
  this.redisConnecting = null;
3009
4895
  return client;
3010
4896
  } catch (err) {
@@ -3017,16 +4903,22 @@ var CacheService = class _CacheService {
3017
4903
  return this.redisConnecting;
3018
4904
  }
3019
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
+ */
3020
4912
  writeSnapshot(altPath) {
3021
4913
  try {
3022
4914
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
3023
4915
  if (entries.length === 0) return;
3024
4916
  const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
3025
- const packed = pack3(payload);
4917
+ const packed = this.codec.encode(payload);
3026
4918
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
3027
4919
  const dest = altPath ?? this.opts.snapshotPath;
3028
- fs2.mkdirSync(path2.dirname(dest), { recursive: true });
3029
- fs2.writeFileSync(dest, final, { mode: 384 });
4920
+ fs4.mkdirSync(path3.dirname(dest), { recursive: true });
4921
+ fs4.writeFileSync(dest, final, { mode: 384 });
3030
4922
  this.logger.info("Cache snapshot written", {
3031
4923
  path: dest,
3032
4924
  entries: entries.length,
@@ -3037,18 +4929,24 @@ var CacheService = class _CacheService {
3037
4929
  this.logger.warn("Cache snapshot write failed", { error: err.message });
3038
4930
  }
3039
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
+ */
3040
4938
  loadSnapshot() {
3041
4939
  const snapshotPath = this.opts.snapshotPath;
3042
4940
  try {
3043
- if (!fs2.existsSync(snapshotPath)) return;
3044
- const stat = fs2.statSync(snapshotPath);
4941
+ if (!fs4.existsSync(snapshotPath)) return;
4942
+ const stat = fs4.statSync(snapshotPath);
3045
4943
  if (stat.size > SNAPSHOT_MAX_FILE_BYTES) {
3046
4944
  this.logger.warn("Snapshot rejected: exceeds size limit", { sizeBytes: stat.size });
3047
- fs2.unlinkSync(snapshotPath);
4945
+ fs4.unlinkSync(snapshotPath);
3048
4946
  return;
3049
4947
  }
3050
- const raw = fs2.readFileSync(snapshotPath);
3051
- fs2.unlinkSync(snapshotPath);
4948
+ const raw = fs4.readFileSync(snapshotPath);
4949
+ fs4.unlinkSync(snapshotPath);
3052
4950
  let buf;
3053
4951
  try {
3054
4952
  buf = this.enc.decryptBuffer(raw);
@@ -3056,13 +4954,25 @@ var CacheService = class _CacheService {
3056
4954
  this.logger.warn("Snapshot rejected: decryption failed", { error: e.message });
3057
4955
  return;
3058
4956
  }
3059
- const snapshot = unpack3(buf);
4957
+ const snapshot = this.codec.decode(buf);
3060
4958
  if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
3061
4959
  this.logger.warn("Snapshot rejected: version mismatch", { got: snapshot?.version });
3062
4960
  return;
3063
4961
  }
3064
- const ageMs = Date.now() - (snapshot.writtenAt ?? 0);
3065
- if (ageMs > this.opts.snapshotMaxAgeMs || ageMs < 0) {
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) {
3066
4976
  this.logger.warn("Snapshot rejected: too old", { ageMinutes: Math.round(ageMs / 6e4) });
3067
4977
  return;
3068
4978
  }
@@ -3079,11 +4989,120 @@ var CacheService = class _CacheService {
3079
4989
  } catch (err) {
3080
4990
  this.logger.warn("Snapshot load failed \u2014 starting cold", { error: err.message });
3081
4991
  try {
3082
- fs2.unlinkSync(snapshotPath);
4992
+ fs4.unlinkSync(snapshotPath);
3083
4993
  } catch {
3084
4994
  }
3085
4995
  }
3086
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
+ }
3087
5106
  // ── Core get (L1 → L1.5 → L2 → fetch) ───────────────────────────────────
3088
5107
  /**
3089
5108
  * Get a value from cache, or fetch and cache it.
@@ -3119,9 +5138,10 @@ var CacheService = class _CacheService {
3119
5138
  if (l1Hit !== null) {
3120
5139
  let isGenerationalStale = false;
3121
5140
  if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
3122
- for (const [tag, entryVer] of Object.entries(l1Hit.tagVersions)) {
3123
- const currentVer = await this._getTagVersion(tag);
3124
- if (currentVer > entryVer) {
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]]) {
3125
5145
  isGenerationalStale = true;
3126
5146
  break;
3127
5147
  }
@@ -3166,116 +5186,140 @@ var CacheService = class _CacheService {
3166
5186
  this.counters.l1Hits++;
3167
5187
  this.opts.onHit?.(cacheKey, "l1");
3168
5188
  if (this.opts.frozen) deepFreeze(l1Hit.value);
3169
- span.setAttribute("cache.hit", "l1").end();
5189
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "memory").setAttribute("cache.hit_tier", "l1").end();
3170
5190
  return this.opts.cloneStrategy === "structuredClone" && l1Hit.value != null && typeof l1Hit.value === "object" ? structuredClone(l1Hit.value) : l1Hit.value;
3171
5191
  }
3172
5192
  }
3173
5193
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
3174
5194
  const swrGraceMs = optSwr * 1e3;
3175
5195
  const priority = optPriority ?? inferPriority(cacheKey);
3176
- if (!this._redisDisabled) {
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 () => {
3177
5204
  try {
3178
- const client = await this.getRedis();
3179
- if (this.opts.tagStrategy === "generational") {
3180
- const hashData = await client.hgetall(k);
3181
- this.cb.onSuccess();
3182
- if (hashData && hashData.d) {
3183
- let isStale = false;
3184
- let storedTagVersions = {};
3185
- if (hashData.tv) {
3186
- try {
3187
- storedTagVersions = JSON.parse(hashData.tv);
3188
- } catch {
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
+ }
3189
5224
  }
3190
- }
3191
- for (const [tag, entryVer] of Object.entries(storedTagVersions)) {
3192
- const currentVer = await this._getTagVersion(tag);
3193
- if (currentVer > entryVer) {
3194
- isStale = true;
3195
- break;
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
+ }
3196
5243
  }
3197
5244
  }
3198
- if (isStale) {
3199
- const setAtMs = parseInt(hashData.t, 10) || 0;
3200
- this._deleteIfStale(k, setAtMs);
3201
- } else {
3202
- const parsed = await this._decryptAndDeserialize(hashData.d);
3203
- this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
3204
- this.counters.l2Hits++;
3205
- this.opts.onHit?.(cacheKey, "l2");
3206
- this.logger.debug("L2 hit (Redis hash)", { cacheKey });
3207
- span.setAttribute("cache.hit", "l2").end();
3208
- if (this.opts.frozen) deepFreeze(parsed);
3209
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
3210
- }
3211
- }
3212
- } else {
3213
- const raw = await client.get(k);
3214
- this.cb.onSuccess();
3215
- if (raw) {
3216
- const parsed = await this._decryptAndDeserialize(raw);
3217
- this.l1.set(k, parsed, ttlMs, priority);
3218
- this.counters.l2Hits++;
3219
- this.opts.onHit?.(cacheKey, "l2");
3220
- this.logger.debug("L2 hit (Redis)", { cacheKey });
3221
- span.setAttribute("cache.hit", "l2").end();
3222
- if (this.opts.frozen) deepFreeze(parsed);
3223
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
3224
- }
3225
- }
3226
- } catch (err) {
3227
- this.cb.onFailure();
3228
- this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
3229
- }
3230
- }
3231
- if (!this._diskDisabled) {
3232
- const diskHit = this.disk.load(k);
3233
- if (diskHit !== null) {
3234
- let isDiskStale = false;
3235
- if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
3236
- for (const [tag, entryVer] of Object.entries(diskHit.tagVersions)) {
3237
- const currentVer = await this._getTagVersion(tag);
3238
- if (currentVer > entryVer) {
3239
- isDiskStale = true;
3240
- break;
3241
- }
3242
5245
  }
3243
5246
  }
3244
- if (isDiskStale) {
3245
- this.disk.delete(k);
3246
- } else {
3247
- const promoted = this.l1.importEntries(
3248
- [{ key: k, entry: diskHit }],
3249
- this.opts.forbiddenSnapshotPrefixes
3250
- );
3251
- if (promoted > 0) {
3252
- const l1Check = this.l1.get(k);
3253
- if (l1Check !== null) {
3254
- this.counters.diskHits++;
3255
- this.opts.onHit?.(cacheKey, "disk");
3256
- this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
3257
- span.setAttribute("cache.hit", "disk").end();
3258
- if (this.opts.frozen) deepFreeze(l1Check.value);
3259
- return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
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
+ }
3260
5302
  }
5303
+ } catch (err) {
5304
+ this.cb.onFailure();
5305
+ this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
3261
5306
  }
3262
5307
  }
3263
- }
3264
- }
3265
- span.setAttribute("cache.hit", "miss");
3266
- this.opts.onMiss?.(cacheKey);
3267
- const existing = this.inflight.get(k);
3268
- if (existing) {
3269
- this.counters.stampedes++;
3270
- this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch", { cacheKey });
3271
- span.end();
3272
- return existing;
3273
- }
3274
- const fetchPromise = (async () => {
3275
- try {
5308
+ span.setAttribute("cache.hit", false).setAttribute("cache.hit_tier", "miss");
5309
+ this.opts.onMiss?.(cacheKey);
3276
5310
  this.counters.fetches++;
3277
5311
  const fetchStart = Date.now();
3278
- const data = await fetchFn();
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
+ }
3279
5323
  const delta = Date.now() - fetchStart;
3280
5324
  const notFoundTtlMs = (optNotFoundTtl ?? this.opts.notFoundTtl) * 1e3;
3281
5325
  let effectiveTtl = data == null && notFoundTtlMs > 0 ? notFoundTtlMs : ttlMs;
@@ -3295,9 +5339,10 @@ var CacheService = class _CacheService {
3295
5339
  let activeTagVersions;
3296
5340
  if (optTags?.length) {
3297
5341
  if (this.opts.tagStrategy === "generational") {
5342
+ const vers = await Promise.all(optTags.map((tag) => this._getTagVersion(tag)));
3298
5343
  activeTagVersions = {};
3299
- for (const tag of optTags) {
3300
- activeTagVersions[tag] = await this._getTagVersion(tag);
5344
+ for (let i = 0; i < optTags.length; i++) {
5345
+ activeTagVersions[optTags[i]] = vers[i];
3301
5346
  }
3302
5347
  } else {
3303
5348
  await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
@@ -3339,8 +5384,64 @@ var CacheService = class _CacheService {
3339
5384
  span.end();
3340
5385
  }
3341
5386
  })();
3342
- this.inflight.set(k, fetchPromise);
3343
- return fetchPromise;
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
+ }
3344
5445
  }
3345
5446
  /**
3346
5447
  * Universal fetch-and-cache wrapper with an ergonomic options object.
@@ -3373,9 +5474,11 @@ var CacheService = class _CacheService {
3373
5474
  let activeTagVersions;
3374
5475
  const l1Existing = this.l1.get(cacheKey);
3375
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)));
3376
5479
  activeTagVersions = {};
3377
- for (const tag of Object.keys(l1Existing.tagVersions)) {
3378
- activeTagVersions[tag] = await this._getTagVersion(tag);
5480
+ for (let i = 0; i < tags.length; i++) {
5481
+ activeTagVersions[tags[i]] = vers[i];
3379
5482
  }
3380
5483
  }
3381
5484
  this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
@@ -3421,62 +5524,77 @@ var CacheService = class _CacheService {
3421
5524
  /** Explicitly write a value into L1 (+ L2 in production). */
3422
5525
  async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
3423
5526
  const span = this._startSpan("tricache.set");
3424
- if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
3425
- const effectiveTtlSeconds = ttlSeconds > 0 ? ttlSeconds : ttlSeconds === 0 ? INDEFINITE_TTL_SECONDS : ttlSeconds;
3426
- const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
3427
- const p = priority ?? inferPriority(cacheKey);
3428
- const k = this.nk(cacheKey);
3429
- this.counters.sets++;
3430
- let activeTagVersions;
3431
- if (opts?.tags?.length) {
3432
- if (this.opts.tagStrategy === "generational") {
3433
- activeTagVersions = {};
3434
- for (const tag of opts.tags) {
3435
- activeTagVersions[tag] = await this._getTagVersion(tag);
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);
3436
5547
  }
3437
- } else {
3438
- await this._registerTags(k, opts.tags, ttlSeconds);
3439
5548
  }
3440
- }
3441
- this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
3442
- if (opts?.dependsOn?.length) {
3443
- for (const pattern of opts.dependsOn) {
3444
- const nsPattern = this.nk(pattern);
3445
- let deps = this.dependencyIndex.get(nsPattern);
3446
- if (!deps) {
3447
- deps = /* @__PURE__ */ new Set();
3448
- this.dependencyIndex.set(nsPattern, deps);
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);
3449
5559
  }
3450
- deps.add(k);
3451
5560
  }
3452
- }
3453
- if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
3454
- try {
3455
- const client = await this.getRedis();
3456
- const s = JSON.stringify(data);
3457
- const stored = await this._serializeAndEncrypt(s);
3458
- const ttlSec = Math.ceil(ttlMs / 1e3);
3459
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
3460
- const now = Date.now();
3461
- const tx = client.multi();
3462
- tx.hset(k, {
3463
- d: stored,
3464
- t: String(now),
3465
- tv: JSON.stringify(activeTagVersions)
3466
- });
3467
- tx.expire(k, ttlSec);
3468
- await tx.exec();
3469
- } else {
3470
- await client.setex(k, ttlSec, stored);
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 });
3471
5588
  }
3472
- this.cb.onSuccess();
3473
- } catch (err) {
3474
- this.cb.onFailure();
3475
- this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
3476
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();
3477
5597
  }
3478
- void this.publishInvalidation("del", k);
3479
- span.end();
3480
5598
  }
3481
5599
  /**
3482
5600
  * Register tags for a cache key in the in-process index and (if Redis is enabled) in
@@ -3518,36 +5636,47 @@ var CacheService = class _CacheService {
3518
5636
  async delete(cacheKey) {
3519
5637
  const span = this._startSpan("tricache.delete");
3520
5638
  if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
3521
- const isPattern = cacheKey.includes("*");
3522
- const k = this.nk(cacheKey);
3523
- this.counters.deletes++;
3524
- if (isPattern) {
3525
- this.l1.deletePattern(k);
3526
- } else {
3527
- this.l1.delete(k);
3528
- setImmediate(() => {
3529
- if (!this._diskDisabled) this.disk.delete(k);
3530
- });
3531
- this._cascadeDependencies(k);
3532
- for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
3533
- }
3534
- if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
3535
- try {
3536
- const client = await this.getRedis();
3537
- if (isPattern) {
3538
- const keys = await this._scanKeys(client, k);
3539
- if (keys.length > 0) await client.del(...keys);
3540
- } else {
3541
- await client.del(k);
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 });
3542
5670
  }
3543
- this.cb.onSuccess();
3544
- } catch (err) {
3545
- this.cb.onFailure();
3546
- this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
3547
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();
3548
5679
  }
3549
- void this.publishInvalidation(isPattern ? "del-glob" : "del", k);
3550
- span.end();
3551
5680
  }
3552
5681
  // ── Counter (distributed rate limiting) ──────────────────────────────────
3553
5682
  /**
@@ -3608,31 +5737,44 @@ var CacheService = class _CacheService {
3608
5737
  * await cache.clear('user:abc'); // flush all keys for one user
3609
5738
  */
3610
5739
  async clear(prefix) {
3611
- this.counters.deletes++;
3612
- const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
3613
- if (k) {
3614
- this.l1.deletePattern(k);
3615
- } else {
3616
- this.l1.clear();
3617
- if (!this._diskDisabled) this.disk.clear();
3618
- this._l1Counters.clear();
3619
- this.tagIndex.clear();
3620
- this.tagVersions.clear();
3621
- }
3622
- if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
3623
- try {
3624
- const client = await this.getRedis();
3625
- const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
3626
- const keys = await this._scanKeys(client, pattern);
3627
- if (keys.length > 0) await client.del(...keys);
3628
- } catch (err) {
3629
- this.logger.debug("clear: Redis unavailable", { error: err.message });
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();
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
+ }
3630
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();
3631
5777
  }
3632
- void this.publishInvalidation(
3633
- "del-glob",
3634
- k ?? (this._namespace ? `${this._namespace}:*` : "*")
3635
- );
3636
5778
  }
3637
5779
  /**
3638
5780
  * Evict L1 entries that violate the current category or global capacity limits.
@@ -3763,7 +5905,7 @@ var CacheService = class _CacheService {
3763
5905
  const now = Date.now();
3764
5906
  if (entry.expiresAt <= now) return null;
3765
5907
  if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
3766
- return entry.value !== void 0 ? entry.value : unpack3(entry.data);
5908
+ return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
3767
5909
  }
3768
5910
  /**
3769
5911
  * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
@@ -3783,8 +5925,12 @@ var CacheService = class _CacheService {
3783
5925
  if (this.opts.frozen) deepFreeze(val);
3784
5926
  return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
3785
5927
  }
3786
- if (!this._diskDisabled) {
5928
+ if (!this._diskDisabled && this.watchdog.isDiskAllowed()) {
5929
+ const diskStart = performance.now();
3787
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);
3788
5934
  if (diskHit !== null) {
3789
5935
  const promoted = this.l1.importEntries(
3790
5936
  [{ key: k, entry: diskHit }],
@@ -3805,7 +5951,10 @@ var CacheService = class _CacheService {
3805
5951
  if (!this._redisDisabled && !this.cb.isOpen) {
3806
5952
  try {
3807
5953
  const client = await this.getRedis();
5954
+ const redisStart = performance.now();
3808
5955
  const raw = await client.get(k);
5956
+ const redisElapsed = performance.now() - redisStart;
5957
+ this.watchdog.recordRedis(redisElapsed);
3809
5958
  if (raw !== null) {
3810
5959
  const parsed = await this._decryptAndDeserialize(raw);
3811
5960
  this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
@@ -3832,90 +5981,129 @@ var CacheService = class _CacheService {
3832
5981
  * `(key) => number` so heterogeneous TTLs can be batched in one call.
3833
5982
  */
3834
5983
  async mget(keys, fetchFn, ttl = 300, priority) {
3835
- const result = Array.from({ length: keys.length });
3836
- const missIndexes = [];
3837
- const missKeys = [];
3838
- for (let i = 0; i < keys.length; i++) {
3839
- const k = this.nk(keys[i]);
3840
- const entry = this.l1.getEntry(k);
3841
- if (entry && entry.expiresAt > Date.now()) {
3842
- result[i] = entry.value !== void 0 ? entry.value : unpack3(entry.data);
3843
- this.counters.l1Hits++;
3844
- } else {
3845
- missIndexes.push(i);
3846
- missKeys.push(keys[i]);
3847
- }
5984
+ const span = this._startSpan("tricache.mget");
5985
+ if (this.opts.tracer) {
5986
+ span.setAttribute("cache.batch.size", keys.length);
3848
5987
  }
3849
- if (missKeys.length === 0) return result;
3850
- if (!this._redisDisabled) {
3851
- try {
3852
- const client = await this.getRedis();
3853
- const nsKeys = missKeys.map((k) => this.nk(k));
3854
- const pipeline = client.multi();
3855
- for (const nk of nsKeys) pipeline.get(nk);
3856
- const raws = await pipeline.exec();
3857
- this.cb.onSuccess();
3858
- for (let j = 0; j < missKeys.length; j++) {
3859
- const raw = raws[j] ? raws[j][1] : null;
3860
- const idx = missIndexes[j];
3861
- if (raw) {
3862
- const parsed = await this._decryptAndDeserialize(raw);
3863
- const k = nsKeys[j];
3864
- const p = priority ?? inferPriority(missKeys[j]);
3865
- this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
3866
- this.counters.l2Hits++;
3867
- result[idx] = parsed;
3868
- missIndexes[j] = -1;
3869
- missKeys[j] = "";
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
+ }
3870
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 });
3871
6048
  }
3872
- const remainingIdx = missIndexes.filter((i) => i >= 0);
3873
- const remainingKeys = missKeys.filter((k) => k !== "");
3874
- missIndexes.length = 0;
3875
- missKeys.length = 0;
3876
- missIndexes.push(...remainingIdx);
3877
- missKeys.push(...remainingKeys);
3878
- if (missKeys.length === 0) return result;
3879
- } catch (err) {
3880
- this.cb.onFailure();
3881
- this.logger.debug("mget: Redis unavailable, continuing to disk/fetch", { error: err.message });
3882
6049
  }
3883
- }
3884
- if (!this._diskDisabled) {
3885
- for (let j = missKeys.length - 1; j >= 0; j--) {
3886
- const k = this.nk(missKeys[j]);
3887
- const diskHit = this.disk.load(k);
3888
- if (diskHit !== null) {
3889
- const promoted = this.l1.importEntries(
3890
- [{ key: k, entry: diskHit }],
3891
- this.opts.forbiddenSnapshotPrefixes
3892
- );
3893
- if (promoted > 0) {
3894
- const l1Check = this.l1.get(k);
3895
- if (l1Check !== null) {
3896
- this.counters.diskHits++;
3897
- result[missIndexes[j]] = l1Check.value;
3898
- missIndexes.splice(j, 1);
3899
- missKeys.splice(j, 1);
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
+ }
3900
6072
  }
3901
6073
  }
3902
6074
  }
3903
6075
  }
3904
- if (missKeys.length === 0) return result;
3905
- }
3906
- if (missKeys.length > 0) {
3907
- this.counters.fetches++;
3908
- const fetched = await fetchFn(missKeys);
3909
- for (let j = 0; j < missKeys.length; j++) {
3910
- const v = fetched[missKeys[j]];
3911
- result[missIndexes[j]] = v;
3912
- if (v !== void 0) {
3913
- const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
3914
- await this.set(missKeys[j], v, resolvedTtl, priority);
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
+ }
3915
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);
3916
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();
3917
6106
  }
3918
- return result;
3919
6107
  }
3920
6108
  /**
3921
6109
  * Returns a Promise that resolves once the cache is fully initialised and any
@@ -3942,12 +6130,24 @@ var CacheService = class _CacheService {
3942
6130
  * });
3943
6131
  */
3944
6132
  async mset(entries) {
6133
+ const span = this._startSpan("tricache.mset");
3945
6134
  const keys = Object.keys(entries);
3946
- await Promise.all(keys.map((key) => {
3947
- const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
3948
- const hasOpts = tags?.length || dependsOn?.length;
3949
- return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
3950
- }));
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
+ }
3951
6151
  }
3952
6152
  /**
3953
6153
  * Batch delete — delete multiple exact keys in a single call.
@@ -3957,7 +6157,19 @@ var CacheService = class _CacheService {
3957
6157
  * await cache.mdel(['user:1', 'user:2', 'user:3']);
3958
6158
  */
3959
6159
  async mdel(keys) {
3960
- await Promise.all(keys.map((k) => this.delete(k)));
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
+ }
3961
6173
  }
3962
6174
  /**
3963
6175
  * Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
@@ -3986,7 +6198,6 @@ var CacheService = class _CacheService {
3986
6198
  const results = await pl.exec();
3987
6199
  this.cb.onSuccess();
3988
6200
  let loaded = 0;
3989
- const now = Date.now();
3990
6201
  for (let i = 0; i < matchedKeys.length; i++) {
3991
6202
  const [err, raw] = results[i];
3992
6203
  if (err || raw == null) continue;
@@ -3998,7 +6209,6 @@ var CacheService = class _CacheService {
3998
6209
  } catch {
3999
6210
  }
4000
6211
  }
4001
- void now;
4002
6212
  this.logger.info("warmFromL2 complete", {
4003
6213
  pattern,
4004
6214
  matched: matchedKeys.length,
@@ -4020,45 +6230,58 @@ var CacheService = class _CacheService {
4020
6230
  * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
4021
6231
  */
4022
6232
  async invalidateTag(tag) {
4023
- if (this.opts.tagStrategy === "generational") {
4024
- let newVer = 1;
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);
4025
6265
  if (!this._redisDisabled) {
4026
6266
  try {
4027
6267
  const client = await this.getRedis();
4028
- newVer = await client.incr(this.nk(`tag_ver:${tag}`));
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
+ }
4029
6275
  } catch (err) {
4030
6276
  this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
4031
- const current = this.tagVersions.get(tag)?.version ?? 0;
4032
- newVer = current + 1;
4033
- }
4034
- } else {
4035
- const current = this.tagVersions.get(tag)?.version ?? 0;
4036
- newVer = current + 1;
4037
- }
4038
- this._setLocalTagVersion(tag, newVer, Date.now());
4039
- void this.publishInvalidation("tag_incr", tag, newVer);
4040
- return;
4041
- }
4042
- const tagKey = this.nk(`_tag_:${tag}`);
4043
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
4044
- for (const k of members) {
4045
- this.l1.delete(k);
4046
- if (!this._diskDisabled) this.disk.delete(k);
4047
- }
4048
- this.tagIndex.delete(tagKey);
4049
- if (!this._redisDisabled) {
4050
- try {
4051
- const client = await this.getRedis();
4052
- const redisMembers = await client.smembers(tagKey);
4053
- const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
4054
- if (toDelete.length > 0) {
4055
- await client.del(...toDelete, tagKey);
4056
- } else {
4057
- await client.del(tagKey);
4058
6277
  }
4059
- } catch (err) {
4060
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
4061
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();
4062
6285
  }
4063
6286
  }
4064
6287
  /**
@@ -4091,7 +6314,7 @@ var CacheService = class _CacheService {
4091
6314
  const [err, newVer] = results[i] ?? [null, null];
4092
6315
  const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
4093
6316
  this._setLocalTagVersion(tags[i], ver, now);
4094
- void this.publishInvalidation("tag_incr", tags[i], ver);
6317
+ void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
4095
6318
  }
4096
6319
  return;
4097
6320
  } catch (err) {
@@ -4101,7 +6324,7 @@ var CacheService = class _CacheService {
4101
6324
  for (const tag of tags) {
4102
6325
  const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
4103
6326
  this._setLocalTagVersion(tag, ver, now);
4104
- void this.publishInvalidation("tag_incr", tag, ver);
6327
+ void this.publishInvalidation("tag_incr", tag, ver, false, true);
4105
6328
  }
4106
6329
  return;
4107
6330
  }
@@ -4172,6 +6395,60 @@ var CacheService = class _CacheService {
4172
6395
  }
4173
6396
  return { l1, disk, l2 };
4174
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
+ }
4175
6452
  /**
4176
6453
  * Export all live L1 entries to Redis via a single pipeline.
4177
6454
  * Useful for warming a new Redis instance or for zero-downtime failover.
@@ -4419,7 +6696,7 @@ var CacheService = class _CacheService {
4419
6696
  if (visited.has(dep)) continue;
4420
6697
  this.l1.delete(dep);
4421
6698
  if (!this._diskDisabled) this.disk.delete(dep);
4422
- void this.publishInvalidation("del", dep);
6699
+ void this.publishInvalidation("del", dep, void 0, false, true);
4423
6700
  this.logger.debug("Dependency cascade: invalidated dependent key", {
4424
6701
  trigger: deletedKey.slice(0, 60),
4425
6702
  dependent: dep.slice(0, 60)
@@ -4484,12 +6761,36 @@ var CacheService = class _CacheService {
4484
6761
  evictions: c.oomEvictions,
4485
6762
  lastTriggeredAt: c.oomLastAt
4486
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
+ },
4487
6784
  l1: {
4488
6785
  entries: l1s.entries,
4489
6786
  sizeBytes: this.l1.memoryUsage,
4490
6787
  maxBytes: this.opts.l1MaxBytes
4491
6788
  },
4492
- disk: { ...this.disk.stats, disabled: this._diskDisabled },
6789
+ disk: {
6790
+ ...this.disk.stats,
6791
+ disabled: this._diskDisabled,
6792
+ latencyWatchdog: this.watchdog.getTelemetry()
6793
+ },
4493
6794
  ...this.latencyTracker && {
4494
6795
  adaptiveTtl: {
4495
6796
  enabled: true,
@@ -4502,9 +6803,16 @@ var CacheService = class _CacheService {
4502
6803
  this.opts.adaptiveTtlMaxMs
4503
6804
  )
4504
6805
  }
6806
+ },
6807
+ ...this.pipeliner && {
6808
+ pipelining: this.pipeliner.stats
4505
6809
  }
4506
6810
  };
4507
6811
  }
6812
+ /** Return auto-pipelining metrics, or null if pipelining is disabled. */
6813
+ getPipelinerStats() {
6814
+ return this.pipeliner ? this.pipeliner.stats : null;
6815
+ }
4508
6816
  /**
4509
6817
  * Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
4510
6818
  * Paste the result into your `/metrics` endpoint.
@@ -4544,6 +6852,18 @@ var CacheService = class _CacheService {
4544
6852
  gauge("l1_entries", m.l1.entries, "Current L1 entry count");
4545
6853
  gauge("l1_size_bytes", m.l1.sizeBytes, "Current L1 used bytes");
4546
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
+ }
4547
6867
  gauge(
4548
6868
  "bloom_false_positive_rate",
4549
6869
  m.bloom.falsePositiveRate,
@@ -4565,6 +6885,17 @@ var CacheService = class _CacheService {
4565
6885
  "Emergency L1 eviction rounds triggered by heap pressure"
4566
6886
  );
4567
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
+ }
4568
6899
  return lines.join("\n");
4569
6900
  }
4570
6901
  // ── Lifecycle ────────────────────────────────────────────────────────────
@@ -4583,23 +6914,31 @@ var CacheService = class _CacheService {
4583
6914
  /** Close Redis connections and stop all background timers. */
4584
6915
  async destroy() {
4585
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
+ }
4586
6922
  if (this.cleanupInterval) clearInterval(this.cleanupInterval);
4587
6923
  if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
4588
6924
  if (this.oomInterval) clearInterval(this.oomInterval);
4589
6925
  if (this.metricsInterval) clearInterval(this.metricsInterval);
4590
- if (this._shutdownHandler) {
4591
- process.off("SIGTERM", this._shutdownHandler);
4592
- process.off("SIGINT", this._shutdownHandler);
4593
- this._shutdownHandler = null;
6926
+ if (this.remoteSnapshotInterval) {
6927
+ clearInterval(this.remoteSnapshotInterval);
6928
+ this.remoteSnapshotInterval = null;
4594
6929
  }
6930
+ ProcessTerminationBus.unregister(this);
6931
+ this._shutdownHandler = null;
4595
6932
  if (this._workerPool) {
4596
6933
  await this._workerPool.destroy();
4597
6934
  this._workerPool = null;
4598
6935
  }
4599
6936
  if (this.subClient) {
4600
- try {
4601
- this.subClient.disconnect();
4602
- } catch {
6937
+ if (!this.opts.redisSubClient) {
6938
+ try {
6939
+ this.subClient.disconnect();
6940
+ } catch {
6941
+ }
4603
6942
  }
4604
6943
  this.subClient = null;
4605
6944
  }
@@ -4611,19 +6950,61 @@ var CacheService = class _CacheService {
4611
6950
  this.streamClient = null;
4612
6951
  }
4613
6952
  if (this.redis) {
4614
- try {
4615
- await this.redis.disconnect();
4616
- } catch {
6953
+ if (!this.opts.redisClient) {
6954
+ try {
6955
+ await this.redis.disconnect();
6956
+ } catch {
6957
+ }
4617
6958
  }
4618
6959
  this.redis = null;
4619
6960
  }
6961
+ if (this._ipcServer) {
6962
+ await this._ipcServer.close();
6963
+ this._ipcServer = void 0;
6964
+ }
4620
6965
  if (!this._diskDisabled) this.disk.close();
4621
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
+ }
4622
6980
  };
4623
6981
 
4624
6982
  export {
4625
- WasmBloomFilter,
6983
+ CacheCodec,
6984
+ defaultCodec,
6985
+ TinyLfuSketch,
6986
+ WTinyLfuCache,
6987
+ WTinyLfuPolicy,
4626
6988
  SmartMemoryCache,
6989
+ resolveDefaultDiskDir,
4627
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,
4628
7009
  CacheService
4629
7010
  };