tricache 0.7.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +89 -1371
  3. package/dashboards/prometheus-scrape.yml +18 -0
  4. package/dashboards/tricache-alerts.yaml +54 -0
  5. package/dashboards/tricache-grafana.json +548 -0
  6. package/dist/cache-service-DVvroyqA.d.ts +886 -0
  7. package/dist/cache-service-KI5ACF3F.js +12 -0
  8. package/dist/chunk-7RV5ZVBB.js +1023 -0
  9. package/dist/chunk-BQRURGGD.js +60 -0
  10. package/dist/chunk-IITRFWHY.js +196 -0
  11. package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
  12. package/dist/{chunk-EUGYR7KR.js → chunk-PL5J3ZNT.js} +3184 -514
  13. package/dist/chunk-QNU7B43J.js +687 -0
  14. package/dist/chunk-UGD4VEPD.js +138 -0
  15. package/dist/chunk-XZL45ABR.js +108 -0
  16. package/dist/cli.cjs +3122 -495
  17. package/dist/cli.d.ts +1 -0
  18. package/dist/cli.js +121 -5
  19. package/dist/dashboard/index.cjs +1065 -0
  20. package/dist/dashboard/index.d.ts +183 -0
  21. package/dist/dashboard/index.js +22 -0
  22. package/dist/drizzle/index.cjs +2846 -494
  23. package/dist/drizzle/index.d.ts +3 -1
  24. package/dist/drizzle/index.js +1 -1
  25. package/dist/edge/index.cjs +1559 -0
  26. package/dist/edge/index.d.ts +127 -0
  27. package/dist/edge/index.js +1109 -0
  28. package/dist/hono/index.cjs +7760 -0
  29. package/dist/hono/index.d.ts +91 -0
  30. package/dist/hono/index.js +185 -0
  31. package/dist/hono-VA9A1m0I.d.ts +371 -0
  32. package/dist/http/index.cjs +3281 -587
  33. package/dist/http/index.d.ts +85 -23
  34. package/dist/http/index.js +176 -78
  35. package/dist/index.cjs +7212 -2505
  36. package/dist/index.d.ts +547 -30
  37. package/dist/index.js +104 -5
  38. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  39. package/dist/nestjs/index.cjs +2787 -487
  40. package/dist/nestjs/index.d.ts +3 -1
  41. package/dist/nestjs/index.js +6 -3
  42. package/dist/next/index.cjs +2804 -501
  43. package/dist/next/index.d.ts +4 -2
  44. package/dist/next/index.js +14 -10
  45. package/dist/prisma/index.d.ts +3 -1
  46. package/dist/serialize-worker.cjs +5 -4
  47. package/dist/serialize-worker.js +1 -1
  48. package/dist/{cache-service-D8tIXmzb.d.ts → types-B_QkVwJ7.d.ts} +622 -662
  49. package/dist/utils-CEsU_Z0s.d.ts +27 -0
  50. package/package.json +48 -10
  51. package/src/adapters/auto-pipeliner.ts +206 -0
  52. package/src/adapters/node-redis.ts +370 -0
  53. package/src/cache-service.ts +1619 -415
  54. package/src/cli.ts +137 -2
  55. package/src/codec.ts +72 -0
  56. package/src/cross-region.ts +245 -0
  57. package/src/dashboard/handler.ts +392 -0
  58. package/src/dashboard/html.ts +594 -0
  59. package/src/dashboard/index.ts +195 -0
  60. package/src/dashboard/types.ts +96 -0
  61. package/src/disk-tier.ts +449 -47
  62. package/src/drizzle/index.ts +86 -86
  63. package/src/edge/adapters/cloudflare-do.ts +130 -0
  64. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  65. package/src/edge/adapters/upstash.ts +143 -0
  66. package/src/edge/cache.ts +797 -0
  67. package/src/edge/crypto.ts +182 -0
  68. package/src/edge/hono.ts +284 -0
  69. package/src/edge/index.ts +37 -0
  70. package/src/edge/types.ts +230 -0
  71. package/src/edge/utils/base64.ts +63 -0
  72. package/src/edge/utils/murmur3.ts +179 -0
  73. package/src/encryption.ts +127 -5
  74. package/src/hono/index.ts +316 -0
  75. package/src/http/express.ts +195 -0
  76. package/src/http/fastify.ts +260 -0
  77. package/src/http/index.ts +44 -258
  78. package/src/http/utils.ts +92 -0
  79. package/src/index.ts +149 -47
  80. package/src/ipc-telemetry.ts +509 -0
  81. package/src/latency-watchdog.ts +282 -0
  82. package/src/nestjs/decorators.ts +161 -161
  83. package/src/nestjs/index.ts +23 -23
  84. package/src/nestjs/tricache.module.ts +104 -104
  85. package/src/nestjs/tricache.store.ts +97 -97
  86. package/src/nestjs/types.ts +79 -79
  87. package/src/next/cache-handler.ts +12 -9
  88. package/src/next/index.ts +37 -37
  89. package/src/next/isr-handler.ts +105 -105
  90. package/src/next/types.ts +130 -130
  91. package/src/remote-snapshot.ts +153 -0
  92. package/src/serialize-worker.ts +120 -120
  93. package/src/sigv4-snapshot-adapter.ts +260 -0
  94. package/src/smart-memory-cache.ts +91 -8
  95. package/src/types.ts +315 -2
  96. package/src/utils/cgroup.ts +100 -0
  97. package/src/utils/tracing.ts +54 -0
  98. package/src/wasm/bloom-filter-wasm.ts +109 -102
  99. package/src/worker-pool.ts +299 -299
  100. package/src/wtiny-lfu.ts +624 -0
  101. package/dist/cache-service-5GATUYAK.js +0 -7
  102. 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,57 @@ return 0
2647
4000
  streamClient = null;
2648
4001
  _lastStreamId = "$";
2649
4002
  _destroyed = false;
4003
+ _pendingDiskDeletes = /* @__PURE__ */ new Set();
4004
+ _globalEpoch = 0;
4005
+ _keyMutationEpochs = /* @__PURE__ */ new Map();
4006
+ /**
4007
+ * Pattern tombstones for disk tier.
4008
+ * Files in the disk tier are keyed by SHA-256 of namespacedKey.
4009
+ * Wildcard pattern deletes cannot scan the filesystem synchronously, so we maintain
4010
+ * pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
4011
+ */
4012
+ _patternTombstones = [];
4013
+ _addPatternTombstone(prefix) {
4014
+ const now = Date.now();
4015
+ while (this._patternTombstones.length > 0 && now - this._patternTombstones[0].createdAt > 36e5) {
4016
+ this._patternTombstones.shift();
4017
+ }
4018
+ if (this._patternTombstones.length >= 2e3) {
4019
+ this._patternTombstones.shift();
4020
+ }
4021
+ this._patternTombstones.push({ prefix, createdAt: now });
4022
+ }
4023
+ _isTombstonedByPattern(namespacedKey) {
4024
+ if (this._patternTombstones.length === 0) return false;
4025
+ for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
4026
+ if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
4027
+ return true;
4028
+ }
4029
+ }
4030
+ return false;
4031
+ }
4032
+ _assertActive(operation) {
4033
+ if (this._destroyed) {
4034
+ throw new Error(`TriCacheError: Cannot perform '${operation}' on a destroyed CacheService instance (namespace: '${this._namespace || "(default)"}').`);
4035
+ }
4036
+ }
4037
+ _bumpKeyMutation(namespacedKey) {
4038
+ const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
4039
+ this._keyMutationEpochs.set(namespacedKey, next);
4040
+ if (this._keyMutationEpochs.size > 5e4) {
4041
+ const oldest = this._keyMutationEpochs.keys().next().value;
4042
+ if (oldest !== void 0) this._keyMutationEpochs.delete(oldest);
4043
+ }
4044
+ return next;
4045
+ }
4046
+ _getKeyMutationEpoch(namespacedKey) {
4047
+ return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
4048
+ }
4049
+ _ipcServer;
2650
4050
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
2651
4051
  _subDisconnectedAt = null;
4052
+ /** Deduplication ring buffer for incoming and outgoing cross-region invalidations (loop prevention) */
4053
+ _seenCrossRegionEvents = /* @__PURE__ */ new Map();
2652
4054
  counters = {
2653
4055
  gets: 0,
2654
4056
  l1Hits: 0,
@@ -2673,7 +4075,16 @@ return 0
2673
4075
  singletonDivergences: 0,
2674
4076
  startedAt: Date.now(),
2675
4077
  bloomChecks: 0,
2676
- bloomFalsePositives: 0
4078
+ bloomFalsePositives: 0,
4079
+ remoteSnapshotUploads: 0,
4080
+ remoteSnapshotDownloads: 0,
4081
+ remoteSnapshotErrors: 0,
4082
+ remoteSnapshotLastUploadedAt: null,
4083
+ remoteSnapshotLastDownloadedAt: null,
4084
+ crossRegionSent: 0,
4085
+ crossRegionReceived: 0,
4086
+ crossRegionDeduplicated: 0,
4087
+ crossRegionErrors: 0
2677
4088
  };
2678
4089
  /** One-time guard so the in-process increment() fallback warning fires only once. */
2679
4090
  _incrementFallbackWarned = false;
@@ -2696,16 +4107,14 @@ return 0
2696
4107
  this.opts = {
2697
4108
  namespace: ns,
2698
4109
  logger,
2699
- l1MaxBytes: options.l1MaxBytes ?? 200 * 1024 * 1024,
4110
+ l1MaxBytes: options.l1MaxBytes ?? resolveAutonomousL1MaxBytes(),
2700
4111
  l1MaxEntries: options.l1MaxEntries ?? 2e3,
2701
4112
  categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...options.categoryLimits },
2702
4113
  forbiddenSnapshotPrefixes: forbiddenPrefixes,
2703
4114
  // Namespace-isolated defaults: separate dir / snapshot per namespace so
2704
4115
  // 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
- ),
4116
+ // Automatically probes /dev/shm tmpfs on Linux (>=256MB capacity and >=128MB free) for off-heap RAM speed.
4117
+ diskCacheDir: options.diskCacheDir ?? resolveDefaultDiskDir(ns, logger).dir,
2709
4118
  diskMaxBytes: options.diskMaxBytes ?? 500 * 1024 * 1024,
2710
4119
  diskEntryMaxBytes: options.diskEntryMaxBytes ?? 10 * 1024 * 1024,
2711
4120
  redisHost: options.redisHost ?? process.env.REDIS_HOST ?? "",
@@ -2713,18 +4122,20 @@ return 0
2713
4122
  redisTls: options.redisTls ?? process.env.NODE_ENV === "production",
2714
4123
  disableRedis: options.disableRedis ?? (() => {
2715
4124
  const explicitConfig = Boolean(
2716
- options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
4125
+ options.redisClient || options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
2717
4126
  );
2718
4127
  return !explicitConfig && process.env.NODE_ENV !== "production";
2719
4128
  })(),
2720
4129
  encryptionKey: encKeyRaw,
2721
4130
  encryptionMode: options.encryptionMode,
2722
4131
  snapshotPath: options.snapshotPath ?? import_path3.default.join(
2723
- import_os2.default.tmpdir(),
4132
+ import_os3.default.tmpdir(),
2724
4133
  ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
2725
4134
  ),
2726
4135
  snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
2727
4136
  invalidationBackplane: options.invalidationBackplane ?? true,
4137
+ awaitInvalidationBackplane: options.awaitInvalidationBackplane ?? false,
4138
+ lockFailClosed: options.lockFailClosed ?? false,
2728
4139
  oomProtection: options.oomProtection ?? true,
2729
4140
  oomHeapThreshold: options.oomHeapThreshold ?? 0.85,
2730
4141
  oomCheckIntervalMs: options.oomCheckIntervalMs ?? 1e4,
@@ -2768,8 +4179,35 @@ return 0
2768
4179
  backplaneMode: options.backplaneMode ?? "pubsub",
2769
4180
  backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
2770
4181
  backplaneStreamBlockMs: options.backplaneStreamBlockMs ?? 2e3,
2771
- backplaneStreamKey: options.backplaneStreamKey
4182
+ backplaneStreamKey: options.backplaneStreamKey,
4183
+ serializeToJSON: options.serializeToJSON ?? true,
4184
+ remoteSnapshot: options.remoteSnapshot,
4185
+ crossRegion: options.crossRegion,
4186
+ redisClient: options.redisClient,
4187
+ redisSubClient: options.redisSubClient,
4188
+ diskMaxConcurrentWrites: options.diskMaxConcurrentWrites,
4189
+ diskMaxPendingWrites: options.diskMaxPendingWrites,
4190
+ diskWriteTimeoutMs: options.diskWriteTimeoutMs,
4191
+ diskCircuitBreakerThreshold: options.diskCircuitBreakerThreshold,
4192
+ diskCircuitBreakerCooldownMs: options.diskCircuitBreakerCooldownMs,
4193
+ redisCommandTimeoutMs: options.redisCommandTimeoutMs,
4194
+ clockSkewToleranceMs: options.clockSkewToleranceMs ?? 250,
4195
+ l1AdmissionPolicy: options.l1AdmissionPolicy,
4196
+ diskLatencyWatchdog: options.diskLatencyWatchdog ?? true,
4197
+ diskLatencyBypassRatio: options.diskLatencyBypassRatio ?? 1.5,
4198
+ diskLatencyBypassMinMs: options.diskLatencyBypassMinMs ?? 10,
4199
+ diskLatencyBypassCooldownMs: options.diskLatencyBypassCooldownMs ?? 3e4,
4200
+ failReadinessOnDegraded: options.failReadinessOnDegraded ?? false,
4201
+ autoPipeline: options.autoPipeline ?? false,
4202
+ maxPipelineBatchSize: options.maxPipelineBatchSize ?? 100,
4203
+ enableIpc: options.enableIpc ?? false,
4204
+ ipcSocketPath: options.ipcSocketPath
2772
4205
  };
4206
+ this.codec = new CacheCodec({
4207
+ useToJSON: this.opts.serializeToJSON,
4208
+ useRecords: true,
4209
+ moreTypes: true
4210
+ });
2773
4211
  const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
2774
4212
  const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
2775
4213
  this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
@@ -2800,15 +4238,33 @@ return 0
2800
4238
  encryption: this.enc.isEnabled ? this.enc : null,
2801
4239
  compression: this.opts.compression,
2802
4240
  compressionThresholdBytes: this.opts.compressionThresholdBytes,
2803
- logger
4241
+ logger,
4242
+ codec: this.codec,
4243
+ diskMaxConcurrentWrites: this.opts.diskMaxConcurrentWrites,
4244
+ diskMaxPendingWrites: this.opts.diskMaxPendingWrites,
4245
+ diskWriteTimeoutMs: this.opts.diskWriteTimeoutMs,
4246
+ diskCircuitBreakerThreshold: this.opts.diskCircuitBreakerThreshold,
4247
+ diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs
2804
4248
  });
2805
4249
  this._namespace = ns;
2806
- this._redisDisabled = this.opts.disableRedis || !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
4250
+ this._redisDisabled = this.opts.disableRedis || !this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
4251
+ this.watchdog = new TierLatencyWatchdog({
4252
+ enabled: options.diskLatencyWatchdog ?? true,
4253
+ minDiskBypassMs: options.diskLatencyBypassMinMs ?? 10,
4254
+ bypassRatio: options.diskLatencyBypassRatio ?? 1.5,
4255
+ cooldownMs: options.diskLatencyBypassCooldownMs ?? 3e4,
4256
+ redisCutoffMs: 15,
4257
+ redisRecoveryFloorMs: 10,
4258
+ minSamples: 16,
4259
+ disableRedis: this._redisDisabled
4260
+ });
2807
4261
  this.l1 = new SmartMemoryCache({
2808
4262
  maxBytes: this.opts.l1MaxBytes,
2809
4263
  maxEntries: this.opts.l1MaxEntries,
2810
4264
  categories: this.opts.categoryLimits,
2811
4265
  evictionWatermark: this.opts.l1EvictionWatermark,
4266
+ admissionPolicy: this.opts.l1AdmissionPolicy,
4267
+ codec: this.codec,
2812
4268
  diskSpill: (key, entry) => {
2813
4269
  if (this._diskDisabled) return;
2814
4270
  setImmediate(() => {
@@ -2823,10 +4279,9 @@ return 0
2823
4279
  if (!this._diskDisabled) this.loadSnapshot();
2824
4280
  }
2825
4281
  this._shutdownHandler = () => {
2826
- if (!this._diskDisabled) this.writeSnapshot();
4282
+ this._triggerShutdown();
2827
4283
  };
2828
- process.once("SIGTERM", this._shutdownHandler);
2829
- process.once("SIGINT", this._shutdownHandler);
4284
+ ProcessTerminationBus.register(this);
2830
4285
  if (this.opts.workerThreads) {
2831
4286
  try {
2832
4287
  const encRef = this.enc.toWorkerInit();
@@ -2866,7 +4321,7 @@ return 0
2866
4321
  }
2867
4322
  if (this.opts.oomProtection) {
2868
4323
  this.oomInterval = setInterval(() => {
2869
- const heap = import_node_v8.default.getHeapStatistics();
4324
+ const heap = import_node_v82.default.getHeapStatistics();
2870
4325
  const used = heap.used_heap_size / heap.heap_size_limit;
2871
4326
  if (used >= this.opts.oomHeapThreshold) {
2872
4327
  const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
@@ -2890,12 +4345,25 @@ return 0
2890
4345
  }, this.opts.metricsIntervalMs);
2891
4346
  if (this.metricsInterval.unref) this.metricsInterval.unref();
2892
4347
  }
4348
+ if (this.opts.remoteSnapshot?.intervalMs && this.opts.remoteSnapshot.intervalMs > 0) {
4349
+ this.remoteSnapshotInterval = setInterval(() => {
4350
+ void this.writeRemoteSnapshot();
4351
+ }, this.opts.remoteSnapshot.intervalMs);
4352
+ if (this.remoteSnapshotInterval.unref) this.remoteSnapshotInterval.unref();
4353
+ }
2893
4354
  this.instanceId = import_crypto3.default.randomBytes(8).toString("hex");
2894
4355
  this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
2895
4356
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
2896
4357
  this.initBackplane();
4358
+ const startupPromises = [];
4359
+ if (this.opts.remoteSnapshot) {
4360
+ startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
4361
+ }
2897
4362
  if (this.opts.warmKeys) {
2898
- this._readyPromise = this.warmFromL2(this.opts.warmKeys).then(() => void 0);
4363
+ startupPromises.push(this.warmFromL2(this.opts.warmKeys).then(() => void 0));
4364
+ }
4365
+ if (startupPromises.length > 0) {
4366
+ this._readyPromise = Promise.all(startupPromises).then(() => void 0);
2899
4367
  }
2900
4368
  if (this.opts.meter) {
2901
4369
  this._initOtelMetrics(this.opts.meter);
@@ -2916,8 +4384,71 @@ return 0
2916
4384
  }
2917
4385
  });
2918
4386
  }
4387
+ if (this.opts.enableIpc) {
4388
+ this._ipcServer = new IpcTelemetryServer(this, this.opts.ipcSocketPath);
4389
+ this._ipcServer.start().catch((err) => {
4390
+ this.logger.warn("Failed to start IPC telemetry server", { error: err.message });
4391
+ });
4392
+ }
4393
+ }
4394
+ // ── Singleton factory & Presets ───────────────────────────────────────────
4395
+ /**
4396
+ * Pre-configured production presets tailored for specific deployment environments.
4397
+ *
4398
+ * - `'nextjs'`: W-TinyLFU, zero-copy cloneStrategy: 'none' (React 19 RSC stream optimized),
4399
+ * generational tags, and Redis stream backplane.
4400
+ * - `'microservice'`: High-throughput Node.js microservice with W-TinyLFU, Streams backplane,
4401
+ * TTL jitter, and L2 circuit breaking.
4402
+ * - `'serverless'`: Stateless Lambda / Cloud Run isolate with memory-only L1, fast timeouts,
4403
+ * and Pub/Sub backplane.
4404
+ * - `'enterprise-hardened'`: Zero-trust production setup with generational tagging, Streams backplane,
4405
+ * fail-closed rate-limits, strict singleton assertions, and 80% OOM guard.
4406
+ *
4407
+ * @param type The preset identifier ('nextjs' | 'microservice' | 'serverless' | 'enterprise-hardened')
4408
+ * @param overrides Optional configuration overrides merged deeply over preset defaults
4409
+ * @returns Singleton CacheService instance configured according to the preset
4410
+ */
4411
+ static preset(type, overrides) {
4412
+ const PRESETS = {
4413
+ "nextjs": {
4414
+ l1AdmissionPolicy: "wtinylfu",
4415
+ cloneStrategy: "none",
4416
+ tagStrategy: "generational",
4417
+ tagVersionTtlMs: 2e3,
4418
+ backplaneMode: "stream",
4419
+ staleIfError: 300,
4420
+ compression: "none"
4421
+ },
4422
+ "microservice": {
4423
+ l1AdmissionPolicy: "wtinylfu",
4424
+ backplaneMode: "stream",
4425
+ ttlJitterFactor: 0.15,
4426
+ l2CircuitBreakerThreshold: 5,
4427
+ l2CircuitBreakerCooldownMs: 15e3
4428
+ },
4429
+ "serverless": {
4430
+ disableDisk: true,
4431
+ l1AdmissionPolicy: "wtinylfu",
4432
+ backplaneMode: "pubsub",
4433
+ redisCommandTimeoutMs: 1e3
4434
+ },
4435
+ "enterprise-hardened": {
4436
+ l1AdmissionPolicy: "wtinylfu",
4437
+ tagStrategy: "generational",
4438
+ backplaneMode: "stream",
4439
+ strictSingleton: true,
4440
+ failClosed: true,
4441
+ oomProtection: true,
4442
+ oomHeapThreshold: 0.8
4443
+ }
4444
+ };
4445
+ const base = PRESETS[type];
4446
+ if (!base) {
4447
+ throw new Error(`tricache: unknown preset '${type}'. Supported presets: 'nextjs', 'microservice', 'serverless', 'enterprise-hardened'`);
4448
+ }
4449
+ const merged = deepMergeOptions(base, overrides);
4450
+ return _CacheService.create(merged);
2919
4451
  }
2920
- // ── Singleton factory ─────────────────────────────────────────────────────
2921
4452
  /**
2922
4453
  * Get (or create) the process-level singleton CacheService instance.
2923
4454
  *
@@ -2970,7 +4501,9 @@ return 0
2970
4501
  "adaptiveTtl",
2971
4502
  "l2WriteMode",
2972
4503
  "instanceName",
2973
- "invalidationBackplane"
4504
+ "invalidationBackplane",
4505
+ "awaitInvalidationBackplane",
4506
+ "lockFailClosed"
2974
4507
  ];
2975
4508
  /** Returns the names of options that differ between `a` and the live `b`. */
2976
4509
  static optionsDiff(a, b) {
@@ -3011,7 +4544,11 @@ return 0
3011
4544
  frozen: o.frozen,
3012
4545
  adaptiveTtl: o.adaptiveTtl,
3013
4546
  invalidationBackplane: o.invalidationBackplane,
3014
- strictSingleton: o.strictSingleton
4547
+ awaitInvalidationBackplane: o.awaitInvalidationBackplane,
4548
+ lockFailClosed: o.lockFailClosed,
4549
+ strictSingleton: o.strictSingleton,
4550
+ remoteSnapshot: o.remoteSnapshot,
4551
+ crossRegion: o.crossRegion
3015
4552
  };
3016
4553
  }
3017
4554
  /**
@@ -3070,15 +4607,30 @@ return 0
3070
4607
  setStatus() {
3071
4608
  return this;
3072
4609
  },
4610
+ recordException() {
4611
+ return this;
4612
+ },
3073
4613
  end() {
3074
4614
  }
3075
4615
  };
3076
4616
  /** 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);
4617
+ _startSpan(name, links) {
4618
+ if (this.opts.tracer) {
4619
+ const span = this.opts.tracer.startSpan(name, links?.length ? { links } : void 0);
4620
+ if (this.opts.namespace) {
4621
+ span.setAttribute("cache.namespace", this.opts.namespace);
4622
+ }
4623
+ return span;
4624
+ }
3079
4625
  return _CacheService._nullSpan;
3080
4626
  }
3081
4627
  createDedicatedRedisClient() {
4628
+ if (this.opts.redisSubClient) {
4629
+ return this.opts.redisSubClient;
4630
+ }
4631
+ if (this.opts.redisClient && typeof this.opts.redisClient.duplicate === "function") {
4632
+ return this.opts.redisClient.duplicate();
4633
+ }
3082
4634
  if (this.opts.redisClusterNodes?.length) {
3083
4635
  return new import_ioredis.Cluster(this.opts.redisClusterNodes, {
3084
4636
  redisOptions: {
@@ -3279,16 +4831,36 @@ return 0
3279
4831
  _applyInvalidationEvent(op, key, tagVersion) {
3280
4832
  if (op === "del") {
3281
4833
  this.l1.delete(key);
4834
+ this._bumpKeyMutation(key);
4835
+ this.inflight.delete(key);
4836
+ this._pendingDiskDeletes.add(key);
3282
4837
  setImmediate(() => {
3283
- if (!this._diskDisabled) this.disk.delete(key);
4838
+ try {
4839
+ if (!this._diskDisabled) this.disk.delete(key);
4840
+ } finally {
4841
+ this._pendingDiskDeletes.delete(key);
4842
+ }
3284
4843
  });
3285
4844
  this._cascadeDependencies(key);
3286
4845
  } else if (op === "del-glob") {
3287
4846
  this.l1.deletePattern(key);
4847
+ const pfx = key.endsWith("*") ? key.slice(0, -1) : key;
4848
+ for (const liveKey of this.l1.liveKeys()) {
4849
+ if (liveKey.startsWith(pfx)) {
4850
+ this._bumpKeyMutation(liveKey);
4851
+ }
4852
+ }
4853
+ for (const inflightKey of Array.from(this.inflight.keys())) {
4854
+ if (inflightKey.startsWith(pfx)) {
4855
+ this._bumpKeyMutation(inflightKey);
4856
+ this.inflight.delete(inflightKey);
4857
+ }
4858
+ }
4859
+ this._addPatternTombstone(pfx);
3288
4860
  } else if (op === "tag_incr") {
3289
4861
  const tag = key;
3290
4862
  const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
3291
- this._setLocalTagVersion(tag, ver, Date.now());
4863
+ this._setLocalTagVersion(tag, ver, performance.now());
3292
4864
  }
3293
4865
  this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
3294
4866
  }
@@ -3312,7 +4884,17 @@ return 0
3312
4884
  this.logger.warn("Backplane: malformed message JSON parse failed");
3313
4885
  }
3314
4886
  }
3315
- async publishInvalidation(op, key, tagVersion) {
4887
+ async publishInvalidation(op, key, tagVersion, isCrossRegionRelay = false, isExplicitInvalidation = false) {
4888
+ if (!isCrossRegionRelay && this.opts.crossRegion) {
4889
+ const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
4890
+ if (shouldBroadcast) {
4891
+ if (this.opts.awaitInvalidationBackplane) {
4892
+ await this._broadcastCrossRegion(op, key, tagVersion);
4893
+ } else {
4894
+ void this._broadcastCrossRegion(op, key, tagVersion);
4895
+ }
4896
+ }
4897
+ }
3316
4898
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
3317
4899
  try {
3318
4900
  const client = await this.getRedis();
@@ -3351,10 +4933,87 @@ return 0
3351
4933
  );
3352
4934
  }
3353
4935
  this.counters.invSent++;
3354
- } catch {
4936
+ } catch (err) {
4937
+ this.logger.warn("Backplane invalidation publish failed", { op, key, error: err.message });
4938
+ if (this.opts.awaitInvalidationBackplane) {
4939
+ throw err;
4940
+ }
3355
4941
  }
3356
4942
  }
3357
- _setLocalTagVersion(tag, version, now = Date.now()) {
4943
+ _markCrossRegionEventSeen(id) {
4944
+ const maxDedup = this.opts.crossRegion?.dedupCacheSize ?? 1e4;
4945
+ if (this._seenCrossRegionEvents.size >= maxDedup) {
4946
+ const oldestKey = this._seenCrossRegionEvents.keys().next().value;
4947
+ if (oldestKey !== void 0) this._seenCrossRegionEvents.delete(oldestKey);
4948
+ }
4949
+ this._seenCrossRegionEvents.set(id, Date.now());
4950
+ }
4951
+ _isCrossRegionEventSeen(id) {
4952
+ return this._seenCrossRegionEvents.has(id);
4953
+ }
4954
+ async _broadcastCrossRegion(op, key, tagVersion) {
4955
+ const cr = this.opts.crossRegion;
4956
+ if (!cr) return;
4957
+ try {
4958
+ const eventId = import_crypto3.default.randomUUID();
4959
+ this._markCrossRegionEventSeen(eventId);
4960
+ const event = {
4961
+ id: eventId,
4962
+ originRegion: cr.currentRegion,
4963
+ originInstanceId: this.instanceId,
4964
+ op,
4965
+ key,
4966
+ tagVersion,
4967
+ timestamp: Date.now(),
4968
+ namespace: this._namespace || void 0
4969
+ };
4970
+ this.counters.crossRegionSent++;
4971
+ await cr.relay.broadcast(event);
4972
+ this.logger.debug("Cross-region invalidation broadcast", { op, key, region: cr.currentRegion });
4973
+ } catch (err) {
4974
+ this.counters.crossRegionSent = Math.max(0, this.counters.crossRegionSent - 1);
4975
+ this.counters.crossRegionErrors++;
4976
+ this.logger.warn("Cross-region invalidation broadcast failed", { error: err.message });
4977
+ }
4978
+ }
4979
+ /**
4980
+ * Receives an invalidation event from another region (e.g. via HTTP webhook or broker subscriber).
4981
+ * Validates origin, deduplicates to prevent loops, applies locally to L1/disk,
4982
+ * and fans out to the local Redis backplane so all regional peers invalidate as well.
4983
+ *
4984
+ * Returns true if the event was accepted and applied, or false if ignored/deduplicated.
4985
+ */
4986
+ async receiveCrossRegionInvalidation(event) {
4987
+ const cr = this.opts.crossRegion;
4988
+ if (!cr) return false;
4989
+ if (!event || typeof event !== "object" || !event.id || !event.originRegion || !event.op || !event.key) {
4990
+ this.counters.crossRegionErrors++;
4991
+ this.logger.warn("Cross-region: rejected invalid event payload", { event });
4992
+ return false;
4993
+ }
4994
+ if (event.originRegion === cr.currentRegion) {
4995
+ this.counters.crossRegionDeduplicated++;
4996
+ return false;
4997
+ }
4998
+ if (this._isCrossRegionEventSeen(event.id)) {
4999
+ this.counters.crossRegionDeduplicated++;
5000
+ return false;
5001
+ }
5002
+ this._markCrossRegionEventSeen(event.id);
5003
+ if (event.namespace !== void 0 && event.namespace !== (this._namespace || void 0)) {
5004
+ return false;
5005
+ }
5006
+ this.counters.crossRegionReceived++;
5007
+ this._applyInvalidationEvent(event.op, event.key, event.tagVersion);
5008
+ void this.publishInvalidation(event.op, event.key, event.tagVersion, true);
5009
+ this.logger.info("Cross-region invalidation applied", {
5010
+ op: event.op,
5011
+ key: event.key,
5012
+ originRegion: event.originRegion
5013
+ });
5014
+ return true;
5015
+ }
5016
+ _setLocalTagVersion(tag, version, now = performance.now()) {
3358
5017
  const existing = this.tagVersions.get(tag)?.version ?? 0;
3359
5018
  const finalVersion = Math.max(existing, version);
3360
5019
  if (this.tagVersions.size >= 1e4 && !this.tagVersions.has(tag)) {
@@ -3364,7 +5023,7 @@ return 0
3364
5023
  this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
3365
5024
  }
3366
5025
  async _getTagVersion(tag) {
3367
- const now = Date.now();
5026
+ const now = performance.now();
3368
5027
  const local = this.tagVersions.get(tag);
3369
5028
  if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
3370
5029
  return local.version;
@@ -3450,13 +5109,25 @@ return 0
3450
5109
  stream.on("error", reject);
3451
5110
  })
3452
5111
  ));
3453
- } else {
5112
+ } else if (typeof client.scanStream === "function") {
3454
5113
  await new Promise((resolve, reject) => {
3455
5114
  const stream = client.scanStream({ match: pattern, count: 100 });
3456
5115
  stream.on("data", (chunk) => keys.push(...chunk));
3457
5116
  stream.on("end", resolve);
3458
5117
  stream.on("error", reject);
3459
5118
  });
5119
+ } else if (typeof client.scanIterator === "function") {
5120
+ for await (const key of client.scanIterator({ MATCH: pattern, COUNT: 100 })) {
5121
+ keys.push(key);
5122
+ }
5123
+ } else if (typeof client.scan === "function") {
5124
+ let cursor = "0";
5125
+ do {
5126
+ const res = await client.scan(cursor, "MATCH", pattern, "COUNT", 100);
5127
+ cursor = String(res[0]);
5128
+ const chunk = res[1];
5129
+ if (chunk?.length) keys.push(...chunk);
5130
+ } while (cursor !== "0");
3460
5131
  }
3461
5132
  return keys;
3462
5133
  }
@@ -3470,9 +5141,23 @@ return 0
3470
5141
  }
3471
5142
  }
3472
5143
  async getRedis() {
5144
+ this._assertActive("getRedis");
3473
5145
  if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
3474
5146
  if (this.redis) return this.redis;
3475
5147
  if (this.redisConnecting) return this.redisConnecting;
5148
+ if (this.opts.redisClient) {
5149
+ const client = this.opts.redisClient;
5150
+ if (typeof client.connect === "function" && client.isOpen === false) {
5151
+ await client.connect();
5152
+ }
5153
+ this.cb.onSuccess();
5154
+ this.redis = client;
5155
+ this.pipeliner = new AutoPipeliner(client, {
5156
+ enabled: this.opts.autoPipeline,
5157
+ maxBatchSize: this.opts.maxPipelineBatchSize
5158
+ });
5159
+ return client;
5160
+ }
3476
5161
  this.redisConnecting = (async () => {
3477
5162
  try {
3478
5163
  let client;
@@ -3481,6 +5166,7 @@ return 0
3481
5166
  redisOptions: {
3482
5167
  tls: this.opts.redisTls ? {} : void 0,
3483
5168
  connectTimeout: 1e4,
5169
+ commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
3484
5170
  maxRetriesPerRequest: 3,
3485
5171
  keepAlive: 3e4,
3486
5172
  ...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
@@ -3501,6 +5187,7 @@ return 0
3501
5187
  name: this.opts.redisSentinel.name,
3502
5188
  tls: this.opts.redisTls ? {} : void 0,
3503
5189
  connectTimeout: 1e4,
5190
+ commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
3504
5191
  lazyConnect: false,
3505
5192
  maxRetriesPerRequest: 3,
3506
5193
  enableAutoPipelining: true,
@@ -3520,6 +5207,7 @@ return 0
3520
5207
  port: this.opts.redisPort,
3521
5208
  tls: this.opts.redisTls ? {} : void 0,
3522
5209
  connectTimeout: 1e4,
5210
+ commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
3523
5211
  lazyConnect: false,
3524
5212
  maxRetriesPerRequest: 3,
3525
5213
  enableAutoPipelining: true,
@@ -3545,6 +5233,10 @@ return 0
3545
5233
  });
3546
5234
  this.cb.onSuccess();
3547
5235
  this.redis = client;
5236
+ this.pipeliner = new AutoPipeliner(client, {
5237
+ enabled: this.opts.autoPipeline,
5238
+ maxBatchSize: this.opts.maxPipelineBatchSize
5239
+ });
3548
5240
  this.redisConnecting = null;
3549
5241
  return client;
3550
5242
  } catch (err) {
@@ -3557,12 +5249,18 @@ return 0
3557
5249
  return this.redisConnecting;
3558
5250
  }
3559
5251
  // ── Snapshot (cold-start persistence) ────────────────────────────────────
5252
+ /**
5253
+ * Writes the cold-start snapshot to disk.
5254
+ * NOTE: fs.writeFileSync is INTENTIONAL here: this method is invoked during SIGTERM/SIGINT
5255
+ * process termination hooks where asynchronous I/O would risk the Node.js event loop dying or
5256
+ * process.exit() being called before the snapshot is physically written to disk.
5257
+ */
3560
5258
  writeSnapshot(altPath) {
3561
5259
  try {
3562
5260
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
3563
5261
  if (entries.length === 0) return;
3564
5262
  const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
3565
- const packed = (0, import_msgpackr3.pack)(payload);
5263
+ const packed = this.codec.encode(payload);
3566
5264
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
3567
5265
  const dest = altPath ?? this.opts.snapshotPath;
3568
5266
  import_fs3.default.mkdirSync(import_path3.default.dirname(dest), { recursive: true });
@@ -3577,6 +5275,12 @@ return 0
3577
5275
  this.logger.warn("Cache snapshot write failed", { error: err.message });
3578
5276
  }
3579
5277
  }
5278
+ /**
5279
+ * Loads cold-start snapshot from disk into L1 memory.
5280
+ * NOTE: fs.readFileSync is INTENTIONAL here: this method is invoked synchronously inside the
5281
+ * CacheService constructor so that the cache is atomically populated before any subsequent
5282
+ * cache.get() or cache.set() operations run, eliminating cold-start race conditions.
5283
+ */
3580
5284
  loadSnapshot() {
3581
5285
  const snapshotPath = this.opts.snapshotPath;
3582
5286
  try {
@@ -3596,13 +5300,25 @@ return 0
3596
5300
  this.logger.warn("Snapshot rejected: decryption failed", { error: e.message });
3597
5301
  return;
3598
5302
  }
3599
- const snapshot = (0, import_msgpackr3.unpack)(buf);
5303
+ const snapshot = this.codec.decode(buf);
3600
5304
  if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
3601
5305
  this.logger.warn("Snapshot rejected: version mismatch", { got: snapshot?.version });
3602
5306
  return;
3603
5307
  }
3604
- const ageMs = Date.now() - (snapshot.writtenAt ?? 0);
3605
- if (ageMs > this.opts.snapshotMaxAgeMs || ageMs < 0) {
5308
+ const now = Date.now();
5309
+ const writtenAt = snapshot.writtenAt ?? 0;
5310
+ const tolerance = this.opts.clockSkewToleranceMs ?? 250;
5311
+ if (writtenAt - now > tolerance) {
5312
+ this.logger.warn("Snapshot rejected: timestamp too far in future (exceeds clock skew tolerance)", {
5313
+ writtenAt,
5314
+ now,
5315
+ skewMs: writtenAt - now,
5316
+ tolerance
5317
+ });
5318
+ return;
5319
+ }
5320
+ const ageMs = Math.max(0, now - writtenAt);
5321
+ if (ageMs > this.opts.snapshotMaxAgeMs) {
3606
5322
  this.logger.warn("Snapshot rejected: too old", { ageMinutes: Math.round(ageMs / 6e4) });
3607
5323
  return;
3608
5324
  }
@@ -3624,6 +5340,115 @@ return 0
3624
5340
  }
3625
5341
  }
3626
5342
  }
5343
+ // ── Remote Snapshot (cold-start persistence for stateless containers) ───────
5344
+ /**
5345
+ * Persists the cold-start snapshot to remote blob storage (S3, GCS, R2, HTTP).
5346
+ * Can be awaited during graceful application shutdown (e.g. Kubernetes preStop or NestJS shutdown).
5347
+ * Returns true if a snapshot was successfully exported and written; false otherwise.
5348
+ */
5349
+ async writeRemoteSnapshot() {
5350
+ if (!this.opts.remoteSnapshot) return false;
5351
+ try {
5352
+ const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
5353
+ if (entries.length === 0) return false;
5354
+ const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
5355
+ const packed = this.codec.encode(payload);
5356
+ let final;
5357
+ if (this.opts.remoteSnapshot.envelope) {
5358
+ final = await EnvelopeEncryption.encrypt(packed, this.opts.remoteSnapshot.envelope);
5359
+ } else {
5360
+ final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
5361
+ }
5362
+ await this.opts.remoteSnapshot.adapter.put(final);
5363
+ this.counters.remoteSnapshotUploads++;
5364
+ this.counters.remoteSnapshotLastUploadedAt = Date.now();
5365
+ this.logger.info("Remote cache snapshot uploaded", {
5366
+ entries: entries.length,
5367
+ sizeKB: Math.round(final.length / 1024),
5368
+ encrypted: Boolean(this.opts.remoteSnapshot.envelope || this.enc.isEnabled)
5369
+ });
5370
+ return true;
5371
+ } catch (err) {
5372
+ this.counters.remoteSnapshotErrors++;
5373
+ this.logger.warn("Remote cache snapshot upload failed", { error: err.message });
5374
+ return false;
5375
+ }
5376
+ }
5377
+ /**
5378
+ * Hydrates L1 memory from remote blob storage (S3, GCS, R2, HTTP).
5379
+ * Called automatically during startup (chained into `cache.ready()`).
5380
+ * Returns the number of entries successfully imported.
5381
+ */
5382
+ async loadRemoteSnapshot() {
5383
+ if (!this.opts.remoteSnapshot) return 0;
5384
+ const maxAgeMs = this.opts.remoteSnapshot.maxAgeMs ?? this.opts.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE;
5385
+ try {
5386
+ const raw = await this.opts.remoteSnapshot.adapter.get();
5387
+ if (!raw || raw.length === 0) {
5388
+ this.logger.debug("Remote snapshot not found or empty \u2014 starting cold");
5389
+ return 0;
5390
+ }
5391
+ const rawBuf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
5392
+ let buf;
5393
+ try {
5394
+ if (EnvelopeEncryption.isEnvelope(rawBuf)) {
5395
+ if (!this.opts.remoteSnapshot.envelope) {
5396
+ throw new Error("Remote snapshot is envelope-encrypted but no envelope options (privateKey or kmsDecrypt) were configured");
5397
+ }
5398
+ buf = await EnvelopeEncryption.decrypt(rawBuf, this.opts.remoteSnapshot.envelope);
5399
+ } else {
5400
+ buf = this.enc.decryptBuffer(rawBuf);
5401
+ }
5402
+ } catch (e) {
5403
+ this.counters.remoteSnapshotErrors++;
5404
+ this.logger.warn("Remote snapshot rejected: decryption failed", { error: e.message });
5405
+ return 0;
5406
+ }
5407
+ const snapshot = this.codec.decode(buf);
5408
+ if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
5409
+ this.counters.remoteSnapshotErrors++;
5410
+ this.logger.warn("Remote snapshot rejected: version mismatch", { got: snapshot?.version });
5411
+ return 0;
5412
+ }
5413
+ const now = Date.now();
5414
+ const writtenAt = snapshot.writtenAt ?? 0;
5415
+ const tolerance = this.opts.clockSkewToleranceMs ?? 250;
5416
+ if (writtenAt - now > tolerance) {
5417
+ this.counters.remoteSnapshotErrors++;
5418
+ this.logger.warn("Remote snapshot rejected: timestamp too far in future (exceeds clock skew tolerance)", {
5419
+ writtenAt,
5420
+ now,
5421
+ skewMs: writtenAt - now,
5422
+ tolerance
5423
+ });
5424
+ return 0;
5425
+ }
5426
+ const ageMs = Math.max(0, now - writtenAt);
5427
+ if (maxAgeMs <= 0 || ageMs > maxAgeMs) {
5428
+ this.counters.remoteSnapshotErrors++;
5429
+ this.logger.warn("Remote snapshot rejected: too old", { ageMinutes: Math.round(ageMs / 6e4) });
5430
+ return 0;
5431
+ }
5432
+ if (!Array.isArray(snapshot.entries)) {
5433
+ this.counters.remoteSnapshotErrors++;
5434
+ this.logger.warn("Remote snapshot rejected: entries is not an array");
5435
+ return 0;
5436
+ }
5437
+ const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
5438
+ this.counters.remoteSnapshotDownloads++;
5439
+ this.counters.remoteSnapshotLastDownloadedAt = Date.now();
5440
+ this.logger.info("Remote cache snapshot loaded (L1 hydrated)", {
5441
+ loaded,
5442
+ total: snapshot.entries.length,
5443
+ sizeKB: this.l1.getStats().sizeKB
5444
+ });
5445
+ return loaded;
5446
+ } catch (err) {
5447
+ this.counters.remoteSnapshotErrors++;
5448
+ this.logger.warn("Remote snapshot load failed \u2014 starting cold", { error: err.message });
5449
+ return 0;
5450
+ }
5451
+ }
3627
5452
  // ── Core get (L1 → L1.5 → L2 → fetch) ───────────────────────────────────
3628
5453
  /**
3629
5454
  * Get a value from cache, or fetch and cache it.
@@ -3645,6 +5470,7 @@ return 0
3645
5470
  * Caches negative lookups to avoid repeated DB hits for missing keys.
3646
5471
  */
3647
5472
  async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
5473
+ this._assertActive("get");
3648
5474
  const span = this._startSpan("tricache.get");
3649
5475
  if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
3650
5476
  const k = this.nk(cacheKey);
@@ -3659,9 +5485,10 @@ return 0
3659
5485
  if (l1Hit !== null) {
3660
5486
  let isGenerationalStale = false;
3661
5487
  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) {
5488
+ const tags = Object.keys(l1Hit.tagVersions);
5489
+ const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5490
+ for (let i = 0; i < tags.length; i++) {
5491
+ if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
3665
5492
  isGenerationalStale = true;
3666
5493
  break;
3667
5494
  }
@@ -3675,7 +5502,14 @@ return 0
3675
5502
  if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
3676
5503
  const priority2 = optPriority ?? inferPriority(cacheKey);
3677
5504
  this.revalidating.add(k);
3678
- void this._revalidate(k, fetchFn, ttlSeconds * 1e3, swrGraceMs2, priority2);
5505
+ void this._revalidate(
5506
+ k,
5507
+ fetchFn,
5508
+ ttlSeconds * 1e3,
5509
+ swrGraceMs2,
5510
+ priority2,
5511
+ l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
5512
+ );
3679
5513
  this.counters.swrRevalidations++;
3680
5514
  this.logger.debug("SWR: serving stale, revalidating", { cacheKey });
3681
5515
  } else {
@@ -3694,7 +5528,14 @@ return 0
3694
5528
  if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
3695
5529
  const priority2 = optPriority ?? inferPriority(cacheKey);
3696
5530
  this.revalidating.add(k);
3697
- void this._revalidate(k, fetchFn, entryTtl, optSwr * 1e3, priority2);
5531
+ void this._revalidate(
5532
+ k,
5533
+ fetchFn,
5534
+ entryTtl,
5535
+ optSwr * 1e3,
5536
+ priority2,
5537
+ l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
5538
+ );
3698
5539
  this.counters.swrRevalidations++;
3699
5540
  this.logger.debug(
3700
5541
  shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
@@ -3706,116 +5547,148 @@ return 0
3706
5547
  this.counters.l1Hits++;
3707
5548
  this.opts.onHit?.(cacheKey, "l1");
3708
5549
  if (this.opts.frozen) deepFreeze(l1Hit.value);
3709
- span.setAttribute("cache.hit", "l1").end();
5550
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "memory").setAttribute("cache.hit_tier", "l1").end();
3710
5551
  return this.opts.cloneStrategy === "structuredClone" && l1Hit.value != null && typeof l1Hit.value === "object" ? structuredClone(l1Hit.value) : l1Hit.value;
3711
5552
  }
3712
5553
  }
3713
5554
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
3714
5555
  const swrGraceMs = optSwr * 1e3;
3715
5556
  const priority = optPriority ?? inferPriority(cacheKey);
3716
- if (!this._redisDisabled) {
5557
+ const existing = this.inflight.get(k);
5558
+ if (existing) {
5559
+ this.counters.stampedes++;
5560
+ this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch/read", { cacheKey });
5561
+ span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
5562
+ return existing;
5563
+ }
5564
+ const mutationEpochAtStart = this._getKeyMutationEpoch(k);
5565
+ const executionPromise = (async () => {
3717
5566
  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 {
3729
- }
5567
+ if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
5568
+ if (this._isTombstonedByPattern(k)) {
5569
+ try {
5570
+ this.disk.delete(k);
5571
+ } catch {
3730
5572
  }
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;
5573
+ } else {
5574
+ const isDiskAllowed = this.watchdog.isDiskAllowed();
5575
+ if (isDiskAllowed) {
5576
+ const diskStart = performance.now();
5577
+ const diskHit = this.disk.load(k);
5578
+ const diskElapsed = performance.now() - diskStart;
5579
+ this.watchdog.recordDisk(diskElapsed);
5580
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
5581
+ if (diskHit !== null) {
5582
+ let isDiskStale = false;
5583
+ if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
5584
+ const tags = Object.keys(diskHit.tagVersions);
5585
+ const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5586
+ for (let i = 0; i < tags.length; i++) {
5587
+ if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
5588
+ isDiskStale = true;
5589
+ break;
5590
+ }
5591
+ }
5592
+ }
5593
+ if (isDiskStale) {
5594
+ this.disk.delete(k);
5595
+ } else {
5596
+ const promoted = this.l1.importEntries(
5597
+ [{ key: k, entry: diskHit }],
5598
+ this.opts.forbiddenSnapshotPrefixes
5599
+ );
5600
+ if (promoted > 0) {
5601
+ const l1Check = this.l1.get(k);
5602
+ if (l1Check !== null) {
5603
+ this.counters.diskHits++;
5604
+ this.opts.onHit?.(cacheKey, "disk");
5605
+ this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
5606
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
5607
+ if (this.opts.frozen) deepFreeze(l1Check.value);
5608
+ return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
5609
+ }
5610
+ }
5611
+ }
3736
5612
  }
3737
5613
  }
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
- }
3765
- }
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
5614
  }
3783
5615
  }
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;
5616
+ if (!this._redisDisabled) {
5617
+ try {
5618
+ const client = await this.getRedis();
5619
+ const redisStart = performance.now();
5620
+ if (this.opts.tagStrategy === "generational") {
5621
+ const hashData = await client.hgetall(k);
5622
+ const redisElapsed = performance.now() - redisStart;
5623
+ this.watchdog.recordRedis(redisElapsed);
5624
+ this.cb.onSuccess();
5625
+ if (hashData && hashData.d) {
5626
+ let isStale = false;
5627
+ let storedTagVersions = {};
5628
+ if (hashData.tv) {
5629
+ try {
5630
+ storedTagVersions = JSON.parse(hashData.tv);
5631
+ } catch {
5632
+ }
5633
+ }
5634
+ const tags = Object.keys(storedTagVersions);
5635
+ const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
5636
+ for (let i = 0; i < tags.length; i++) {
5637
+ if (currentVers[i] > storedTagVersions[tags[i]]) {
5638
+ isStale = true;
5639
+ break;
5640
+ }
5641
+ }
5642
+ if (isStale) {
5643
+ const setAtMs = parseInt(hashData.t, 10) || 0;
5644
+ this._deleteIfStale(k, setAtMs);
5645
+ } else {
5646
+ const parsed = await this._decryptAndDeserialize(hashData.d);
5647
+ this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
5648
+ this.counters.l2Hits++;
5649
+ this.opts.onHit?.(cacheKey, "l2");
5650
+ this.logger.debug("L2 hit (Redis hash)", { cacheKey });
5651
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5652
+ if (this.opts.frozen) deepFreeze(parsed);
5653
+ return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
5654
+ }
5655
+ }
5656
+ } else {
5657
+ const raw = this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
5658
+ const redisElapsed = performance.now() - redisStart;
5659
+ this.watchdog.recordRedis(redisElapsed);
5660
+ this.cb.onSuccess();
5661
+ if (raw) {
5662
+ const parsed = await this._decryptAndDeserialize(raw);
5663
+ this.l1.set(k, parsed, ttlMs, priority);
5664
+ this.counters.l2Hits++;
5665
+ this.opts.onHit?.(cacheKey, "l2");
5666
+ this.logger.debug("L2 hit (Redis)", { cacheKey });
5667
+ span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
5668
+ if (this.opts.frozen) deepFreeze(parsed);
5669
+ return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
5670
+ }
3800
5671
  }
5672
+ } catch (err) {
5673
+ this.cb.onFailure();
5674
+ this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
3801
5675
  }
3802
5676
  }
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 {
5677
+ span.setAttribute("cache.hit", false).setAttribute("cache.hit_tier", "miss");
5678
+ this.opts.onMiss?.(cacheKey);
3816
5679
  this.counters.fetches++;
3817
5680
  const fetchStart = Date.now();
3818
- const data = await fetchFn();
5681
+ let data;
5682
+ try {
5683
+ data = await fetchFn();
5684
+ } catch (fetchErr) {
5685
+ span.setStatus({
5686
+ code: 2,
5687
+ message: fetchErr instanceof Error ? fetchErr.message : String(fetchErr)
5688
+ });
5689
+ span.recordException?.(fetchErr);
5690
+ throw fetchErr;
5691
+ }
3819
5692
  const delta = Date.now() - fetchStart;
3820
5693
  const notFoundTtlMs = (optNotFoundTtl ?? this.opts.notFoundTtl) * 1e3;
3821
5694
  let effectiveTtl = data == null && notFoundTtlMs > 0 ? notFoundTtlMs : ttlMs;
@@ -3835,14 +5708,27 @@ return 0
3835
5708
  let activeTagVersions;
3836
5709
  if (optTags?.length) {
3837
5710
  if (this.opts.tagStrategy === "generational") {
5711
+ const vers = await Promise.all(optTags.map((tag) => this._getTagVersion(tag)));
3838
5712
  activeTagVersions = {};
3839
- for (const tag of optTags) {
3840
- activeTagVersions[tag] = await this._getTagVersion(tag);
5713
+ for (let i = 0; i < optTags.length; i++) {
5714
+ activeTagVersions[optTags[i]] = vers[i];
3841
5715
  }
3842
5716
  } else {
3843
5717
  await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
3844
5718
  }
3845
5719
  }
5720
+ if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
5721
+ this.logger.debug("Aborting in-flight cache commit \u2014 key was mutated or deleted during fetch", { cacheKey });
5722
+ span.setAttribute("cache.aborted_mutation_race", true);
5723
+ const current = this.l1.get(k);
5724
+ if (current && !current.isStale && current.value !== void 0) {
5725
+ const freshVal = current.value;
5726
+ if (this.opts.frozen) deepFreeze(freshVal);
5727
+ return this.opts.cloneStrategy === "structuredClone" && freshVal != null && typeof freshVal === "object" ? structuredClone(freshVal) : freshVal;
5728
+ }
5729
+ if (this.opts.frozen) deepFreeze(data);
5730
+ return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
5731
+ }
3846
5732
  this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
3847
5733
  if (!this._redisDisabled) {
3848
5734
  try {
@@ -3879,8 +5765,64 @@ return 0
3879
5765
  span.end();
3880
5766
  }
3881
5767
  })();
3882
- this.inflight.set(k, fetchPromise);
3883
- return fetchPromise;
5768
+ this.inflight.set(k, executionPromise);
5769
+ return executionPromise;
5770
+ }
5771
+ /**
5772
+ * Graceful shutdown flusher for Kubernetes preStop hooks, NestJS onApplicationShutdown,
5773
+ * or manual microservice teardown.
5774
+ *
5775
+ * Flushes both local disk and remote cloud snapshots (S3/R2/GCS), returning a Promise
5776
+ * that resolves when the upload completes or after `timeoutMs` expires.
5777
+ *
5778
+ * @param timeoutMs Maximum time permitted for snapshot persistence before timing out. Default: 8000ms.
5779
+ */
5780
+ async flushSnapshotOnShutdown(timeoutMs = 8e3) {
5781
+ const flusher = async () => {
5782
+ let localOk = true;
5783
+ let remoteOk = true;
5784
+ if (!this._diskDisabled) {
5785
+ try {
5786
+ this.writeSnapshot();
5787
+ } catch (err) {
5788
+ localOk = false;
5789
+ this.logger.warn("flushSnapshotOnShutdown: disk snapshot write failed", { error: err.message });
5790
+ }
5791
+ }
5792
+ if (this.opts.remoteSnapshot && this.opts.remoteSnapshot.saveOnShutdown !== false) {
5793
+ try {
5794
+ remoteOk = await this.writeRemoteSnapshot();
5795
+ } catch (err) {
5796
+ remoteOk = false;
5797
+ this.logger.warn("flushSnapshotOnShutdown: remote snapshot upload failed", { error: err.message });
5798
+ }
5799
+ }
5800
+ return localOk && remoteOk;
5801
+ };
5802
+ let timer = null;
5803
+ try {
5804
+ return await Promise.race([
5805
+ flusher(),
5806
+ new Promise((resolve) => {
5807
+ timer = setTimeout(() => {
5808
+ this.logger.warn(`flushSnapshotOnShutdown timed out after ${timeoutMs}ms`);
5809
+ resolve(false);
5810
+ }, timeoutMs);
5811
+ if (timer.unref) timer.unref();
5812
+ })
5813
+ ]);
5814
+ } finally {
5815
+ if (timer) clearTimeout(timer);
5816
+ }
5817
+ }
5818
+ /**
5819
+ * Internal graceful shutdown trigger invoked by ProcessTerminationBus.
5820
+ */
5821
+ _triggerShutdown() {
5822
+ if (!this._diskDisabled) this.writeSnapshot();
5823
+ if (this.opts.remoteSnapshot && this.opts.remoteSnapshot.saveOnShutdown !== false) {
5824
+ void this.flushSnapshotOnShutdown();
5825
+ }
3884
5826
  }
3885
5827
  /**
3886
5828
  * Universal fetch-and-cache wrapper with an ergonomic options object.
@@ -3903,21 +5845,41 @@ return 0
3903
5845
  const ttl = options?.ttl ?? 300;
3904
5846
  return this.get(cacheKey, fetchFn, ttl, options);
3905
5847
  }
3906
- async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
5848
+ async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority, knownTagVersions) {
5849
+ const startEpoch = this._getKeyMutationEpoch(cacheKey);
3907
5850
  try {
3908
5851
  const fetchStart = Date.now();
3909
5852
  const data = await fetchFn();
3910
5853
  const delta = Date.now() - fetchStart;
3911
5854
  const staleAt = Date.now() + ttlMs;
5855
+ if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
5856
+ this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during fetch", { cacheKey });
5857
+ return;
5858
+ }
3912
5859
  if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
3913
5860
  let activeTagVersions;
3914
5861
  const l1Existing = this.l1.get(cacheKey);
3915
- if (this.opts.tagStrategy === "generational" && l1Existing?.tagVersions) {
5862
+ const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
5863
+ if (this.opts.tagStrategy === "generational" && tagVersionsSource) {
5864
+ const tags = Object.keys(tagVersionsSource);
5865
+ const vers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
3916
5866
  activeTagVersions = {};
3917
- for (const tag of Object.keys(l1Existing.tagVersions)) {
3918
- activeTagVersions[tag] = await this._getTagVersion(tag);
5867
+ for (let i = 0; i < tags.length; i++) {
5868
+ activeTagVersions[tags[i]] = vers[i];
5869
+ }
5870
+ if (knownTagVersions) {
5871
+ for (const t of tags) {
5872
+ if (knownTagVersions[t] !== void 0 && activeTagVersions[t] !== knownTagVersions[t]) {
5873
+ this.logger.debug("SWR: aborting revalidation commit \u2014 tag version bumped during revalidation", { cacheKey, tag: t });
5874
+ return;
5875
+ }
5876
+ }
3919
5877
  }
3920
5878
  }
5879
+ if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
5880
+ this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
5881
+ return;
5882
+ }
3921
5883
  this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
3922
5884
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
3923
5885
  try {
@@ -3960,63 +5922,86 @@ return 0
3960
5922
  // ── Explicit set / delete ─────────────────────────────────────────────────
3961
5923
  /** Explicitly write a value into L1 (+ L2 in production). */
3962
5924
  async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
5925
+ this._assertActive("set");
3963
5926
  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);
5927
+ if (this.opts.tracer) {
5928
+ span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
5929
+ span.setAttribute("cache.ttl", ttlSeconds);
5930
+ }
5931
+ try {
5932
+ const effectiveTtlSeconds = ttlSeconds > 0 ? ttlSeconds : ttlSeconds === 0 ? INDEFINITE_TTL_SECONDS : ttlSeconds;
5933
+ const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
5934
+ const p = priority ?? inferPriority(cacheKey);
5935
+ const k = this.nk(cacheKey);
5936
+ this._bumpKeyMutation(k);
5937
+ this.inflight.delete(k);
5938
+ this._pendingDiskDeletes.delete(k);
5939
+ this.counters.sets++;
5940
+ let activeTagVersions;
5941
+ if (opts?.tags?.length) {
5942
+ if (this.opts.tagStrategy === "generational") {
5943
+ const vers = await Promise.all(opts.tags.map((tag) => this._getTagVersion(tag)));
5944
+ activeTagVersions = {};
5945
+ for (let i = 0; i < opts.tags.length; i++) {
5946
+ activeTagVersions[opts.tags[i]] = vers[i];
5947
+ }
5948
+ } else {
5949
+ await this._registerTags(k, opts.tags, ttlSeconds);
3976
5950
  }
3977
- } else {
3978
- await this._registerTags(k, opts.tags, ttlSeconds);
3979
5951
  }
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);
5952
+ this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
5953
+ if (opts?.dependsOn?.length) {
5954
+ for (const pattern of opts.dependsOn) {
5955
+ const nsPattern = this.nk(pattern);
5956
+ let deps = this.dependencyIndex.get(nsPattern);
5957
+ if (!deps) {
5958
+ deps = /* @__PURE__ */ new Set();
5959
+ this.dependencyIndex.set(nsPattern, deps);
5960
+ }
5961
+ deps.add(k);
3989
5962
  }
3990
- deps.add(k);
3991
5963
  }
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);
5964
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
5965
+ try {
5966
+ const client = await this.getRedis();
5967
+ const s = JSON.stringify(data);
5968
+ const stored = await this._serializeAndEncrypt(s);
5969
+ const ttlSec = Math.ceil(ttlMs / 1e3);
5970
+ if (this.opts.tagStrategy === "generational" && activeTagVersions) {
5971
+ const now = Date.now();
5972
+ const tx = client.multi();
5973
+ tx.hset(k, {
5974
+ d: stored,
5975
+ t: String(now),
5976
+ tv: JSON.stringify(activeTagVersions)
5977
+ });
5978
+ tx.expire(k, ttlSec);
5979
+ await tx.exec();
5980
+ } else {
5981
+ if (this.opts.autoPipeline && this.pipeliner) {
5982
+ await this.pipeliner.setex(k, ttlSec, stored);
5983
+ } else {
5984
+ await client.setex(k, ttlSec, stored);
5985
+ }
5986
+ }
5987
+ this.cb.onSuccess();
5988
+ } catch (err) {
5989
+ this.cb.onFailure();
5990
+ this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
4011
5991
  }
4012
- this.cb.onSuccess();
4013
- } catch (err) {
4014
- this.cb.onFailure();
4015
- this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
4016
5992
  }
5993
+ if (this.opts.awaitInvalidationBackplane) {
5994
+ await this.publishInvalidation("del", k);
5995
+ } else {
5996
+ void this.publishInvalidation("del", k);
5997
+ }
5998
+ } catch (err) {
5999
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
6000
+ span.recordException?.(err);
6001
+ throw err;
6002
+ } finally {
6003
+ span.end();
4017
6004
  }
4018
- void this.publishInvalidation("del", k);
4019
- span.end();
4020
6005
  }
4021
6006
  /**
4022
6007
  * Register tags for a cache key in the in-process index and (if Redis is enabled) in
@@ -4056,38 +6041,74 @@ return 0
4056
6041
  * await cache.delete('user:abc:*'); // all keys for user abc
4057
6042
  */
4058
6043
  async delete(cacheKey) {
6044
+ this._assertActive("delete");
4059
6045
  const span = this._startSpan("tricache.delete");
4060
6046
  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);
6047
+ try {
6048
+ const isPattern = cacheKey.includes("*");
6049
+ const k = this.nk(cacheKey);
6050
+ this.counters.deletes++;
6051
+ if (isPattern) {
6052
+ const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6053
+ for (const liveKey of this.l1.liveKeys()) {
6054
+ if (liveKey.startsWith(pfx)) {
6055
+ this._bumpKeyMutation(liveKey);
6056
+ }
4082
6057
  }
4083
- this.cb.onSuccess();
4084
- } catch (err) {
4085
- this.cb.onFailure();
4086
- this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
6058
+ for (const inflightKey of Array.from(this.inflight.keys())) {
6059
+ if (inflightKey.startsWith(pfx)) {
6060
+ this._bumpKeyMutation(inflightKey);
6061
+ this.inflight.delete(inflightKey);
6062
+ }
6063
+ }
6064
+ this._addPatternTombstone(pfx);
6065
+ this.l1.deletePattern(k);
6066
+ } else {
6067
+ this._bumpKeyMutation(k);
6068
+ this.inflight.delete(k);
6069
+ this.l1.delete(k);
6070
+ this._pendingDiskDeletes.add(k);
6071
+ setImmediate(() => {
6072
+ try {
6073
+ if (!this._diskDisabled) this.disk.delete(k);
6074
+ } finally {
6075
+ this._pendingDiskDeletes.delete(k);
6076
+ }
6077
+ });
6078
+ this._cascadeDependencies(k);
6079
+ for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
6080
+ }
6081
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6082
+ try {
6083
+ const client = await this.getRedis();
6084
+ if (isPattern) {
6085
+ const keys = await this._scanKeys(client, k);
6086
+ if (keys.length > 0) await client.del(...keys);
6087
+ } else {
6088
+ if (this.opts.autoPipeline && this.pipeliner) {
6089
+ await this.pipeliner.del(k);
6090
+ } else {
6091
+ await client.del(k);
6092
+ }
6093
+ }
6094
+ this.cb.onSuccess();
6095
+ } catch (err) {
6096
+ this.cb.onFailure();
6097
+ this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
6098
+ }
6099
+ }
6100
+ if (this.opts.awaitInvalidationBackplane) {
6101
+ await this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
6102
+ } else {
6103
+ void this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
4087
6104
  }
6105
+ } catch (err) {
6106
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
6107
+ span.recordException?.(err);
6108
+ throw err;
6109
+ } finally {
6110
+ span.end();
4088
6111
  }
4089
- void this.publishInvalidation(isPattern ? "del-glob" : "del", k);
4090
- span.end();
4091
6112
  }
4092
6113
  // ── Counter (distributed rate limiting) ──────────────────────────────────
4093
6114
  /**
@@ -4107,6 +6128,7 @@ return 0
4107
6128
  * fleet-wide.
4108
6129
  */
4109
6130
  async increment(cacheKey, ttlSeconds) {
6131
+ this._assertActive("increment");
4110
6132
  const k = this.nk(cacheKey);
4111
6133
  if (this._redisDisabled) {
4112
6134
  if (!this._incrementFallbackWarned) {
@@ -4148,31 +6170,73 @@ return 0
4148
6170
  * await cache.clear('user:abc'); // flush all keys for one user
4149
6171
  */
4150
6172
  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 });
6173
+ this._assertActive("clear");
6174
+ const span = this._startSpan("tricache.clear");
6175
+ if (this.opts.tracer) span.setAttribute("cache.prefix", prefix || "*");
6176
+ try {
6177
+ this.counters.deletes++;
6178
+ const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
6179
+ if (k) {
6180
+ const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
6181
+ for (const liveKey of this.l1.liveKeys()) {
6182
+ if (liveKey.startsWith(pfx)) {
6183
+ this._bumpKeyMutation(liveKey);
6184
+ }
6185
+ }
6186
+ for (const inflightKey of Array.from(this.inflight.keys())) {
6187
+ if (inflightKey.startsWith(pfx)) {
6188
+ this._bumpKeyMutation(inflightKey);
6189
+ this.inflight.delete(inflightKey);
6190
+ }
6191
+ }
6192
+ this._addPatternTombstone(pfx);
6193
+ this.l1.deletePattern(k);
6194
+ } else {
6195
+ this._globalEpoch++;
6196
+ this.inflight.clear();
6197
+ this._patternTombstones.length = 0;
6198
+ this.l1.clear();
6199
+ if (!this._diskDisabled) this.disk.clear();
6200
+ this._l1Counters.clear();
6201
+ this.tagIndex.clear();
6202
+ this.tagVersions.clear();
6203
+ this._pendingDiskDeletes.clear();
6204
+ this._keyMutationEpochs.clear();
6205
+ }
6206
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
6207
+ try {
6208
+ const client = await this.getRedis();
6209
+ const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
6210
+ const keys = await this._scanKeys(client, pattern);
6211
+ if (keys.length > 0) await client.del(...keys);
6212
+ } catch (err) {
6213
+ this.logger.debug("clear: Redis unavailable", { error: err.message });
6214
+ }
6215
+ }
6216
+ if (this.opts.awaitInvalidationBackplane) {
6217
+ await this.publishInvalidation(
6218
+ "del-glob",
6219
+ k ?? (this._namespace ? `${this._namespace}:*` : "*"),
6220
+ void 0,
6221
+ false,
6222
+ true
6223
+ );
6224
+ } else {
6225
+ void this.publishInvalidation(
6226
+ "del-glob",
6227
+ k ?? (this._namespace ? `${this._namespace}:*` : "*"),
6228
+ void 0,
6229
+ false,
6230
+ true
6231
+ );
4170
6232
  }
6233
+ } catch (err) {
6234
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
6235
+ span.recordException?.(err);
6236
+ throw err;
6237
+ } finally {
6238
+ span.end();
4171
6239
  }
4172
- void this.publishInvalidation(
4173
- "del-glob",
4174
- k ?? (this._namespace ? `${this._namespace}:*` : "*")
4175
- );
4176
6240
  }
4177
6241
  /**
4178
6242
  * Evict L1 entries that violate the current category or global capacity limits.
@@ -4180,6 +6244,7 @@ return 0
4180
6244
  * Returns the number of entries evicted.
4181
6245
  */
4182
6246
  rebalance() {
6247
+ this._assertActive("rebalance");
4183
6248
  return this.l1.rebalance();
4184
6249
  }
4185
6250
  /**
@@ -4188,6 +6253,7 @@ return 0
4188
6253
  * Only reflects L1 state — does not query Redis or disk.
4189
6254
  */
4190
6255
  ttl(cacheKey) {
6256
+ this._assertActive("ttl");
4191
6257
  return this.l1.ttl(this.nk(cacheKey));
4192
6258
  }
4193
6259
  /**
@@ -4195,6 +6261,7 @@ return 0
4195
6261
  * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
4196
6262
  */
4197
6263
  has(cacheKey) {
6264
+ this._assertActive("has");
4198
6265
  return this.l1.has(this.nk(cacheKey));
4199
6266
  }
4200
6267
  // ── Iteration ─────────────────────────────────────────────────────────────
@@ -4205,6 +6272,7 @@ return 0
4205
6272
  * for (const key of cache.keys()) console.log(key);
4206
6273
  */
4207
6274
  *keys() {
6275
+ this._assertActive("keys");
4208
6276
  const prefix = this._namespace ? this._namespace + ":" : "";
4209
6277
  for (const key of this.l1.liveKeys()) {
4210
6278
  if (prefix && !key.startsWith(prefix)) continue;
@@ -4219,6 +6287,7 @@ return 0
4219
6287
  * for (const val of cache.values<User>()) console.log(val.id);
4220
6288
  */
4221
6289
  *values() {
6290
+ this._assertActive("values");
4222
6291
  const prefix = this._namespace ? this._namespace + ":" : "";
4223
6292
  if (!prefix) {
4224
6293
  yield* this.l1.liveValues();
@@ -4237,6 +6306,7 @@ return 0
4237
6306
  * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
4238
6307
  */
4239
6308
  *entries() {
6309
+ this._assertActive("entries");
4240
6310
  const prefix = this._namespace ? this._namespace + ":" : "";
4241
6311
  for (const [key, entry] of this.l1.liveEntries()) {
4242
6312
  if (prefix && !key.startsWith(prefix)) continue;
@@ -4264,6 +6334,7 @@ return 0
4264
6334
  * `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
4265
6335
  */
4266
6336
  scan(fn) {
6337
+ this._assertActive("scan");
4267
6338
  const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
4268
6339
  this.l1.scan((key, entry, pfx) => {
4269
6340
  const value = entry.value !== void 0 ? entry.value : entry.data;
@@ -4277,6 +6348,7 @@ return 0
4277
6348
  * @param newTtlSeconds - The new TTL from now, in seconds.
4278
6349
  */
4279
6350
  async touch(cacheKey, newTtlSeconds) {
6351
+ this._assertActive("touch");
4280
6352
  const k = this.nk(cacheKey);
4281
6353
  const hit = this.l1.touch(k, newTtlSeconds * 1e3);
4282
6354
  if (hit && !this._redisDisabled) {
@@ -4297,13 +6369,14 @@ return 0
4297
6369
  * if (fresh !== null) return fresh; // serve from L1, no network hop
4298
6370
  */
4299
6371
  getIfFresh(cacheKey) {
6372
+ this._assertActive("getIfFresh");
4300
6373
  const k = this.nk(cacheKey);
4301
6374
  const entry = this.l1.getEntry(k);
4302
6375
  if (!entry) return null;
4303
6376
  const now = Date.now();
4304
6377
  if (entry.expiresAt <= now) return null;
4305
6378
  if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
4306
- return entry.value !== void 0 ? entry.value : (0, import_msgpackr3.unpack)(entry.data);
6379
+ return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
4307
6380
  }
4308
6381
  /**
4309
6382
  * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
@@ -4314,6 +6387,7 @@ return 0
4314
6387
  * const val = await cache.peek<User>('user:123');
4315
6388
  */
4316
6389
  async peek(cacheKey) {
6390
+ this._assertActive("peek");
4317
6391
  const k = this.nk(cacheKey);
4318
6392
  const l1Hit = this.l1.get(k);
4319
6393
  if (l1Hit !== null) {
@@ -4323,21 +6397,32 @@ return 0
4323
6397
  if (this.opts.frozen) deepFreeze(val);
4324
6398
  return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
4325
6399
  }
4326
- if (!this._diskDisabled) {
4327
- const diskHit = this.disk.load(k);
4328
- if (diskHit !== null) {
4329
- const promoted = this.l1.importEntries(
4330
- [{ key: k, entry: diskHit }],
4331
- this.opts.forbiddenSnapshotPrefixes
4332
- );
4333
- if (promoted > 0) {
4334
- const l1Check = this.l1.get(k);
4335
- if (l1Check !== null) {
4336
- this.counters.gets++;
4337
- this.counters.diskHits++;
4338
- const val = l1Check.value;
4339
- if (this.opts.frozen) deepFreeze(val);
4340
- return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6400
+ if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
6401
+ if (this._isTombstonedByPattern(k)) {
6402
+ try {
6403
+ this.disk.delete(k);
6404
+ } catch {
6405
+ }
6406
+ } else if (this.watchdog.isDiskAllowed()) {
6407
+ const diskStart = performance.now();
6408
+ const diskHit = this.disk.load(k);
6409
+ const diskElapsed = performance.now() - diskStart;
6410
+ this.watchdog.recordDisk(diskElapsed);
6411
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6412
+ if (diskHit !== null) {
6413
+ const promoted = this.l1.importEntries(
6414
+ [{ key: k, entry: diskHit }],
6415
+ this.opts.forbiddenSnapshotPrefixes
6416
+ );
6417
+ if (promoted > 0) {
6418
+ const l1Check = this.l1.get(k);
6419
+ if (l1Check !== null) {
6420
+ this.counters.gets++;
6421
+ this.counters.diskHits++;
6422
+ const val = l1Check.value;
6423
+ if (this.opts.frozen) deepFreeze(val);
6424
+ return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
6425
+ }
4341
6426
  }
4342
6427
  }
4343
6428
  }
@@ -4345,7 +6430,10 @@ return 0
4345
6430
  if (!this._redisDisabled && !this.cb.isOpen) {
4346
6431
  try {
4347
6432
  const client = await this.getRedis();
6433
+ const redisStart = performance.now();
4348
6434
  const raw = await client.get(k);
6435
+ const redisElapsed = performance.now() - redisStart;
6436
+ this.watchdog.recordRedis(redisElapsed);
4349
6437
  if (raw !== null) {
4350
6438
  const parsed = await this._decryptAndDeserialize(raw);
4351
6439
  this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
@@ -4372,90 +6460,138 @@ return 0
4372
6460
  * `(key) => number` so heterogeneous TTLs can be batched in one call.
4373
6461
  */
4374
6462
  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
- }
6463
+ this._assertActive("mget");
6464
+ const span = this._startSpan("tricache.mget");
6465
+ if (this.opts.tracer) {
6466
+ span.setAttribute("cache.batch.size", keys.length);
4388
6467
  }
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] = "";
6468
+ try {
6469
+ const result = Array.from({ length: keys.length });
6470
+ const missIndexes = [];
6471
+ const missKeys = [];
6472
+ for (let i = 0; i < keys.length; i++) {
6473
+ const k = this.nk(keys[i]);
6474
+ const entry = this.l1.getEntry(k);
6475
+ if (entry && entry.expiresAt > Date.now()) {
6476
+ result[i] = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
6477
+ this.counters.l1Hits++;
6478
+ } else {
6479
+ missIndexes.push(i);
6480
+ missKeys.push(keys[i]);
6481
+ }
6482
+ }
6483
+ if (missKeys.length === 0) {
6484
+ if (this.opts.tracer) {
6485
+ span.setAttribute("cache.hits", keys.length);
6486
+ span.setAttribute("cache.misses", 0);
6487
+ span.setAttribute("cache.l1_hits", keys.length);
6488
+ span.setAttribute("cache.l2_hits", 0);
6489
+ }
6490
+ return result;
6491
+ }
6492
+ let l2HitCount = 0;
6493
+ if (!this._redisDisabled) {
6494
+ try {
6495
+ const client = await this.getRedis();
6496
+ const nsKeys = missKeys.map((k) => this.nk(k));
6497
+ const pipeline = client.multi();
6498
+ for (const nk of nsKeys) pipeline.get(nk);
6499
+ const redisStart = performance.now();
6500
+ const raws = await pipeline.exec();
6501
+ const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
6502
+ this.watchdog.recordRedis(redisElapsed);
6503
+ this.cb.onSuccess();
6504
+ for (let j = 0; j < missKeys.length; j++) {
6505
+ const raw = raws[j] ? raws[j][1] : null;
6506
+ const idx = missIndexes[j];
6507
+ if (raw) {
6508
+ const parsed = await this._decryptAndDeserialize(raw);
6509
+ const k = nsKeys[j];
6510
+ const p = priority ?? inferPriority(missKeys[j]);
6511
+ this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
6512
+ this.counters.l2Hits++;
6513
+ l2HitCount++;
6514
+ result[idx] = parsed;
6515
+ missIndexes[j] = -1;
6516
+ missKeys[j] = "";
6517
+ }
4410
6518
  }
6519
+ const remainingIdx = missIndexes.filter((i) => i >= 0);
6520
+ const remainingKeys = missKeys.filter((k) => k !== "");
6521
+ missIndexes.length = 0;
6522
+ missKeys.length = 0;
6523
+ missIndexes.push(...remainingIdx);
6524
+ missKeys.push(...remainingKeys);
6525
+ } catch (err) {
6526
+ this.cb.onFailure();
6527
+ this.logger.debug("mget: Redis unavailable, continuing to disk/fetch", { error: err.message });
4411
6528
  }
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
6529
  }
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);
6530
+ if (!this._diskDisabled && missKeys.length > 0) {
6531
+ for (let j = missKeys.length - 1; j >= 0; j--) {
6532
+ const k = this.nk(missKeys[j]);
6533
+ if (this._pendingDiskDeletes.has(k)) continue;
6534
+ if (this._isTombstonedByPattern(k)) {
6535
+ try {
6536
+ this.disk.delete(k);
6537
+ } catch {
6538
+ }
6539
+ continue;
6540
+ }
6541
+ if (!this.watchdog.isDiskAllowed()) continue;
6542
+ const diskStart = performance.now();
6543
+ const diskHit = this.disk.load(k);
6544
+ const diskElapsed = performance.now() - diskStart;
6545
+ this.watchdog.recordDisk(diskElapsed);
6546
+ this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
6547
+ if (diskHit !== null) {
6548
+ const promoted = this.l1.importEntries(
6549
+ [{ key: k, entry: diskHit }],
6550
+ this.opts.forbiddenSnapshotPrefixes
6551
+ );
6552
+ if (promoted > 0) {
6553
+ const l1Check = this.l1.get(k);
6554
+ if (l1Check !== null) {
6555
+ this.counters.diskHits++;
6556
+ result[missIndexes[j]] = l1Check.value;
6557
+ missIndexes.splice(j, 1);
6558
+ missKeys.splice(j, 1);
6559
+ }
4440
6560
  }
4441
6561
  }
4442
6562
  }
4443
6563
  }
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);
6564
+ if (missKeys.length > 0) {
6565
+ this.counters.fetches++;
6566
+ const fetched = await fetchFn(missKeys);
6567
+ const setPromises = [];
6568
+ for (let j = 0; j < missKeys.length; j++) {
6569
+ const v = fetched[missKeys[j]];
6570
+ result[missIndexes[j]] = v;
6571
+ if (v !== void 0) {
6572
+ const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
6573
+ setPromises.push(this.set(missKeys[j], v, resolvedTtl, priority));
6574
+ }
6575
+ }
6576
+ if (setPromises.length > 0) {
6577
+ await Promise.all(setPromises);
4455
6578
  }
4456
6579
  }
6580
+ if (this.opts.tracer) {
6581
+ const finalMisses = missKeys.length;
6582
+ const totalHits = keys.length - finalMisses;
6583
+ span.setAttribute("cache.hits", totalHits);
6584
+ span.setAttribute("cache.misses", finalMisses);
6585
+ span.setAttribute("cache.l2_hits", l2HitCount);
6586
+ }
6587
+ return result;
6588
+ } catch (err) {
6589
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
6590
+ span.recordException?.(err);
6591
+ throw err;
6592
+ } finally {
6593
+ span.end();
4457
6594
  }
4458
- return result;
4459
6595
  }
4460
6596
  /**
4461
6597
  * Returns a Promise that resolves once the cache is fully initialised and any
@@ -4482,12 +6618,25 @@ return 0
4482
6618
  * });
4483
6619
  */
4484
6620
  async mset(entries) {
6621
+ this._assertActive("mset");
6622
+ const span = this._startSpan("tricache.mset");
4485
6623
  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
- }));
6624
+ if (this.opts.tracer) {
6625
+ span.setAttribute("cache.batch.size", keys.length);
6626
+ }
6627
+ try {
6628
+ await Promise.all(keys.map((key) => {
6629
+ const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
6630
+ const hasOpts = tags?.length || dependsOn?.length;
6631
+ return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
6632
+ }));
6633
+ } catch (err) {
6634
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
6635
+ span.recordException?.(err);
6636
+ throw err;
6637
+ } finally {
6638
+ span.end();
6639
+ }
4491
6640
  }
4492
6641
  /**
4493
6642
  * Batch delete — delete multiple exact keys in a single call.
@@ -4497,7 +6646,20 @@ return 0
4497
6646
  * await cache.mdel(['user:1', 'user:2', 'user:3']);
4498
6647
  */
4499
6648
  async mdel(keys) {
4500
- await Promise.all(keys.map((k) => this.delete(k)));
6649
+ this._assertActive("mdel");
6650
+ const span = this._startSpan("tricache.mdel");
6651
+ if (this.opts.tracer) {
6652
+ span.setAttribute("cache.batch.size", keys.length);
6653
+ }
6654
+ try {
6655
+ await Promise.all(keys.map((k) => this.delete(k)));
6656
+ } catch (err) {
6657
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
6658
+ span.recordException?.(err);
6659
+ throw err;
6660
+ } finally {
6661
+ span.end();
6662
+ }
4501
6663
  }
4502
6664
  /**
4503
6665
  * Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
@@ -4512,6 +6674,7 @@ return 0
4512
6674
  * console.log(`Warmed ${loaded} keys from Redis`);
4513
6675
  */
4514
6676
  async warmFromL2(pattern, opts) {
6677
+ this._assertActive("warmFromL2");
4515
6678
  if (this._redisDisabled) return 0;
4516
6679
  try {
4517
6680
  const client = await this.getRedis();
@@ -4526,7 +6689,6 @@ return 0
4526
6689
  const results = await pl.exec();
4527
6690
  this.cb.onSuccess();
4528
6691
  let loaded = 0;
4529
- const now = Date.now();
4530
6692
  for (let i = 0; i < matchedKeys.length; i++) {
4531
6693
  const [err, raw] = results[i];
4532
6694
  if (err || raw == null) continue;
@@ -4538,7 +6700,6 @@ return 0
4538
6700
  } catch {
4539
6701
  }
4540
6702
  }
4541
- void now;
4542
6703
  this.logger.info("warmFromL2 complete", {
4543
6704
  pattern,
4544
6705
  matched: matchedKeys.length,
@@ -4560,45 +6721,71 @@ return 0
4560
6721
  * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
4561
6722
  */
4562
6723
  async invalidateTag(tag) {
4563
- if (this.opts.tagStrategy === "generational") {
4564
- let newVer = 1;
6724
+ this._assertActive("invalidateTag");
6725
+ const span = this._startSpan("tricache.invalidate_tag");
6726
+ if (this.opts.tracer) {
6727
+ span.setAttribute("cache.tag", tag);
6728
+ span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
6729
+ }
6730
+ try {
6731
+ if (this.opts.tagStrategy === "generational") {
6732
+ let newVer = 1;
6733
+ if (!this._redisDisabled) {
6734
+ try {
6735
+ const client = await this.getRedis();
6736
+ newVer = await client.incr(this.nk(`tag_ver:${tag}`));
6737
+ } catch (err) {
6738
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
6739
+ const current = this.tagVersions.get(tag)?.version ?? 0;
6740
+ newVer = current + 1;
6741
+ }
6742
+ } else {
6743
+ const current = this.tagVersions.get(tag)?.version ?? 0;
6744
+ newVer = current + 1;
6745
+ }
6746
+ this._setLocalTagVersion(tag, newVer, performance.now());
6747
+ if (this.opts.awaitInvalidationBackplane) {
6748
+ await this.publishInvalidation("tag_incr", tag, newVer, false, true);
6749
+ } else {
6750
+ void this.publishInvalidation("tag_incr", tag, newVer, false, true);
6751
+ }
6752
+ return;
6753
+ }
6754
+ const tagKey = this.nk(`_tag_:${tag}`);
6755
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
6756
+ for (const k of members) {
6757
+ this.l1.delete(k);
6758
+ this._bumpKeyMutation(k);
6759
+ this._pendingDiskDeletes.add(k);
6760
+ setImmediate(() => {
6761
+ try {
6762
+ if (!this._diskDisabled) this.disk.delete(k);
6763
+ } finally {
6764
+ this._pendingDiskDeletes.delete(k);
6765
+ }
6766
+ });
6767
+ }
6768
+ this.tagIndex.delete(tagKey);
4565
6769
  if (!this._redisDisabled) {
4566
6770
  try {
4567
6771
  const client = await this.getRedis();
4568
- newVer = await client.incr(this.nk(`tag_ver:${tag}`));
6772
+ const redisMembers = await client.smembers(tagKey);
6773
+ const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
6774
+ if (toDelete.length > 0) {
6775
+ await client.del(...toDelete, tagKey);
6776
+ } else {
6777
+ await client.del(tagKey);
6778
+ }
4569
6779
  } catch (err) {
4570
6780
  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
6781
  }
4599
- } catch (err) {
4600
- this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
4601
6782
  }
6783
+ } catch (err) {
6784
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
6785
+ span.recordException?.(err);
6786
+ throw err;
6787
+ } finally {
6788
+ span.end();
4602
6789
  }
4603
6790
  }
4604
6791
  /**
@@ -4614,13 +6801,14 @@ return 0
4614
6801
  * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
4615
6802
  */
4616
6803
  async invalidateTags(tags) {
6804
+ this._assertActive("invalidateTags");
4617
6805
  if (tags.length === 0) return;
4618
6806
  if (tags.length === 1) {
4619
6807
  await this.invalidateTag(tags[0]);
4620
6808
  return;
4621
6809
  }
4622
6810
  if (this.opts.tagStrategy === "generational") {
4623
- const now = Date.now();
6811
+ const now = performance.now();
4624
6812
  if (!this._redisDisabled) {
4625
6813
  try {
4626
6814
  const client = await this.getRedis();
@@ -4631,7 +6819,11 @@ return 0
4631
6819
  const [err, newVer] = results[i] ?? [null, null];
4632
6820
  const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
4633
6821
  this._setLocalTagVersion(tags[i], ver, now);
4634
- void this.publishInvalidation("tag_incr", tags[i], ver);
6822
+ if (this.opts.awaitInvalidationBackplane) {
6823
+ await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
6824
+ } else {
6825
+ void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
6826
+ }
4635
6827
  }
4636
6828
  return;
4637
6829
  } catch (err) {
@@ -4641,7 +6833,11 @@ return 0
4641
6833
  for (const tag of tags) {
4642
6834
  const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
4643
6835
  this._setLocalTagVersion(tag, ver, now);
4644
- void this.publishInvalidation("tag_incr", tag, ver);
6836
+ if (this.opts.awaitInvalidationBackplane) {
6837
+ await this.publishInvalidation("tag_incr", tag, ver, false, true);
6838
+ } else {
6839
+ void this.publishInvalidation("tag_incr", tag, ver, false, true);
6840
+ }
4645
6841
  }
4646
6842
  return;
4647
6843
  }
@@ -4656,7 +6852,15 @@ return 0
4656
6852
  }
4657
6853
  for (const k of allMembers) {
4658
6854
  this.l1.delete(k);
4659
- this.disk.delete(k);
6855
+ this._bumpKeyMutation(k);
6856
+ this._pendingDiskDeletes.add(k);
6857
+ setImmediate(() => {
6858
+ try {
6859
+ if (!this._diskDisabled) this.disk.delete(k);
6860
+ } finally {
6861
+ this._pendingDiskDeletes.delete(k);
6862
+ }
6863
+ });
4660
6864
  }
4661
6865
  if (!this._redisDisabled) {
4662
6866
  try {
@@ -4693,6 +6897,7 @@ return 0
4693
6897
  * `l2` is `null` when Redis is disabled.
4694
6898
  */
4695
6899
  async ping() {
6900
+ this._assertActive("ping");
4696
6901
  const t0 = Date.now();
4697
6902
  this.l1.has("__ping__");
4698
6903
  const l1 = Date.now() - t0;
@@ -4712,12 +6917,67 @@ return 0
4712
6917
  }
4713
6918
  return { l1, disk, l2 };
4714
6919
  }
6920
+ /**
6921
+ * Health and readiness diagnostics for container orchestrators (e.g. Kubernetes, ECS, Nomad).
6922
+ *
6923
+ * ─────────────────────────────────────────────────────────────────────────────
6924
+ * ⚠️ CRITICAL CONTAINER PROBE SEMANTICS (Liveness vs. Readiness):
6925
+ * ─────────────────────────────────────────────────────────────────────────────
6926
+ * ❌ NEVER bind `degraded` checks or `cache.health()` to your Liveness Probe (/livez, /healthz).
6927
+ * If an SRE hooks degraded status into liveness, a storage-starved or EBS-throttled pod
6928
+ * will be killed by the kubelet, triggering a cluster-wide cascading restart shockwave.
6929
+ * Liveness probes must only check that the event loop / process is alive.
6930
+ *
6931
+ * ✅ BIND degraded checks strictly to your Readiness Probe (/ready, /readyz).
6932
+ * A degraded cache (e.g. EBS latency spike, quota watermark pruning, or open Redis circuit)
6933
+ * can shed traffic at the ingress load balancer while the Node.js process remains
6934
+ * alive to drain in-flight promises and heal its local storage.
6935
+ *
6936
+ * By default, `healthy` remains `true` even when degraded (graceful local degradation).
6937
+ * Set `failReadinessOnDegraded: true` in CacheOptions if you want your Readiness probe
6938
+ * to route ingress traffic away while degraded.
6939
+ * ─────────────────────────────────────────────────────────────────────────────
6940
+ */
6941
+ health() {
6942
+ const watchdogTel = this.watchdog.getTelemetry();
6943
+ const diskPruning = !this._diskDisabled && this.disk.isPruning;
6944
+ const diskLowSpace = !this._diskDisabled && this.disk.hostVolumeLowSpace;
6945
+ const circuitOpen = this.cb.isOpen;
6946
+ const latencyBypass = watchdogTel.bypassActive;
6947
+ const degraded = circuitOpen || latencyBypass || diskPruning || diskLowSpace;
6948
+ const healthy = this.opts.failReadinessOnDegraded ? !degraded : true;
6949
+ const reasons = [];
6950
+ if (circuitOpen) reasons.push("redis_circuit_breaker_open");
6951
+ if (latencyBypass) reasons.push(`disk_latency_bypass_stage_${watchdogTel.bypassStage}`);
6952
+ if (diskPruning) reasons.push("disk_quota_watermark_pruning_active");
6953
+ if (diskLowSpace) reasons.push("disk_host_volume_low_space");
6954
+ return {
6955
+ healthy,
6956
+ degraded,
6957
+ reasons,
6958
+ details: {
6959
+ redisConnected: !circuitOpen && !this._redisDisabled,
6960
+ circuitBreakerState: this.cb.currentState,
6961
+ diskPruningActive: diskPruning,
6962
+ diskHostVolumeLowSpace: diskLowSpace,
6963
+ watchdog: watchdogTel
6964
+ }
6965
+ };
6966
+ }
6967
+ /**
6968
+ * Direct access to the internal tier latency watchdog instance.
6969
+ * Used for diagnostics, canary probes, and control-loop tuning.
6970
+ */
6971
+ getLatencyWatchdog() {
6972
+ return this.watchdog;
6973
+ }
4715
6974
  /**
4716
6975
  * Export all live L1 entries to Redis via a single pipeline.
4717
6976
  * Useful for warming a new Redis instance or for zero-downtime failover.
4718
6977
  * Returns the number of keys written.
4719
6978
  */
4720
6979
  async drainToL2() {
6980
+ this._assertActive("drainToL2");
4721
6981
  if (this._redisDisabled) return 0;
4722
6982
  try {
4723
6983
  const client = await this.getRedis();
@@ -4761,6 +7021,7 @@ return 0
4761
7021
  * if (!claimed) return res.status(409).json({ error: 'duplicate request' });
4762
7022
  */
4763
7023
  async setIfAbsent(cacheKey, value, ttlSeconds = 300, priority) {
7024
+ this._assertActive("setIfAbsent");
4764
7025
  const k = this.nk(cacheKey);
4765
7026
  if (this.l1.has(k)) return false;
4766
7027
  if (!this._redisDisabled) {
@@ -4779,6 +7040,8 @@ return 0
4779
7040
  }
4780
7041
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
4781
7042
  const p = priority ?? inferPriority(cacheKey);
7043
+ this._bumpKeyMutation(k);
7044
+ this._pendingDiskDeletes.delete(k);
4782
7045
  this.l1.set(k, value, ttlMs, p);
4783
7046
  this.counters.sets++;
4784
7047
  return true;
@@ -4797,6 +7060,7 @@ return 0
4797
7060
  * @param options TTL, acquire timeout, and retry polling intervals.
4798
7061
  */
4799
7062
  async lock(resourceKey, fn, options) {
7063
+ this._assertActive("lock");
4800
7064
  const ttlSeconds = Math.max(1, options?.ttl ?? 30);
4801
7065
  const acquireTimeout = Math.max(0, options?.acquireTimeout ?? 5e3);
4802
7066
  const retryInterval = Math.max(10, options?.retryInterval ?? 100);
@@ -4823,6 +7087,10 @@ return 0
4823
7087
  }
4824
7088
  } catch (err) {
4825
7089
  if (err.message.startsWith("Failed to acquire lock")) throw err;
7090
+ const failClosed = options?.failClosedOnRedisError ?? this.opts.lockFailClosed;
7091
+ if (failClosed) {
7092
+ throw new Error(`Distributed lock acquisition failed for resource "${resourceKey}" due to Redis error: ${err.message}`);
7093
+ }
4826
7094
  this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
4827
7095
  resourceKey,
4828
7096
  error: err.message
@@ -4959,7 +7227,7 @@ return 0
4959
7227
  if (visited.has(dep)) continue;
4960
7228
  this.l1.delete(dep);
4961
7229
  if (!this._diskDisabled) this.disk.delete(dep);
4962
- void this.publishInvalidation("del", dep);
7230
+ void this.publishInvalidation("del", dep, void 0, false, true);
4963
7231
  this.logger.debug("Dependency cascade: invalidated dependent key", {
4964
7232
  trigger: deletedKey.slice(0, 60),
4965
7233
  dependent: dep.slice(0, 60)
@@ -5024,12 +7292,36 @@ return 0
5024
7292
  evictions: c.oomEvictions,
5025
7293
  lastTriggeredAt: c.oomLastAt
5026
7294
  },
7295
+ ...this.opts.remoteSnapshot && {
7296
+ remoteSnapshot: {
7297
+ enabled: true,
7298
+ uploads: c.remoteSnapshotUploads,
7299
+ downloads: c.remoteSnapshotDownloads,
7300
+ errors: c.remoteSnapshotErrors,
7301
+ lastUploadedAt: c.remoteSnapshotLastUploadedAt,
7302
+ lastDownloadedAt: c.remoteSnapshotLastDownloadedAt
7303
+ }
7304
+ },
7305
+ ...this.opts.crossRegion && {
7306
+ crossRegion: {
7307
+ enabled: true,
7308
+ currentRegion: this.opts.crossRegion.currentRegion,
7309
+ sent: c.crossRegionSent,
7310
+ received: c.crossRegionReceived,
7311
+ deduplicated: c.crossRegionDeduplicated,
7312
+ errors: c.crossRegionErrors
7313
+ }
7314
+ },
5027
7315
  l1: {
5028
7316
  entries: l1s.entries,
5029
7317
  sizeBytes: this.l1.memoryUsage,
5030
7318
  maxBytes: this.opts.l1MaxBytes
5031
7319
  },
5032
- disk: { ...this.disk.stats, disabled: this._diskDisabled },
7320
+ disk: {
7321
+ ...this.disk.stats,
7322
+ disabled: this._diskDisabled,
7323
+ latencyWatchdog: this.watchdog.getTelemetry()
7324
+ },
5033
7325
  ...this.latencyTracker && {
5034
7326
  adaptiveTtl: {
5035
7327
  enabled: true,
@@ -5042,9 +7334,16 @@ return 0
5042
7334
  this.opts.adaptiveTtlMaxMs
5043
7335
  )
5044
7336
  }
7337
+ },
7338
+ ...this.pipeliner && {
7339
+ pipelining: this.pipeliner.stats
5045
7340
  }
5046
7341
  };
5047
7342
  }
7343
+ /** Return auto-pipelining metrics, or null if pipelining is disabled. */
7344
+ getPipelinerStats() {
7345
+ return this.pipeliner ? this.pipeliner.stats : null;
7346
+ }
5048
7347
  /**
5049
7348
  * Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
5050
7349
  * Paste the result into your `/metrics` endpoint.
@@ -5084,6 +7383,18 @@ return 0
5084
7383
  gauge("l1_entries", m.l1.entries, "Current L1 entry count");
5085
7384
  gauge("l1_size_bytes", m.l1.sizeBytes, "Current L1 used bytes");
5086
7385
  gauge("disk_files", m.disk.files, "Current L1.5 disk file count");
7386
+ if (m.disk.latencyWatchdog) {
7387
+ gauge("disk_latency_bypass_stage", m.disk.latencyWatchdog.bypassStage, "Disk latency watchdog bypass stage (0: normal, 1: 25%, 2: 75%, 3: 100%)");
7388
+ gauge("disk_p95_ms", m.disk.latencyWatchdog.diskP95Ms, "Disk read p95 latency in ms");
7389
+ gauge("redis_p95_ms", m.disk.latencyWatchdog.redisP95Ms, "Redis read p95 latency in ms");
7390
+ counter("disk_bypassed_events", m.disk.latencyWatchdog.bypassedTotal, "Total disk bypass activation events");
7391
+ }
7392
+ if (m.disk.pruning) {
7393
+ counter("disk_spills_shed", m.disk.pruning.spillsShedTotal, "Total disk spills shed due to pruning or low disk space");
7394
+ counter("disk_prune_rounds", m.disk.pruning.pruneRounds, "Total high-watermark disk prune rounds");
7395
+ counter("disk_entries_pruned", m.disk.pruning.entriesPruned, "Total entries removed by watermark pruning");
7396
+ counter("disk_low_space_pauses", m.disk.pruning.hostVolumeLowSpacePauses, "Total times spills paused due to <10% host volume space");
7397
+ }
5087
7398
  gauge(
5088
7399
  "bloom_false_positive_rate",
5089
7400
  m.bloom.falsePositiveRate,
@@ -5105,6 +7416,17 @@ return 0
5105
7416
  "Emergency L1 eviction rounds triggered by heap pressure"
5106
7417
  );
5107
7418
  }
7419
+ if (m.remoteSnapshot?.enabled) {
7420
+ counter("remote_snapshot_uploads", m.remoteSnapshot.uploads, "Total remote snapshot uploads");
7421
+ counter("remote_snapshot_downloads", m.remoteSnapshot.downloads, "Total remote snapshot downloads");
7422
+ counter("remote_snapshot_errors", m.remoteSnapshot.errors, "Total remote snapshot errors");
7423
+ }
7424
+ if (m.crossRegion?.enabled) {
7425
+ counter("cross_region_sent", m.crossRegion.sent, "Total cross-region invalidations broadcast");
7426
+ counter("cross_region_received", m.crossRegion.received, "Total cross-region invalidations received");
7427
+ counter("cross_region_deduplicated", m.crossRegion.deduplicated, "Total cross-region invalidations deduplicated or self-filtered");
7428
+ counter("cross_region_errors", m.crossRegion.errors, "Total cross-region relay errors");
7429
+ }
5108
7430
  return lines.join("\n");
5109
7431
  }
5110
7432
  // ── Lifecycle ────────────────────────────────────────────────────────────
@@ -5114,6 +7436,7 @@ return 0
5114
7436
  * the previous key for seamless fallback decryption of existing cache entries.
5115
7437
  */
5116
7438
  async rotateEncryptionKey(newKeyBase64, newMode) {
7439
+ this._assertActive("rotateEncryptionKey");
5117
7440
  this.enc.rotateKey(newKeyBase64, newMode);
5118
7441
  if (this._workerPool) {
5119
7442
  await this._workerPool.drainAndReinit(this.enc.toWorkerInit());
@@ -5123,23 +7446,33 @@ return 0
5123
7446
  /** Close Redis connections and stop all background timers. */
5124
7447
  async destroy() {
5125
7448
  this._destroyed = true;
7449
+ this._pendingDiskDeletes.clear();
7450
+ this._keyMutationEpochs.clear();
7451
+ const g = globalThis;
7452
+ const key = _CacheService.globalKey(this.opts);
7453
+ if (g[key] === this) {
7454
+ delete g[key];
7455
+ }
5126
7456
  if (this.cleanupInterval) clearInterval(this.cleanupInterval);
5127
7457
  if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
5128
7458
  if (this.oomInterval) clearInterval(this.oomInterval);
5129
7459
  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;
7460
+ if (this.remoteSnapshotInterval) {
7461
+ clearInterval(this.remoteSnapshotInterval);
7462
+ this.remoteSnapshotInterval = null;
5134
7463
  }
7464
+ ProcessTerminationBus.unregister(this);
7465
+ this._shutdownHandler = null;
5135
7466
  if (this._workerPool) {
5136
7467
  await this._workerPool.destroy();
5137
7468
  this._workerPool = null;
5138
7469
  }
5139
7470
  if (this.subClient) {
5140
- try {
5141
- this.subClient.disconnect();
5142
- } catch {
7471
+ if (!this.opts.redisSubClient) {
7472
+ try {
7473
+ this.subClient.disconnect();
7474
+ } catch {
7475
+ }
5143
7476
  }
5144
7477
  this.subClient = null;
5145
7478
  }
@@ -5151,14 +7484,33 @@ return 0
5151
7484
  this.streamClient = null;
5152
7485
  }
5153
7486
  if (this.redis) {
5154
- try {
5155
- await this.redis.disconnect();
5156
- } catch {
7487
+ if (!this.opts.redisClient) {
7488
+ try {
7489
+ await this.redis.disconnect();
7490
+ } catch {
7491
+ }
5157
7492
  }
5158
7493
  this.redis = null;
5159
7494
  }
7495
+ if (this._ipcServer) {
7496
+ await this._ipcServer.close();
7497
+ this._ipcServer = void 0;
7498
+ }
5160
7499
  if (!this._diskDisabled) this.disk.close();
5161
7500
  }
7501
+ /**
7502
+ * Return the active IPC telemetry server instance, if enabled.
7503
+ */
7504
+ getIpcServer() {
7505
+ return this._ipcServer;
7506
+ }
7507
+ /**
7508
+ * Return real-time telemetry and metrics for the Window TinyLFU admission policy.
7509
+ * Returns `undefined` if W-TinyLFU admission is not active.
7510
+ */
7511
+ getWTinyLfuStats() {
7512
+ return this.l1.getWTinyLfuStats();
7513
+ }
5162
7514
  };
5163
7515
  }
5164
7516
  });