tricache 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +144 -1428
  3. package/bin/tricache.js +8 -8
  4. package/dashboards/tricache-alerts.yaml +54 -0
  5. package/dashboards/tricache-grafana.json +548 -0
  6. package/dist/cache-service-5MZXFIGK.js +12 -0
  7. package/dist/cache-service-CyLdpo77.d.ts +871 -0
  8. package/dist/{chunk-3XQUQBOZ.js → chunk-6PQ5MOWR.js} +2950 -523
  9. package/dist/chunk-7RV5ZVBB.js +1023 -0
  10. package/dist/{chunk-PFB5FMEY.js → chunk-LJ5QJB5O.js} +116 -20
  11. package/dist/chunk-QNU7B43J.js +687 -0
  12. package/dist/chunk-UGD4VEPD.js +138 -0
  13. package/dist/chunk-XZL45ABR.js +108 -0
  14. package/dist/chunk-ZTSWCFYO.js +135 -0
  15. package/dist/cli.cjs +2894 -518
  16. package/dist/cli.d.ts +1 -0
  17. package/dist/cli.js +103 -5
  18. package/dist/dashboard/index.cjs +1065 -0
  19. package/dist/dashboard/index.d.ts +183 -0
  20. package/dist/dashboard/index.js +22 -0
  21. package/dist/drizzle/index.cjs +2648 -508
  22. package/dist/drizzle/index.d.ts +3 -1
  23. package/dist/drizzle/index.js +1 -1
  24. package/dist/edge/index.cjs +1498 -0
  25. package/dist/edge/index.d.ts +127 -0
  26. package/dist/edge/index.js +1109 -0
  27. package/dist/hono-DQRS1Xd7.d.ts +370 -0
  28. package/dist/http/index.cjs +3038 -589
  29. package/dist/http/index.d.ts +109 -23
  30. package/dist/http/index.js +238 -62
  31. package/dist/index.cjs +6962 -2487
  32. package/dist/index.d.ts +547 -30
  33. package/dist/index.js +104 -5
  34. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  35. package/dist/nestjs/index.cjs +2586 -498
  36. package/dist/nestjs/index.d.ts +3 -1
  37. package/dist/nestjs/index.js +6 -3
  38. package/dist/next/index.cjs +2633 -519
  39. package/dist/next/index.d.ts +13 -7
  40. package/dist/next/index.js +45 -18
  41. package/dist/prisma/index.cjs +2 -1
  42. package/dist/prisma/index.d.ts +3 -1
  43. package/dist/prisma/index.js +2 -1
  44. package/dist/serialize-worker.cjs +31 -19
  45. package/dist/serialize-worker.js +1 -1
  46. package/dist/{cache-service-BblHuF3i.d.ts → types-B6krw64X.d.ts} +605 -646
  47. package/package.json +37 -7
  48. package/src/adapters/auto-pipeliner.ts +206 -0
  49. package/src/adapters/node-redis.ts +370 -0
  50. package/src/cache-service.ts +4231 -3226
  51. package/src/cli.ts +261 -143
  52. package/src/codec.ts +72 -0
  53. package/src/compression.ts +56 -63
  54. package/src/cross-region.ts +245 -0
  55. package/src/dashboard/handler.ts +392 -0
  56. package/src/dashboard/html.ts +594 -0
  57. package/src/dashboard/index.ts +195 -0
  58. package/src/dashboard/types.ts +96 -0
  59. package/src/disk-tier.ts +1223 -821
  60. package/src/drizzle/index.ts +86 -86
  61. package/src/edge/adapters/cloudflare-do.ts +130 -0
  62. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  63. package/src/edge/adapters/upstash.ts +143 -0
  64. package/src/edge/cache.ts +797 -0
  65. package/src/edge/crypto.ts +182 -0
  66. package/src/edge/hono.ts +203 -0
  67. package/src/edge/index.ts +37 -0
  68. package/src/edge/types.ts +230 -0
  69. package/src/edge/utils/base64.ts +63 -0
  70. package/src/edge/utils/murmur3.ts +179 -0
  71. package/src/encryption.ts +635 -493
  72. package/src/http/express.ts +195 -0
  73. package/src/http/fastify.ts +260 -0
  74. package/src/http/index.ts +46 -223
  75. package/src/http/utils.ts +92 -0
  76. package/src/index.ts +149 -47
  77. package/src/ipc-telemetry.ts +481 -0
  78. package/src/latency-watchdog.ts +282 -0
  79. package/src/nestjs/decorators.ts +161 -161
  80. package/src/nestjs/index.ts +23 -23
  81. package/src/nestjs/tricache.module.ts +104 -104
  82. package/src/nestjs/tricache.store.ts +97 -97
  83. package/src/nestjs/types.ts +79 -79
  84. package/src/next/cache-handler.ts +271 -244
  85. package/src/next/index.ts +37 -37
  86. package/src/next/isr-handler.ts +105 -105
  87. package/src/next/types.ts +130 -130
  88. package/src/prisma/index.ts +154 -151
  89. package/src/remote-snapshot.ts +153 -0
  90. package/src/serialize-worker.ts +120 -120
  91. package/src/sigv4-snapshot-adapter.ts +260 -0
  92. package/src/smart-memory-cache.ts +1109 -1024
  93. package/src/types.ts +1199 -902
  94. package/src/utils/cgroup.ts +100 -0
  95. package/src/utils/tracing.ts +54 -0
  96. package/src/wasm/bloom-filter-wasm.ts +109 -102
  97. package/src/worker-pool.ts +299 -299
  98. package/src/wtiny-lfu.ts +624 -0
  99. package/dist/cache-service-AJASH5FX.js +0 -7
  100. package/dist/chunk-UBSR5UYA.js +0 -0
@@ -35,6 +35,45 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
35
35
  ));
36
36
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
37
 
38
+ // src/codec.ts
39
+ var import_msgpackr, CacheCodec, defaultCodec;
40
+ var init_codec = __esm({
41
+ "src/codec.ts"() {
42
+ "use strict";
43
+ import_msgpackr = require("msgpackr");
44
+ CacheCodec = class {
45
+ packr;
46
+ constructor(options) {
47
+ const packrOptions = {
48
+ useToJSON: options?.useToJSON ?? true,
49
+ useRecords: options?.useRecords ?? true,
50
+ moreTypes: options?.moreTypes ?? true,
51
+ mapsAsObjects: options?.mapsAsObjects ?? true
52
+ };
53
+ this.packr = new import_msgpackr.Packr(packrOptions);
54
+ }
55
+ /**
56
+ * Serializes a JavaScript value to a binary MessagePack Buffer.
57
+ */
58
+ encode(data) {
59
+ const packed = this.packr.pack(data);
60
+ return Buffer.isBuffer(packed) ? packed : Buffer.from(packed.buffer, packed.byteOffset, packed.byteLength);
61
+ }
62
+ /**
63
+ * Deserializes a binary MessagePack Buffer or Uint8Array back to a JavaScript value.
64
+ */
65
+ decode(data) {
66
+ return this.packr.unpack(data);
67
+ }
68
+ };
69
+ defaultCodec = new CacheCodec({
70
+ useToJSON: true,
71
+ useRecords: true,
72
+ moreTypes: true
73
+ });
74
+ }
75
+ });
76
+
38
77
  // src/worker-pool.ts
39
78
  function getTransferableArrayBuffer(buf) {
40
79
  if (buf.buffer instanceof ArrayBuffer) {
@@ -258,11 +297,11 @@ var init_types = __esm({
258
297
  });
259
298
 
260
299
  // src/encryption.ts
261
- var import_crypto, IV_BYTES, TAG_BYTES, PREFIX_256, PREFIX_128, PREFIX_XOR, MAGIC_256, MAGIC_128, MAGIC_XOR, MAGIC_CTR, MAGIC_LEN, CTR_IV_BYTES, PREFIX_CTR, IV_POOL_COUNT, CacheEncryption;
300
+ var import_crypto2, IV_BYTES, TAG_BYTES, PREFIX_256, PREFIX_128, PREFIX_XOR, MAGIC_256, MAGIC_128, MAGIC_XOR, MAGIC_CTR, MAGIC_LEN, CTR_IV_BYTES, PREFIX_CTR, IV_POOL_COUNT, CacheEncryption, MAGIC_ENVELOPE, EnvelopeEncryption;
262
301
  var init_encryption = __esm({
263
302
  "src/encryption.ts"() {
264
303
  "use strict";
265
- import_crypto = require("crypto");
304
+ import_crypto2 = require("crypto");
266
305
  init_types();
267
306
  IV_BYTES = 12;
268
307
  TAG_BYTES = 16;
@@ -283,6 +322,8 @@ var init_encryption = __esm({
283
322
  _keyObj = null;
284
323
  // parsed KeyObject — used for all AES modes
285
324
  _mode;
325
+ /** Fail-closed on invalid key material when opted in via constructor opts. */
326
+ _strictKeyValidation;
286
327
  _prevKey = null;
287
328
  _prevKeyObj = null;
288
329
  _prevMode = "aes-256-gcm";
@@ -293,7 +334,7 @@ var init_encryption = __esm({
293
334
  /** Return the next unique 12-byte IV slice from the pre-allocated GCM pool. */
294
335
  _nextIV() {
295
336
  if (this._ivOffset >= this._ivPool.length) {
296
- (0, import_crypto.randomFillSync)(this._ivPool);
337
+ (0, import_crypto2.randomFillSync)(this._ivPool);
297
338
  this._ivOffset = 0;
298
339
  }
299
340
  const iv = this._ivPool.subarray(this._ivOffset, this._ivOffset + IV_BYTES);
@@ -306,7 +347,7 @@ var init_encryption = __esm({
306
347
  /** Return the next unique 16-byte IV slice from the pre-allocated CTR pool. */
307
348
  _nextCtrIV() {
308
349
  if (this._ctrIvOffset >= this._ctrIvPool.length) {
309
- (0, import_crypto.randomFillSync)(this._ctrIvPool);
350
+ (0, import_crypto2.randomFillSync)(this._ctrIvPool);
310
351
  this._ctrIvOffset = 0;
311
352
  }
312
353
  const iv = this._ctrIvPool.subarray(this._ctrIvOffset, this._ctrIvOffset + CTR_IV_BYTES);
@@ -348,11 +389,12 @@ var init_encryption = __esm({
348
389
  }
349
390
  return out;
350
391
  }
351
- constructor(keyBase64, loggerOrMode = consoleLogger, mode = "aes-256-gcm", previousKeyBase64, previousMode) {
392
+ constructor(keyBase64, loggerOrMode = consoleLogger, mode = "aes-256-gcm", previousKeyBase64, previousMode, opts) {
352
393
  const logger = typeof loggerOrMode === "object" && loggerOrMode !== null ? loggerOrMode : consoleLogger;
353
394
  const resolvedMode = typeof loggerOrMode === "string" ? loggerOrMode : mode;
395
+ this._strictKeyValidation = opts?.strictKeyValidation ?? false;
354
396
  this._mode = resolvedMode;
355
- if (!keyBase64) {
397
+ if (keyBase64 === void 0 || keyBase64 === null) {
356
398
  if (process.env.NODE_ENV === "production") {
357
399
  logger.warn(
358
400
  "SECURITY: encryption key not set \u2014 cache data stored unencrypted at rest",
@@ -361,27 +403,33 @@ var init_encryption = __esm({
361
403
  }
362
404
  return;
363
405
  }
406
+ if (keyBase64 === "") {
407
+ const err = new Error("Encryption key is empty \u2014 set encryptionKey option or CACHE_ENCRYPTION_KEY");
408
+ if (this._strictKeyValidation) throw err;
409
+ logger.error("Empty encryption key \u2014 falling back to plaintext", {}, err);
410
+ return;
411
+ }
364
412
  try {
365
413
  const buf = Buffer.from(keyBase64, "base64");
366
414
  const requiredLen = resolvedMode === "aes-256-gcm" ? 32 : resolvedMode === "aes-128-gcm" || resolvedMode === "aes-128-ctr" ? 16 : 0;
367
415
  if (requiredLen > 0 && buf.length !== requiredLen) {
368
- throw new Error(`${mode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
416
+ throw new Error(`${resolvedMode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
369
417
  }
370
418
  if (buf.length < 1) {
371
419
  throw new Error("XOR key must be at least 1 byte");
372
420
  }
373
421
  this._key = buf;
374
- if (mode !== "xor") {
375
- this._keyObj = (0, import_crypto.createSecretKey)(buf);
376
- const _wc = (0, import_crypto.createCipheriv)(
377
- mode,
422
+ if (resolvedMode !== "xor") {
423
+ this._keyObj = (0, import_crypto2.createSecretKey)(buf);
424
+ const _wc = (0, import_crypto2.createCipheriv)(
425
+ resolvedMode,
378
426
  this._keyObj,
379
- Buffer.alloc(mode === "aes-128-ctr" ? CTR_IV_BYTES : IV_BYTES)
427
+ Buffer.alloc(resolvedMode === "aes-128-ctr" ? CTR_IV_BYTES : IV_BYTES)
380
428
  );
381
429
  _wc.update(Buffer.alloc(0));
382
430
  _wc.final();
383
431
  }
384
- if (mode === "xor") {
432
+ if (resolvedMode === "xor") {
385
433
  logger.warn(
386
434
  "Cache obfuscation enabled (XOR). WARNING: XOR is NOT cryptographic \u2014 use only for dev or non-sensitive data."
387
435
  );
@@ -389,6 +437,9 @@ var init_encryption = __esm({
389
437
  logger.debug(`Cache encryption enabled (${mode.toUpperCase()})`);
390
438
  }
391
439
  } catch (err) {
440
+ if (this._strictKeyValidation) {
441
+ throw err;
442
+ }
392
443
  logger.error("Invalid encryption key \u2014 falling back to plaintext", {}, err);
393
444
  }
394
445
  if (previousKeyBase64) {
@@ -396,8 +447,8 @@ var init_encryption = __esm({
396
447
  this._prevMode = previousMode ?? mode;
397
448
  this._prevKey = Buffer.from(previousKeyBase64, "base64");
398
449
  if (this._prevMode !== "xor") {
399
- this._prevKeyObj = (0, import_crypto.createSecretKey)(this._prevKey);
400
- const _wc = (0, import_crypto.createCipheriv)(
450
+ this._prevKeyObj = (0, import_crypto2.createSecretKey)(this._prevKey);
451
+ const _wc = (0, import_crypto2.createCipheriv)(
401
452
  this._prevMode,
402
453
  this._prevKeyObj,
403
454
  Buffer.alloc(this._prevMode === "aes-128-ctr" ? CTR_IV_BYTES : IV_BYTES)
@@ -452,8 +503,8 @@ var init_encryption = __esm({
452
503
  }
453
504
  let newKeyObj = null;
454
505
  if (mode !== "xor") {
455
- newKeyObj = (0, import_crypto.createSecretKey)(buf);
456
- const _wc = (0, import_crypto.createCipheriv)(
506
+ newKeyObj = (0, import_crypto2.createSecretKey)(buf);
507
+ const _wc = (0, import_crypto2.createCipheriv)(
457
508
  mode,
458
509
  newKeyObj,
459
510
  Buffer.alloc(mode === "aes-128-ctr" ? CTR_IV_BYTES : IV_BYTES)
@@ -482,7 +533,7 @@ var init_encryption = __esm({
482
533
  }
483
534
  if (this._mode === "aes-128-ctr") {
484
535
  const iv2 = this._nextCtrIV();
485
- const c2 = (0, import_crypto.createCipheriv)("aes-128-ctr", this._keyObj, iv2);
536
+ const c2 = (0, import_crypto2.createCipheriv)("aes-128-ctr", this._keyObj, iv2);
486
537
  const enc2 = c2.update(plaintext, "utf8");
487
538
  const fin = c2.final();
488
539
  const out2 = Buffer.allocUnsafe(CTR_IV_BYTES + enc2.length + fin.length);
@@ -494,7 +545,7 @@ var init_encryption = __esm({
494
545
  const algo = this._mode === "aes-128-gcm" ? "aes-128-gcm" : "aes-256-gcm";
495
546
  const prefix = this._mode === "aes-128-gcm" ? PREFIX_128 : PREFIX_256;
496
547
  const iv = this._nextIV();
497
- const c = (0, import_crypto.createCipheriv)(algo, this._keyObj, iv);
548
+ const c = (0, import_crypto2.createCipheriv)(algo, this._keyObj, iv);
498
549
  const enc = c.update(plaintext, "utf8");
499
550
  c.final();
500
551
  const out = Buffer.allocUnsafe(IV_BYTES + TAG_BYTES + enc.length);
@@ -536,7 +587,7 @@ var init_encryption = __esm({
536
587
  const combined2 = Buffer.from(value.slice(PREFIX_CTR.length), "base64");
537
588
  const iv2 = combined2.subarray(0, CTR_IV_BYTES);
538
589
  const ct2 = combined2.subarray(CTR_IV_BYTES);
539
- const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr", keyObj, iv2);
590
+ const d2 = (0, import_crypto2.createDecipheriv)("aes-128-ctr", keyObj, iv2);
540
591
  const plain2 = d2.update(ct2);
541
592
  const fin = d2.final();
542
593
  return (fin.length > 0 ? Buffer.concat([plain2, fin]) : plain2).toString("utf8");
@@ -551,7 +602,7 @@ var init_encryption = __esm({
551
602
  const iv = combined.subarray(0, IV_BYTES);
552
603
  const tag = combined.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
553
604
  const ct = combined.subarray(IV_BYTES + TAG_BYTES);
554
- const d = (0, import_crypto.createDecipheriv)(algo, keyObj, iv);
605
+ const d = (0, import_crypto2.createDecipheriv)(algo, keyObj, iv);
555
606
  d.setAuthTag(tag);
556
607
  const plain = d.update(ct);
557
608
  d.final();
@@ -570,7 +621,7 @@ var init_encryption = __esm({
570
621
  }
571
622
  if (this._mode === "aes-128-ctr") {
572
623
  const iv2 = this._nextCtrIV();
573
- const c2 = (0, import_crypto.createCipheriv)("aes-128-ctr", this._keyObj, iv2);
624
+ const c2 = (0, import_crypto2.createCipheriv)("aes-128-ctr", this._keyObj, iv2);
574
625
  const enc2 = c2.update(data);
575
626
  const fin = c2.final();
576
627
  const out2 = Buffer.allocUnsafe(MAGIC_LEN + CTR_IV_BYTES + enc2.length + fin.length);
@@ -583,7 +634,7 @@ var init_encryption = __esm({
583
634
  const magic = this._mode === "aes-128-gcm" ? MAGIC_128 : MAGIC_256;
584
635
  const algo = this._mode === "aes-128-gcm" ? "aes-128-gcm" : "aes-256-gcm";
585
636
  const iv = this._nextIV();
586
- const c = (0, import_crypto.createCipheriv)(algo, this._keyObj, iv);
637
+ const c = (0, import_crypto2.createCipheriv)(algo, this._keyObj, iv);
587
638
  const enc = c.update(data);
588
639
  c.final();
589
640
  const out = Buffer.allocUnsafe(MAGIC_LEN + IV_BYTES + TAG_BYTES + enc.length);
@@ -626,7 +677,7 @@ var init_encryption = __esm({
626
677
  if (!keyObj) throw new Error("Cannot decrypt buffer: encryption key is not set");
627
678
  const iv2 = data.subarray(MAGIC_LEN, MAGIC_LEN + CTR_IV_BYTES);
628
679
  const ct2 = data.subarray(MAGIC_LEN + CTR_IV_BYTES);
629
- const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr", keyObj, iv2);
680
+ const d2 = (0, import_crypto2.createDecipheriv)("aes-128-ctr", keyObj, iv2);
630
681
  const plain2 = d2.update(ct2);
631
682
  const fin = d2.final();
632
683
  return fin.length > 0 ? Buffer.concat([plain2, fin]) : plain2;
@@ -639,13 +690,267 @@ var init_encryption = __esm({
639
690
  const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + IV_BYTES);
640
691
  const tag = data.subarray(MAGIC_LEN + IV_BYTES, MAGIC_LEN + IV_BYTES + TAG_BYTES);
641
692
  const ct = data.subarray(MAGIC_LEN + IV_BYTES + TAG_BYTES);
642
- const d = (0, import_crypto.createDecipheriv)(algo, keyObj, iv);
693
+ const d = (0, import_crypto2.createDecipheriv)(algo, keyObj, iv);
643
694
  d.setAuthTag(tag);
644
695
  const plain = d.update(ct);
645
696
  d.final();
646
697
  return plain;
647
698
  }
648
699
  };
700
+ MAGIC_ENVELOPE = Buffer.from([84, 82, 73, 67, 69, 78, 86, 49]);
701
+ EnvelopeEncryption = class {
702
+ static isEnvelope(data) {
703
+ return data.length >= MAGIC_LEN && data.subarray(0, MAGIC_LEN).equals(MAGIC_ENVELOPE);
704
+ }
705
+ static async encrypt(data, options) {
706
+ const dek = (0, import_crypto2.randomBytes)(32);
707
+ let encryptedKey;
708
+ if (options.kmsEncrypt) {
709
+ encryptedKey = await options.kmsEncrypt(dek);
710
+ } else if (options.publicKey) {
711
+ encryptedKey = (0, import_crypto2.publicEncrypt)(
712
+ {
713
+ key: options.publicKey,
714
+ padding: import_crypto2.constants.RSA_PKCS1_OAEP_PADDING,
715
+ oaepHash: "sha256"
716
+ },
717
+ dek
718
+ );
719
+ } else {
720
+ throw new Error("EnvelopeEncryption: either publicKey or kmsEncrypt must be provided to encrypt");
721
+ }
722
+ const iv = (0, import_crypto2.randomBytes)(IV_BYTES);
723
+ const cipher = (0, import_crypto2.createCipheriv)("aes-256-gcm", dek, iv);
724
+ const ct = cipher.update(data);
725
+ cipher.final();
726
+ const tag = cipher.getAuthTag();
727
+ const keyLen = encryptedKey.length;
728
+ const out = Buffer.allocUnsafe(MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES + ct.length);
729
+ MAGIC_ENVELOPE.copy(out, 0);
730
+ out.writeUInt32BE(keyLen, MAGIC_LEN);
731
+ encryptedKey.copy(out, MAGIC_LEN + 4);
732
+ iv.copy(out, MAGIC_LEN + 4 + keyLen);
733
+ tag.copy(out, MAGIC_LEN + 4 + keyLen + IV_BYTES);
734
+ ct.copy(out, MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES);
735
+ return out;
736
+ }
737
+ static async decrypt(data, options) {
738
+ if (!this.isEnvelope(data)) {
739
+ throw new Error("EnvelopeEncryption: invalid header, expected TRICENV1");
740
+ }
741
+ if (data.length < MAGIC_LEN + 4 + IV_BYTES + TAG_BYTES) {
742
+ throw new Error("EnvelopeEncryption: truncated envelope buffer");
743
+ }
744
+ const keyLen = data.readUInt32BE(MAGIC_LEN);
745
+ const minExpected = MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES;
746
+ if (data.length < minExpected) {
747
+ throw new Error("EnvelopeEncryption: truncated envelope buffer (key length mismatch)");
748
+ }
749
+ const encryptedKey = data.subarray(MAGIC_LEN + 4, MAGIC_LEN + 4 + keyLen);
750
+ const iv = data.subarray(MAGIC_LEN + 4 + keyLen, MAGIC_LEN + 4 + keyLen + IV_BYTES);
751
+ const tag = data.subarray(MAGIC_LEN + 4 + keyLen + IV_BYTES, MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES);
752
+ const ct = data.subarray(MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES);
753
+ let dek;
754
+ if (options.kmsDecrypt) {
755
+ dek = await options.kmsDecrypt(encryptedKey);
756
+ } else if (options.privateKey) {
757
+ dek = (0, import_crypto2.privateDecrypt)(
758
+ {
759
+ key: options.privateKey,
760
+ padding: import_crypto2.constants.RSA_PKCS1_OAEP_PADDING,
761
+ oaepHash: "sha256"
762
+ },
763
+ encryptedKey
764
+ );
765
+ } else {
766
+ throw new Error("EnvelopeEncryption: either privateKey or kmsDecrypt must be provided to decrypt");
767
+ }
768
+ const decipher = (0, import_crypto2.createDecipheriv)("aes-256-gcm", dek, iv);
769
+ decipher.setAuthTag(tag);
770
+ const pt = decipher.update(ct);
771
+ decipher.final();
772
+ return pt;
773
+ }
774
+ };
775
+ }
776
+ });
777
+
778
+ // src/wtiny-lfu.ts
779
+ var WTinyLfuPolicy;
780
+ var init_wtiny_lfu = __esm({
781
+ "src/wtiny-lfu.ts"() {
782
+ "use strict";
783
+ WTinyLfuPolicy = class {
784
+ constructor(capacity, sketch, windowPercent = 0.01, protectedPercent = 0.8) {
785
+ this.sketch = sketch;
786
+ this.maxTotal = Math.max(2, capacity);
787
+ this.maxWindow = Math.max(1, Math.floor(this.maxTotal * windowPercent));
788
+ const mainCapacity = Math.max(1, this.maxTotal - this.maxWindow);
789
+ this.maxProtected = Math.max(1, Math.floor(mainCapacity * protectedPercent));
790
+ this.maxProbation = Math.max(1, mainCapacity - this.maxProtected);
791
+ }
792
+ sketch;
793
+ maxTotal;
794
+ maxWindow;
795
+ maxProtected;
796
+ maxProbation;
797
+ window = /* @__PURE__ */ new Set();
798
+ probation = /* @__PURE__ */ new Set();
799
+ protected_ = /* @__PURE__ */ new Set();
800
+ // Telemetry metrics
801
+ hitCount = 0;
802
+ missCount = 0;
803
+ admissionCount = 0;
804
+ rejectionCount = 0;
805
+ promotionCount = 0;
806
+ demotionCount = 0;
807
+ get windowSize() {
808
+ return this.window.size;
809
+ }
810
+ get probationSize() {
811
+ return this.probation.size;
812
+ }
813
+ get protectedSize() {
814
+ return this.protected_.size;
815
+ }
816
+ onAccess(key) {
817
+ if (this.window.has(key)) {
818
+ this.window.delete(key);
819
+ this.window.add(key);
820
+ this.hitCount++;
821
+ return;
822
+ }
823
+ if (this.protected_.has(key)) {
824
+ this.protected_.delete(key);
825
+ this.protected_.add(key);
826
+ this.hitCount++;
827
+ return;
828
+ }
829
+ if (this.probation.has(key)) {
830
+ this.probation.delete(key);
831
+ this.protected_.add(key);
832
+ this.promotionCount++;
833
+ this.hitCount++;
834
+ if (this.protected_.size > this.maxProtected) {
835
+ const oldestProtKey = this.protected_.values().next().value;
836
+ this.protected_.delete(oldestProtKey);
837
+ this.probation.add(oldestProtKey);
838
+ this.demotionCount++;
839
+ }
840
+ return;
841
+ }
842
+ this.missCount++;
843
+ }
844
+ onSet(key, isUpdate) {
845
+ if (isUpdate) {
846
+ if (this.window.has(key)) {
847
+ this.window.delete(key);
848
+ this.window.add(key);
849
+ } else if (this.protected_.has(key)) {
850
+ this.protected_.delete(key);
851
+ this.protected_.add(key);
852
+ } else if (this.probation.has(key)) {
853
+ this.probation.delete(key);
854
+ this.probation.add(key);
855
+ }
856
+ return { admit: true };
857
+ }
858
+ this.window.add(key);
859
+ if (this.window.size <= this.maxWindow) {
860
+ this.admissionCount++;
861
+ return { admit: true };
862
+ }
863
+ const candKey = this.window.values().next().value;
864
+ this.window.delete(candKey);
865
+ if (this.probation.size + this.protected_.size < this.maxProbation + this.maxProtected) {
866
+ this.probation.add(candKey);
867
+ this.admissionCount++;
868
+ return { admit: true };
869
+ }
870
+ let victimKey;
871
+ let victimIsProbation = true;
872
+ if (this.probation.size > 0) {
873
+ victimKey = this.probation.values().next().value;
874
+ } else {
875
+ victimKey = this.protected_.values().next().value;
876
+ victimIsProbation = false;
877
+ }
878
+ const candFreq = this.sketch.estimate(candKey);
879
+ const victimFreq = this.sketch.estimate(victimKey);
880
+ if (candFreq > victimFreq) {
881
+ if (victimIsProbation) {
882
+ this.probation.delete(victimKey);
883
+ } else {
884
+ this.protected_.delete(victimKey);
885
+ }
886
+ this.probation.add(candKey);
887
+ this.admissionCount++;
888
+ return { admit: true, evictKey: victimKey, candidateKey: candKey };
889
+ } else {
890
+ this.rejectionCount++;
891
+ return { admit: false, candidateKey: candKey };
892
+ }
893
+ }
894
+ onDelete(key) {
895
+ this.window.delete(key);
896
+ this.probation.delete(key);
897
+ this.protected_.delete(key);
898
+ }
899
+ clear() {
900
+ this.window.clear();
901
+ this.probation.clear();
902
+ this.protected_.clear();
903
+ this.hitCount = 0;
904
+ this.missCount = 0;
905
+ this.admissionCount = 0;
906
+ this.rejectionCount = 0;
907
+ this.promotionCount = 0;
908
+ this.demotionCount = 0;
909
+ }
910
+ getStats() {
911
+ const totalRequests = this.hitCount + this.missCount;
912
+ return {
913
+ capacity: this.maxTotal,
914
+ size: this.window.size + this.probation.size + this.protected_.size,
915
+ windowSize: this.window.size,
916
+ probationSize: this.probation.size,
917
+ protectedSize: this.protected_.size,
918
+ hits: this.hitCount,
919
+ misses: this.missCount,
920
+ hitRate: totalRequests > 0 ? this.hitCount / totalRequests : 0,
921
+ admissions: this.admissionCount,
922
+ rejections: this.rejectionCount,
923
+ promotions: this.promotionCount,
924
+ demotions: this.demotionCount
925
+ };
926
+ }
927
+ getSegment(key) {
928
+ if (this.window.has(key)) return "window";
929
+ if (this.probation.has(key)) return "probation";
930
+ if (this.protected_.has(key)) return "protected";
931
+ return null;
932
+ }
933
+ };
934
+ }
935
+ });
936
+
937
+ // src/edge/utils/base64.ts
938
+ function base64ToUint8Array(base64) {
939
+ const modernU8 = Uint8Array;
940
+ if (typeof modernU8.fromBase64 === "function") {
941
+ return modernU8.fromBase64(base64);
942
+ }
943
+ const binary = globalThis.atob(base64);
944
+ const len = binary.length;
945
+ const bytes = new Uint8Array(len);
946
+ for (let i = 0; i < len; i++) {
947
+ bytes[i] = binary.charCodeAt(i);
948
+ }
949
+ return bytes;
950
+ }
951
+ var init_base64 = __esm({
952
+ "src/edge/utils/base64.ts"() {
953
+ "use strict";
649
954
  }
650
955
  });
651
956
 
@@ -654,10 +959,13 @@ var BLOOM_WASM_BASE64, KEY_STAGING_OFFSET, MAX_KEY_BYTES, BLOOM_WASM_MODULE, Was
654
959
  var init_bloom_filter_wasm = __esm({
655
960
  "src/wasm/bloom-filter-wasm.ts"() {
656
961
  "use strict";
962
+ init_base64();
657
963
  BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
658
964
  KEY_STAGING_OFFSET = 2e4;
659
965
  MAX_KEY_BYTES = 512;
660
- BLOOM_WASM_MODULE = new WebAssembly.Module(Buffer.from(BLOOM_WASM_BASE64, "base64"));
966
+ BLOOM_WASM_MODULE = new WebAssembly.Module(
967
+ base64ToUint8Array(BLOOM_WASM_BASE64)
968
+ );
661
969
  WasmBloomFilter = class {
662
970
  exports;
663
971
  mem;
@@ -755,13 +1063,13 @@ function globMatchParts(parts, first, last, key) {
755
1063
  }
756
1064
  return true;
757
1065
  }
758
- var import_msgpackr, _hit, LARGE_VALUE_BYTES, EVICTION_BATCH_PERCENT, EVICTION_SAMPLE, EVICT_COUNT, JsBloomFilter, SKETCH_ROWS, SKETCH_WIDTH, SKETCH_MASK, SKETCH_DECAY_THRESHOLD, CountMinSketch, SmartMemoryCache;
1066
+ var LARGE_VALUE_BYTES, EVICTION_BATCH_PERCENT, EVICTION_SAMPLE, EVICT_COUNT, JsBloomFilter, SKETCH_ROWS, SKETCH_WIDTH, SKETCH_MASK, SKETCH_DECAY_THRESHOLD, CountMinSketch, SmartMemoryCache;
759
1067
  var init_smart_memory_cache = __esm({
760
1068
  "src/smart-memory-cache.ts"() {
761
1069
  "use strict";
762
- import_msgpackr = require("msgpackr");
1070
+ init_codec();
1071
+ init_wtiny_lfu();
763
1072
  init_bloom_filter_wasm();
764
- _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0, fetchedAt: 0, tagVersions: void 0, setAt: void 0 };
765
1073
  LARGE_VALUE_BYTES = 16384;
766
1074
  EVICTION_BATCH_PERCENT = 0.2;
767
1075
  EVICTION_SAMPLE = 16;
@@ -901,11 +1209,13 @@ var init_smart_memory_cache = __esm({
901
1209
  SmartMemoryCache = class {
902
1210
  cache = /* @__PURE__ */ new Map();
903
1211
  opts;
1212
+ codec;
904
1213
  bloom;
905
1214
  /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
906
1215
  categoryPrefixes;
907
1216
  /** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
908
1217
  sketch = new CountMinSketch();
1218
+ wtinyPolicy;
909
1219
  totalSize = 0;
910
1220
  categoryCount = /* @__PURE__ */ new Map();
911
1221
  categorySize = /* @__PURE__ */ new Map();
@@ -929,8 +1239,12 @@ var init_smart_memory_cache = __esm({
929
1239
  _evictGPool = Array.from({ length: EVICTION_SAMPLE }, () => ({ key: "", score: 0 }));
930
1240
  constructor(opts, existing) {
931
1241
  this.opts = opts;
1242
+ this.codec = opts.codec ?? defaultCodec;
932
1243
  this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
933
1244
  this.categoryPrefixes = Object.keys(opts.categories).filter((k) => k !== "default");
1245
+ if (opts.admissionPolicy === "wtinylfu") {
1246
+ this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch);
1247
+ }
934
1248
  if (existing) {
935
1249
  for (const [k, v] of existing) this.cache.set(k, v);
936
1250
  this.recalculateStats();
@@ -943,6 +1257,12 @@ var init_smart_memory_cache = __esm({
943
1257
  this.categoryCount.clear();
944
1258
  this.categorySize.clear();
945
1259
  this.categoryKeys.clear();
1260
+ if (this.wtinyPolicy) {
1261
+ this.wtinyPolicy.clear();
1262
+ for (const key of this.cache.keys()) {
1263
+ this.wtinyPolicy.onSet(key, false);
1264
+ }
1265
+ }
946
1266
  for (const [key, entry] of this.cache) {
947
1267
  this.totalSize += entry.size;
948
1268
  const cat = this.getCategory(key);
@@ -968,6 +1288,7 @@ var init_smart_memory_cache = __esm({
968
1288
  _delete(key, reason = "manual") {
969
1289
  const entry = this.cache.get(key);
970
1290
  if (!entry) return false;
1291
+ this.wtinyPolicy?.onDelete(key);
971
1292
  const cat = this.getCategory(key);
972
1293
  this.totalSize -= entry.size;
973
1294
  this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
@@ -1128,19 +1449,22 @@ var init_smart_memory_cache = __esm({
1128
1449
  entry.hits++;
1129
1450
  entry.lastAccess = now;
1130
1451
  if ((entry.hits & 3) === 0) this.sketch.increment(key);
1131
- const value = entry.value !== void 0 ? entry.value : (0, import_msgpackr.unpack)(entry.data);
1132
- _hit.value = value;
1133
- _hit.isStale = entry.staleAt !== void 0 && now > entry.staleAt;
1134
- _hit.expiresAt = entry.expiresAt;
1135
- _hit.ttlMs = entry.ttlMs;
1136
- _hit.delta = entry.delta;
1137
- _hit.fetchedAt = now;
1138
- _hit.tagVersions = entry.tagVersions;
1139
- _hit.setAt = entry.setAt;
1140
- return _hit;
1452
+ this.wtinyPolicy?.onAccess(key);
1453
+ const value = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
1454
+ const hit = {
1455
+ value,
1456
+ isStale: entry.staleAt !== void 0 && now > entry.staleAt,
1457
+ expiresAt: entry.expiresAt,
1458
+ ttlMs: entry.ttlMs,
1459
+ delta: entry.delta,
1460
+ fetchedAt: now,
1461
+ tagVersions: entry.tagVersions,
1462
+ setAt: entry.setAt
1463
+ };
1464
+ return hit;
1141
1465
  }
1142
1466
  set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
1143
- const packed = (0, import_msgpackr.pack)(data);
1467
+ const packed = this.codec.encode(data);
1144
1468
  const size = packed.byteLength;
1145
1469
  this.compressions++;
1146
1470
  this.sketch.increment(key);
@@ -1157,7 +1481,51 @@ var init_smart_memory_cache = __esm({
1157
1481
  this.categorySize.set(cat, (this.categorySize.get(cat) ?? existingEntry.size) - existingEntry.size);
1158
1482
  this.cache.delete(key);
1159
1483
  }
1160
- this.ensureCapacity(cat, size);
1484
+ if (this.wtinyPolicy) {
1485
+ const decision = this.wtinyPolicy.onSet(key, Boolean(existingEntry));
1486
+ if (!decision.admit) {
1487
+ if (decision.candidateKey === key) {
1488
+ if (this.opts.diskSpill) {
1489
+ const now2 = Date.now();
1490
+ const liveValue2 = size <= LARGE_VALUE_BYTES ? data : void 0;
1491
+ this.opts.diskSpill(key, {
1492
+ data: packed,
1493
+ value: liveValue2,
1494
+ isCompressed: true,
1495
+ expiresAt: now2 + ttlMs,
1496
+ staleAt,
1497
+ size,
1498
+ hits: 1,
1499
+ lastAccess: now2,
1500
+ priority,
1501
+ ttlMs,
1502
+ delta,
1503
+ setAt: now2,
1504
+ tagVersions
1505
+ });
1506
+ }
1507
+ return;
1508
+ } else if (decision.candidateKey) {
1509
+ const candEntry = this.cache.get(decision.candidateKey);
1510
+ if (candEntry && this.opts.diskSpill) {
1511
+ this.opts.diskSpill(decision.candidateKey, candEntry);
1512
+ }
1513
+ this._delete(decision.candidateKey, "capacity");
1514
+ }
1515
+ } else if (decision.evictKey) {
1516
+ const victimEntry = this.cache.get(decision.evictKey);
1517
+ if (victimEntry && this.opts.diskSpill) {
1518
+ this.opts.diskSpill(decision.evictKey, victimEntry);
1519
+ }
1520
+ this._delete(decision.evictKey, "capacity");
1521
+ }
1522
+ const catSz = this.categorySize.get(cat) ?? 0;
1523
+ if (catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
1524
+ this.ensureCapacity(cat, size);
1525
+ }
1526
+ } else {
1527
+ this.ensureCapacity(cat, size);
1528
+ }
1161
1529
  const now = Date.now();
1162
1530
  const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
1163
1531
  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 });
@@ -1217,6 +1585,7 @@ var init_smart_memory_cache = __esm({
1217
1585
  }
1218
1586
  const count = this.cache.size;
1219
1587
  this.cache.clear();
1588
+ this.wtinyPolicy?.clear();
1220
1589
  this.totalSize = 0;
1221
1590
  this.categoryCount.clear();
1222
1591
  this.categorySize.clear();
@@ -1384,8 +1753,8 @@ var init_smart_memory_cache = __esm({
1384
1753
  if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
1385
1754
  if (this.cache.has(key)) continue;
1386
1755
  const rawData = entry.data;
1387
- const data = !entry.isCompressed ? (0, import_msgpackr.pack)(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
1388
- const value = entry.size <= LARGE_VALUE_BYTES ? (0, import_msgpackr.unpack)(data) : void 0;
1756
+ const data = !entry.isCompressed ? this.codec.encode(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
1757
+ const value = entry.size <= LARGE_VALUE_BYTES ? this.codec.decode(data) : void 0;
1389
1758
  this.cache.set(key, { ...entry, data, value, isCompressed: true });
1390
1759
  this.bloom.add(key);
1391
1760
  loaded++;
@@ -1456,7 +1825,7 @@ var init_smart_memory_cache = __esm({
1456
1825
  * if the live object was not cached (large-entry optimisation or disk-restored entry).
1457
1826
  */
1458
1827
  resolveValue(entry) {
1459
- return entry.value !== void 0 ? entry.value : (0, import_msgpackr.unpack)(entry.data);
1828
+ return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
1460
1829
  }
1461
1830
  // ── Stats ─────────────────────────────────────────────────────────────────
1462
1831
  get size() {
@@ -1561,6 +1930,13 @@ var init_smart_memory_cache = __esm({
1561
1930
  out.sort((a, b) => b.hits - a.hits);
1562
1931
  return out.slice(0, n);
1563
1932
  }
1933
+ /**
1934
+ * Return real-time metrics and telemetry for the Window TinyLFU admission policy.
1935
+ * Returns `undefined` when running under default adaptive eviction.
1936
+ */
1937
+ getWTinyLfuStats() {
1938
+ return this.wtinyPolicy?.getStats();
1939
+ }
1564
1940
  };
1565
1941
  }
1566
1942
  });
@@ -1584,26 +1960,25 @@ function compressBuffer(buf, algorithm) {
1584
1960
  return buf;
1585
1961
  }
1586
1962
  function decompressBuffer(buf, algorithm = "brotli") {
1587
- if (algorithm === "gzip") {
1963
+ const tryBrotli = () => {
1588
1964
  try {
1589
- return import_zlib.default.gunzipSync(buf);
1965
+ return import_zlib.default.brotliDecompressSync(buf);
1590
1966
  } catch {
1591
- try {
1592
- return import_zlib.default.brotliDecompressSync(buf);
1593
- } catch {
1594
- return buf;
1595
- }
1967
+ return null;
1596
1968
  }
1597
- }
1598
- try {
1599
- return import_zlib.default.brotliDecompressSync(buf);
1600
- } catch {
1969
+ };
1970
+ const tryGzip = () => {
1601
1971
  try {
1602
1972
  return import_zlib.default.gunzipSync(buf);
1603
1973
  } catch {
1604
- return buf;
1974
+ return null;
1605
1975
  }
1976
+ };
1977
+ const result = algorithm === "gzip" ? tryGzip() ?? tryBrotli() : tryBrotli() ?? tryGzip();
1978
+ if (result === null) {
1979
+ throw new Error(`tricache: corrupt compressed payload (${buf.length} bytes, algorithm=${algorithm})`);
1606
1980
  }
1981
+ return result;
1607
1982
  }
1608
1983
  function compressWithHeader(buf, algorithm) {
1609
1984
  if (algorithm === "none") return buf;
@@ -1628,19 +2003,146 @@ var init_compression = __esm({
1628
2003
  });
1629
2004
 
1630
2005
  // src/disk-tier.ts
1631
- var import_fs2, import_path2, import_crypto2, import_msgpackr2, _SqliteDB, DISK_MAGIC, DISK_MAGIC_V2, V2_HEADER_LEN, DISK_TIER_VERSION, DiskTier;
2006
+ function resolveDefaultDiskDir(namespace, logger) {
2007
+ const ns = namespace?.trim() ?? "";
2008
+ const nsDir = ns ? `tricache-disk-${ns}` : "tricache-disk";
2009
+ if (process.platform === "linux") {
2010
+ const shmPath = "/dev/shm";
2011
+ try {
2012
+ import_fs2.default.accessSync(shmPath, import_fs2.default.constants.W_OK | import_fs2.default.constants.R_OK);
2013
+ if (typeof import_fs2.default.statfsSync === "function") {
2014
+ const stats = import_fs2.default.statfsSync(shmPath);
2015
+ const totalBytes = Number(stats.blocks) * Number(stats.bsize);
2016
+ const freeBytes = Number(stats.bavail) * Number(stats.bsize);
2017
+ if (totalBytes >= 256 * 1024 * 1024 && freeBytes >= 128 * 1024 * 1024) {
2018
+ const targetDir = import_path2.default.join(shmPath, nsDir);
2019
+ logger?.info?.("DiskTier: Targeting Linux /dev/shm tmpfs for off-heap storage", {
2020
+ path: targetDir,
2021
+ totalBytes,
2022
+ freeBytes
2023
+ });
2024
+ return { dir: targetDir, isShm: true };
2025
+ } else {
2026
+ logger?.info?.("DiskTier: /dev/shm capacity or free space insufficient (<256MB total or <128MB free); falling back to tmpdir", {
2027
+ totalBytes,
2028
+ freeBytes
2029
+ });
2030
+ }
2031
+ }
2032
+ } catch (err) {
2033
+ logger?.debug?.("DiskTier: /dev/shm not usable, falling back to tmpdir", {
2034
+ error: err.message
2035
+ });
2036
+ }
2037
+ }
2038
+ return { dir: import_path2.default.join(import_os2.default.tmpdir(), nsDir), isShm: false };
2039
+ }
2040
+ var import_fs2, import_path2, import_crypto3, import_os2, BoundedDiskQueue, _SqliteDB, DISK_MAGIC, DISK_MAGIC_V2, V2_HEADER_LEN, DISK_TIER_VERSION, DiskTier;
1632
2041
  var init_disk_tier = __esm({
1633
2042
  "src/disk-tier.ts"() {
1634
2043
  "use strict";
1635
2044
  import_fs2 = __toESM(require("fs"), 1);
1636
2045
  import_path2 = __toESM(require("path"), 1);
1637
- import_crypto2 = __toESM(require("crypto"), 1);
1638
- import_msgpackr2 = require("msgpackr");
2046
+ import_crypto3 = __toESM(require("crypto"), 1);
2047
+ import_os2 = __toESM(require("os"), 1);
2048
+ init_codec();
1639
2049
  init_compression();
2050
+ BoundedDiskQueue = class {
2051
+ constructor(maxConcurrent = Math.min(4, Math.max(1, Math.floor((import_os2.default?.availableParallelism?.() ?? 4) / 4))), maxPending = 512, writeTimeoutMs = 500, failureThreshold = 5, cooldownMs = 5e3) {
2052
+ this.maxConcurrent = maxConcurrent;
2053
+ this.maxPending = maxPending;
2054
+ this.writeTimeoutMs = writeTimeoutMs;
2055
+ this.failureThreshold = failureThreshold;
2056
+ this.cooldownMs = cooldownMs;
2057
+ }
2058
+ maxConcurrent;
2059
+ maxPending;
2060
+ writeTimeoutMs;
2061
+ failureThreshold;
2062
+ cooldownMs;
2063
+ active = 0;
2064
+ queue = [];
2065
+ spillsDropped = 0;
2066
+ consecutiveFailures = 0;
2067
+ circuitState = "closed";
2068
+ lastStateChangeMonotonic = performance.now();
2069
+ async schedule(task) {
2070
+ const now = performance.now();
2071
+ if (this.circuitState === "open") {
2072
+ if (now - this.lastStateChangeMonotonic > this.cooldownMs) {
2073
+ this.circuitState = "half-open";
2074
+ this.lastStateChangeMonotonic = now;
2075
+ } else {
2076
+ this.spillsDropped++;
2077
+ return null;
2078
+ }
2079
+ }
2080
+ if (this.circuitState === "half-open" && this.active > 0) {
2081
+ this.spillsDropped++;
2082
+ return null;
2083
+ }
2084
+ if (this.queue.length >= this.maxPending) {
2085
+ this.spillsDropped++;
2086
+ return null;
2087
+ }
2088
+ if (this.active >= this.maxConcurrent) {
2089
+ await new Promise((resolve) => this.queue.push(resolve));
2090
+ }
2091
+ this.active++;
2092
+ let timeoutId = null;
2093
+ try {
2094
+ const result = await Promise.race([
2095
+ task(),
2096
+ new Promise((_, reject) => {
2097
+ timeoutId = setTimeout(
2098
+ () => reject(new Error(`Disk write exceeded timeout of ${this.writeTimeoutMs}ms`)),
2099
+ this.writeTimeoutMs
2100
+ );
2101
+ })
2102
+ ]);
2103
+ this.consecutiveFailures = 0;
2104
+ if (this.circuitState === "half-open") {
2105
+ this.circuitState = "closed";
2106
+ this.lastStateChangeMonotonic = performance.now();
2107
+ }
2108
+ return result;
2109
+ } catch {
2110
+ this.consecutiveFailures++;
2111
+ if (this.consecutiveFailures >= this.failureThreshold || this.circuitState === "half-open") {
2112
+ this.circuitState = "open";
2113
+ this.lastStateChangeMonotonic = performance.now();
2114
+ }
2115
+ this.spillsDropped++;
2116
+ return null;
2117
+ } finally {
2118
+ if (timeoutId) clearTimeout(timeoutId);
2119
+ this.active--;
2120
+ const next = this.queue.shift();
2121
+ if (next) next();
2122
+ }
2123
+ }
2124
+ getStats() {
2125
+ return {
2126
+ activeWrites: this.active,
2127
+ pendingWrites: this.queue.length,
2128
+ spillsDropped: this.spillsDropped,
2129
+ circuitState: this.circuitState,
2130
+ lastTripTimestamp: this.lastStateChangeMonotonic
2131
+ };
2132
+ }
2133
+ reset() {
2134
+ this.consecutiveFailures = 0;
2135
+ this.circuitState = "closed";
2136
+ this.lastStateChangeMonotonic = performance.now();
2137
+ }
2138
+ };
1640
2139
  _SqliteDB = null;
1641
2140
  try {
1642
- const sqlite = process.getBuiltinModule("node:sqlite");
1643
- _SqliteDB = sqlite?.DatabaseSync ?? null;
2141
+ const proc = process;
2142
+ if (typeof proc.getBuiltinModule === "function") {
2143
+ const sqlite = proc.getBuiltinModule("node:sqlite");
2144
+ _SqliteDB = sqlite?.DatabaseSync ?? null;
2145
+ }
1644
2146
  } catch {
1645
2147
  }
1646
2148
  DISK_MAGIC = Buffer.from([68, 84, 73, 69, 82, 86, 49, 0]);
@@ -1649,6 +2151,8 @@ var init_disk_tier = __esm({
1649
2151
  DISK_TIER_VERSION = 1;
1650
2152
  DiskTier = class {
1651
2153
  opts;
2154
+ codec;
2155
+ diskQueue;
1652
2156
  dirReady = false;
1653
2157
  diskUsageBytes = 0;
1654
2158
  usageCounted = false;
@@ -1656,6 +2160,14 @@ var init_disk_tier = __esm({
1656
2160
  // maintained in-memory; avoids walkCacheFiles() in stats
1657
2161
  /** Next bucket index (0–255) for the staggered janitor wheel. */
1658
2162
  _nextJanitorBucket = 0;
2163
+ // ── High-watermark pruning & host volume health state ─────────────────────
2164
+ _isPruning = false;
2165
+ _pruneRounds = 0;
2166
+ _entriesPruned = 0;
2167
+ _spillsShedTotal = 0;
2168
+ _hostVolumeLowSpace = false;
2169
+ _hostVolumeLowSpacePauses = 0;
2170
+ _writeCounter = 0;
1659
2171
  // ── SQLite metadata index (optional, requires node:sqlite) ───────────────
1660
2172
  _db = null;
1661
2173
  _stmtInsert = null;
@@ -1670,8 +2182,19 @@ var init_disk_tier = __esm({
1670
2182
  // DELETE expired rows
1671
2183
  _stmtStats = null;
1672
2184
  // COUNT + SUM(size)
2185
+ _stmtPruneChunk = null;
2186
+ // SELECT chunk for watermark pruning
1673
2187
  constructor(opts) {
1674
2188
  this.opts = opts;
2189
+ this.codec = opts.codec ?? defaultCodec;
2190
+ const defaultConcurrent = Math.min(4, Math.max(1, Math.floor((import_os2.default?.availableParallelism?.() ?? 4) / 4)));
2191
+ this.diskQueue = new BoundedDiskQueue(
2192
+ opts.diskMaxConcurrentWrites ?? defaultConcurrent,
2193
+ opts.diskMaxPendingWrites ?? 512,
2194
+ opts.diskWriteTimeoutMs ?? 500,
2195
+ opts.diskCircuitBreakerThreshold ?? 5,
2196
+ opts.diskCircuitBreakerCooldownMs ?? 5e3
2197
+ );
1675
2198
  }
1676
2199
  // ── Helpers ───────────────────────────────────────────────────────────────
1677
2200
  ensureDir() {
@@ -1706,15 +2229,30 @@ var init_disk_tier = __esm({
1706
2229
  PRAGMA synchronous = NORMAL;
1707
2230
  PRAGMA temp_store = MEMORY;
1708
2231
  CREATE TABLE IF NOT EXISTS meta (
1709
- key_hash TEXT PRIMARY KEY,
1710
- file_path TEXT NOT NULL,
1711
- expires_at INTEGER NOT NULL,
1712
- size INTEGER NOT NULL DEFAULT 0
2232
+ key_hash TEXT PRIMARY KEY,
2233
+ file_path TEXT NOT NULL,
2234
+ expires_at INTEGER NOT NULL,
2235
+ size INTEGER NOT NULL DEFAULT 0,
2236
+ priority INTEGER NOT NULL DEFAULT 2,
2237
+ last_accessed_at INTEGER NOT NULL DEFAULT 0
1713
2238
  );
1714
2239
  CREATE INDEX IF NOT EXISTS idx_expires ON meta (expires_at);
2240
+ CREATE INDEX IF NOT EXISTS idx_priority_access ON meta (priority ASC, last_accessed_at ASC);
1715
2241
  `);
2242
+ try {
2243
+ this._db.exec("ALTER TABLE meta ADD COLUMN priority INTEGER NOT NULL DEFAULT 2;");
2244
+ } catch {
2245
+ }
2246
+ try {
2247
+ this._db.exec("ALTER TABLE meta ADD COLUMN last_accessed_at INTEGER NOT NULL DEFAULT 0;");
2248
+ } catch {
2249
+ }
2250
+ try {
2251
+ this._db.exec("CREATE INDEX IF NOT EXISTS idx_priority_access ON meta (priority ASC, last_accessed_at ASC);");
2252
+ } catch {
2253
+ }
1716
2254
  this._stmtInsert = this._db.prepare(
1717
- "INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size) VALUES (?,?,?,?)"
2255
+ "INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size, priority, last_accessed_at) VALUES (?,?,?,?,?,?)"
1718
2256
  );
1719
2257
  this._stmtSelect = this._db.prepare(
1720
2258
  "SELECT file_path, expires_at FROM meta WHERE key_hash = ?"
@@ -1727,13 +2265,16 @@ var init_disk_tier = __esm({
1727
2265
  this._stmtStats = this._db.prepare(
1728
2266
  "SELECT COUNT(*) AS cnt, COALESCE(SUM(size), 0) AS bytes FROM meta"
1729
2267
  );
2268
+ this._stmtPruneChunk = this._db.prepare(
2269
+ "SELECT key_hash, file_path, size FROM meta ORDER BY priority ASC, last_accessed_at ASC LIMIT 500"
2270
+ );
1730
2271
  const row = this._stmtStats.get();
1731
2272
  this.fileCount = row.cnt;
1732
2273
  this.diskUsageBytes = row.bytes;
1733
2274
  this.usageCounted = true;
1734
2275
  this.opts.logger.debug("DiskTier: SQLite index ready", { entries: row.cnt });
1735
2276
  } catch (err) {
1736
- this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
2277
+ this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = this._stmtPruneChunk = null;
1737
2278
  this.opts.logger.warn("DiskTier: SQLite init failed, using file-only mode", {
1738
2279
  error: err.message
1739
2280
  });
@@ -1766,7 +2307,7 @@ var init_disk_tier = __esm({
1766
2307
  * without knowing which filename generation was used when the file was written.
1767
2308
  */
1768
2309
  keyToHash(key) {
1769
- return import_crypto2.default.createHash("sha256").update(key, "utf8").digest("hex");
2310
+ return import_crypto3.default.createHash("sha256").update(key, "utf8").digest("hex");
1770
2311
  }
1771
2312
  /**
1772
2313
  * Build the write path for a NEW file (V3 generation).
@@ -1828,7 +2369,7 @@ var init_disk_tier = __esm({
1828
2369
  return results;
1829
2370
  }
1830
2371
  isForbidden(key) {
1831
- return this.opts.forbiddenPrefixes.some((p) => key.startsWith(p));
2372
+ return this.opts.forbiddenPrefixes?.some((p) => key.startsWith(p)) ?? false;
1832
2373
  }
1833
2374
  encrypt(data) {
1834
2375
  if (!this.opts.encryption) return data;
@@ -1880,7 +2421,16 @@ var init_disk_tier = __esm({
1880
2421
  this.ensureDir();
1881
2422
  if (!this.dirReady) return;
1882
2423
  this.ensureUsageCounted();
1883
- if (this.diskUsageBytes >= this.opts.maxBytes) return;
2424
+ if (++this._writeCounter % 2e3 === 0) {
2425
+ this.checkHostVolumeHealth();
2426
+ }
2427
+ if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes >= this.opts.maxBytes) {
2428
+ this._spillsShedTotal++;
2429
+ return;
2430
+ }
2431
+ if (this.diskUsageBytes >= this.opts.maxBytes * 0.8 && !this._isPruning) {
2432
+ void this.triggerChunkedPrune();
2433
+ }
1884
2434
  let final;
1885
2435
  try {
1886
2436
  const payload = {
@@ -1892,7 +2442,7 @@ var init_disk_tier = __esm({
1892
2442
  },
1893
2443
  writtenAt: Date.now()
1894
2444
  };
1895
- const packed = (0, import_msgpackr2.pack)(payload);
2445
+ const packed = this.codec.encode(payload);
1896
2446
  if (packed.length > this.opts.entryMaxBytes) return;
1897
2447
  let toEncrypt = packed;
1898
2448
  if (this.opts.compression && this.opts.compression !== "none" && packed.length > (this.opts.compressionThresholdBytes ?? 1024)) {
@@ -1908,39 +2458,52 @@ var init_disk_tier = __esm({
1908
2458
  }
1909
2459
  const hash = this.keyToHash(key);
1910
2460
  const filePath = this.hashToWritePath(hash, entry.expiresAt);
1911
- const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
2461
+ const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${import_crypto3.default.randomBytes(6).toString("hex")}.tmp`;
1912
2462
  this.diskUsageBytes += final.length;
1913
2463
  this.fileCount++;
1914
- try {
1915
- await import_fs2.default.promises.mkdir(import_path2.default.dirname(filePath), { recursive: true });
1916
- await import_fs2.default.promises.writeFile(tmpPath, final, { mode: 384 });
2464
+ if (this.diskUsageBytes >= this.opts.maxBytes * 0.8 && !this._isPruning) {
2465
+ void this.triggerChunkedPrune();
2466
+ }
2467
+ const result = await this.diskQueue.schedule(async () => {
1917
2468
  try {
1918
- await import_fs2.default.promises.rename(tmpPath, filePath);
1919
- } catch (renameErr) {
1920
- const code = renameErr?.code;
1921
- if (code === "EBUSY" || code === "EPERM") {
1922
- await new Promise((resolve) => setTimeout(resolve, 5));
2469
+ await import_fs2.default.promises.mkdir(import_path2.default.dirname(filePath), { recursive: true });
2470
+ await import_fs2.default.promises.writeFile(tmpPath, final, { mode: 384 });
2471
+ try {
1923
2472
  await import_fs2.default.promises.rename(tmpPath, filePath);
1924
- } else {
1925
- throw renameErr;
2473
+ } catch (renameErr) {
2474
+ const code = renameErr?.code;
2475
+ if (code === "EBUSY" || code === "EPERM") {
2476
+ await new Promise((resolve) => setTimeout(resolve, 5));
2477
+ await import_fs2.default.promises.rename(tmpPath, filePath);
2478
+ } else {
2479
+ throw renameErr;
2480
+ }
1926
2481
  }
2482
+ if (this._db) {
2483
+ const priority = typeof entry.priority === "number" ? entry.priority : 2;
2484
+ const lastAccess = typeof entry.lastAccess === "number" ? entry.lastAccess : Date.now();
2485
+ this._stmtInsert.run(hash, filePath, entry.expiresAt, final.length, priority, lastAccess);
2486
+ }
2487
+ this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
2488
+ return true;
2489
+ } catch (err) {
2490
+ try {
2491
+ await import_fs2.default.promises.unlink(tmpPath);
2492
+ } catch {
2493
+ }
2494
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
2495
+ this.fileCount = Math.max(0, this.fileCount - 1);
2496
+ if (this._db) try {
2497
+ this._stmtDelete.run(hash);
2498
+ } catch {
2499
+ }
2500
+ this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
2501
+ throw err;
1927
2502
  }
1928
- if (this._db) {
1929
- this._stmtInsert.run(hash, filePath, entry.expiresAt, final.length);
1930
- }
1931
- this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
1932
- } catch (err) {
1933
- try {
1934
- await import_fs2.default.promises.unlink(tmpPath);
1935
- } catch {
1936
- }
2503
+ });
2504
+ if (result === null) {
1937
2505
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
1938
2506
  this.fileCount = Math.max(0, this.fileCount - 1);
1939
- if (this._db) try {
1940
- this._stmtDelete.run(hash);
1941
- } catch {
1942
- }
1943
- this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
1944
2507
  }
1945
2508
  }
1946
2509
  /** Load a key from disk, or return null on miss/expiry/corruption. */
@@ -2018,7 +2581,7 @@ var init_disk_tier = __esm({
2018
2581
  }
2019
2582
  }
2020
2583
  const uncompressed = decompressWithHeader(decrypted, this.opts.compression ?? "brotli");
2021
- const payload = (0, import_msgpackr2.unpack)(uncompressed);
2584
+ const payload = this.codec.decode(uncompressed);
2022
2585
  if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
2023
2586
  if (payload.entry.expiresAt <= Date.now()) return null;
2024
2587
  const entry = payload.entry;
@@ -2136,11 +2699,12 @@ var init_disk_tier = __esm({
2136
2699
  dec = this.decrypt(raw);
2137
2700
  } catch {
2138
2701
  import_fs2.default.unlinkSync(filePath);
2702
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
2139
2703
  this.fileCount = Math.max(0, this.fileCount - 1);
2140
2704
  purged++;
2141
2705
  continue;
2142
2706
  }
2143
- const payload = (0, import_msgpackr2.unpack)(dec);
2707
+ const payload = this.codec.decode(dec);
2144
2708
  if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
2145
2709
  import_fs2.default.unlinkSync(filePath);
2146
2710
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
@@ -2299,11 +2863,12 @@ var init_disk_tier = __esm({
2299
2863
  dec = this.decrypt(raw);
2300
2864
  } catch {
2301
2865
  import_fs2.default.unlinkSync(filePath);
2866
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
2302
2867
  this.fileCount = Math.max(0, this.fileCount - 1);
2303
2868
  purged++;
2304
2869
  continue;
2305
2870
  }
2306
- const payload = (0, import_msgpackr2.unpack)(dec);
2871
+ const payload = this.codec.decode(dec);
2307
2872
  if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
2308
2873
  import_fs2.default.unlinkSync(filePath);
2309
2874
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
@@ -2342,13 +2907,141 @@ var init_disk_tier = __esm({
2342
2907
  }
2343
2908
  return cleared;
2344
2909
  }
2910
+ /**
2911
+ * Proactively checks host volume free space via statfsSync.
2912
+ * If free space on the volume drops below 10%, pauses spills to prevent
2913
+ * Kubernetes pod eviction (DiskPressure / EphemeralStorageExceeded).
2914
+ */
2915
+ checkHostVolumeHealth() {
2916
+ try {
2917
+ if (typeof import_fs2.default.statfsSync === "function") {
2918
+ const stats = import_fs2.default.statfsSync(this.opts.dir);
2919
+ const total = Number(stats.blocks);
2920
+ const avail = Number(stats.bavail);
2921
+ if (total > 0) {
2922
+ const freeRatio = avail / total;
2923
+ if (freeRatio < 0.1) {
2924
+ if (!this._hostVolumeLowSpace) {
2925
+ this._hostVolumeLowSpace = true;
2926
+ this._hostVolumeLowSpacePauses++;
2927
+ this.opts.logger.warn(
2928
+ "DiskTier: host volume has <10% free space. Pausing disk cache spills to prevent Kubernetes eviction.",
2929
+ { dir: this.opts.dir, freePct: Number((freeRatio * 100).toFixed(1)) }
2930
+ );
2931
+ }
2932
+ return false;
2933
+ } else if (this._hostVolumeLowSpace) {
2934
+ this._hostVolumeLowSpace = false;
2935
+ this.opts.logger.info(
2936
+ "DiskTier: host volume space recovered (>=10% free). Resuming disk cache spills.",
2937
+ { dir: this.opts.dir, freePct: Number((freeRatio * 100).toFixed(1)) }
2938
+ );
2939
+ return true;
2940
+ }
2941
+ }
2942
+ }
2943
+ } catch {
2944
+ }
2945
+ return true;
2946
+ }
2947
+ /**
2948
+ * Non-blocking chunked pruning:
2949
+ * Evicts oldest entries in 500-entry chunks down to 60% watermark,
2950
+ * yielding to the event loop via setImmediate between chunks.
2951
+ */
2952
+ async triggerChunkedPrune() {
2953
+ if (this._isPruning) return 0;
2954
+ this._isPruning = true;
2955
+ this._pruneRounds++;
2956
+ let prunedInThisRound = 0;
2957
+ try {
2958
+ this.ensureUsageCounted();
2959
+ const targetBytes = Math.floor(this.opts.maxBytes * 0.6);
2960
+ if (this._db && this._stmtPruneChunk) {
2961
+ while (this.diskUsageBytes > targetBytes) {
2962
+ const rows = this._stmtPruneChunk.all();
2963
+ if (!rows || rows.length === 0) break;
2964
+ for (const row of rows) {
2965
+ try {
2966
+ import_fs2.default.unlinkSync(row.file_path);
2967
+ } catch {
2968
+ }
2969
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
2970
+ this.fileCount = Math.max(0, this.fileCount - 1);
2971
+ this._entriesPruned++;
2972
+ prunedInThisRound++;
2973
+ try {
2974
+ this._stmtDelete.run(row.key_hash);
2975
+ } catch {
2976
+ }
2977
+ if (this.diskUsageBytes <= targetBytes) break;
2978
+ }
2979
+ if (this.diskUsageBytes > targetBytes) {
2980
+ await new Promise((resolve) => setImmediate(resolve));
2981
+ }
2982
+ }
2983
+ } else {
2984
+ while (this.diskUsageBytes > targetBytes) {
2985
+ const files = this.walkCacheFiles();
2986
+ if (files.length === 0) break;
2987
+ const chunk = files.slice(0, 500);
2988
+ for (const filePath of chunk) {
2989
+ try {
2990
+ const stat = import_fs2.default.statSync(filePath);
2991
+ import_fs2.default.unlinkSync(filePath);
2992
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
2993
+ this.fileCount = Math.max(0, this.fileCount - 1);
2994
+ this._entriesPruned++;
2995
+ prunedInThisRound++;
2996
+ } catch {
2997
+ }
2998
+ if (this.diskUsageBytes <= targetBytes) break;
2999
+ }
3000
+ if (this.diskUsageBytes > targetBytes) {
3001
+ await new Promise((resolve) => setImmediate(resolve));
3002
+ }
3003
+ }
3004
+ }
3005
+ } finally {
3006
+ this._isPruning = false;
3007
+ }
3008
+ return prunedInThisRound;
3009
+ }
3010
+ get isPruning() {
3011
+ return this._isPruning;
3012
+ }
3013
+ get hostVolumeLowSpace() {
3014
+ return this._hostVolumeLowSpace;
3015
+ }
3016
+ get spillsShedTotal() {
3017
+ return this._spillsShedTotal;
3018
+ }
3019
+ getPruningStats() {
3020
+ return {
3021
+ active: this._isPruning,
3022
+ pruneRounds: this._pruneRounds,
3023
+ entriesPruned: this._entriesPruned,
3024
+ spillsShedTotal: this._spillsShedTotal,
3025
+ hostVolumeLowSpacePauses: this._hostVolumeLowSpacePauses
3026
+ };
3027
+ }
2345
3028
  get stats() {
2346
3029
  if (this._db) {
2347
3030
  const row = this._stmtStats.get();
2348
3031
  this.fileCount = row.cnt;
2349
3032
  this.diskUsageBytes = row.bytes;
2350
3033
  }
2351
- return { files: this.fileCount, sizeKB: Math.round(this.diskUsageBytes / 1024), maxKB: Math.round(this.opts.maxBytes / 1024) };
3034
+ return {
3035
+ files: this.fileCount,
3036
+ sizeKB: Math.round(this.diskUsageBytes / 1024),
3037
+ maxKB: Math.round(this.opts.maxBytes / 1024),
3038
+ backpressure: this.diskQueue.getStats(),
3039
+ pruning: this.getPruningStats()
3040
+ };
3041
+ }
3042
+ /** Direct access to the bounded write queue for chaos diagnostics and canary controls. */
3043
+ get backpressure() {
3044
+ return this.diskQueue;
2352
3045
  }
2353
3046
  /** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
2354
3047
  get indexMode() {
@@ -2361,44 +3054,633 @@ var init_disk_tier = __esm({
2361
3054
  this._db.close();
2362
3055
  } catch {
2363
3056
  }
2364
- this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
3057
+ this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = this._stmtPruneChunk = null;
2365
3058
  }
2366
3059
  }
2367
3060
  };
2368
3061
  }
2369
3062
  });
2370
3063
 
2371
- // src/cache-service.ts
2372
- var cache_service_exports = {};
2373
- __export(cache_service_exports, {
2374
- CacheService: () => CacheService
2375
- });
2376
- function getGlobRegex(pattern) {
2377
- let re = globRegexCache.get(pattern);
2378
- if (re) {
2379
- globRegexCache.delete(pattern);
2380
- globRegexCache.set(pattern, re);
2381
- return re;
2382
- }
2383
- const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*+/g, ".*");
2384
- re = new RegExp("^" + escaped + "$");
2385
- if (globRegexCache.size >= GLOB_REGEX_CACHE_MAX) {
2386
- const oldestKey = globRegexCache.keys().next().value;
2387
- if (oldestKey !== void 0) globRegexCache.delete(oldestKey);
2388
- }
2389
- globRegexCache.set(pattern, re);
2390
- return re;
2391
- }
2392
- function deepFreeze(obj) {
2393
- if (obj === null || typeof obj !== "object" || Object.isFrozen(obj)) return obj;
2394
- Object.freeze(obj);
2395
- for (const v of Object.values(obj)) deepFreeze(v);
2396
- return obj;
2397
- }
2398
- function inferPriority(cacheKey) {
2399
- if (cacheKey.includes("auth:") || cacheKey.includes("session:")) return 4 /* CRITICAL */;
2400
- if (cacheKey.includes("user:") || cacheKey.includes("org:") || cacheKey.includes("profile:")) return 3 /* HIGH */;
2401
- if (cacheKey.includes("analytics:") || cacheKey.includes("report:") || cacheKey.includes("stats:")) return 1 /* LOW */;
3064
+ // src/latency-watchdog.ts
3065
+ var TierLatencyWatchdog;
3066
+ var init_latency_watchdog = __esm({
3067
+ "src/latency-watchdog.ts"() {
3068
+ "use strict";
3069
+ TierLatencyWatchdog = class {
3070
+ enabled;
3071
+ minDiskBypassMs;
3072
+ bypassRatio;
3073
+ cooldownMs;
3074
+ redisCutoffMs;
3075
+ redisRecoveryFloorMs;
3076
+ minSamples;
3077
+ disableRedis;
3078
+ // Zero-allocation rolling ring buffers
3079
+ diskRing = new Float32Array(32);
3080
+ redisRing = new Float32Array(32);
3081
+ scratch = new Float32Array(32);
3082
+ diskIdx = 0;
3083
+ redisIdx = 0;
3084
+ diskCount = 0;
3085
+ redisCount = 0;
3086
+ // Cached amortized p95 values
3087
+ cachedDiskP95 = 0;
3088
+ cachedRedisP95 = 0;
3089
+ // State machine & control-theory flags
3090
+ stage = 0;
3091
+ redisDampened = false;
3092
+ // Asymmetric hysteresis latch
3093
+ redisRecoveryConsecutiveSamples = 0;
3094
+ bypassedUntilMonotonic = 0;
3095
+ canaryInFlight = false;
3096
+ bypassedTotal = 0;
3097
+ constructor(options = {}) {
3098
+ this.enabled = options.enabled ?? true;
3099
+ this.minDiskBypassMs = options.minDiskBypassMs ?? 10;
3100
+ this.bypassRatio = options.bypassRatio ?? 1.5;
3101
+ this.cooldownMs = options.cooldownMs ?? 3e4;
3102
+ this.redisCutoffMs = options.redisCutoffMs ?? 15;
3103
+ this.redisRecoveryFloorMs = options.redisRecoveryFloorMs ?? 10;
3104
+ this.minSamples = options.minSamples ?? 16;
3105
+ this.disableRedis = options.disableRedis ?? false;
3106
+ }
3107
+ setDisableRedis(disabled) {
3108
+ this.disableRedis = disabled;
3109
+ if (disabled) {
3110
+ this.stage = 0;
3111
+ this.bypassedUntilMonotonic = 0;
3112
+ this.canaryInFlight = false;
3113
+ this.redisRecoveryConsecutiveSamples = 0;
3114
+ }
3115
+ }
3116
+ /**
3117
+ * Record disk read duration in milliseconds (zero-allocation hot path).
3118
+ */
3119
+ recordDisk(ms) {
3120
+ if (!this.enabled) return;
3121
+ this.diskRing[this.diskIdx++ & 31] = ms;
3122
+ this.diskCount++;
3123
+ if ((this.diskIdx & 31) === 0) {
3124
+ this.recalculateP95();
3125
+ }
3126
+ }
3127
+ /**
3128
+ * Record Redis read duration in milliseconds (zero-allocation hot path).
3129
+ */
3130
+ recordRedis(ms) {
3131
+ if (!this.enabled || this.disableRedis) return;
3132
+ this.redisRing[this.redisIdx++ & 31] = ms;
3133
+ this.redisCount++;
3134
+ if (ms <= this.redisRecoveryFloorMs) {
3135
+ this.redisRecoveryConsecutiveSamples++;
3136
+ } else {
3137
+ this.redisRecoveryConsecutiveSamples = 0;
3138
+ }
3139
+ if ((this.redisIdx & 31) === 0) {
3140
+ this.recalculateP95();
3141
+ }
3142
+ }
3143
+ recalculateP95() {
3144
+ if (this.diskCount >= this.minSamples) {
3145
+ this.cachedDiskP95 = this.computeP95(this.diskRing, Math.min(this.diskCount, 32));
3146
+ }
3147
+ if (this.redisCount >= this.minSamples) {
3148
+ this.cachedRedisP95 = this.computeP95(this.redisRing, Math.min(this.redisCount, 32));
3149
+ }
3150
+ this.evaluateControlLoop();
3151
+ }
3152
+ computeP95(ring, count) {
3153
+ for (let i = 0; i < count; i++) {
3154
+ this.scratch[i] = ring[i];
3155
+ }
3156
+ this.scratch.subarray(0, count).sort();
3157
+ const rank = Math.min(count - 1, Math.max(0, Math.floor((count - 1) * 0.95)));
3158
+ return this.scratch[rank];
3159
+ }
3160
+ /**
3161
+ * Core Control Loop:
3162
+ * - Evaluates asymmetric hysteresis on Redis circuit.
3163
+ * - Assigns graduated stage (0, 1, 2, 3) with anti-synchronicity jitter.
3164
+ */
3165
+ evaluateControlLoop() {
3166
+ if (this.disableRedis) {
3167
+ this.stage = 0;
3168
+ return;
3169
+ }
3170
+ if (this.cachedRedisP95 >= this.redisCutoffMs) {
3171
+ this.redisDampened = true;
3172
+ } else if (this.redisDampened && this.cachedRedisP95 <= this.redisRecoveryFloorMs && this.redisRecoveryConsecutiveSamples >= this.minSamples) {
3173
+ this.redisDampened = false;
3174
+ }
3175
+ if (this.redisDampened) {
3176
+ this.stage = 0;
3177
+ return;
3178
+ }
3179
+ if (this.diskCount < this.minSamples || this.redisCount < this.minSamples) {
3180
+ return;
3181
+ }
3182
+ const diskP95 = this.cachedDiskP95;
3183
+ const redisP95 = Math.max(0.1, this.cachedRedisP95);
3184
+ if (diskP95 >= 50) {
3185
+ if (this.stage !== 3) {
3186
+ this.stage = 3;
3187
+ this.bypassedUntilMonotonic = performance.now() + this.calculateJitteredCooldown();
3188
+ this.bypassedTotal++;
3189
+ }
3190
+ } else if (diskP95 >= this.minDiskBypassMs * 2.5 && diskP95 >= redisP95 * (this.bypassRatio * 1.5)) {
3191
+ if (this.stage !== 2) {
3192
+ this.stage = 2;
3193
+ this.bypassedTotal++;
3194
+ }
3195
+ } else if (diskP95 >= this.minDiskBypassMs && diskP95 >= redisP95 * this.bypassRatio) {
3196
+ if (this.stage !== 1) {
3197
+ this.stage = 1;
3198
+ this.bypassedTotal++;
3199
+ }
3200
+ } else {
3201
+ this.stage = 0;
3202
+ this.bypassedUntilMonotonic = 0;
3203
+ this.canaryInFlight = false;
3204
+ }
3205
+ }
3206
+ calculateJitteredCooldown() {
3207
+ const jitterFactor = 0.7 + Math.random() * 0.6;
3208
+ return this.cooldownMs * jitterFactor;
3209
+ }
3210
+ /**
3211
+ * Determine whether a read is permitted to check the disk tier.
3212
+ *
3213
+ * In Stage 1 and 2, sheds traffic probabilistically.
3214
+ * In Stage 3, blocks all reads except for a single canary probe once cooldown expires.
3215
+ *
3216
+ * @param randomOverride Optional seeded random number [0, 1) for deterministic unit testing.
3217
+ */
3218
+ isDiskAllowed(randomOverride) {
3219
+ if (!this.enabled || this.disableRedis) return true;
3220
+ if (this.stage === 0) return true;
3221
+ const rand = randomOverride !== void 0 ? randomOverride : Math.random();
3222
+ if (this.stage === 1) {
3223
+ return rand > 0.25;
3224
+ }
3225
+ if (this.stage === 2) {
3226
+ return rand > 0.75;
3227
+ }
3228
+ const now = performance.now();
3229
+ if (now < this.bypassedUntilMonotonic) {
3230
+ return false;
3231
+ }
3232
+ if (!this.canaryInFlight) {
3233
+ this.canaryInFlight = true;
3234
+ return true;
3235
+ }
3236
+ return false;
3237
+ }
3238
+ /**
3239
+ * Callback invoked when the single canary read probe completes.
3240
+ */
3241
+ onCanaryResult(success, elapsedMs) {
3242
+ if (!this.canaryInFlight) return;
3243
+ this.canaryInFlight = false;
3244
+ if (success && elapsedMs < this.minDiskBypassMs) {
3245
+ this.stage = 0;
3246
+ this.bypassedUntilMonotonic = 0;
3247
+ this.recordDisk(elapsedMs);
3248
+ } else {
3249
+ this.bypassedUntilMonotonic = performance.now() + this.calculateJitteredCooldown();
3250
+ this.bypassedTotal++;
3251
+ }
3252
+ }
3253
+ getTelemetry() {
3254
+ return {
3255
+ bypassActive: this.stage > 0,
3256
+ bypassStage: this.stage,
3257
+ diskP95Ms: Number(this.cachedDiskP95.toFixed(2)),
3258
+ redisP95Ms: Number(this.cachedRedisP95.toFixed(2)),
3259
+ redisDampened: this.redisDampened,
3260
+ bypassedTotal: this.bypassedTotal
3261
+ };
3262
+ }
3263
+ };
3264
+ }
3265
+ });
3266
+
3267
+ // src/utils/cgroup.ts
3268
+ function readCgroupMemoryLimit() {
3269
+ if (process.platform !== "linux") {
3270
+ return Infinity;
3271
+ }
3272
+ try {
3273
+ if (import_node_fs.default.existsSync("/sys/fs/cgroup/memory.max")) {
3274
+ const raw = import_node_fs.default.readFileSync("/sys/fs/cgroup/memory.max", "utf8").trim();
3275
+ if (raw === "max") {
3276
+ return Infinity;
3277
+ }
3278
+ const bytes = parseInt(raw, 10);
3279
+ if (Number.isFinite(bytes) && bytes > 0 && bytes < UNBOUNDED_CGROUP_THRESHOLD) {
3280
+ return bytes;
3281
+ }
3282
+ }
3283
+ } catch {
3284
+ }
3285
+ try {
3286
+ if (import_node_fs.default.existsSync("/sys/fs/cgroup/memory/memory.limit_in_bytes")) {
3287
+ const raw = import_node_fs.default.readFileSync("/sys/fs/cgroup/memory/memory.limit_in_bytes", "utf8").trim();
3288
+ const bytes = parseInt(raw, 10);
3289
+ if (Number.isFinite(bytes) && bytes > 0 && bytes < UNBOUNDED_CGROUP_THRESHOLD) {
3290
+ return bytes;
3291
+ }
3292
+ }
3293
+ } catch {
3294
+ }
3295
+ return Infinity;
3296
+ }
3297
+ function getV8HeapLimit() {
3298
+ try {
3299
+ const stats = import_node_v8.default.getHeapStatistics();
3300
+ if (stats && Number.isFinite(stats.heap_size_limit) && stats.heap_size_limit > 0) {
3301
+ return stats.heap_size_limit;
3302
+ }
3303
+ } catch {
3304
+ }
3305
+ return Infinity;
3306
+ }
3307
+ function resolveAutonomousL1MaxBytes(options) {
3308
+ const cgroup = options?.cgroupLimit !== void 0 ? options.cgroupLimit : readCgroupMemoryLimit();
3309
+ const v8Limit = options?.v8HeapLimit !== void 0 ? options.v8HeapLimit : getV8HeapLimit();
3310
+ const ceiling = options?.defaultCeilingBytes ?? DEFAULT_AUTONOMOUS_L1_CEILING_BYTES;
3311
+ const cgroupCap = Number.isFinite(cgroup) && cgroup > 0 ? cgroup * 0.4 : Infinity;
3312
+ const v8Cap = Number.isFinite(v8Limit) && v8Limit > 0 ? v8Limit * 0.5 : Infinity;
3313
+ const resolved = Math.min(cgroupCap, v8Cap, ceiling);
3314
+ if (!Number.isFinite(resolved) || resolved <= 0) {
3315
+ return ceiling;
3316
+ }
3317
+ return Math.max(MIN_AUTONOMOUS_L1_FLOOR_BYTES, Math.floor(resolved));
3318
+ }
3319
+ var import_node_fs, import_node_v8, UNBOUNDED_CGROUP_THRESHOLD, DEFAULT_AUTONOMOUS_L1_CEILING_BYTES, MIN_AUTONOMOUS_L1_FLOOR_BYTES;
3320
+ var init_cgroup = __esm({
3321
+ "src/utils/cgroup.ts"() {
3322
+ "use strict";
3323
+ import_node_fs = __toESM(require("fs"), 1);
3324
+ import_node_v8 = __toESM(require("v8"), 1);
3325
+ UNBOUNDED_CGROUP_THRESHOLD = 9e18;
3326
+ DEFAULT_AUTONOMOUS_L1_CEILING_BYTES = 512 * 1024 * 1024;
3327
+ MIN_AUTONOMOUS_L1_FLOOR_BYTES = 16 * 1024 * 1024;
3328
+ }
3329
+ });
3330
+
3331
+ // src/adapters/auto-pipeliner.ts
3332
+ var AutoPipeliner;
3333
+ var init_auto_pipeliner = __esm({
3334
+ "src/adapters/auto-pipeliner.ts"() {
3335
+ "use strict";
3336
+ AutoPipeliner = class {
3337
+ constructor(client, options) {
3338
+ this.client = client;
3339
+ this.maxBatchSize = options?.maxBatchSize ?? 100;
3340
+ this.enabled = options?.enabled ?? true;
3341
+ }
3342
+ client;
3343
+ maxBatchSize;
3344
+ enabled;
3345
+ queue = [];
3346
+ scheduled = false;
3347
+ inFlight = false;
3348
+ statsInternal = {
3349
+ batchesDispatched: 0,
3350
+ operationsBatched: 0
3351
+ };
3352
+ get stats() {
3353
+ return {
3354
+ batchesDispatched: this.statsInternal.batchesDispatched,
3355
+ operationsBatched: this.statsInternal.operationsBatched,
3356
+ pendingQueueSize: this.queue.length
3357
+ };
3358
+ }
3359
+ async get(key) {
3360
+ if (!this.enabled || !this.supportsPipelines()) {
3361
+ return this.client.get(key);
3362
+ }
3363
+ return new Promise((resolve, reject) => {
3364
+ this.enqueue({ type: "get", key, resolve, reject });
3365
+ });
3366
+ }
3367
+ async setex(key, seconds, value) {
3368
+ if (!this.enabled || !this.supportsPipelines()) {
3369
+ if (typeof this.client.setex === "function") {
3370
+ await this.client.setex(key, seconds, value);
3371
+ } else {
3372
+ await this.client.set(key, value, "EX", seconds);
3373
+ }
3374
+ return;
3375
+ }
3376
+ return new Promise((resolve, reject) => {
3377
+ this.enqueue({ type: "setex", key, seconds, value, resolve, reject });
3378
+ });
3379
+ }
3380
+ async del(...keys) {
3381
+ if (keys.length === 0) return 0;
3382
+ if (!this.enabled || !this.supportsPipelines()) {
3383
+ return this.client.del(...keys);
3384
+ }
3385
+ return new Promise((resolve, reject) => {
3386
+ this.enqueue({ type: "del", keys, resolve, reject });
3387
+ });
3388
+ }
3389
+ supportsPipelines() {
3390
+ return Boolean(
3391
+ typeof this.client?.pipeline === "function" || typeof this.client?.multi === "function"
3392
+ );
3393
+ }
3394
+ enqueue(op) {
3395
+ this.queue.push(op);
3396
+ if (this.queue.length >= this.maxBatchSize) {
3397
+ void this.flush();
3398
+ return;
3399
+ }
3400
+ if (!this.scheduled) {
3401
+ this.scheduled = true;
3402
+ queueMicrotask(() => {
3403
+ this.scheduled = false;
3404
+ void this.flush();
3405
+ });
3406
+ }
3407
+ }
3408
+ async flush() {
3409
+ if (this.queue.length === 0) return;
3410
+ const batch = this.queue;
3411
+ this.queue = [];
3412
+ this.scheduled = false;
3413
+ this.statsInternal.batchesDispatched++;
3414
+ this.statsInternal.operationsBatched += batch.length;
3415
+ const pipe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
3416
+ for (const op of batch) {
3417
+ switch (op.type) {
3418
+ case "get":
3419
+ pipe.get(op.key);
3420
+ break;
3421
+ case "setex":
3422
+ pipe.setex(op.key, op.seconds, op.value);
3423
+ break;
3424
+ case "del":
3425
+ pipe.del(...op.keys);
3426
+ break;
3427
+ }
3428
+ }
3429
+ try {
3430
+ const results = await pipe.exec();
3431
+ if (!results) {
3432
+ for (const op of batch) {
3433
+ if (op.type === "get") op.resolve(null);
3434
+ else if (op.type === "del") op.resolve(0);
3435
+ else op.resolve();
3436
+ }
3437
+ return;
3438
+ }
3439
+ for (let i = 0; i < batch.length; i++) {
3440
+ const op = batch[i];
3441
+ const resTuple = results[i];
3442
+ if (!resTuple) {
3443
+ if (op.type === "get") op.resolve(null);
3444
+ else if (op.type === "del") op.resolve(0);
3445
+ else op.resolve();
3446
+ continue;
3447
+ }
3448
+ const [err, val] = resTuple;
3449
+ if (err) {
3450
+ op.reject(err instanceof Error ? err : new Error(String(err)));
3451
+ } else {
3452
+ if (op.type === "get") {
3453
+ op.resolve(val != null ? String(val) : null);
3454
+ } else if (op.type === "del") {
3455
+ op.resolve(typeof val === "number" ? val : Number(val) || 0);
3456
+ } else {
3457
+ op.resolve();
3458
+ }
3459
+ }
3460
+ }
3461
+ } catch (err) {
3462
+ for (const op of batch) {
3463
+ op.reject(err instanceof Error ? err : new Error(String(err)));
3464
+ }
3465
+ }
3466
+ }
3467
+ };
3468
+ }
3469
+ });
3470
+
3471
+ // src/ipc-telemetry.ts
3472
+ function resolveIpcSocketPath(id = process.pid) {
3473
+ if (process.platform === "win32") {
3474
+ return `\\\\.\\pipe\\tricache-${id}`;
3475
+ }
3476
+ const dir = process.env.TMPDIR || "/tmp";
3477
+ return import_node_path.default.join(dir, `tricache-${id}.sock`);
3478
+ }
3479
+ var import_node_net, import_node_fs2, import_node_path, IpcTelemetryServer;
3480
+ var init_ipc_telemetry = __esm({
3481
+ "src/ipc-telemetry.ts"() {
3482
+ "use strict";
3483
+ import_node_net = __toESM(require("net"), 1);
3484
+ import_node_fs2 = __toESM(require("fs"), 1);
3485
+ import_node_path = __toESM(require("path"), 1);
3486
+ IpcTelemetryServer = class {
3487
+ constructor(cache, customSocketPath) {
3488
+ this.cache = cache;
3489
+ this.socketPath = customSocketPath || resolveIpcSocketPath();
3490
+ }
3491
+ cache;
3492
+ server = null;
3493
+ socketPath;
3494
+ _closed = false;
3495
+ _exitHandler = null;
3496
+ _sigintHandler = null;
3497
+ _sigtermHandler = null;
3498
+ /**
3499
+ * Start listening on the IPC socket / pipe.
3500
+ */
3501
+ async start() {
3502
+ if (this.server && this.server.listening) return;
3503
+ if (process.platform !== "win32" && import_node_fs2.default.existsSync(this.socketPath)) {
3504
+ await new Promise((resolve) => {
3505
+ const testSocket = import_node_net.default.createConnection(this.socketPath);
3506
+ testSocket.once("connect", () => {
3507
+ testSocket.destroy();
3508
+ resolve();
3509
+ });
3510
+ testSocket.once("error", () => {
3511
+ testSocket.destroy();
3512
+ try {
3513
+ import_node_fs2.default.unlinkSync(this.socketPath);
3514
+ } catch {
3515
+ }
3516
+ resolve();
3517
+ });
3518
+ });
3519
+ }
3520
+ this.server = import_node_net.default.createServer((socket) => {
3521
+ let buffer = "";
3522
+ socket.on("data", (chunk) => {
3523
+ buffer += chunk.toString("utf8");
3524
+ let newlineIndex;
3525
+ while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
3526
+ const line = buffer.slice(0, newlineIndex).trim();
3527
+ buffer = buffer.slice(newlineIndex + 1);
3528
+ if (!line) continue;
3529
+ setImmediate(() => {
3530
+ if (socket.destroyed) return;
3531
+ try {
3532
+ let cmd = line;
3533
+ try {
3534
+ const parsed = JSON.parse(line);
3535
+ if (parsed && typeof parsed.cmd === "string") {
3536
+ cmd = parsed.cmd;
3537
+ }
3538
+ } catch {
3539
+ }
3540
+ if (cmd === "PING") {
3541
+ socket.write(JSON.stringify({ pong: true, timestamp: Date.now() }) + "\n");
3542
+ return;
3543
+ }
3544
+ if (cmd === "GET_METRICS" || cmd === "INSPECT") {
3545
+ const payload = this.getSnapshot();
3546
+ const serialized = JSON.stringify(payload) + "\n";
3547
+ socket.write(serialized);
3548
+ return;
3549
+ }
3550
+ socket.write(JSON.stringify({ error: `Unknown command: ${cmd}` }) + "\n");
3551
+ } catch (err) {
3552
+ if (!socket.destroyed) {
3553
+ socket.write(JSON.stringify({ error: err.message }) + "\n");
3554
+ }
3555
+ }
3556
+ });
3557
+ }
3558
+ });
3559
+ socket.on("error", () => {
3560
+ });
3561
+ });
3562
+ await new Promise((resolve, reject) => {
3563
+ this.server.once("error", reject);
3564
+ this.server.listen(this.socketPath, () => {
3565
+ this.server.removeListener("error", reject);
3566
+ resolve();
3567
+ });
3568
+ });
3569
+ this._exitHandler = () => this._unlinkSocket();
3570
+ this._sigintHandler = () => {
3571
+ this._unlinkSocket();
3572
+ process.exit(0);
3573
+ };
3574
+ this._sigtermHandler = () => {
3575
+ this._unlinkSocket();
3576
+ process.exit(0);
3577
+ };
3578
+ process.once("exit", this._exitHandler);
3579
+ process.once("SIGINT", this._sigintHandler);
3580
+ process.once("SIGTERM", this._sigtermHandler);
3581
+ }
3582
+ /**
3583
+ * Build a complete telemetry snapshot from the underlying cache provider.
3584
+ */
3585
+ getSnapshot() {
3586
+ const metrics = this.cache.metrics();
3587
+ const stats = typeof this.cache.stats === "function" ? this.cache.stats() : void 0;
3588
+ const hotKeys = typeof this.cache.hotKeys === "function" ? this.cache.hotKeys(10) : void 0;
3589
+ const health = typeof this.cache.health === "function" ? this.cache.health() : void 0;
3590
+ const l1MaxBytes = this.cache.options?.l1MaxBytes ?? metrics.l1?.maxBytes;
3591
+ return {
3592
+ pid: process.pid,
3593
+ uptimeMs: metrics.uptimeMs,
3594
+ timestamp: Date.now(),
3595
+ namespace: this.cache.options?.namespace || metrics.namespace,
3596
+ l1MaxBytes,
3597
+ metrics,
3598
+ stats,
3599
+ hotKeys,
3600
+ health
3601
+ };
3602
+ }
3603
+ _unlinkSocket() {
3604
+ if (this._closed) return;
3605
+ this._closed = true;
3606
+ try {
3607
+ this.server?.close();
3608
+ } catch {
3609
+ }
3610
+ if (process.platform !== "win32") {
3611
+ try {
3612
+ if (import_node_fs2.default.existsSync(this.socketPath)) {
3613
+ import_node_fs2.default.unlinkSync(this.socketPath);
3614
+ }
3615
+ } catch {
3616
+ }
3617
+ }
3618
+ }
3619
+ /**
3620
+ * Gracefully close the IPC telemetry server and clean up handlers and sockets.
3621
+ */
3622
+ async close() {
3623
+ if (this._exitHandler) {
3624
+ process.removeListener("exit", this._exitHandler);
3625
+ this._exitHandler = null;
3626
+ }
3627
+ if (this._sigintHandler) {
3628
+ process.removeListener("SIGINT", this._sigintHandler);
3629
+ this._sigintHandler = null;
3630
+ }
3631
+ if (this._sigtermHandler) {
3632
+ process.removeListener("SIGTERM", this._sigtermHandler);
3633
+ this._sigtermHandler = null;
3634
+ }
3635
+ this._unlinkSocket();
3636
+ return new Promise((resolve) => {
3637
+ if (!this.server || !this.server.listening) {
3638
+ resolve();
3639
+ return;
3640
+ }
3641
+ this.server.close(() => resolve());
3642
+ });
3643
+ }
3644
+ get isListening() {
3645
+ return Boolean(this.server && this.server.listening);
3646
+ }
3647
+ };
3648
+ }
3649
+ });
3650
+
3651
+ // src/cache-service.ts
3652
+ var cache_service_exports = {};
3653
+ __export(cache_service_exports, {
3654
+ CacheService: () => CacheService,
3655
+ ProcessTerminationBus: () => ProcessTerminationBus,
3656
+ deepMergeOptions: () => deepMergeOptions
3657
+ });
3658
+ function getGlobRegex(pattern) {
3659
+ let re = globRegexCache.get(pattern);
3660
+ if (re) {
3661
+ globRegexCache.delete(pattern);
3662
+ globRegexCache.set(pattern, re);
3663
+ return re;
3664
+ }
3665
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*+/g, ".*");
3666
+ re = new RegExp("^" + escaped + "$");
3667
+ if (globRegexCache.size >= GLOB_REGEX_CACHE_MAX) {
3668
+ const oldestKey = globRegexCache.keys().next().value;
3669
+ if (oldestKey !== void 0) globRegexCache.delete(oldestKey);
3670
+ }
3671
+ globRegexCache.set(pattern, re);
3672
+ return re;
3673
+ }
3674
+ function deepFreeze(obj) {
3675
+ if (obj === null || typeof obj !== "object" || Object.isFrozen(obj)) return obj;
3676
+ Object.freeze(obj);
3677
+ for (const v of Object.values(obj)) deepFreeze(v);
3678
+ return obj;
3679
+ }
3680
+ function inferPriority(cacheKey) {
3681
+ if (cacheKey.includes("auth:") || cacheKey.includes("session:")) return 4 /* CRITICAL */;
3682
+ if (cacheKey.includes("user:") || cacheKey.includes("org:") || cacheKey.includes("profile:")) return 3 /* HIGH */;
3683
+ if (cacheKey.includes("analytics:") || cacheKey.includes("report:") || cacheKey.includes("stats:")) return 1 /* LOW */;
2402
3684
  return 2 /* NORMAL */;
2403
3685
  }
2404
3686
  function detectServerlessRuntime() {
@@ -2411,22 +3693,44 @@ function detectServerlessRuntime() {
2411
3693
  if (process.env["VERCEL"]) return "Vercel";
2412
3694
  return null;
2413
3695
  }
2414
- var import_ioredis, import_msgpackr3, import_crypto3, import_os2, import_node_v8, import_fs3, import_path3, LUA_COMPARE_AND_DELETE, SNAPSHOT_VERSION, DEFAULT_SNAPSHOT_MAX_AGE, SNAPSHOT_MAX_FILE_BYTES, DEFAULT_CATEGORY_LIMITS, DEFAULT_FORBIDDEN_PREFIXES, DEFAULT_COUNTER_TTL_SECONDS, GLOB_REGEX_CACHE_MAX, globRegexCache, L2CircuitBreaker, LatencyTracker, GLOBAL_KEY, CacheService;
3696
+ function isPlainObject(item) {
3697
+ return typeof item === "object" && item !== null && item.constructor === Object;
3698
+ }
3699
+ function deepMergeOptions(base, overrides) {
3700
+ if (!overrides) return { ...base };
3701
+ const output = { ...base };
3702
+ for (const key of Object.keys(overrides)) {
3703
+ const sourceVal = overrides[key];
3704
+ if (sourceVal === void 0) continue;
3705
+ const targetVal = output[key];
3706
+ if (isPlainObject(targetVal) && isPlainObject(sourceVal)) {
3707
+ output[key] = deepMergeOptions(targetVal, sourceVal);
3708
+ } else {
3709
+ output[key] = sourceVal;
3710
+ }
3711
+ }
3712
+ return output;
3713
+ }
3714
+ var import_ioredis, import_crypto4, import_os3, import_node_v82, import_fs3, import_path3, LUA_COMPARE_AND_DELETE, SNAPSHOT_VERSION, DEFAULT_SNAPSHOT_MAX_AGE, INDEFINITE_TTL_SECONDS, SNAPSHOT_MAX_FILE_BYTES, DEFAULT_CATEGORY_LIMITS, DEFAULT_FORBIDDEN_PREFIXES, DEFAULT_COUNTER_TTL_SECONDS, GLOB_REGEX_CACHE_MAX, globRegexCache, L2CircuitBreaker, LatencyTracker, GLOBAL_KEY, ProcessTerminationBus, CacheService;
2415
3715
  var init_cache_service = __esm({
2416
3716
  "src/cache-service.ts"() {
2417
3717
  "use strict";
2418
3718
  import_ioredis = require("ioredis");
2419
- import_msgpackr3 = require("msgpackr");
2420
- import_crypto3 = __toESM(require("crypto"), 1);
2421
- import_os2 = __toESM(require("os"), 1);
3719
+ init_codec();
3720
+ import_crypto4 = __toESM(require("crypto"), 1);
3721
+ import_os3 = __toESM(require("os"), 1);
2422
3722
  init_worker_pool();
2423
- import_node_v8 = __toESM(require("v8"), 1);
3723
+ import_node_v82 = __toESM(require("v8"), 1);
2424
3724
  import_fs3 = __toESM(require("fs"), 1);
2425
3725
  import_path3 = __toESM(require("path"), 1);
2426
3726
  init_types();
2427
3727
  init_encryption();
2428
3728
  init_smart_memory_cache();
2429
3729
  init_disk_tier();
3730
+ init_latency_watchdog();
3731
+ init_cgroup();
3732
+ init_auto_pipeliner();
3733
+ init_ipc_telemetry();
2430
3734
  init_compression();
2431
3735
  LUA_COMPARE_AND_DELETE = `
2432
3736
  local currentTs = redis.call('HGET', KEYS[1], 't')
@@ -2437,6 +3741,7 @@ return 0
2437
3741
  `;
2438
3742
  SNAPSHOT_VERSION = 1;
2439
3743
  DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
3744
+ INDEFINITE_TTL_SECONDS = 31536e3;
2440
3745
  SNAPSHOT_MAX_FILE_BYTES = 220 * 1024 * 1024;
2441
3746
  DEFAULT_CATEGORY_LIMITS = {
2442
3747
  "default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
@@ -2454,7 +3759,7 @@ return 0
2454
3759
  cooldownMs;
2455
3760
  state = 0 /* CLOSED */;
2456
3761
  failures = 0;
2457
- openedAt = 0;
3762
+ openedAt = performance.now();
2458
3763
  /** True while the single permitted HALF_OPEN probe is in flight. */
2459
3764
  probing = false;
2460
3765
  /**
@@ -2470,7 +3775,8 @@ return 0
2470
3775
  this.probing = true;
2471
3776
  return true;
2472
3777
  }
2473
- if (Date.now() - this.openedAt >= this.cooldownMs) {
3778
+ const now = this.openedAt > 1e12 ? Date.now() : performance.now();
3779
+ if (now - this.openedAt >= this.cooldownMs) {
2474
3780
  this.state = 2 /* HALF_OPEN */;
2475
3781
  this.probing = true;
2476
3782
  return true;
@@ -2489,7 +3795,7 @@ return 0
2489
3795
  this.probing = false;
2490
3796
  if (this.state === 2 /* HALF_OPEN */ || this.failures >= this.threshold) {
2491
3797
  this.state = 1 /* OPEN */;
2492
- this.openedAt = Date.now();
3798
+ this.openedAt = performance.now();
2493
3799
  this.failures = 0;
2494
3800
  }
2495
3801
  }
@@ -2584,9 +3890,68 @@ return 0
2584
3890
  }
2585
3891
  };
2586
3892
  GLOBAL_KEY = "__tricache_instance__";
3893
+ ProcessTerminationBus = class {
3894
+ static instances = /* @__PURE__ */ new Set();
3895
+ static registered = false;
3896
+ static sigtermHandler = null;
3897
+ static sigintHandler = null;
3898
+ static register(instance) {
3899
+ this.instances.add(instance);
3900
+ if (!this.registered) {
3901
+ this.registered = true;
3902
+ this.sigtermHandler = () => {
3903
+ for (const inst of this.instances) {
3904
+ try {
3905
+ inst._triggerShutdown();
3906
+ } catch {
3907
+ }
3908
+ }
3909
+ };
3910
+ this.sigintHandler = () => {
3911
+ for (const inst of this.instances) {
3912
+ try {
3913
+ inst._triggerShutdown();
3914
+ } catch {
3915
+ }
3916
+ }
3917
+ };
3918
+ process.on("SIGTERM", this.sigtermHandler);
3919
+ process.on("SIGINT", this.sigintHandler);
3920
+ }
3921
+ }
3922
+ static unregister(instance) {
3923
+ this.instances.delete(instance);
3924
+ if (this.instances.size === 0 && this.registered) {
3925
+ if (this.sigtermHandler) process.removeListener("SIGTERM", this.sigtermHandler);
3926
+ if (this.sigintHandler) process.removeListener("SIGINT", this.sigintHandler);
3927
+ this.sigtermHandler = null;
3928
+ this.sigintHandler = null;
3929
+ this.registered = false;
3930
+ }
3931
+ }
3932
+ /**
3933
+ * Flushes snapshots across all active registered cache instances concurrently.
3934
+ * Awaits both local disk and remote cloud snapshot uploads with timeout protection.
3935
+ *
3936
+ * @param timeoutMs Timeout in milliseconds per instance before aborting slow flushes. Default: 8000ms.
3937
+ */
3938
+ static async flushAll(timeoutMs = 8e3) {
3939
+ if (this.instances.size === 0) return;
3940
+ const tasks = Array.from(this.instances).map((inst) => inst.flushSnapshotOnShutdown(timeoutMs));
3941
+ await Promise.allSettled(tasks);
3942
+ }
3943
+ /** For testing diagnostics and assertions */
3944
+ static get size() {
3945
+ return this.instances.size;
3946
+ }
3947
+ static get isRegistered() {
3948
+ return this.registered;
3949
+ }
3950
+ };
2587
3951
  CacheService = class _CacheService {
2588
3952
  logger;
2589
3953
  enc;
3954
+ codec;
2590
3955
  l1;
2591
3956
  disk;
2592
3957
  /** When true, all disk-tier and snapshot operations are skipped. */
@@ -2598,6 +3963,8 @@ return 0
2598
3963
  _namespace;
2599
3964
  /** Pre-computed once — disableRedis and redisHost never change after construction. */
2600
3965
  _redisDisabled;
3966
+ watchdog;
3967
+ pipeliner = null;
2601
3968
  inflight = /* @__PURE__ */ new Map();
2602
3969
  revalidating = /* @__PURE__ */ new Set();
2603
3970
  _l1Counters = /* @__PURE__ */ new Map();
@@ -2623,6 +3990,7 @@ return 0
2623
3990
  diskJanitorInterval = null;
2624
3991
  oomInterval = null;
2625
3992
  metricsInterval = null;
3993
+ remoteSnapshotInterval = null;
2626
3994
  _shutdownHandler = null;
2627
3995
  latencyTracker = null;
2628
3996
  instanceId;
@@ -2632,8 +4000,11 @@ return 0
2632
4000
  streamClient = null;
2633
4001
  _lastStreamId = "$";
2634
4002
  _destroyed = false;
4003
+ _ipcServer;
2635
4004
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
2636
4005
  _subDisconnectedAt = null;
4006
+ /** Deduplication ring buffer for incoming and outgoing cross-region invalidations (loop prevention) */
4007
+ _seenCrossRegionEvents = /* @__PURE__ */ new Map();
2637
4008
  counters = {
2638
4009
  gets: 0,
2639
4010
  l1Hits: 0,
@@ -2658,7 +4029,16 @@ return 0
2658
4029
  singletonDivergences: 0,
2659
4030
  startedAt: Date.now(),
2660
4031
  bloomChecks: 0,
2661
- bloomFalsePositives: 0
4032
+ bloomFalsePositives: 0,
4033
+ remoteSnapshotUploads: 0,
4034
+ remoteSnapshotDownloads: 0,
4035
+ remoteSnapshotErrors: 0,
4036
+ remoteSnapshotLastUploadedAt: null,
4037
+ remoteSnapshotLastDownloadedAt: null,
4038
+ crossRegionSent: 0,
4039
+ crossRegionReceived: 0,
4040
+ crossRegionDeduplicated: 0,
4041
+ crossRegionErrors: 0
2662
4042
  };
2663
4043
  /** One-time guard so the in-process increment() fallback warning fires only once. */
2664
4044
  _incrementFallbackWarned = false;
@@ -2673,32 +4053,37 @@ return 0
2673
4053
  logger,
2674
4054
  options.encryptionMode,
2675
4055
  options.previousEncryptionKey,
2676
- options.previousEncryptionMode
4056
+ options.previousEncryptionMode,
4057
+ { strictKeyValidation: options.strictKeyValidation ?? false }
2677
4058
  );
2678
4059
  const rawForbidden = options.forbiddenSnapshotPrefixes ?? [...DEFAULT_FORBIDDEN_PREFIXES];
2679
4060
  const forbiddenPrefixes = ns ? rawForbidden.map((p) => `${ns}:${p}`) : rawForbidden;
2680
4061
  this.opts = {
2681
4062
  namespace: ns,
2682
4063
  logger,
2683
- l1MaxBytes: options.l1MaxBytes ?? 200 * 1024 * 1024,
4064
+ l1MaxBytes: options.l1MaxBytes ?? resolveAutonomousL1MaxBytes(),
2684
4065
  l1MaxEntries: options.l1MaxEntries ?? 2e3,
2685
4066
  categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...options.categoryLimits },
2686
4067
  forbiddenSnapshotPrefixes: forbiddenPrefixes,
2687
4068
  // Namespace-isolated defaults: separate dir / snapshot per namespace so
2688
4069
  // two instances with different namespaces never share cache files.
2689
- diskCacheDir: options.diskCacheDir ?? import_path3.default.join(
2690
- import_os2.default.tmpdir(),
2691
- ns ? `tricache-disk-${ns}` : "tricache-disk"
2692
- ),
4070
+ // Automatically probes /dev/shm tmpfs on Linux (>=256MB capacity and >=128MB free) for off-heap RAM speed.
4071
+ diskCacheDir: options.diskCacheDir ?? resolveDefaultDiskDir(ns, logger).dir,
2693
4072
  diskMaxBytes: options.diskMaxBytes ?? 500 * 1024 * 1024,
2694
4073
  diskEntryMaxBytes: options.diskEntryMaxBytes ?? 10 * 1024 * 1024,
2695
4074
  redisHost: options.redisHost ?? process.env.REDIS_HOST ?? "",
2696
4075
  redisPort: options.redisPort ?? 6379,
2697
4076
  redisTls: options.redisTls ?? process.env.NODE_ENV === "production",
2698
- disableRedis: options.disableRedis ?? process.env.NODE_ENV !== "production",
4077
+ disableRedis: options.disableRedis ?? (() => {
4078
+ const explicitConfig = Boolean(
4079
+ options.redisClient || options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
4080
+ );
4081
+ return !explicitConfig && process.env.NODE_ENV !== "production";
4082
+ })(),
2699
4083
  encryptionKey: encKeyRaw,
4084
+ encryptionMode: options.encryptionMode,
2700
4085
  snapshotPath: options.snapshotPath ?? import_path3.default.join(
2701
- import_os2.default.tmpdir(),
4086
+ import_os3.default.tmpdir(),
2702
4087
  ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
2703
4088
  ),
2704
4089
  snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
@@ -2746,8 +4131,35 @@ return 0
2746
4131
  backplaneMode: options.backplaneMode ?? "pubsub",
2747
4132
  backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
2748
4133
  backplaneStreamBlockMs: options.backplaneStreamBlockMs ?? 2e3,
2749
- backplaneStreamKey: options.backplaneStreamKey
4134
+ backplaneStreamKey: options.backplaneStreamKey,
4135
+ serializeToJSON: options.serializeToJSON ?? true,
4136
+ remoteSnapshot: options.remoteSnapshot,
4137
+ crossRegion: options.crossRegion,
4138
+ redisClient: options.redisClient,
4139
+ redisSubClient: options.redisSubClient,
4140
+ diskMaxConcurrentWrites: options.diskMaxConcurrentWrites,
4141
+ diskMaxPendingWrites: options.diskMaxPendingWrites,
4142
+ diskWriteTimeoutMs: options.diskWriteTimeoutMs,
4143
+ diskCircuitBreakerThreshold: options.diskCircuitBreakerThreshold,
4144
+ diskCircuitBreakerCooldownMs: options.diskCircuitBreakerCooldownMs,
4145
+ redisCommandTimeoutMs: options.redisCommandTimeoutMs,
4146
+ clockSkewToleranceMs: options.clockSkewToleranceMs ?? 250,
4147
+ l1AdmissionPolicy: options.l1AdmissionPolicy,
4148
+ diskLatencyWatchdog: options.diskLatencyWatchdog ?? true,
4149
+ diskLatencyBypassRatio: options.diskLatencyBypassRatio ?? 1.5,
4150
+ diskLatencyBypassMinMs: options.diskLatencyBypassMinMs ?? 10,
4151
+ diskLatencyBypassCooldownMs: options.diskLatencyBypassCooldownMs ?? 3e4,
4152
+ failReadinessOnDegraded: options.failReadinessOnDegraded ?? false,
4153
+ autoPipeline: options.autoPipeline ?? false,
4154
+ maxPipelineBatchSize: options.maxPipelineBatchSize ?? 100,
4155
+ enableIpc: options.enableIpc ?? false,
4156
+ ipcSocketPath: options.ipcSocketPath
2750
4157
  };
4158
+ this.codec = new CacheCodec({
4159
+ useToJSON: this.opts.serializeToJSON,
4160
+ useRecords: true,
4161
+ moreTypes: true
4162
+ });
2751
4163
  const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
2752
4164
  const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
2753
4165
  this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
@@ -2778,15 +4190,33 @@ return 0
2778
4190
  encryption: this.enc.isEnabled ? this.enc : null,
2779
4191
  compression: this.opts.compression,
2780
4192
  compressionThresholdBytes: this.opts.compressionThresholdBytes,
2781
- logger
4193
+ logger,
4194
+ codec: this.codec,
4195
+ diskMaxConcurrentWrites: this.opts.diskMaxConcurrentWrites,
4196
+ diskMaxPendingWrites: this.opts.diskMaxPendingWrites,
4197
+ diskWriteTimeoutMs: this.opts.diskWriteTimeoutMs,
4198
+ diskCircuitBreakerThreshold: this.opts.diskCircuitBreakerThreshold,
4199
+ diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs
2782
4200
  });
2783
4201
  this._namespace = ns;
2784
- this._redisDisabled = this.opts.disableRedis || !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
4202
+ this._redisDisabled = this.opts.disableRedis || !this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
4203
+ this.watchdog = new TierLatencyWatchdog({
4204
+ enabled: options.diskLatencyWatchdog ?? true,
4205
+ minDiskBypassMs: options.diskLatencyBypassMinMs ?? 10,
4206
+ bypassRatio: options.diskLatencyBypassRatio ?? 1.5,
4207
+ cooldownMs: options.diskLatencyBypassCooldownMs ?? 3e4,
4208
+ redisCutoffMs: 15,
4209
+ redisRecoveryFloorMs: 10,
4210
+ minSamples: 16,
4211
+ disableRedis: this._redisDisabled
4212
+ });
2785
4213
  this.l1 = new SmartMemoryCache({
2786
4214
  maxBytes: this.opts.l1MaxBytes,
2787
4215
  maxEntries: this.opts.l1MaxEntries,
2788
4216
  categories: this.opts.categoryLimits,
2789
4217
  evictionWatermark: this.opts.l1EvictionWatermark,
4218
+ admissionPolicy: this.opts.l1AdmissionPolicy,
4219
+ codec: this.codec,
2790
4220
  diskSpill: (key, entry) => {
2791
4221
  if (this._diskDisabled) return;
2792
4222
  setImmediate(() => {
@@ -2801,11 +4231,9 @@ return 0
2801
4231
  if (!this._diskDisabled) this.loadSnapshot();
2802
4232
  }
2803
4233
  this._shutdownHandler = () => {
2804
- if (!this._diskDisabled) this.writeSnapshot();
2805
- process.exit(0);
4234
+ this._triggerShutdown();
2806
4235
  };
2807
- process.once("SIGTERM", this._shutdownHandler);
2808
- process.once("SIGINT", this._shutdownHandler);
4236
+ ProcessTerminationBus.register(this);
2809
4237
  if (this.opts.workerThreads) {
2810
4238
  try {
2811
4239
  const encRef = this.enc.toWorkerInit();
@@ -2845,7 +4273,7 @@ return 0
2845
4273
  }
2846
4274
  if (this.opts.oomProtection) {
2847
4275
  this.oomInterval = setInterval(() => {
2848
- const heap = import_node_v8.default.getHeapStatistics();
4276
+ const heap = import_node_v82.default.getHeapStatistics();
2849
4277
  const used = heap.used_heap_size / heap.heap_size_limit;
2850
4278
  if (used >= this.opts.oomHeapThreshold) {
2851
4279
  const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
@@ -2869,12 +4297,25 @@ return 0
2869
4297
  }, this.opts.metricsIntervalMs);
2870
4298
  if (this.metricsInterval.unref) this.metricsInterval.unref();
2871
4299
  }
2872
- this.instanceId = import_crypto3.default.randomBytes(8).toString("hex");
4300
+ if (this.opts.remoteSnapshot?.intervalMs && this.opts.remoteSnapshot.intervalMs > 0) {
4301
+ this.remoteSnapshotInterval = setInterval(() => {
4302
+ void this.writeRemoteSnapshot();
4303
+ }, this.opts.remoteSnapshot.intervalMs);
4304
+ if (this.remoteSnapshotInterval.unref) this.remoteSnapshotInterval.unref();
4305
+ }
4306
+ this.instanceId = import_crypto4.default.randomBytes(8).toString("hex");
2873
4307
  this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
2874
4308
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
2875
4309
  this.initBackplane();
4310
+ const startupPromises = [];
4311
+ if (this.opts.remoteSnapshot) {
4312
+ startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
4313
+ }
2876
4314
  if (this.opts.warmKeys) {
2877
- this._readyPromise = this.warmFromL2(this.opts.warmKeys).then(() => void 0);
4315
+ startupPromises.push(this.warmFromL2(this.opts.warmKeys).then(() => void 0));
4316
+ }
4317
+ if (startupPromises.length > 0) {
4318
+ this._readyPromise = Promise.all(startupPromises).then(() => void 0);
2878
4319
  }
2879
4320
  if (this.opts.meter) {
2880
4321
  this._initOtelMetrics(this.opts.meter);
@@ -2895,8 +4336,71 @@ return 0
2895
4336
  }
2896
4337
  });
2897
4338
  }
4339
+ if (this.opts.enableIpc) {
4340
+ this._ipcServer = new IpcTelemetryServer(this, this.opts.ipcSocketPath);
4341
+ this._ipcServer.start().catch((err) => {
4342
+ this.logger.warn("Failed to start IPC telemetry server", { error: err.message });
4343
+ });
4344
+ }
4345
+ }
4346
+ // ── Singleton factory & Presets ───────────────────────────────────────────
4347
+ /**
4348
+ * Pre-configured production presets tailored for specific deployment environments.
4349
+ *
4350
+ * - `'nextjs'`: W-TinyLFU, zero-copy cloneStrategy: 'none' (React 19 RSC stream optimized),
4351
+ * generational tags, and Redis stream backplane.
4352
+ * - `'microservice'`: High-throughput Node.js microservice with W-TinyLFU, Streams backplane,
4353
+ * TTL jitter, and L2 circuit breaking.
4354
+ * - `'serverless'`: Stateless Lambda / Cloud Run isolate with memory-only L1, fast timeouts,
4355
+ * and Pub/Sub backplane.
4356
+ * - `'enterprise-hardened'`: Zero-trust production setup with generational tagging, Streams backplane,
4357
+ * fail-closed rate-limits, strict singleton assertions, and 80% OOM guard.
4358
+ *
4359
+ * @param type The preset identifier ('nextjs' | 'microservice' | 'serverless' | 'enterprise-hardened')
4360
+ * @param overrides Optional configuration overrides merged deeply over preset defaults
4361
+ * @returns Singleton CacheService instance configured according to the preset
4362
+ */
4363
+ static preset(type, overrides) {
4364
+ const PRESETS = {
4365
+ "nextjs": {
4366
+ l1AdmissionPolicy: "wtinylfu",
4367
+ cloneStrategy: "none",
4368
+ tagStrategy: "generational",
4369
+ tagVersionTtlMs: 2e3,
4370
+ backplaneMode: "stream",
4371
+ staleIfError: 300,
4372
+ compression: "none"
4373
+ },
4374
+ "microservice": {
4375
+ l1AdmissionPolicy: "wtinylfu",
4376
+ backplaneMode: "stream",
4377
+ ttlJitterFactor: 0.15,
4378
+ l2CircuitBreakerThreshold: 5,
4379
+ l2CircuitBreakerCooldownMs: 15e3
4380
+ },
4381
+ "serverless": {
4382
+ disableDisk: true,
4383
+ l1AdmissionPolicy: "wtinylfu",
4384
+ backplaneMode: "pubsub",
4385
+ redisCommandTimeoutMs: 1e3
4386
+ },
4387
+ "enterprise-hardened": {
4388
+ l1AdmissionPolicy: "wtinylfu",
4389
+ tagStrategy: "generational",
4390
+ backplaneMode: "stream",
4391
+ strictSingleton: true,
4392
+ failClosed: true,
4393
+ oomProtection: true,
4394
+ oomHeapThreshold: 0.8
4395
+ }
4396
+ };
4397
+ const base = PRESETS[type];
4398
+ if (!base) {
4399
+ throw new Error(`tricache: unknown preset '${type}'. Supported presets: 'nextjs', 'microservice', 'serverless', 'enterprise-hardened'`);
4400
+ }
4401
+ const merged = deepMergeOptions(base, overrides);
4402
+ return _CacheService.create(merged);
2898
4403
  }
2899
- // ── Singleton factory ─────────────────────────────────────────────────────
2900
4404
  /**
2901
4405
  * Get (or create) the process-level singleton CacheService instance.
2902
4406
  *
@@ -2981,13 +4485,18 @@ return 0
2981
4485
  disableRedis: this._redisDisabled,
2982
4486
  redisClusterNodes: o.redisClusterNodes,
2983
4487
  redisSentinel: o.redisSentinel,
2984
- encryptionKey: o.encryptionKey,
4488
+ // Never surface key material through diagnostics — a JSON.stringify of
4489
+ // this object previously leaked the raw encryption key.
4490
+ encryptionKey: o.encryptionKey ? "[REDACTED]" : void 0,
4491
+ encryptionMode: o.encryptionMode,
2985
4492
  l2WriteMode: o.l2WriteMode,
2986
4493
  instanceName: o.instanceName,
2987
4494
  frozen: o.frozen,
2988
4495
  adaptiveTtl: o.adaptiveTtl,
2989
4496
  invalidationBackplane: o.invalidationBackplane,
2990
- strictSingleton: o.strictSingleton
4497
+ strictSingleton: o.strictSingleton,
4498
+ remoteSnapshot: o.remoteSnapshot,
4499
+ crossRegion: o.crossRegion
2991
4500
  };
2992
4501
  }
2993
4502
  /**
@@ -3034,7 +4543,7 @@ return 0
3034
4543
  _jitterTtl(ttlMs) {
3035
4544
  const j = this.opts.ttlJitterFactor;
3036
4545
  if (j === 0) return ttlMs;
3037
- const rand = import_crypto3.default.randomInt(0, 1e5) / 5e4 - 1;
4546
+ const rand = import_crypto4.default.randomInt(0, 1e5) / 5e4 - 1;
3038
4547
  return Math.round(ttlMs * (1 + rand * j));
3039
4548
  }
3040
4549
  /** Shared no-op span for the common case where no tracer is configured.
@@ -3046,15 +4555,30 @@ return 0
3046
4555
  setStatus() {
3047
4556
  return this;
3048
4557
  },
4558
+ recordException() {
4559
+ return this;
4560
+ },
3049
4561
  end() {
3050
4562
  }
3051
4563
  };
3052
4564
  /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
3053
- _startSpan(name) {
3054
- if (this.opts.tracer) return this.opts.tracer.startSpan(name);
4565
+ _startSpan(name, links) {
4566
+ if (this.opts.tracer) {
4567
+ const span = this.opts.tracer.startSpan(name, links?.length ? { links } : void 0);
4568
+ if (this.opts.namespace) {
4569
+ span.setAttribute("cache.namespace", this.opts.namespace);
4570
+ }
4571
+ return span;
4572
+ }
3055
4573
  return _CacheService._nullSpan;
3056
4574
  }
3057
4575
  createDedicatedRedisClient() {
4576
+ if (this.opts.redisSubClient) {
4577
+ return this.opts.redisSubClient;
4578
+ }
4579
+ if (this.opts.redisClient && typeof this.opts.redisClient.duplicate === "function") {
4580
+ return this.opts.redisClient.duplicate();
4581
+ }
3058
4582
  if (this.opts.redisClusterNodes?.length) {
3059
4583
  return new import_ioredis.Cluster(this.opts.redisClusterNodes, {
3060
4584
  redisOptions: {
@@ -3186,24 +4710,7 @@ return 0
3186
4710
  for (const [id, fields] of entries) {
3187
4711
  this._lastStreamId = id;
3188
4712
  this.counters.streamEntriesReceived++;
3189
- let op = "";
3190
- let key = "";
3191
- let src = "";
3192
- let tagVersion;
3193
- for (let i = 0; i < fields.length; i += 2) {
3194
- const f = fields[i];
3195
- const v = fields[i + 1];
3196
- if (f === "op") op = v;
3197
- else if (f === "key") key = v;
3198
- else if (f === "src") src = v;
3199
- else if (f === "tagVersion") tagVersion = parseInt(v, 10);
3200
- }
3201
- if (src === this.instanceId) {
3202
- this.counters.invSkipped++;
3203
- continue;
3204
- }
3205
- this.counters.invReceived++;
3206
- this._applyInvalidationEvent(op, key, tagVersion);
4713
+ this._processStreamEntry(fields);
3207
4714
  }
3208
4715
  }
3209
4716
  }
@@ -3224,6 +4731,51 @@ return 0
3224
4731
  };
3225
4732
  void runLoop();
3226
4733
  }
4734
+ /**
4735
+ * Validate + apply one XREAD stream entry. `fields` is the flat ioredis
4736
+ * shape [name, value, name, value, …]. Mirrors the schema rules of the
4737
+ * pubsub path (`_handleBackplaneMessage`): op must be a known operation,
4738
+ * key/src must be non-empty strings, tagVersion must parse to a finite
4739
+ * number. Invalid entries are logged and dropped — never applied.
4740
+ */
4741
+ /** @internal Exposed for testing. */
4742
+ _processStreamEntry(fields) {
4743
+ let op = "";
4744
+ let key = "";
4745
+ let src = "";
4746
+ let tagVersionRaw;
4747
+ for (let i = 0; i + 1 < fields.length; i += 2) {
4748
+ const f = fields[i];
4749
+ const v = fields[i + 1];
4750
+ if (f === "op") op = v;
4751
+ else if (f === "key") key = v;
4752
+ else if (f === "src") src = v;
4753
+ else if (f === "tagVersion") tagVersionRaw = v;
4754
+ }
4755
+ const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
4756
+ if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
4757
+ this.logger.warn("Backplane: rejected invalid stream entry", {
4758
+ op: String(op).slice(0, 40),
4759
+ key: typeof key === "string" ? key.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(key)
4760
+ });
4761
+ return;
4762
+ }
4763
+ let tagVersion;
4764
+ if (tagVersionRaw !== void 0) {
4765
+ const parsed = parseInt(tagVersionRaw, 10);
4766
+ if (!Number.isFinite(parsed)) {
4767
+ this.logger.warn("Backplane: rejected stream entry with non-numeric tagVersion", { key });
4768
+ return;
4769
+ }
4770
+ tagVersion = parsed;
4771
+ }
4772
+ if (src === this.instanceId) {
4773
+ this.counters.invSkipped++;
4774
+ return;
4775
+ }
4776
+ this.counters.invReceived++;
4777
+ this._applyInvalidationEvent(op, key, tagVersion);
4778
+ }
3227
4779
  _applyInvalidationEvent(op, key, tagVersion) {
3228
4780
  if (op === "del") {
3229
4781
  this.l1.delete(key);
@@ -3260,7 +4812,13 @@ return 0
3260
4812
  this.logger.warn("Backplane: malformed message JSON parse failed");
3261
4813
  }
3262
4814
  }
3263
- async publishInvalidation(op, key, tagVersion) {
4815
+ async publishInvalidation(op, key, tagVersion, isCrossRegionRelay = false, isExplicitInvalidation = false) {
4816
+ if (!isCrossRegionRelay && this.opts.crossRegion) {
4817
+ const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
4818
+ if (shouldBroadcast) {
4819
+ void this._broadcastCrossRegion(op, key, tagVersion);
4820
+ }
4821
+ }
3264
4822
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
3265
4823
  try {
3266
4824
  const client = await this.getRedis();
@@ -3302,7 +4860,80 @@ return 0
3302
4860
  } catch {
3303
4861
  }
3304
4862
  }
3305
- _setLocalTagVersion(tag, version, now = Date.now()) {
4863
+ _markCrossRegionEventSeen(id) {
4864
+ const maxDedup = this.opts.crossRegion?.dedupCacheSize ?? 1e4;
4865
+ if (this._seenCrossRegionEvents.size >= maxDedup) {
4866
+ const oldestKey = this._seenCrossRegionEvents.keys().next().value;
4867
+ if (oldestKey !== void 0) this._seenCrossRegionEvents.delete(oldestKey);
4868
+ }
4869
+ this._seenCrossRegionEvents.set(id, Date.now());
4870
+ }
4871
+ _isCrossRegionEventSeen(id) {
4872
+ return this._seenCrossRegionEvents.has(id);
4873
+ }
4874
+ async _broadcastCrossRegion(op, key, tagVersion) {
4875
+ const cr = this.opts.crossRegion;
4876
+ if (!cr) return;
4877
+ try {
4878
+ const eventId = import_crypto4.default.randomUUID();
4879
+ this._markCrossRegionEventSeen(eventId);
4880
+ const event = {
4881
+ id: eventId,
4882
+ originRegion: cr.currentRegion,
4883
+ originInstanceId: this.instanceId,
4884
+ op,
4885
+ key,
4886
+ tagVersion,
4887
+ timestamp: Date.now(),
4888
+ namespace: this._namespace || void 0
4889
+ };
4890
+ this.counters.crossRegionSent++;
4891
+ await cr.relay.broadcast(event);
4892
+ this.logger.debug("Cross-region invalidation broadcast", { op, key, region: cr.currentRegion });
4893
+ } catch (err) {
4894
+ this.counters.crossRegionSent = Math.max(0, this.counters.crossRegionSent - 1);
4895
+ this.counters.crossRegionErrors++;
4896
+ this.logger.warn("Cross-region invalidation broadcast failed", { error: err.message });
4897
+ }
4898
+ }
4899
+ /**
4900
+ * Receives an invalidation event from another region (e.g. via HTTP webhook or broker subscriber).
4901
+ * Validates origin, deduplicates to prevent loops, applies locally to L1/disk,
4902
+ * and fans out to the local Redis backplane so all regional peers invalidate as well.
4903
+ *
4904
+ * Returns true if the event was accepted and applied, or false if ignored/deduplicated.
4905
+ */
4906
+ async receiveCrossRegionInvalidation(event) {
4907
+ const cr = this.opts.crossRegion;
4908
+ if (!cr) return false;
4909
+ if (!event || typeof event !== "object" || !event.id || !event.originRegion || !event.op || !event.key) {
4910
+ this.counters.crossRegionErrors++;
4911
+ this.logger.warn("Cross-region: rejected invalid event payload", { event });
4912
+ return false;
4913
+ }
4914
+ if (event.originRegion === cr.currentRegion) {
4915
+ this.counters.crossRegionDeduplicated++;
4916
+ return false;
4917
+ }
4918
+ if (this._isCrossRegionEventSeen(event.id)) {
4919
+ this.counters.crossRegionDeduplicated++;
4920
+ return false;
4921
+ }
4922
+ this._markCrossRegionEventSeen(event.id);
4923
+ if (event.namespace !== void 0 && event.namespace !== (this._namespace || void 0)) {
4924
+ return false;
4925
+ }
4926
+ this.counters.crossRegionReceived++;
4927
+ this._applyInvalidationEvent(event.op, event.key, event.tagVersion);
4928
+ void this.publishInvalidation(event.op, event.key, event.tagVersion, true);
4929
+ this.logger.info("Cross-region invalidation applied", {
4930
+ op: event.op,
4931
+ key: event.key,
4932
+ originRegion: event.originRegion
4933
+ });
4934
+ return true;
4935
+ }
4936
+ _setLocalTagVersion(tag, version, now = performance.now()) {
3306
4937
  const existing = this.tagVersions.get(tag)?.version ?? 0;
3307
4938
  const finalVersion = Math.max(existing, version);
3308
4939
  if (this.tagVersions.size >= 1e4 && !this.tagVersions.has(tag)) {
@@ -3312,7 +4943,7 @@ return 0
3312
4943
  this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
3313
4944
  }
3314
4945
  async _getTagVersion(tag) {
3315
- const now = Date.now();
4946
+ const now = performance.now();
3316
4947
  const local = this.tagVersions.get(tag);
3317
4948
  if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
3318
4949
  return local.version;
@@ -3398,13 +5029,25 @@ return 0
3398
5029
  stream.on("error", reject);
3399
5030
  })
3400
5031
  ));
3401
- } else {
5032
+ } else if (typeof client.scanStream === "function") {
3402
5033
  await new Promise((resolve, reject) => {
3403
5034
  const stream = client.scanStream({ match: pattern, count: 100 });
3404
5035
  stream.on("data", (chunk) => keys.push(...chunk));
3405
5036
  stream.on("end", resolve);
3406
5037
  stream.on("error", reject);
3407
5038
  });
5039
+ } else if (typeof client.scanIterator === "function") {
5040
+ for await (const key of client.scanIterator({ MATCH: pattern, COUNT: 100 })) {
5041
+ keys.push(key);
5042
+ }
5043
+ } else if (typeof client.scan === "function") {
5044
+ let cursor = "0";
5045
+ do {
5046
+ const res = await client.scan(cursor, "MATCH", pattern, "COUNT", 100);
5047
+ cursor = String(res[0]);
5048
+ const chunk = res[1];
5049
+ if (chunk?.length) keys.push(...chunk);
5050
+ } while (cursor !== "0");
3408
5051
  }
3409
5052
  return keys;
3410
5053
  }
@@ -3421,6 +5064,19 @@ return 0
3421
5064
  if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
3422
5065
  if (this.redis) return this.redis;
3423
5066
  if (this.redisConnecting) return this.redisConnecting;
5067
+ if (this.opts.redisClient) {
5068
+ const client = this.opts.redisClient;
5069
+ if (typeof client.connect === "function" && client.isOpen === false) {
5070
+ await client.connect();
5071
+ }
5072
+ this.cb.onSuccess();
5073
+ this.redis = client;
5074
+ this.pipeliner = new AutoPipeliner(client, {
5075
+ enabled: this.opts.autoPipeline,
5076
+ maxBatchSize: this.opts.maxPipelineBatchSize
5077
+ });
5078
+ return client;
5079
+ }
3424
5080
  this.redisConnecting = (async () => {
3425
5081
  try {
3426
5082
  let client;
@@ -3429,6 +5085,7 @@ return 0
3429
5085
  redisOptions: {
3430
5086
  tls: this.opts.redisTls ? {} : void 0,
3431
5087
  connectTimeout: 1e4,
5088
+ commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
3432
5089
  maxRetriesPerRequest: 3,
3433
5090
  keepAlive: 3e4,
3434
5091
  ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
@@ -3449,6 +5106,7 @@ return 0
3449
5106
  name: this.opts.redisSentinel.name,
3450
5107
  tls: this.opts.redisTls ? {} : void 0,
3451
5108
  connectTimeout: 1e4,
5109
+ commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
3452
5110
  lazyConnect: false,
3453
5111
  maxRetriesPerRequest: 3,
3454
5112
  enableAutoPipelining: true,
@@ -3468,6 +5126,7 @@ return 0
3468
5126
  port: this.opts.redisPort,
3469
5127
  tls: this.opts.redisTls ? {} : void 0,
3470
5128
  connectTimeout: 1e4,
5129
+ commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
3471
5130
  lazyConnect: false,
3472
5131
  maxRetriesPerRequest: 3,
3473
5132
  enableAutoPipelining: true,
@@ -3493,6 +5152,10 @@ return 0
3493
5152
  });
3494
5153
  this.cb.onSuccess();
3495
5154
  this.redis = client;
5155
+ this.pipeliner = new AutoPipeliner(client, {
5156
+ enabled: this.opts.autoPipeline,
5157
+ maxBatchSize: this.opts.maxPipelineBatchSize
5158
+ });
3496
5159
  this.redisConnecting = null;
3497
5160
  return client;
3498
5161
  } catch (err) {
@@ -3505,12 +5168,18 @@ return 0
3505
5168
  return this.redisConnecting;
3506
5169
  }
3507
5170
  // ── Snapshot (cold-start persistence) ────────────────────────────────────
5171
+ /**
5172
+ * Writes the cold-start snapshot to disk.
5173
+ * NOTE: fs.writeFileSync is INTENTIONAL here: this method is invoked during SIGTERM/SIGINT
5174
+ * process termination hooks where asynchronous I/O would risk the Node.js event loop dying or
5175
+ * process.exit() being called before the snapshot is physically written to disk.
5176
+ */
3508
5177
  writeSnapshot(altPath) {
3509
5178
  try {
3510
5179
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
3511
5180
  if (entries.length === 0) return;
3512
5181
  const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
3513
- const packed = (0, import_msgpackr3.pack)(payload);
5182
+ const packed = this.codec.encode(payload);
3514
5183
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
3515
5184
  const dest = altPath ?? this.opts.snapshotPath;
3516
5185
  import_fs3.default.mkdirSync(import_path3.default.dirname(dest), { recursive: true });
@@ -3525,6 +5194,12 @@ return 0
3525
5194
  this.logger.warn("Cache snapshot write failed", { error: err.message });
3526
5195
  }
3527
5196
  }
5197
+ /**
5198
+ * Loads cold-start snapshot from disk into L1 memory.
5199
+ * NOTE: fs.readFileSync is INTENTIONAL here: this method is invoked synchronously inside the
5200
+ * CacheService constructor so that the cache is atomically populated before any subsequent
5201
+ * cache.get() or cache.set() operations run, eliminating cold-start race conditions.
5202
+ */
3528
5203
  loadSnapshot() {
3529
5204
  const snapshotPath = this.opts.snapshotPath;
3530
5205
  try {
@@ -3544,13 +5219,25 @@ return 0
3544
5219
  this.logger.warn("Snapshot rejected: decryption failed", { error: e.message });
3545
5220
  return;
3546
5221
  }
3547
- const snapshot = (0, import_msgpackr3.unpack)(buf);
5222
+ const snapshot = this.codec.decode(buf);
3548
5223
  if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
3549
5224
  this.logger.warn("Snapshot rejected: version mismatch", { got: snapshot?.version });
3550
5225
  return;
3551
5226
  }
3552
- const ageMs = Date.now() - (snapshot.writtenAt ?? 0);
3553
- if (ageMs > this.opts.snapshotMaxAgeMs || ageMs < 0) {
5227
+ const now = Date.now();
5228
+ const writtenAt = snapshot.writtenAt ?? 0;
5229
+ const tolerance = this.opts.clockSkewToleranceMs ?? 250;
5230
+ if (writtenAt - now > tolerance) {
5231
+ this.logger.warn("Snapshot rejected: timestamp too far in future (exceeds clock skew tolerance)", {
5232
+ writtenAt,
5233
+ now,
5234
+ skewMs: writtenAt - now,
5235
+ tolerance
5236
+ });
5237
+ return;
5238
+ }
5239
+ const ageMs = Math.max(0, now - writtenAt);
5240
+ if (ageMs > this.opts.snapshotMaxAgeMs) {
3554
5241
  this.logger.warn("Snapshot rejected: too old", { ageMinutes: Math.round(ageMs / 6e4) });
3555
5242
  return;
3556
5243
  }
@@ -3572,6 +5259,115 @@ return 0
3572
5259
  }
3573
5260
  }
3574
5261
  }
5262
+ // ── Remote Snapshot (cold-start persistence for stateless containers) ───────
5263
+ /**
5264
+ * Persists the cold-start snapshot to remote blob storage (S3, GCS, R2, HTTP).
5265
+ * Can be awaited during graceful application shutdown (e.g. Kubernetes preStop or NestJS shutdown).
5266
+ * Returns true if a snapshot was successfully exported and written; false otherwise.
5267
+ */
5268
+ async writeRemoteSnapshot() {
5269
+ if (!this.opts.remoteSnapshot) return false;
5270
+ try {
5271
+ const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
5272
+ if (entries.length === 0) return false;
5273
+ const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
5274
+ const packed = this.codec.encode(payload);
5275
+ let final;
5276
+ if (this.opts.remoteSnapshot.envelope) {
5277
+ final = await EnvelopeEncryption.encrypt(packed, this.opts.remoteSnapshot.envelope);
5278
+ } else {
5279
+ final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
5280
+ }
5281
+ await this.opts.remoteSnapshot.adapter.put(final);
5282
+ this.counters.remoteSnapshotUploads++;
5283
+ this.counters.remoteSnapshotLastUploadedAt = Date.now();
5284
+ this.logger.info("Remote cache snapshot uploaded", {
5285
+ entries: entries.length,
5286
+ sizeKB: Math.round(final.length / 1024),
5287
+ encrypted: Boolean(this.opts.remoteSnapshot.envelope || this.enc.isEnabled)
5288
+ });
5289
+ return true;
5290
+ } catch (err) {
5291
+ this.counters.remoteSnapshotErrors++;
5292
+ this.logger.warn("Remote cache snapshot upload failed", { error: err.message });
5293
+ return false;
5294
+ }
5295
+ }
5296
+ /**
5297
+ * Hydrates L1 memory from remote blob storage (S3, GCS, R2, HTTP).
5298
+ * Called automatically during startup (chained into `cache.ready()`).
5299
+ * Returns the number of entries successfully imported.
5300
+ */
5301
+ async loadRemoteSnapshot() {
5302
+ if (!this.opts.remoteSnapshot) return 0;
5303
+ const maxAgeMs = this.opts.remoteSnapshot.maxAgeMs ?? this.opts.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE;
5304
+ try {
5305
+ const raw = await this.opts.remoteSnapshot.adapter.get();
5306
+ if (!raw || raw.length === 0) {
5307
+ this.logger.debug("Remote snapshot not found or empty \u2014 starting cold");
5308
+ return 0;
5309
+ }
5310
+ const rawBuf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
5311
+ let buf;
5312
+ try {
5313
+ if (EnvelopeEncryption.isEnvelope(rawBuf)) {
5314
+ if (!this.opts.remoteSnapshot.envelope) {
5315
+ throw new Error("Remote snapshot is envelope-encrypted but no envelope options (privateKey or kmsDecrypt) were configured");
5316
+ }
5317
+ buf = await EnvelopeEncryption.decrypt(rawBuf, this.opts.remoteSnapshot.envelope);
5318
+ } else {
5319
+ buf = this.enc.decryptBuffer(rawBuf);
5320
+ }
5321
+ } catch (e) {
5322
+ this.counters.remoteSnapshotErrors++;
5323
+ this.logger.warn("Remote snapshot rejected: decryption failed", { error: e.message });
5324
+ return 0;
5325
+ }
5326
+ const snapshot = this.codec.decode(buf);
5327
+ if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
5328
+ this.counters.remoteSnapshotErrors++;
5329
+ this.logger.warn("Remote snapshot rejected: version mismatch", { got: snapshot?.version });
5330
+ return 0;
5331
+ }
5332
+ const now = Date.now();
5333
+ const writtenAt = snapshot.writtenAt ?? 0;
5334
+ const tolerance = this.opts.clockSkewToleranceMs ?? 250;
5335
+ if (writtenAt - now > tolerance) {
5336
+ this.counters.remoteSnapshotErrors++;
5337
+ this.logger.warn("Remote snapshot rejected: timestamp too far in future (exceeds clock skew tolerance)", {
5338
+ writtenAt,
5339
+ now,
5340
+ skewMs: writtenAt - now,
5341
+ tolerance
5342
+ });
5343
+ return 0;
5344
+ }
5345
+ const ageMs = Math.max(0, now - writtenAt);
5346
+ if (maxAgeMs <= 0 || ageMs > maxAgeMs) {
5347
+ this.counters.remoteSnapshotErrors++;
5348
+ this.logger.warn("Remote snapshot rejected: too old", { ageMinutes: Math.round(ageMs / 6e4) });
5349
+ return 0;
5350
+ }
5351
+ if (!Array.isArray(snapshot.entries)) {
5352
+ this.counters.remoteSnapshotErrors++;
5353
+ this.logger.warn("Remote snapshot rejected: entries is not an array");
5354
+ return 0;
5355
+ }
5356
+ const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
5357
+ this.counters.remoteSnapshotDownloads++;
5358
+ this.counters.remoteSnapshotLastDownloadedAt = Date.now();
5359
+ this.logger.info("Remote cache snapshot loaded (L1 hydrated)", {
5360
+ loaded,
5361
+ total: snapshot.entries.length,
5362
+ sizeKB: this.l1.getStats().sizeKB
5363
+ });
5364
+ return loaded;
5365
+ } catch (err) {
5366
+ this.counters.remoteSnapshotErrors++;
5367
+ this.logger.warn("Remote snapshot load failed \u2014 starting cold", { error: err.message });
5368
+ return 0;
5369
+ }
5370
+ }
3575
5371
  // ── Core get (L1 → L1.5 → L2 → fetch) ───────────────────────────────────
3576
5372
  /**
3577
5373
  * Get a value from cache, or fetch and cache it.
@@ -3607,9 +5403,10 @@ return 0
3607
5403
  if (l1Hit !== null) {
3608
5404
  let isGenerationalStale = false;
3609
5405
  if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
3610
- for (const [tag, entryVer] of Object.entries(l1Hit.tagVersions)) {
3611
- const currentVer = await this._getTagVersion(tag);
3612
- if (currentVer > entryVer) {
5406
+ const tags = Object.keys(l1Hit.tagVersions);
5407
+ const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5408
+ for (let i = 0; i < tags.length; i++) {
5409
+ if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
3613
5410
  isGenerationalStale = true;
3614
5411
  break;
3615
5412
  }
@@ -3654,116 +5451,140 @@ return 0
3654
5451
  this.counters.l1Hits++;
3655
5452
  this.opts.onHit?.(cacheKey, "l1");
3656
5453
  if (this.opts.frozen) deepFreeze(l1Hit.value);
3657
- span.setAttribute("cache.hit", "l1").end();
5454
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "memory").setAttribute("cache.hit_tier", "l1").end();
3658
5455
  return this.opts.cloneStrategy === "structuredClone" && l1Hit.value != null && typeof l1Hit.value === "object" ? structuredClone(l1Hit.value) : l1Hit.value;
3659
5456
  }
3660
5457
  }
3661
5458
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
3662
5459
  const swrGraceMs = optSwr * 1e3;
3663
5460
  const priority = optPriority ?? inferPriority(cacheKey);
3664
- if (!this._redisDisabled) {
5461
+ const existing = this.inflight.get(k);
5462
+ if (existing) {
5463
+ this.counters.stampedes++;
5464
+ this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch/read", { cacheKey });
5465
+ span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
5466
+ return existing;
5467
+ }
5468
+ const executionPromise = (async () => {
3665
5469
  try {
3666
- const client = await this.getRedis();
3667
- if (this.opts.tagStrategy === "generational") {
3668
- const hashData = await client.hgetall(k);
3669
- this.cb.onSuccess();
3670
- if (hashData && hashData.d) {
3671
- let isStale = false;
3672
- let storedTagVersions = {};
3673
- if (hashData.tv) {
3674
- try {
3675
- storedTagVersions = JSON.parse(hashData.tv);
3676
- } catch {
5470
+ if (!this._diskDisabled) {
5471
+ const isDiskAllowed = this.watchdog.isDiskAllowed();
5472
+ if (isDiskAllowed) {
5473
+ const diskStart = performance.now();
5474
+ const diskHit = this.disk.load(k);
5475
+ const diskElapsed = performance.now() - diskStart;
5476
+ this.watchdog.recordDisk(diskElapsed);
5477
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
5478
+ if (diskHit !== null) {
5479
+ let isDiskStale = false;
5480
+ if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
5481
+ const tags = Object.keys(diskHit.tagVersions);
5482
+ const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5483
+ for (let i = 0; i < tags.length; i++) {
5484
+ if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
5485
+ isDiskStale = true;
5486
+ break;
5487
+ }
5488
+ }
3677
5489
  }
3678
- }
3679
- for (const [tag, entryVer] of Object.entries(storedTagVersions)) {
3680
- const currentVer = await this._getTagVersion(tag);
3681
- if (currentVer > entryVer) {
3682
- isStale = true;
3683
- break;
5490
+ if (isDiskStale) {
5491
+ this.disk.delete(k);
5492
+ } else {
5493
+ const promoted = this.l1.importEntries(
5494
+ [{ key: k, entry: diskHit }],
5495
+ this.opts.forbiddenSnapshotPrefixes
5496
+ );
5497
+ if (promoted > 0) {
5498
+ const l1Check = this.l1.get(k);
5499
+ if (l1Check !== null) {
5500
+ this.counters.diskHits++;
5501
+ this.opts.onHit?.(cacheKey, "disk");
5502
+ this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
5503
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
5504
+ if (this.opts.frozen) deepFreeze(l1Check.value);
5505
+ return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
5506
+ }
5507
+ }
3684
5508
  }
3685
5509
  }
3686
- if (isStale) {
3687
- const setAtMs = parseInt(hashData.t, 10) || 0;
3688
- this._deleteIfStale(k, setAtMs);
3689
- } else {
3690
- const parsed = await this._decryptAndDeserialize(hashData.d);
3691
- this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
3692
- this.counters.l2Hits++;
3693
- this.opts.onHit?.(cacheKey, "l2");
3694
- this.logger.debug("L2 hit (Redis hash)", { cacheKey });
3695
- span.setAttribute("cache.hit", "l2").end();
3696
- if (this.opts.frozen) deepFreeze(parsed);
3697
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
3698
- }
3699
- }
3700
- } else {
3701
- const raw = await client.get(k);
3702
- this.cb.onSuccess();
3703
- if (raw) {
3704
- const parsed = await this._decryptAndDeserialize(raw);
3705
- this.l1.set(k, parsed, ttlMs, priority);
3706
- this.counters.l2Hits++;
3707
- this.opts.onHit?.(cacheKey, "l2");
3708
- this.logger.debug("L2 hit (Redis)", { cacheKey });
3709
- span.setAttribute("cache.hit", "l2").end();
3710
- if (this.opts.frozen) deepFreeze(parsed);
3711
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
3712
- }
3713
- }
3714
- } catch (err) {
3715
- this.cb.onFailure();
3716
- this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
3717
- }
3718
- }
3719
- if (!this._diskDisabled) {
3720
- const diskHit = this.disk.load(k);
3721
- if (diskHit !== null) {
3722
- let isDiskStale = false;
3723
- if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
3724
- for (const [tag, entryVer] of Object.entries(diskHit.tagVersions)) {
3725
- const currentVer = await this._getTagVersion(tag);
3726
- if (currentVer > entryVer) {
3727
- isDiskStale = true;
3728
- break;
3729
- }
3730
5510
  }
3731
5511
  }
3732
- if (isDiskStale) {
3733
- this.disk.delete(k);
3734
- } else {
3735
- const promoted = this.l1.importEntries(
3736
- [{ key: k, entry: diskHit }],
3737
- this.opts.forbiddenSnapshotPrefixes
3738
- );
3739
- if (promoted > 0) {
3740
- const l1Check = this.l1.get(k);
3741
- if (l1Check !== null) {
3742
- this.counters.diskHits++;
3743
- this.opts.onHit?.(cacheKey, "disk");
3744
- this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
3745
- span.setAttribute("cache.hit", "disk").end();
3746
- if (this.opts.frozen) deepFreeze(l1Check.value);
3747
- return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
5512
+ if (!this._redisDisabled) {
5513
+ try {
5514
+ const client = await this.getRedis();
5515
+ const redisStart = performance.now();
5516
+ if (this.opts.tagStrategy === "generational") {
5517
+ const hashData = await client.hgetall(k);
5518
+ const redisElapsed = performance.now() - redisStart;
5519
+ this.watchdog.recordRedis(redisElapsed);
5520
+ this.cb.onSuccess();
5521
+ if (hashData && hashData.d) {
5522
+ let isStale = false;
5523
+ let storedTagVersions = {};
5524
+ if (hashData.tv) {
5525
+ try {
5526
+ storedTagVersions = JSON.parse(hashData.tv);
5527
+ } catch {
5528
+ }
5529
+ }
5530
+ const tags = Object.keys(storedTagVersions);
5531
+ const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5532
+ for (let i = 0; i < tags.length; i++) {
5533
+ if (currentVers[i] > storedTagVersions[tags[i]]) {
5534
+ isStale = true;
5535
+ break;
5536
+ }
5537
+ }
5538
+ if (isStale) {
5539
+ const setAtMs = parseInt(hashData.t, 10) || 0;
5540
+ this._deleteIfStale(k, setAtMs);
5541
+ } else {
5542
+ const parsed = await this._decryptAndDeserialize(hashData.d);
5543
+ this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
5544
+ this.counters.l2Hits++;
5545
+ this.opts.onHit?.(cacheKey, "l2");
5546
+ this.logger.debug("L2 hit (Redis hash)", { cacheKey });
5547
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5548
+ if (this.opts.frozen) deepFreeze(parsed);
5549
+ return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
5550
+ }
5551
+ }
5552
+ } else {
5553
+ const raw = this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
5554
+ const redisElapsed = performance.now() - redisStart;
5555
+ this.watchdog.recordRedis(redisElapsed);
5556
+ this.cb.onSuccess();
5557
+ if (raw) {
5558
+ const parsed = await this._decryptAndDeserialize(raw);
5559
+ this.l1.set(k, parsed, ttlMs, priority);
5560
+ this.counters.l2Hits++;
5561
+ this.opts.onHit?.(cacheKey, "l2");
5562
+ this.logger.debug("L2 hit (Redis)", { cacheKey });
5563
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5564
+ if (this.opts.frozen) deepFreeze(parsed);
5565
+ return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
5566
+ }
3748
5567
  }
5568
+ } catch (err) {
5569
+ this.cb.onFailure();
5570
+ this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
3749
5571
  }
3750
5572
  }
3751
- }
3752
- }
3753
- span.setAttribute("cache.hit", "miss");
3754
- this.opts.onMiss?.(cacheKey);
3755
- const existing = this.inflight.get(k);
3756
- if (existing) {
3757
- this.counters.stampedes++;
3758
- this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch", { cacheKey });
3759
- span.end();
3760
- return existing;
3761
- }
3762
- const fetchPromise = (async () => {
3763
- try {
5573
+ span.setAttribute("cache.hit", false).setAttribute("cache.hit_tier", "miss");
5574
+ this.opts.onMiss?.(cacheKey);
3764
5575
  this.counters.fetches++;
3765
5576
  const fetchStart = Date.now();
3766
- const data = await fetchFn();
5577
+ let data;
5578
+ try {
5579
+ data = await fetchFn();
5580
+ } catch (fetchErr) {
5581
+ span.setStatus({
5582
+ code: 2,
5583
+ message: fetchErr instanceof Error ? fetchErr.message : String(fetchErr)
5584
+ });
5585
+ span.recordException?.(fetchErr);
5586
+ throw fetchErr;
5587
+ }
3767
5588
  const delta = Date.now() - fetchStart;
3768
5589
  const notFoundTtlMs = (optNotFoundTtl ?? this.opts.notFoundTtl) * 1e3;
3769
5590
  let effectiveTtl = data == null && notFoundTtlMs > 0 ? notFoundTtlMs : ttlMs;
@@ -3783,9 +5604,10 @@ return 0
3783
5604
  let activeTagVersions;
3784
5605
  if (optTags?.length) {
3785
5606
  if (this.opts.tagStrategy === "generational") {
5607
+ const vers = await Promise.all(optTags.map((tag) => this._getTagVersion(tag)));
3786
5608
  activeTagVersions = {};
3787
- for (const tag of optTags) {
3788
- activeTagVersions[tag] = await this._getTagVersion(tag);
5609
+ for (let i = 0; i < optTags.length; i++) {
5610
+ activeTagVersions[optTags[i]] = vers[i];
3789
5611
  }
3790
5612
  } else {
3791
5613
  await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
@@ -3827,8 +5649,64 @@ return 0
3827
5649
  span.end();
3828
5650
  }
3829
5651
  })();
3830
- this.inflight.set(k, fetchPromise);
3831
- return fetchPromise;
5652
+ this.inflight.set(k, executionPromise);
5653
+ return executionPromise;
5654
+ }
5655
+ /**
5656
+ * Graceful shutdown flusher for Kubernetes preStop hooks, NestJS onApplicationShutdown,
5657
+ * or manual microservice teardown.
5658
+ *
5659
+ * Flushes both local disk and remote cloud snapshots (S3/R2/GCS), returning a Promise
5660
+ * that resolves when the upload completes or after `timeoutMs` expires.
5661
+ *
5662
+ * @param timeoutMs Maximum time permitted for snapshot persistence before timing out. Default: 8000ms.
5663
+ */
5664
+ async flushSnapshotOnShutdown(timeoutMs = 8e3) {
5665
+ const flusher = async () => {
5666
+ let localOk = true;
5667
+ let remoteOk = true;
5668
+ if (!this._diskDisabled) {
5669
+ try {
5670
+ this.writeSnapshot();
5671
+ } catch (err) {
5672
+ localOk = false;
5673
+ this.logger.warn("flushSnapshotOnShutdown: disk snapshot write failed", { error: err.message });
5674
+ }
5675
+ }
5676
+ if (this.opts.remoteSnapshot && this.opts.remoteSnapshot.saveOnShutdown !== false) {
5677
+ try {
5678
+ remoteOk = await this.writeRemoteSnapshot();
5679
+ } catch (err) {
5680
+ remoteOk = false;
5681
+ this.logger.warn("flushSnapshotOnShutdown: remote snapshot upload failed", { error: err.message });
5682
+ }
5683
+ }
5684
+ return localOk && remoteOk;
5685
+ };
5686
+ let timer = null;
5687
+ try {
5688
+ return await Promise.race([
5689
+ flusher(),
5690
+ new Promise((resolve) => {
5691
+ timer = setTimeout(() => {
5692
+ this.logger.warn(`flushSnapshotOnShutdown timed out after ${timeoutMs}ms`);
5693
+ resolve(false);
5694
+ }, timeoutMs);
5695
+ if (timer.unref) timer.unref();
5696
+ })
5697
+ ]);
5698
+ } finally {
5699
+ if (timer) clearTimeout(timer);
5700
+ }
5701
+ }
5702
+ /**
5703
+ * Internal graceful shutdown trigger invoked by ProcessTerminationBus.
5704
+ */
5705
+ _triggerShutdown() {
5706
+ if (!this._diskDisabled) this.writeSnapshot();
5707
+ if (this.opts.remoteSnapshot && this.opts.remoteSnapshot.saveOnShutdown !== false) {
5708
+ void this.flushSnapshotOnShutdown();
5709
+ }
3832
5710
  }
3833
5711
  /**
3834
5712
  * Universal fetch-and-cache wrapper with an ergonomic options object.
@@ -3861,9 +5739,11 @@ return 0
3861
5739
  let activeTagVersions;
3862
5740
  const l1Existing = this.l1.get(cacheKey);
3863
5741
  if (this.opts.tagStrategy === "generational" && l1Existing?.tagVersions) {
5742
+ const tags = Object.keys(l1Existing.tagVersions);
5743
+ const vers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
3864
5744
  activeTagVersions = {};
3865
- for (const tag of Object.keys(l1Existing.tagVersions)) {
3866
- activeTagVersions[tag] = await this._getTagVersion(tag);
5745
+ for (let i = 0; i < tags.length; i++) {
5746
+ activeTagVersions[tags[i]] = vers[i];
3867
5747
  }
3868
5748
  }
3869
5749
  this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
@@ -3909,61 +5789,77 @@ return 0
3909
5789
  /** Explicitly write a value into L1 (+ L2 in production). */
3910
5790
  async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
3911
5791
  const span = this._startSpan("tricache.set");
3912
- if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
3913
- const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
3914
- const p = priority ?? inferPriority(cacheKey);
3915
- const k = this.nk(cacheKey);
3916
- this.counters.sets++;
3917
- let activeTagVersions;
3918
- if (opts?.tags?.length) {
3919
- if (this.opts.tagStrategy === "generational") {
3920
- activeTagVersions = {};
3921
- for (const tag of opts.tags) {
3922
- activeTagVersions[tag] = await this._getTagVersion(tag);
5792
+ if (this.opts.tracer) {
5793
+ span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
5794
+ span.setAttribute("cache.ttl", ttlSeconds);
5795
+ }
5796
+ try {
5797
+ const effectiveTtlSeconds = ttlSeconds > 0 ? ttlSeconds : ttlSeconds === 0 ? INDEFINITE_TTL_SECONDS : ttlSeconds;
5798
+ const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
5799
+ const p = priority ?? inferPriority(cacheKey);
5800
+ const k = this.nk(cacheKey);
5801
+ this.counters.sets++;
5802
+ let activeTagVersions;
5803
+ if (opts?.tags?.length) {
5804
+ if (this.opts.tagStrategy === "generational") {
5805
+ const vers = await Promise.all(opts.tags.map((tag) => this._getTagVersion(tag)));
5806
+ activeTagVersions = {};
5807
+ for (let i = 0; i < opts.tags.length; i++) {
5808
+ activeTagVersions[opts.tags[i]] = vers[i];
5809
+ }
5810
+ } else {
5811
+ await this._registerTags(k, opts.tags, ttlSeconds);
3923
5812
  }
3924
- } else {
3925
- await this._registerTags(k, opts.tags, ttlSeconds);
3926
5813
  }
3927
- }
3928
- this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
3929
- if (opts?.dependsOn?.length) {
3930
- for (const pattern of opts.dependsOn) {
3931
- const nsPattern = this.nk(pattern);
3932
- let deps = this.dependencyIndex.get(nsPattern);
3933
- if (!deps) {
3934
- deps = /* @__PURE__ */ new Set();
3935
- this.dependencyIndex.set(nsPattern, deps);
5814
+ this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
5815
+ if (opts?.dependsOn?.length) {
5816
+ for (const pattern of opts.dependsOn) {
5817
+ const nsPattern = this.nk(pattern);
5818
+ let deps = this.dependencyIndex.get(nsPattern);
5819
+ if (!deps) {
5820
+ deps = /* @__PURE__ */ new Set();
5821
+ this.dependencyIndex.set(nsPattern, deps);
5822
+ }
5823
+ deps.add(k);
3936
5824
  }
3937
- deps.add(k);
3938
5825
  }
3939
- }
3940
- if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
3941
- try {
3942
- const client = await this.getRedis();
3943
- const s = JSON.stringify(data);
3944
- const stored = await this._serializeAndEncrypt(s);
3945
- const ttlSec = Math.ceil(ttlMs / 1e3);
3946
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
3947
- const now = Date.now();
3948
- const tx = client.multi();
3949
- tx.hset(k, {
3950
- d: stored,
3951
- t: String(now),
3952
- tv: JSON.stringify(activeTagVersions)
3953
- });
3954
- tx.expire(k, ttlSec);
3955
- await tx.exec();
3956
- } else {
3957
- await client.setex(k, ttlSec, stored);
5826
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
5827
+ try {
5828
+ const client = await this.getRedis();
5829
+ const s = JSON.stringify(data);
5830
+ const stored = await this._serializeAndEncrypt(s);
5831
+ const ttlSec = Math.ceil(ttlMs / 1e3);
5832
+ if (this.opts.tagStrategy === "generational" && activeTagVersions) {
5833
+ const now = Date.now();
5834
+ const tx = client.multi();
5835
+ tx.hset(k, {
5836
+ d: stored,
5837
+ t: String(now),
5838
+ tv: JSON.stringify(activeTagVersions)
5839
+ });
5840
+ tx.expire(k, ttlSec);
5841
+ await tx.exec();
5842
+ } else {
5843
+ if (this.opts.autoPipeline && this.pipeliner) {
5844
+ await this.pipeliner.setex(k, ttlSec, stored);
5845
+ } else {
5846
+ await client.setex(k, ttlSec, stored);
5847
+ }
5848
+ }
5849
+ this.cb.onSuccess();
5850
+ } catch (err) {
5851
+ this.cb.onFailure();
5852
+ this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
3958
5853
  }
3959
- this.cb.onSuccess();
3960
- } catch (err) {
3961
- this.cb.onFailure();
3962
- this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
3963
5854
  }
5855
+ void this.publishInvalidation("del", k);
5856
+ } catch (err) {
5857
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
5858
+ span.recordException?.(err);
5859
+ throw err;
5860
+ } finally {
5861
+ span.end();
3964
5862
  }
3965
- void this.publishInvalidation("del", k);
3966
- span.end();
3967
5863
  }
3968
5864
  /**
3969
5865
  * Register tags for a cache key in the in-process index and (if Redis is enabled) in
@@ -4005,36 +5901,47 @@ return 0
4005
5901
  async delete(cacheKey) {
4006
5902
  const span = this._startSpan("tricache.delete");
4007
5903
  if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
4008
- const isPattern = cacheKey.includes("*");
4009
- const k = this.nk(cacheKey);
4010
- this.counters.deletes++;
4011
- if (isPattern) {
4012
- this.l1.deletePattern(k);
4013
- } else {
4014
- this.l1.delete(k);
4015
- setImmediate(() => {
4016
- if (!this._diskDisabled) this.disk.delete(k);
4017
- });
4018
- this._cascadeDependencies(k);
4019
- for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
4020
- }
4021
- if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
4022
- try {
4023
- const client = await this.getRedis();
4024
- if (isPattern) {
4025
- const keys = await this._scanKeys(client, k);
4026
- if (keys.length > 0) await client.del(...keys);
4027
- } else {
4028
- await client.del(k);
5904
+ try {
5905
+ const isPattern = cacheKey.includes("*");
5906
+ const k = this.nk(cacheKey);
5907
+ this.counters.deletes++;
5908
+ if (isPattern) {
5909
+ this.l1.deletePattern(k);
5910
+ } else {
5911
+ this.l1.delete(k);
5912
+ setImmediate(() => {
5913
+ if (!this._diskDisabled) this.disk.delete(k);
5914
+ });
5915
+ this._cascadeDependencies(k);
5916
+ for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
5917
+ }
5918
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
5919
+ try {
5920
+ const client = await this.getRedis();
5921
+ if (isPattern) {
5922
+ const keys = await this._scanKeys(client, k);
5923
+ if (keys.length > 0) await client.del(...keys);
5924
+ } else {
5925
+ if (this.opts.autoPipeline && this.pipeliner) {
5926
+ await this.pipeliner.del(k);
5927
+ } else {
5928
+ await client.del(k);
5929
+ }
5930
+ }
5931
+ this.cb.onSuccess();
5932
+ } catch (err) {
5933
+ this.cb.onFailure();
5934
+ this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
4029
5935
  }
4030
- this.cb.onSuccess();
4031
- } catch (err) {
4032
- this.cb.onFailure();
4033
- this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
4034
5936
  }
5937
+ void this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
5938
+ } catch (err) {
5939
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
5940
+ span.recordException?.(err);
5941
+ throw err;
5942
+ } finally {
5943
+ span.end();
4035
5944
  }
4036
- void this.publishInvalidation(isPattern ? "del-glob" : "del", k);
4037
- span.end();
4038
5945
  }
4039
5946
  // ── Counter (distributed rate limiting) ──────────────────────────────────
4040
5947
  /**
@@ -4095,31 +6002,44 @@ return 0
4095
6002
  * await cache.clear('user:abc'); // flush all keys for one user
4096
6003
  */
4097
6004
  async clear(prefix) {
4098
- this.counters.deletes++;
4099
- const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
4100
- if (k) {
4101
- this.l1.deletePattern(k);
4102
- } else {
4103
- this.l1.clear();
4104
- if (!this._diskDisabled) this.disk.clear();
4105
- this._l1Counters.clear();
4106
- this.tagIndex.clear();
4107
- this.tagVersions.clear();
4108
- }
4109
- if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
4110
- try {
4111
- const client = await this.getRedis();
4112
- const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
4113
- const keys = await this._scanKeys(client, pattern);
4114
- if (keys.length > 0) await client.del(...keys);
4115
- } catch (err) {
4116
- this.logger.debug("clear: Redis unavailable", { error: err.message });
6005
+ const span = this._startSpan("tricache.clear");
6006
+ if (this.opts.tracer) span.setAttribute("cache.prefix", prefix || "*");
6007
+ try {
6008
+ this.counters.deletes++;
6009
+ const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
6010
+ if (k) {
6011
+ this.l1.deletePattern(k);
6012
+ } else {
6013
+ this.l1.clear();
6014
+ if (!this._diskDisabled) this.disk.clear();
6015
+ this._l1Counters.clear();
6016
+ this.tagIndex.clear();
6017
+ this.tagVersions.clear();
6018
+ }
6019
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6020
+ try {
6021
+ const client = await this.getRedis();
6022
+ const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
6023
+ const keys = await this._scanKeys(client, pattern);
6024
+ if (keys.length > 0) await client.del(...keys);
6025
+ } catch (err) {
6026
+ this.logger.debug("clear: Redis unavailable", { error: err.message });
6027
+ }
4117
6028
  }
6029
+ void this.publishInvalidation(
6030
+ "del-glob",
6031
+ k ?? (this._namespace ? `${this._namespace}:*` : "*"),
6032
+ void 0,
6033
+ false,
6034
+ true
6035
+ );
6036
+ } catch (err) {
6037
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
6038
+ span.recordException?.(err);
6039
+ throw err;
6040
+ } finally {
6041
+ span.end();
4118
6042
  }
4119
- void this.publishInvalidation(
4120
- "del-glob",
4121
- k ?? (this._namespace ? `${this._namespace}:*` : "*")
4122
- );
4123
6043
  }
4124
6044
  /**
4125
6045
  * Evict L1 entries that violate the current category or global capacity limits.
@@ -4250,7 +6170,7 @@ return 0
4250
6170
  const now = Date.now();
4251
6171
  if (entry.expiresAt <= now) return null;
4252
6172
  if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
4253
- return entry.value !== void 0 ? entry.value : (0, import_msgpackr3.unpack)(entry.data);
6173
+ return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
4254
6174
  }
4255
6175
  /**
4256
6176
  * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
@@ -4270,8 +6190,12 @@ return 0
4270
6190
  if (this.opts.frozen) deepFreeze(val);
4271
6191
  return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
4272
6192
  }
4273
- if (!this._diskDisabled) {
6193
+ if (!this._diskDisabled && this.watchdog.isDiskAllowed()) {
6194
+ const diskStart = performance.now();
4274
6195
  const diskHit = this.disk.load(k);
6196
+ const diskElapsed = performance.now() - diskStart;
6197
+ this.watchdog.recordDisk(diskElapsed);
6198
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
4275
6199
  if (diskHit !== null) {
4276
6200
  const promoted = this.l1.importEntries(
4277
6201
  [{ key: k, entry: diskHit }],
@@ -4292,7 +6216,10 @@ return 0
4292
6216
  if (!this._redisDisabled && !this.cb.isOpen) {
4293
6217
  try {
4294
6218
  const client = await this.getRedis();
6219
+ const redisStart = performance.now();
4295
6220
  const raw = await client.get(k);
6221
+ const redisElapsed = performance.now() - redisStart;
6222
+ this.watchdog.recordRedis(redisElapsed);
4296
6223
  if (raw !== null) {
4297
6224
  const parsed = await this._decryptAndDeserialize(raw);
4298
6225
  this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
@@ -4319,90 +6246,129 @@ return 0
4319
6246
  * `(key) => number` so heterogeneous TTLs can be batched in one call.
4320
6247
  */
4321
6248
  async mget(keys, fetchFn, ttl = 300, priority) {
4322
- const result = Array.from({ length: keys.length });
4323
- const missIndexes = [];
4324
- const missKeys = [];
4325
- for (let i = 0; i < keys.length; i++) {
4326
- const k = this.nk(keys[i]);
4327
- const entry = this.l1.getEntry(k);
4328
- if (entry && entry.expiresAt > Date.now()) {
4329
- result[i] = entry.value !== void 0 ? entry.value : (0, import_msgpackr3.unpack)(entry.data);
4330
- this.counters.l1Hits++;
4331
- } else {
4332
- missIndexes.push(i);
4333
- missKeys.push(keys[i]);
6249
+ const span = this._startSpan("tricache.mget");
6250
+ if (this.opts.tracer) {
6251
+ span.setAttribute("cache.batch.size", keys.length);
6252
+ }
6253
+ try {
6254
+ const result = Array.from({ length: keys.length });
6255
+ const missIndexes = [];
6256
+ const missKeys = [];
6257
+ for (let i = 0; i < keys.length; i++) {
6258
+ const k = this.nk(keys[i]);
6259
+ const entry = this.l1.getEntry(k);
6260
+ if (entry && entry.expiresAt > Date.now()) {
6261
+ result[i] = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
6262
+ this.counters.l1Hits++;
6263
+ } else {
6264
+ missIndexes.push(i);
6265
+ missKeys.push(keys[i]);
6266
+ }
6267
+ }
6268
+ if (missKeys.length === 0) {
6269
+ if (this.opts.tracer) {
6270
+ span.setAttribute("cache.hits", keys.length);
6271
+ span.setAttribute("cache.misses", 0);
6272
+ span.setAttribute("cache.l1_hits", keys.length);
6273
+ span.setAttribute("cache.l2_hits", 0);
6274
+ }
6275
+ return result;
4334
6276
  }
4335
- }
4336
- if (missKeys.length === 0) return result;
4337
- if (!this._redisDisabled) {
4338
- try {
4339
- const client = await this.getRedis();
4340
- const nsKeys = missKeys.map((k) => this.nk(k));
4341
- const pipeline = client.multi();
4342
- for (const nk of nsKeys) pipeline.get(nk);
4343
- const raws = await pipeline.exec();
4344
- this.cb.onSuccess();
4345
- for (let j = 0; j < missKeys.length; j++) {
4346
- const raw = raws[j] ? raws[j][1] : null;
4347
- const idx = missIndexes[j];
4348
- if (raw) {
4349
- const parsed = await this._decryptAndDeserialize(raw);
4350
- const k = nsKeys[j];
4351
- const p = priority ?? inferPriority(missKeys[j]);
4352
- this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
4353
- this.counters.l2Hits++;
4354
- result[idx] = parsed;
4355
- missIndexes[j] = -1;
4356
- missKeys[j] = "";
6277
+ let l2HitCount = 0;
6278
+ if (!this._redisDisabled) {
6279
+ try {
6280
+ const client = await this.getRedis();
6281
+ const nsKeys = missKeys.map((k) => this.nk(k));
6282
+ const pipeline = client.multi();
6283
+ for (const nk of nsKeys) pipeline.get(nk);
6284
+ const redisStart = performance.now();
6285
+ const raws = await pipeline.exec();
6286
+ const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
6287
+ this.watchdog.recordRedis(redisElapsed);
6288
+ this.cb.onSuccess();
6289
+ for (let j = 0; j < missKeys.length; j++) {
6290
+ const raw = raws[j] ? raws[j][1] : null;
6291
+ const idx = missIndexes[j];
6292
+ if (raw) {
6293
+ const parsed = await this._decryptAndDeserialize(raw);
6294
+ const k = nsKeys[j];
6295
+ const p = priority ?? inferPriority(missKeys[j]);
6296
+ this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
6297
+ this.counters.l2Hits++;
6298
+ l2HitCount++;
6299
+ result[idx] = parsed;
6300
+ missIndexes[j] = -1;
6301
+ missKeys[j] = "";
6302
+ }
4357
6303
  }
6304
+ const remainingIdx = missIndexes.filter((i) => i >= 0);
6305
+ const remainingKeys = missKeys.filter((k) => k !== "");
6306
+ missIndexes.length = 0;
6307
+ missKeys.length = 0;
6308
+ missIndexes.push(...remainingIdx);
6309
+ missKeys.push(...remainingKeys);
6310
+ } catch (err) {
6311
+ this.cb.onFailure();
6312
+ this.logger.debug("mget: Redis unavailable, continuing to disk/fetch", { error: err.message });
4358
6313
  }
4359
- const remainingIdx = missIndexes.filter((i) => i >= 0);
4360
- const remainingKeys = missKeys.filter((k) => k !== "");
4361
- missIndexes.length = 0;
4362
- missKeys.length = 0;
4363
- missIndexes.push(...remainingIdx);
4364
- missKeys.push(...remainingKeys);
4365
- if (missKeys.length === 0) return result;
4366
- } catch (err) {
4367
- this.cb.onFailure();
4368
- this.logger.debug("mget: Redis unavailable, continuing to disk/fetch", { error: err.message });
4369
6314
  }
4370
- }
4371
- if (!this._diskDisabled) {
4372
- for (let j = missKeys.length - 1; j >= 0; j--) {
4373
- const k = this.nk(missKeys[j]);
4374
- const diskHit = this.disk.load(k);
4375
- if (diskHit !== null) {
4376
- const promoted = this.l1.importEntries(
4377
- [{ key: k, entry: diskHit }],
4378
- this.opts.forbiddenSnapshotPrefixes
4379
- );
4380
- if (promoted > 0) {
4381
- const l1Check = this.l1.get(k);
4382
- if (l1Check !== null) {
4383
- this.counters.diskHits++;
4384
- result[missIndexes[j]] = l1Check.value;
4385
- missIndexes.splice(j, 1);
4386
- missKeys.splice(j, 1);
6315
+ if (!this._diskDisabled && missKeys.length > 0) {
6316
+ for (let j = missKeys.length - 1; j >= 0; j--) {
6317
+ if (!this.watchdog.isDiskAllowed()) continue;
6318
+ const k = this.nk(missKeys[j]);
6319
+ const diskStart = performance.now();
6320
+ const diskHit = this.disk.load(k);
6321
+ const diskElapsed = performance.now() - diskStart;
6322
+ this.watchdog.recordDisk(diskElapsed);
6323
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6324
+ if (diskHit !== null) {
6325
+ const promoted = this.l1.importEntries(
6326
+ [{ key: k, entry: diskHit }],
6327
+ this.opts.forbiddenSnapshotPrefixes
6328
+ );
6329
+ if (promoted > 0) {
6330
+ const l1Check = this.l1.get(k);
6331
+ if (l1Check !== null) {
6332
+ this.counters.diskHits++;
6333
+ result[missIndexes[j]] = l1Check.value;
6334
+ missIndexes.splice(j, 1);
6335
+ missKeys.splice(j, 1);
6336
+ }
4387
6337
  }
4388
6338
  }
4389
6339
  }
4390
6340
  }
4391
- if (missKeys.length === 0) return result;
4392
- }
4393
- if (missKeys.length > 0) {
4394
- this.counters.fetches++;
4395
- const fetched = await fetchFn(missKeys);
4396
- for (let j = 0; j < missKeys.length; j++) {
4397
- const v = fetched[missKeys[j]];
4398
- result[missIndexes[j]] = v;
4399
- if (v !== void 0) {
4400
- const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
4401
- await this.set(missKeys[j], v, resolvedTtl, priority);
6341
+ if (missKeys.length > 0) {
6342
+ this.counters.fetches++;
6343
+ const fetched = await fetchFn(missKeys);
6344
+ const setPromises = [];
6345
+ for (let j = 0; j < missKeys.length; j++) {
6346
+ const v = fetched[missKeys[j]];
6347
+ result[missIndexes[j]] = v;
6348
+ if (v !== void 0) {
6349
+ const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
6350
+ setPromises.push(this.set(missKeys[j], v, resolvedTtl, priority));
6351
+ }
4402
6352
  }
6353
+ if (setPromises.length > 0) {
6354
+ await Promise.all(setPromises);
6355
+ }
6356
+ }
6357
+ if (this.opts.tracer) {
6358
+ const finalMisses = missKeys.length;
6359
+ const totalHits = keys.length - finalMisses;
6360
+ span.setAttribute("cache.hits", totalHits);
6361
+ span.setAttribute("cache.misses", finalMisses);
6362
+ span.setAttribute("cache.l2_hits", l2HitCount);
4403
6363
  }
6364
+ return result;
6365
+ } catch (err) {
6366
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
6367
+ span.recordException?.(err);
6368
+ throw err;
6369
+ } finally {
6370
+ span.end();
4404
6371
  }
4405
- return result;
4406
6372
  }
4407
6373
  /**
4408
6374
  * Returns a Promise that resolves once the cache is fully initialised and any
@@ -4429,12 +6395,24 @@ return 0
4429
6395
  * });
4430
6396
  */
4431
6397
  async mset(entries) {
6398
+ const span = this._startSpan("tricache.mset");
4432
6399
  const keys = Object.keys(entries);
4433
- await Promise.all(keys.map((key) => {
4434
- const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
4435
- const hasOpts = tags?.length || dependsOn?.length;
4436
- return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
4437
- }));
6400
+ if (this.opts.tracer) {
6401
+ span.setAttribute("cache.batch.size", keys.length);
6402
+ }
6403
+ try {
6404
+ await Promise.all(keys.map((key) => {
6405
+ const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
6406
+ const hasOpts = tags?.length || dependsOn?.length;
6407
+ return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
6408
+ }));
6409
+ } catch (err) {
6410
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
6411
+ span.recordException?.(err);
6412
+ throw err;
6413
+ } finally {
6414
+ span.end();
6415
+ }
4438
6416
  }
4439
6417
  /**
4440
6418
  * Batch delete — delete multiple exact keys in a single call.
@@ -4444,7 +6422,19 @@ return 0
4444
6422
  * await cache.mdel(['user:1', 'user:2', 'user:3']);
4445
6423
  */
4446
6424
  async mdel(keys) {
4447
- await Promise.all(keys.map((k) => this.delete(k)));
6425
+ const span = this._startSpan("tricache.mdel");
6426
+ if (this.opts.tracer) {
6427
+ span.setAttribute("cache.batch.size", keys.length);
6428
+ }
6429
+ try {
6430
+ await Promise.all(keys.map((k) => this.delete(k)));
6431
+ } catch (err) {
6432
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
6433
+ span.recordException?.(err);
6434
+ throw err;
6435
+ } finally {
6436
+ span.end();
6437
+ }
4448
6438
  }
4449
6439
  /**
4450
6440
  * Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
@@ -4473,7 +6463,6 @@ return 0
4473
6463
  const results = await pl.exec();
4474
6464
  this.cb.onSuccess();
4475
6465
  let loaded = 0;
4476
- const now = Date.now();
4477
6466
  for (let i = 0; i < matchedKeys.length; i++) {
4478
6467
  const [err, raw] = results[i];
4479
6468
  if (err || raw == null) continue;
@@ -4485,7 +6474,6 @@ return 0
4485
6474
  } catch {
4486
6475
  }
4487
6476
  }
4488
- void now;
4489
6477
  this.logger.info("warmFromL2 complete", {
4490
6478
  pattern,
4491
6479
  matched: matchedKeys.length,
@@ -4507,45 +6495,58 @@ return 0
4507
6495
  * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
4508
6496
  */
4509
6497
  async invalidateTag(tag) {
4510
- if (this.opts.tagStrategy === "generational") {
4511
- let newVer = 1;
6498
+ const span = this._startSpan("tricache.invalidate_tag");
6499
+ if (this.opts.tracer) {
6500
+ span.setAttribute("cache.tag", tag);
6501
+ span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
6502
+ }
6503
+ try {
6504
+ if (this.opts.tagStrategy === "generational") {
6505
+ let newVer = 1;
6506
+ if (!this._redisDisabled) {
6507
+ try {
6508
+ const client = await this.getRedis();
6509
+ newVer = await client.incr(this.nk(`tag_ver:${tag}`));
6510
+ } catch (err) {
6511
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
6512
+ const current = this.tagVersions.get(tag)?.version ?? 0;
6513
+ newVer = current + 1;
6514
+ }
6515
+ } else {
6516
+ const current = this.tagVersions.get(tag)?.version ?? 0;
6517
+ newVer = current + 1;
6518
+ }
6519
+ this._setLocalTagVersion(tag, newVer, Date.now());
6520
+ void this.publishInvalidation("tag_incr", tag, newVer, false, true);
6521
+ return;
6522
+ }
6523
+ const tagKey = this.nk(`_tag_:${tag}`);
6524
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
6525
+ for (const k of members) {
6526
+ this.l1.delete(k);
6527
+ if (!this._diskDisabled) this.disk.delete(k);
6528
+ }
6529
+ this.tagIndex.delete(tagKey);
4512
6530
  if (!this._redisDisabled) {
4513
6531
  try {
4514
6532
  const client = await this.getRedis();
4515
- newVer = await client.incr(this.nk(`tag_ver:${tag}`));
6533
+ const redisMembers = await client.smembers(tagKey);
6534
+ const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
6535
+ if (toDelete.length > 0) {
6536
+ await client.del(...toDelete, tagKey);
6537
+ } else {
6538
+ await client.del(tagKey);
6539
+ }
4516
6540
  } catch (err) {
4517
6541
  this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
4518
- const current = this.tagVersions.get(tag)?.version ?? 0;
4519
- newVer = current + 1;
4520
- }
4521
- } else {
4522
- const current = this.tagVersions.get(tag)?.version ?? 0;
4523
- newVer = current + 1;
4524
- }
4525
- this._setLocalTagVersion(tag, newVer, Date.now());
4526
- void this.publishInvalidation("tag_incr", tag, newVer);
4527
- return;
4528
- }
4529
- const tagKey = this.nk(`_tag_:${tag}`);
4530
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
4531
- for (const k of members) {
4532
- this.l1.delete(k);
4533
- if (!this._diskDisabled) this.disk.delete(k);
4534
- }
4535
- this.tagIndex.delete(tagKey);
4536
- if (!this._redisDisabled) {
4537
- try {
4538
- const client = await this.getRedis();
4539
- const redisMembers = await client.smembers(tagKey);
4540
- const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
4541
- if (toDelete.length > 0) {
4542
- await client.del(...toDelete, tagKey);
4543
- } else {
4544
- await client.del(tagKey);
4545
6542
  }
4546
- } catch (err) {
4547
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
4548
6543
  }
6544
+ } catch (err) {
6545
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
6546
+ span.recordException?.(err);
6547
+ throw err;
6548
+ } finally {
6549
+ span.end();
4549
6550
  }
4550
6551
  }
4551
6552
  /**
@@ -4578,7 +6579,7 @@ return 0
4578
6579
  const [err, newVer] = results[i] ?? [null, null];
4579
6580
  const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
4580
6581
  this._setLocalTagVersion(tags[i], ver, now);
4581
- void this.publishInvalidation("tag_incr", tags[i], ver);
6582
+ void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
4582
6583
  }
4583
6584
  return;
4584
6585
  } catch (err) {
@@ -4588,7 +6589,7 @@ return 0
4588
6589
  for (const tag of tags) {
4589
6590
  const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
4590
6591
  this._setLocalTagVersion(tag, ver, now);
4591
- void this.publishInvalidation("tag_incr", tag, ver);
6592
+ void this.publishInvalidation("tag_incr", tag, ver, false, true);
4592
6593
  }
4593
6594
  return;
4594
6595
  }
@@ -4659,6 +6660,60 @@ return 0
4659
6660
  }
4660
6661
  return { l1, disk, l2 };
4661
6662
  }
6663
+ /**
6664
+ * Health and readiness diagnostics for container orchestrators (e.g. Kubernetes, ECS, Nomad).
6665
+ *
6666
+ * ─────────────────────────────────────────────────────────────────────────────
6667
+ * ⚠️ CRITICAL CONTAINER PROBE SEMANTICS (Liveness vs. Readiness):
6668
+ * ─────────────────────────────────────────────────────────────────────────────
6669
+ * ❌ NEVER bind `degraded` checks or `cache.health()` to your Liveness Probe (/livez, /healthz).
6670
+ * If an SRE hooks degraded status into liveness, a storage-starved or EBS-throttled pod
6671
+ * will be killed by the kubelet, triggering a cluster-wide cascading restart shockwave.
6672
+ * Liveness probes must only check that the event loop / process is alive.
6673
+ *
6674
+ * ✅ BIND degraded checks strictly to your Readiness Probe (/ready, /readyz).
6675
+ * A degraded cache (e.g. EBS latency spike, quota watermark pruning, or open Redis circuit)
6676
+ * can shed traffic at the ingress load balancer while the Node.js process remains
6677
+ * alive to drain in-flight promises and heal its local storage.
6678
+ *
6679
+ * By default, `healthy` remains `true` even when degraded (graceful local degradation).
6680
+ * Set `failReadinessOnDegraded: true` in CacheOptions if you want your Readiness probe
6681
+ * to route ingress traffic away while degraded.
6682
+ * ─────────────────────────────────────────────────────────────────────────────
6683
+ */
6684
+ health() {
6685
+ const watchdogTel = this.watchdog.getTelemetry();
6686
+ const diskPruning = !this._diskDisabled && this.disk.isPruning;
6687
+ const diskLowSpace = !this._diskDisabled && this.disk.hostVolumeLowSpace;
6688
+ const circuitOpen = this.cb.isOpen;
6689
+ const latencyBypass = watchdogTel.bypassActive;
6690
+ const degraded = circuitOpen || latencyBypass || diskPruning || diskLowSpace;
6691
+ const healthy = this.opts.failReadinessOnDegraded ? !degraded : true;
6692
+ const reasons = [];
6693
+ if (circuitOpen) reasons.push("redis_circuit_breaker_open");
6694
+ if (latencyBypass) reasons.push(`disk_latency_bypass_stage_${watchdogTel.bypassStage}`);
6695
+ if (diskPruning) reasons.push("disk_quota_watermark_pruning_active");
6696
+ if (diskLowSpace) reasons.push("disk_host_volume_low_space");
6697
+ return {
6698
+ healthy,
6699
+ degraded,
6700
+ reasons,
6701
+ details: {
6702
+ redisConnected: !circuitOpen && !this._redisDisabled,
6703
+ circuitBreakerState: this.cb.currentState,
6704
+ diskPruningActive: diskPruning,
6705
+ diskHostVolumeLowSpace: diskLowSpace,
6706
+ watchdog: watchdogTel
6707
+ }
6708
+ };
6709
+ }
6710
+ /**
6711
+ * Direct access to the internal tier latency watchdog instance.
6712
+ * Used for diagnostics, canary probes, and control-loop tuning.
6713
+ */
6714
+ getLatencyWatchdog() {
6715
+ return this.watchdog;
6716
+ }
4662
6717
  /**
4663
6718
  * Export all live L1 entries to Redis via a single pipeline.
4664
6719
  * Useful for warming a new Redis instance or for zero-downtime failover.
@@ -4748,12 +6803,13 @@ return 0
4748
6803
  const acquireTimeout = Math.max(0, options?.acquireTimeout ?? 5e3);
4749
6804
  const retryInterval = Math.max(10, options?.retryInterval ?? 100);
4750
6805
  const lockKey = this.nk(`lock:${resourceKey}`);
4751
- const token = import_crypto3.default.randomUUID();
6806
+ const token = import_crypto4.default.randomUUID();
4752
6807
  const deadline = Date.now() + acquireTimeout;
4753
6808
  let acquired = false;
4754
6809
  if (!this._redisDisabled) {
6810
+ let client = null;
4755
6811
  try {
4756
- const client = await this.getRedis();
6812
+ client = await this.getRedis();
4757
6813
  while (Date.now() <= deadline) {
4758
6814
  const res = await client.set(lockKey, token, "EX", ttlSeconds, "NX");
4759
6815
  if (res === "OK") {
@@ -4767,6 +6823,15 @@ return 0
4767
6823
  if (!acquired) {
4768
6824
  throw new Error(`Failed to acquire lock for resource "${resourceKey}" within ${acquireTimeout}ms`);
4769
6825
  }
6826
+ } catch (err) {
6827
+ if (err.message.startsWith("Failed to acquire lock")) throw err;
6828
+ this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
6829
+ resourceKey,
6830
+ error: err.message
6831
+ });
6832
+ client = null;
6833
+ }
6834
+ if (client !== null && acquired) {
4770
6835
  try {
4771
6836
  return await fn();
4772
6837
  } finally {
@@ -4782,12 +6847,6 @@ return 0
4782
6847
  } catch {
4783
6848
  }
4784
6849
  }
4785
- } catch (err) {
4786
- if (err.message.startsWith("Failed to acquire lock")) throw err;
4787
- this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
4788
- resourceKey,
4789
- error: err.message
4790
- });
4791
6850
  }
4792
6851
  }
4793
6852
  let unlock = () => {
@@ -4902,7 +6961,7 @@ return 0
4902
6961
  if (visited.has(dep)) continue;
4903
6962
  this.l1.delete(dep);
4904
6963
  if (!this._diskDisabled) this.disk.delete(dep);
4905
- void this.publishInvalidation("del", dep);
6964
+ void this.publishInvalidation("del", dep, void 0, false, true);
4906
6965
  this.logger.debug("Dependency cascade: invalidated dependent key", {
4907
6966
  trigger: deletedKey.slice(0, 60),
4908
6967
  dependent: dep.slice(0, 60)
@@ -4967,12 +7026,36 @@ return 0
4967
7026
  evictions: c.oomEvictions,
4968
7027
  lastTriggeredAt: c.oomLastAt
4969
7028
  },
7029
+ ...this.opts.remoteSnapshot && {
7030
+ remoteSnapshot: {
7031
+ enabled: true,
7032
+ uploads: c.remoteSnapshotUploads,
7033
+ downloads: c.remoteSnapshotDownloads,
7034
+ errors: c.remoteSnapshotErrors,
7035
+ lastUploadedAt: c.remoteSnapshotLastUploadedAt,
7036
+ lastDownloadedAt: c.remoteSnapshotLastDownloadedAt
7037
+ }
7038
+ },
7039
+ ...this.opts.crossRegion && {
7040
+ crossRegion: {
7041
+ enabled: true,
7042
+ currentRegion: this.opts.crossRegion.currentRegion,
7043
+ sent: c.crossRegionSent,
7044
+ received: c.crossRegionReceived,
7045
+ deduplicated: c.crossRegionDeduplicated,
7046
+ errors: c.crossRegionErrors
7047
+ }
7048
+ },
4970
7049
  l1: {
4971
7050
  entries: l1s.entries,
4972
7051
  sizeBytes: this.l1.memoryUsage,
4973
7052
  maxBytes: this.opts.l1MaxBytes
4974
7053
  },
4975
- disk: { ...this.disk.stats, disabled: this._diskDisabled },
7054
+ disk: {
7055
+ ...this.disk.stats,
7056
+ disabled: this._diskDisabled,
7057
+ latencyWatchdog: this.watchdog.getTelemetry()
7058
+ },
4976
7059
  ...this.latencyTracker && {
4977
7060
  adaptiveTtl: {
4978
7061
  enabled: true,
@@ -4985,9 +7068,16 @@ return 0
4985
7068
  this.opts.adaptiveTtlMaxMs
4986
7069
  )
4987
7070
  }
7071
+ },
7072
+ ...this.pipeliner && {
7073
+ pipelining: this.pipeliner.stats
4988
7074
  }
4989
7075
  };
4990
7076
  }
7077
+ /** Return auto-pipelining metrics, or null if pipelining is disabled. */
7078
+ getPipelinerStats() {
7079
+ return this.pipeliner ? this.pipeliner.stats : null;
7080
+ }
4991
7081
  /**
4992
7082
  * Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
4993
7083
  * Paste the result into your `/metrics` endpoint.
@@ -5027,6 +7117,18 @@ return 0
5027
7117
  gauge("l1_entries", m.l1.entries, "Current L1 entry count");
5028
7118
  gauge("l1_size_bytes", m.l1.sizeBytes, "Current L1 used bytes");
5029
7119
  gauge("disk_files", m.disk.files, "Current L1.5 disk file count");
7120
+ if (m.disk.latencyWatchdog) {
7121
+ gauge("disk_latency_bypass_stage", m.disk.latencyWatchdog.bypassStage, "Disk latency watchdog bypass stage (0: normal, 1: 25%, 2: 75%, 3: 100%)");
7122
+ gauge("disk_p95_ms", m.disk.latencyWatchdog.diskP95Ms, "Disk read p95 latency in ms");
7123
+ gauge("redis_p95_ms", m.disk.latencyWatchdog.redisP95Ms, "Redis read p95 latency in ms");
7124
+ counter("disk_bypassed_events", m.disk.latencyWatchdog.bypassedTotal, "Total disk bypass activation events");
7125
+ }
7126
+ if (m.disk.pruning) {
7127
+ counter("disk_spills_shed", m.disk.pruning.spillsShedTotal, "Total disk spills shed due to pruning or low disk space");
7128
+ counter("disk_prune_rounds", m.disk.pruning.pruneRounds, "Total high-watermark disk prune rounds");
7129
+ counter("disk_entries_pruned", m.disk.pruning.entriesPruned, "Total entries removed by watermark pruning");
7130
+ counter("disk_low_space_pauses", m.disk.pruning.hostVolumeLowSpacePauses, "Total times spills paused due to <10% host volume space");
7131
+ }
5030
7132
  gauge(
5031
7133
  "bloom_false_positive_rate",
5032
7134
  m.bloom.falsePositiveRate,
@@ -5048,6 +7150,17 @@ return 0
5048
7150
  "Emergency L1 eviction rounds triggered by heap pressure"
5049
7151
  );
5050
7152
  }
7153
+ if (m.remoteSnapshot?.enabled) {
7154
+ counter("remote_snapshot_uploads", m.remoteSnapshot.uploads, "Total remote snapshot uploads");
7155
+ counter("remote_snapshot_downloads", m.remoteSnapshot.downloads, "Total remote snapshot downloads");
7156
+ counter("remote_snapshot_errors", m.remoteSnapshot.errors, "Total remote snapshot errors");
7157
+ }
7158
+ if (m.crossRegion?.enabled) {
7159
+ counter("cross_region_sent", m.crossRegion.sent, "Total cross-region invalidations broadcast");
7160
+ counter("cross_region_received", m.crossRegion.received, "Total cross-region invalidations received");
7161
+ counter("cross_region_deduplicated", m.crossRegion.deduplicated, "Total cross-region invalidations deduplicated or self-filtered");
7162
+ counter("cross_region_errors", m.crossRegion.errors, "Total cross-region relay errors");
7163
+ }
5051
7164
  return lines.join("\n");
5052
7165
  }
5053
7166
  // ── Lifecycle ────────────────────────────────────────────────────────────
@@ -5066,23 +7179,31 @@ return 0
5066
7179
  /** Close Redis connections and stop all background timers. */
5067
7180
  async destroy() {
5068
7181
  this._destroyed = true;
7182
+ const g = globalThis;
7183
+ const key = _CacheService.globalKey(this.opts);
7184
+ if (g[key] === this) {
7185
+ delete g[key];
7186
+ }
5069
7187
  if (this.cleanupInterval) clearInterval(this.cleanupInterval);
5070
7188
  if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
5071
7189
  if (this.oomInterval) clearInterval(this.oomInterval);
5072
7190
  if (this.metricsInterval) clearInterval(this.metricsInterval);
5073
- if (this._shutdownHandler) {
5074
- process.off("SIGTERM", this._shutdownHandler);
5075
- process.off("SIGINT", this._shutdownHandler);
5076
- this._shutdownHandler = null;
7191
+ if (this.remoteSnapshotInterval) {
7192
+ clearInterval(this.remoteSnapshotInterval);
7193
+ this.remoteSnapshotInterval = null;
5077
7194
  }
7195
+ ProcessTerminationBus.unregister(this);
7196
+ this._shutdownHandler = null;
5078
7197
  if (this._workerPool) {
5079
7198
  await this._workerPool.destroy();
5080
7199
  this._workerPool = null;
5081
7200
  }
5082
7201
  if (this.subClient) {
5083
- try {
5084
- this.subClient.disconnect();
5085
- } catch {
7202
+ if (!this.opts.redisSubClient) {
7203
+ try {
7204
+ this.subClient.disconnect();
7205
+ } catch {
7206
+ }
5086
7207
  }
5087
7208
  this.subClient = null;
5088
7209
  }
@@ -5094,14 +7215,33 @@ return 0
5094
7215
  this.streamClient = null;
5095
7216
  }
5096
7217
  if (this.redis) {
5097
- try {
5098
- await this.redis.disconnect();
5099
- } catch {
7218
+ if (!this.opts.redisClient) {
7219
+ try {
7220
+ await this.redis.disconnect();
7221
+ } catch {
7222
+ }
5100
7223
  }
5101
7224
  this.redis = null;
5102
7225
  }
7226
+ if (this._ipcServer) {
7227
+ await this._ipcServer.close();
7228
+ this._ipcServer = void 0;
7229
+ }
5103
7230
  if (!this._diskDisabled) this.disk.close();
5104
7231
  }
7232
+ /**
7233
+ * Return the active IPC telemetry server instance, if enabled.
7234
+ */
7235
+ getIpcServer() {
7236
+ return this._ipcServer;
7237
+ }
7238
+ /**
7239
+ * Return real-time telemetry and metrics for the Window TinyLFU admission policy.
7240
+ * Returns `undefined` if W-TinyLFU admission is not active.
7241
+ */
7242
+ getWTinyLfuStats() {
7243
+ return this.l1.getWTinyLfuStats();
7244
+ }
5105
7245
  };
5106
7246
  }
5107
7247
  });
@@ -5109,31 +7249,102 @@ return 0
5109
7249
  // src/http/index.ts
5110
7250
  var http_exports = {};
5111
7251
  __export(http_exports, {
7252
+ buildDeterministicKey: () => buildDeterministicKey,
7253
+ buildEdgeDeterministicKey: () => buildEdgeDeterministicKey,
7254
+ computeEdgeETag: () => computeEdgeETag,
7255
+ createExpressMiddleware: () => createExpressMiddleware,
7256
+ createFastifyPlugin: () => createFastifyPlugin,
5112
7257
  expressCache: () => expressCache,
5113
7258
  fastifyCache: () => fastifyCache,
7259
+ fastifyCachePlugin: () => fastifyCachePlugin,
5114
7260
  generateETag: () => generateETag,
5115
- honoCache: () => honoCache
7261
+ honoCache: () => honoEdgeCache,
7262
+ shouldSkipCache: () => shouldSkipCache
5116
7263
  });
5117
7264
  module.exports = __toCommonJS(http_exports);
5118
- var import_crypto4 = __toESM(require("crypto"), 1);
7265
+
7266
+ // src/http/utils.ts
7267
+ var import_crypto = __toESM(require("crypto"), 1);
7268
+ function buildDeterministicKey(req, options) {
7269
+ if (options?.keyGenerator) {
7270
+ return options.keyGenerator(req);
7271
+ }
7272
+ const method = (req.method || "GET").toUpperCase();
7273
+ const rawUrl = req.originalUrl || req.url || "/";
7274
+ const qIdx = rawUrl.indexOf("?");
7275
+ const path4 = qIdx >= 0 ? rawUrl.slice(0, qIdx) : rawUrl;
7276
+ let queryString = "";
7277
+ if (qIdx >= 0) {
7278
+ const rawQuery = rawUrl.slice(qIdx + 1);
7279
+ try {
7280
+ const params = new URLSearchParams(rawQuery);
7281
+ params.sort();
7282
+ queryString = params.toString();
7283
+ } catch {
7284
+ queryString = rawQuery;
7285
+ }
7286
+ }
7287
+ let key = `http:${method}:${path4}`;
7288
+ if (queryString) {
7289
+ key += `?${queryString}`;
7290
+ }
7291
+ if (options?.headerWhitelist && options.headerWhitelist.length > 0 && req.headers) {
7292
+ const sortedHeaders = [...options.headerWhitelist].sort();
7293
+ for (const h of sortedHeaders) {
7294
+ const normalizedHeader = h.toLowerCase();
7295
+ const val = req.headers[normalizedHeader];
7296
+ if (val !== void 0 && val !== null && val !== "") {
7297
+ const headerStr = Array.isArray(val) ? val.join(",") : String(val);
7298
+ key += `|h:${normalizedHeader}=${headerStr}`;
7299
+ }
7300
+ }
7301
+ }
7302
+ return key;
7303
+ }
7304
+ function shouldSkipCache(req, customSkip) {
7305
+ if (customSkip && customSkip(req)) return true;
7306
+ const cc = req.headers ? req.headers["cache-control"] || req.headers["Cache-Control"] : void 0;
7307
+ if (typeof cc === "string") {
7308
+ const lower = cc.toLowerCase();
7309
+ if (lower.includes("no-cache") || lower.includes("no-store")) {
7310
+ return true;
7311
+ }
7312
+ }
7313
+ return false;
7314
+ }
5119
7315
  function generateETag(data) {
5120
7316
  const str = typeof data === "string" ? data : Buffer.isBuffer(data) ? data.toString("utf8") : JSON.stringify(data);
5121
- const hash = import_crypto4.default.createHash("sha1").update(str).digest("hex").slice(0, 16);
7317
+ const hash = import_crypto.default.createHash("sha1").update(str).digest("hex").slice(0, 16);
5122
7318
  return `W/"${str.length.toString(16)}-${hash}"`;
5123
7319
  }
5124
- function expressCache(options = {}) {
5125
- const { cache, keyGenerator, etag = true, ttl = 300, swr, tags } = options;
7320
+
7321
+ // src/http/express.ts
7322
+ function createExpressMiddleware(options = {}) {
7323
+ const {
7324
+ cache,
7325
+ etag = true,
7326
+ ttl = 300,
7327
+ swr,
7328
+ tags,
7329
+ skipCache,
7330
+ keyGenerator,
7331
+ headerWhitelist
7332
+ } = options;
5126
7333
  return async (req, res, next) => {
5127
7334
  if (req.method !== "GET" && req.method !== "HEAD") {
5128
7335
  return next();
5129
7336
  }
7337
+ if (shouldSkipCache(req, skipCache)) {
7338
+ return next();
7339
+ }
5130
7340
  let activeCache = cache;
5131
7341
  if (!activeCache) {
5132
7342
  const { CacheService: CacheService2 } = await Promise.resolve().then(() => (init_cache_service(), cache_service_exports));
5133
7343
  activeCache = CacheService2.create();
5134
7344
  }
5135
- const key = keyGenerator ? keyGenerator(req) : `http:${req.method}:${req.originalUrl || req.url}`;
5136
- const ifNoneMatch = req.headers ? req.headers["if-none-match"] : void 0;
7345
+ const key = buildDeterministicKey(req, { keyGenerator, headerWhitelist });
7346
+ const ifNoneMatch = req.headers ? req.headers["if-none-match"] || req.headers["If-None-Match"] : void 0;
7347
+ const resolvedTags = typeof tags === "function" ? tags(req) : tags;
5137
7348
  try {
5138
7349
  const cached = await activeCache.get(
5139
7350
  key,
@@ -5141,34 +7352,62 @@ function expressCache(options = {}) {
5141
7352
  return new Promise((resolve) => {
5142
7353
  const origJson = res.json?.bind(res);
5143
7354
  const origSend = res.send?.bind(res);
7355
+ const origEnd = res.end?.bind(res);
7356
+ const getStatusCode = () => res.statusCode ?? 200;
5144
7357
  if (origJson) {
5145
7358
  res.json = (body) => {
7359
+ const status = getStatusCode();
5146
7360
  const bodyEtag = etag ? generateETag(body) : void 0;
5147
- resolve({ body, contentType: "application/json; charset=utf-8", etag: bodyEtag });
5148
- if (ifNoneMatch && ifNoneMatch === bodyEtag) {
5149
- return res.status(304).end();
7361
+ const contentType = res.getHeader?.("content-type") || "application/json; charset=utf-8";
7362
+ resolve({ body, contentType, etag: bodyEtag, status });
7363
+ if (ifNoneMatch && bodyEtag && ifNoneMatch === bodyEtag) {
7364
+ res.status?.(304);
7365
+ origEnd?.();
7366
+ return;
7367
+ }
7368
+ if (bodyEtag && res.setHeader) {
7369
+ res.setHeader("ETag", bodyEtag);
5150
7370
  }
5151
- if (bodyEtag && res.setHeader) res.setHeader("ETag", bodyEtag);
5152
7371
  return origJson(body);
5153
7372
  };
5154
7373
  }
5155
7374
  if (origSend) {
5156
7375
  res.send = (body) => {
7376
+ const status = getStatusCode();
5157
7377
  const bodyEtag = etag ? generateETag(body) : void 0;
5158
- resolve({ body, contentType: res.getHeader ? res.getHeader("content-type") : void 0, etag: bodyEtag });
5159
- if (ifNoneMatch && ifNoneMatch === bodyEtag) {
5160
- return res.status(304).end();
7378
+ const contentType = res.getHeader?.("content-type");
7379
+ resolve({ body, contentType, etag: bodyEtag, status });
7380
+ if (ifNoneMatch && bodyEtag && ifNoneMatch === bodyEtag) {
7381
+ res.status?.(304);
7382
+ origEnd?.();
7383
+ return;
7384
+ }
7385
+ if (bodyEtag && res.setHeader) {
7386
+ res.setHeader("ETag", bodyEtag);
5161
7387
  }
5162
- if (bodyEtag && res.setHeader) res.setHeader("ETag", bodyEtag);
5163
7388
  return origSend(body);
5164
7389
  };
5165
7390
  }
7391
+ if (origEnd) {
7392
+ res.end = (body) => {
7393
+ const status = getStatusCode();
7394
+ const bodyEtag = etag && body != null ? generateETag(body) : void 0;
7395
+ const contentType = res.getHeader?.("content-type");
7396
+ resolve({ body, contentType, etag: bodyEtag, status });
7397
+ return origEnd(body);
7398
+ };
7399
+ }
5166
7400
  next();
5167
7401
  });
5168
7402
  },
5169
7403
  ttl,
5170
- { swr, tags }
7404
+ { swr, tags: resolvedTags }
5171
7405
  );
7406
+ if (typeof cached.status === "number" && (cached.status < 200 || cached.status >= 300)) {
7407
+ await activeCache.delete(key).catch(() => {
7408
+ });
7409
+ return;
7410
+ }
5172
7411
  if (!res.headersSent) {
5173
7412
  if (cached.etag) {
5174
7413
  if (res.setHeader) res.setHeader("ETag", cached.etag);
@@ -5179,10 +7418,15 @@ function expressCache(options = {}) {
5179
7418
  if (cached.contentType && res.setHeader) {
5180
7419
  res.setHeader("Content-Type", cached.contentType);
5181
7420
  }
7421
+ if (cached.status && res.status) {
7422
+ res.status(cached.status);
7423
+ }
5182
7424
  if (typeof cached.body === "object" && cached.body !== null && res.json) {
5183
7425
  return res.json(cached.body);
5184
7426
  } else if (res.send) {
5185
7427
  return res.send(cached.body);
7428
+ } else if (res.end) {
7429
+ return res.end(cached.body);
5186
7430
  }
5187
7431
  }
5188
7432
  } catch (err) {
@@ -5190,61 +7434,114 @@ function expressCache(options = {}) {
5190
7434
  }
5191
7435
  };
5192
7436
  }
5193
- function honoCache(options = {}) {
5194
- const { cache, keyGenerator, etag = true, ttl = 300, swr, tags } = options;
5195
- return async (c, next) => {
5196
- if (c.req.method !== "GET" && c.req.method !== "HEAD") {
5197
- return await next();
5198
- }
5199
- let activeCache = cache;
7437
+ var expressCache = createExpressMiddleware;
7438
+
7439
+ // src/http/fastify.ts
7440
+ function createFastifyPlugin(options = {}) {
7441
+ const plugin = async function(fastify, pluginOpts = {}) {
7442
+ const mergedOpts = { ...options, ...pluginOpts };
7443
+ const etag = mergedOpts.etag ?? true;
7444
+ const ttl = mergedOpts.ttl ?? 300;
7445
+ let activeCache = mergedOpts.cache;
5200
7446
  if (!activeCache) {
5201
7447
  const { CacheService: CacheService2 } = await Promise.resolve().then(() => (init_cache_service(), cache_service_exports));
5202
7448
  activeCache = CacheService2.create();
5203
7449
  }
5204
- const key = keyGenerator ? keyGenerator(c.req) : `http:${c.req.method}:${c.req.url}`;
5205
- const ifNoneMatch = c.req.header ? c.req.header("if-none-match") : void 0;
5206
- const cached = await activeCache.get(
5207
- key,
5208
- async () => {
5209
- await next();
5210
- const res = c.res;
5211
- const text = await res.clone().text();
5212
- const bodyEtag = etag ? generateETag(text) : void 0;
5213
- return {
5214
- body: text,
5215
- contentType: res.headers.get("content-type") ?? "text/plain",
5216
- etag: bodyEtag
7450
+ fastify.addHook("onRequest", async (req, reply) => {
7451
+ if (req.method !== "GET" && req.method !== "HEAD") {
7452
+ return;
7453
+ }
7454
+ if (shouldSkipCache(req, mergedOpts.skipCache)) {
7455
+ return;
7456
+ }
7457
+ const key = buildDeterministicKey(req, {
7458
+ keyGenerator: mergedOpts.keyGenerator,
7459
+ headerWhitelist: mergedOpts.headerWhitelist
7460
+ });
7461
+ const ifNoneMatch = req.headers ? req.headers["if-none-match"] || req.headers["If-None-Match"] : void 0;
7462
+ const cached = await activeCache.get(
7463
+ key,
7464
+ async () => null,
7465
+ 0
7466
+ );
7467
+ if (cached && typeof cached === "object" && cached.body !== null) {
7468
+ if (cached.etag) {
7469
+ reply.header("ETag", cached.etag);
7470
+ if (ifNoneMatch === cached.etag) {
7471
+ reply.code(304);
7472
+ return reply.send();
7473
+ }
7474
+ }
7475
+ if (cached.contentType) {
7476
+ reply.header("Content-Type", cached.contentType);
7477
+ }
7478
+ reply.code(cached.status ?? 200);
7479
+ return reply.send(cached.body);
7480
+ }
7481
+ req._tricacheKey = key;
7482
+ const resolvedTags = typeof mergedOpts.tags === "function" ? mergedOpts.tags(req) : mergedOpts.tags;
7483
+ req._tricacheTags = resolvedTags;
7484
+ });
7485
+ fastify.addHook("onSend", async (req, reply, payload) => {
7486
+ const key = req._tricacheKey;
7487
+ if (!key) {
7488
+ return payload;
7489
+ }
7490
+ const statusCode = reply.statusCode ?? reply.raw?.statusCode ?? 200;
7491
+ if (statusCode >= 200 && statusCode < 300 && payload !== void 0 && payload !== null) {
7492
+ const payloadEtag = etag ? generateETag(payload) : void 0;
7493
+ const contentType = reply.getHeader("content-type") || (typeof payload === "object" ? "application/json" : "text/plain");
7494
+ if (payloadEtag) {
7495
+ reply.header("ETag", payloadEtag);
7496
+ }
7497
+ const ifNoneMatch = req.headers ? req.headers["if-none-match"] || req.headers["If-None-Match"] : void 0;
7498
+ if (ifNoneMatch && payloadEtag && ifNoneMatch === payloadEtag) {
7499
+ reply.code(304);
7500
+ return "";
7501
+ }
7502
+ const entry = {
7503
+ body: payload,
7504
+ contentType,
7505
+ etag: payloadEtag,
7506
+ status: statusCode
5217
7507
  };
5218
- },
5219
- ttl,
5220
- { swr, tags }
5221
- );
5222
- if (cached.etag && ifNoneMatch === cached.etag) {
5223
- return c.body(null, 304, { ETag: cached.etag });
5224
- }
5225
- const headers = {};
5226
- if (cached.etag) headers["ETag"] = cached.etag;
5227
- if (cached.contentType) headers["Content-Type"] = cached.contentType;
5228
- return c.body(cached.body, 200, headers);
7508
+ void activeCache.set(key, entry, mergedOpts.ttl ?? ttl, void 0, {
7509
+ tags: req._tricacheTags
7510
+ });
7511
+ }
7512
+ return payload;
7513
+ });
5229
7514
  };
7515
+ plugin[/* @__PURE__ */ Symbol.for("skip-override")] = true;
7516
+ return plugin;
5230
7517
  }
7518
+ var fastifyCachePlugin = createFastifyPlugin();
5231
7519
  function fastifyCache(options = {}) {
5232
- const { cache, keyGenerator, etag = true, ttl = 300, tags } = options;
5233
- return async (req, reply) => {
7520
+ const plugin = createFastifyPlugin(options);
7521
+ const dualHandler = async function(first, second) {
7522
+ if (first && typeof first.addHook === "function") {
7523
+ return plugin(first, second);
7524
+ }
7525
+ const req = first;
7526
+ const reply = second;
5234
7527
  if (req.method !== "GET" && req.method !== "HEAD") return;
5235
- let activeCache = cache;
7528
+ if (shouldSkipCache(req, options.skipCache)) return;
7529
+ let activeCache = options.cache;
5236
7530
  if (!activeCache) {
5237
7531
  const { CacheService: CacheService2 } = await Promise.resolve().then(() => (init_cache_service(), cache_service_exports));
5238
7532
  activeCache = CacheService2.create();
5239
7533
  }
5240
- const key = keyGenerator ? keyGenerator(req) : `http:${req.method}:${req.url}`;
5241
- const ifNoneMatch = req.headers ? req.headers["if-none-match"] : void 0;
7534
+ const key = buildDeterministicKey(req, {
7535
+ keyGenerator: options.keyGenerator,
7536
+ headerWhitelist: options.headerWhitelist
7537
+ });
7538
+ const ifNoneMatch = req.headers ? req.headers["if-none-match"] || req.headers["If-None-Match"] : void 0;
5242
7539
  const cached = await activeCache.get(
5243
7540
  key,
5244
7541
  async () => null,
5245
7542
  0
5246
7543
  );
5247
- if (cached) {
7544
+ if (cached && typeof cached === "object" && cached.body !== null) {
5248
7545
  if (cached.etag) {
5249
7546
  if (reply.header) reply.header("ETag", cached.etag);
5250
7547
  if (ifNoneMatch === cached.etag) {
@@ -5257,17 +7554,30 @@ function fastifyCache(options = {}) {
5257
7554
  if (cached.contentType && reply.header) {
5258
7555
  reply.header("Content-Type", cached.contentType);
5259
7556
  }
7557
+ if (cached.status) {
7558
+ if (reply.code) reply.code(cached.status);
7559
+ else if (reply.status) reply.status(cached.status);
7560
+ }
5260
7561
  if (reply.send) return reply.send(cached.body);
5261
7562
  return;
5262
7563
  }
5263
7564
  const origSend = reply.send?.bind(reply);
5264
7565
  if (origSend) {
5265
- reply.send = function(payload) {
5266
- if (payload !== void 0 && payload !== null) {
5267
- const payloadEtag = etag ? generateETag(payload) : void 0;
5268
- const contentType = reply.getHeader && reply.getHeader("content-type") || (typeof payload === "object" ? "application/json" : "text/plain");
5269
- activeCache.set(key, { body: payload, contentType, etag: payloadEtag }, ttl, void 0, { tags }).catch(() => {
5270
- });
7566
+ reply.send = function(resPayload) {
7567
+ if (resPayload !== void 0 && resPayload !== null) {
7568
+ const payloadEtag = options.etag !== false ? generateETag(resPayload) : void 0;
7569
+ const contentType = reply.getHeader && reply.getHeader("content-type") || (typeof resPayload === "object" ? "application/json" : "text/plain");
7570
+ const respStatus = reply.statusCode ?? reply.raw?.statusCode ?? 200;
7571
+ if (respStatus >= 200 && respStatus < 300) {
7572
+ const resolvedTags = typeof options.tags === "function" ? options.tags(req) : options.tags;
7573
+ void activeCache.set(
7574
+ key,
7575
+ { body: resPayload, contentType, etag: payloadEtag, status: respStatus },
7576
+ options.ttl ?? 300,
7577
+ void 0,
7578
+ { tags: resolvedTags }
7579
+ );
7580
+ }
5271
7581
  if (ifNoneMatch && ifNoneMatch === payloadEtag) {
5272
7582
  if (reply.code) reply.code(304);
5273
7583
  else if (reply.status) reply.status(304);
@@ -5275,15 +7585,154 @@ function fastifyCache(options = {}) {
5275
7585
  }
5276
7586
  if (payloadEtag && reply.header) reply.header("ETag", payloadEtag);
5277
7587
  }
5278
- return origSend(payload);
7588
+ return origSend(resPayload);
5279
7589
  };
5280
7590
  }
5281
7591
  };
7592
+ dualHandler[/* @__PURE__ */ Symbol.for("skip-override")] = true;
7593
+ return dualHandler;
7594
+ }
7595
+
7596
+ // src/edge/hono.ts
7597
+ async function computeEdgeETag(text) {
7598
+ try {
7599
+ if (typeof crypto !== "undefined" && crypto.subtle) {
7600
+ const encoder = new TextEncoder();
7601
+ const data = encoder.encode(text);
7602
+ const hashBuf = await crypto.subtle.digest("SHA-1", data);
7603
+ const hashArr = Array.from(new Uint8Array(hashBuf));
7604
+ const hashHex = hashArr.map((b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
7605
+ return `W/"${text.length.toString(16)}-${hashHex}"`;
7606
+ }
7607
+ } catch {
7608
+ }
7609
+ let h = 0;
7610
+ for (let i = 0; i < text.length; i++) {
7611
+ h = Math.imul(31, h) + text.charCodeAt(i) | 0;
7612
+ }
7613
+ return `W/"${text.length.toString(16)}-${Math.abs(h).toString(16)}"`;
7614
+ }
7615
+ function buildEdgeDeterministicKey(c, options) {
7616
+ if (options?.keyGenerator) {
7617
+ return options.keyGenerator(c);
7618
+ }
7619
+ const req = c.req;
7620
+ const method = (req.method || "GET").toUpperCase();
7621
+ const rawUrl = req.url || "/";
7622
+ const qIdx = rawUrl.indexOf("?");
7623
+ const path4 = qIdx >= 0 ? rawUrl.slice(0, qIdx) : rawUrl;
7624
+ let queryString = "";
7625
+ if (qIdx >= 0) {
7626
+ const rawQuery = rawUrl.slice(qIdx + 1);
7627
+ try {
7628
+ const params = new URLSearchParams(rawQuery);
7629
+ params.sort();
7630
+ queryString = params.toString();
7631
+ } catch {
7632
+ queryString = rawQuery;
7633
+ }
7634
+ }
7635
+ let key = `edge:http:${method}:${path4}`;
7636
+ if (queryString) {
7637
+ key += `?${queryString}`;
7638
+ }
7639
+ if (options?.headerWhitelist && options.headerWhitelist.length > 0 && req.header) {
7640
+ const sortedHeaders = [...options.headerWhitelist].sort();
7641
+ for (const h of sortedHeaders) {
7642
+ const val = req.header(h);
7643
+ if (val !== void 0 && val !== null && val !== "") {
7644
+ key += `|h:${h.toLowerCase()}=${val}`;
7645
+ }
7646
+ }
7647
+ }
7648
+ return key;
7649
+ }
7650
+ function honoEdgeCache(options = {}) {
7651
+ const {
7652
+ cache,
7653
+ etag = true,
7654
+ ttl = 300,
7655
+ swr,
7656
+ tags,
7657
+ skipCache,
7658
+ keyGenerator,
7659
+ headerWhitelist
7660
+ } = options;
7661
+ return async (c, next) => {
7662
+ const method = c.req.method;
7663
+ if (method !== "GET" && method !== "HEAD") {
7664
+ return await next();
7665
+ }
7666
+ if (skipCache && skipCache(c)) {
7667
+ return await next();
7668
+ }
7669
+ const cc = c.req.header?.("cache-control") || c.req.header?.("Cache-Control");
7670
+ if (typeof cc === "string") {
7671
+ const lower = cc.toLowerCase();
7672
+ if (lower.includes("no-cache") || lower.includes("no-store")) {
7673
+ return await next();
7674
+ }
7675
+ }
7676
+ if (!cache) {
7677
+ return await next();
7678
+ }
7679
+ const key = buildEdgeDeterministicKey(c, { keyGenerator, headerWhitelist });
7680
+ const ifNoneMatch = c.req.header?.("if-none-match") || c.req.header?.("If-None-Match");
7681
+ const resolvedTags = typeof tags === "function" ? tags(c) : tags;
7682
+ const cached = await cache.get(
7683
+ key,
7684
+ async () => {
7685
+ await next();
7686
+ const res = c.res;
7687
+ if (!res) {
7688
+ return null;
7689
+ }
7690
+ const clone = res.clone();
7691
+ const text = await clone.text();
7692
+ const statusCode = res.status ?? 200;
7693
+ const bodyEtag = etag ? await computeEdgeETag(text) : void 0;
7694
+ const contentType = res.headers.get("content-type") || "text/plain; charset=utf-8";
7695
+ return {
7696
+ body: text,
7697
+ contentType,
7698
+ etag: bodyEtag,
7699
+ status: statusCode
7700
+ };
7701
+ },
7702
+ ttl,
7703
+ {
7704
+ swr,
7705
+ tags: resolvedTags,
7706
+ ctx: c.executionCtx
7707
+ }
7708
+ );
7709
+ if (!cached) {
7710
+ return;
7711
+ }
7712
+ if (typeof cached.status === "number" && (cached.status < 200 || cached.status >= 300)) {
7713
+ await cache.delete?.(key);
7714
+ return;
7715
+ }
7716
+ if (cached.etag && ifNoneMatch === cached.etag) {
7717
+ return c.body(null, 304, { ETag: cached.etag });
7718
+ }
7719
+ const headers = {};
7720
+ if (cached.etag) headers["ETag"] = cached.etag;
7721
+ if (cached.contentType) headers["Content-Type"] = cached.contentType;
7722
+ return c.body(cached.body, cached.status ?? 200, headers);
7723
+ };
5282
7724
  }
5283
7725
  // Annotate the CommonJS export names for ESM import in node:
5284
7726
  0 && (module.exports = {
7727
+ buildDeterministicKey,
7728
+ buildEdgeDeterministicKey,
7729
+ computeEdgeETag,
7730
+ createExpressMiddleware,
7731
+ createFastifyPlugin,
5285
7732
  expressCache,
5286
7733
  fastifyCache,
7734
+ fastifyCachePlugin,
5287
7735
  generateETag,
5288
- honoCache
7736
+ honoCache,
7737
+ shouldSkipCache
5289
7738
  });