tricache 0.7.1 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +87 -1371
- package/dashboards/tricache-alerts.yaml +54 -0
- package/dashboards/tricache-grafana.json +548 -0
- package/dist/cache-service-5MZXFIGK.js +12 -0
- package/dist/cache-service-CyLdpo77.d.ts +871 -0
- package/dist/{chunk-EUGYR7KR.js → chunk-6PQ5MOWR.js} +2871 -490
- package/dist/chunk-7RV5ZVBB.js +1023 -0
- package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
- package/dist/chunk-QNU7B43J.js +687 -0
- package/dist/chunk-UGD4VEPD.js +138 -0
- package/dist/chunk-XZL45ABR.js +108 -0
- package/dist/chunk-ZTSWCFYO.js +135 -0
- package/dist/cli.cjs +2790 -471
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +103 -5
- package/dist/dashboard/index.cjs +1065 -0
- package/dist/dashboard/index.d.ts +183 -0
- package/dist/dashboard/index.js +22 -0
- package/dist/drizzle/index.cjs +2553 -470
- package/dist/drizzle/index.d.ts +3 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +1498 -0
- package/dist/edge/index.d.ts +127 -0
- package/dist/edge/index.js +1109 -0
- package/dist/hono-DQRS1Xd7.d.ts +370 -0
- package/dist/http/index.cjs +2926 -562
- package/dist/http/index.d.ts +109 -23
- package/dist/http/index.js +220 -72
- package/dist/index.cjs +6936 -2518
- package/dist/index.d.ts +547 -30
- package/dist/index.js +104 -5
- package/dist/murmur3-CMGw9PbV.d.ts +98 -0
- package/dist/nestjs/index.cjs +2494 -463
- package/dist/nestjs/index.d.ts +3 -1
- package/dist/nestjs/index.js +6 -3
- package/dist/next/index.cjs +2517 -483
- package/dist/next/index.d.ts +4 -2
- package/dist/next/index.js +14 -10
- package/dist/prisma/index.d.ts +3 -1
- package/dist/serialize-worker.cjs +5 -4
- package/dist/serialize-worker.js +1 -1
- package/dist/{cache-service-D8tIXmzb.d.ts → types-B6krw64X.d.ts} +596 -659
- package/package.json +34 -6
- package/src/adapters/auto-pipeliner.ts +206 -0
- package/src/adapters/node-redis.ts +370 -0
- package/src/cache-service.ts +1339 -402
- package/src/cli.ts +120 -2
- package/src/codec.ts +72 -0
- package/src/cross-region.ts +245 -0
- package/src/dashboard/handler.ts +392 -0
- package/src/dashboard/html.ts +594 -0
- package/src/dashboard/index.ts +195 -0
- package/src/dashboard/types.ts +96 -0
- package/src/disk-tier.ts +449 -47
- package/src/drizzle/index.ts +86 -86
- package/src/edge/adapters/cloudflare-do.ts +130 -0
- package/src/edge/adapters/cloudflare-kv.ts +115 -0
- package/src/edge/adapters/upstash.ts +143 -0
- package/src/edge/cache.ts +797 -0
- package/src/edge/crypto.ts +182 -0
- package/src/edge/hono.ts +203 -0
- package/src/edge/index.ts +37 -0
- package/src/edge/types.ts +230 -0
- package/src/edge/utils/base64.ts +63 -0
- package/src/edge/utils/murmur3.ts +179 -0
- package/src/encryption.ts +127 -5
- package/src/http/express.ts +195 -0
- package/src/http/fastify.ts +260 -0
- package/src/http/index.ts +39 -258
- package/src/http/utils.ts +92 -0
- package/src/index.ts +149 -47
- package/src/ipc-telemetry.ts +481 -0
- package/src/latency-watchdog.ts +282 -0
- package/src/nestjs/decorators.ts +161 -161
- package/src/nestjs/index.ts +23 -23
- package/src/nestjs/tricache.module.ts +104 -104
- package/src/nestjs/tricache.store.ts +97 -97
- package/src/nestjs/types.ts +79 -79
- package/src/next/cache-handler.ts +12 -9
- package/src/next/index.ts +37 -37
- package/src/next/isr-handler.ts +105 -105
- package/src/next/types.ts +130 -130
- package/src/remote-snapshot.ts +153 -0
- package/src/serialize-worker.ts +120 -120
- package/src/sigv4-snapshot-adapter.ts +260 -0
- package/src/smart-memory-cache.ts +91 -8
- package/src/types.ts +290 -2
- package/src/utils/cgroup.ts +100 -0
- package/src/utils/tracing.ts +54 -0
- package/src/wasm/bloom-filter-wasm.ts +109 -102
- package/src/worker-pool.ts +299 -299
- package/src/wtiny-lfu.ts +624 -0
- package/dist/cache-service-5GATUYAK.js +0 -7
- package/dist/chunk-UBSR5UYA.js +0 -0
package/dist/nestjs/index.cjs
CHANGED
|
@@ -42,9 +42,43 @@ module.exports = __toCommonJS(nestjs_exports);
|
|
|
42
42
|
|
|
43
43
|
// src/cache-service.ts
|
|
44
44
|
var import_ioredis = require("ioredis");
|
|
45
|
-
|
|
45
|
+
|
|
46
|
+
// src/codec.ts
|
|
47
|
+
var import_msgpackr = require("msgpackr");
|
|
48
|
+
var CacheCodec = class {
|
|
49
|
+
packr;
|
|
50
|
+
constructor(options) {
|
|
51
|
+
const packrOptions = {
|
|
52
|
+
useToJSON: options?.useToJSON ?? true,
|
|
53
|
+
useRecords: options?.useRecords ?? true,
|
|
54
|
+
moreTypes: options?.moreTypes ?? true,
|
|
55
|
+
mapsAsObjects: options?.mapsAsObjects ?? true
|
|
56
|
+
};
|
|
57
|
+
this.packr = new import_msgpackr.Packr(packrOptions);
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Serializes a JavaScript value to a binary MessagePack Buffer.
|
|
61
|
+
*/
|
|
62
|
+
encode(data) {
|
|
63
|
+
const packed = this.packr.pack(data);
|
|
64
|
+
return Buffer.isBuffer(packed) ? packed : Buffer.from(packed.buffer, packed.byteOffset, packed.byteLength);
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Deserializes a binary MessagePack Buffer or Uint8Array back to a JavaScript value.
|
|
68
|
+
*/
|
|
69
|
+
decode(data) {
|
|
70
|
+
return this.packr.unpack(data);
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
var defaultCodec = new CacheCodec({
|
|
74
|
+
useToJSON: true,
|
|
75
|
+
useRecords: true,
|
|
76
|
+
moreTypes: true
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
// src/cache-service.ts
|
|
46
80
|
var import_crypto3 = __toESM(require("crypto"), 1);
|
|
47
|
-
var
|
|
81
|
+
var import_os3 = __toESM(require("os"), 1);
|
|
48
82
|
|
|
49
83
|
// src/worker-pool.ts
|
|
50
84
|
var import_worker_threads = require("worker_threads");
|
|
@@ -249,7 +283,7 @@ function availableCpus() {
|
|
|
249
283
|
}
|
|
250
284
|
|
|
251
285
|
// src/cache-service.ts
|
|
252
|
-
var
|
|
286
|
+
var import_node_v82 = __toESM(require("v8"), 1);
|
|
253
287
|
var import_fs3 = __toESM(require("fs"), 1);
|
|
254
288
|
var import_path3 = __toESM(require("path"), 1);
|
|
255
289
|
|
|
@@ -380,17 +414,17 @@ var CacheEncryption = class {
|
|
|
380
414
|
throw new Error("XOR key must be at least 1 byte");
|
|
381
415
|
}
|
|
382
416
|
this._key = buf;
|
|
383
|
-
if (
|
|
417
|
+
if (resolvedMode !== "xor") {
|
|
384
418
|
this._keyObj = (0, import_crypto.createSecretKey)(buf);
|
|
385
419
|
const _wc = (0, import_crypto.createCipheriv)(
|
|
386
|
-
|
|
420
|
+
resolvedMode,
|
|
387
421
|
this._keyObj,
|
|
388
|
-
Buffer.alloc(
|
|
422
|
+
Buffer.alloc(resolvedMode === "aes-128-ctr" ? CTR_IV_BYTES : IV_BYTES)
|
|
389
423
|
);
|
|
390
424
|
_wc.update(Buffer.alloc(0));
|
|
391
425
|
_wc.final();
|
|
392
426
|
}
|
|
393
|
-
if (
|
|
427
|
+
if (resolvedMode === "xor") {
|
|
394
428
|
logger.warn(
|
|
395
429
|
"Cache obfuscation enabled (XOR). WARNING: XOR is NOT cryptographic \u2014 use only for dev or non-sensitive data."
|
|
396
430
|
);
|
|
@@ -658,15 +692,257 @@ var CacheEncryption = class {
|
|
|
658
692
|
return plain;
|
|
659
693
|
}
|
|
660
694
|
};
|
|
695
|
+
var MAGIC_ENVELOPE = Buffer.from([84, 82, 73, 67, 69, 78, 86, 49]);
|
|
696
|
+
var EnvelopeEncryption = class {
|
|
697
|
+
static isEnvelope(data) {
|
|
698
|
+
return data.length >= MAGIC_LEN && data.subarray(0, MAGIC_LEN).equals(MAGIC_ENVELOPE);
|
|
699
|
+
}
|
|
700
|
+
static async encrypt(data, options) {
|
|
701
|
+
const dek = (0, import_crypto.randomBytes)(32);
|
|
702
|
+
let encryptedKey;
|
|
703
|
+
if (options.kmsEncrypt) {
|
|
704
|
+
encryptedKey = await options.kmsEncrypt(dek);
|
|
705
|
+
} else if (options.publicKey) {
|
|
706
|
+
encryptedKey = (0, import_crypto.publicEncrypt)(
|
|
707
|
+
{
|
|
708
|
+
key: options.publicKey,
|
|
709
|
+
padding: import_crypto.constants.RSA_PKCS1_OAEP_PADDING,
|
|
710
|
+
oaepHash: "sha256"
|
|
711
|
+
},
|
|
712
|
+
dek
|
|
713
|
+
);
|
|
714
|
+
} else {
|
|
715
|
+
throw new Error("EnvelopeEncryption: either publicKey or kmsEncrypt must be provided to encrypt");
|
|
716
|
+
}
|
|
717
|
+
const iv = (0, import_crypto.randomBytes)(IV_BYTES);
|
|
718
|
+
const cipher = (0, import_crypto.createCipheriv)("aes-256-gcm", dek, iv);
|
|
719
|
+
const ct = cipher.update(data);
|
|
720
|
+
cipher.final();
|
|
721
|
+
const tag = cipher.getAuthTag();
|
|
722
|
+
const keyLen = encryptedKey.length;
|
|
723
|
+
const out = Buffer.allocUnsafe(MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES + ct.length);
|
|
724
|
+
MAGIC_ENVELOPE.copy(out, 0);
|
|
725
|
+
out.writeUInt32BE(keyLen, MAGIC_LEN);
|
|
726
|
+
encryptedKey.copy(out, MAGIC_LEN + 4);
|
|
727
|
+
iv.copy(out, MAGIC_LEN + 4 + keyLen);
|
|
728
|
+
tag.copy(out, MAGIC_LEN + 4 + keyLen + IV_BYTES);
|
|
729
|
+
ct.copy(out, MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES);
|
|
730
|
+
return out;
|
|
731
|
+
}
|
|
732
|
+
static async decrypt(data, options) {
|
|
733
|
+
if (!this.isEnvelope(data)) {
|
|
734
|
+
throw new Error("EnvelopeEncryption: invalid header, expected TRICENV1");
|
|
735
|
+
}
|
|
736
|
+
if (data.length < MAGIC_LEN + 4 + IV_BYTES + TAG_BYTES) {
|
|
737
|
+
throw new Error("EnvelopeEncryption: truncated envelope buffer");
|
|
738
|
+
}
|
|
739
|
+
const keyLen = data.readUInt32BE(MAGIC_LEN);
|
|
740
|
+
const minExpected = MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES;
|
|
741
|
+
if (data.length < minExpected) {
|
|
742
|
+
throw new Error("EnvelopeEncryption: truncated envelope buffer (key length mismatch)");
|
|
743
|
+
}
|
|
744
|
+
const encryptedKey = data.subarray(MAGIC_LEN + 4, MAGIC_LEN + 4 + keyLen);
|
|
745
|
+
const iv = data.subarray(MAGIC_LEN + 4 + keyLen, MAGIC_LEN + 4 + keyLen + IV_BYTES);
|
|
746
|
+
const tag = data.subarray(MAGIC_LEN + 4 + keyLen + IV_BYTES, MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES);
|
|
747
|
+
const ct = data.subarray(MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES);
|
|
748
|
+
let dek;
|
|
749
|
+
if (options.kmsDecrypt) {
|
|
750
|
+
dek = await options.kmsDecrypt(encryptedKey);
|
|
751
|
+
} else if (options.privateKey) {
|
|
752
|
+
dek = (0, import_crypto.privateDecrypt)(
|
|
753
|
+
{
|
|
754
|
+
key: options.privateKey,
|
|
755
|
+
padding: import_crypto.constants.RSA_PKCS1_OAEP_PADDING,
|
|
756
|
+
oaepHash: "sha256"
|
|
757
|
+
},
|
|
758
|
+
encryptedKey
|
|
759
|
+
);
|
|
760
|
+
} else {
|
|
761
|
+
throw new Error("EnvelopeEncryption: either privateKey or kmsDecrypt must be provided to decrypt");
|
|
762
|
+
}
|
|
763
|
+
const decipher = (0, import_crypto.createDecipheriv)("aes-256-gcm", dek, iv);
|
|
764
|
+
decipher.setAuthTag(tag);
|
|
765
|
+
const pt = decipher.update(ct);
|
|
766
|
+
decipher.final();
|
|
767
|
+
return pt;
|
|
768
|
+
}
|
|
769
|
+
};
|
|
661
770
|
|
|
662
|
-
// src/
|
|
663
|
-
var
|
|
771
|
+
// src/wtiny-lfu.ts
|
|
772
|
+
var WTinyLfuPolicy = class {
|
|
773
|
+
constructor(capacity, sketch, windowPercent = 0.01, protectedPercent = 0.8) {
|
|
774
|
+
this.sketch = sketch;
|
|
775
|
+
this.maxTotal = Math.max(2, capacity);
|
|
776
|
+
this.maxWindow = Math.max(1, Math.floor(this.maxTotal * windowPercent));
|
|
777
|
+
const mainCapacity = Math.max(1, this.maxTotal - this.maxWindow);
|
|
778
|
+
this.maxProtected = Math.max(1, Math.floor(mainCapacity * protectedPercent));
|
|
779
|
+
this.maxProbation = Math.max(1, mainCapacity - this.maxProtected);
|
|
780
|
+
}
|
|
781
|
+
sketch;
|
|
782
|
+
maxTotal;
|
|
783
|
+
maxWindow;
|
|
784
|
+
maxProtected;
|
|
785
|
+
maxProbation;
|
|
786
|
+
window = /* @__PURE__ */ new Set();
|
|
787
|
+
probation = /* @__PURE__ */ new Set();
|
|
788
|
+
protected_ = /* @__PURE__ */ new Set();
|
|
789
|
+
// Telemetry metrics
|
|
790
|
+
hitCount = 0;
|
|
791
|
+
missCount = 0;
|
|
792
|
+
admissionCount = 0;
|
|
793
|
+
rejectionCount = 0;
|
|
794
|
+
promotionCount = 0;
|
|
795
|
+
demotionCount = 0;
|
|
796
|
+
get windowSize() {
|
|
797
|
+
return this.window.size;
|
|
798
|
+
}
|
|
799
|
+
get probationSize() {
|
|
800
|
+
return this.probation.size;
|
|
801
|
+
}
|
|
802
|
+
get protectedSize() {
|
|
803
|
+
return this.protected_.size;
|
|
804
|
+
}
|
|
805
|
+
onAccess(key) {
|
|
806
|
+
if (this.window.has(key)) {
|
|
807
|
+
this.window.delete(key);
|
|
808
|
+
this.window.add(key);
|
|
809
|
+
this.hitCount++;
|
|
810
|
+
return;
|
|
811
|
+
}
|
|
812
|
+
if (this.protected_.has(key)) {
|
|
813
|
+
this.protected_.delete(key);
|
|
814
|
+
this.protected_.add(key);
|
|
815
|
+
this.hitCount++;
|
|
816
|
+
return;
|
|
817
|
+
}
|
|
818
|
+
if (this.probation.has(key)) {
|
|
819
|
+
this.probation.delete(key);
|
|
820
|
+
this.protected_.add(key);
|
|
821
|
+
this.promotionCount++;
|
|
822
|
+
this.hitCount++;
|
|
823
|
+
if (this.protected_.size > this.maxProtected) {
|
|
824
|
+
const oldestProtKey = this.protected_.values().next().value;
|
|
825
|
+
this.protected_.delete(oldestProtKey);
|
|
826
|
+
this.probation.add(oldestProtKey);
|
|
827
|
+
this.demotionCount++;
|
|
828
|
+
}
|
|
829
|
+
return;
|
|
830
|
+
}
|
|
831
|
+
this.missCount++;
|
|
832
|
+
}
|
|
833
|
+
onSet(key, isUpdate) {
|
|
834
|
+
if (isUpdate) {
|
|
835
|
+
if (this.window.has(key)) {
|
|
836
|
+
this.window.delete(key);
|
|
837
|
+
this.window.add(key);
|
|
838
|
+
} else if (this.protected_.has(key)) {
|
|
839
|
+
this.protected_.delete(key);
|
|
840
|
+
this.protected_.add(key);
|
|
841
|
+
} else if (this.probation.has(key)) {
|
|
842
|
+
this.probation.delete(key);
|
|
843
|
+
this.probation.add(key);
|
|
844
|
+
}
|
|
845
|
+
return { admit: true };
|
|
846
|
+
}
|
|
847
|
+
this.window.add(key);
|
|
848
|
+
if (this.window.size <= this.maxWindow) {
|
|
849
|
+
this.admissionCount++;
|
|
850
|
+
return { admit: true };
|
|
851
|
+
}
|
|
852
|
+
const candKey = this.window.values().next().value;
|
|
853
|
+
this.window.delete(candKey);
|
|
854
|
+
if (this.probation.size + this.protected_.size < this.maxProbation + this.maxProtected) {
|
|
855
|
+
this.probation.add(candKey);
|
|
856
|
+
this.admissionCount++;
|
|
857
|
+
return { admit: true };
|
|
858
|
+
}
|
|
859
|
+
let victimKey;
|
|
860
|
+
let victimIsProbation = true;
|
|
861
|
+
if (this.probation.size > 0) {
|
|
862
|
+
victimKey = this.probation.values().next().value;
|
|
863
|
+
} else {
|
|
864
|
+
victimKey = this.protected_.values().next().value;
|
|
865
|
+
victimIsProbation = false;
|
|
866
|
+
}
|
|
867
|
+
const candFreq = this.sketch.estimate(candKey);
|
|
868
|
+
const victimFreq = this.sketch.estimate(victimKey);
|
|
869
|
+
if (candFreq > victimFreq) {
|
|
870
|
+
if (victimIsProbation) {
|
|
871
|
+
this.probation.delete(victimKey);
|
|
872
|
+
} else {
|
|
873
|
+
this.protected_.delete(victimKey);
|
|
874
|
+
}
|
|
875
|
+
this.probation.add(candKey);
|
|
876
|
+
this.admissionCount++;
|
|
877
|
+
return { admit: true, evictKey: victimKey, candidateKey: candKey };
|
|
878
|
+
} else {
|
|
879
|
+
this.rejectionCount++;
|
|
880
|
+
return { admit: false, candidateKey: candKey };
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
onDelete(key) {
|
|
884
|
+
this.window.delete(key);
|
|
885
|
+
this.probation.delete(key);
|
|
886
|
+
this.protected_.delete(key);
|
|
887
|
+
}
|
|
888
|
+
clear() {
|
|
889
|
+
this.window.clear();
|
|
890
|
+
this.probation.clear();
|
|
891
|
+
this.protected_.clear();
|
|
892
|
+
this.hitCount = 0;
|
|
893
|
+
this.missCount = 0;
|
|
894
|
+
this.admissionCount = 0;
|
|
895
|
+
this.rejectionCount = 0;
|
|
896
|
+
this.promotionCount = 0;
|
|
897
|
+
this.demotionCount = 0;
|
|
898
|
+
}
|
|
899
|
+
getStats() {
|
|
900
|
+
const totalRequests = this.hitCount + this.missCount;
|
|
901
|
+
return {
|
|
902
|
+
capacity: this.maxTotal,
|
|
903
|
+
size: this.window.size + this.probation.size + this.protected_.size,
|
|
904
|
+
windowSize: this.window.size,
|
|
905
|
+
probationSize: this.probation.size,
|
|
906
|
+
protectedSize: this.protected_.size,
|
|
907
|
+
hits: this.hitCount,
|
|
908
|
+
misses: this.missCount,
|
|
909
|
+
hitRate: totalRequests > 0 ? this.hitCount / totalRequests : 0,
|
|
910
|
+
admissions: this.admissionCount,
|
|
911
|
+
rejections: this.rejectionCount,
|
|
912
|
+
promotions: this.promotionCount,
|
|
913
|
+
demotions: this.demotionCount
|
|
914
|
+
};
|
|
915
|
+
}
|
|
916
|
+
getSegment(key) {
|
|
917
|
+
if (this.window.has(key)) return "window";
|
|
918
|
+
if (this.probation.has(key)) return "probation";
|
|
919
|
+
if (this.protected_.has(key)) return "protected";
|
|
920
|
+
return null;
|
|
921
|
+
}
|
|
922
|
+
};
|
|
923
|
+
|
|
924
|
+
// src/edge/utils/base64.ts
|
|
925
|
+
function base64ToUint8Array(base64) {
|
|
926
|
+
const modernU8 = Uint8Array;
|
|
927
|
+
if (typeof modernU8.fromBase64 === "function") {
|
|
928
|
+
return modernU8.fromBase64(base64);
|
|
929
|
+
}
|
|
930
|
+
const binary = globalThis.atob(base64);
|
|
931
|
+
const len = binary.length;
|
|
932
|
+
const bytes = new Uint8Array(len);
|
|
933
|
+
for (let i = 0; i < len; i++) {
|
|
934
|
+
bytes[i] = binary.charCodeAt(i);
|
|
935
|
+
}
|
|
936
|
+
return bytes;
|
|
937
|
+
}
|
|
664
938
|
|
|
665
939
|
// src/wasm/bloom-filter-wasm.ts
|
|
666
940
|
var BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
|
|
667
941
|
var KEY_STAGING_OFFSET = 2e4;
|
|
668
942
|
var MAX_KEY_BYTES = 512;
|
|
669
|
-
var BLOOM_WASM_MODULE = new WebAssembly.Module(
|
|
943
|
+
var BLOOM_WASM_MODULE = new WebAssembly.Module(
|
|
944
|
+
base64ToUint8Array(BLOOM_WASM_BASE64)
|
|
945
|
+
);
|
|
670
946
|
var WasmBloomFilter = class {
|
|
671
947
|
exports;
|
|
672
948
|
mem;
|
|
@@ -901,11 +1177,13 @@ function globMatchParts(parts, first, last, key) {
|
|
|
901
1177
|
var SmartMemoryCache = class {
|
|
902
1178
|
cache = /* @__PURE__ */ new Map();
|
|
903
1179
|
opts;
|
|
1180
|
+
codec;
|
|
904
1181
|
bloom;
|
|
905
1182
|
/** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
|
|
906
1183
|
categoryPrefixes;
|
|
907
1184
|
/** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
|
|
908
1185
|
sketch = new CountMinSketch();
|
|
1186
|
+
wtinyPolicy;
|
|
909
1187
|
totalSize = 0;
|
|
910
1188
|
categoryCount = /* @__PURE__ */ new Map();
|
|
911
1189
|
categorySize = /* @__PURE__ */ new Map();
|
|
@@ -929,8 +1207,12 @@ var SmartMemoryCache = class {
|
|
|
929
1207
|
_evictGPool = Array.from({ length: EVICTION_SAMPLE }, () => ({ key: "", score: 0 }));
|
|
930
1208
|
constructor(opts, existing) {
|
|
931
1209
|
this.opts = opts;
|
|
1210
|
+
this.codec = opts.codec ?? defaultCodec;
|
|
932
1211
|
this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
|
|
933
1212
|
this.categoryPrefixes = Object.keys(opts.categories).filter((k) => k !== "default");
|
|
1213
|
+
if (opts.admissionPolicy === "wtinylfu") {
|
|
1214
|
+
this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch);
|
|
1215
|
+
}
|
|
934
1216
|
if (existing) {
|
|
935
1217
|
for (const [k, v] of existing) this.cache.set(k, v);
|
|
936
1218
|
this.recalculateStats();
|
|
@@ -943,6 +1225,12 @@ var SmartMemoryCache = class {
|
|
|
943
1225
|
this.categoryCount.clear();
|
|
944
1226
|
this.categorySize.clear();
|
|
945
1227
|
this.categoryKeys.clear();
|
|
1228
|
+
if (this.wtinyPolicy) {
|
|
1229
|
+
this.wtinyPolicy.clear();
|
|
1230
|
+
for (const key of this.cache.keys()) {
|
|
1231
|
+
this.wtinyPolicy.onSet(key, false);
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
946
1234
|
for (const [key, entry] of this.cache) {
|
|
947
1235
|
this.totalSize += entry.size;
|
|
948
1236
|
const cat = this.getCategory(key);
|
|
@@ -968,6 +1256,7 @@ var SmartMemoryCache = class {
|
|
|
968
1256
|
_delete(key, reason = "manual") {
|
|
969
1257
|
const entry = this.cache.get(key);
|
|
970
1258
|
if (!entry) return false;
|
|
1259
|
+
this.wtinyPolicy?.onDelete(key);
|
|
971
1260
|
const cat = this.getCategory(key);
|
|
972
1261
|
this.totalSize -= entry.size;
|
|
973
1262
|
this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
|
|
@@ -1128,7 +1417,8 @@ var SmartMemoryCache = class {
|
|
|
1128
1417
|
entry.hits++;
|
|
1129
1418
|
entry.lastAccess = now;
|
|
1130
1419
|
if ((entry.hits & 3) === 0) this.sketch.increment(key);
|
|
1131
|
-
|
|
1420
|
+
this.wtinyPolicy?.onAccess(key);
|
|
1421
|
+
const value = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
1132
1422
|
const hit = {
|
|
1133
1423
|
value,
|
|
1134
1424
|
isStale: entry.staleAt !== void 0 && now > entry.staleAt,
|
|
@@ -1142,7 +1432,7 @@ var SmartMemoryCache = class {
|
|
|
1142
1432
|
return hit;
|
|
1143
1433
|
}
|
|
1144
1434
|
set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
|
|
1145
|
-
const packed =
|
|
1435
|
+
const packed = this.codec.encode(data);
|
|
1146
1436
|
const size = packed.byteLength;
|
|
1147
1437
|
this.compressions++;
|
|
1148
1438
|
this.sketch.increment(key);
|
|
@@ -1159,7 +1449,51 @@ var SmartMemoryCache = class {
|
|
|
1159
1449
|
this.categorySize.set(cat, (this.categorySize.get(cat) ?? existingEntry.size) - existingEntry.size);
|
|
1160
1450
|
this.cache.delete(key);
|
|
1161
1451
|
}
|
|
1162
|
-
this.
|
|
1452
|
+
if (this.wtinyPolicy) {
|
|
1453
|
+
const decision = this.wtinyPolicy.onSet(key, Boolean(existingEntry));
|
|
1454
|
+
if (!decision.admit) {
|
|
1455
|
+
if (decision.candidateKey === key) {
|
|
1456
|
+
if (this.opts.diskSpill) {
|
|
1457
|
+
const now2 = Date.now();
|
|
1458
|
+
const liveValue2 = size <= LARGE_VALUE_BYTES ? data : void 0;
|
|
1459
|
+
this.opts.diskSpill(key, {
|
|
1460
|
+
data: packed,
|
|
1461
|
+
value: liveValue2,
|
|
1462
|
+
isCompressed: true,
|
|
1463
|
+
expiresAt: now2 + ttlMs,
|
|
1464
|
+
staleAt,
|
|
1465
|
+
size,
|
|
1466
|
+
hits: 1,
|
|
1467
|
+
lastAccess: now2,
|
|
1468
|
+
priority,
|
|
1469
|
+
ttlMs,
|
|
1470
|
+
delta,
|
|
1471
|
+
setAt: now2,
|
|
1472
|
+
tagVersions
|
|
1473
|
+
});
|
|
1474
|
+
}
|
|
1475
|
+
return;
|
|
1476
|
+
} else if (decision.candidateKey) {
|
|
1477
|
+
const candEntry = this.cache.get(decision.candidateKey);
|
|
1478
|
+
if (candEntry && this.opts.diskSpill) {
|
|
1479
|
+
this.opts.diskSpill(decision.candidateKey, candEntry);
|
|
1480
|
+
}
|
|
1481
|
+
this._delete(decision.candidateKey, "capacity");
|
|
1482
|
+
}
|
|
1483
|
+
} else if (decision.evictKey) {
|
|
1484
|
+
const victimEntry = this.cache.get(decision.evictKey);
|
|
1485
|
+
if (victimEntry && this.opts.diskSpill) {
|
|
1486
|
+
this.opts.diskSpill(decision.evictKey, victimEntry);
|
|
1487
|
+
}
|
|
1488
|
+
this._delete(decision.evictKey, "capacity");
|
|
1489
|
+
}
|
|
1490
|
+
const catSz = this.categorySize.get(cat) ?? 0;
|
|
1491
|
+
if (catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
|
|
1492
|
+
this.ensureCapacity(cat, size);
|
|
1493
|
+
}
|
|
1494
|
+
} else {
|
|
1495
|
+
this.ensureCapacity(cat, size);
|
|
1496
|
+
}
|
|
1163
1497
|
const now = Date.now();
|
|
1164
1498
|
const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
|
|
1165
1499
|
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 });
|
|
@@ -1219,6 +1553,7 @@ var SmartMemoryCache = class {
|
|
|
1219
1553
|
}
|
|
1220
1554
|
const count = this.cache.size;
|
|
1221
1555
|
this.cache.clear();
|
|
1556
|
+
this.wtinyPolicy?.clear();
|
|
1222
1557
|
this.totalSize = 0;
|
|
1223
1558
|
this.categoryCount.clear();
|
|
1224
1559
|
this.categorySize.clear();
|
|
@@ -1386,8 +1721,8 @@ var SmartMemoryCache = class {
|
|
|
1386
1721
|
if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
|
|
1387
1722
|
if (this.cache.has(key)) continue;
|
|
1388
1723
|
const rawData = entry.data;
|
|
1389
|
-
const data = !entry.isCompressed ?
|
|
1390
|
-
const value = entry.size <= LARGE_VALUE_BYTES ?
|
|
1724
|
+
const data = !entry.isCompressed ? this.codec.encode(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
|
|
1725
|
+
const value = entry.size <= LARGE_VALUE_BYTES ? this.codec.decode(data) : void 0;
|
|
1391
1726
|
this.cache.set(key, { ...entry, data, value, isCompressed: true });
|
|
1392
1727
|
this.bloom.add(key);
|
|
1393
1728
|
loaded++;
|
|
@@ -1458,7 +1793,7 @@ var SmartMemoryCache = class {
|
|
|
1458
1793
|
* if the live object was not cached (large-entry optimisation or disk-restored entry).
|
|
1459
1794
|
*/
|
|
1460
1795
|
resolveValue(entry) {
|
|
1461
|
-
return entry.value !== void 0 ? entry.value :
|
|
1796
|
+
return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
1462
1797
|
}
|
|
1463
1798
|
// ── Stats ─────────────────────────────────────────────────────────────────
|
|
1464
1799
|
get size() {
|
|
@@ -1563,13 +1898,20 @@ var SmartMemoryCache = class {
|
|
|
1563
1898
|
out.sort((a, b) => b.hits - a.hits);
|
|
1564
1899
|
return out.slice(0, n);
|
|
1565
1900
|
}
|
|
1901
|
+
/**
|
|
1902
|
+
* Return real-time metrics and telemetry for the Window TinyLFU admission policy.
|
|
1903
|
+
* Returns `undefined` when running under default adaptive eviction.
|
|
1904
|
+
*/
|
|
1905
|
+
getWTinyLfuStats() {
|
|
1906
|
+
return this.wtinyPolicy?.getStats();
|
|
1907
|
+
}
|
|
1566
1908
|
};
|
|
1567
1909
|
|
|
1568
1910
|
// src/disk-tier.ts
|
|
1569
1911
|
var import_fs2 = __toESM(require("fs"), 1);
|
|
1570
1912
|
var import_path2 = __toESM(require("path"), 1);
|
|
1571
1913
|
var import_crypto2 = __toESM(require("crypto"), 1);
|
|
1572
|
-
var
|
|
1914
|
+
var import_os2 = __toESM(require("os"), 1);
|
|
1573
1915
|
|
|
1574
1916
|
// src/compression.ts
|
|
1575
1917
|
var import_zlib = __toESM(require("zlib"), 1);
|
|
@@ -1627,18 +1969,146 @@ function decompressWithHeader(buf, algorithm = "brotli") {
|
|
|
1627
1969
|
}
|
|
1628
1970
|
|
|
1629
1971
|
// src/disk-tier.ts
|
|
1972
|
+
var BoundedDiskQueue = class {
|
|
1973
|
+
constructor(maxConcurrent = Math.min(4, Math.max(1, Math.floor((import_os2.default?.availableParallelism?.() ?? 4) / 4))), maxPending = 512, writeTimeoutMs = 500, failureThreshold = 5, cooldownMs = 5e3) {
|
|
1974
|
+
this.maxConcurrent = maxConcurrent;
|
|
1975
|
+
this.maxPending = maxPending;
|
|
1976
|
+
this.writeTimeoutMs = writeTimeoutMs;
|
|
1977
|
+
this.failureThreshold = failureThreshold;
|
|
1978
|
+
this.cooldownMs = cooldownMs;
|
|
1979
|
+
}
|
|
1980
|
+
maxConcurrent;
|
|
1981
|
+
maxPending;
|
|
1982
|
+
writeTimeoutMs;
|
|
1983
|
+
failureThreshold;
|
|
1984
|
+
cooldownMs;
|
|
1985
|
+
active = 0;
|
|
1986
|
+
queue = [];
|
|
1987
|
+
spillsDropped = 0;
|
|
1988
|
+
consecutiveFailures = 0;
|
|
1989
|
+
circuitState = "closed";
|
|
1990
|
+
lastStateChangeMonotonic = performance.now();
|
|
1991
|
+
async schedule(task) {
|
|
1992
|
+
const now = performance.now();
|
|
1993
|
+
if (this.circuitState === "open") {
|
|
1994
|
+
if (now - this.lastStateChangeMonotonic > this.cooldownMs) {
|
|
1995
|
+
this.circuitState = "half-open";
|
|
1996
|
+
this.lastStateChangeMonotonic = now;
|
|
1997
|
+
} else {
|
|
1998
|
+
this.spillsDropped++;
|
|
1999
|
+
return null;
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
if (this.circuitState === "half-open" && this.active > 0) {
|
|
2003
|
+
this.spillsDropped++;
|
|
2004
|
+
return null;
|
|
2005
|
+
}
|
|
2006
|
+
if (this.queue.length >= this.maxPending) {
|
|
2007
|
+
this.spillsDropped++;
|
|
2008
|
+
return null;
|
|
2009
|
+
}
|
|
2010
|
+
if (this.active >= this.maxConcurrent) {
|
|
2011
|
+
await new Promise((resolve) => this.queue.push(resolve));
|
|
2012
|
+
}
|
|
2013
|
+
this.active++;
|
|
2014
|
+
let timeoutId = null;
|
|
2015
|
+
try {
|
|
2016
|
+
const result = await Promise.race([
|
|
2017
|
+
task(),
|
|
2018
|
+
new Promise((_, reject) => {
|
|
2019
|
+
timeoutId = setTimeout(
|
|
2020
|
+
() => reject(new Error(`Disk write exceeded timeout of ${this.writeTimeoutMs}ms`)),
|
|
2021
|
+
this.writeTimeoutMs
|
|
2022
|
+
);
|
|
2023
|
+
})
|
|
2024
|
+
]);
|
|
2025
|
+
this.consecutiveFailures = 0;
|
|
2026
|
+
if (this.circuitState === "half-open") {
|
|
2027
|
+
this.circuitState = "closed";
|
|
2028
|
+
this.lastStateChangeMonotonic = performance.now();
|
|
2029
|
+
}
|
|
2030
|
+
return result;
|
|
2031
|
+
} catch {
|
|
2032
|
+
this.consecutiveFailures++;
|
|
2033
|
+
if (this.consecutiveFailures >= this.failureThreshold || this.circuitState === "half-open") {
|
|
2034
|
+
this.circuitState = "open";
|
|
2035
|
+
this.lastStateChangeMonotonic = performance.now();
|
|
2036
|
+
}
|
|
2037
|
+
this.spillsDropped++;
|
|
2038
|
+
return null;
|
|
2039
|
+
} finally {
|
|
2040
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
2041
|
+
this.active--;
|
|
2042
|
+
const next = this.queue.shift();
|
|
2043
|
+
if (next) next();
|
|
2044
|
+
}
|
|
2045
|
+
}
|
|
2046
|
+
getStats() {
|
|
2047
|
+
return {
|
|
2048
|
+
activeWrites: this.active,
|
|
2049
|
+
pendingWrites: this.queue.length,
|
|
2050
|
+
spillsDropped: this.spillsDropped,
|
|
2051
|
+
circuitState: this.circuitState,
|
|
2052
|
+
lastTripTimestamp: this.lastStateChangeMonotonic
|
|
2053
|
+
};
|
|
2054
|
+
}
|
|
2055
|
+
reset() {
|
|
2056
|
+
this.consecutiveFailures = 0;
|
|
2057
|
+
this.circuitState = "closed";
|
|
2058
|
+
this.lastStateChangeMonotonic = performance.now();
|
|
2059
|
+
}
|
|
2060
|
+
};
|
|
1630
2061
|
var _SqliteDB = null;
|
|
1631
2062
|
try {
|
|
1632
|
-
const
|
|
1633
|
-
|
|
2063
|
+
const proc = process;
|
|
2064
|
+
if (typeof proc.getBuiltinModule === "function") {
|
|
2065
|
+
const sqlite = proc.getBuiltinModule("node:sqlite");
|
|
2066
|
+
_SqliteDB = sqlite?.DatabaseSync ?? null;
|
|
2067
|
+
}
|
|
1634
2068
|
} catch {
|
|
1635
2069
|
}
|
|
1636
2070
|
var DISK_MAGIC = Buffer.from([68, 84, 73, 69, 82, 86, 49, 0]);
|
|
1637
2071
|
var DISK_MAGIC_V2 = Buffer.from([68, 84, 73, 69, 82, 86, 50, 0]);
|
|
1638
2072
|
var V2_HEADER_LEN = 16;
|
|
1639
2073
|
var DISK_TIER_VERSION = 1;
|
|
2074
|
+
function resolveDefaultDiskDir(namespace, logger) {
|
|
2075
|
+
const ns = namespace?.trim() ?? "";
|
|
2076
|
+
const nsDir = ns ? `tricache-disk-${ns}` : "tricache-disk";
|
|
2077
|
+
if (process.platform === "linux") {
|
|
2078
|
+
const shmPath = "/dev/shm";
|
|
2079
|
+
try {
|
|
2080
|
+
import_fs2.default.accessSync(shmPath, import_fs2.default.constants.W_OK | import_fs2.default.constants.R_OK);
|
|
2081
|
+
if (typeof import_fs2.default.statfsSync === "function") {
|
|
2082
|
+
const stats = import_fs2.default.statfsSync(shmPath);
|
|
2083
|
+
const totalBytes = Number(stats.blocks) * Number(stats.bsize);
|
|
2084
|
+
const freeBytes = Number(stats.bavail) * Number(stats.bsize);
|
|
2085
|
+
if (totalBytes >= 256 * 1024 * 1024 && freeBytes >= 128 * 1024 * 1024) {
|
|
2086
|
+
const targetDir = import_path2.default.join(shmPath, nsDir);
|
|
2087
|
+
logger?.info?.("DiskTier: Targeting Linux /dev/shm tmpfs for off-heap storage", {
|
|
2088
|
+
path: targetDir,
|
|
2089
|
+
totalBytes,
|
|
2090
|
+
freeBytes
|
|
2091
|
+
});
|
|
2092
|
+
return { dir: targetDir, isShm: true };
|
|
2093
|
+
} else {
|
|
2094
|
+
logger?.info?.("DiskTier: /dev/shm capacity or free space insufficient (<256MB total or <128MB free); falling back to tmpdir", {
|
|
2095
|
+
totalBytes,
|
|
2096
|
+
freeBytes
|
|
2097
|
+
});
|
|
2098
|
+
}
|
|
2099
|
+
}
|
|
2100
|
+
} catch (err) {
|
|
2101
|
+
logger?.debug?.("DiskTier: /dev/shm not usable, falling back to tmpdir", {
|
|
2102
|
+
error: err.message
|
|
2103
|
+
});
|
|
2104
|
+
}
|
|
2105
|
+
}
|
|
2106
|
+
return { dir: import_path2.default.join(import_os2.default.tmpdir(), nsDir), isShm: false };
|
|
2107
|
+
}
|
|
1640
2108
|
var DiskTier = class {
|
|
1641
2109
|
opts;
|
|
2110
|
+
codec;
|
|
2111
|
+
diskQueue;
|
|
1642
2112
|
dirReady = false;
|
|
1643
2113
|
diskUsageBytes = 0;
|
|
1644
2114
|
usageCounted = false;
|
|
@@ -1646,6 +2116,14 @@ var DiskTier = class {
|
|
|
1646
2116
|
// maintained in-memory; avoids walkCacheFiles() in stats
|
|
1647
2117
|
/** Next bucket index (0–255) for the staggered janitor wheel. */
|
|
1648
2118
|
_nextJanitorBucket = 0;
|
|
2119
|
+
// ── High-watermark pruning & host volume health state ─────────────────────
|
|
2120
|
+
_isPruning = false;
|
|
2121
|
+
_pruneRounds = 0;
|
|
2122
|
+
_entriesPruned = 0;
|
|
2123
|
+
_spillsShedTotal = 0;
|
|
2124
|
+
_hostVolumeLowSpace = false;
|
|
2125
|
+
_hostVolumeLowSpacePauses = 0;
|
|
2126
|
+
_writeCounter = 0;
|
|
1649
2127
|
// ── SQLite metadata index (optional, requires node:sqlite) ───────────────
|
|
1650
2128
|
_db = null;
|
|
1651
2129
|
_stmtInsert = null;
|
|
@@ -1660,8 +2138,19 @@ var DiskTier = class {
|
|
|
1660
2138
|
// DELETE expired rows
|
|
1661
2139
|
_stmtStats = null;
|
|
1662
2140
|
// COUNT + SUM(size)
|
|
2141
|
+
_stmtPruneChunk = null;
|
|
2142
|
+
// SELECT chunk for watermark pruning
|
|
1663
2143
|
constructor(opts) {
|
|
1664
2144
|
this.opts = opts;
|
|
2145
|
+
this.codec = opts.codec ?? defaultCodec;
|
|
2146
|
+
const defaultConcurrent = Math.min(4, Math.max(1, Math.floor((import_os2.default?.availableParallelism?.() ?? 4) / 4)));
|
|
2147
|
+
this.diskQueue = new BoundedDiskQueue(
|
|
2148
|
+
opts.diskMaxConcurrentWrites ?? defaultConcurrent,
|
|
2149
|
+
opts.diskMaxPendingWrites ?? 512,
|
|
2150
|
+
opts.diskWriteTimeoutMs ?? 500,
|
|
2151
|
+
opts.diskCircuitBreakerThreshold ?? 5,
|
|
2152
|
+
opts.diskCircuitBreakerCooldownMs ?? 5e3
|
|
2153
|
+
);
|
|
1665
2154
|
}
|
|
1666
2155
|
// ── Helpers ───────────────────────────────────────────────────────────────
|
|
1667
2156
|
ensureDir() {
|
|
@@ -1696,15 +2185,30 @@ var DiskTier = class {
|
|
|
1696
2185
|
PRAGMA synchronous = NORMAL;
|
|
1697
2186
|
PRAGMA temp_store = MEMORY;
|
|
1698
2187
|
CREATE TABLE IF NOT EXISTS meta (
|
|
1699
|
-
key_hash
|
|
1700
|
-
file_path
|
|
1701
|
-
expires_at
|
|
1702
|
-
size
|
|
2188
|
+
key_hash TEXT PRIMARY KEY,
|
|
2189
|
+
file_path TEXT NOT NULL,
|
|
2190
|
+
expires_at INTEGER NOT NULL,
|
|
2191
|
+
size INTEGER NOT NULL DEFAULT 0,
|
|
2192
|
+
priority INTEGER NOT NULL DEFAULT 2,
|
|
2193
|
+
last_accessed_at INTEGER NOT NULL DEFAULT 0
|
|
1703
2194
|
);
|
|
1704
2195
|
CREATE INDEX IF NOT EXISTS idx_expires ON meta (expires_at);
|
|
2196
|
+
CREATE INDEX IF NOT EXISTS idx_priority_access ON meta (priority ASC, last_accessed_at ASC);
|
|
1705
2197
|
`);
|
|
2198
|
+
try {
|
|
2199
|
+
this._db.exec("ALTER TABLE meta ADD COLUMN priority INTEGER NOT NULL DEFAULT 2;");
|
|
2200
|
+
} catch {
|
|
2201
|
+
}
|
|
2202
|
+
try {
|
|
2203
|
+
this._db.exec("ALTER TABLE meta ADD COLUMN last_accessed_at INTEGER NOT NULL DEFAULT 0;");
|
|
2204
|
+
} catch {
|
|
2205
|
+
}
|
|
2206
|
+
try {
|
|
2207
|
+
this._db.exec("CREATE INDEX IF NOT EXISTS idx_priority_access ON meta (priority ASC, last_accessed_at ASC);");
|
|
2208
|
+
} catch {
|
|
2209
|
+
}
|
|
1706
2210
|
this._stmtInsert = this._db.prepare(
|
|
1707
|
-
"INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size) VALUES (
|
|
2211
|
+
"INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size, priority, last_accessed_at) VALUES (?,?,?,?,?,?)"
|
|
1708
2212
|
);
|
|
1709
2213
|
this._stmtSelect = this._db.prepare(
|
|
1710
2214
|
"SELECT file_path, expires_at FROM meta WHERE key_hash = ?"
|
|
@@ -1717,13 +2221,16 @@ var DiskTier = class {
|
|
|
1717
2221
|
this._stmtStats = this._db.prepare(
|
|
1718
2222
|
"SELECT COUNT(*) AS cnt, COALESCE(SUM(size), 0) AS bytes FROM meta"
|
|
1719
2223
|
);
|
|
2224
|
+
this._stmtPruneChunk = this._db.prepare(
|
|
2225
|
+
"SELECT key_hash, file_path, size FROM meta ORDER BY priority ASC, last_accessed_at ASC LIMIT 500"
|
|
2226
|
+
);
|
|
1720
2227
|
const row = this._stmtStats.get();
|
|
1721
2228
|
this.fileCount = row.cnt;
|
|
1722
2229
|
this.diskUsageBytes = row.bytes;
|
|
1723
2230
|
this.usageCounted = true;
|
|
1724
2231
|
this.opts.logger.debug("DiskTier: SQLite index ready", { entries: row.cnt });
|
|
1725
2232
|
} catch (err) {
|
|
1726
|
-
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
|
|
2233
|
+
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = this._stmtPruneChunk = null;
|
|
1727
2234
|
this.opts.logger.warn("DiskTier: SQLite init failed, using file-only mode", {
|
|
1728
2235
|
error: err.message
|
|
1729
2236
|
});
|
|
@@ -1818,7 +2325,7 @@ var DiskTier = class {
|
|
|
1818
2325
|
return results;
|
|
1819
2326
|
}
|
|
1820
2327
|
isForbidden(key) {
|
|
1821
|
-
return this.opts.forbiddenPrefixes
|
|
2328
|
+
return this.opts.forbiddenPrefixes?.some((p) => key.startsWith(p)) ?? false;
|
|
1822
2329
|
}
|
|
1823
2330
|
encrypt(data) {
|
|
1824
2331
|
if (!this.opts.encryption) return data;
|
|
@@ -1870,7 +2377,16 @@ var DiskTier = class {
|
|
|
1870
2377
|
this.ensureDir();
|
|
1871
2378
|
if (!this.dirReady) return;
|
|
1872
2379
|
this.ensureUsageCounted();
|
|
1873
|
-
if (this.
|
|
2380
|
+
if (++this._writeCounter % 2e3 === 0) {
|
|
2381
|
+
this.checkHostVolumeHealth();
|
|
2382
|
+
}
|
|
2383
|
+
if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes >= this.opts.maxBytes) {
|
|
2384
|
+
this._spillsShedTotal++;
|
|
2385
|
+
return;
|
|
2386
|
+
}
|
|
2387
|
+
if (this.diskUsageBytes >= this.opts.maxBytes * 0.8 && !this._isPruning) {
|
|
2388
|
+
void this.triggerChunkedPrune();
|
|
2389
|
+
}
|
|
1874
2390
|
let final;
|
|
1875
2391
|
try {
|
|
1876
2392
|
const payload = {
|
|
@@ -1882,7 +2398,7 @@ var DiskTier = class {
|
|
|
1882
2398
|
},
|
|
1883
2399
|
writtenAt: Date.now()
|
|
1884
2400
|
};
|
|
1885
|
-
const packed =
|
|
2401
|
+
const packed = this.codec.encode(payload);
|
|
1886
2402
|
if (packed.length > this.opts.entryMaxBytes) return;
|
|
1887
2403
|
let toEncrypt = packed;
|
|
1888
2404
|
if (this.opts.compression && this.opts.compression !== "none" && packed.length > (this.opts.compressionThresholdBytes ?? 1024)) {
|
|
@@ -1898,39 +2414,52 @@ var DiskTier = class {
|
|
|
1898
2414
|
}
|
|
1899
2415
|
const hash = this.keyToHash(key);
|
|
1900
2416
|
const filePath = this.hashToWritePath(hash, entry.expiresAt);
|
|
1901
|
-
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${
|
|
2417
|
+
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${import_crypto2.default.randomBytes(6).toString("hex")}.tmp`;
|
|
1902
2418
|
this.diskUsageBytes += final.length;
|
|
1903
2419
|
this.fileCount++;
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
2420
|
+
if (this.diskUsageBytes >= this.opts.maxBytes * 0.8 && !this._isPruning) {
|
|
2421
|
+
void this.triggerChunkedPrune();
|
|
2422
|
+
}
|
|
2423
|
+
const result = await this.diskQueue.schedule(async () => {
|
|
1907
2424
|
try {
|
|
1908
|
-
await import_fs2.default.promises.
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
if (code === "EBUSY" || code === "EPERM") {
|
|
1912
|
-
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
2425
|
+
await import_fs2.default.promises.mkdir(import_path2.default.dirname(filePath), { recursive: true });
|
|
2426
|
+
await import_fs2.default.promises.writeFile(tmpPath, final, { mode: 384 });
|
|
2427
|
+
try {
|
|
1913
2428
|
await import_fs2.default.promises.rename(tmpPath, filePath);
|
|
1914
|
-
}
|
|
1915
|
-
|
|
2429
|
+
} catch (renameErr) {
|
|
2430
|
+
const code = renameErr?.code;
|
|
2431
|
+
if (code === "EBUSY" || code === "EPERM") {
|
|
2432
|
+
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
2433
|
+
await import_fs2.default.promises.rename(tmpPath, filePath);
|
|
2434
|
+
} else {
|
|
2435
|
+
throw renameErr;
|
|
2436
|
+
}
|
|
1916
2437
|
}
|
|
2438
|
+
if (this._db) {
|
|
2439
|
+
const priority = typeof entry.priority === "number" ? entry.priority : 2;
|
|
2440
|
+
const lastAccess = typeof entry.lastAccess === "number" ? entry.lastAccess : Date.now();
|
|
2441
|
+
this._stmtInsert.run(hash, filePath, entry.expiresAt, final.length, priority, lastAccess);
|
|
2442
|
+
}
|
|
2443
|
+
this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
|
|
2444
|
+
return true;
|
|
2445
|
+
} catch (err) {
|
|
2446
|
+
try {
|
|
2447
|
+
await import_fs2.default.promises.unlink(tmpPath);
|
|
2448
|
+
} catch {
|
|
2449
|
+
}
|
|
2450
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
|
|
2451
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2452
|
+
if (this._db) try {
|
|
2453
|
+
this._stmtDelete.run(hash);
|
|
2454
|
+
} catch {
|
|
2455
|
+
}
|
|
2456
|
+
this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
|
|
2457
|
+
throw err;
|
|
1917
2458
|
}
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
}
|
|
1921
|
-
this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
|
|
1922
|
-
} catch (err) {
|
|
1923
|
-
try {
|
|
1924
|
-
await import_fs2.default.promises.unlink(tmpPath);
|
|
1925
|
-
} catch {
|
|
1926
|
-
}
|
|
2459
|
+
});
|
|
2460
|
+
if (result === null) {
|
|
1927
2461
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
|
|
1928
2462
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1929
|
-
if (this._db) try {
|
|
1930
|
-
this._stmtDelete.run(hash);
|
|
1931
|
-
} catch {
|
|
1932
|
-
}
|
|
1933
|
-
this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
|
|
1934
2463
|
}
|
|
1935
2464
|
}
|
|
1936
2465
|
/** Load a key from disk, or return null on miss/expiry/corruption. */
|
|
@@ -2008,7 +2537,7 @@ var DiskTier = class {
|
|
|
2008
2537
|
}
|
|
2009
2538
|
}
|
|
2010
2539
|
const uncompressed = decompressWithHeader(decrypted, this.opts.compression ?? "brotli");
|
|
2011
|
-
const payload =
|
|
2540
|
+
const payload = this.codec.decode(uncompressed);
|
|
2012
2541
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
|
|
2013
2542
|
if (payload.entry.expiresAt <= Date.now()) return null;
|
|
2014
2543
|
const entry = payload.entry;
|
|
@@ -2131,7 +2660,7 @@ var DiskTier = class {
|
|
|
2131
2660
|
purged++;
|
|
2132
2661
|
continue;
|
|
2133
2662
|
}
|
|
2134
|
-
const payload =
|
|
2663
|
+
const payload = this.codec.decode(dec);
|
|
2135
2664
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
2136
2665
|
import_fs2.default.unlinkSync(filePath);
|
|
2137
2666
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
@@ -2295,7 +2824,7 @@ var DiskTier = class {
|
|
|
2295
2824
|
purged++;
|
|
2296
2825
|
continue;
|
|
2297
2826
|
}
|
|
2298
|
-
const payload =
|
|
2827
|
+
const payload = this.codec.decode(dec);
|
|
2299
2828
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
2300
2829
|
import_fs2.default.unlinkSync(filePath);
|
|
2301
2830
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
@@ -2334,13 +2863,141 @@ var DiskTier = class {
|
|
|
2334
2863
|
}
|
|
2335
2864
|
return cleared;
|
|
2336
2865
|
}
|
|
2866
|
+
/**
|
|
2867
|
+
* Proactively checks host volume free space via statfsSync.
|
|
2868
|
+
* If free space on the volume drops below 10%, pauses spills to prevent
|
|
2869
|
+
* Kubernetes pod eviction (DiskPressure / EphemeralStorageExceeded).
|
|
2870
|
+
*/
|
|
2871
|
+
checkHostVolumeHealth() {
|
|
2872
|
+
try {
|
|
2873
|
+
if (typeof import_fs2.default.statfsSync === "function") {
|
|
2874
|
+
const stats = import_fs2.default.statfsSync(this.opts.dir);
|
|
2875
|
+
const total = Number(stats.blocks);
|
|
2876
|
+
const avail = Number(stats.bavail);
|
|
2877
|
+
if (total > 0) {
|
|
2878
|
+
const freeRatio = avail / total;
|
|
2879
|
+
if (freeRatio < 0.1) {
|
|
2880
|
+
if (!this._hostVolumeLowSpace) {
|
|
2881
|
+
this._hostVolumeLowSpace = true;
|
|
2882
|
+
this._hostVolumeLowSpacePauses++;
|
|
2883
|
+
this.opts.logger.warn(
|
|
2884
|
+
"DiskTier: host volume has <10% free space. Pausing disk cache spills to prevent Kubernetes eviction.",
|
|
2885
|
+
{ dir: this.opts.dir, freePct: Number((freeRatio * 100).toFixed(1)) }
|
|
2886
|
+
);
|
|
2887
|
+
}
|
|
2888
|
+
return false;
|
|
2889
|
+
} else if (this._hostVolumeLowSpace) {
|
|
2890
|
+
this._hostVolumeLowSpace = false;
|
|
2891
|
+
this.opts.logger.info(
|
|
2892
|
+
"DiskTier: host volume space recovered (>=10% free). Resuming disk cache spills.",
|
|
2893
|
+
{ dir: this.opts.dir, freePct: Number((freeRatio * 100).toFixed(1)) }
|
|
2894
|
+
);
|
|
2895
|
+
return true;
|
|
2896
|
+
}
|
|
2897
|
+
}
|
|
2898
|
+
}
|
|
2899
|
+
} catch {
|
|
2900
|
+
}
|
|
2901
|
+
return true;
|
|
2902
|
+
}
|
|
2903
|
+
/**
|
|
2904
|
+
* Non-blocking chunked pruning:
|
|
2905
|
+
* Evicts oldest entries in 500-entry chunks down to 60% watermark,
|
|
2906
|
+
* yielding to the event loop via setImmediate between chunks.
|
|
2907
|
+
*/
|
|
2908
|
+
async triggerChunkedPrune() {
|
|
2909
|
+
if (this._isPruning) return 0;
|
|
2910
|
+
this._isPruning = true;
|
|
2911
|
+
this._pruneRounds++;
|
|
2912
|
+
let prunedInThisRound = 0;
|
|
2913
|
+
try {
|
|
2914
|
+
this.ensureUsageCounted();
|
|
2915
|
+
const targetBytes = Math.floor(this.opts.maxBytes * 0.6);
|
|
2916
|
+
if (this._db && this._stmtPruneChunk) {
|
|
2917
|
+
while (this.diskUsageBytes > targetBytes) {
|
|
2918
|
+
const rows = this._stmtPruneChunk.all();
|
|
2919
|
+
if (!rows || rows.length === 0) break;
|
|
2920
|
+
for (const row of rows) {
|
|
2921
|
+
try {
|
|
2922
|
+
import_fs2.default.unlinkSync(row.file_path);
|
|
2923
|
+
} catch {
|
|
2924
|
+
}
|
|
2925
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
|
|
2926
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2927
|
+
this._entriesPruned++;
|
|
2928
|
+
prunedInThisRound++;
|
|
2929
|
+
try {
|
|
2930
|
+
this._stmtDelete.run(row.key_hash);
|
|
2931
|
+
} catch {
|
|
2932
|
+
}
|
|
2933
|
+
if (this.diskUsageBytes <= targetBytes) break;
|
|
2934
|
+
}
|
|
2935
|
+
if (this.diskUsageBytes > targetBytes) {
|
|
2936
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
2937
|
+
}
|
|
2938
|
+
}
|
|
2939
|
+
} else {
|
|
2940
|
+
while (this.diskUsageBytes > targetBytes) {
|
|
2941
|
+
const files = this.walkCacheFiles();
|
|
2942
|
+
if (files.length === 0) break;
|
|
2943
|
+
const chunk = files.slice(0, 500);
|
|
2944
|
+
for (const filePath of chunk) {
|
|
2945
|
+
try {
|
|
2946
|
+
const stat = import_fs2.default.statSync(filePath);
|
|
2947
|
+
import_fs2.default.unlinkSync(filePath);
|
|
2948
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
2949
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2950
|
+
this._entriesPruned++;
|
|
2951
|
+
prunedInThisRound++;
|
|
2952
|
+
} catch {
|
|
2953
|
+
}
|
|
2954
|
+
if (this.diskUsageBytes <= targetBytes) break;
|
|
2955
|
+
}
|
|
2956
|
+
if (this.diskUsageBytes > targetBytes) {
|
|
2957
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
2958
|
+
}
|
|
2959
|
+
}
|
|
2960
|
+
}
|
|
2961
|
+
} finally {
|
|
2962
|
+
this._isPruning = false;
|
|
2963
|
+
}
|
|
2964
|
+
return prunedInThisRound;
|
|
2965
|
+
}
|
|
2966
|
+
get isPruning() {
|
|
2967
|
+
return this._isPruning;
|
|
2968
|
+
}
|
|
2969
|
+
get hostVolumeLowSpace() {
|
|
2970
|
+
return this._hostVolumeLowSpace;
|
|
2971
|
+
}
|
|
2972
|
+
get spillsShedTotal() {
|
|
2973
|
+
return this._spillsShedTotal;
|
|
2974
|
+
}
|
|
2975
|
+
getPruningStats() {
|
|
2976
|
+
return {
|
|
2977
|
+
active: this._isPruning,
|
|
2978
|
+
pruneRounds: this._pruneRounds,
|
|
2979
|
+
entriesPruned: this._entriesPruned,
|
|
2980
|
+
spillsShedTotal: this._spillsShedTotal,
|
|
2981
|
+
hostVolumeLowSpacePauses: this._hostVolumeLowSpacePauses
|
|
2982
|
+
};
|
|
2983
|
+
}
|
|
2337
2984
|
get stats() {
|
|
2338
2985
|
if (this._db) {
|
|
2339
2986
|
const row = this._stmtStats.get();
|
|
2340
2987
|
this.fileCount = row.cnt;
|
|
2341
2988
|
this.diskUsageBytes = row.bytes;
|
|
2342
2989
|
}
|
|
2343
|
-
return {
|
|
2990
|
+
return {
|
|
2991
|
+
files: this.fileCount,
|
|
2992
|
+
sizeKB: Math.round(this.diskUsageBytes / 1024),
|
|
2993
|
+
maxKB: Math.round(this.opts.maxBytes / 1024),
|
|
2994
|
+
backpressure: this.diskQueue.getStats(),
|
|
2995
|
+
pruning: this.getPruningStats()
|
|
2996
|
+
};
|
|
2997
|
+
}
|
|
2998
|
+
/** Direct access to the bounded write queue for chaos diagnostics and canary controls. */
|
|
2999
|
+
get backpressure() {
|
|
3000
|
+
return this.diskQueue;
|
|
2344
3001
|
}
|
|
2345
3002
|
/** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
|
|
2346
3003
|
get indexMode() {
|
|
@@ -2353,58 +3010,621 @@ var DiskTier = class {
|
|
|
2353
3010
|
this._db.close();
|
|
2354
3011
|
} catch {
|
|
2355
3012
|
}
|
|
2356
|
-
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
|
|
3013
|
+
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = this._stmtPruneChunk = null;
|
|
2357
3014
|
}
|
|
2358
3015
|
}
|
|
2359
3016
|
};
|
|
2360
3017
|
|
|
2361
|
-
// src/
|
|
2362
|
-
var
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
2384
|
-
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
|
|
3018
|
+
// src/latency-watchdog.ts
|
|
3019
|
+
var TierLatencyWatchdog = class {
|
|
3020
|
+
enabled;
|
|
3021
|
+
minDiskBypassMs;
|
|
3022
|
+
bypassRatio;
|
|
3023
|
+
cooldownMs;
|
|
3024
|
+
redisCutoffMs;
|
|
3025
|
+
redisRecoveryFloorMs;
|
|
3026
|
+
minSamples;
|
|
3027
|
+
disableRedis;
|
|
3028
|
+
// Zero-allocation rolling ring buffers
|
|
3029
|
+
diskRing = new Float32Array(32);
|
|
3030
|
+
redisRing = new Float32Array(32);
|
|
3031
|
+
scratch = new Float32Array(32);
|
|
3032
|
+
diskIdx = 0;
|
|
3033
|
+
redisIdx = 0;
|
|
3034
|
+
diskCount = 0;
|
|
3035
|
+
redisCount = 0;
|
|
3036
|
+
// Cached amortized p95 values
|
|
3037
|
+
cachedDiskP95 = 0;
|
|
3038
|
+
cachedRedisP95 = 0;
|
|
3039
|
+
// State machine & control-theory flags
|
|
3040
|
+
stage = 0;
|
|
3041
|
+
redisDampened = false;
|
|
3042
|
+
// Asymmetric hysteresis latch
|
|
3043
|
+
redisRecoveryConsecutiveSamples = 0;
|
|
3044
|
+
bypassedUntilMonotonic = 0;
|
|
3045
|
+
canaryInFlight = false;
|
|
3046
|
+
bypassedTotal = 0;
|
|
3047
|
+
constructor(options = {}) {
|
|
3048
|
+
this.enabled = options.enabled ?? true;
|
|
3049
|
+
this.minDiskBypassMs = options.minDiskBypassMs ?? 10;
|
|
3050
|
+
this.bypassRatio = options.bypassRatio ?? 1.5;
|
|
3051
|
+
this.cooldownMs = options.cooldownMs ?? 3e4;
|
|
3052
|
+
this.redisCutoffMs = options.redisCutoffMs ?? 15;
|
|
3053
|
+
this.redisRecoveryFloorMs = options.redisRecoveryFloorMs ?? 10;
|
|
3054
|
+
this.minSamples = options.minSamples ?? 16;
|
|
3055
|
+
this.disableRedis = options.disableRedis ?? false;
|
|
3056
|
+
}
|
|
3057
|
+
setDisableRedis(disabled) {
|
|
3058
|
+
this.disableRedis = disabled;
|
|
3059
|
+
if (disabled) {
|
|
3060
|
+
this.stage = 0;
|
|
3061
|
+
this.bypassedUntilMonotonic = 0;
|
|
3062
|
+
this.canaryInFlight = false;
|
|
3063
|
+
this.redisRecoveryConsecutiveSamples = 0;
|
|
3064
|
+
}
|
|
2392
3065
|
}
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
this.
|
|
2399
|
-
this.
|
|
3066
|
+
/**
|
|
3067
|
+
* Record disk read duration in milliseconds (zero-allocation hot path).
|
|
3068
|
+
*/
|
|
3069
|
+
recordDisk(ms) {
|
|
3070
|
+
if (!this.enabled) return;
|
|
3071
|
+
this.diskRing[this.diskIdx++ & 31] = ms;
|
|
3072
|
+
this.diskCount++;
|
|
3073
|
+
if ((this.diskIdx & 31) === 0) {
|
|
3074
|
+
this.recalculateP95();
|
|
3075
|
+
}
|
|
2400
3076
|
}
|
|
2401
|
-
|
|
2402
|
-
|
|
2403
|
-
|
|
2404
|
-
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
3077
|
+
/**
|
|
3078
|
+
* Record Redis read duration in milliseconds (zero-allocation hot path).
|
|
3079
|
+
*/
|
|
3080
|
+
recordRedis(ms) {
|
|
3081
|
+
if (!this.enabled || this.disableRedis) return;
|
|
3082
|
+
this.redisRing[this.redisIdx++ & 31] = ms;
|
|
3083
|
+
this.redisCount++;
|
|
3084
|
+
if (ms <= this.redisRecoveryFloorMs) {
|
|
3085
|
+
this.redisRecoveryConsecutiveSamples++;
|
|
3086
|
+
} else {
|
|
3087
|
+
this.redisRecoveryConsecutiveSamples = 0;
|
|
3088
|
+
}
|
|
3089
|
+
if ((this.redisIdx & 31) === 0) {
|
|
3090
|
+
this.recalculateP95();
|
|
3091
|
+
}
|
|
3092
|
+
}
|
|
3093
|
+
recalculateP95() {
|
|
3094
|
+
if (this.diskCount >= this.minSamples) {
|
|
3095
|
+
this.cachedDiskP95 = this.computeP95(this.diskRing, Math.min(this.diskCount, 32));
|
|
3096
|
+
}
|
|
3097
|
+
if (this.redisCount >= this.minSamples) {
|
|
3098
|
+
this.cachedRedisP95 = this.computeP95(this.redisRing, Math.min(this.redisCount, 32));
|
|
3099
|
+
}
|
|
3100
|
+
this.evaluateControlLoop();
|
|
3101
|
+
}
|
|
3102
|
+
computeP95(ring, count) {
|
|
3103
|
+
for (let i = 0; i < count; i++) {
|
|
3104
|
+
this.scratch[i] = ring[i];
|
|
3105
|
+
}
|
|
3106
|
+
this.scratch.subarray(0, count).sort();
|
|
3107
|
+
const rank = Math.min(count - 1, Math.max(0, Math.floor((count - 1) * 0.95)));
|
|
3108
|
+
return this.scratch[rank];
|
|
3109
|
+
}
|
|
3110
|
+
/**
|
|
3111
|
+
* Core Control Loop:
|
|
3112
|
+
* - Evaluates asymmetric hysteresis on Redis circuit.
|
|
3113
|
+
* - Assigns graduated stage (0, 1, 2, 3) with anti-synchronicity jitter.
|
|
3114
|
+
*/
|
|
3115
|
+
evaluateControlLoop() {
|
|
3116
|
+
if (this.disableRedis) {
|
|
3117
|
+
this.stage = 0;
|
|
3118
|
+
return;
|
|
3119
|
+
}
|
|
3120
|
+
if (this.cachedRedisP95 >= this.redisCutoffMs) {
|
|
3121
|
+
this.redisDampened = true;
|
|
3122
|
+
} else if (this.redisDampened && this.cachedRedisP95 <= this.redisRecoveryFloorMs && this.redisRecoveryConsecutiveSamples >= this.minSamples) {
|
|
3123
|
+
this.redisDampened = false;
|
|
3124
|
+
}
|
|
3125
|
+
if (this.redisDampened) {
|
|
3126
|
+
this.stage = 0;
|
|
3127
|
+
return;
|
|
3128
|
+
}
|
|
3129
|
+
if (this.diskCount < this.minSamples || this.redisCount < this.minSamples) {
|
|
3130
|
+
return;
|
|
3131
|
+
}
|
|
3132
|
+
const diskP95 = this.cachedDiskP95;
|
|
3133
|
+
const redisP95 = Math.max(0.1, this.cachedRedisP95);
|
|
3134
|
+
if (diskP95 >= 50) {
|
|
3135
|
+
if (this.stage !== 3) {
|
|
3136
|
+
this.stage = 3;
|
|
3137
|
+
this.bypassedUntilMonotonic = performance.now() + this.calculateJitteredCooldown();
|
|
3138
|
+
this.bypassedTotal++;
|
|
3139
|
+
}
|
|
3140
|
+
} else if (diskP95 >= this.minDiskBypassMs * 2.5 && diskP95 >= redisP95 * (this.bypassRatio * 1.5)) {
|
|
3141
|
+
if (this.stage !== 2) {
|
|
3142
|
+
this.stage = 2;
|
|
3143
|
+
this.bypassedTotal++;
|
|
3144
|
+
}
|
|
3145
|
+
} else if (diskP95 >= this.minDiskBypassMs && diskP95 >= redisP95 * this.bypassRatio) {
|
|
3146
|
+
if (this.stage !== 1) {
|
|
3147
|
+
this.stage = 1;
|
|
3148
|
+
this.bypassedTotal++;
|
|
3149
|
+
}
|
|
3150
|
+
} else {
|
|
3151
|
+
this.stage = 0;
|
|
3152
|
+
this.bypassedUntilMonotonic = 0;
|
|
3153
|
+
this.canaryInFlight = false;
|
|
3154
|
+
}
|
|
3155
|
+
}
|
|
3156
|
+
calculateJitteredCooldown() {
|
|
3157
|
+
const jitterFactor = 0.7 + Math.random() * 0.6;
|
|
3158
|
+
return this.cooldownMs * jitterFactor;
|
|
3159
|
+
}
|
|
3160
|
+
/**
|
|
3161
|
+
* Determine whether a read is permitted to check the disk tier.
|
|
3162
|
+
*
|
|
3163
|
+
* In Stage 1 and 2, sheds traffic probabilistically.
|
|
3164
|
+
* In Stage 3, blocks all reads except for a single canary probe once cooldown expires.
|
|
3165
|
+
*
|
|
3166
|
+
* @param randomOverride Optional seeded random number [0, 1) for deterministic unit testing.
|
|
3167
|
+
*/
|
|
3168
|
+
isDiskAllowed(randomOverride) {
|
|
3169
|
+
if (!this.enabled || this.disableRedis) return true;
|
|
3170
|
+
if (this.stage === 0) return true;
|
|
3171
|
+
const rand = randomOverride !== void 0 ? randomOverride : Math.random();
|
|
3172
|
+
if (this.stage === 1) {
|
|
3173
|
+
return rand > 0.25;
|
|
3174
|
+
}
|
|
3175
|
+
if (this.stage === 2) {
|
|
3176
|
+
return rand > 0.75;
|
|
3177
|
+
}
|
|
3178
|
+
const now = performance.now();
|
|
3179
|
+
if (now < this.bypassedUntilMonotonic) {
|
|
3180
|
+
return false;
|
|
3181
|
+
}
|
|
3182
|
+
if (!this.canaryInFlight) {
|
|
3183
|
+
this.canaryInFlight = true;
|
|
3184
|
+
return true;
|
|
3185
|
+
}
|
|
3186
|
+
return false;
|
|
3187
|
+
}
|
|
3188
|
+
/**
|
|
3189
|
+
* Callback invoked when the single canary read probe completes.
|
|
3190
|
+
*/
|
|
3191
|
+
onCanaryResult(success, elapsedMs) {
|
|
3192
|
+
if (!this.canaryInFlight) return;
|
|
3193
|
+
this.canaryInFlight = false;
|
|
3194
|
+
if (success && elapsedMs < this.minDiskBypassMs) {
|
|
3195
|
+
this.stage = 0;
|
|
3196
|
+
this.bypassedUntilMonotonic = 0;
|
|
3197
|
+
this.recordDisk(elapsedMs);
|
|
3198
|
+
} else {
|
|
3199
|
+
this.bypassedUntilMonotonic = performance.now() + this.calculateJitteredCooldown();
|
|
3200
|
+
this.bypassedTotal++;
|
|
3201
|
+
}
|
|
3202
|
+
}
|
|
3203
|
+
getTelemetry() {
|
|
3204
|
+
return {
|
|
3205
|
+
bypassActive: this.stage > 0,
|
|
3206
|
+
bypassStage: this.stage,
|
|
3207
|
+
diskP95Ms: Number(this.cachedDiskP95.toFixed(2)),
|
|
3208
|
+
redisP95Ms: Number(this.cachedRedisP95.toFixed(2)),
|
|
3209
|
+
redisDampened: this.redisDampened,
|
|
3210
|
+
bypassedTotal: this.bypassedTotal
|
|
3211
|
+
};
|
|
3212
|
+
}
|
|
3213
|
+
};
|
|
3214
|
+
|
|
3215
|
+
// src/utils/cgroup.ts
|
|
3216
|
+
var import_node_fs = __toESM(require("fs"), 1);
|
|
3217
|
+
var import_node_v8 = __toESM(require("v8"), 1);
|
|
3218
|
+
var UNBOUNDED_CGROUP_THRESHOLD = 9e18;
|
|
3219
|
+
var DEFAULT_AUTONOMOUS_L1_CEILING_BYTES = 512 * 1024 * 1024;
|
|
3220
|
+
var MIN_AUTONOMOUS_L1_FLOOR_BYTES = 16 * 1024 * 1024;
|
|
3221
|
+
function readCgroupMemoryLimit() {
|
|
3222
|
+
if (process.platform !== "linux") {
|
|
3223
|
+
return Infinity;
|
|
3224
|
+
}
|
|
3225
|
+
try {
|
|
3226
|
+
if (import_node_fs.default.existsSync("/sys/fs/cgroup/memory.max")) {
|
|
3227
|
+
const raw = import_node_fs.default.readFileSync("/sys/fs/cgroup/memory.max", "utf8").trim();
|
|
3228
|
+
if (raw === "max") {
|
|
3229
|
+
return Infinity;
|
|
3230
|
+
}
|
|
3231
|
+
const bytes = parseInt(raw, 10);
|
|
3232
|
+
if (Number.isFinite(bytes) && bytes > 0 && bytes < UNBOUNDED_CGROUP_THRESHOLD) {
|
|
3233
|
+
return bytes;
|
|
3234
|
+
}
|
|
3235
|
+
}
|
|
3236
|
+
} catch {
|
|
3237
|
+
}
|
|
3238
|
+
try {
|
|
3239
|
+
if (import_node_fs.default.existsSync("/sys/fs/cgroup/memory/memory.limit_in_bytes")) {
|
|
3240
|
+
const raw = import_node_fs.default.readFileSync("/sys/fs/cgroup/memory/memory.limit_in_bytes", "utf8").trim();
|
|
3241
|
+
const bytes = parseInt(raw, 10);
|
|
3242
|
+
if (Number.isFinite(bytes) && bytes > 0 && bytes < UNBOUNDED_CGROUP_THRESHOLD) {
|
|
3243
|
+
return bytes;
|
|
3244
|
+
}
|
|
3245
|
+
}
|
|
3246
|
+
} catch {
|
|
3247
|
+
}
|
|
3248
|
+
return Infinity;
|
|
3249
|
+
}
|
|
3250
|
+
function getV8HeapLimit() {
|
|
3251
|
+
try {
|
|
3252
|
+
const stats = import_node_v8.default.getHeapStatistics();
|
|
3253
|
+
if (stats && Number.isFinite(stats.heap_size_limit) && stats.heap_size_limit > 0) {
|
|
3254
|
+
return stats.heap_size_limit;
|
|
3255
|
+
}
|
|
3256
|
+
} catch {
|
|
3257
|
+
}
|
|
3258
|
+
return Infinity;
|
|
3259
|
+
}
|
|
3260
|
+
function resolveAutonomousL1MaxBytes(options) {
|
|
3261
|
+
const cgroup = options?.cgroupLimit !== void 0 ? options.cgroupLimit : readCgroupMemoryLimit();
|
|
3262
|
+
const v8Limit = options?.v8HeapLimit !== void 0 ? options.v8HeapLimit : getV8HeapLimit();
|
|
3263
|
+
const ceiling = options?.defaultCeilingBytes ?? DEFAULT_AUTONOMOUS_L1_CEILING_BYTES;
|
|
3264
|
+
const cgroupCap = Number.isFinite(cgroup) && cgroup > 0 ? cgroup * 0.4 : Infinity;
|
|
3265
|
+
const v8Cap = Number.isFinite(v8Limit) && v8Limit > 0 ? v8Limit * 0.5 : Infinity;
|
|
3266
|
+
const resolved = Math.min(cgroupCap, v8Cap, ceiling);
|
|
3267
|
+
if (!Number.isFinite(resolved) || resolved <= 0) {
|
|
3268
|
+
return ceiling;
|
|
3269
|
+
}
|
|
3270
|
+
return Math.max(MIN_AUTONOMOUS_L1_FLOOR_BYTES, Math.floor(resolved));
|
|
3271
|
+
}
|
|
3272
|
+
|
|
3273
|
+
// src/adapters/auto-pipeliner.ts
|
|
3274
|
+
var AutoPipeliner = class {
|
|
3275
|
+
constructor(client, options) {
|
|
3276
|
+
this.client = client;
|
|
3277
|
+
this.maxBatchSize = options?.maxBatchSize ?? 100;
|
|
3278
|
+
this.enabled = options?.enabled ?? true;
|
|
3279
|
+
}
|
|
3280
|
+
client;
|
|
3281
|
+
maxBatchSize;
|
|
3282
|
+
enabled;
|
|
3283
|
+
queue = [];
|
|
3284
|
+
scheduled = false;
|
|
3285
|
+
inFlight = false;
|
|
3286
|
+
statsInternal = {
|
|
3287
|
+
batchesDispatched: 0,
|
|
3288
|
+
operationsBatched: 0
|
|
3289
|
+
};
|
|
3290
|
+
get stats() {
|
|
3291
|
+
return {
|
|
3292
|
+
batchesDispatched: this.statsInternal.batchesDispatched,
|
|
3293
|
+
operationsBatched: this.statsInternal.operationsBatched,
|
|
3294
|
+
pendingQueueSize: this.queue.length
|
|
3295
|
+
};
|
|
3296
|
+
}
|
|
3297
|
+
async get(key) {
|
|
3298
|
+
if (!this.enabled || !this.supportsPipelines()) {
|
|
3299
|
+
return this.client.get(key);
|
|
3300
|
+
}
|
|
3301
|
+
return new Promise((resolve, reject) => {
|
|
3302
|
+
this.enqueue({ type: "get", key, resolve, reject });
|
|
3303
|
+
});
|
|
3304
|
+
}
|
|
3305
|
+
async setex(key, seconds, value) {
|
|
3306
|
+
if (!this.enabled || !this.supportsPipelines()) {
|
|
3307
|
+
if (typeof this.client.setex === "function") {
|
|
3308
|
+
await this.client.setex(key, seconds, value);
|
|
3309
|
+
} else {
|
|
3310
|
+
await this.client.set(key, value, "EX", seconds);
|
|
3311
|
+
}
|
|
3312
|
+
return;
|
|
3313
|
+
}
|
|
3314
|
+
return new Promise((resolve, reject) => {
|
|
3315
|
+
this.enqueue({ type: "setex", key, seconds, value, resolve, reject });
|
|
3316
|
+
});
|
|
3317
|
+
}
|
|
3318
|
+
async del(...keys) {
|
|
3319
|
+
if (keys.length === 0) return 0;
|
|
3320
|
+
if (!this.enabled || !this.supportsPipelines()) {
|
|
3321
|
+
return this.client.del(...keys);
|
|
3322
|
+
}
|
|
3323
|
+
return new Promise((resolve, reject) => {
|
|
3324
|
+
this.enqueue({ type: "del", keys, resolve, reject });
|
|
3325
|
+
});
|
|
3326
|
+
}
|
|
3327
|
+
supportsPipelines() {
|
|
3328
|
+
return Boolean(
|
|
3329
|
+
typeof this.client?.pipeline === "function" || typeof this.client?.multi === "function"
|
|
3330
|
+
);
|
|
3331
|
+
}
|
|
3332
|
+
enqueue(op) {
|
|
3333
|
+
this.queue.push(op);
|
|
3334
|
+
if (this.queue.length >= this.maxBatchSize) {
|
|
3335
|
+
void this.flush();
|
|
3336
|
+
return;
|
|
3337
|
+
}
|
|
3338
|
+
if (!this.scheduled) {
|
|
3339
|
+
this.scheduled = true;
|
|
3340
|
+
queueMicrotask(() => {
|
|
3341
|
+
this.scheduled = false;
|
|
3342
|
+
void this.flush();
|
|
3343
|
+
});
|
|
3344
|
+
}
|
|
3345
|
+
}
|
|
3346
|
+
async flush() {
|
|
3347
|
+
if (this.queue.length === 0) return;
|
|
3348
|
+
const batch = this.queue;
|
|
3349
|
+
this.queue = [];
|
|
3350
|
+
this.scheduled = false;
|
|
3351
|
+
this.statsInternal.batchesDispatched++;
|
|
3352
|
+
this.statsInternal.operationsBatched += batch.length;
|
|
3353
|
+
const pipe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
|
|
3354
|
+
for (const op of batch) {
|
|
3355
|
+
switch (op.type) {
|
|
3356
|
+
case "get":
|
|
3357
|
+
pipe.get(op.key);
|
|
3358
|
+
break;
|
|
3359
|
+
case "setex":
|
|
3360
|
+
pipe.setex(op.key, op.seconds, op.value);
|
|
3361
|
+
break;
|
|
3362
|
+
case "del":
|
|
3363
|
+
pipe.del(...op.keys);
|
|
3364
|
+
break;
|
|
3365
|
+
}
|
|
3366
|
+
}
|
|
3367
|
+
try {
|
|
3368
|
+
const results = await pipe.exec();
|
|
3369
|
+
if (!results) {
|
|
3370
|
+
for (const op of batch) {
|
|
3371
|
+
if (op.type === "get") op.resolve(null);
|
|
3372
|
+
else if (op.type === "del") op.resolve(0);
|
|
3373
|
+
else op.resolve();
|
|
3374
|
+
}
|
|
3375
|
+
return;
|
|
3376
|
+
}
|
|
3377
|
+
for (let i = 0; i < batch.length; i++) {
|
|
3378
|
+
const op = batch[i];
|
|
3379
|
+
const resTuple = results[i];
|
|
3380
|
+
if (!resTuple) {
|
|
3381
|
+
if (op.type === "get") op.resolve(null);
|
|
3382
|
+
else if (op.type === "del") op.resolve(0);
|
|
3383
|
+
else op.resolve();
|
|
3384
|
+
continue;
|
|
3385
|
+
}
|
|
3386
|
+
const [err, val] = resTuple;
|
|
3387
|
+
if (err) {
|
|
3388
|
+
op.reject(err instanceof Error ? err : new Error(String(err)));
|
|
3389
|
+
} else {
|
|
3390
|
+
if (op.type === "get") {
|
|
3391
|
+
op.resolve(val != null ? String(val) : null);
|
|
3392
|
+
} else if (op.type === "del") {
|
|
3393
|
+
op.resolve(typeof val === "number" ? val : Number(val) || 0);
|
|
3394
|
+
} else {
|
|
3395
|
+
op.resolve();
|
|
3396
|
+
}
|
|
3397
|
+
}
|
|
3398
|
+
}
|
|
3399
|
+
} catch (err) {
|
|
3400
|
+
for (const op of batch) {
|
|
3401
|
+
op.reject(err instanceof Error ? err : new Error(String(err)));
|
|
3402
|
+
}
|
|
3403
|
+
}
|
|
3404
|
+
}
|
|
3405
|
+
};
|
|
3406
|
+
|
|
3407
|
+
// src/ipc-telemetry.ts
|
|
3408
|
+
var import_node_net = __toESM(require("net"), 1);
|
|
3409
|
+
var import_node_fs2 = __toESM(require("fs"), 1);
|
|
3410
|
+
var import_node_path = __toESM(require("path"), 1);
|
|
3411
|
+
function resolveIpcSocketPath(id = process.pid) {
|
|
3412
|
+
if (process.platform === "win32") {
|
|
3413
|
+
return `\\\\.\\pipe\\tricache-${id}`;
|
|
3414
|
+
}
|
|
3415
|
+
const dir = process.env.TMPDIR || "/tmp";
|
|
3416
|
+
return import_node_path.default.join(dir, `tricache-${id}.sock`);
|
|
3417
|
+
}
|
|
3418
|
+
var IpcTelemetryServer = class {
|
|
3419
|
+
constructor(cache, customSocketPath) {
|
|
3420
|
+
this.cache = cache;
|
|
3421
|
+
this.socketPath = customSocketPath || resolveIpcSocketPath();
|
|
3422
|
+
}
|
|
3423
|
+
cache;
|
|
3424
|
+
server = null;
|
|
3425
|
+
socketPath;
|
|
3426
|
+
_closed = false;
|
|
3427
|
+
_exitHandler = null;
|
|
3428
|
+
_sigintHandler = null;
|
|
3429
|
+
_sigtermHandler = null;
|
|
3430
|
+
/**
|
|
3431
|
+
* Start listening on the IPC socket / pipe.
|
|
3432
|
+
*/
|
|
3433
|
+
async start() {
|
|
3434
|
+
if (this.server && this.server.listening) return;
|
|
3435
|
+
if (process.platform !== "win32" && import_node_fs2.default.existsSync(this.socketPath)) {
|
|
3436
|
+
await new Promise((resolve) => {
|
|
3437
|
+
const testSocket = import_node_net.default.createConnection(this.socketPath);
|
|
3438
|
+
testSocket.once("connect", () => {
|
|
3439
|
+
testSocket.destroy();
|
|
3440
|
+
resolve();
|
|
3441
|
+
});
|
|
3442
|
+
testSocket.once("error", () => {
|
|
3443
|
+
testSocket.destroy();
|
|
3444
|
+
try {
|
|
3445
|
+
import_node_fs2.default.unlinkSync(this.socketPath);
|
|
3446
|
+
} catch {
|
|
3447
|
+
}
|
|
3448
|
+
resolve();
|
|
3449
|
+
});
|
|
3450
|
+
});
|
|
3451
|
+
}
|
|
3452
|
+
this.server = import_node_net.default.createServer((socket) => {
|
|
3453
|
+
let buffer = "";
|
|
3454
|
+
socket.on("data", (chunk) => {
|
|
3455
|
+
buffer += chunk.toString("utf8");
|
|
3456
|
+
let newlineIndex;
|
|
3457
|
+
while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
|
|
3458
|
+
const line = buffer.slice(0, newlineIndex).trim();
|
|
3459
|
+
buffer = buffer.slice(newlineIndex + 1);
|
|
3460
|
+
if (!line) continue;
|
|
3461
|
+
setImmediate(() => {
|
|
3462
|
+
if (socket.destroyed) return;
|
|
3463
|
+
try {
|
|
3464
|
+
let cmd = line;
|
|
3465
|
+
try {
|
|
3466
|
+
const parsed = JSON.parse(line);
|
|
3467
|
+
if (parsed && typeof parsed.cmd === "string") {
|
|
3468
|
+
cmd = parsed.cmd;
|
|
3469
|
+
}
|
|
3470
|
+
} catch {
|
|
3471
|
+
}
|
|
3472
|
+
if (cmd === "PING") {
|
|
3473
|
+
socket.write(JSON.stringify({ pong: true, timestamp: Date.now() }) + "\n");
|
|
3474
|
+
return;
|
|
3475
|
+
}
|
|
3476
|
+
if (cmd === "GET_METRICS" || cmd === "INSPECT") {
|
|
3477
|
+
const payload = this.getSnapshot();
|
|
3478
|
+
const serialized = JSON.stringify(payload) + "\n";
|
|
3479
|
+
socket.write(serialized);
|
|
3480
|
+
return;
|
|
3481
|
+
}
|
|
3482
|
+
socket.write(JSON.stringify({ error: `Unknown command: ${cmd}` }) + "\n");
|
|
3483
|
+
} catch (err) {
|
|
3484
|
+
if (!socket.destroyed) {
|
|
3485
|
+
socket.write(JSON.stringify({ error: err.message }) + "\n");
|
|
3486
|
+
}
|
|
3487
|
+
}
|
|
3488
|
+
});
|
|
3489
|
+
}
|
|
3490
|
+
});
|
|
3491
|
+
socket.on("error", () => {
|
|
3492
|
+
});
|
|
3493
|
+
});
|
|
3494
|
+
await new Promise((resolve, reject) => {
|
|
3495
|
+
this.server.once("error", reject);
|
|
3496
|
+
this.server.listen(this.socketPath, () => {
|
|
3497
|
+
this.server.removeListener("error", reject);
|
|
3498
|
+
resolve();
|
|
3499
|
+
});
|
|
3500
|
+
});
|
|
3501
|
+
this._exitHandler = () => this._unlinkSocket();
|
|
3502
|
+
this._sigintHandler = () => {
|
|
3503
|
+
this._unlinkSocket();
|
|
3504
|
+
process.exit(0);
|
|
3505
|
+
};
|
|
3506
|
+
this._sigtermHandler = () => {
|
|
3507
|
+
this._unlinkSocket();
|
|
3508
|
+
process.exit(0);
|
|
3509
|
+
};
|
|
3510
|
+
process.once("exit", this._exitHandler);
|
|
3511
|
+
process.once("SIGINT", this._sigintHandler);
|
|
3512
|
+
process.once("SIGTERM", this._sigtermHandler);
|
|
3513
|
+
}
|
|
3514
|
+
/**
|
|
3515
|
+
* Build a complete telemetry snapshot from the underlying cache provider.
|
|
3516
|
+
*/
|
|
3517
|
+
getSnapshot() {
|
|
3518
|
+
const metrics = this.cache.metrics();
|
|
3519
|
+
const stats = typeof this.cache.stats === "function" ? this.cache.stats() : void 0;
|
|
3520
|
+
const hotKeys = typeof this.cache.hotKeys === "function" ? this.cache.hotKeys(10) : void 0;
|
|
3521
|
+
const health = typeof this.cache.health === "function" ? this.cache.health() : void 0;
|
|
3522
|
+
const l1MaxBytes = this.cache.options?.l1MaxBytes ?? metrics.l1?.maxBytes;
|
|
3523
|
+
return {
|
|
3524
|
+
pid: process.pid,
|
|
3525
|
+
uptimeMs: metrics.uptimeMs,
|
|
3526
|
+
timestamp: Date.now(),
|
|
3527
|
+
namespace: this.cache.options?.namespace || metrics.namespace,
|
|
3528
|
+
l1MaxBytes,
|
|
3529
|
+
metrics,
|
|
3530
|
+
stats,
|
|
3531
|
+
hotKeys,
|
|
3532
|
+
health
|
|
3533
|
+
};
|
|
3534
|
+
}
|
|
3535
|
+
_unlinkSocket() {
|
|
3536
|
+
if (this._closed) return;
|
|
3537
|
+
this._closed = true;
|
|
3538
|
+
try {
|
|
3539
|
+
this.server?.close();
|
|
3540
|
+
} catch {
|
|
3541
|
+
}
|
|
3542
|
+
if (process.platform !== "win32") {
|
|
3543
|
+
try {
|
|
3544
|
+
if (import_node_fs2.default.existsSync(this.socketPath)) {
|
|
3545
|
+
import_node_fs2.default.unlinkSync(this.socketPath);
|
|
3546
|
+
}
|
|
3547
|
+
} catch {
|
|
3548
|
+
}
|
|
3549
|
+
}
|
|
3550
|
+
}
|
|
3551
|
+
/**
|
|
3552
|
+
* Gracefully close the IPC telemetry server and clean up handlers and sockets.
|
|
3553
|
+
*/
|
|
3554
|
+
async close() {
|
|
3555
|
+
if (this._exitHandler) {
|
|
3556
|
+
process.removeListener("exit", this._exitHandler);
|
|
3557
|
+
this._exitHandler = null;
|
|
3558
|
+
}
|
|
3559
|
+
if (this._sigintHandler) {
|
|
3560
|
+
process.removeListener("SIGINT", this._sigintHandler);
|
|
3561
|
+
this._sigintHandler = null;
|
|
3562
|
+
}
|
|
3563
|
+
if (this._sigtermHandler) {
|
|
3564
|
+
process.removeListener("SIGTERM", this._sigtermHandler);
|
|
3565
|
+
this._sigtermHandler = null;
|
|
3566
|
+
}
|
|
3567
|
+
this._unlinkSocket();
|
|
3568
|
+
return new Promise((resolve) => {
|
|
3569
|
+
if (!this.server || !this.server.listening) {
|
|
3570
|
+
resolve();
|
|
3571
|
+
return;
|
|
3572
|
+
}
|
|
3573
|
+
this.server.close(() => resolve());
|
|
3574
|
+
});
|
|
3575
|
+
}
|
|
3576
|
+
get isListening() {
|
|
3577
|
+
return Boolean(this.server && this.server.listening);
|
|
3578
|
+
}
|
|
3579
|
+
};
|
|
3580
|
+
|
|
3581
|
+
// src/cache-service.ts
|
|
3582
|
+
var LUA_COMPARE_AND_DELETE = `
|
|
3583
|
+
local currentTs = redis.call('HGET', KEYS[1], 't')
|
|
3584
|
+
if currentTs and currentTs == ARGV[1] then
|
|
3585
|
+
return redis.call('DEL', KEYS[1])
|
|
3586
|
+
end
|
|
3587
|
+
return 0
|
|
3588
|
+
`;
|
|
3589
|
+
var SNAPSHOT_VERSION = 1;
|
|
3590
|
+
var DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
|
|
3591
|
+
var INDEFINITE_TTL_SECONDS = 31536e3;
|
|
3592
|
+
var SNAPSHOT_MAX_FILE_BYTES = 220 * 1024 * 1024;
|
|
3593
|
+
var DEFAULT_CATEGORY_LIMITS = {
|
|
3594
|
+
"default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
|
|
3595
|
+
};
|
|
3596
|
+
var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
|
|
3597
|
+
var DEFAULT_COUNTER_TTL_SECONDS = 60;
|
|
3598
|
+
var GLOB_REGEX_CACHE_MAX = 256;
|
|
3599
|
+
var globRegexCache = /* @__PURE__ */ new Map();
|
|
3600
|
+
function getGlobRegex(pattern) {
|
|
3601
|
+
let re = globRegexCache.get(pattern);
|
|
3602
|
+
if (re) {
|
|
3603
|
+
globRegexCache.delete(pattern);
|
|
3604
|
+
globRegexCache.set(pattern, re);
|
|
3605
|
+
return re;
|
|
3606
|
+
}
|
|
3607
|
+
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*+/g, ".*");
|
|
3608
|
+
re = new RegExp("^" + escaped + "$");
|
|
3609
|
+
if (globRegexCache.size >= GLOB_REGEX_CACHE_MAX) {
|
|
3610
|
+
const oldestKey = globRegexCache.keys().next().value;
|
|
3611
|
+
if (oldestKey !== void 0) globRegexCache.delete(oldestKey);
|
|
3612
|
+
}
|
|
3613
|
+
globRegexCache.set(pattern, re);
|
|
3614
|
+
return re;
|
|
3615
|
+
}
|
|
3616
|
+
var L2CircuitBreaker = class {
|
|
3617
|
+
constructor(threshold, cooldownMs) {
|
|
3618
|
+
this.threshold = threshold;
|
|
3619
|
+
this.cooldownMs = cooldownMs;
|
|
3620
|
+
}
|
|
3621
|
+
threshold;
|
|
3622
|
+
cooldownMs;
|
|
3623
|
+
state = 0 /* CLOSED */;
|
|
3624
|
+
failures = 0;
|
|
3625
|
+
openedAt = performance.now();
|
|
3626
|
+
/** True while the single permitted HALF_OPEN probe is in flight. */
|
|
3627
|
+
probing = false;
|
|
2408
3628
|
/**
|
|
2409
3629
|
* Call before each Redis attempt. Returns false when the circuit is open.
|
|
2410
3630
|
* In HALF_OPEN, only ONE probe is permitted at a time — concurrent callers
|
|
@@ -2418,7 +3638,8 @@ var L2CircuitBreaker = class {
|
|
|
2418
3638
|
this.probing = true;
|
|
2419
3639
|
return true;
|
|
2420
3640
|
}
|
|
2421
|
-
|
|
3641
|
+
const now = this.openedAt > 1e12 ? Date.now() : performance.now();
|
|
3642
|
+
if (now - this.openedAt >= this.cooldownMs) {
|
|
2422
3643
|
this.state = 2 /* HALF_OPEN */;
|
|
2423
3644
|
this.probing = true;
|
|
2424
3645
|
return true;
|
|
@@ -2437,7 +3658,7 @@ var L2CircuitBreaker = class {
|
|
|
2437
3658
|
this.probing = false;
|
|
2438
3659
|
if (this.state === 2 /* HALF_OPEN */ || this.failures >= this.threshold) {
|
|
2439
3660
|
this.state = 1 /* OPEN */;
|
|
2440
|
-
this.openedAt =
|
|
3661
|
+
this.openedAt = performance.now();
|
|
2441
3662
|
this.failures = 0;
|
|
2442
3663
|
}
|
|
2443
3664
|
}
|
|
@@ -2554,9 +3775,86 @@ function detectServerlessRuntime() {
|
|
|
2554
3775
|
if (process.env["VERCEL"]) return "Vercel";
|
|
2555
3776
|
return null;
|
|
2556
3777
|
}
|
|
3778
|
+
var ProcessTerminationBus = class {
|
|
3779
|
+
static instances = /* @__PURE__ */ new Set();
|
|
3780
|
+
static registered = false;
|
|
3781
|
+
static sigtermHandler = null;
|
|
3782
|
+
static sigintHandler = null;
|
|
3783
|
+
static register(instance) {
|
|
3784
|
+
this.instances.add(instance);
|
|
3785
|
+
if (!this.registered) {
|
|
3786
|
+
this.registered = true;
|
|
3787
|
+
this.sigtermHandler = () => {
|
|
3788
|
+
for (const inst of this.instances) {
|
|
3789
|
+
try {
|
|
3790
|
+
inst._triggerShutdown();
|
|
3791
|
+
} catch {
|
|
3792
|
+
}
|
|
3793
|
+
}
|
|
3794
|
+
};
|
|
3795
|
+
this.sigintHandler = () => {
|
|
3796
|
+
for (const inst of this.instances) {
|
|
3797
|
+
try {
|
|
3798
|
+
inst._triggerShutdown();
|
|
3799
|
+
} catch {
|
|
3800
|
+
}
|
|
3801
|
+
}
|
|
3802
|
+
};
|
|
3803
|
+
process.on("SIGTERM", this.sigtermHandler);
|
|
3804
|
+
process.on("SIGINT", this.sigintHandler);
|
|
3805
|
+
}
|
|
3806
|
+
}
|
|
3807
|
+
static unregister(instance) {
|
|
3808
|
+
this.instances.delete(instance);
|
|
3809
|
+
if (this.instances.size === 0 && this.registered) {
|
|
3810
|
+
if (this.sigtermHandler) process.removeListener("SIGTERM", this.sigtermHandler);
|
|
3811
|
+
if (this.sigintHandler) process.removeListener("SIGINT", this.sigintHandler);
|
|
3812
|
+
this.sigtermHandler = null;
|
|
3813
|
+
this.sigintHandler = null;
|
|
3814
|
+
this.registered = false;
|
|
3815
|
+
}
|
|
3816
|
+
}
|
|
3817
|
+
/**
|
|
3818
|
+
* Flushes snapshots across all active registered cache instances concurrently.
|
|
3819
|
+
* Awaits both local disk and remote cloud snapshot uploads with timeout protection.
|
|
3820
|
+
*
|
|
3821
|
+
* @param timeoutMs Timeout in milliseconds per instance before aborting slow flushes. Default: 8000ms.
|
|
3822
|
+
*/
|
|
3823
|
+
static async flushAll(timeoutMs = 8e3) {
|
|
3824
|
+
if (this.instances.size === 0) return;
|
|
3825
|
+
const tasks = Array.from(this.instances).map((inst) => inst.flushSnapshotOnShutdown(timeoutMs));
|
|
3826
|
+
await Promise.allSettled(tasks);
|
|
3827
|
+
}
|
|
3828
|
+
/** For testing diagnostics and assertions */
|
|
3829
|
+
static get size() {
|
|
3830
|
+
return this.instances.size;
|
|
3831
|
+
}
|
|
3832
|
+
static get isRegistered() {
|
|
3833
|
+
return this.registered;
|
|
3834
|
+
}
|
|
3835
|
+
};
|
|
3836
|
+
function isPlainObject(item) {
|
|
3837
|
+
return typeof item === "object" && item !== null && item.constructor === Object;
|
|
3838
|
+
}
|
|
3839
|
+
function deepMergeOptions(base, overrides) {
|
|
3840
|
+
if (!overrides) return { ...base };
|
|
3841
|
+
const output = { ...base };
|
|
3842
|
+
for (const key of Object.keys(overrides)) {
|
|
3843
|
+
const sourceVal = overrides[key];
|
|
3844
|
+
if (sourceVal === void 0) continue;
|
|
3845
|
+
const targetVal = output[key];
|
|
3846
|
+
if (isPlainObject(targetVal) && isPlainObject(sourceVal)) {
|
|
3847
|
+
output[key] = deepMergeOptions(targetVal, sourceVal);
|
|
3848
|
+
} else {
|
|
3849
|
+
output[key] = sourceVal;
|
|
3850
|
+
}
|
|
3851
|
+
}
|
|
3852
|
+
return output;
|
|
3853
|
+
}
|
|
2557
3854
|
var CacheService = class _CacheService {
|
|
2558
3855
|
logger;
|
|
2559
3856
|
enc;
|
|
3857
|
+
codec;
|
|
2560
3858
|
l1;
|
|
2561
3859
|
disk;
|
|
2562
3860
|
/** When true, all disk-tier and snapshot operations are skipped. */
|
|
@@ -2568,6 +3866,8 @@ var CacheService = class _CacheService {
|
|
|
2568
3866
|
_namespace;
|
|
2569
3867
|
/** Pre-computed once — disableRedis and redisHost never change after construction. */
|
|
2570
3868
|
_redisDisabled;
|
|
3869
|
+
watchdog;
|
|
3870
|
+
pipeliner = null;
|
|
2571
3871
|
inflight = /* @__PURE__ */ new Map();
|
|
2572
3872
|
revalidating = /* @__PURE__ */ new Set();
|
|
2573
3873
|
_l1Counters = /* @__PURE__ */ new Map();
|
|
@@ -2593,6 +3893,7 @@ var CacheService = class _CacheService {
|
|
|
2593
3893
|
diskJanitorInterval = null;
|
|
2594
3894
|
oomInterval = null;
|
|
2595
3895
|
metricsInterval = null;
|
|
3896
|
+
remoteSnapshotInterval = null;
|
|
2596
3897
|
_shutdownHandler = null;
|
|
2597
3898
|
latencyTracker = null;
|
|
2598
3899
|
instanceId;
|
|
@@ -2602,8 +3903,11 @@ var CacheService = class _CacheService {
|
|
|
2602
3903
|
streamClient = null;
|
|
2603
3904
|
_lastStreamId = "$";
|
|
2604
3905
|
_destroyed = false;
|
|
3906
|
+
_ipcServer;
|
|
2605
3907
|
/** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
|
|
2606
3908
|
_subDisconnectedAt = null;
|
|
3909
|
+
/** Deduplication ring buffer for incoming and outgoing cross-region invalidations (loop prevention) */
|
|
3910
|
+
_seenCrossRegionEvents = /* @__PURE__ */ new Map();
|
|
2607
3911
|
counters = {
|
|
2608
3912
|
gets: 0,
|
|
2609
3913
|
l1Hits: 0,
|
|
@@ -2628,7 +3932,16 @@ var CacheService = class _CacheService {
|
|
|
2628
3932
|
singletonDivergences: 0,
|
|
2629
3933
|
startedAt: Date.now(),
|
|
2630
3934
|
bloomChecks: 0,
|
|
2631
|
-
bloomFalsePositives: 0
|
|
3935
|
+
bloomFalsePositives: 0,
|
|
3936
|
+
remoteSnapshotUploads: 0,
|
|
3937
|
+
remoteSnapshotDownloads: 0,
|
|
3938
|
+
remoteSnapshotErrors: 0,
|
|
3939
|
+
remoteSnapshotLastUploadedAt: null,
|
|
3940
|
+
remoteSnapshotLastDownloadedAt: null,
|
|
3941
|
+
crossRegionSent: 0,
|
|
3942
|
+
crossRegionReceived: 0,
|
|
3943
|
+
crossRegionDeduplicated: 0,
|
|
3944
|
+
crossRegionErrors: 0
|
|
2632
3945
|
};
|
|
2633
3946
|
/** One-time guard so the in-process increment() fallback warning fires only once. */
|
|
2634
3947
|
_incrementFallbackWarned = false;
|
|
@@ -2651,16 +3964,14 @@ var CacheService = class _CacheService {
|
|
|
2651
3964
|
this.opts = {
|
|
2652
3965
|
namespace: ns,
|
|
2653
3966
|
logger,
|
|
2654
|
-
l1MaxBytes: options.l1MaxBytes ??
|
|
3967
|
+
l1MaxBytes: options.l1MaxBytes ?? resolveAutonomousL1MaxBytes(),
|
|
2655
3968
|
l1MaxEntries: options.l1MaxEntries ?? 2e3,
|
|
2656
3969
|
categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...options.categoryLimits },
|
|
2657
3970
|
forbiddenSnapshotPrefixes: forbiddenPrefixes,
|
|
2658
3971
|
// Namespace-isolated defaults: separate dir / snapshot per namespace so
|
|
2659
3972
|
// two instances with different namespaces never share cache files.
|
|
2660
|
-
|
|
2661
|
-
|
|
2662
|
-
ns ? `tricache-disk-${ns}` : "tricache-disk"
|
|
2663
|
-
),
|
|
3973
|
+
// Automatically probes /dev/shm tmpfs on Linux (>=256MB capacity and >=128MB free) for off-heap RAM speed.
|
|
3974
|
+
diskCacheDir: options.diskCacheDir ?? resolveDefaultDiskDir(ns, logger).dir,
|
|
2664
3975
|
diskMaxBytes: options.diskMaxBytes ?? 500 * 1024 * 1024,
|
|
2665
3976
|
diskEntryMaxBytes: options.diskEntryMaxBytes ?? 10 * 1024 * 1024,
|
|
2666
3977
|
redisHost: options.redisHost ?? process.env.REDIS_HOST ?? "",
|
|
@@ -2668,14 +3979,14 @@ var CacheService = class _CacheService {
|
|
|
2668
3979
|
redisTls: options.redisTls ?? process.env.NODE_ENV === "production",
|
|
2669
3980
|
disableRedis: options.disableRedis ?? (() => {
|
|
2670
3981
|
const explicitConfig = Boolean(
|
|
2671
|
-
options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
|
|
3982
|
+
options.redisClient || options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
|
|
2672
3983
|
);
|
|
2673
3984
|
return !explicitConfig && process.env.NODE_ENV !== "production";
|
|
2674
3985
|
})(),
|
|
2675
3986
|
encryptionKey: encKeyRaw,
|
|
2676
3987
|
encryptionMode: options.encryptionMode,
|
|
2677
3988
|
snapshotPath: options.snapshotPath ?? import_path3.default.join(
|
|
2678
|
-
|
|
3989
|
+
import_os3.default.tmpdir(),
|
|
2679
3990
|
ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
|
|
2680
3991
|
),
|
|
2681
3992
|
snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
|
|
@@ -2723,8 +4034,35 @@ var CacheService = class _CacheService {
|
|
|
2723
4034
|
backplaneMode: options.backplaneMode ?? "pubsub",
|
|
2724
4035
|
backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
|
|
2725
4036
|
backplaneStreamBlockMs: options.backplaneStreamBlockMs ?? 2e3,
|
|
2726
|
-
backplaneStreamKey: options.backplaneStreamKey
|
|
4037
|
+
backplaneStreamKey: options.backplaneStreamKey,
|
|
4038
|
+
serializeToJSON: options.serializeToJSON ?? true,
|
|
4039
|
+
remoteSnapshot: options.remoteSnapshot,
|
|
4040
|
+
crossRegion: options.crossRegion,
|
|
4041
|
+
redisClient: options.redisClient,
|
|
4042
|
+
redisSubClient: options.redisSubClient,
|
|
4043
|
+
diskMaxConcurrentWrites: options.diskMaxConcurrentWrites,
|
|
4044
|
+
diskMaxPendingWrites: options.diskMaxPendingWrites,
|
|
4045
|
+
diskWriteTimeoutMs: options.diskWriteTimeoutMs,
|
|
4046
|
+
diskCircuitBreakerThreshold: options.diskCircuitBreakerThreshold,
|
|
4047
|
+
diskCircuitBreakerCooldownMs: options.diskCircuitBreakerCooldownMs,
|
|
4048
|
+
redisCommandTimeoutMs: options.redisCommandTimeoutMs,
|
|
4049
|
+
clockSkewToleranceMs: options.clockSkewToleranceMs ?? 250,
|
|
4050
|
+
l1AdmissionPolicy: options.l1AdmissionPolicy,
|
|
4051
|
+
diskLatencyWatchdog: options.diskLatencyWatchdog ?? true,
|
|
4052
|
+
diskLatencyBypassRatio: options.diskLatencyBypassRatio ?? 1.5,
|
|
4053
|
+
diskLatencyBypassMinMs: options.diskLatencyBypassMinMs ?? 10,
|
|
4054
|
+
diskLatencyBypassCooldownMs: options.diskLatencyBypassCooldownMs ?? 3e4,
|
|
4055
|
+
failReadinessOnDegraded: options.failReadinessOnDegraded ?? false,
|
|
4056
|
+
autoPipeline: options.autoPipeline ?? false,
|
|
4057
|
+
maxPipelineBatchSize: options.maxPipelineBatchSize ?? 100,
|
|
4058
|
+
enableIpc: options.enableIpc ?? false,
|
|
4059
|
+
ipcSocketPath: options.ipcSocketPath
|
|
2727
4060
|
};
|
|
4061
|
+
this.codec = new CacheCodec({
|
|
4062
|
+
useToJSON: this.opts.serializeToJSON,
|
|
4063
|
+
useRecords: true,
|
|
4064
|
+
moreTypes: true
|
|
4065
|
+
});
|
|
2728
4066
|
const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
|
|
2729
4067
|
const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
|
|
2730
4068
|
this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
|
|
@@ -2755,15 +4093,33 @@ var CacheService = class _CacheService {
|
|
|
2755
4093
|
encryption: this.enc.isEnabled ? this.enc : null,
|
|
2756
4094
|
compression: this.opts.compression,
|
|
2757
4095
|
compressionThresholdBytes: this.opts.compressionThresholdBytes,
|
|
2758
|
-
logger
|
|
4096
|
+
logger,
|
|
4097
|
+
codec: this.codec,
|
|
4098
|
+
diskMaxConcurrentWrites: this.opts.diskMaxConcurrentWrites,
|
|
4099
|
+
diskMaxPendingWrites: this.opts.diskMaxPendingWrites,
|
|
4100
|
+
diskWriteTimeoutMs: this.opts.diskWriteTimeoutMs,
|
|
4101
|
+
diskCircuitBreakerThreshold: this.opts.diskCircuitBreakerThreshold,
|
|
4102
|
+
diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs
|
|
2759
4103
|
});
|
|
2760
4104
|
this._namespace = ns;
|
|
2761
|
-
this._redisDisabled = this.opts.disableRedis || !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
|
|
4105
|
+
this._redisDisabled = this.opts.disableRedis || !this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
|
|
4106
|
+
this.watchdog = new TierLatencyWatchdog({
|
|
4107
|
+
enabled: options.diskLatencyWatchdog ?? true,
|
|
4108
|
+
minDiskBypassMs: options.diskLatencyBypassMinMs ?? 10,
|
|
4109
|
+
bypassRatio: options.diskLatencyBypassRatio ?? 1.5,
|
|
4110
|
+
cooldownMs: options.diskLatencyBypassCooldownMs ?? 3e4,
|
|
4111
|
+
redisCutoffMs: 15,
|
|
4112
|
+
redisRecoveryFloorMs: 10,
|
|
4113
|
+
minSamples: 16,
|
|
4114
|
+
disableRedis: this._redisDisabled
|
|
4115
|
+
});
|
|
2762
4116
|
this.l1 = new SmartMemoryCache({
|
|
2763
4117
|
maxBytes: this.opts.l1MaxBytes,
|
|
2764
4118
|
maxEntries: this.opts.l1MaxEntries,
|
|
2765
4119
|
categories: this.opts.categoryLimits,
|
|
2766
4120
|
evictionWatermark: this.opts.l1EvictionWatermark,
|
|
4121
|
+
admissionPolicy: this.opts.l1AdmissionPolicy,
|
|
4122
|
+
codec: this.codec,
|
|
2767
4123
|
diskSpill: (key, entry) => {
|
|
2768
4124
|
if (this._diskDisabled) return;
|
|
2769
4125
|
setImmediate(() => {
|
|
@@ -2778,10 +4134,9 @@ var CacheService = class _CacheService {
|
|
|
2778
4134
|
if (!this._diskDisabled) this.loadSnapshot();
|
|
2779
4135
|
}
|
|
2780
4136
|
this._shutdownHandler = () => {
|
|
2781
|
-
|
|
4137
|
+
this._triggerShutdown();
|
|
2782
4138
|
};
|
|
2783
|
-
|
|
2784
|
-
process.once("SIGINT", this._shutdownHandler);
|
|
4139
|
+
ProcessTerminationBus.register(this);
|
|
2785
4140
|
if (this.opts.workerThreads) {
|
|
2786
4141
|
try {
|
|
2787
4142
|
const encRef = this.enc.toWorkerInit();
|
|
@@ -2821,7 +4176,7 @@ var CacheService = class _CacheService {
|
|
|
2821
4176
|
}
|
|
2822
4177
|
if (this.opts.oomProtection) {
|
|
2823
4178
|
this.oomInterval = setInterval(() => {
|
|
2824
|
-
const heap =
|
|
4179
|
+
const heap = import_node_v82.default.getHeapStatistics();
|
|
2825
4180
|
const used = heap.used_heap_size / heap.heap_size_limit;
|
|
2826
4181
|
if (used >= this.opts.oomHeapThreshold) {
|
|
2827
4182
|
const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
|
|
@@ -2845,12 +4200,25 @@ var CacheService = class _CacheService {
|
|
|
2845
4200
|
}, this.opts.metricsIntervalMs);
|
|
2846
4201
|
if (this.metricsInterval.unref) this.metricsInterval.unref();
|
|
2847
4202
|
}
|
|
4203
|
+
if (this.opts.remoteSnapshot?.intervalMs && this.opts.remoteSnapshot.intervalMs > 0) {
|
|
4204
|
+
this.remoteSnapshotInterval = setInterval(() => {
|
|
4205
|
+
void this.writeRemoteSnapshot();
|
|
4206
|
+
}, this.opts.remoteSnapshot.intervalMs);
|
|
4207
|
+
if (this.remoteSnapshotInterval.unref) this.remoteSnapshotInterval.unref();
|
|
4208
|
+
}
|
|
2848
4209
|
this.instanceId = import_crypto3.default.randomBytes(8).toString("hex");
|
|
2849
4210
|
this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
|
|
2850
4211
|
this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
|
|
2851
4212
|
this.initBackplane();
|
|
4213
|
+
const startupPromises = [];
|
|
4214
|
+
if (this.opts.remoteSnapshot) {
|
|
4215
|
+
startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
|
|
4216
|
+
}
|
|
2852
4217
|
if (this.opts.warmKeys) {
|
|
2853
|
-
|
|
4218
|
+
startupPromises.push(this.warmFromL2(this.opts.warmKeys).then(() => void 0));
|
|
4219
|
+
}
|
|
4220
|
+
if (startupPromises.length > 0) {
|
|
4221
|
+
this._readyPromise = Promise.all(startupPromises).then(() => void 0);
|
|
2854
4222
|
}
|
|
2855
4223
|
if (this.opts.meter) {
|
|
2856
4224
|
this._initOtelMetrics(this.opts.meter);
|
|
@@ -2871,8 +4239,71 @@ var CacheService = class _CacheService {
|
|
|
2871
4239
|
}
|
|
2872
4240
|
});
|
|
2873
4241
|
}
|
|
4242
|
+
if (this.opts.enableIpc) {
|
|
4243
|
+
this._ipcServer = new IpcTelemetryServer(this, this.opts.ipcSocketPath);
|
|
4244
|
+
this._ipcServer.start().catch((err) => {
|
|
4245
|
+
this.logger.warn("Failed to start IPC telemetry server", { error: err.message });
|
|
4246
|
+
});
|
|
4247
|
+
}
|
|
4248
|
+
}
|
|
4249
|
+
// ── Singleton factory & Presets ───────────────────────────────────────────
|
|
4250
|
+
/**
|
|
4251
|
+
* Pre-configured production presets tailored for specific deployment environments.
|
|
4252
|
+
*
|
|
4253
|
+
* - `'nextjs'`: W-TinyLFU, zero-copy cloneStrategy: 'none' (React 19 RSC stream optimized),
|
|
4254
|
+
* generational tags, and Redis stream backplane.
|
|
4255
|
+
* - `'microservice'`: High-throughput Node.js microservice with W-TinyLFU, Streams backplane,
|
|
4256
|
+
* TTL jitter, and L2 circuit breaking.
|
|
4257
|
+
* - `'serverless'`: Stateless Lambda / Cloud Run isolate with memory-only L1, fast timeouts,
|
|
4258
|
+
* and Pub/Sub backplane.
|
|
4259
|
+
* - `'enterprise-hardened'`: Zero-trust production setup with generational tagging, Streams backplane,
|
|
4260
|
+
* fail-closed rate-limits, strict singleton assertions, and 80% OOM guard.
|
|
4261
|
+
*
|
|
4262
|
+
* @param type The preset identifier ('nextjs' | 'microservice' | 'serverless' | 'enterprise-hardened')
|
|
4263
|
+
* @param overrides Optional configuration overrides merged deeply over preset defaults
|
|
4264
|
+
* @returns Singleton CacheService instance configured according to the preset
|
|
4265
|
+
*/
|
|
4266
|
+
static preset(type, overrides) {
|
|
4267
|
+
const PRESETS = {
|
|
4268
|
+
"nextjs": {
|
|
4269
|
+
l1AdmissionPolicy: "wtinylfu",
|
|
4270
|
+
cloneStrategy: "none",
|
|
4271
|
+
tagStrategy: "generational",
|
|
4272
|
+
tagVersionTtlMs: 2e3,
|
|
4273
|
+
backplaneMode: "stream",
|
|
4274
|
+
staleIfError: 300,
|
|
4275
|
+
compression: "none"
|
|
4276
|
+
},
|
|
4277
|
+
"microservice": {
|
|
4278
|
+
l1AdmissionPolicy: "wtinylfu",
|
|
4279
|
+
backplaneMode: "stream",
|
|
4280
|
+
ttlJitterFactor: 0.15,
|
|
4281
|
+
l2CircuitBreakerThreshold: 5,
|
|
4282
|
+
l2CircuitBreakerCooldownMs: 15e3
|
|
4283
|
+
},
|
|
4284
|
+
"serverless": {
|
|
4285
|
+
disableDisk: true,
|
|
4286
|
+
l1AdmissionPolicy: "wtinylfu",
|
|
4287
|
+
backplaneMode: "pubsub",
|
|
4288
|
+
redisCommandTimeoutMs: 1e3
|
|
4289
|
+
},
|
|
4290
|
+
"enterprise-hardened": {
|
|
4291
|
+
l1AdmissionPolicy: "wtinylfu",
|
|
4292
|
+
tagStrategy: "generational",
|
|
4293
|
+
backplaneMode: "stream",
|
|
4294
|
+
strictSingleton: true,
|
|
4295
|
+
failClosed: true,
|
|
4296
|
+
oomProtection: true,
|
|
4297
|
+
oomHeapThreshold: 0.8
|
|
4298
|
+
}
|
|
4299
|
+
};
|
|
4300
|
+
const base = PRESETS[type];
|
|
4301
|
+
if (!base) {
|
|
4302
|
+
throw new Error(`tricache: unknown preset '${type}'. Supported presets: 'nextjs', 'microservice', 'serverless', 'enterprise-hardened'`);
|
|
4303
|
+
}
|
|
4304
|
+
const merged = deepMergeOptions(base, overrides);
|
|
4305
|
+
return _CacheService.create(merged);
|
|
2874
4306
|
}
|
|
2875
|
-
// ── Singleton factory ─────────────────────────────────────────────────────
|
|
2876
4307
|
/**
|
|
2877
4308
|
* Get (or create) the process-level singleton CacheService instance.
|
|
2878
4309
|
*
|
|
@@ -2966,7 +4397,9 @@ var CacheService = class _CacheService {
|
|
|
2966
4397
|
frozen: o.frozen,
|
|
2967
4398
|
adaptiveTtl: o.adaptiveTtl,
|
|
2968
4399
|
invalidationBackplane: o.invalidationBackplane,
|
|
2969
|
-
strictSingleton: o.strictSingleton
|
|
4400
|
+
strictSingleton: o.strictSingleton,
|
|
4401
|
+
remoteSnapshot: o.remoteSnapshot,
|
|
4402
|
+
crossRegion: o.crossRegion
|
|
2970
4403
|
};
|
|
2971
4404
|
}
|
|
2972
4405
|
/**
|
|
@@ -3025,15 +4458,30 @@ var CacheService = class _CacheService {
|
|
|
3025
4458
|
setStatus() {
|
|
3026
4459
|
return this;
|
|
3027
4460
|
},
|
|
4461
|
+
recordException() {
|
|
4462
|
+
return this;
|
|
4463
|
+
},
|
|
3028
4464
|
end() {
|
|
3029
4465
|
}
|
|
3030
4466
|
};
|
|
3031
4467
|
/** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
|
|
3032
|
-
_startSpan(name) {
|
|
3033
|
-
if (this.opts.tracer)
|
|
4468
|
+
_startSpan(name, links) {
|
|
4469
|
+
if (this.opts.tracer) {
|
|
4470
|
+
const span = this.opts.tracer.startSpan(name, links?.length ? { links } : void 0);
|
|
4471
|
+
if (this.opts.namespace) {
|
|
4472
|
+
span.setAttribute("cache.namespace", this.opts.namespace);
|
|
4473
|
+
}
|
|
4474
|
+
return span;
|
|
4475
|
+
}
|
|
3034
4476
|
return _CacheService._nullSpan;
|
|
3035
4477
|
}
|
|
3036
4478
|
createDedicatedRedisClient() {
|
|
4479
|
+
if (this.opts.redisSubClient) {
|
|
4480
|
+
return this.opts.redisSubClient;
|
|
4481
|
+
}
|
|
4482
|
+
if (this.opts.redisClient && typeof this.opts.redisClient.duplicate === "function") {
|
|
4483
|
+
return this.opts.redisClient.duplicate();
|
|
4484
|
+
}
|
|
3037
4485
|
if (this.opts.redisClusterNodes?.length) {
|
|
3038
4486
|
return new import_ioredis.Cluster(this.opts.redisClusterNodes, {
|
|
3039
4487
|
redisOptions: {
|
|
@@ -3267,7 +4715,13 @@ var CacheService = class _CacheService {
|
|
|
3267
4715
|
this.logger.warn("Backplane: malformed message JSON parse failed");
|
|
3268
4716
|
}
|
|
3269
4717
|
}
|
|
3270
|
-
async publishInvalidation(op, key, tagVersion) {
|
|
4718
|
+
async publishInvalidation(op, key, tagVersion, isCrossRegionRelay = false, isExplicitInvalidation = false) {
|
|
4719
|
+
if (!isCrossRegionRelay && this.opts.crossRegion) {
|
|
4720
|
+
const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
|
|
4721
|
+
if (shouldBroadcast) {
|
|
4722
|
+
void this._broadcastCrossRegion(op, key, tagVersion);
|
|
4723
|
+
}
|
|
4724
|
+
}
|
|
3271
4725
|
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
3272
4726
|
try {
|
|
3273
4727
|
const client = await this.getRedis();
|
|
@@ -3309,7 +4763,80 @@ var CacheService = class _CacheService {
|
|
|
3309
4763
|
} catch {
|
|
3310
4764
|
}
|
|
3311
4765
|
}
|
|
3312
|
-
|
|
4766
|
+
_markCrossRegionEventSeen(id) {
|
|
4767
|
+
const maxDedup = this.opts.crossRegion?.dedupCacheSize ?? 1e4;
|
|
4768
|
+
if (this._seenCrossRegionEvents.size >= maxDedup) {
|
|
4769
|
+
const oldestKey = this._seenCrossRegionEvents.keys().next().value;
|
|
4770
|
+
if (oldestKey !== void 0) this._seenCrossRegionEvents.delete(oldestKey);
|
|
4771
|
+
}
|
|
4772
|
+
this._seenCrossRegionEvents.set(id, Date.now());
|
|
4773
|
+
}
|
|
4774
|
+
_isCrossRegionEventSeen(id) {
|
|
4775
|
+
return this._seenCrossRegionEvents.has(id);
|
|
4776
|
+
}
|
|
4777
|
+
async _broadcastCrossRegion(op, key, tagVersion) {
|
|
4778
|
+
const cr = this.opts.crossRegion;
|
|
4779
|
+
if (!cr) return;
|
|
4780
|
+
try {
|
|
4781
|
+
const eventId = import_crypto3.default.randomUUID();
|
|
4782
|
+
this._markCrossRegionEventSeen(eventId);
|
|
4783
|
+
const event = {
|
|
4784
|
+
id: eventId,
|
|
4785
|
+
originRegion: cr.currentRegion,
|
|
4786
|
+
originInstanceId: this.instanceId,
|
|
4787
|
+
op,
|
|
4788
|
+
key,
|
|
4789
|
+
tagVersion,
|
|
4790
|
+
timestamp: Date.now(),
|
|
4791
|
+
namespace: this._namespace || void 0
|
|
4792
|
+
};
|
|
4793
|
+
this.counters.crossRegionSent++;
|
|
4794
|
+
await cr.relay.broadcast(event);
|
|
4795
|
+
this.logger.debug("Cross-region invalidation broadcast", { op, key, region: cr.currentRegion });
|
|
4796
|
+
} catch (err) {
|
|
4797
|
+
this.counters.crossRegionSent = Math.max(0, this.counters.crossRegionSent - 1);
|
|
4798
|
+
this.counters.crossRegionErrors++;
|
|
4799
|
+
this.logger.warn("Cross-region invalidation broadcast failed", { error: err.message });
|
|
4800
|
+
}
|
|
4801
|
+
}
|
|
4802
|
+
/**
|
|
4803
|
+
* Receives an invalidation event from another region (e.g. via HTTP webhook or broker subscriber).
|
|
4804
|
+
* Validates origin, deduplicates to prevent loops, applies locally to L1/disk,
|
|
4805
|
+
* and fans out to the local Redis backplane so all regional peers invalidate as well.
|
|
4806
|
+
*
|
|
4807
|
+
* Returns true if the event was accepted and applied, or false if ignored/deduplicated.
|
|
4808
|
+
*/
|
|
4809
|
+
async receiveCrossRegionInvalidation(event) {
|
|
4810
|
+
const cr = this.opts.crossRegion;
|
|
4811
|
+
if (!cr) return false;
|
|
4812
|
+
if (!event || typeof event !== "object" || !event.id || !event.originRegion || !event.op || !event.key) {
|
|
4813
|
+
this.counters.crossRegionErrors++;
|
|
4814
|
+
this.logger.warn("Cross-region: rejected invalid event payload", { event });
|
|
4815
|
+
return false;
|
|
4816
|
+
}
|
|
4817
|
+
if (event.originRegion === cr.currentRegion) {
|
|
4818
|
+
this.counters.crossRegionDeduplicated++;
|
|
4819
|
+
return false;
|
|
4820
|
+
}
|
|
4821
|
+
if (this._isCrossRegionEventSeen(event.id)) {
|
|
4822
|
+
this.counters.crossRegionDeduplicated++;
|
|
4823
|
+
return false;
|
|
4824
|
+
}
|
|
4825
|
+
this._markCrossRegionEventSeen(event.id);
|
|
4826
|
+
if (event.namespace !== void 0 && event.namespace !== (this._namespace || void 0)) {
|
|
4827
|
+
return false;
|
|
4828
|
+
}
|
|
4829
|
+
this.counters.crossRegionReceived++;
|
|
4830
|
+
this._applyInvalidationEvent(event.op, event.key, event.tagVersion);
|
|
4831
|
+
void this.publishInvalidation(event.op, event.key, event.tagVersion, true);
|
|
4832
|
+
this.logger.info("Cross-region invalidation applied", {
|
|
4833
|
+
op: event.op,
|
|
4834
|
+
key: event.key,
|
|
4835
|
+
originRegion: event.originRegion
|
|
4836
|
+
});
|
|
4837
|
+
return true;
|
|
4838
|
+
}
|
|
4839
|
+
_setLocalTagVersion(tag, version, now = performance.now()) {
|
|
3313
4840
|
const existing = this.tagVersions.get(tag)?.version ?? 0;
|
|
3314
4841
|
const finalVersion = Math.max(existing, version);
|
|
3315
4842
|
if (this.tagVersions.size >= 1e4 && !this.tagVersions.has(tag)) {
|
|
@@ -3319,7 +4846,7 @@ var CacheService = class _CacheService {
|
|
|
3319
4846
|
this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
|
|
3320
4847
|
}
|
|
3321
4848
|
async _getTagVersion(tag) {
|
|
3322
|
-
const now =
|
|
4849
|
+
const now = performance.now();
|
|
3323
4850
|
const local = this.tagVersions.get(tag);
|
|
3324
4851
|
if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
|
|
3325
4852
|
return local.version;
|
|
@@ -3405,13 +4932,25 @@ var CacheService = class _CacheService {
|
|
|
3405
4932
|
stream.on("error", reject);
|
|
3406
4933
|
})
|
|
3407
4934
|
));
|
|
3408
|
-
} else {
|
|
4935
|
+
} else if (typeof client.scanStream === "function") {
|
|
3409
4936
|
await new Promise((resolve, reject) => {
|
|
3410
4937
|
const stream = client.scanStream({ match: pattern, count: 100 });
|
|
3411
4938
|
stream.on("data", (chunk) => keys.push(...chunk));
|
|
3412
4939
|
stream.on("end", resolve);
|
|
3413
4940
|
stream.on("error", reject);
|
|
3414
4941
|
});
|
|
4942
|
+
} else if (typeof client.scanIterator === "function") {
|
|
4943
|
+
for await (const key of client.scanIterator({ MATCH: pattern, COUNT: 100 })) {
|
|
4944
|
+
keys.push(key);
|
|
4945
|
+
}
|
|
4946
|
+
} else if (typeof client.scan === "function") {
|
|
4947
|
+
let cursor = "0";
|
|
4948
|
+
do {
|
|
4949
|
+
const res = await client.scan(cursor, "MATCH", pattern, "COUNT", 100);
|
|
4950
|
+
cursor = String(res[0]);
|
|
4951
|
+
const chunk = res[1];
|
|
4952
|
+
if (chunk?.length) keys.push(...chunk);
|
|
4953
|
+
} while (cursor !== "0");
|
|
3415
4954
|
}
|
|
3416
4955
|
return keys;
|
|
3417
4956
|
}
|
|
@@ -3428,6 +4967,19 @@ var CacheService = class _CacheService {
|
|
|
3428
4967
|
if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
|
|
3429
4968
|
if (this.redis) return this.redis;
|
|
3430
4969
|
if (this.redisConnecting) return this.redisConnecting;
|
|
4970
|
+
if (this.opts.redisClient) {
|
|
4971
|
+
const client = this.opts.redisClient;
|
|
4972
|
+
if (typeof client.connect === "function" && client.isOpen === false) {
|
|
4973
|
+
await client.connect();
|
|
4974
|
+
}
|
|
4975
|
+
this.cb.onSuccess();
|
|
4976
|
+
this.redis = client;
|
|
4977
|
+
this.pipeliner = new AutoPipeliner(client, {
|
|
4978
|
+
enabled: this.opts.autoPipeline,
|
|
4979
|
+
maxBatchSize: this.opts.maxPipelineBatchSize
|
|
4980
|
+
});
|
|
4981
|
+
return client;
|
|
4982
|
+
}
|
|
3431
4983
|
this.redisConnecting = (async () => {
|
|
3432
4984
|
try {
|
|
3433
4985
|
let client;
|
|
@@ -3436,6 +4988,7 @@ var CacheService = class _CacheService {
|
|
|
3436
4988
|
redisOptions: {
|
|
3437
4989
|
tls: this.opts.redisTls ? {} : void 0,
|
|
3438
4990
|
connectTimeout: 1e4,
|
|
4991
|
+
commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
|
|
3439
4992
|
maxRetriesPerRequest: 3,
|
|
3440
4993
|
keepAlive: 3e4,
|
|
3441
4994
|
...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
|
|
@@ -3456,6 +5009,7 @@ var CacheService = class _CacheService {
|
|
|
3456
5009
|
name: this.opts.redisSentinel.name,
|
|
3457
5010
|
tls: this.opts.redisTls ? {} : void 0,
|
|
3458
5011
|
connectTimeout: 1e4,
|
|
5012
|
+
commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
|
|
3459
5013
|
lazyConnect: false,
|
|
3460
5014
|
maxRetriesPerRequest: 3,
|
|
3461
5015
|
enableAutoPipelining: true,
|
|
@@ -3475,6 +5029,7 @@ var CacheService = class _CacheService {
|
|
|
3475
5029
|
port: this.opts.redisPort,
|
|
3476
5030
|
tls: this.opts.redisTls ? {} : void 0,
|
|
3477
5031
|
connectTimeout: 1e4,
|
|
5032
|
+
commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
|
|
3478
5033
|
lazyConnect: false,
|
|
3479
5034
|
maxRetriesPerRequest: 3,
|
|
3480
5035
|
enableAutoPipelining: true,
|
|
@@ -3500,6 +5055,10 @@ var CacheService = class _CacheService {
|
|
|
3500
5055
|
});
|
|
3501
5056
|
this.cb.onSuccess();
|
|
3502
5057
|
this.redis = client;
|
|
5058
|
+
this.pipeliner = new AutoPipeliner(client, {
|
|
5059
|
+
enabled: this.opts.autoPipeline,
|
|
5060
|
+
maxBatchSize: this.opts.maxPipelineBatchSize
|
|
5061
|
+
});
|
|
3503
5062
|
this.redisConnecting = null;
|
|
3504
5063
|
return client;
|
|
3505
5064
|
} catch (err) {
|
|
@@ -3512,12 +5071,18 @@ var CacheService = class _CacheService {
|
|
|
3512
5071
|
return this.redisConnecting;
|
|
3513
5072
|
}
|
|
3514
5073
|
// ── Snapshot (cold-start persistence) ────────────────────────────────────
|
|
5074
|
+
/**
|
|
5075
|
+
* Writes the cold-start snapshot to disk.
|
|
5076
|
+
* NOTE: fs.writeFileSync is INTENTIONAL here: this method is invoked during SIGTERM/SIGINT
|
|
5077
|
+
* process termination hooks where asynchronous I/O would risk the Node.js event loop dying or
|
|
5078
|
+
* process.exit() being called before the snapshot is physically written to disk.
|
|
5079
|
+
*/
|
|
3515
5080
|
writeSnapshot(altPath) {
|
|
3516
5081
|
try {
|
|
3517
5082
|
const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
|
|
3518
5083
|
if (entries.length === 0) return;
|
|
3519
5084
|
const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
|
|
3520
|
-
const packed =
|
|
5085
|
+
const packed = this.codec.encode(payload);
|
|
3521
5086
|
const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
|
|
3522
5087
|
const dest = altPath ?? this.opts.snapshotPath;
|
|
3523
5088
|
import_fs3.default.mkdirSync(import_path3.default.dirname(dest), { recursive: true });
|
|
@@ -3532,6 +5097,12 @@ var CacheService = class _CacheService {
|
|
|
3532
5097
|
this.logger.warn("Cache snapshot write failed", { error: err.message });
|
|
3533
5098
|
}
|
|
3534
5099
|
}
|
|
5100
|
+
/**
|
|
5101
|
+
* Loads cold-start snapshot from disk into L1 memory.
|
|
5102
|
+
* NOTE: fs.readFileSync is INTENTIONAL here: this method is invoked synchronously inside the
|
|
5103
|
+
* CacheService constructor so that the cache is atomically populated before any subsequent
|
|
5104
|
+
* cache.get() or cache.set() operations run, eliminating cold-start race conditions.
|
|
5105
|
+
*/
|
|
3535
5106
|
loadSnapshot() {
|
|
3536
5107
|
const snapshotPath = this.opts.snapshotPath;
|
|
3537
5108
|
try {
|
|
@@ -3551,13 +5122,25 @@ var CacheService = class _CacheService {
|
|
|
3551
5122
|
this.logger.warn("Snapshot rejected: decryption failed", { error: e.message });
|
|
3552
5123
|
return;
|
|
3553
5124
|
}
|
|
3554
|
-
const snapshot =
|
|
5125
|
+
const snapshot = this.codec.decode(buf);
|
|
3555
5126
|
if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
|
|
3556
5127
|
this.logger.warn("Snapshot rejected: version mismatch", { got: snapshot?.version });
|
|
3557
5128
|
return;
|
|
3558
5129
|
}
|
|
3559
|
-
const
|
|
3560
|
-
|
|
5130
|
+
const now = Date.now();
|
|
5131
|
+
const writtenAt = snapshot.writtenAt ?? 0;
|
|
5132
|
+
const tolerance = this.opts.clockSkewToleranceMs ?? 250;
|
|
5133
|
+
if (writtenAt - now > tolerance) {
|
|
5134
|
+
this.logger.warn("Snapshot rejected: timestamp too far in future (exceeds clock skew tolerance)", {
|
|
5135
|
+
writtenAt,
|
|
5136
|
+
now,
|
|
5137
|
+
skewMs: writtenAt - now,
|
|
5138
|
+
tolerance
|
|
5139
|
+
});
|
|
5140
|
+
return;
|
|
5141
|
+
}
|
|
5142
|
+
const ageMs = Math.max(0, now - writtenAt);
|
|
5143
|
+
if (ageMs > this.opts.snapshotMaxAgeMs) {
|
|
3561
5144
|
this.logger.warn("Snapshot rejected: too old", { ageMinutes: Math.round(ageMs / 6e4) });
|
|
3562
5145
|
return;
|
|
3563
5146
|
}
|
|
@@ -3579,6 +5162,115 @@ var CacheService = class _CacheService {
|
|
|
3579
5162
|
}
|
|
3580
5163
|
}
|
|
3581
5164
|
}
|
|
5165
|
+
// ── Remote Snapshot (cold-start persistence for stateless containers) ───────
|
|
5166
|
+
/**
|
|
5167
|
+
* Persists the cold-start snapshot to remote blob storage (S3, GCS, R2, HTTP).
|
|
5168
|
+
* Can be awaited during graceful application shutdown (e.g. Kubernetes preStop or NestJS shutdown).
|
|
5169
|
+
* Returns true if a snapshot was successfully exported and written; false otherwise.
|
|
5170
|
+
*/
|
|
5171
|
+
async writeRemoteSnapshot() {
|
|
5172
|
+
if (!this.opts.remoteSnapshot) return false;
|
|
5173
|
+
try {
|
|
5174
|
+
const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
|
|
5175
|
+
if (entries.length === 0) return false;
|
|
5176
|
+
const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
|
|
5177
|
+
const packed = this.codec.encode(payload);
|
|
5178
|
+
let final;
|
|
5179
|
+
if (this.opts.remoteSnapshot.envelope) {
|
|
5180
|
+
final = await EnvelopeEncryption.encrypt(packed, this.opts.remoteSnapshot.envelope);
|
|
5181
|
+
} else {
|
|
5182
|
+
final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
|
|
5183
|
+
}
|
|
5184
|
+
await this.opts.remoteSnapshot.adapter.put(final);
|
|
5185
|
+
this.counters.remoteSnapshotUploads++;
|
|
5186
|
+
this.counters.remoteSnapshotLastUploadedAt = Date.now();
|
|
5187
|
+
this.logger.info("Remote cache snapshot uploaded", {
|
|
5188
|
+
entries: entries.length,
|
|
5189
|
+
sizeKB: Math.round(final.length / 1024),
|
|
5190
|
+
encrypted: Boolean(this.opts.remoteSnapshot.envelope || this.enc.isEnabled)
|
|
5191
|
+
});
|
|
5192
|
+
return true;
|
|
5193
|
+
} catch (err) {
|
|
5194
|
+
this.counters.remoteSnapshotErrors++;
|
|
5195
|
+
this.logger.warn("Remote cache snapshot upload failed", { error: err.message });
|
|
5196
|
+
return false;
|
|
5197
|
+
}
|
|
5198
|
+
}
|
|
5199
|
+
/**
|
|
5200
|
+
* Hydrates L1 memory from remote blob storage (S3, GCS, R2, HTTP).
|
|
5201
|
+
* Called automatically during startup (chained into `cache.ready()`).
|
|
5202
|
+
* Returns the number of entries successfully imported.
|
|
5203
|
+
*/
|
|
5204
|
+
async loadRemoteSnapshot() {
|
|
5205
|
+
if (!this.opts.remoteSnapshot) return 0;
|
|
5206
|
+
const maxAgeMs = this.opts.remoteSnapshot.maxAgeMs ?? this.opts.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE;
|
|
5207
|
+
try {
|
|
5208
|
+
const raw = await this.opts.remoteSnapshot.adapter.get();
|
|
5209
|
+
if (!raw || raw.length === 0) {
|
|
5210
|
+
this.logger.debug("Remote snapshot not found or empty \u2014 starting cold");
|
|
5211
|
+
return 0;
|
|
5212
|
+
}
|
|
5213
|
+
const rawBuf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
|
|
5214
|
+
let buf;
|
|
5215
|
+
try {
|
|
5216
|
+
if (EnvelopeEncryption.isEnvelope(rawBuf)) {
|
|
5217
|
+
if (!this.opts.remoteSnapshot.envelope) {
|
|
5218
|
+
throw new Error("Remote snapshot is envelope-encrypted but no envelope options (privateKey or kmsDecrypt) were configured");
|
|
5219
|
+
}
|
|
5220
|
+
buf = await EnvelopeEncryption.decrypt(rawBuf, this.opts.remoteSnapshot.envelope);
|
|
5221
|
+
} else {
|
|
5222
|
+
buf = this.enc.decryptBuffer(rawBuf);
|
|
5223
|
+
}
|
|
5224
|
+
} catch (e) {
|
|
5225
|
+
this.counters.remoteSnapshotErrors++;
|
|
5226
|
+
this.logger.warn("Remote snapshot rejected: decryption failed", { error: e.message });
|
|
5227
|
+
return 0;
|
|
5228
|
+
}
|
|
5229
|
+
const snapshot = this.codec.decode(buf);
|
|
5230
|
+
if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
|
|
5231
|
+
this.counters.remoteSnapshotErrors++;
|
|
5232
|
+
this.logger.warn("Remote snapshot rejected: version mismatch", { got: snapshot?.version });
|
|
5233
|
+
return 0;
|
|
5234
|
+
}
|
|
5235
|
+
const now = Date.now();
|
|
5236
|
+
const writtenAt = snapshot.writtenAt ?? 0;
|
|
5237
|
+
const tolerance = this.opts.clockSkewToleranceMs ?? 250;
|
|
5238
|
+
if (writtenAt - now > tolerance) {
|
|
5239
|
+
this.counters.remoteSnapshotErrors++;
|
|
5240
|
+
this.logger.warn("Remote snapshot rejected: timestamp too far in future (exceeds clock skew tolerance)", {
|
|
5241
|
+
writtenAt,
|
|
5242
|
+
now,
|
|
5243
|
+
skewMs: writtenAt - now,
|
|
5244
|
+
tolerance
|
|
5245
|
+
});
|
|
5246
|
+
return 0;
|
|
5247
|
+
}
|
|
5248
|
+
const ageMs = Math.max(0, now - writtenAt);
|
|
5249
|
+
if (maxAgeMs <= 0 || ageMs > maxAgeMs) {
|
|
5250
|
+
this.counters.remoteSnapshotErrors++;
|
|
5251
|
+
this.logger.warn("Remote snapshot rejected: too old", { ageMinutes: Math.round(ageMs / 6e4) });
|
|
5252
|
+
return 0;
|
|
5253
|
+
}
|
|
5254
|
+
if (!Array.isArray(snapshot.entries)) {
|
|
5255
|
+
this.counters.remoteSnapshotErrors++;
|
|
5256
|
+
this.logger.warn("Remote snapshot rejected: entries is not an array");
|
|
5257
|
+
return 0;
|
|
5258
|
+
}
|
|
5259
|
+
const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
|
|
5260
|
+
this.counters.remoteSnapshotDownloads++;
|
|
5261
|
+
this.counters.remoteSnapshotLastDownloadedAt = Date.now();
|
|
5262
|
+
this.logger.info("Remote cache snapshot loaded (L1 hydrated)", {
|
|
5263
|
+
loaded,
|
|
5264
|
+
total: snapshot.entries.length,
|
|
5265
|
+
sizeKB: this.l1.getStats().sizeKB
|
|
5266
|
+
});
|
|
5267
|
+
return loaded;
|
|
5268
|
+
} catch (err) {
|
|
5269
|
+
this.counters.remoteSnapshotErrors++;
|
|
5270
|
+
this.logger.warn("Remote snapshot load failed \u2014 starting cold", { error: err.message });
|
|
5271
|
+
return 0;
|
|
5272
|
+
}
|
|
5273
|
+
}
|
|
3582
5274
|
// ── Core get (L1 → L1.5 → L2 → fetch) ───────────────────────────────────
|
|
3583
5275
|
/**
|
|
3584
5276
|
* Get a value from cache, or fetch and cache it.
|
|
@@ -3614,9 +5306,10 @@ var CacheService = class _CacheService {
|
|
|
3614
5306
|
if (l1Hit !== null) {
|
|
3615
5307
|
let isGenerationalStale = false;
|
|
3616
5308
|
if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
|
|
3617
|
-
|
|
3618
|
-
|
|
3619
|
-
|
|
5309
|
+
const tags = Object.keys(l1Hit.tagVersions);
|
|
5310
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5311
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5312
|
+
if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
|
|
3620
5313
|
isGenerationalStale = true;
|
|
3621
5314
|
break;
|
|
3622
5315
|
}
|
|
@@ -3661,116 +5354,140 @@ var CacheService = class _CacheService {
|
|
|
3661
5354
|
this.counters.l1Hits++;
|
|
3662
5355
|
this.opts.onHit?.(cacheKey, "l1");
|
|
3663
5356
|
if (this.opts.frozen) deepFreeze(l1Hit.value);
|
|
3664
|
-
span.setAttribute("cache.hit", "l1").end();
|
|
5357
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "memory").setAttribute("cache.hit_tier", "l1").end();
|
|
3665
5358
|
return this.opts.cloneStrategy === "structuredClone" && l1Hit.value != null && typeof l1Hit.value === "object" ? structuredClone(l1Hit.value) : l1Hit.value;
|
|
3666
5359
|
}
|
|
3667
5360
|
}
|
|
3668
5361
|
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
3669
5362
|
const swrGraceMs = optSwr * 1e3;
|
|
3670
5363
|
const priority = optPriority ?? inferPriority(cacheKey);
|
|
3671
|
-
|
|
5364
|
+
const existing = this.inflight.get(k);
|
|
5365
|
+
if (existing) {
|
|
5366
|
+
this.counters.stampedes++;
|
|
5367
|
+
this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch/read", { cacheKey });
|
|
5368
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
|
|
5369
|
+
return existing;
|
|
5370
|
+
}
|
|
5371
|
+
const executionPromise = (async () => {
|
|
3672
5372
|
try {
|
|
3673
|
-
|
|
3674
|
-
|
|
3675
|
-
|
|
3676
|
-
|
|
3677
|
-
|
|
3678
|
-
|
|
3679
|
-
|
|
3680
|
-
|
|
3681
|
-
|
|
3682
|
-
|
|
3683
|
-
|
|
5373
|
+
if (!this._diskDisabled) {
|
|
5374
|
+
const isDiskAllowed = this.watchdog.isDiskAllowed();
|
|
5375
|
+
if (isDiskAllowed) {
|
|
5376
|
+
const diskStart = performance.now();
|
|
5377
|
+
const diskHit = this.disk.load(k);
|
|
5378
|
+
const diskElapsed = performance.now() - diskStart;
|
|
5379
|
+
this.watchdog.recordDisk(diskElapsed);
|
|
5380
|
+
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
5381
|
+
if (diskHit !== null) {
|
|
5382
|
+
let isDiskStale = false;
|
|
5383
|
+
if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
|
|
5384
|
+
const tags = Object.keys(diskHit.tagVersions);
|
|
5385
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5386
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5387
|
+
if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
|
|
5388
|
+
isDiskStale = true;
|
|
5389
|
+
break;
|
|
5390
|
+
}
|
|
5391
|
+
}
|
|
3684
5392
|
}
|
|
3685
|
-
|
|
3686
|
-
|
|
3687
|
-
|
|
3688
|
-
|
|
3689
|
-
|
|
3690
|
-
|
|
5393
|
+
if (isDiskStale) {
|
|
5394
|
+
this.disk.delete(k);
|
|
5395
|
+
} else {
|
|
5396
|
+
const promoted = this.l1.importEntries(
|
|
5397
|
+
[{ key: k, entry: diskHit }],
|
|
5398
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
5399
|
+
);
|
|
5400
|
+
if (promoted > 0) {
|
|
5401
|
+
const l1Check = this.l1.get(k);
|
|
5402
|
+
if (l1Check !== null) {
|
|
5403
|
+
this.counters.diskHits++;
|
|
5404
|
+
this.opts.onHit?.(cacheKey, "disk");
|
|
5405
|
+
this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
|
|
5406
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
|
|
5407
|
+
if (this.opts.frozen) deepFreeze(l1Check.value);
|
|
5408
|
+
return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
|
|
5409
|
+
}
|
|
5410
|
+
}
|
|
3691
5411
|
}
|
|
3692
5412
|
}
|
|
3693
|
-
if (isStale) {
|
|
3694
|
-
const setAtMs = parseInt(hashData.t, 10) || 0;
|
|
3695
|
-
this._deleteIfStale(k, setAtMs);
|
|
3696
|
-
} else {
|
|
3697
|
-
const parsed = await this._decryptAndDeserialize(hashData.d);
|
|
3698
|
-
this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
|
|
3699
|
-
this.counters.l2Hits++;
|
|
3700
|
-
this.opts.onHit?.(cacheKey, "l2");
|
|
3701
|
-
this.logger.debug("L2 hit (Redis hash)", { cacheKey });
|
|
3702
|
-
span.setAttribute("cache.hit", "l2").end();
|
|
3703
|
-
if (this.opts.frozen) deepFreeze(parsed);
|
|
3704
|
-
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
3705
|
-
}
|
|
3706
|
-
}
|
|
3707
|
-
} else {
|
|
3708
|
-
const raw = await client.get(k);
|
|
3709
|
-
this.cb.onSuccess();
|
|
3710
|
-
if (raw) {
|
|
3711
|
-
const parsed = await this._decryptAndDeserialize(raw);
|
|
3712
|
-
this.l1.set(k, parsed, ttlMs, priority);
|
|
3713
|
-
this.counters.l2Hits++;
|
|
3714
|
-
this.opts.onHit?.(cacheKey, "l2");
|
|
3715
|
-
this.logger.debug("L2 hit (Redis)", { cacheKey });
|
|
3716
|
-
span.setAttribute("cache.hit", "l2").end();
|
|
3717
|
-
if (this.opts.frozen) deepFreeze(parsed);
|
|
3718
|
-
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
3719
5413
|
}
|
|
3720
5414
|
}
|
|
3721
|
-
|
|
3722
|
-
|
|
3723
|
-
|
|
3724
|
-
|
|
3725
|
-
|
|
3726
|
-
|
|
3727
|
-
|
|
3728
|
-
|
|
3729
|
-
|
|
3730
|
-
|
|
3731
|
-
|
|
3732
|
-
|
|
3733
|
-
|
|
3734
|
-
|
|
3735
|
-
|
|
3736
|
-
|
|
3737
|
-
|
|
3738
|
-
|
|
3739
|
-
|
|
3740
|
-
|
|
3741
|
-
|
|
3742
|
-
|
|
3743
|
-
|
|
3744
|
-
|
|
3745
|
-
|
|
3746
|
-
|
|
3747
|
-
|
|
3748
|
-
|
|
3749
|
-
|
|
3750
|
-
|
|
3751
|
-
|
|
3752
|
-
|
|
3753
|
-
|
|
3754
|
-
|
|
5415
|
+
if (!this._redisDisabled) {
|
|
5416
|
+
try {
|
|
5417
|
+
const client = await this.getRedis();
|
|
5418
|
+
const redisStart = performance.now();
|
|
5419
|
+
if (this.opts.tagStrategy === "generational") {
|
|
5420
|
+
const hashData = await client.hgetall(k);
|
|
5421
|
+
const redisElapsed = performance.now() - redisStart;
|
|
5422
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
5423
|
+
this.cb.onSuccess();
|
|
5424
|
+
if (hashData && hashData.d) {
|
|
5425
|
+
let isStale = false;
|
|
5426
|
+
let storedTagVersions = {};
|
|
5427
|
+
if (hashData.tv) {
|
|
5428
|
+
try {
|
|
5429
|
+
storedTagVersions = JSON.parse(hashData.tv);
|
|
5430
|
+
} catch {
|
|
5431
|
+
}
|
|
5432
|
+
}
|
|
5433
|
+
const tags = Object.keys(storedTagVersions);
|
|
5434
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5435
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5436
|
+
if (currentVers[i] > storedTagVersions[tags[i]]) {
|
|
5437
|
+
isStale = true;
|
|
5438
|
+
break;
|
|
5439
|
+
}
|
|
5440
|
+
}
|
|
5441
|
+
if (isStale) {
|
|
5442
|
+
const setAtMs = parseInt(hashData.t, 10) || 0;
|
|
5443
|
+
this._deleteIfStale(k, setAtMs);
|
|
5444
|
+
} else {
|
|
5445
|
+
const parsed = await this._decryptAndDeserialize(hashData.d);
|
|
5446
|
+
this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
|
|
5447
|
+
this.counters.l2Hits++;
|
|
5448
|
+
this.opts.onHit?.(cacheKey, "l2");
|
|
5449
|
+
this.logger.debug("L2 hit (Redis hash)", { cacheKey });
|
|
5450
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
5451
|
+
if (this.opts.frozen) deepFreeze(parsed);
|
|
5452
|
+
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
5453
|
+
}
|
|
5454
|
+
}
|
|
5455
|
+
} else {
|
|
5456
|
+
const raw = this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
|
|
5457
|
+
const redisElapsed = performance.now() - redisStart;
|
|
5458
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
5459
|
+
this.cb.onSuccess();
|
|
5460
|
+
if (raw) {
|
|
5461
|
+
const parsed = await this._decryptAndDeserialize(raw);
|
|
5462
|
+
this.l1.set(k, parsed, ttlMs, priority);
|
|
5463
|
+
this.counters.l2Hits++;
|
|
5464
|
+
this.opts.onHit?.(cacheKey, "l2");
|
|
5465
|
+
this.logger.debug("L2 hit (Redis)", { cacheKey });
|
|
5466
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
5467
|
+
if (this.opts.frozen) deepFreeze(parsed);
|
|
5468
|
+
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
5469
|
+
}
|
|
3755
5470
|
}
|
|
5471
|
+
} catch (err) {
|
|
5472
|
+
this.cb.onFailure();
|
|
5473
|
+
this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
|
|
3756
5474
|
}
|
|
3757
5475
|
}
|
|
3758
|
-
|
|
3759
|
-
|
|
3760
|
-
span.setAttribute("cache.hit", "miss");
|
|
3761
|
-
this.opts.onMiss?.(cacheKey);
|
|
3762
|
-
const existing = this.inflight.get(k);
|
|
3763
|
-
if (existing) {
|
|
3764
|
-
this.counters.stampedes++;
|
|
3765
|
-
this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch", { cacheKey });
|
|
3766
|
-
span.end();
|
|
3767
|
-
return existing;
|
|
3768
|
-
}
|
|
3769
|
-
const fetchPromise = (async () => {
|
|
3770
|
-
try {
|
|
5476
|
+
span.setAttribute("cache.hit", false).setAttribute("cache.hit_tier", "miss");
|
|
5477
|
+
this.opts.onMiss?.(cacheKey);
|
|
3771
5478
|
this.counters.fetches++;
|
|
3772
5479
|
const fetchStart = Date.now();
|
|
3773
|
-
|
|
5480
|
+
let data;
|
|
5481
|
+
try {
|
|
5482
|
+
data = await fetchFn();
|
|
5483
|
+
} catch (fetchErr) {
|
|
5484
|
+
span.setStatus({
|
|
5485
|
+
code: 2,
|
|
5486
|
+
message: fetchErr instanceof Error ? fetchErr.message : String(fetchErr)
|
|
5487
|
+
});
|
|
5488
|
+
span.recordException?.(fetchErr);
|
|
5489
|
+
throw fetchErr;
|
|
5490
|
+
}
|
|
3774
5491
|
const delta = Date.now() - fetchStart;
|
|
3775
5492
|
const notFoundTtlMs = (optNotFoundTtl ?? this.opts.notFoundTtl) * 1e3;
|
|
3776
5493
|
let effectiveTtl = data == null && notFoundTtlMs > 0 ? notFoundTtlMs : ttlMs;
|
|
@@ -3790,9 +5507,10 @@ var CacheService = class _CacheService {
|
|
|
3790
5507
|
let activeTagVersions;
|
|
3791
5508
|
if (optTags?.length) {
|
|
3792
5509
|
if (this.opts.tagStrategy === "generational") {
|
|
5510
|
+
const vers = await Promise.all(optTags.map((tag) => this._getTagVersion(tag)));
|
|
3793
5511
|
activeTagVersions = {};
|
|
3794
|
-
for (
|
|
3795
|
-
activeTagVersions[
|
|
5512
|
+
for (let i = 0; i < optTags.length; i++) {
|
|
5513
|
+
activeTagVersions[optTags[i]] = vers[i];
|
|
3796
5514
|
}
|
|
3797
5515
|
} else {
|
|
3798
5516
|
await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
|
|
@@ -3834,8 +5552,64 @@ var CacheService = class _CacheService {
|
|
|
3834
5552
|
span.end();
|
|
3835
5553
|
}
|
|
3836
5554
|
})();
|
|
3837
|
-
this.inflight.set(k,
|
|
3838
|
-
return
|
|
5555
|
+
this.inflight.set(k, executionPromise);
|
|
5556
|
+
return executionPromise;
|
|
5557
|
+
}
|
|
5558
|
+
/**
|
|
5559
|
+
* Graceful shutdown flusher for Kubernetes preStop hooks, NestJS onApplicationShutdown,
|
|
5560
|
+
* or manual microservice teardown.
|
|
5561
|
+
*
|
|
5562
|
+
* Flushes both local disk and remote cloud snapshots (S3/R2/GCS), returning a Promise
|
|
5563
|
+
* that resolves when the upload completes or after `timeoutMs` expires.
|
|
5564
|
+
*
|
|
5565
|
+
* @param timeoutMs Maximum time permitted for snapshot persistence before timing out. Default: 8000ms.
|
|
5566
|
+
*/
|
|
5567
|
+
async flushSnapshotOnShutdown(timeoutMs = 8e3) {
|
|
5568
|
+
const flusher = async () => {
|
|
5569
|
+
let localOk = true;
|
|
5570
|
+
let remoteOk = true;
|
|
5571
|
+
if (!this._diskDisabled) {
|
|
5572
|
+
try {
|
|
5573
|
+
this.writeSnapshot();
|
|
5574
|
+
} catch (err) {
|
|
5575
|
+
localOk = false;
|
|
5576
|
+
this.logger.warn("flushSnapshotOnShutdown: disk snapshot write failed", { error: err.message });
|
|
5577
|
+
}
|
|
5578
|
+
}
|
|
5579
|
+
if (this.opts.remoteSnapshot && this.opts.remoteSnapshot.saveOnShutdown !== false) {
|
|
5580
|
+
try {
|
|
5581
|
+
remoteOk = await this.writeRemoteSnapshot();
|
|
5582
|
+
} catch (err) {
|
|
5583
|
+
remoteOk = false;
|
|
5584
|
+
this.logger.warn("flushSnapshotOnShutdown: remote snapshot upload failed", { error: err.message });
|
|
5585
|
+
}
|
|
5586
|
+
}
|
|
5587
|
+
return localOk && remoteOk;
|
|
5588
|
+
};
|
|
5589
|
+
let timer = null;
|
|
5590
|
+
try {
|
|
5591
|
+
return await Promise.race([
|
|
5592
|
+
flusher(),
|
|
5593
|
+
new Promise((resolve) => {
|
|
5594
|
+
timer = setTimeout(() => {
|
|
5595
|
+
this.logger.warn(`flushSnapshotOnShutdown timed out after ${timeoutMs}ms`);
|
|
5596
|
+
resolve(false);
|
|
5597
|
+
}, timeoutMs);
|
|
5598
|
+
if (timer.unref) timer.unref();
|
|
5599
|
+
})
|
|
5600
|
+
]);
|
|
5601
|
+
} finally {
|
|
5602
|
+
if (timer) clearTimeout(timer);
|
|
5603
|
+
}
|
|
5604
|
+
}
|
|
5605
|
+
/**
|
|
5606
|
+
* Internal graceful shutdown trigger invoked by ProcessTerminationBus.
|
|
5607
|
+
*/
|
|
5608
|
+
_triggerShutdown() {
|
|
5609
|
+
if (!this._diskDisabled) this.writeSnapshot();
|
|
5610
|
+
if (this.opts.remoteSnapshot && this.opts.remoteSnapshot.saveOnShutdown !== false) {
|
|
5611
|
+
void this.flushSnapshotOnShutdown();
|
|
5612
|
+
}
|
|
3839
5613
|
}
|
|
3840
5614
|
/**
|
|
3841
5615
|
* Universal fetch-and-cache wrapper with an ergonomic options object.
|
|
@@ -3868,9 +5642,11 @@ var CacheService = class _CacheService {
|
|
|
3868
5642
|
let activeTagVersions;
|
|
3869
5643
|
const l1Existing = this.l1.get(cacheKey);
|
|
3870
5644
|
if (this.opts.tagStrategy === "generational" && l1Existing?.tagVersions) {
|
|
5645
|
+
const tags = Object.keys(l1Existing.tagVersions);
|
|
5646
|
+
const vers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
3871
5647
|
activeTagVersions = {};
|
|
3872
|
-
for (
|
|
3873
|
-
activeTagVersions[
|
|
5648
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5649
|
+
activeTagVersions[tags[i]] = vers[i];
|
|
3874
5650
|
}
|
|
3875
5651
|
}
|
|
3876
5652
|
this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
|
|
@@ -3916,62 +5692,77 @@ var CacheService = class _CacheService {
|
|
|
3916
5692
|
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
3917
5693
|
async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
|
|
3918
5694
|
const span = this._startSpan("tricache.set");
|
|
3919
|
-
if (this.opts.tracer)
|
|
3920
|
-
|
|
3921
|
-
|
|
3922
|
-
|
|
3923
|
-
|
|
3924
|
-
|
|
3925
|
-
|
|
3926
|
-
|
|
3927
|
-
|
|
3928
|
-
|
|
3929
|
-
|
|
3930
|
-
|
|
5695
|
+
if (this.opts.tracer) {
|
|
5696
|
+
span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
5697
|
+
span.setAttribute("cache.ttl", ttlSeconds);
|
|
5698
|
+
}
|
|
5699
|
+
try {
|
|
5700
|
+
const effectiveTtlSeconds = ttlSeconds > 0 ? ttlSeconds : ttlSeconds === 0 ? INDEFINITE_TTL_SECONDS : ttlSeconds;
|
|
5701
|
+
const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
|
|
5702
|
+
const p = priority ?? inferPriority(cacheKey);
|
|
5703
|
+
const k = this.nk(cacheKey);
|
|
5704
|
+
this.counters.sets++;
|
|
5705
|
+
let activeTagVersions;
|
|
5706
|
+
if (opts?.tags?.length) {
|
|
5707
|
+
if (this.opts.tagStrategy === "generational") {
|
|
5708
|
+
const vers = await Promise.all(opts.tags.map((tag) => this._getTagVersion(tag)));
|
|
5709
|
+
activeTagVersions = {};
|
|
5710
|
+
for (let i = 0; i < opts.tags.length; i++) {
|
|
5711
|
+
activeTagVersions[opts.tags[i]] = vers[i];
|
|
5712
|
+
}
|
|
5713
|
+
} else {
|
|
5714
|
+
await this._registerTags(k, opts.tags, ttlSeconds);
|
|
3931
5715
|
}
|
|
3932
|
-
} else {
|
|
3933
|
-
await this._registerTags(k, opts.tags, ttlSeconds);
|
|
3934
5716
|
}
|
|
3935
|
-
|
|
3936
|
-
|
|
3937
|
-
|
|
3938
|
-
|
|
3939
|
-
|
|
3940
|
-
|
|
3941
|
-
|
|
3942
|
-
|
|
3943
|
-
|
|
5717
|
+
this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
|
|
5718
|
+
if (opts?.dependsOn?.length) {
|
|
5719
|
+
for (const pattern of opts.dependsOn) {
|
|
5720
|
+
const nsPattern = this.nk(pattern);
|
|
5721
|
+
let deps = this.dependencyIndex.get(nsPattern);
|
|
5722
|
+
if (!deps) {
|
|
5723
|
+
deps = /* @__PURE__ */ new Set();
|
|
5724
|
+
this.dependencyIndex.set(nsPattern, deps);
|
|
5725
|
+
}
|
|
5726
|
+
deps.add(k);
|
|
3944
5727
|
}
|
|
3945
|
-
deps.add(k);
|
|
3946
5728
|
}
|
|
3947
|
-
|
|
3948
|
-
|
|
3949
|
-
|
|
3950
|
-
|
|
3951
|
-
|
|
3952
|
-
|
|
3953
|
-
|
|
3954
|
-
|
|
3955
|
-
|
|
3956
|
-
|
|
3957
|
-
|
|
3958
|
-
|
|
3959
|
-
|
|
3960
|
-
|
|
3961
|
-
|
|
3962
|
-
|
|
3963
|
-
|
|
3964
|
-
|
|
3965
|
-
|
|
5729
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5730
|
+
try {
|
|
5731
|
+
const client = await this.getRedis();
|
|
5732
|
+
const s = JSON.stringify(data);
|
|
5733
|
+
const stored = await this._serializeAndEncrypt(s);
|
|
5734
|
+
const ttlSec = Math.ceil(ttlMs / 1e3);
|
|
5735
|
+
if (this.opts.tagStrategy === "generational" && activeTagVersions) {
|
|
5736
|
+
const now = Date.now();
|
|
5737
|
+
const tx = client.multi();
|
|
5738
|
+
tx.hset(k, {
|
|
5739
|
+
d: stored,
|
|
5740
|
+
t: String(now),
|
|
5741
|
+
tv: JSON.stringify(activeTagVersions)
|
|
5742
|
+
});
|
|
5743
|
+
tx.expire(k, ttlSec);
|
|
5744
|
+
await tx.exec();
|
|
5745
|
+
} else {
|
|
5746
|
+
if (this.opts.autoPipeline && this.pipeliner) {
|
|
5747
|
+
await this.pipeliner.setex(k, ttlSec, stored);
|
|
5748
|
+
} else {
|
|
5749
|
+
await client.setex(k, ttlSec, stored);
|
|
5750
|
+
}
|
|
5751
|
+
}
|
|
5752
|
+
this.cb.onSuccess();
|
|
5753
|
+
} catch (err) {
|
|
5754
|
+
this.cb.onFailure();
|
|
5755
|
+
this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
|
|
3966
5756
|
}
|
|
3967
|
-
this.cb.onSuccess();
|
|
3968
|
-
} catch (err) {
|
|
3969
|
-
this.cb.onFailure();
|
|
3970
|
-
this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
|
|
3971
5757
|
}
|
|
5758
|
+
void this.publishInvalidation("del", k);
|
|
5759
|
+
} catch (err) {
|
|
5760
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
5761
|
+
span.recordException?.(err);
|
|
5762
|
+
throw err;
|
|
5763
|
+
} finally {
|
|
5764
|
+
span.end();
|
|
3972
5765
|
}
|
|
3973
|
-
void this.publishInvalidation("del", k);
|
|
3974
|
-
span.end();
|
|
3975
5766
|
}
|
|
3976
5767
|
/**
|
|
3977
5768
|
* Register tags for a cache key in the in-process index and (if Redis is enabled) in
|
|
@@ -4013,36 +5804,47 @@ var CacheService = class _CacheService {
|
|
|
4013
5804
|
async delete(cacheKey) {
|
|
4014
5805
|
const span = this._startSpan("tricache.delete");
|
|
4015
5806
|
if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
4016
|
-
|
|
4017
|
-
|
|
4018
|
-
|
|
4019
|
-
|
|
4020
|
-
|
|
4021
|
-
|
|
4022
|
-
|
|
4023
|
-
|
|
4024
|
-
|
|
4025
|
-
|
|
4026
|
-
|
|
4027
|
-
|
|
4028
|
-
|
|
4029
|
-
|
|
4030
|
-
|
|
4031
|
-
|
|
4032
|
-
|
|
4033
|
-
|
|
4034
|
-
|
|
4035
|
-
|
|
4036
|
-
|
|
5807
|
+
try {
|
|
5808
|
+
const isPattern = cacheKey.includes("*");
|
|
5809
|
+
const k = this.nk(cacheKey);
|
|
5810
|
+
this.counters.deletes++;
|
|
5811
|
+
if (isPattern) {
|
|
5812
|
+
this.l1.deletePattern(k);
|
|
5813
|
+
} else {
|
|
5814
|
+
this.l1.delete(k);
|
|
5815
|
+
setImmediate(() => {
|
|
5816
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
5817
|
+
});
|
|
5818
|
+
this._cascadeDependencies(k);
|
|
5819
|
+
for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
|
|
5820
|
+
}
|
|
5821
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5822
|
+
try {
|
|
5823
|
+
const client = await this.getRedis();
|
|
5824
|
+
if (isPattern) {
|
|
5825
|
+
const keys = await this._scanKeys(client, k);
|
|
5826
|
+
if (keys.length > 0) await client.del(...keys);
|
|
5827
|
+
} else {
|
|
5828
|
+
if (this.opts.autoPipeline && this.pipeliner) {
|
|
5829
|
+
await this.pipeliner.del(k);
|
|
5830
|
+
} else {
|
|
5831
|
+
await client.del(k);
|
|
5832
|
+
}
|
|
5833
|
+
}
|
|
5834
|
+
this.cb.onSuccess();
|
|
5835
|
+
} catch (err) {
|
|
5836
|
+
this.cb.onFailure();
|
|
5837
|
+
this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
|
|
4037
5838
|
}
|
|
4038
|
-
this.cb.onSuccess();
|
|
4039
|
-
} catch (err) {
|
|
4040
|
-
this.cb.onFailure();
|
|
4041
|
-
this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
|
|
4042
5839
|
}
|
|
5840
|
+
void this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
|
|
5841
|
+
} catch (err) {
|
|
5842
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
5843
|
+
span.recordException?.(err);
|
|
5844
|
+
throw err;
|
|
5845
|
+
} finally {
|
|
5846
|
+
span.end();
|
|
4043
5847
|
}
|
|
4044
|
-
void this.publishInvalidation(isPattern ? "del-glob" : "del", k);
|
|
4045
|
-
span.end();
|
|
4046
5848
|
}
|
|
4047
5849
|
// ── Counter (distributed rate limiting) ──────────────────────────────────
|
|
4048
5850
|
/**
|
|
@@ -4103,31 +5905,44 @@ var CacheService = class _CacheService {
|
|
|
4103
5905
|
* await cache.clear('user:abc'); // flush all keys for one user
|
|
4104
5906
|
*/
|
|
4105
5907
|
async clear(prefix) {
|
|
4106
|
-
this.
|
|
4107
|
-
|
|
4108
|
-
|
|
4109
|
-
this.
|
|
4110
|
-
|
|
4111
|
-
|
|
4112
|
-
|
|
4113
|
-
|
|
4114
|
-
|
|
4115
|
-
|
|
4116
|
-
|
|
4117
|
-
|
|
4118
|
-
|
|
4119
|
-
|
|
4120
|
-
|
|
4121
|
-
|
|
4122
|
-
|
|
4123
|
-
|
|
4124
|
-
|
|
5908
|
+
const span = this._startSpan("tricache.clear");
|
|
5909
|
+
if (this.opts.tracer) span.setAttribute("cache.prefix", prefix || "*");
|
|
5910
|
+
try {
|
|
5911
|
+
this.counters.deletes++;
|
|
5912
|
+
const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
|
|
5913
|
+
if (k) {
|
|
5914
|
+
this.l1.deletePattern(k);
|
|
5915
|
+
} else {
|
|
5916
|
+
this.l1.clear();
|
|
5917
|
+
if (!this._diskDisabled) this.disk.clear();
|
|
5918
|
+
this._l1Counters.clear();
|
|
5919
|
+
this.tagIndex.clear();
|
|
5920
|
+
this.tagVersions.clear();
|
|
5921
|
+
}
|
|
5922
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5923
|
+
try {
|
|
5924
|
+
const client = await this.getRedis();
|
|
5925
|
+
const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
|
|
5926
|
+
const keys = await this._scanKeys(client, pattern);
|
|
5927
|
+
if (keys.length > 0) await client.del(...keys);
|
|
5928
|
+
} catch (err) {
|
|
5929
|
+
this.logger.debug("clear: Redis unavailable", { error: err.message });
|
|
5930
|
+
}
|
|
4125
5931
|
}
|
|
5932
|
+
void this.publishInvalidation(
|
|
5933
|
+
"del-glob",
|
|
5934
|
+
k ?? (this._namespace ? `${this._namespace}:*` : "*"),
|
|
5935
|
+
void 0,
|
|
5936
|
+
false,
|
|
5937
|
+
true
|
|
5938
|
+
);
|
|
5939
|
+
} catch (err) {
|
|
5940
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
5941
|
+
span.recordException?.(err);
|
|
5942
|
+
throw err;
|
|
5943
|
+
} finally {
|
|
5944
|
+
span.end();
|
|
4126
5945
|
}
|
|
4127
|
-
void this.publishInvalidation(
|
|
4128
|
-
"del-glob",
|
|
4129
|
-
k ?? (this._namespace ? `${this._namespace}:*` : "*")
|
|
4130
|
-
);
|
|
4131
5946
|
}
|
|
4132
5947
|
/**
|
|
4133
5948
|
* Evict L1 entries that violate the current category or global capacity limits.
|
|
@@ -4258,7 +6073,7 @@ var CacheService = class _CacheService {
|
|
|
4258
6073
|
const now = Date.now();
|
|
4259
6074
|
if (entry.expiresAt <= now) return null;
|
|
4260
6075
|
if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
|
|
4261
|
-
return entry.value !== void 0 ? entry.value :
|
|
6076
|
+
return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
4262
6077
|
}
|
|
4263
6078
|
/**
|
|
4264
6079
|
* Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
|
|
@@ -4278,8 +6093,12 @@ var CacheService = class _CacheService {
|
|
|
4278
6093
|
if (this.opts.frozen) deepFreeze(val);
|
|
4279
6094
|
return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
|
|
4280
6095
|
}
|
|
4281
|
-
if (!this._diskDisabled) {
|
|
6096
|
+
if (!this._diskDisabled && this.watchdog.isDiskAllowed()) {
|
|
6097
|
+
const diskStart = performance.now();
|
|
4282
6098
|
const diskHit = this.disk.load(k);
|
|
6099
|
+
const diskElapsed = performance.now() - diskStart;
|
|
6100
|
+
this.watchdog.recordDisk(diskElapsed);
|
|
6101
|
+
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
4283
6102
|
if (diskHit !== null) {
|
|
4284
6103
|
const promoted = this.l1.importEntries(
|
|
4285
6104
|
[{ key: k, entry: diskHit }],
|
|
@@ -4300,7 +6119,10 @@ var CacheService = class _CacheService {
|
|
|
4300
6119
|
if (!this._redisDisabled && !this.cb.isOpen) {
|
|
4301
6120
|
try {
|
|
4302
6121
|
const client = await this.getRedis();
|
|
6122
|
+
const redisStart = performance.now();
|
|
4303
6123
|
const raw = await client.get(k);
|
|
6124
|
+
const redisElapsed = performance.now() - redisStart;
|
|
6125
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
4304
6126
|
if (raw !== null) {
|
|
4305
6127
|
const parsed = await this._decryptAndDeserialize(raw);
|
|
4306
6128
|
this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
|
|
@@ -4327,90 +6149,129 @@ var CacheService = class _CacheService {
|
|
|
4327
6149
|
* `(key) => number` so heterogeneous TTLs can be batched in one call.
|
|
4328
6150
|
*/
|
|
4329
6151
|
async mget(keys, fetchFn, ttl = 300, priority) {
|
|
4330
|
-
const
|
|
4331
|
-
|
|
4332
|
-
|
|
4333
|
-
for (let i = 0; i < keys.length; i++) {
|
|
4334
|
-
const k = this.nk(keys[i]);
|
|
4335
|
-
const entry = this.l1.getEntry(k);
|
|
4336
|
-
if (entry && entry.expiresAt > Date.now()) {
|
|
4337
|
-
result[i] = entry.value !== void 0 ? entry.value : (0, import_msgpackr3.unpack)(entry.data);
|
|
4338
|
-
this.counters.l1Hits++;
|
|
4339
|
-
} else {
|
|
4340
|
-
missIndexes.push(i);
|
|
4341
|
-
missKeys.push(keys[i]);
|
|
4342
|
-
}
|
|
6152
|
+
const span = this._startSpan("tricache.mget");
|
|
6153
|
+
if (this.opts.tracer) {
|
|
6154
|
+
span.setAttribute("cache.batch.size", keys.length);
|
|
4343
6155
|
}
|
|
4344
|
-
|
|
4345
|
-
|
|
4346
|
-
|
|
4347
|
-
|
|
4348
|
-
|
|
4349
|
-
const
|
|
4350
|
-
|
|
4351
|
-
|
|
4352
|
-
|
|
4353
|
-
|
|
4354
|
-
|
|
4355
|
-
|
|
4356
|
-
|
|
4357
|
-
|
|
4358
|
-
|
|
4359
|
-
|
|
4360
|
-
|
|
4361
|
-
|
|
4362
|
-
|
|
4363
|
-
|
|
4364
|
-
|
|
6156
|
+
try {
|
|
6157
|
+
const result = Array.from({ length: keys.length });
|
|
6158
|
+
const missIndexes = [];
|
|
6159
|
+
const missKeys = [];
|
|
6160
|
+
for (let i = 0; i < keys.length; i++) {
|
|
6161
|
+
const k = this.nk(keys[i]);
|
|
6162
|
+
const entry = this.l1.getEntry(k);
|
|
6163
|
+
if (entry && entry.expiresAt > Date.now()) {
|
|
6164
|
+
result[i] = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
6165
|
+
this.counters.l1Hits++;
|
|
6166
|
+
} else {
|
|
6167
|
+
missIndexes.push(i);
|
|
6168
|
+
missKeys.push(keys[i]);
|
|
6169
|
+
}
|
|
6170
|
+
}
|
|
6171
|
+
if (missKeys.length === 0) {
|
|
6172
|
+
if (this.opts.tracer) {
|
|
6173
|
+
span.setAttribute("cache.hits", keys.length);
|
|
6174
|
+
span.setAttribute("cache.misses", 0);
|
|
6175
|
+
span.setAttribute("cache.l1_hits", keys.length);
|
|
6176
|
+
span.setAttribute("cache.l2_hits", 0);
|
|
6177
|
+
}
|
|
6178
|
+
return result;
|
|
6179
|
+
}
|
|
6180
|
+
let l2HitCount = 0;
|
|
6181
|
+
if (!this._redisDisabled) {
|
|
6182
|
+
try {
|
|
6183
|
+
const client = await this.getRedis();
|
|
6184
|
+
const nsKeys = missKeys.map((k) => this.nk(k));
|
|
6185
|
+
const pipeline = client.multi();
|
|
6186
|
+
for (const nk of nsKeys) pipeline.get(nk);
|
|
6187
|
+
const redisStart = performance.now();
|
|
6188
|
+
const raws = await pipeline.exec();
|
|
6189
|
+
const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
|
|
6190
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
6191
|
+
this.cb.onSuccess();
|
|
6192
|
+
for (let j = 0; j < missKeys.length; j++) {
|
|
6193
|
+
const raw = raws[j] ? raws[j][1] : null;
|
|
6194
|
+
const idx = missIndexes[j];
|
|
6195
|
+
if (raw) {
|
|
6196
|
+
const parsed = await this._decryptAndDeserialize(raw);
|
|
6197
|
+
const k = nsKeys[j];
|
|
6198
|
+
const p = priority ?? inferPriority(missKeys[j]);
|
|
6199
|
+
this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
|
|
6200
|
+
this.counters.l2Hits++;
|
|
6201
|
+
l2HitCount++;
|
|
6202
|
+
result[idx] = parsed;
|
|
6203
|
+
missIndexes[j] = -1;
|
|
6204
|
+
missKeys[j] = "";
|
|
6205
|
+
}
|
|
4365
6206
|
}
|
|
6207
|
+
const remainingIdx = missIndexes.filter((i) => i >= 0);
|
|
6208
|
+
const remainingKeys = missKeys.filter((k) => k !== "");
|
|
6209
|
+
missIndexes.length = 0;
|
|
6210
|
+
missKeys.length = 0;
|
|
6211
|
+
missIndexes.push(...remainingIdx);
|
|
6212
|
+
missKeys.push(...remainingKeys);
|
|
6213
|
+
} catch (err) {
|
|
6214
|
+
this.cb.onFailure();
|
|
6215
|
+
this.logger.debug("mget: Redis unavailable, continuing to disk/fetch", { error: err.message });
|
|
4366
6216
|
}
|
|
4367
|
-
const remainingIdx = missIndexes.filter((i) => i >= 0);
|
|
4368
|
-
const remainingKeys = missKeys.filter((k) => k !== "");
|
|
4369
|
-
missIndexes.length = 0;
|
|
4370
|
-
missKeys.length = 0;
|
|
4371
|
-
missIndexes.push(...remainingIdx);
|
|
4372
|
-
missKeys.push(...remainingKeys);
|
|
4373
|
-
if (missKeys.length === 0) return result;
|
|
4374
|
-
} catch (err) {
|
|
4375
|
-
this.cb.onFailure();
|
|
4376
|
-
this.logger.debug("mget: Redis unavailable, continuing to disk/fetch", { error: err.message });
|
|
4377
6217
|
}
|
|
4378
|
-
|
|
4379
|
-
|
|
4380
|
-
|
|
4381
|
-
|
|
4382
|
-
|
|
4383
|
-
|
|
4384
|
-
const
|
|
4385
|
-
|
|
4386
|
-
|
|
4387
|
-
)
|
|
4388
|
-
|
|
4389
|
-
|
|
4390
|
-
|
|
4391
|
-
|
|
4392
|
-
|
|
4393
|
-
|
|
4394
|
-
|
|
6218
|
+
if (!this._diskDisabled && missKeys.length > 0) {
|
|
6219
|
+
for (let j = missKeys.length - 1; j >= 0; j--) {
|
|
6220
|
+
if (!this.watchdog.isDiskAllowed()) continue;
|
|
6221
|
+
const k = this.nk(missKeys[j]);
|
|
6222
|
+
const diskStart = performance.now();
|
|
6223
|
+
const diskHit = this.disk.load(k);
|
|
6224
|
+
const diskElapsed = performance.now() - diskStart;
|
|
6225
|
+
this.watchdog.recordDisk(diskElapsed);
|
|
6226
|
+
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
6227
|
+
if (diskHit !== null) {
|
|
6228
|
+
const promoted = this.l1.importEntries(
|
|
6229
|
+
[{ key: k, entry: diskHit }],
|
|
6230
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
6231
|
+
);
|
|
6232
|
+
if (promoted > 0) {
|
|
6233
|
+
const l1Check = this.l1.get(k);
|
|
6234
|
+
if (l1Check !== null) {
|
|
6235
|
+
this.counters.diskHits++;
|
|
6236
|
+
result[missIndexes[j]] = l1Check.value;
|
|
6237
|
+
missIndexes.splice(j, 1);
|
|
6238
|
+
missKeys.splice(j, 1);
|
|
6239
|
+
}
|
|
4395
6240
|
}
|
|
4396
6241
|
}
|
|
4397
6242
|
}
|
|
4398
6243
|
}
|
|
4399
|
-
if (missKeys.length
|
|
4400
|
-
|
|
4401
|
-
|
|
4402
|
-
|
|
4403
|
-
|
|
4404
|
-
|
|
4405
|
-
|
|
4406
|
-
|
|
4407
|
-
|
|
4408
|
-
|
|
4409
|
-
|
|
6244
|
+
if (missKeys.length > 0) {
|
|
6245
|
+
this.counters.fetches++;
|
|
6246
|
+
const fetched = await fetchFn(missKeys);
|
|
6247
|
+
const setPromises = [];
|
|
6248
|
+
for (let j = 0; j < missKeys.length; j++) {
|
|
6249
|
+
const v = fetched[missKeys[j]];
|
|
6250
|
+
result[missIndexes[j]] = v;
|
|
6251
|
+
if (v !== void 0) {
|
|
6252
|
+
const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
|
|
6253
|
+
setPromises.push(this.set(missKeys[j], v, resolvedTtl, priority));
|
|
6254
|
+
}
|
|
4410
6255
|
}
|
|
6256
|
+
if (setPromises.length > 0) {
|
|
6257
|
+
await Promise.all(setPromises);
|
|
6258
|
+
}
|
|
6259
|
+
}
|
|
6260
|
+
if (this.opts.tracer) {
|
|
6261
|
+
const finalMisses = missKeys.length;
|
|
6262
|
+
const totalHits = keys.length - finalMisses;
|
|
6263
|
+
span.setAttribute("cache.hits", totalHits);
|
|
6264
|
+
span.setAttribute("cache.misses", finalMisses);
|
|
6265
|
+
span.setAttribute("cache.l2_hits", l2HitCount);
|
|
4411
6266
|
}
|
|
6267
|
+
return result;
|
|
6268
|
+
} catch (err) {
|
|
6269
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6270
|
+
span.recordException?.(err);
|
|
6271
|
+
throw err;
|
|
6272
|
+
} finally {
|
|
6273
|
+
span.end();
|
|
4412
6274
|
}
|
|
4413
|
-
return result;
|
|
4414
6275
|
}
|
|
4415
6276
|
/**
|
|
4416
6277
|
* Returns a Promise that resolves once the cache is fully initialised and any
|
|
@@ -4437,12 +6298,24 @@ var CacheService = class _CacheService {
|
|
|
4437
6298
|
* });
|
|
4438
6299
|
*/
|
|
4439
6300
|
async mset(entries) {
|
|
6301
|
+
const span = this._startSpan("tricache.mset");
|
|
4440
6302
|
const keys = Object.keys(entries);
|
|
4441
|
-
|
|
4442
|
-
|
|
4443
|
-
|
|
4444
|
-
|
|
4445
|
-
|
|
6303
|
+
if (this.opts.tracer) {
|
|
6304
|
+
span.setAttribute("cache.batch.size", keys.length);
|
|
6305
|
+
}
|
|
6306
|
+
try {
|
|
6307
|
+
await Promise.all(keys.map((key) => {
|
|
6308
|
+
const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
|
|
6309
|
+
const hasOpts = tags?.length || dependsOn?.length;
|
|
6310
|
+
return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
|
|
6311
|
+
}));
|
|
6312
|
+
} catch (err) {
|
|
6313
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6314
|
+
span.recordException?.(err);
|
|
6315
|
+
throw err;
|
|
6316
|
+
} finally {
|
|
6317
|
+
span.end();
|
|
6318
|
+
}
|
|
4446
6319
|
}
|
|
4447
6320
|
/**
|
|
4448
6321
|
* Batch delete — delete multiple exact keys in a single call.
|
|
@@ -4452,7 +6325,19 @@ var CacheService = class _CacheService {
|
|
|
4452
6325
|
* await cache.mdel(['user:1', 'user:2', 'user:3']);
|
|
4453
6326
|
*/
|
|
4454
6327
|
async mdel(keys) {
|
|
4455
|
-
|
|
6328
|
+
const span = this._startSpan("tricache.mdel");
|
|
6329
|
+
if (this.opts.tracer) {
|
|
6330
|
+
span.setAttribute("cache.batch.size", keys.length);
|
|
6331
|
+
}
|
|
6332
|
+
try {
|
|
6333
|
+
await Promise.all(keys.map((k) => this.delete(k)));
|
|
6334
|
+
} catch (err) {
|
|
6335
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6336
|
+
span.recordException?.(err);
|
|
6337
|
+
throw err;
|
|
6338
|
+
} finally {
|
|
6339
|
+
span.end();
|
|
6340
|
+
}
|
|
4456
6341
|
}
|
|
4457
6342
|
/**
|
|
4458
6343
|
* Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
|
|
@@ -4481,7 +6366,6 @@ var CacheService = class _CacheService {
|
|
|
4481
6366
|
const results = await pl.exec();
|
|
4482
6367
|
this.cb.onSuccess();
|
|
4483
6368
|
let loaded = 0;
|
|
4484
|
-
const now = Date.now();
|
|
4485
6369
|
for (let i = 0; i < matchedKeys.length; i++) {
|
|
4486
6370
|
const [err, raw] = results[i];
|
|
4487
6371
|
if (err || raw == null) continue;
|
|
@@ -4493,7 +6377,6 @@ var CacheService = class _CacheService {
|
|
|
4493
6377
|
} catch {
|
|
4494
6378
|
}
|
|
4495
6379
|
}
|
|
4496
|
-
void now;
|
|
4497
6380
|
this.logger.info("warmFromL2 complete", {
|
|
4498
6381
|
pattern,
|
|
4499
6382
|
matched: matchedKeys.length,
|
|
@@ -4515,45 +6398,58 @@ var CacheService = class _CacheService {
|
|
|
4515
6398
|
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
4516
6399
|
*/
|
|
4517
6400
|
async invalidateTag(tag) {
|
|
4518
|
-
|
|
4519
|
-
|
|
6401
|
+
const span = this._startSpan("tricache.invalidate_tag");
|
|
6402
|
+
if (this.opts.tracer) {
|
|
6403
|
+
span.setAttribute("cache.tag", tag);
|
|
6404
|
+
span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
|
|
6405
|
+
}
|
|
6406
|
+
try {
|
|
6407
|
+
if (this.opts.tagStrategy === "generational") {
|
|
6408
|
+
let newVer = 1;
|
|
6409
|
+
if (!this._redisDisabled) {
|
|
6410
|
+
try {
|
|
6411
|
+
const client = await this.getRedis();
|
|
6412
|
+
newVer = await client.incr(this.nk(`tag_ver:${tag}`));
|
|
6413
|
+
} catch (err) {
|
|
6414
|
+
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
6415
|
+
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
6416
|
+
newVer = current + 1;
|
|
6417
|
+
}
|
|
6418
|
+
} else {
|
|
6419
|
+
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
6420
|
+
newVer = current + 1;
|
|
6421
|
+
}
|
|
6422
|
+
this._setLocalTagVersion(tag, newVer, Date.now());
|
|
6423
|
+
void this.publishInvalidation("tag_incr", tag, newVer, false, true);
|
|
6424
|
+
return;
|
|
6425
|
+
}
|
|
6426
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
6427
|
+
const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
|
|
6428
|
+
for (const k of members) {
|
|
6429
|
+
this.l1.delete(k);
|
|
6430
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
6431
|
+
}
|
|
6432
|
+
this.tagIndex.delete(tagKey);
|
|
4520
6433
|
if (!this._redisDisabled) {
|
|
4521
6434
|
try {
|
|
4522
6435
|
const client = await this.getRedis();
|
|
4523
|
-
|
|
6436
|
+
const redisMembers = await client.smembers(tagKey);
|
|
6437
|
+
const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
|
|
6438
|
+
if (toDelete.length > 0) {
|
|
6439
|
+
await client.del(...toDelete, tagKey);
|
|
6440
|
+
} else {
|
|
6441
|
+
await client.del(tagKey);
|
|
6442
|
+
}
|
|
4524
6443
|
} catch (err) {
|
|
4525
6444
|
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
4526
|
-
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
4527
|
-
newVer = current + 1;
|
|
4528
|
-
}
|
|
4529
|
-
} else {
|
|
4530
|
-
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
4531
|
-
newVer = current + 1;
|
|
4532
|
-
}
|
|
4533
|
-
this._setLocalTagVersion(tag, newVer, Date.now());
|
|
4534
|
-
void this.publishInvalidation("tag_incr", tag, newVer);
|
|
4535
|
-
return;
|
|
4536
|
-
}
|
|
4537
|
-
const tagKey = this.nk(`_tag_:${tag}`);
|
|
4538
|
-
const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
|
|
4539
|
-
for (const k of members) {
|
|
4540
|
-
this.l1.delete(k);
|
|
4541
|
-
if (!this._diskDisabled) this.disk.delete(k);
|
|
4542
|
-
}
|
|
4543
|
-
this.tagIndex.delete(tagKey);
|
|
4544
|
-
if (!this._redisDisabled) {
|
|
4545
|
-
try {
|
|
4546
|
-
const client = await this.getRedis();
|
|
4547
|
-
const redisMembers = await client.smembers(tagKey);
|
|
4548
|
-
const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
|
|
4549
|
-
if (toDelete.length > 0) {
|
|
4550
|
-
await client.del(...toDelete, tagKey);
|
|
4551
|
-
} else {
|
|
4552
|
-
await client.del(tagKey);
|
|
4553
6445
|
}
|
|
4554
|
-
} catch (err) {
|
|
4555
|
-
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
4556
6446
|
}
|
|
6447
|
+
} catch (err) {
|
|
6448
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6449
|
+
span.recordException?.(err);
|
|
6450
|
+
throw err;
|
|
6451
|
+
} finally {
|
|
6452
|
+
span.end();
|
|
4557
6453
|
}
|
|
4558
6454
|
}
|
|
4559
6455
|
/**
|
|
@@ -4586,7 +6482,7 @@ var CacheService = class _CacheService {
|
|
|
4586
6482
|
const [err, newVer] = results[i] ?? [null, null];
|
|
4587
6483
|
const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
|
|
4588
6484
|
this._setLocalTagVersion(tags[i], ver, now);
|
|
4589
|
-
void this.publishInvalidation("tag_incr", tags[i], ver);
|
|
6485
|
+
void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
|
|
4590
6486
|
}
|
|
4591
6487
|
return;
|
|
4592
6488
|
} catch (err) {
|
|
@@ -4596,7 +6492,7 @@ var CacheService = class _CacheService {
|
|
|
4596
6492
|
for (const tag of tags) {
|
|
4597
6493
|
const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
4598
6494
|
this._setLocalTagVersion(tag, ver, now);
|
|
4599
|
-
void this.publishInvalidation("tag_incr", tag, ver);
|
|
6495
|
+
void this.publishInvalidation("tag_incr", tag, ver, false, true);
|
|
4600
6496
|
}
|
|
4601
6497
|
return;
|
|
4602
6498
|
}
|
|
@@ -4667,6 +6563,60 @@ var CacheService = class _CacheService {
|
|
|
4667
6563
|
}
|
|
4668
6564
|
return { l1, disk, l2 };
|
|
4669
6565
|
}
|
|
6566
|
+
/**
|
|
6567
|
+
* Health and readiness diagnostics for container orchestrators (e.g. Kubernetes, ECS, Nomad).
|
|
6568
|
+
*
|
|
6569
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
6570
|
+
* ⚠️ CRITICAL CONTAINER PROBE SEMANTICS (Liveness vs. Readiness):
|
|
6571
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
6572
|
+
* ❌ NEVER bind `degraded` checks or `cache.health()` to your Liveness Probe (/livez, /healthz).
|
|
6573
|
+
* If an SRE hooks degraded status into liveness, a storage-starved or EBS-throttled pod
|
|
6574
|
+
* will be killed by the kubelet, triggering a cluster-wide cascading restart shockwave.
|
|
6575
|
+
* Liveness probes must only check that the event loop / process is alive.
|
|
6576
|
+
*
|
|
6577
|
+
* ✅ BIND degraded checks strictly to your Readiness Probe (/ready, /readyz).
|
|
6578
|
+
* A degraded cache (e.g. EBS latency spike, quota watermark pruning, or open Redis circuit)
|
|
6579
|
+
* can shed traffic at the ingress load balancer while the Node.js process remains
|
|
6580
|
+
* alive to drain in-flight promises and heal its local storage.
|
|
6581
|
+
*
|
|
6582
|
+
* By default, `healthy` remains `true` even when degraded (graceful local degradation).
|
|
6583
|
+
* Set `failReadinessOnDegraded: true` in CacheOptions if you want your Readiness probe
|
|
6584
|
+
* to route ingress traffic away while degraded.
|
|
6585
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
6586
|
+
*/
|
|
6587
|
+
health() {
|
|
6588
|
+
const watchdogTel = this.watchdog.getTelemetry();
|
|
6589
|
+
const diskPruning = !this._diskDisabled && this.disk.isPruning;
|
|
6590
|
+
const diskLowSpace = !this._diskDisabled && this.disk.hostVolumeLowSpace;
|
|
6591
|
+
const circuitOpen = this.cb.isOpen;
|
|
6592
|
+
const latencyBypass = watchdogTel.bypassActive;
|
|
6593
|
+
const degraded = circuitOpen || latencyBypass || diskPruning || diskLowSpace;
|
|
6594
|
+
const healthy = this.opts.failReadinessOnDegraded ? !degraded : true;
|
|
6595
|
+
const reasons = [];
|
|
6596
|
+
if (circuitOpen) reasons.push("redis_circuit_breaker_open");
|
|
6597
|
+
if (latencyBypass) reasons.push(`disk_latency_bypass_stage_${watchdogTel.bypassStage}`);
|
|
6598
|
+
if (diskPruning) reasons.push("disk_quota_watermark_pruning_active");
|
|
6599
|
+
if (diskLowSpace) reasons.push("disk_host_volume_low_space");
|
|
6600
|
+
return {
|
|
6601
|
+
healthy,
|
|
6602
|
+
degraded,
|
|
6603
|
+
reasons,
|
|
6604
|
+
details: {
|
|
6605
|
+
redisConnected: !circuitOpen && !this._redisDisabled,
|
|
6606
|
+
circuitBreakerState: this.cb.currentState,
|
|
6607
|
+
diskPruningActive: diskPruning,
|
|
6608
|
+
diskHostVolumeLowSpace: diskLowSpace,
|
|
6609
|
+
watchdog: watchdogTel
|
|
6610
|
+
}
|
|
6611
|
+
};
|
|
6612
|
+
}
|
|
6613
|
+
/**
|
|
6614
|
+
* Direct access to the internal tier latency watchdog instance.
|
|
6615
|
+
* Used for diagnostics, canary probes, and control-loop tuning.
|
|
6616
|
+
*/
|
|
6617
|
+
getLatencyWatchdog() {
|
|
6618
|
+
return this.watchdog;
|
|
6619
|
+
}
|
|
4670
6620
|
/**
|
|
4671
6621
|
* Export all live L1 entries to Redis via a single pipeline.
|
|
4672
6622
|
* Useful for warming a new Redis instance or for zero-downtime failover.
|
|
@@ -4914,7 +6864,7 @@ var CacheService = class _CacheService {
|
|
|
4914
6864
|
if (visited.has(dep)) continue;
|
|
4915
6865
|
this.l1.delete(dep);
|
|
4916
6866
|
if (!this._diskDisabled) this.disk.delete(dep);
|
|
4917
|
-
void this.publishInvalidation("del", dep);
|
|
6867
|
+
void this.publishInvalidation("del", dep, void 0, false, true);
|
|
4918
6868
|
this.logger.debug("Dependency cascade: invalidated dependent key", {
|
|
4919
6869
|
trigger: deletedKey.slice(0, 60),
|
|
4920
6870
|
dependent: dep.slice(0, 60)
|
|
@@ -4979,12 +6929,36 @@ var CacheService = class _CacheService {
|
|
|
4979
6929
|
evictions: c.oomEvictions,
|
|
4980
6930
|
lastTriggeredAt: c.oomLastAt
|
|
4981
6931
|
},
|
|
6932
|
+
...this.opts.remoteSnapshot && {
|
|
6933
|
+
remoteSnapshot: {
|
|
6934
|
+
enabled: true,
|
|
6935
|
+
uploads: c.remoteSnapshotUploads,
|
|
6936
|
+
downloads: c.remoteSnapshotDownloads,
|
|
6937
|
+
errors: c.remoteSnapshotErrors,
|
|
6938
|
+
lastUploadedAt: c.remoteSnapshotLastUploadedAt,
|
|
6939
|
+
lastDownloadedAt: c.remoteSnapshotLastDownloadedAt
|
|
6940
|
+
}
|
|
6941
|
+
},
|
|
6942
|
+
...this.opts.crossRegion && {
|
|
6943
|
+
crossRegion: {
|
|
6944
|
+
enabled: true,
|
|
6945
|
+
currentRegion: this.opts.crossRegion.currentRegion,
|
|
6946
|
+
sent: c.crossRegionSent,
|
|
6947
|
+
received: c.crossRegionReceived,
|
|
6948
|
+
deduplicated: c.crossRegionDeduplicated,
|
|
6949
|
+
errors: c.crossRegionErrors
|
|
6950
|
+
}
|
|
6951
|
+
},
|
|
4982
6952
|
l1: {
|
|
4983
6953
|
entries: l1s.entries,
|
|
4984
6954
|
sizeBytes: this.l1.memoryUsage,
|
|
4985
6955
|
maxBytes: this.opts.l1MaxBytes
|
|
4986
6956
|
},
|
|
4987
|
-
disk: {
|
|
6957
|
+
disk: {
|
|
6958
|
+
...this.disk.stats,
|
|
6959
|
+
disabled: this._diskDisabled,
|
|
6960
|
+
latencyWatchdog: this.watchdog.getTelemetry()
|
|
6961
|
+
},
|
|
4988
6962
|
...this.latencyTracker && {
|
|
4989
6963
|
adaptiveTtl: {
|
|
4990
6964
|
enabled: true,
|
|
@@ -4997,9 +6971,16 @@ var CacheService = class _CacheService {
|
|
|
4997
6971
|
this.opts.adaptiveTtlMaxMs
|
|
4998
6972
|
)
|
|
4999
6973
|
}
|
|
6974
|
+
},
|
|
6975
|
+
...this.pipeliner && {
|
|
6976
|
+
pipelining: this.pipeliner.stats
|
|
5000
6977
|
}
|
|
5001
6978
|
};
|
|
5002
6979
|
}
|
|
6980
|
+
/** Return auto-pipelining metrics, or null if pipelining is disabled. */
|
|
6981
|
+
getPipelinerStats() {
|
|
6982
|
+
return this.pipeliner ? this.pipeliner.stats : null;
|
|
6983
|
+
}
|
|
5003
6984
|
/**
|
|
5004
6985
|
* Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
|
|
5005
6986
|
* Paste the result into your `/metrics` endpoint.
|
|
@@ -5039,6 +7020,18 @@ var CacheService = class _CacheService {
|
|
|
5039
7020
|
gauge("l1_entries", m.l1.entries, "Current L1 entry count");
|
|
5040
7021
|
gauge("l1_size_bytes", m.l1.sizeBytes, "Current L1 used bytes");
|
|
5041
7022
|
gauge("disk_files", m.disk.files, "Current L1.5 disk file count");
|
|
7023
|
+
if (m.disk.latencyWatchdog) {
|
|
7024
|
+
gauge("disk_latency_bypass_stage", m.disk.latencyWatchdog.bypassStage, "Disk latency watchdog bypass stage (0: normal, 1: 25%, 2: 75%, 3: 100%)");
|
|
7025
|
+
gauge("disk_p95_ms", m.disk.latencyWatchdog.diskP95Ms, "Disk read p95 latency in ms");
|
|
7026
|
+
gauge("redis_p95_ms", m.disk.latencyWatchdog.redisP95Ms, "Redis read p95 latency in ms");
|
|
7027
|
+
counter("disk_bypassed_events", m.disk.latencyWatchdog.bypassedTotal, "Total disk bypass activation events");
|
|
7028
|
+
}
|
|
7029
|
+
if (m.disk.pruning) {
|
|
7030
|
+
counter("disk_spills_shed", m.disk.pruning.spillsShedTotal, "Total disk spills shed due to pruning or low disk space");
|
|
7031
|
+
counter("disk_prune_rounds", m.disk.pruning.pruneRounds, "Total high-watermark disk prune rounds");
|
|
7032
|
+
counter("disk_entries_pruned", m.disk.pruning.entriesPruned, "Total entries removed by watermark pruning");
|
|
7033
|
+
counter("disk_low_space_pauses", m.disk.pruning.hostVolumeLowSpacePauses, "Total times spills paused due to <10% host volume space");
|
|
7034
|
+
}
|
|
5042
7035
|
gauge(
|
|
5043
7036
|
"bloom_false_positive_rate",
|
|
5044
7037
|
m.bloom.falsePositiveRate,
|
|
@@ -5060,6 +7053,17 @@ var CacheService = class _CacheService {
|
|
|
5060
7053
|
"Emergency L1 eviction rounds triggered by heap pressure"
|
|
5061
7054
|
);
|
|
5062
7055
|
}
|
|
7056
|
+
if (m.remoteSnapshot?.enabled) {
|
|
7057
|
+
counter("remote_snapshot_uploads", m.remoteSnapshot.uploads, "Total remote snapshot uploads");
|
|
7058
|
+
counter("remote_snapshot_downloads", m.remoteSnapshot.downloads, "Total remote snapshot downloads");
|
|
7059
|
+
counter("remote_snapshot_errors", m.remoteSnapshot.errors, "Total remote snapshot errors");
|
|
7060
|
+
}
|
|
7061
|
+
if (m.crossRegion?.enabled) {
|
|
7062
|
+
counter("cross_region_sent", m.crossRegion.sent, "Total cross-region invalidations broadcast");
|
|
7063
|
+
counter("cross_region_received", m.crossRegion.received, "Total cross-region invalidations received");
|
|
7064
|
+
counter("cross_region_deduplicated", m.crossRegion.deduplicated, "Total cross-region invalidations deduplicated or self-filtered");
|
|
7065
|
+
counter("cross_region_errors", m.crossRegion.errors, "Total cross-region relay errors");
|
|
7066
|
+
}
|
|
5063
7067
|
return lines.join("\n");
|
|
5064
7068
|
}
|
|
5065
7069
|
// ── Lifecycle ────────────────────────────────────────────────────────────
|
|
@@ -5078,23 +7082,31 @@ var CacheService = class _CacheService {
|
|
|
5078
7082
|
/** Close Redis connections and stop all background timers. */
|
|
5079
7083
|
async destroy() {
|
|
5080
7084
|
this._destroyed = true;
|
|
7085
|
+
const g = globalThis;
|
|
7086
|
+
const key = _CacheService.globalKey(this.opts);
|
|
7087
|
+
if (g[key] === this) {
|
|
7088
|
+
delete g[key];
|
|
7089
|
+
}
|
|
5081
7090
|
if (this.cleanupInterval) clearInterval(this.cleanupInterval);
|
|
5082
7091
|
if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
|
|
5083
7092
|
if (this.oomInterval) clearInterval(this.oomInterval);
|
|
5084
7093
|
if (this.metricsInterval) clearInterval(this.metricsInterval);
|
|
5085
|
-
if (this.
|
|
5086
|
-
|
|
5087
|
-
|
|
5088
|
-
this._shutdownHandler = null;
|
|
7094
|
+
if (this.remoteSnapshotInterval) {
|
|
7095
|
+
clearInterval(this.remoteSnapshotInterval);
|
|
7096
|
+
this.remoteSnapshotInterval = null;
|
|
5089
7097
|
}
|
|
7098
|
+
ProcessTerminationBus.unregister(this);
|
|
7099
|
+
this._shutdownHandler = null;
|
|
5090
7100
|
if (this._workerPool) {
|
|
5091
7101
|
await this._workerPool.destroy();
|
|
5092
7102
|
this._workerPool = null;
|
|
5093
7103
|
}
|
|
5094
7104
|
if (this.subClient) {
|
|
5095
|
-
|
|
5096
|
-
|
|
5097
|
-
|
|
7105
|
+
if (!this.opts.redisSubClient) {
|
|
7106
|
+
try {
|
|
7107
|
+
this.subClient.disconnect();
|
|
7108
|
+
} catch {
|
|
7109
|
+
}
|
|
5098
7110
|
}
|
|
5099
7111
|
this.subClient = null;
|
|
5100
7112
|
}
|
|
@@ -5106,14 +7118,33 @@ var CacheService = class _CacheService {
|
|
|
5106
7118
|
this.streamClient = null;
|
|
5107
7119
|
}
|
|
5108
7120
|
if (this.redis) {
|
|
5109
|
-
|
|
5110
|
-
|
|
5111
|
-
|
|
7121
|
+
if (!this.opts.redisClient) {
|
|
7122
|
+
try {
|
|
7123
|
+
await this.redis.disconnect();
|
|
7124
|
+
} catch {
|
|
7125
|
+
}
|
|
5112
7126
|
}
|
|
5113
7127
|
this.redis = null;
|
|
5114
7128
|
}
|
|
7129
|
+
if (this._ipcServer) {
|
|
7130
|
+
await this._ipcServer.close();
|
|
7131
|
+
this._ipcServer = void 0;
|
|
7132
|
+
}
|
|
5115
7133
|
if (!this._diskDisabled) this.disk.close();
|
|
5116
7134
|
}
|
|
7135
|
+
/**
|
|
7136
|
+
* Return the active IPC telemetry server instance, if enabled.
|
|
7137
|
+
*/
|
|
7138
|
+
getIpcServer() {
|
|
7139
|
+
return this._ipcServer;
|
|
7140
|
+
}
|
|
7141
|
+
/**
|
|
7142
|
+
* Return real-time telemetry and metrics for the Window TinyLFU admission policy.
|
|
7143
|
+
* Returns `undefined` if W-TinyLFU admission is not active.
|
|
7144
|
+
*/
|
|
7145
|
+
getWTinyLfuStats() {
|
|
7146
|
+
return this.l1.getWTinyLfuStats();
|
|
7147
|
+
}
|
|
5117
7148
|
};
|
|
5118
7149
|
|
|
5119
7150
|
// src/nestjs/tricache.store.ts
|