tricache 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +87 -1371
  3. package/dashboards/tricache-alerts.yaml +54 -0
  4. package/dashboards/tricache-grafana.json +548 -0
  5. package/dist/cache-service-5MZXFIGK.js +12 -0
  6. package/dist/cache-service-CyLdpo77.d.ts +871 -0
  7. package/dist/{chunk-EUGYR7KR.js → chunk-6PQ5MOWR.js} +2871 -490
  8. package/dist/chunk-7RV5ZVBB.js +1023 -0
  9. package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
  10. package/dist/chunk-QNU7B43J.js +687 -0
  11. package/dist/chunk-UGD4VEPD.js +138 -0
  12. package/dist/chunk-XZL45ABR.js +108 -0
  13. package/dist/chunk-ZTSWCFYO.js +135 -0
  14. package/dist/cli.cjs +2790 -471
  15. package/dist/cli.d.ts +1 -0
  16. package/dist/cli.js +103 -5
  17. package/dist/dashboard/index.cjs +1065 -0
  18. package/dist/dashboard/index.d.ts +183 -0
  19. package/dist/dashboard/index.js +22 -0
  20. package/dist/drizzle/index.cjs +2553 -470
  21. package/dist/drizzle/index.d.ts +3 -1
  22. package/dist/drizzle/index.js +1 -1
  23. package/dist/edge/index.cjs +1498 -0
  24. package/dist/edge/index.d.ts +127 -0
  25. package/dist/edge/index.js +1109 -0
  26. package/dist/hono-DQRS1Xd7.d.ts +370 -0
  27. package/dist/http/index.cjs +2926 -562
  28. package/dist/http/index.d.ts +109 -23
  29. package/dist/http/index.js +220 -72
  30. package/dist/index.cjs +6936 -2518
  31. package/dist/index.d.ts +547 -30
  32. package/dist/index.js +104 -5
  33. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  34. package/dist/nestjs/index.cjs +2494 -463
  35. package/dist/nestjs/index.d.ts +3 -1
  36. package/dist/nestjs/index.js +6 -3
  37. package/dist/next/index.cjs +2517 -483
  38. package/dist/next/index.d.ts +4 -2
  39. package/dist/next/index.js +14 -10
  40. package/dist/prisma/index.d.ts +3 -1
  41. package/dist/serialize-worker.cjs +5 -4
  42. package/dist/serialize-worker.js +1 -1
  43. package/dist/{cache-service-D8tIXmzb.d.ts → types-B6krw64X.d.ts} +596 -659
  44. package/package.json +34 -6
  45. package/src/adapters/auto-pipeliner.ts +206 -0
  46. package/src/adapters/node-redis.ts +370 -0
  47. package/src/cache-service.ts +1339 -402
  48. package/src/cli.ts +120 -2
  49. package/src/codec.ts +72 -0
  50. package/src/cross-region.ts +245 -0
  51. package/src/dashboard/handler.ts +392 -0
  52. package/src/dashboard/html.ts +594 -0
  53. package/src/dashboard/index.ts +195 -0
  54. package/src/dashboard/types.ts +96 -0
  55. package/src/disk-tier.ts +449 -47
  56. package/src/drizzle/index.ts +86 -86
  57. package/src/edge/adapters/cloudflare-do.ts +130 -0
  58. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  59. package/src/edge/adapters/upstash.ts +143 -0
  60. package/src/edge/cache.ts +797 -0
  61. package/src/edge/crypto.ts +182 -0
  62. package/src/edge/hono.ts +203 -0
  63. package/src/edge/index.ts +37 -0
  64. package/src/edge/types.ts +230 -0
  65. package/src/edge/utils/base64.ts +63 -0
  66. package/src/edge/utils/murmur3.ts +179 -0
  67. package/src/encryption.ts +127 -5
  68. package/src/http/express.ts +195 -0
  69. package/src/http/fastify.ts +260 -0
  70. package/src/http/index.ts +39 -258
  71. package/src/http/utils.ts +92 -0
  72. package/src/index.ts +149 -47
  73. package/src/ipc-telemetry.ts +481 -0
  74. package/src/latency-watchdog.ts +282 -0
  75. package/src/nestjs/decorators.ts +161 -161
  76. package/src/nestjs/index.ts +23 -23
  77. package/src/nestjs/tricache.module.ts +104 -104
  78. package/src/nestjs/tricache.store.ts +97 -97
  79. package/src/nestjs/types.ts +79 -79
  80. package/src/next/cache-handler.ts +12 -9
  81. package/src/next/index.ts +37 -37
  82. package/src/next/isr-handler.ts +105 -105
  83. package/src/next/types.ts +130 -130
  84. package/src/remote-snapshot.ts +153 -0
  85. package/src/serialize-worker.ts +120 -120
  86. package/src/sigv4-snapshot-adapter.ts +260 -0
  87. package/src/smart-memory-cache.ts +91 -8
  88. package/src/types.ts +290 -2
  89. package/src/utils/cgroup.ts +100 -0
  90. package/src/utils/tracing.ts +54 -0
  91. package/src/wasm/bloom-filter-wasm.ts +109 -102
  92. package/src/worker-pool.ts +299 -299
  93. package/src/wtiny-lfu.ts +624 -0
  94. package/dist/cache-service-5GATUYAK.js +0 -7
  95. package/dist/chunk-UBSR5UYA.js +0 -0
@@ -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,7 +297,7 @@ 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_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, MAGIC_ENVELOPE, EnvelopeEncryption;
262
301
  var init_encryption = __esm({
263
302
  "src/encryption.ts"() {
264
303
  "use strict";
@@ -380,17 +419,17 @@ var init_encryption = __esm({
380
419
  throw new Error("XOR key must be at least 1 byte");
381
420
  }
382
421
  this._key = buf;
383
- if (mode !== "xor") {
422
+ if (resolvedMode !== "xor") {
384
423
  this._keyObj = (0, import_crypto.createSecretKey)(buf);
385
424
  const _wc = (0, import_crypto.createCipheriv)(
386
- mode,
425
+ resolvedMode,
387
426
  this._keyObj,
388
- Buffer.alloc(mode === "aes-128-ctr" ? CTR_IV_BYTES : IV_BYTES)
427
+ Buffer.alloc(resolvedMode === "aes-128-ctr" ? CTR_IV_BYTES : IV_BYTES)
389
428
  );
390
429
  _wc.update(Buffer.alloc(0));
391
430
  _wc.final();
392
431
  }
393
- if (mode === "xor") {
432
+ if (resolvedMode === "xor") {
394
433
  logger.warn(
395
434
  "Cache obfuscation enabled (XOR). WARNING: XOR is NOT cryptographic \u2014 use only for dev or non-sensitive data."
396
435
  );
@@ -658,6 +697,260 @@ var init_encryption = __esm({
658
697
  return plain;
659
698
  }
660
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_crypto.randomBytes)(32);
707
+ let encryptedKey;
708
+ if (options.kmsEncrypt) {
709
+ encryptedKey = await options.kmsEncrypt(dek);
710
+ } else if (options.publicKey) {
711
+ encryptedKey = (0, import_crypto.publicEncrypt)(
712
+ {
713
+ key: options.publicKey,
714
+ padding: import_crypto.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_crypto.randomBytes)(IV_BYTES);
723
+ const cipher = (0, import_crypto.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_crypto.privateDecrypt)(
758
+ {
759
+ key: options.privateKey,
760
+ padding: import_crypto.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_crypto.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";
661
954
  }
662
955
  });
663
956
 
@@ -666,10 +959,13 @@ var BLOOM_WASM_BASE64, KEY_STAGING_OFFSET, MAX_KEY_BYTES, BLOOM_WASM_MODULE, Was
666
959
  var init_bloom_filter_wasm = __esm({
667
960
  "src/wasm/bloom-filter-wasm.ts"() {
668
961
  "use strict";
962
+ init_base64();
669
963
  BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
670
964
  KEY_STAGING_OFFSET = 2e4;
671
965
  MAX_KEY_BYTES = 512;
672
- 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
+ );
673
969
  WasmBloomFilter = class {
674
970
  exports;
675
971
  mem;
@@ -767,11 +1063,12 @@ function globMatchParts(parts, first, last, key) {
767
1063
  }
768
1064
  return true;
769
1065
  }
770
- var import_msgpackr, 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;
771
1067
  var init_smart_memory_cache = __esm({
772
1068
  "src/smart-memory-cache.ts"() {
773
1069
  "use strict";
774
- import_msgpackr = require("msgpackr");
1070
+ init_codec();
1071
+ init_wtiny_lfu();
775
1072
  init_bloom_filter_wasm();
776
1073
  LARGE_VALUE_BYTES = 16384;
777
1074
  EVICTION_BATCH_PERCENT = 0.2;
@@ -912,11 +1209,13 @@ var init_smart_memory_cache = __esm({
912
1209
  SmartMemoryCache = class {
913
1210
  cache = /* @__PURE__ */ new Map();
914
1211
  opts;
1212
+ codec;
915
1213
  bloom;
916
1214
  /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
917
1215
  categoryPrefixes;
918
1216
  /** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
919
1217
  sketch = new CountMinSketch();
1218
+ wtinyPolicy;
920
1219
  totalSize = 0;
921
1220
  categoryCount = /* @__PURE__ */ new Map();
922
1221
  categorySize = /* @__PURE__ */ new Map();
@@ -940,8 +1239,12 @@ var init_smart_memory_cache = __esm({
940
1239
  _evictGPool = Array.from({ length: EVICTION_SAMPLE }, () => ({ key: "", score: 0 }));
941
1240
  constructor(opts, existing) {
942
1241
  this.opts = opts;
1242
+ this.codec = opts.codec ?? defaultCodec;
943
1243
  this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
944
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
+ }
945
1248
  if (existing) {
946
1249
  for (const [k, v] of existing) this.cache.set(k, v);
947
1250
  this.recalculateStats();
@@ -954,6 +1257,12 @@ var init_smart_memory_cache = __esm({
954
1257
  this.categoryCount.clear();
955
1258
  this.categorySize.clear();
956
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
+ }
957
1266
  for (const [key, entry] of this.cache) {
958
1267
  this.totalSize += entry.size;
959
1268
  const cat = this.getCategory(key);
@@ -979,6 +1288,7 @@ var init_smart_memory_cache = __esm({
979
1288
  _delete(key, reason = "manual") {
980
1289
  const entry = this.cache.get(key);
981
1290
  if (!entry) return false;
1291
+ this.wtinyPolicy?.onDelete(key);
982
1292
  const cat = this.getCategory(key);
983
1293
  this.totalSize -= entry.size;
984
1294
  this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
@@ -1139,7 +1449,8 @@ var init_smart_memory_cache = __esm({
1139
1449
  entry.hits++;
1140
1450
  entry.lastAccess = now;
1141
1451
  if ((entry.hits & 3) === 0) this.sketch.increment(key);
1142
- const value = entry.value !== void 0 ? entry.value : (0, import_msgpackr.unpack)(entry.data);
1452
+ this.wtinyPolicy?.onAccess(key);
1453
+ const value = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
1143
1454
  const hit = {
1144
1455
  value,
1145
1456
  isStale: entry.staleAt !== void 0 && now > entry.staleAt,
@@ -1153,7 +1464,7 @@ var init_smart_memory_cache = __esm({
1153
1464
  return hit;
1154
1465
  }
1155
1466
  set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
1156
- const packed = (0, import_msgpackr.pack)(data);
1467
+ const packed = this.codec.encode(data);
1157
1468
  const size = packed.byteLength;
1158
1469
  this.compressions++;
1159
1470
  this.sketch.increment(key);
@@ -1170,7 +1481,51 @@ var init_smart_memory_cache = __esm({
1170
1481
  this.categorySize.set(cat, (this.categorySize.get(cat) ?? existingEntry.size) - existingEntry.size);
1171
1482
  this.cache.delete(key);
1172
1483
  }
1173
- 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
+ }
1174
1529
  const now = Date.now();
1175
1530
  const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
1176
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 });
@@ -1230,6 +1585,7 @@ var init_smart_memory_cache = __esm({
1230
1585
  }
1231
1586
  const count = this.cache.size;
1232
1587
  this.cache.clear();
1588
+ this.wtinyPolicy?.clear();
1233
1589
  this.totalSize = 0;
1234
1590
  this.categoryCount.clear();
1235
1591
  this.categorySize.clear();
@@ -1397,8 +1753,8 @@ var init_smart_memory_cache = __esm({
1397
1753
  if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
1398
1754
  if (this.cache.has(key)) continue;
1399
1755
  const rawData = entry.data;
1400
- const data = !entry.isCompressed ? (0, import_msgpackr.pack)(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
1401
- 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;
1402
1758
  this.cache.set(key, { ...entry, data, value, isCompressed: true });
1403
1759
  this.bloom.add(key);
1404
1760
  loaded++;
@@ -1469,7 +1825,7 @@ var init_smart_memory_cache = __esm({
1469
1825
  * if the live object was not cached (large-entry optimisation or disk-restored entry).
1470
1826
  */
1471
1827
  resolveValue(entry) {
1472
- 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);
1473
1829
  }
1474
1830
  // ── Stats ─────────────────────────────────────────────────────────────────
1475
1831
  get size() {
@@ -1574,6 +1930,13 @@ var init_smart_memory_cache = __esm({
1574
1930
  out.sort((a, b) => b.hits - a.hits);
1575
1931
  return out.slice(0, n);
1576
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
+ }
1577
1940
  };
1578
1941
  }
1579
1942
  });
@@ -1640,19 +2003,146 @@ var init_compression = __esm({
1640
2003
  });
1641
2004
 
1642
2005
  // src/disk-tier.ts
1643
- 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_crypto2, import_os2, BoundedDiskQueue, _SqliteDB, DISK_MAGIC, DISK_MAGIC_V2, V2_HEADER_LEN, DISK_TIER_VERSION, DiskTier;
1644
2041
  var init_disk_tier = __esm({
1645
2042
  "src/disk-tier.ts"() {
1646
2043
  "use strict";
1647
2044
  import_fs2 = __toESM(require("fs"), 1);
1648
2045
  import_path2 = __toESM(require("path"), 1);
1649
2046
  import_crypto2 = __toESM(require("crypto"), 1);
1650
- import_msgpackr2 = require("msgpackr");
2047
+ import_os2 = __toESM(require("os"), 1);
2048
+ init_codec();
1651
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
+ };
1652
2139
  _SqliteDB = null;
1653
2140
  try {
1654
- const sqlite = process.getBuiltinModule("node:sqlite");
1655
- _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
+ }
1656
2146
  } catch {
1657
2147
  }
1658
2148
  DISK_MAGIC = Buffer.from([68, 84, 73, 69, 82, 86, 49, 0]);
@@ -1661,6 +2151,8 @@ var init_disk_tier = __esm({
1661
2151
  DISK_TIER_VERSION = 1;
1662
2152
  DiskTier = class {
1663
2153
  opts;
2154
+ codec;
2155
+ diskQueue;
1664
2156
  dirReady = false;
1665
2157
  diskUsageBytes = 0;
1666
2158
  usageCounted = false;
@@ -1668,6 +2160,14 @@ var init_disk_tier = __esm({
1668
2160
  // maintained in-memory; avoids walkCacheFiles() in stats
1669
2161
  /** Next bucket index (0–255) for the staggered janitor wheel. */
1670
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;
1671
2171
  // ── SQLite metadata index (optional, requires node:sqlite) ───────────────
1672
2172
  _db = null;
1673
2173
  _stmtInsert = null;
@@ -1682,8 +2182,19 @@ var init_disk_tier = __esm({
1682
2182
  // DELETE expired rows
1683
2183
  _stmtStats = null;
1684
2184
  // COUNT + SUM(size)
2185
+ _stmtPruneChunk = null;
2186
+ // SELECT chunk for watermark pruning
1685
2187
  constructor(opts) {
1686
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
+ );
1687
2198
  }
1688
2199
  // ── Helpers ───────────────────────────────────────────────────────────────
1689
2200
  ensureDir() {
@@ -1718,15 +2229,30 @@ var init_disk_tier = __esm({
1718
2229
  PRAGMA synchronous = NORMAL;
1719
2230
  PRAGMA temp_store = MEMORY;
1720
2231
  CREATE TABLE IF NOT EXISTS meta (
1721
- key_hash TEXT PRIMARY KEY,
1722
- file_path TEXT NOT NULL,
1723
- expires_at INTEGER NOT NULL,
1724
- 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
1725
2238
  );
1726
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);
1727
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
+ }
1728
2254
  this._stmtInsert = this._db.prepare(
1729
- "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 (?,?,?,?,?,?)"
1730
2256
  );
1731
2257
  this._stmtSelect = this._db.prepare(
1732
2258
  "SELECT file_path, expires_at FROM meta WHERE key_hash = ?"
@@ -1739,13 +2265,16 @@ var init_disk_tier = __esm({
1739
2265
  this._stmtStats = this._db.prepare(
1740
2266
  "SELECT COUNT(*) AS cnt, COALESCE(SUM(size), 0) AS bytes FROM meta"
1741
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
+ );
1742
2271
  const row = this._stmtStats.get();
1743
2272
  this.fileCount = row.cnt;
1744
2273
  this.diskUsageBytes = row.bytes;
1745
2274
  this.usageCounted = true;
1746
2275
  this.opts.logger.debug("DiskTier: SQLite index ready", { entries: row.cnt });
1747
2276
  } catch (err) {
1748
- 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;
1749
2278
  this.opts.logger.warn("DiskTier: SQLite init failed, using file-only mode", {
1750
2279
  error: err.message
1751
2280
  });
@@ -1840,7 +2369,7 @@ var init_disk_tier = __esm({
1840
2369
  return results;
1841
2370
  }
1842
2371
  isForbidden(key) {
1843
- return this.opts.forbiddenPrefixes.some((p) => key.startsWith(p));
2372
+ return this.opts.forbiddenPrefixes?.some((p) => key.startsWith(p)) ?? false;
1844
2373
  }
1845
2374
  encrypt(data) {
1846
2375
  if (!this.opts.encryption) return data;
@@ -1892,7 +2421,16 @@ var init_disk_tier = __esm({
1892
2421
  this.ensureDir();
1893
2422
  if (!this.dirReady) return;
1894
2423
  this.ensureUsageCounted();
1895
- 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
+ }
1896
2434
  let final;
1897
2435
  try {
1898
2436
  const payload = {
@@ -1904,7 +2442,7 @@ var init_disk_tier = __esm({
1904
2442
  },
1905
2443
  writtenAt: Date.now()
1906
2444
  };
1907
- const packed = (0, import_msgpackr2.pack)(payload);
2445
+ const packed = this.codec.encode(payload);
1908
2446
  if (packed.length > this.opts.entryMaxBytes) return;
1909
2447
  let toEncrypt = packed;
1910
2448
  if (this.opts.compression && this.opts.compression !== "none" && packed.length > (this.opts.compressionThresholdBytes ?? 1024)) {
@@ -1920,39 +2458,52 @@ var init_disk_tier = __esm({
1920
2458
  }
1921
2459
  const hash = this.keyToHash(key);
1922
2460
  const filePath = this.hashToWritePath(hash, entry.expiresAt);
1923
- const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
2461
+ const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${import_crypto2.default.randomBytes(6).toString("hex")}.tmp`;
1924
2462
  this.diskUsageBytes += final.length;
1925
2463
  this.fileCount++;
1926
- try {
1927
- await import_fs2.default.promises.mkdir(import_path2.default.dirname(filePath), { recursive: true });
1928
- 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 () => {
1929
2468
  try {
1930
- await import_fs2.default.promises.rename(tmpPath, filePath);
1931
- } catch (renameErr) {
1932
- const code = renameErr?.code;
1933
- if (code === "EBUSY" || code === "EPERM") {
1934
- 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 {
1935
2472
  await import_fs2.default.promises.rename(tmpPath, filePath);
1936
- } else {
1937
- 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
+ }
1938
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;
1939
2502
  }
1940
- if (this._db) {
1941
- this._stmtInsert.run(hash, filePath, entry.expiresAt, final.length);
1942
- }
1943
- this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
1944
- } catch (err) {
1945
- try {
1946
- await import_fs2.default.promises.unlink(tmpPath);
1947
- } catch {
1948
- }
2503
+ });
2504
+ if (result === null) {
1949
2505
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
1950
2506
  this.fileCount = Math.max(0, this.fileCount - 1);
1951
- if (this._db) try {
1952
- this._stmtDelete.run(hash);
1953
- } catch {
1954
- }
1955
- this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
1956
2507
  }
1957
2508
  }
1958
2509
  /** Load a key from disk, or return null on miss/expiry/corruption. */
@@ -2030,7 +2581,7 @@ var init_disk_tier = __esm({
2030
2581
  }
2031
2582
  }
2032
2583
  const uncompressed = decompressWithHeader(decrypted, this.opts.compression ?? "brotli");
2033
- const payload = (0, import_msgpackr2.unpack)(uncompressed);
2584
+ const payload = this.codec.decode(uncompressed);
2034
2585
  if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
2035
2586
  if (payload.entry.expiresAt <= Date.now()) return null;
2036
2587
  const entry = payload.entry;
@@ -2153,7 +2704,7 @@ var init_disk_tier = __esm({
2153
2704
  purged++;
2154
2705
  continue;
2155
2706
  }
2156
- const payload = (0, import_msgpackr2.unpack)(dec);
2707
+ const payload = this.codec.decode(dec);
2157
2708
  if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
2158
2709
  import_fs2.default.unlinkSync(filePath);
2159
2710
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
@@ -2317,7 +2868,7 @@ var init_disk_tier = __esm({
2317
2868
  purged++;
2318
2869
  continue;
2319
2870
  }
2320
- const payload = (0, import_msgpackr2.unpack)(dec);
2871
+ const payload = this.codec.decode(dec);
2321
2872
  if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
2322
2873
  import_fs2.default.unlinkSync(filePath);
2323
2874
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
@@ -2356,13 +2907,141 @@ var init_disk_tier = __esm({
2356
2907
  }
2357
2908
  return cleared;
2358
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
+ }
2359
3028
  get stats() {
2360
3029
  if (this._db) {
2361
3030
  const row = this._stmtStats.get();
2362
3031
  this.fileCount = row.cnt;
2363
3032
  this.diskUsageBytes = row.bytes;
2364
3033
  }
2365
- 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;
2366
3045
  }
2367
3046
  /** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
2368
3047
  get indexMode() {
@@ -2375,72 +3054,683 @@ var init_disk_tier = __esm({
2375
3054
  this._db.close();
2376
3055
  } catch {
2377
3056
  }
2378
- 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;
2379
3058
  }
2380
3059
  }
2381
3060
  };
2382
3061
  }
2383
3062
  });
2384
3063
 
2385
- // src/cache-service.ts
2386
- var cache_service_exports = {};
2387
- __export(cache_service_exports, {
2388
- CacheService: () => CacheService
2389
- });
2390
- function getGlobRegex(pattern) {
2391
- let re = globRegexCache.get(pattern);
2392
- if (re) {
2393
- globRegexCache.delete(pattern);
2394
- globRegexCache.set(pattern, re);
2395
- return re;
2396
- }
2397
- const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*+/g, ".*");
2398
- re = new RegExp("^" + escaped + "$");
2399
- if (globRegexCache.size >= GLOB_REGEX_CACHE_MAX) {
2400
- const oldestKey = globRegexCache.keys().next().value;
2401
- if (oldestKey !== void 0) globRegexCache.delete(oldestKey);
2402
- }
2403
- globRegexCache.set(pattern, re);
2404
- return re;
2405
- }
2406
- function deepFreeze(obj) {
2407
- if (obj === null || typeof obj !== "object" || Object.isFrozen(obj)) return obj;
2408
- Object.freeze(obj);
2409
- for (const v of Object.values(obj)) deepFreeze(v);
2410
- return obj;
2411
- }
2412
- function inferPriority(cacheKey) {
2413
- if (cacheKey.includes("auth:") || cacheKey.includes("session:")) return 4 /* CRITICAL */;
2414
- if (cacheKey.includes("user:") || cacheKey.includes("org:") || cacheKey.includes("profile:")) return 3 /* HIGH */;
2415
- if (cacheKey.includes("analytics:") || cacheKey.includes("report:") || cacheKey.includes("stats:")) return 1 /* LOW */;
2416
- return 2 /* NORMAL */;
2417
- }
2418
- function detectServerlessRuntime() {
2419
- if (process.env["AWS_LAMBDA_FUNCTION_NAME"]) return "AWS Lambda";
2420
- if (process.env["K_SERVICE"]) return "Google Cloud Run";
2421
- if (process.env["FUNCTION_TARGET"]) return "Google Cloud Functions";
2422
- if (process.env["WEBSITE_INSTANCE_ID"]) return "Azure Functions";
2423
- if (process.env["FLY_APP_NAME"]) return "Fly.io";
2424
- if (process.env["RAILWAY_ENVIRONMENT"]) return "Railway";
2425
- if (process.env["VERCEL"]) return "Vercel";
2426
- return null;
2427
- }
2428
- 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, 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, CacheService;
2429
- var init_cache_service = __esm({
2430
- "src/cache-service.ts"() {
3064
+ // src/latency-watchdog.ts
3065
+ var TierLatencyWatchdog;
3066
+ var init_latency_watchdog = __esm({
3067
+ "src/latency-watchdog.ts"() {
2431
3068
  "use strict";
2432
- import_ioredis = require("ioredis");
2433
- import_msgpackr3 = require("msgpackr");
2434
- import_crypto3 = __toESM(require("crypto"), 1);
2435
- import_os2 = __toESM(require("os"), 1);
2436
- init_worker_pool();
2437
- import_node_v8 = __toESM(require("v8"), 1);
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 */;
3684
+ return 2 /* NORMAL */;
3685
+ }
3686
+ function detectServerlessRuntime() {
3687
+ if (process.env["AWS_LAMBDA_FUNCTION_NAME"]) return "AWS Lambda";
3688
+ if (process.env["K_SERVICE"]) return "Google Cloud Run";
3689
+ if (process.env["FUNCTION_TARGET"]) return "Google Cloud Functions";
3690
+ if (process.env["WEBSITE_INSTANCE_ID"]) return "Azure Functions";
3691
+ if (process.env["FLY_APP_NAME"]) return "Fly.io";
3692
+ if (process.env["RAILWAY_ENVIRONMENT"]) return "Railway";
3693
+ if (process.env["VERCEL"]) return "Vercel";
3694
+ return null;
3695
+ }
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_crypto3, 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;
3715
+ var init_cache_service = __esm({
3716
+ "src/cache-service.ts"() {
3717
+ "use strict";
3718
+ import_ioredis = require("ioredis");
3719
+ init_codec();
3720
+ import_crypto3 = __toESM(require("crypto"), 1);
3721
+ import_os3 = __toESM(require("os"), 1);
3722
+ init_worker_pool();
3723
+ import_node_v82 = __toESM(require("v8"), 1);
2438
3724
  import_fs3 = __toESM(require("fs"), 1);
2439
3725
  import_path3 = __toESM(require("path"), 1);
2440
3726
  init_types();
2441
3727
  init_encryption();
2442
3728
  init_smart_memory_cache();
2443
3729
  init_disk_tier();
3730
+ init_latency_watchdog();
3731
+ init_cgroup();
3732
+ init_auto_pipeliner();
3733
+ init_ipc_telemetry();
2444
3734
  init_compression();
2445
3735
  LUA_COMPARE_AND_DELETE = `
2446
3736
  local currentTs = redis.call('HGET', KEYS[1], 't')
@@ -2469,7 +3759,7 @@ return 0
2469
3759
  cooldownMs;
2470
3760
  state = 0 /* CLOSED */;
2471
3761
  failures = 0;
2472
- openedAt = 0;
3762
+ openedAt = performance.now();
2473
3763
  /** True while the single permitted HALF_OPEN probe is in flight. */
2474
3764
  probing = false;
2475
3765
  /**
@@ -2485,7 +3775,8 @@ return 0
2485
3775
  this.probing = true;
2486
3776
  return true;
2487
3777
  }
2488
- if (Date.now() - this.openedAt >= this.cooldownMs) {
3778
+ const now = this.openedAt > 1e12 ? Date.now() : performance.now();
3779
+ if (now - this.openedAt >= this.cooldownMs) {
2489
3780
  this.state = 2 /* HALF_OPEN */;
2490
3781
  this.probing = true;
2491
3782
  return true;
@@ -2504,7 +3795,7 @@ return 0
2504
3795
  this.probing = false;
2505
3796
  if (this.state === 2 /* HALF_OPEN */ || this.failures >= this.threshold) {
2506
3797
  this.state = 1 /* OPEN */;
2507
- this.openedAt = Date.now();
3798
+ this.openedAt = performance.now();
2508
3799
  this.failures = 0;
2509
3800
  }
2510
3801
  }
@@ -2599,9 +3890,68 @@ return 0
2599
3890
  }
2600
3891
  };
2601
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
+ };
2602
3951
  CacheService = class _CacheService {
2603
3952
  logger;
2604
3953
  enc;
3954
+ codec;
2605
3955
  l1;
2606
3956
  disk;
2607
3957
  /** When true, all disk-tier and snapshot operations are skipped. */
@@ -2613,6 +3963,8 @@ return 0
2613
3963
  _namespace;
2614
3964
  /** Pre-computed once — disableRedis and redisHost never change after construction. */
2615
3965
  _redisDisabled;
3966
+ watchdog;
3967
+ pipeliner = null;
2616
3968
  inflight = /* @__PURE__ */ new Map();
2617
3969
  revalidating = /* @__PURE__ */ new Set();
2618
3970
  _l1Counters = /* @__PURE__ */ new Map();
@@ -2638,6 +3990,7 @@ return 0
2638
3990
  diskJanitorInterval = null;
2639
3991
  oomInterval = null;
2640
3992
  metricsInterval = null;
3993
+ remoteSnapshotInterval = null;
2641
3994
  _shutdownHandler = null;
2642
3995
  latencyTracker = null;
2643
3996
  instanceId;
@@ -2647,8 +4000,11 @@ return 0
2647
4000
  streamClient = null;
2648
4001
  _lastStreamId = "$";
2649
4002
  _destroyed = false;
4003
+ _ipcServer;
2650
4004
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
2651
4005
  _subDisconnectedAt = null;
4006
+ /** Deduplication ring buffer for incoming and outgoing cross-region invalidations (loop prevention) */
4007
+ _seenCrossRegionEvents = /* @__PURE__ */ new Map();
2652
4008
  counters = {
2653
4009
  gets: 0,
2654
4010
  l1Hits: 0,
@@ -2673,7 +4029,16 @@ return 0
2673
4029
  singletonDivergences: 0,
2674
4030
  startedAt: Date.now(),
2675
4031
  bloomChecks: 0,
2676
- 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
2677
4042
  };
2678
4043
  /** One-time guard so the in-process increment() fallback warning fires only once. */
2679
4044
  _incrementFallbackWarned = false;
@@ -2696,16 +4061,14 @@ return 0
2696
4061
  this.opts = {
2697
4062
  namespace: ns,
2698
4063
  logger,
2699
- l1MaxBytes: options.l1MaxBytes ?? 200 * 1024 * 1024,
4064
+ l1MaxBytes: options.l1MaxBytes ?? resolveAutonomousL1MaxBytes(),
2700
4065
  l1MaxEntries: options.l1MaxEntries ?? 2e3,
2701
4066
  categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...options.categoryLimits },
2702
4067
  forbiddenSnapshotPrefixes: forbiddenPrefixes,
2703
4068
  // Namespace-isolated defaults: separate dir / snapshot per namespace so
2704
4069
  // two instances with different namespaces never share cache files.
2705
- diskCacheDir: options.diskCacheDir ?? import_path3.default.join(
2706
- import_os2.default.tmpdir(),
2707
- ns ? `tricache-disk-${ns}` : "tricache-disk"
2708
- ),
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,
2709
4072
  diskMaxBytes: options.diskMaxBytes ?? 500 * 1024 * 1024,
2710
4073
  diskEntryMaxBytes: options.diskEntryMaxBytes ?? 10 * 1024 * 1024,
2711
4074
  redisHost: options.redisHost ?? process.env.REDIS_HOST ?? "",
@@ -2713,14 +4076,14 @@ return 0
2713
4076
  redisTls: options.redisTls ?? process.env.NODE_ENV === "production",
2714
4077
  disableRedis: options.disableRedis ?? (() => {
2715
4078
  const explicitConfig = Boolean(
2716
- options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
4079
+ options.redisClient || options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
2717
4080
  );
2718
4081
  return !explicitConfig && process.env.NODE_ENV !== "production";
2719
4082
  })(),
2720
4083
  encryptionKey: encKeyRaw,
2721
4084
  encryptionMode: options.encryptionMode,
2722
4085
  snapshotPath: options.snapshotPath ?? import_path3.default.join(
2723
- import_os2.default.tmpdir(),
4086
+ import_os3.default.tmpdir(),
2724
4087
  ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
2725
4088
  ),
2726
4089
  snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
@@ -2768,8 +4131,35 @@ return 0
2768
4131
  backplaneMode: options.backplaneMode ?? "pubsub",
2769
4132
  backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
2770
4133
  backplaneStreamBlockMs: options.backplaneStreamBlockMs ?? 2e3,
2771
- 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
2772
4157
  };
4158
+ this.codec = new CacheCodec({
4159
+ useToJSON: this.opts.serializeToJSON,
4160
+ useRecords: true,
4161
+ moreTypes: true
4162
+ });
2773
4163
  const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
2774
4164
  const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
2775
4165
  this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
@@ -2800,15 +4190,33 @@ return 0
2800
4190
  encryption: this.enc.isEnabled ? this.enc : null,
2801
4191
  compression: this.opts.compression,
2802
4192
  compressionThresholdBytes: this.opts.compressionThresholdBytes,
2803
- 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
2804
4200
  });
2805
4201
  this._namespace = ns;
2806
- 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
+ });
2807
4213
  this.l1 = new SmartMemoryCache({
2808
4214
  maxBytes: this.opts.l1MaxBytes,
2809
4215
  maxEntries: this.opts.l1MaxEntries,
2810
4216
  categories: this.opts.categoryLimits,
2811
4217
  evictionWatermark: this.opts.l1EvictionWatermark,
4218
+ admissionPolicy: this.opts.l1AdmissionPolicy,
4219
+ codec: this.codec,
2812
4220
  diskSpill: (key, entry) => {
2813
4221
  if (this._diskDisabled) return;
2814
4222
  setImmediate(() => {
@@ -2823,10 +4231,9 @@ return 0
2823
4231
  if (!this._diskDisabled) this.loadSnapshot();
2824
4232
  }
2825
4233
  this._shutdownHandler = () => {
2826
- if (!this._diskDisabled) this.writeSnapshot();
4234
+ this._triggerShutdown();
2827
4235
  };
2828
- process.once("SIGTERM", this._shutdownHandler);
2829
- process.once("SIGINT", this._shutdownHandler);
4236
+ ProcessTerminationBus.register(this);
2830
4237
  if (this.opts.workerThreads) {
2831
4238
  try {
2832
4239
  const encRef = this.enc.toWorkerInit();
@@ -2866,7 +4273,7 @@ return 0
2866
4273
  }
2867
4274
  if (this.opts.oomProtection) {
2868
4275
  this.oomInterval = setInterval(() => {
2869
- const heap = import_node_v8.default.getHeapStatistics();
4276
+ const heap = import_node_v82.default.getHeapStatistics();
2870
4277
  const used = heap.used_heap_size / heap.heap_size_limit;
2871
4278
  if (used >= this.opts.oomHeapThreshold) {
2872
4279
  const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
@@ -2890,12 +4297,25 @@ return 0
2890
4297
  }, this.opts.metricsIntervalMs);
2891
4298
  if (this.metricsInterval.unref) this.metricsInterval.unref();
2892
4299
  }
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
+ }
2893
4306
  this.instanceId = import_crypto3.default.randomBytes(8).toString("hex");
2894
4307
  this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
2895
4308
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
2896
4309
  this.initBackplane();
4310
+ const startupPromises = [];
4311
+ if (this.opts.remoteSnapshot) {
4312
+ startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
4313
+ }
2897
4314
  if (this.opts.warmKeys) {
2898
- 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);
2899
4319
  }
2900
4320
  if (this.opts.meter) {
2901
4321
  this._initOtelMetrics(this.opts.meter);
@@ -2916,8 +4336,71 @@ return 0
2916
4336
  }
2917
4337
  });
2918
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);
2919
4403
  }
2920
- // ── Singleton factory ─────────────────────────────────────────────────────
2921
4404
  /**
2922
4405
  * Get (or create) the process-level singleton CacheService instance.
2923
4406
  *
@@ -3011,7 +4494,9 @@ return 0
3011
4494
  frozen: o.frozen,
3012
4495
  adaptiveTtl: o.adaptiveTtl,
3013
4496
  invalidationBackplane: o.invalidationBackplane,
3014
- strictSingleton: o.strictSingleton
4497
+ strictSingleton: o.strictSingleton,
4498
+ remoteSnapshot: o.remoteSnapshot,
4499
+ crossRegion: o.crossRegion
3015
4500
  };
3016
4501
  }
3017
4502
  /**
@@ -3070,15 +4555,30 @@ return 0
3070
4555
  setStatus() {
3071
4556
  return this;
3072
4557
  },
4558
+ recordException() {
4559
+ return this;
4560
+ },
3073
4561
  end() {
3074
4562
  }
3075
4563
  };
3076
4564
  /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
3077
- _startSpan(name) {
3078
- 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
+ }
3079
4573
  return _CacheService._nullSpan;
3080
4574
  }
3081
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
+ }
3082
4582
  if (this.opts.redisClusterNodes?.length) {
3083
4583
  return new import_ioredis.Cluster(this.opts.redisClusterNodes, {
3084
4584
  redisOptions: {
@@ -3312,7 +4812,13 @@ return 0
3312
4812
  this.logger.warn("Backplane: malformed message JSON parse failed");
3313
4813
  }
3314
4814
  }
3315
- 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
+ }
3316
4822
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
3317
4823
  try {
3318
4824
  const client = await this.getRedis();
@@ -3354,7 +4860,80 @@ return 0
3354
4860
  } catch {
3355
4861
  }
3356
4862
  }
3357
- _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_crypto3.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()) {
3358
4937
  const existing = this.tagVersions.get(tag)?.version ?? 0;
3359
4938
  const finalVersion = Math.max(existing, version);
3360
4939
  if (this.tagVersions.size >= 1e4 && !this.tagVersions.has(tag)) {
@@ -3364,7 +4943,7 @@ return 0
3364
4943
  this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
3365
4944
  }
3366
4945
  async _getTagVersion(tag) {
3367
- const now = Date.now();
4946
+ const now = performance.now();
3368
4947
  const local = this.tagVersions.get(tag);
3369
4948
  if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
3370
4949
  return local.version;
@@ -3450,13 +5029,25 @@ return 0
3450
5029
  stream.on("error", reject);
3451
5030
  })
3452
5031
  ));
3453
- } else {
5032
+ } else if (typeof client.scanStream === "function") {
3454
5033
  await new Promise((resolve, reject) => {
3455
5034
  const stream = client.scanStream({ match: pattern, count: 100 });
3456
5035
  stream.on("data", (chunk) => keys.push(...chunk));
3457
5036
  stream.on("end", resolve);
3458
5037
  stream.on("error", reject);
3459
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");
3460
5051
  }
3461
5052
  return keys;
3462
5053
  }
@@ -3473,6 +5064,19 @@ return 0
3473
5064
  if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
3474
5065
  if (this.redis) return this.redis;
3475
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
+ }
3476
5080
  this.redisConnecting = (async () => {
3477
5081
  try {
3478
5082
  let client;
@@ -3481,6 +5085,7 @@ return 0
3481
5085
  redisOptions: {
3482
5086
  tls: this.opts.redisTls ? {} : void 0,
3483
5087
  connectTimeout: 1e4,
5088
+ commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
3484
5089
  maxRetriesPerRequest: 3,
3485
5090
  keepAlive: 3e4,
3486
5091
  ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
@@ -3501,6 +5106,7 @@ return 0
3501
5106
  name: this.opts.redisSentinel.name,
3502
5107
  tls: this.opts.redisTls ? {} : void 0,
3503
5108
  connectTimeout: 1e4,
5109
+ commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
3504
5110
  lazyConnect: false,
3505
5111
  maxRetriesPerRequest: 3,
3506
5112
  enableAutoPipelining: true,
@@ -3520,6 +5126,7 @@ return 0
3520
5126
  port: this.opts.redisPort,
3521
5127
  tls: this.opts.redisTls ? {} : void 0,
3522
5128
  connectTimeout: 1e4,
5129
+ commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
3523
5130
  lazyConnect: false,
3524
5131
  maxRetriesPerRequest: 3,
3525
5132
  enableAutoPipelining: true,
@@ -3545,6 +5152,10 @@ return 0
3545
5152
  });
3546
5153
  this.cb.onSuccess();
3547
5154
  this.redis = client;
5155
+ this.pipeliner = new AutoPipeliner(client, {
5156
+ enabled: this.opts.autoPipeline,
5157
+ maxBatchSize: this.opts.maxPipelineBatchSize
5158
+ });
3548
5159
  this.redisConnecting = null;
3549
5160
  return client;
3550
5161
  } catch (err) {
@@ -3557,12 +5168,18 @@ return 0
3557
5168
  return this.redisConnecting;
3558
5169
  }
3559
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
+ */
3560
5177
  writeSnapshot(altPath) {
3561
5178
  try {
3562
5179
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
3563
5180
  if (entries.length === 0) return;
3564
5181
  const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
3565
- const packed = (0, import_msgpackr3.pack)(payload);
5182
+ const packed = this.codec.encode(payload);
3566
5183
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
3567
5184
  const dest = altPath ?? this.opts.snapshotPath;
3568
5185
  import_fs3.default.mkdirSync(import_path3.default.dirname(dest), { recursive: true });
@@ -3577,6 +5194,12 @@ return 0
3577
5194
  this.logger.warn("Cache snapshot write failed", { error: err.message });
3578
5195
  }
3579
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
+ */
3580
5203
  loadSnapshot() {
3581
5204
  const snapshotPath = this.opts.snapshotPath;
3582
5205
  try {
@@ -3596,13 +5219,25 @@ return 0
3596
5219
  this.logger.warn("Snapshot rejected: decryption failed", { error: e.message });
3597
5220
  return;
3598
5221
  }
3599
- const snapshot = (0, import_msgpackr3.unpack)(buf);
5222
+ const snapshot = this.codec.decode(buf);
3600
5223
  if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
3601
5224
  this.logger.warn("Snapshot rejected: version mismatch", { got: snapshot?.version });
3602
5225
  return;
3603
5226
  }
3604
- const ageMs = Date.now() - (snapshot.writtenAt ?? 0);
3605
- 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) {
3606
5241
  this.logger.warn("Snapshot rejected: too old", { ageMinutes: Math.round(ageMs / 6e4) });
3607
5242
  return;
3608
5243
  }
@@ -3624,6 +5259,115 @@ return 0
3624
5259
  }
3625
5260
  }
3626
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
+ }
3627
5371
  // ── Core get (L1 → L1.5 → L2 → fetch) ───────────────────────────────────
3628
5372
  /**
3629
5373
  * Get a value from cache, or fetch and cache it.
@@ -3659,9 +5403,10 @@ return 0
3659
5403
  if (l1Hit !== null) {
3660
5404
  let isGenerationalStale = false;
3661
5405
  if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
3662
- for (const [tag, entryVer] of Object.entries(l1Hit.tagVersions)) {
3663
- const currentVer = await this._getTagVersion(tag);
3664
- 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]]) {
3665
5410
  isGenerationalStale = true;
3666
5411
  break;
3667
5412
  }
@@ -3706,116 +5451,140 @@ return 0
3706
5451
  this.counters.l1Hits++;
3707
5452
  this.opts.onHit?.(cacheKey, "l1");
3708
5453
  if (this.opts.frozen) deepFreeze(l1Hit.value);
3709
- span.setAttribute("cache.hit", "l1").end();
5454
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "memory").setAttribute("cache.hit_tier", "l1").end();
3710
5455
  return this.opts.cloneStrategy === "structuredClone" && l1Hit.value != null && typeof l1Hit.value === "object" ? structuredClone(l1Hit.value) : l1Hit.value;
3711
5456
  }
3712
5457
  }
3713
5458
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
3714
5459
  const swrGraceMs = optSwr * 1e3;
3715
5460
  const priority = optPriority ?? inferPriority(cacheKey);
3716
- 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 () => {
3717
5469
  try {
3718
- const client = await this.getRedis();
3719
- if (this.opts.tagStrategy === "generational") {
3720
- const hashData = await client.hgetall(k);
3721
- this.cb.onSuccess();
3722
- if (hashData && hashData.d) {
3723
- let isStale = false;
3724
- let storedTagVersions = {};
3725
- if (hashData.tv) {
3726
- try {
3727
- storedTagVersions = JSON.parse(hashData.tv);
3728
- } 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
+ }
3729
5489
  }
3730
- }
3731
- for (const [tag, entryVer] of Object.entries(storedTagVersions)) {
3732
- const currentVer = await this._getTagVersion(tag);
3733
- if (currentVer > entryVer) {
3734
- isStale = true;
3735
- 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
+ }
3736
5508
  }
3737
5509
  }
3738
- if (isStale) {
3739
- const setAtMs = parseInt(hashData.t, 10) || 0;
3740
- this._deleteIfStale(k, setAtMs);
3741
- } else {
3742
- const parsed = await this._decryptAndDeserialize(hashData.d);
3743
- this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
3744
- this.counters.l2Hits++;
3745
- this.opts.onHit?.(cacheKey, "l2");
3746
- this.logger.debug("L2 hit (Redis hash)", { cacheKey });
3747
- span.setAttribute("cache.hit", "l2").end();
3748
- if (this.opts.frozen) deepFreeze(parsed);
3749
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
3750
- }
3751
- }
3752
- } else {
3753
- const raw = await client.get(k);
3754
- this.cb.onSuccess();
3755
- if (raw) {
3756
- const parsed = await this._decryptAndDeserialize(raw);
3757
- this.l1.set(k, parsed, ttlMs, priority);
3758
- this.counters.l2Hits++;
3759
- this.opts.onHit?.(cacheKey, "l2");
3760
- this.logger.debug("L2 hit (Redis)", { cacheKey });
3761
- span.setAttribute("cache.hit", "l2").end();
3762
- if (this.opts.frozen) deepFreeze(parsed);
3763
- return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
3764
5510
  }
3765
5511
  }
3766
- } catch (err) {
3767
- this.cb.onFailure();
3768
- this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
3769
- }
3770
- }
3771
- if (!this._diskDisabled) {
3772
- const diskHit = this.disk.load(k);
3773
- if (diskHit !== null) {
3774
- let isDiskStale = false;
3775
- if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
3776
- for (const [tag, entryVer] of Object.entries(diskHit.tagVersions)) {
3777
- const currentVer = await this._getTagVersion(tag);
3778
- if (currentVer > entryVer) {
3779
- isDiskStale = true;
3780
- break;
3781
- }
3782
- }
3783
- }
3784
- if (isDiskStale) {
3785
- this.disk.delete(k);
3786
- } else {
3787
- const promoted = this.l1.importEntries(
3788
- [{ key: k, entry: diskHit }],
3789
- this.opts.forbiddenSnapshotPrefixes
3790
- );
3791
- if (promoted > 0) {
3792
- const l1Check = this.l1.get(k);
3793
- if (l1Check !== null) {
3794
- this.counters.diskHits++;
3795
- this.opts.onHit?.(cacheKey, "disk");
3796
- this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
3797
- span.setAttribute("cache.hit", "disk").end();
3798
- if (this.opts.frozen) deepFreeze(l1Check.value);
3799
- 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
+ }
3800
5567
  }
5568
+ } catch (err) {
5569
+ this.cb.onFailure();
5570
+ this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
3801
5571
  }
3802
5572
  }
3803
- }
3804
- }
3805
- span.setAttribute("cache.hit", "miss");
3806
- this.opts.onMiss?.(cacheKey);
3807
- const existing = this.inflight.get(k);
3808
- if (existing) {
3809
- this.counters.stampedes++;
3810
- this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch", { cacheKey });
3811
- span.end();
3812
- return existing;
3813
- }
3814
- const fetchPromise = (async () => {
3815
- try {
5573
+ span.setAttribute("cache.hit", false).setAttribute("cache.hit_tier", "miss");
5574
+ this.opts.onMiss?.(cacheKey);
3816
5575
  this.counters.fetches++;
3817
5576
  const fetchStart = Date.now();
3818
- 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
+ }
3819
5588
  const delta = Date.now() - fetchStart;
3820
5589
  const notFoundTtlMs = (optNotFoundTtl ?? this.opts.notFoundTtl) * 1e3;
3821
5590
  let effectiveTtl = data == null && notFoundTtlMs > 0 ? notFoundTtlMs : ttlMs;
@@ -3835,9 +5604,10 @@ return 0
3835
5604
  let activeTagVersions;
3836
5605
  if (optTags?.length) {
3837
5606
  if (this.opts.tagStrategy === "generational") {
5607
+ const vers = await Promise.all(optTags.map((tag) => this._getTagVersion(tag)));
3838
5608
  activeTagVersions = {};
3839
- for (const tag of optTags) {
3840
- activeTagVersions[tag] = await this._getTagVersion(tag);
5609
+ for (let i = 0; i < optTags.length; i++) {
5610
+ activeTagVersions[optTags[i]] = vers[i];
3841
5611
  }
3842
5612
  } else {
3843
5613
  await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
@@ -3879,8 +5649,64 @@ return 0
3879
5649
  span.end();
3880
5650
  }
3881
5651
  })();
3882
- this.inflight.set(k, fetchPromise);
3883
- 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
+ }
3884
5710
  }
3885
5711
  /**
3886
5712
  * Universal fetch-and-cache wrapper with an ergonomic options object.
@@ -3913,9 +5739,11 @@ return 0
3913
5739
  let activeTagVersions;
3914
5740
  const l1Existing = this.l1.get(cacheKey);
3915
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)));
3916
5744
  activeTagVersions = {};
3917
- for (const tag of Object.keys(l1Existing.tagVersions)) {
3918
- activeTagVersions[tag] = await this._getTagVersion(tag);
5745
+ for (let i = 0; i < tags.length; i++) {
5746
+ activeTagVersions[tags[i]] = vers[i];
3919
5747
  }
3920
5748
  }
3921
5749
  this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
@@ -3961,62 +5789,77 @@ return 0
3961
5789
  /** Explicitly write a value into L1 (+ L2 in production). */
3962
5790
  async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
3963
5791
  const span = this._startSpan("tricache.set");
3964
- if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
3965
- const effectiveTtlSeconds = ttlSeconds > 0 ? ttlSeconds : ttlSeconds === 0 ? INDEFINITE_TTL_SECONDS : ttlSeconds;
3966
- const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
3967
- const p = priority ?? inferPriority(cacheKey);
3968
- const k = this.nk(cacheKey);
3969
- this.counters.sets++;
3970
- let activeTagVersions;
3971
- if (opts?.tags?.length) {
3972
- if (this.opts.tagStrategy === "generational") {
3973
- activeTagVersions = {};
3974
- for (const tag of opts.tags) {
3975
- 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);
3976
5812
  }
3977
- } else {
3978
- await this._registerTags(k, opts.tags, ttlSeconds);
3979
5813
  }
3980
- }
3981
- this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
3982
- if (opts?.dependsOn?.length) {
3983
- for (const pattern of opts.dependsOn) {
3984
- const nsPattern = this.nk(pattern);
3985
- let deps = this.dependencyIndex.get(nsPattern);
3986
- if (!deps) {
3987
- deps = /* @__PURE__ */ new Set();
3988
- 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);
3989
5824
  }
3990
- deps.add(k);
3991
5825
  }
3992
- }
3993
- if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
3994
- try {
3995
- const client = await this.getRedis();
3996
- const s = JSON.stringify(data);
3997
- const stored = await this._serializeAndEncrypt(s);
3998
- const ttlSec = Math.ceil(ttlMs / 1e3);
3999
- if (this.opts.tagStrategy === "generational" && activeTagVersions) {
4000
- const now = Date.now();
4001
- const tx = client.multi();
4002
- tx.hset(k, {
4003
- d: stored,
4004
- t: String(now),
4005
- tv: JSON.stringify(activeTagVersions)
4006
- });
4007
- tx.expire(k, ttlSec);
4008
- await tx.exec();
4009
- } else {
4010
- 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 });
4011
5853
  }
4012
- this.cb.onSuccess();
4013
- } catch (err) {
4014
- this.cb.onFailure();
4015
- this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
4016
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();
4017
5862
  }
4018
- void this.publishInvalidation("del", k);
4019
- span.end();
4020
5863
  }
4021
5864
  /**
4022
5865
  * Register tags for a cache key in the in-process index and (if Redis is enabled) in
@@ -4058,36 +5901,47 @@ return 0
4058
5901
  async delete(cacheKey) {
4059
5902
  const span = this._startSpan("tricache.delete");
4060
5903
  if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
4061
- const isPattern = cacheKey.includes("*");
4062
- const k = this.nk(cacheKey);
4063
- this.counters.deletes++;
4064
- if (isPattern) {
4065
- this.l1.deletePattern(k);
4066
- } else {
4067
- this.l1.delete(k);
4068
- setImmediate(() => {
4069
- if (!this._diskDisabled) this.disk.delete(k);
4070
- });
4071
- this._cascadeDependencies(k);
4072
- for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
4073
- }
4074
- if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
4075
- try {
4076
- const client = await this.getRedis();
4077
- if (isPattern) {
4078
- const keys = await this._scanKeys(client, k);
4079
- if (keys.length > 0) await client.del(...keys);
4080
- } else {
4081
- 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 });
4082
5935
  }
4083
- this.cb.onSuccess();
4084
- } catch (err) {
4085
- this.cb.onFailure();
4086
- this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
4087
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();
4088
5944
  }
4089
- void this.publishInvalidation(isPattern ? "del-glob" : "del", k);
4090
- span.end();
4091
5945
  }
4092
5946
  // ── Counter (distributed rate limiting) ──────────────────────────────────
4093
5947
  /**
@@ -4148,31 +6002,44 @@ return 0
4148
6002
  * await cache.clear('user:abc'); // flush all keys for one user
4149
6003
  */
4150
6004
  async clear(prefix) {
4151
- this.counters.deletes++;
4152
- const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
4153
- if (k) {
4154
- this.l1.deletePattern(k);
4155
- } else {
4156
- this.l1.clear();
4157
- if (!this._diskDisabled) this.disk.clear();
4158
- this._l1Counters.clear();
4159
- this.tagIndex.clear();
4160
- this.tagVersions.clear();
4161
- }
4162
- if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
4163
- try {
4164
- const client = await this.getRedis();
4165
- const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
4166
- const keys = await this._scanKeys(client, pattern);
4167
- if (keys.length > 0) await client.del(...keys);
4168
- } catch (err) {
4169
- 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
+ }
4170
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();
4171
6042
  }
4172
- void this.publishInvalidation(
4173
- "del-glob",
4174
- k ?? (this._namespace ? `${this._namespace}:*` : "*")
4175
- );
4176
6043
  }
4177
6044
  /**
4178
6045
  * Evict L1 entries that violate the current category or global capacity limits.
@@ -4303,7 +6170,7 @@ return 0
4303
6170
  const now = Date.now();
4304
6171
  if (entry.expiresAt <= now) return null;
4305
6172
  if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
4306
- 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);
4307
6174
  }
4308
6175
  /**
4309
6176
  * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
@@ -4323,8 +6190,12 @@ return 0
4323
6190
  if (this.opts.frozen) deepFreeze(val);
4324
6191
  return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
4325
6192
  }
4326
- if (!this._diskDisabled) {
6193
+ if (!this._diskDisabled && this.watchdog.isDiskAllowed()) {
6194
+ const diskStart = performance.now();
4327
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);
4328
6199
  if (diskHit !== null) {
4329
6200
  const promoted = this.l1.importEntries(
4330
6201
  [{ key: k, entry: diskHit }],
@@ -4345,7 +6216,10 @@ return 0
4345
6216
  if (!this._redisDisabled && !this.cb.isOpen) {
4346
6217
  try {
4347
6218
  const client = await this.getRedis();
6219
+ const redisStart = performance.now();
4348
6220
  const raw = await client.get(k);
6221
+ const redisElapsed = performance.now() - redisStart;
6222
+ this.watchdog.recordRedis(redisElapsed);
4349
6223
  if (raw !== null) {
4350
6224
  const parsed = await this._decryptAndDeserialize(raw);
4351
6225
  this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
@@ -4372,90 +6246,129 @@ return 0
4372
6246
  * `(key) => number` so heterogeneous TTLs can be batched in one call.
4373
6247
  */
4374
6248
  async mget(keys, fetchFn, ttl = 300, priority) {
4375
- const result = Array.from({ length: keys.length });
4376
- const missIndexes = [];
4377
- const missKeys = [];
4378
- for (let i = 0; i < keys.length; i++) {
4379
- const k = this.nk(keys[i]);
4380
- const entry = this.l1.getEntry(k);
4381
- if (entry && entry.expiresAt > Date.now()) {
4382
- result[i] = entry.value !== void 0 ? entry.value : (0, import_msgpackr3.unpack)(entry.data);
4383
- this.counters.l1Hits++;
4384
- } else {
4385
- missIndexes.push(i);
4386
- missKeys.push(keys[i]);
4387
- }
6249
+ const span = this._startSpan("tricache.mget");
6250
+ if (this.opts.tracer) {
6251
+ span.setAttribute("cache.batch.size", keys.length);
4388
6252
  }
4389
- if (missKeys.length === 0) return result;
4390
- if (!this._redisDisabled) {
4391
- try {
4392
- const client = await this.getRedis();
4393
- const nsKeys = missKeys.map((k) => this.nk(k));
4394
- const pipeline = client.multi();
4395
- for (const nk of nsKeys) pipeline.get(nk);
4396
- const raws = await pipeline.exec();
4397
- this.cb.onSuccess();
4398
- for (let j = 0; j < missKeys.length; j++) {
4399
- const raw = raws[j] ? raws[j][1] : null;
4400
- const idx = missIndexes[j];
4401
- if (raw) {
4402
- const parsed = await this._decryptAndDeserialize(raw);
4403
- const k = nsKeys[j];
4404
- const p = priority ?? inferPriority(missKeys[j]);
4405
- this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
4406
- this.counters.l2Hits++;
4407
- result[idx] = parsed;
4408
- missIndexes[j] = -1;
4409
- missKeys[j] = "";
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;
6276
+ }
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
+ }
4410
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 });
4411
6313
  }
4412
- const remainingIdx = missIndexes.filter((i) => i >= 0);
4413
- const remainingKeys = missKeys.filter((k) => k !== "");
4414
- missIndexes.length = 0;
4415
- missKeys.length = 0;
4416
- missIndexes.push(...remainingIdx);
4417
- missKeys.push(...remainingKeys);
4418
- if (missKeys.length === 0) return result;
4419
- } catch (err) {
4420
- this.cb.onFailure();
4421
- this.logger.debug("mget: Redis unavailable, continuing to disk/fetch", { error: err.message });
4422
6314
  }
4423
- }
4424
- if (!this._diskDisabled) {
4425
- for (let j = missKeys.length - 1; j >= 0; j--) {
4426
- const k = this.nk(missKeys[j]);
4427
- const diskHit = this.disk.load(k);
4428
- if (diskHit !== null) {
4429
- const promoted = this.l1.importEntries(
4430
- [{ key: k, entry: diskHit }],
4431
- this.opts.forbiddenSnapshotPrefixes
4432
- );
4433
- if (promoted > 0) {
4434
- const l1Check = this.l1.get(k);
4435
- if (l1Check !== null) {
4436
- this.counters.diskHits++;
4437
- result[missIndexes[j]] = l1Check.value;
4438
- missIndexes.splice(j, 1);
4439
- 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
+ }
4440
6337
  }
4441
6338
  }
4442
6339
  }
4443
6340
  }
4444
- if (missKeys.length === 0) return result;
4445
- }
4446
- if (missKeys.length > 0) {
4447
- this.counters.fetches++;
4448
- const fetched = await fetchFn(missKeys);
4449
- for (let j = 0; j < missKeys.length; j++) {
4450
- const v = fetched[missKeys[j]];
4451
- result[missIndexes[j]] = v;
4452
- if (v !== void 0) {
4453
- const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
4454
- 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
+ }
6352
+ }
6353
+ if (setPromises.length > 0) {
6354
+ await Promise.all(setPromises);
4455
6355
  }
4456
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);
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();
4457
6371
  }
4458
- return result;
4459
6372
  }
4460
6373
  /**
4461
6374
  * Returns a Promise that resolves once the cache is fully initialised and any
@@ -4482,12 +6395,24 @@ return 0
4482
6395
  * });
4483
6396
  */
4484
6397
  async mset(entries) {
6398
+ const span = this._startSpan("tricache.mset");
4485
6399
  const keys = Object.keys(entries);
4486
- await Promise.all(keys.map((key) => {
4487
- const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
4488
- const hasOpts = tags?.length || dependsOn?.length;
4489
- return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
4490
- }));
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
+ }
4491
6416
  }
4492
6417
  /**
4493
6418
  * Batch delete — delete multiple exact keys in a single call.
@@ -4497,7 +6422,19 @@ return 0
4497
6422
  * await cache.mdel(['user:1', 'user:2', 'user:3']);
4498
6423
  */
4499
6424
  async mdel(keys) {
4500
- 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
+ }
4501
6438
  }
4502
6439
  /**
4503
6440
  * Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
@@ -4526,7 +6463,6 @@ return 0
4526
6463
  const results = await pl.exec();
4527
6464
  this.cb.onSuccess();
4528
6465
  let loaded = 0;
4529
- const now = Date.now();
4530
6466
  for (let i = 0; i < matchedKeys.length; i++) {
4531
6467
  const [err, raw] = results[i];
4532
6468
  if (err || raw == null) continue;
@@ -4538,7 +6474,6 @@ return 0
4538
6474
  } catch {
4539
6475
  }
4540
6476
  }
4541
- void now;
4542
6477
  this.logger.info("warmFromL2 complete", {
4543
6478
  pattern,
4544
6479
  matched: matchedKeys.length,
@@ -4560,45 +6495,58 @@ return 0
4560
6495
  * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
4561
6496
  */
4562
6497
  async invalidateTag(tag) {
4563
- if (this.opts.tagStrategy === "generational") {
4564
- 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);
4565
6530
  if (!this._redisDisabled) {
4566
6531
  try {
4567
6532
  const client = await this.getRedis();
4568
- 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
+ }
4569
6540
  } catch (err) {
4570
6541
  this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
4571
- const current = this.tagVersions.get(tag)?.version ?? 0;
4572
- newVer = current + 1;
4573
- }
4574
- } else {
4575
- const current = this.tagVersions.get(tag)?.version ?? 0;
4576
- newVer = current + 1;
4577
- }
4578
- this._setLocalTagVersion(tag, newVer, Date.now());
4579
- void this.publishInvalidation("tag_incr", tag, newVer);
4580
- return;
4581
- }
4582
- const tagKey = this.nk(`_tag_:${tag}`);
4583
- const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
4584
- for (const k of members) {
4585
- this.l1.delete(k);
4586
- if (!this._diskDisabled) this.disk.delete(k);
4587
- }
4588
- this.tagIndex.delete(tagKey);
4589
- if (!this._redisDisabled) {
4590
- try {
4591
- const client = await this.getRedis();
4592
- const redisMembers = await client.smembers(tagKey);
4593
- const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
4594
- if (toDelete.length > 0) {
4595
- await client.del(...toDelete, tagKey);
4596
- } else {
4597
- await client.del(tagKey);
4598
6542
  }
4599
- } catch (err) {
4600
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
4601
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();
4602
6550
  }
4603
6551
  }
4604
6552
  /**
@@ -4631,7 +6579,7 @@ return 0
4631
6579
  const [err, newVer] = results[i] ?? [null, null];
4632
6580
  const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
4633
6581
  this._setLocalTagVersion(tags[i], ver, now);
4634
- void this.publishInvalidation("tag_incr", tags[i], ver);
6582
+ void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
4635
6583
  }
4636
6584
  return;
4637
6585
  } catch (err) {
@@ -4641,7 +6589,7 @@ return 0
4641
6589
  for (const tag of tags) {
4642
6590
  const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
4643
6591
  this._setLocalTagVersion(tag, ver, now);
4644
- void this.publishInvalidation("tag_incr", tag, ver);
6592
+ void this.publishInvalidation("tag_incr", tag, ver, false, true);
4645
6593
  }
4646
6594
  return;
4647
6595
  }
@@ -4712,6 +6660,60 @@ return 0
4712
6660
  }
4713
6661
  return { l1, disk, l2 };
4714
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
+ }
4715
6717
  /**
4716
6718
  * Export all live L1 entries to Redis via a single pipeline.
4717
6719
  * Useful for warming a new Redis instance or for zero-downtime failover.
@@ -4959,7 +6961,7 @@ return 0
4959
6961
  if (visited.has(dep)) continue;
4960
6962
  this.l1.delete(dep);
4961
6963
  if (!this._diskDisabled) this.disk.delete(dep);
4962
- void this.publishInvalidation("del", dep);
6964
+ void this.publishInvalidation("del", dep, void 0, false, true);
4963
6965
  this.logger.debug("Dependency cascade: invalidated dependent key", {
4964
6966
  trigger: deletedKey.slice(0, 60),
4965
6967
  dependent: dep.slice(0, 60)
@@ -5024,12 +7026,36 @@ return 0
5024
7026
  evictions: c.oomEvictions,
5025
7027
  lastTriggeredAt: c.oomLastAt
5026
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
+ },
5027
7049
  l1: {
5028
7050
  entries: l1s.entries,
5029
7051
  sizeBytes: this.l1.memoryUsage,
5030
7052
  maxBytes: this.opts.l1MaxBytes
5031
7053
  },
5032
- disk: { ...this.disk.stats, disabled: this._diskDisabled },
7054
+ disk: {
7055
+ ...this.disk.stats,
7056
+ disabled: this._diskDisabled,
7057
+ latencyWatchdog: this.watchdog.getTelemetry()
7058
+ },
5033
7059
  ...this.latencyTracker && {
5034
7060
  adaptiveTtl: {
5035
7061
  enabled: true,
@@ -5042,9 +7068,16 @@ return 0
5042
7068
  this.opts.adaptiveTtlMaxMs
5043
7069
  )
5044
7070
  }
7071
+ },
7072
+ ...this.pipeliner && {
7073
+ pipelining: this.pipeliner.stats
5045
7074
  }
5046
7075
  };
5047
7076
  }
7077
+ /** Return auto-pipelining metrics, or null if pipelining is disabled. */
7078
+ getPipelinerStats() {
7079
+ return this.pipeliner ? this.pipeliner.stats : null;
7080
+ }
5048
7081
  /**
5049
7082
  * Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
5050
7083
  * Paste the result into your `/metrics` endpoint.
@@ -5084,6 +7117,18 @@ return 0
5084
7117
  gauge("l1_entries", m.l1.entries, "Current L1 entry count");
5085
7118
  gauge("l1_size_bytes", m.l1.sizeBytes, "Current L1 used bytes");
5086
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
+ }
5087
7132
  gauge(
5088
7133
  "bloom_false_positive_rate",
5089
7134
  m.bloom.falsePositiveRate,
@@ -5105,6 +7150,17 @@ return 0
5105
7150
  "Emergency L1 eviction rounds triggered by heap pressure"
5106
7151
  );
5107
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
+ }
5108
7164
  return lines.join("\n");
5109
7165
  }
5110
7166
  // ── Lifecycle ────────────────────────────────────────────────────────────
@@ -5123,23 +7179,31 @@ return 0
5123
7179
  /** Close Redis connections and stop all background timers. */
5124
7180
  async destroy() {
5125
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
+ }
5126
7187
  if (this.cleanupInterval) clearInterval(this.cleanupInterval);
5127
7188
  if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
5128
7189
  if (this.oomInterval) clearInterval(this.oomInterval);
5129
7190
  if (this.metricsInterval) clearInterval(this.metricsInterval);
5130
- if (this._shutdownHandler) {
5131
- process.off("SIGTERM", this._shutdownHandler);
5132
- process.off("SIGINT", this._shutdownHandler);
5133
- this._shutdownHandler = null;
7191
+ if (this.remoteSnapshotInterval) {
7192
+ clearInterval(this.remoteSnapshotInterval);
7193
+ this.remoteSnapshotInterval = null;
5134
7194
  }
7195
+ ProcessTerminationBus.unregister(this);
7196
+ this._shutdownHandler = null;
5135
7197
  if (this._workerPool) {
5136
7198
  await this._workerPool.destroy();
5137
7199
  this._workerPool = null;
5138
7200
  }
5139
7201
  if (this.subClient) {
5140
- try {
5141
- this.subClient.disconnect();
5142
- } catch {
7202
+ if (!this.opts.redisSubClient) {
7203
+ try {
7204
+ this.subClient.disconnect();
7205
+ } catch {
7206
+ }
5143
7207
  }
5144
7208
  this.subClient = null;
5145
7209
  }
@@ -5151,14 +7215,33 @@ return 0
5151
7215
  this.streamClient = null;
5152
7216
  }
5153
7217
  if (this.redis) {
5154
- try {
5155
- await this.redis.disconnect();
5156
- } catch {
7218
+ if (!this.opts.redisClient) {
7219
+ try {
7220
+ await this.redis.disconnect();
7221
+ } catch {
7222
+ }
5157
7223
  }
5158
7224
  this.redis = null;
5159
7225
  }
7226
+ if (this._ipcServer) {
7227
+ await this._ipcServer.close();
7228
+ this._ipcServer = void 0;
7229
+ }
5160
7230
  if (!this._diskDisabled) this.disk.close();
5161
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
+ }
5162
7245
  };
5163
7246
  }
5164
7247
  });