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/cli.cjs
CHANGED
|
@@ -37,9 +37,43 @@ var import_node_util = require("util");
|
|
|
37
37
|
|
|
38
38
|
// src/cache-service.ts
|
|
39
39
|
var import_ioredis = require("ioredis");
|
|
40
|
-
|
|
40
|
+
|
|
41
|
+
// src/codec.ts
|
|
42
|
+
var import_msgpackr = require("msgpackr");
|
|
43
|
+
var CacheCodec = class {
|
|
44
|
+
packr;
|
|
45
|
+
constructor(options) {
|
|
46
|
+
const packrOptions = {
|
|
47
|
+
useToJSON: options?.useToJSON ?? true,
|
|
48
|
+
useRecords: options?.useRecords ?? true,
|
|
49
|
+
moreTypes: options?.moreTypes ?? true,
|
|
50
|
+
mapsAsObjects: options?.mapsAsObjects ?? true
|
|
51
|
+
};
|
|
52
|
+
this.packr = new import_msgpackr.Packr(packrOptions);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Serializes a JavaScript value to a binary MessagePack Buffer.
|
|
56
|
+
*/
|
|
57
|
+
encode(data) {
|
|
58
|
+
const packed = this.packr.pack(data);
|
|
59
|
+
return Buffer.isBuffer(packed) ? packed : Buffer.from(packed.buffer, packed.byteOffset, packed.byteLength);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Deserializes a binary MessagePack Buffer or Uint8Array back to a JavaScript value.
|
|
63
|
+
*/
|
|
64
|
+
decode(data) {
|
|
65
|
+
return this.packr.unpack(data);
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
var defaultCodec = new CacheCodec({
|
|
69
|
+
useToJSON: true,
|
|
70
|
+
useRecords: true,
|
|
71
|
+
moreTypes: true
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
// src/cache-service.ts
|
|
41
75
|
var import_crypto3 = __toESM(require("crypto"), 1);
|
|
42
|
-
var
|
|
76
|
+
var import_os3 = __toESM(require("os"), 1);
|
|
43
77
|
|
|
44
78
|
// src/worker-pool.ts
|
|
45
79
|
var import_worker_threads = require("worker_threads");
|
|
@@ -244,7 +278,7 @@ function availableCpus() {
|
|
|
244
278
|
}
|
|
245
279
|
|
|
246
280
|
// src/cache-service.ts
|
|
247
|
-
var
|
|
281
|
+
var import_node_v82 = __toESM(require("v8"), 1);
|
|
248
282
|
var import_fs3 = __toESM(require("fs"), 1);
|
|
249
283
|
var import_path3 = __toESM(require("path"), 1);
|
|
250
284
|
|
|
@@ -375,17 +409,17 @@ var CacheEncryption = class {
|
|
|
375
409
|
throw new Error("XOR key must be at least 1 byte");
|
|
376
410
|
}
|
|
377
411
|
this._key = buf;
|
|
378
|
-
if (
|
|
412
|
+
if (resolvedMode !== "xor") {
|
|
379
413
|
this._keyObj = (0, import_crypto.createSecretKey)(buf);
|
|
380
414
|
const _wc = (0, import_crypto.createCipheriv)(
|
|
381
|
-
|
|
415
|
+
resolvedMode,
|
|
382
416
|
this._keyObj,
|
|
383
|
-
Buffer.alloc(
|
|
417
|
+
Buffer.alloc(resolvedMode === "aes-128-ctr" ? CTR_IV_BYTES : IV_BYTES)
|
|
384
418
|
);
|
|
385
419
|
_wc.update(Buffer.alloc(0));
|
|
386
420
|
_wc.final();
|
|
387
421
|
}
|
|
388
|
-
if (
|
|
422
|
+
if (resolvedMode === "xor") {
|
|
389
423
|
logger.warn(
|
|
390
424
|
"Cache obfuscation enabled (XOR). WARNING: XOR is NOT cryptographic \u2014 use only for dev or non-sensitive data."
|
|
391
425
|
);
|
|
@@ -653,15 +687,257 @@ var CacheEncryption = class {
|
|
|
653
687
|
return plain;
|
|
654
688
|
}
|
|
655
689
|
};
|
|
690
|
+
var MAGIC_ENVELOPE = Buffer.from([84, 82, 73, 67, 69, 78, 86, 49]);
|
|
691
|
+
var EnvelopeEncryption = class {
|
|
692
|
+
static isEnvelope(data) {
|
|
693
|
+
return data.length >= MAGIC_LEN && data.subarray(0, MAGIC_LEN).equals(MAGIC_ENVELOPE);
|
|
694
|
+
}
|
|
695
|
+
static async encrypt(data, options) {
|
|
696
|
+
const dek = (0, import_crypto.randomBytes)(32);
|
|
697
|
+
let encryptedKey;
|
|
698
|
+
if (options.kmsEncrypt) {
|
|
699
|
+
encryptedKey = await options.kmsEncrypt(dek);
|
|
700
|
+
} else if (options.publicKey) {
|
|
701
|
+
encryptedKey = (0, import_crypto.publicEncrypt)(
|
|
702
|
+
{
|
|
703
|
+
key: options.publicKey,
|
|
704
|
+
padding: import_crypto.constants.RSA_PKCS1_OAEP_PADDING,
|
|
705
|
+
oaepHash: "sha256"
|
|
706
|
+
},
|
|
707
|
+
dek
|
|
708
|
+
);
|
|
709
|
+
} else {
|
|
710
|
+
throw new Error("EnvelopeEncryption: either publicKey or kmsEncrypt must be provided to encrypt");
|
|
711
|
+
}
|
|
712
|
+
const iv = (0, import_crypto.randomBytes)(IV_BYTES);
|
|
713
|
+
const cipher = (0, import_crypto.createCipheriv)("aes-256-gcm", dek, iv);
|
|
714
|
+
const ct = cipher.update(data);
|
|
715
|
+
cipher.final();
|
|
716
|
+
const tag = cipher.getAuthTag();
|
|
717
|
+
const keyLen = encryptedKey.length;
|
|
718
|
+
const out = Buffer.allocUnsafe(MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES + ct.length);
|
|
719
|
+
MAGIC_ENVELOPE.copy(out, 0);
|
|
720
|
+
out.writeUInt32BE(keyLen, MAGIC_LEN);
|
|
721
|
+
encryptedKey.copy(out, MAGIC_LEN + 4);
|
|
722
|
+
iv.copy(out, MAGIC_LEN + 4 + keyLen);
|
|
723
|
+
tag.copy(out, MAGIC_LEN + 4 + keyLen + IV_BYTES);
|
|
724
|
+
ct.copy(out, MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES);
|
|
725
|
+
return out;
|
|
726
|
+
}
|
|
727
|
+
static async decrypt(data, options) {
|
|
728
|
+
if (!this.isEnvelope(data)) {
|
|
729
|
+
throw new Error("EnvelopeEncryption: invalid header, expected TRICENV1");
|
|
730
|
+
}
|
|
731
|
+
if (data.length < MAGIC_LEN + 4 + IV_BYTES + TAG_BYTES) {
|
|
732
|
+
throw new Error("EnvelopeEncryption: truncated envelope buffer");
|
|
733
|
+
}
|
|
734
|
+
const keyLen = data.readUInt32BE(MAGIC_LEN);
|
|
735
|
+
const minExpected = MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES;
|
|
736
|
+
if (data.length < minExpected) {
|
|
737
|
+
throw new Error("EnvelopeEncryption: truncated envelope buffer (key length mismatch)");
|
|
738
|
+
}
|
|
739
|
+
const encryptedKey = data.subarray(MAGIC_LEN + 4, MAGIC_LEN + 4 + keyLen);
|
|
740
|
+
const iv = data.subarray(MAGIC_LEN + 4 + keyLen, MAGIC_LEN + 4 + keyLen + IV_BYTES);
|
|
741
|
+
const tag = data.subarray(MAGIC_LEN + 4 + keyLen + IV_BYTES, MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES);
|
|
742
|
+
const ct = data.subarray(MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES);
|
|
743
|
+
let dek;
|
|
744
|
+
if (options.kmsDecrypt) {
|
|
745
|
+
dek = await options.kmsDecrypt(encryptedKey);
|
|
746
|
+
} else if (options.privateKey) {
|
|
747
|
+
dek = (0, import_crypto.privateDecrypt)(
|
|
748
|
+
{
|
|
749
|
+
key: options.privateKey,
|
|
750
|
+
padding: import_crypto.constants.RSA_PKCS1_OAEP_PADDING,
|
|
751
|
+
oaepHash: "sha256"
|
|
752
|
+
},
|
|
753
|
+
encryptedKey
|
|
754
|
+
);
|
|
755
|
+
} else {
|
|
756
|
+
throw new Error("EnvelopeEncryption: either privateKey or kmsDecrypt must be provided to decrypt");
|
|
757
|
+
}
|
|
758
|
+
const decipher = (0, import_crypto.createDecipheriv)("aes-256-gcm", dek, iv);
|
|
759
|
+
decipher.setAuthTag(tag);
|
|
760
|
+
const pt = decipher.update(ct);
|
|
761
|
+
decipher.final();
|
|
762
|
+
return pt;
|
|
763
|
+
}
|
|
764
|
+
};
|
|
656
765
|
|
|
657
|
-
// src/
|
|
658
|
-
var
|
|
766
|
+
// src/wtiny-lfu.ts
|
|
767
|
+
var WTinyLfuPolicy = class {
|
|
768
|
+
constructor(capacity, sketch, windowPercent = 0.01, protectedPercent = 0.8) {
|
|
769
|
+
this.sketch = sketch;
|
|
770
|
+
this.maxTotal = Math.max(2, capacity);
|
|
771
|
+
this.maxWindow = Math.max(1, Math.floor(this.maxTotal * windowPercent));
|
|
772
|
+
const mainCapacity = Math.max(1, this.maxTotal - this.maxWindow);
|
|
773
|
+
this.maxProtected = Math.max(1, Math.floor(mainCapacity * protectedPercent));
|
|
774
|
+
this.maxProbation = Math.max(1, mainCapacity - this.maxProtected);
|
|
775
|
+
}
|
|
776
|
+
sketch;
|
|
777
|
+
maxTotal;
|
|
778
|
+
maxWindow;
|
|
779
|
+
maxProtected;
|
|
780
|
+
maxProbation;
|
|
781
|
+
window = /* @__PURE__ */ new Set();
|
|
782
|
+
probation = /* @__PURE__ */ new Set();
|
|
783
|
+
protected_ = /* @__PURE__ */ new Set();
|
|
784
|
+
// Telemetry metrics
|
|
785
|
+
hitCount = 0;
|
|
786
|
+
missCount = 0;
|
|
787
|
+
admissionCount = 0;
|
|
788
|
+
rejectionCount = 0;
|
|
789
|
+
promotionCount = 0;
|
|
790
|
+
demotionCount = 0;
|
|
791
|
+
get windowSize() {
|
|
792
|
+
return this.window.size;
|
|
793
|
+
}
|
|
794
|
+
get probationSize() {
|
|
795
|
+
return this.probation.size;
|
|
796
|
+
}
|
|
797
|
+
get protectedSize() {
|
|
798
|
+
return this.protected_.size;
|
|
799
|
+
}
|
|
800
|
+
onAccess(key) {
|
|
801
|
+
if (this.window.has(key)) {
|
|
802
|
+
this.window.delete(key);
|
|
803
|
+
this.window.add(key);
|
|
804
|
+
this.hitCount++;
|
|
805
|
+
return;
|
|
806
|
+
}
|
|
807
|
+
if (this.protected_.has(key)) {
|
|
808
|
+
this.protected_.delete(key);
|
|
809
|
+
this.protected_.add(key);
|
|
810
|
+
this.hitCount++;
|
|
811
|
+
return;
|
|
812
|
+
}
|
|
813
|
+
if (this.probation.has(key)) {
|
|
814
|
+
this.probation.delete(key);
|
|
815
|
+
this.protected_.add(key);
|
|
816
|
+
this.promotionCount++;
|
|
817
|
+
this.hitCount++;
|
|
818
|
+
if (this.protected_.size > this.maxProtected) {
|
|
819
|
+
const oldestProtKey = this.protected_.values().next().value;
|
|
820
|
+
this.protected_.delete(oldestProtKey);
|
|
821
|
+
this.probation.add(oldestProtKey);
|
|
822
|
+
this.demotionCount++;
|
|
823
|
+
}
|
|
824
|
+
return;
|
|
825
|
+
}
|
|
826
|
+
this.missCount++;
|
|
827
|
+
}
|
|
828
|
+
onSet(key, isUpdate) {
|
|
829
|
+
if (isUpdate) {
|
|
830
|
+
if (this.window.has(key)) {
|
|
831
|
+
this.window.delete(key);
|
|
832
|
+
this.window.add(key);
|
|
833
|
+
} else if (this.protected_.has(key)) {
|
|
834
|
+
this.protected_.delete(key);
|
|
835
|
+
this.protected_.add(key);
|
|
836
|
+
} else if (this.probation.has(key)) {
|
|
837
|
+
this.probation.delete(key);
|
|
838
|
+
this.probation.add(key);
|
|
839
|
+
}
|
|
840
|
+
return { admit: true };
|
|
841
|
+
}
|
|
842
|
+
this.window.add(key);
|
|
843
|
+
if (this.window.size <= this.maxWindow) {
|
|
844
|
+
this.admissionCount++;
|
|
845
|
+
return { admit: true };
|
|
846
|
+
}
|
|
847
|
+
const candKey = this.window.values().next().value;
|
|
848
|
+
this.window.delete(candKey);
|
|
849
|
+
if (this.probation.size + this.protected_.size < this.maxProbation + this.maxProtected) {
|
|
850
|
+
this.probation.add(candKey);
|
|
851
|
+
this.admissionCount++;
|
|
852
|
+
return { admit: true };
|
|
853
|
+
}
|
|
854
|
+
let victimKey;
|
|
855
|
+
let victimIsProbation = true;
|
|
856
|
+
if (this.probation.size > 0) {
|
|
857
|
+
victimKey = this.probation.values().next().value;
|
|
858
|
+
} else {
|
|
859
|
+
victimKey = this.protected_.values().next().value;
|
|
860
|
+
victimIsProbation = false;
|
|
861
|
+
}
|
|
862
|
+
const candFreq = this.sketch.estimate(candKey);
|
|
863
|
+
const victimFreq = this.sketch.estimate(victimKey);
|
|
864
|
+
if (candFreq > victimFreq) {
|
|
865
|
+
if (victimIsProbation) {
|
|
866
|
+
this.probation.delete(victimKey);
|
|
867
|
+
} else {
|
|
868
|
+
this.protected_.delete(victimKey);
|
|
869
|
+
}
|
|
870
|
+
this.probation.add(candKey);
|
|
871
|
+
this.admissionCount++;
|
|
872
|
+
return { admit: true, evictKey: victimKey, candidateKey: candKey };
|
|
873
|
+
} else {
|
|
874
|
+
this.rejectionCount++;
|
|
875
|
+
return { admit: false, candidateKey: candKey };
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
onDelete(key) {
|
|
879
|
+
this.window.delete(key);
|
|
880
|
+
this.probation.delete(key);
|
|
881
|
+
this.protected_.delete(key);
|
|
882
|
+
}
|
|
883
|
+
clear() {
|
|
884
|
+
this.window.clear();
|
|
885
|
+
this.probation.clear();
|
|
886
|
+
this.protected_.clear();
|
|
887
|
+
this.hitCount = 0;
|
|
888
|
+
this.missCount = 0;
|
|
889
|
+
this.admissionCount = 0;
|
|
890
|
+
this.rejectionCount = 0;
|
|
891
|
+
this.promotionCount = 0;
|
|
892
|
+
this.demotionCount = 0;
|
|
893
|
+
}
|
|
894
|
+
getStats() {
|
|
895
|
+
const totalRequests = this.hitCount + this.missCount;
|
|
896
|
+
return {
|
|
897
|
+
capacity: this.maxTotal,
|
|
898
|
+
size: this.window.size + this.probation.size + this.protected_.size,
|
|
899
|
+
windowSize: this.window.size,
|
|
900
|
+
probationSize: this.probation.size,
|
|
901
|
+
protectedSize: this.protected_.size,
|
|
902
|
+
hits: this.hitCount,
|
|
903
|
+
misses: this.missCount,
|
|
904
|
+
hitRate: totalRequests > 0 ? this.hitCount / totalRequests : 0,
|
|
905
|
+
admissions: this.admissionCount,
|
|
906
|
+
rejections: this.rejectionCount,
|
|
907
|
+
promotions: this.promotionCount,
|
|
908
|
+
demotions: this.demotionCount
|
|
909
|
+
};
|
|
910
|
+
}
|
|
911
|
+
getSegment(key) {
|
|
912
|
+
if (this.window.has(key)) return "window";
|
|
913
|
+
if (this.probation.has(key)) return "probation";
|
|
914
|
+
if (this.protected_.has(key)) return "protected";
|
|
915
|
+
return null;
|
|
916
|
+
}
|
|
917
|
+
};
|
|
918
|
+
|
|
919
|
+
// src/edge/utils/base64.ts
|
|
920
|
+
function base64ToUint8Array(base64) {
|
|
921
|
+
const modernU8 = Uint8Array;
|
|
922
|
+
if (typeof modernU8.fromBase64 === "function") {
|
|
923
|
+
return modernU8.fromBase64(base64);
|
|
924
|
+
}
|
|
925
|
+
const binary = globalThis.atob(base64);
|
|
926
|
+
const len = binary.length;
|
|
927
|
+
const bytes = new Uint8Array(len);
|
|
928
|
+
for (let i = 0; i < len; i++) {
|
|
929
|
+
bytes[i] = binary.charCodeAt(i);
|
|
930
|
+
}
|
|
931
|
+
return bytes;
|
|
932
|
+
}
|
|
659
933
|
|
|
660
934
|
// src/wasm/bloom-filter-wasm.ts
|
|
661
935
|
var BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
|
|
662
936
|
var KEY_STAGING_OFFSET = 2e4;
|
|
663
937
|
var MAX_KEY_BYTES = 512;
|
|
664
|
-
var BLOOM_WASM_MODULE = new WebAssembly.Module(
|
|
938
|
+
var BLOOM_WASM_MODULE = new WebAssembly.Module(
|
|
939
|
+
base64ToUint8Array(BLOOM_WASM_BASE64)
|
|
940
|
+
);
|
|
665
941
|
var WasmBloomFilter = class {
|
|
666
942
|
exports;
|
|
667
943
|
mem;
|
|
@@ -896,11 +1172,13 @@ function globMatchParts(parts, first, last, key) {
|
|
|
896
1172
|
var SmartMemoryCache = class {
|
|
897
1173
|
cache = /* @__PURE__ */ new Map();
|
|
898
1174
|
opts;
|
|
1175
|
+
codec;
|
|
899
1176
|
bloom;
|
|
900
1177
|
/** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
|
|
901
1178
|
categoryPrefixes;
|
|
902
1179
|
/** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
|
|
903
1180
|
sketch = new CountMinSketch();
|
|
1181
|
+
wtinyPolicy;
|
|
904
1182
|
totalSize = 0;
|
|
905
1183
|
categoryCount = /* @__PURE__ */ new Map();
|
|
906
1184
|
categorySize = /* @__PURE__ */ new Map();
|
|
@@ -924,8 +1202,12 @@ var SmartMemoryCache = class {
|
|
|
924
1202
|
_evictGPool = Array.from({ length: EVICTION_SAMPLE }, () => ({ key: "", score: 0 }));
|
|
925
1203
|
constructor(opts, existing) {
|
|
926
1204
|
this.opts = opts;
|
|
1205
|
+
this.codec = opts.codec ?? defaultCodec;
|
|
927
1206
|
this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
|
|
928
1207
|
this.categoryPrefixes = Object.keys(opts.categories).filter((k) => k !== "default");
|
|
1208
|
+
if (opts.admissionPolicy === "wtinylfu") {
|
|
1209
|
+
this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch);
|
|
1210
|
+
}
|
|
929
1211
|
if (existing) {
|
|
930
1212
|
for (const [k, v] of existing) this.cache.set(k, v);
|
|
931
1213
|
this.recalculateStats();
|
|
@@ -938,6 +1220,12 @@ var SmartMemoryCache = class {
|
|
|
938
1220
|
this.categoryCount.clear();
|
|
939
1221
|
this.categorySize.clear();
|
|
940
1222
|
this.categoryKeys.clear();
|
|
1223
|
+
if (this.wtinyPolicy) {
|
|
1224
|
+
this.wtinyPolicy.clear();
|
|
1225
|
+
for (const key of this.cache.keys()) {
|
|
1226
|
+
this.wtinyPolicy.onSet(key, false);
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
941
1229
|
for (const [key, entry] of this.cache) {
|
|
942
1230
|
this.totalSize += entry.size;
|
|
943
1231
|
const cat = this.getCategory(key);
|
|
@@ -963,6 +1251,7 @@ var SmartMemoryCache = class {
|
|
|
963
1251
|
_delete(key, reason = "manual") {
|
|
964
1252
|
const entry = this.cache.get(key);
|
|
965
1253
|
if (!entry) return false;
|
|
1254
|
+
this.wtinyPolicy?.onDelete(key);
|
|
966
1255
|
const cat = this.getCategory(key);
|
|
967
1256
|
this.totalSize -= entry.size;
|
|
968
1257
|
this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
|
|
@@ -1123,7 +1412,8 @@ var SmartMemoryCache = class {
|
|
|
1123
1412
|
entry.hits++;
|
|
1124
1413
|
entry.lastAccess = now;
|
|
1125
1414
|
if ((entry.hits & 3) === 0) this.sketch.increment(key);
|
|
1126
|
-
|
|
1415
|
+
this.wtinyPolicy?.onAccess(key);
|
|
1416
|
+
const value = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
1127
1417
|
const hit = {
|
|
1128
1418
|
value,
|
|
1129
1419
|
isStale: entry.staleAt !== void 0 && now > entry.staleAt,
|
|
@@ -1137,7 +1427,7 @@ var SmartMemoryCache = class {
|
|
|
1137
1427
|
return hit;
|
|
1138
1428
|
}
|
|
1139
1429
|
set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
|
|
1140
|
-
const packed =
|
|
1430
|
+
const packed = this.codec.encode(data);
|
|
1141
1431
|
const size = packed.byteLength;
|
|
1142
1432
|
this.compressions++;
|
|
1143
1433
|
this.sketch.increment(key);
|
|
@@ -1154,7 +1444,51 @@ var SmartMemoryCache = class {
|
|
|
1154
1444
|
this.categorySize.set(cat, (this.categorySize.get(cat) ?? existingEntry.size) - existingEntry.size);
|
|
1155
1445
|
this.cache.delete(key);
|
|
1156
1446
|
}
|
|
1157
|
-
this.
|
|
1447
|
+
if (this.wtinyPolicy) {
|
|
1448
|
+
const decision = this.wtinyPolicy.onSet(key, Boolean(existingEntry));
|
|
1449
|
+
if (!decision.admit) {
|
|
1450
|
+
if (decision.candidateKey === key) {
|
|
1451
|
+
if (this.opts.diskSpill) {
|
|
1452
|
+
const now2 = Date.now();
|
|
1453
|
+
const liveValue2 = size <= LARGE_VALUE_BYTES ? data : void 0;
|
|
1454
|
+
this.opts.diskSpill(key, {
|
|
1455
|
+
data: packed,
|
|
1456
|
+
value: liveValue2,
|
|
1457
|
+
isCompressed: true,
|
|
1458
|
+
expiresAt: now2 + ttlMs,
|
|
1459
|
+
staleAt,
|
|
1460
|
+
size,
|
|
1461
|
+
hits: 1,
|
|
1462
|
+
lastAccess: now2,
|
|
1463
|
+
priority,
|
|
1464
|
+
ttlMs,
|
|
1465
|
+
delta,
|
|
1466
|
+
setAt: now2,
|
|
1467
|
+
tagVersions
|
|
1468
|
+
});
|
|
1469
|
+
}
|
|
1470
|
+
return;
|
|
1471
|
+
} else if (decision.candidateKey) {
|
|
1472
|
+
const candEntry = this.cache.get(decision.candidateKey);
|
|
1473
|
+
if (candEntry && this.opts.diskSpill) {
|
|
1474
|
+
this.opts.diskSpill(decision.candidateKey, candEntry);
|
|
1475
|
+
}
|
|
1476
|
+
this._delete(decision.candidateKey, "capacity");
|
|
1477
|
+
}
|
|
1478
|
+
} else if (decision.evictKey) {
|
|
1479
|
+
const victimEntry = this.cache.get(decision.evictKey);
|
|
1480
|
+
if (victimEntry && this.opts.diskSpill) {
|
|
1481
|
+
this.opts.diskSpill(decision.evictKey, victimEntry);
|
|
1482
|
+
}
|
|
1483
|
+
this._delete(decision.evictKey, "capacity");
|
|
1484
|
+
}
|
|
1485
|
+
const catSz = this.categorySize.get(cat) ?? 0;
|
|
1486
|
+
if (catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
|
|
1487
|
+
this.ensureCapacity(cat, size);
|
|
1488
|
+
}
|
|
1489
|
+
} else {
|
|
1490
|
+
this.ensureCapacity(cat, size);
|
|
1491
|
+
}
|
|
1158
1492
|
const now = Date.now();
|
|
1159
1493
|
const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
|
|
1160
1494
|
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 });
|
|
@@ -1214,6 +1548,7 @@ var SmartMemoryCache = class {
|
|
|
1214
1548
|
}
|
|
1215
1549
|
const count = this.cache.size;
|
|
1216
1550
|
this.cache.clear();
|
|
1551
|
+
this.wtinyPolicy?.clear();
|
|
1217
1552
|
this.totalSize = 0;
|
|
1218
1553
|
this.categoryCount.clear();
|
|
1219
1554
|
this.categorySize.clear();
|
|
@@ -1381,8 +1716,8 @@ var SmartMemoryCache = class {
|
|
|
1381
1716
|
if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
|
|
1382
1717
|
if (this.cache.has(key)) continue;
|
|
1383
1718
|
const rawData = entry.data;
|
|
1384
|
-
const data = !entry.isCompressed ?
|
|
1385
|
-
const value = entry.size <= LARGE_VALUE_BYTES ?
|
|
1719
|
+
const data = !entry.isCompressed ? this.codec.encode(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
|
|
1720
|
+
const value = entry.size <= LARGE_VALUE_BYTES ? this.codec.decode(data) : void 0;
|
|
1386
1721
|
this.cache.set(key, { ...entry, data, value, isCompressed: true });
|
|
1387
1722
|
this.bloom.add(key);
|
|
1388
1723
|
loaded++;
|
|
@@ -1453,7 +1788,7 @@ var SmartMemoryCache = class {
|
|
|
1453
1788
|
* if the live object was not cached (large-entry optimisation or disk-restored entry).
|
|
1454
1789
|
*/
|
|
1455
1790
|
resolveValue(entry) {
|
|
1456
|
-
return entry.value !== void 0 ? entry.value :
|
|
1791
|
+
return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
1457
1792
|
}
|
|
1458
1793
|
// ── Stats ─────────────────────────────────────────────────────────────────
|
|
1459
1794
|
get size() {
|
|
@@ -1558,13 +1893,20 @@ var SmartMemoryCache = class {
|
|
|
1558
1893
|
out.sort((a, b) => b.hits - a.hits);
|
|
1559
1894
|
return out.slice(0, n);
|
|
1560
1895
|
}
|
|
1896
|
+
/**
|
|
1897
|
+
* Return real-time metrics and telemetry for the Window TinyLFU admission policy.
|
|
1898
|
+
* Returns `undefined` when running under default adaptive eviction.
|
|
1899
|
+
*/
|
|
1900
|
+
getWTinyLfuStats() {
|
|
1901
|
+
return this.wtinyPolicy?.getStats();
|
|
1902
|
+
}
|
|
1561
1903
|
};
|
|
1562
1904
|
|
|
1563
1905
|
// src/disk-tier.ts
|
|
1564
1906
|
var import_fs2 = __toESM(require("fs"), 1);
|
|
1565
1907
|
var import_path2 = __toESM(require("path"), 1);
|
|
1566
1908
|
var import_crypto2 = __toESM(require("crypto"), 1);
|
|
1567
|
-
var
|
|
1909
|
+
var import_os2 = __toESM(require("os"), 1);
|
|
1568
1910
|
|
|
1569
1911
|
// src/compression.ts
|
|
1570
1912
|
var import_zlib = __toESM(require("zlib"), 1);
|
|
@@ -1622,18 +1964,146 @@ function decompressWithHeader(buf, algorithm = "brotli") {
|
|
|
1622
1964
|
}
|
|
1623
1965
|
|
|
1624
1966
|
// src/disk-tier.ts
|
|
1967
|
+
var BoundedDiskQueue = class {
|
|
1968
|
+
constructor(maxConcurrent = Math.min(4, Math.max(1, Math.floor((import_os2.default?.availableParallelism?.() ?? 4) / 4))), maxPending = 512, writeTimeoutMs = 500, failureThreshold = 5, cooldownMs = 5e3) {
|
|
1969
|
+
this.maxConcurrent = maxConcurrent;
|
|
1970
|
+
this.maxPending = maxPending;
|
|
1971
|
+
this.writeTimeoutMs = writeTimeoutMs;
|
|
1972
|
+
this.failureThreshold = failureThreshold;
|
|
1973
|
+
this.cooldownMs = cooldownMs;
|
|
1974
|
+
}
|
|
1975
|
+
maxConcurrent;
|
|
1976
|
+
maxPending;
|
|
1977
|
+
writeTimeoutMs;
|
|
1978
|
+
failureThreshold;
|
|
1979
|
+
cooldownMs;
|
|
1980
|
+
active = 0;
|
|
1981
|
+
queue = [];
|
|
1982
|
+
spillsDropped = 0;
|
|
1983
|
+
consecutiveFailures = 0;
|
|
1984
|
+
circuitState = "closed";
|
|
1985
|
+
lastStateChangeMonotonic = performance.now();
|
|
1986
|
+
async schedule(task) {
|
|
1987
|
+
const now = performance.now();
|
|
1988
|
+
if (this.circuitState === "open") {
|
|
1989
|
+
if (now - this.lastStateChangeMonotonic > this.cooldownMs) {
|
|
1990
|
+
this.circuitState = "half-open";
|
|
1991
|
+
this.lastStateChangeMonotonic = now;
|
|
1992
|
+
} else {
|
|
1993
|
+
this.spillsDropped++;
|
|
1994
|
+
return null;
|
|
1995
|
+
}
|
|
1996
|
+
}
|
|
1997
|
+
if (this.circuitState === "half-open" && this.active > 0) {
|
|
1998
|
+
this.spillsDropped++;
|
|
1999
|
+
return null;
|
|
2000
|
+
}
|
|
2001
|
+
if (this.queue.length >= this.maxPending) {
|
|
2002
|
+
this.spillsDropped++;
|
|
2003
|
+
return null;
|
|
2004
|
+
}
|
|
2005
|
+
if (this.active >= this.maxConcurrent) {
|
|
2006
|
+
await new Promise((resolve) => this.queue.push(resolve));
|
|
2007
|
+
}
|
|
2008
|
+
this.active++;
|
|
2009
|
+
let timeoutId = null;
|
|
2010
|
+
try {
|
|
2011
|
+
const result = await Promise.race([
|
|
2012
|
+
task(),
|
|
2013
|
+
new Promise((_, reject) => {
|
|
2014
|
+
timeoutId = setTimeout(
|
|
2015
|
+
() => reject(new Error(`Disk write exceeded timeout of ${this.writeTimeoutMs}ms`)),
|
|
2016
|
+
this.writeTimeoutMs
|
|
2017
|
+
);
|
|
2018
|
+
})
|
|
2019
|
+
]);
|
|
2020
|
+
this.consecutiveFailures = 0;
|
|
2021
|
+
if (this.circuitState === "half-open") {
|
|
2022
|
+
this.circuitState = "closed";
|
|
2023
|
+
this.lastStateChangeMonotonic = performance.now();
|
|
2024
|
+
}
|
|
2025
|
+
return result;
|
|
2026
|
+
} catch {
|
|
2027
|
+
this.consecutiveFailures++;
|
|
2028
|
+
if (this.consecutiveFailures >= this.failureThreshold || this.circuitState === "half-open") {
|
|
2029
|
+
this.circuitState = "open";
|
|
2030
|
+
this.lastStateChangeMonotonic = performance.now();
|
|
2031
|
+
}
|
|
2032
|
+
this.spillsDropped++;
|
|
2033
|
+
return null;
|
|
2034
|
+
} finally {
|
|
2035
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
2036
|
+
this.active--;
|
|
2037
|
+
const next = this.queue.shift();
|
|
2038
|
+
if (next) next();
|
|
2039
|
+
}
|
|
2040
|
+
}
|
|
2041
|
+
getStats() {
|
|
2042
|
+
return {
|
|
2043
|
+
activeWrites: this.active,
|
|
2044
|
+
pendingWrites: this.queue.length,
|
|
2045
|
+
spillsDropped: this.spillsDropped,
|
|
2046
|
+
circuitState: this.circuitState,
|
|
2047
|
+
lastTripTimestamp: this.lastStateChangeMonotonic
|
|
2048
|
+
};
|
|
2049
|
+
}
|
|
2050
|
+
reset() {
|
|
2051
|
+
this.consecutiveFailures = 0;
|
|
2052
|
+
this.circuitState = "closed";
|
|
2053
|
+
this.lastStateChangeMonotonic = performance.now();
|
|
2054
|
+
}
|
|
2055
|
+
};
|
|
1625
2056
|
var _SqliteDB = null;
|
|
1626
2057
|
try {
|
|
1627
|
-
const
|
|
1628
|
-
|
|
2058
|
+
const proc = process;
|
|
2059
|
+
if (typeof proc.getBuiltinModule === "function") {
|
|
2060
|
+
const sqlite = proc.getBuiltinModule("node:sqlite");
|
|
2061
|
+
_SqliteDB = sqlite?.DatabaseSync ?? null;
|
|
2062
|
+
}
|
|
1629
2063
|
} catch {
|
|
1630
2064
|
}
|
|
1631
2065
|
var DISK_MAGIC = Buffer.from([68, 84, 73, 69, 82, 86, 49, 0]);
|
|
1632
2066
|
var DISK_MAGIC_V2 = Buffer.from([68, 84, 73, 69, 82, 86, 50, 0]);
|
|
1633
2067
|
var V2_HEADER_LEN = 16;
|
|
1634
2068
|
var DISK_TIER_VERSION = 1;
|
|
2069
|
+
function resolveDefaultDiskDir(namespace, logger) {
|
|
2070
|
+
const ns = namespace?.trim() ?? "";
|
|
2071
|
+
const nsDir = ns ? `tricache-disk-${ns}` : "tricache-disk";
|
|
2072
|
+
if (process.platform === "linux") {
|
|
2073
|
+
const shmPath = "/dev/shm";
|
|
2074
|
+
try {
|
|
2075
|
+
import_fs2.default.accessSync(shmPath, import_fs2.default.constants.W_OK | import_fs2.default.constants.R_OK);
|
|
2076
|
+
if (typeof import_fs2.default.statfsSync === "function") {
|
|
2077
|
+
const stats = import_fs2.default.statfsSync(shmPath);
|
|
2078
|
+
const totalBytes = Number(stats.blocks) * Number(stats.bsize);
|
|
2079
|
+
const freeBytes = Number(stats.bavail) * Number(stats.bsize);
|
|
2080
|
+
if (totalBytes >= 256 * 1024 * 1024 && freeBytes >= 128 * 1024 * 1024) {
|
|
2081
|
+
const targetDir = import_path2.default.join(shmPath, nsDir);
|
|
2082
|
+
logger?.info?.("DiskTier: Targeting Linux /dev/shm tmpfs for off-heap storage", {
|
|
2083
|
+
path: targetDir,
|
|
2084
|
+
totalBytes,
|
|
2085
|
+
freeBytes
|
|
2086
|
+
});
|
|
2087
|
+
return { dir: targetDir, isShm: true };
|
|
2088
|
+
} else {
|
|
2089
|
+
logger?.info?.("DiskTier: /dev/shm capacity or free space insufficient (<256MB total or <128MB free); falling back to tmpdir", {
|
|
2090
|
+
totalBytes,
|
|
2091
|
+
freeBytes
|
|
2092
|
+
});
|
|
2093
|
+
}
|
|
2094
|
+
}
|
|
2095
|
+
} catch (err) {
|
|
2096
|
+
logger?.debug?.("DiskTier: /dev/shm not usable, falling back to tmpdir", {
|
|
2097
|
+
error: err.message
|
|
2098
|
+
});
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
2101
|
+
return { dir: import_path2.default.join(import_os2.default.tmpdir(), nsDir), isShm: false };
|
|
2102
|
+
}
|
|
1635
2103
|
var DiskTier = class {
|
|
1636
2104
|
opts;
|
|
2105
|
+
codec;
|
|
2106
|
+
diskQueue;
|
|
1637
2107
|
dirReady = false;
|
|
1638
2108
|
diskUsageBytes = 0;
|
|
1639
2109
|
usageCounted = false;
|
|
@@ -1641,6 +2111,14 @@ var DiskTier = class {
|
|
|
1641
2111
|
// maintained in-memory; avoids walkCacheFiles() in stats
|
|
1642
2112
|
/** Next bucket index (0–255) for the staggered janitor wheel. */
|
|
1643
2113
|
_nextJanitorBucket = 0;
|
|
2114
|
+
// ── High-watermark pruning & host volume health state ─────────────────────
|
|
2115
|
+
_isPruning = false;
|
|
2116
|
+
_pruneRounds = 0;
|
|
2117
|
+
_entriesPruned = 0;
|
|
2118
|
+
_spillsShedTotal = 0;
|
|
2119
|
+
_hostVolumeLowSpace = false;
|
|
2120
|
+
_hostVolumeLowSpacePauses = 0;
|
|
2121
|
+
_writeCounter = 0;
|
|
1644
2122
|
// ── SQLite metadata index (optional, requires node:sqlite) ───────────────
|
|
1645
2123
|
_db = null;
|
|
1646
2124
|
_stmtInsert = null;
|
|
@@ -1655,8 +2133,19 @@ var DiskTier = class {
|
|
|
1655
2133
|
// DELETE expired rows
|
|
1656
2134
|
_stmtStats = null;
|
|
1657
2135
|
// COUNT + SUM(size)
|
|
2136
|
+
_stmtPruneChunk = null;
|
|
2137
|
+
// SELECT chunk for watermark pruning
|
|
1658
2138
|
constructor(opts) {
|
|
1659
2139
|
this.opts = opts;
|
|
2140
|
+
this.codec = opts.codec ?? defaultCodec;
|
|
2141
|
+
const defaultConcurrent = Math.min(4, Math.max(1, Math.floor((import_os2.default?.availableParallelism?.() ?? 4) / 4)));
|
|
2142
|
+
this.diskQueue = new BoundedDiskQueue(
|
|
2143
|
+
opts.diskMaxConcurrentWrites ?? defaultConcurrent,
|
|
2144
|
+
opts.diskMaxPendingWrites ?? 512,
|
|
2145
|
+
opts.diskWriteTimeoutMs ?? 500,
|
|
2146
|
+
opts.diskCircuitBreakerThreshold ?? 5,
|
|
2147
|
+
opts.diskCircuitBreakerCooldownMs ?? 5e3
|
|
2148
|
+
);
|
|
1660
2149
|
}
|
|
1661
2150
|
// ── Helpers ───────────────────────────────────────────────────────────────
|
|
1662
2151
|
ensureDir() {
|
|
@@ -1691,15 +2180,30 @@ var DiskTier = class {
|
|
|
1691
2180
|
PRAGMA synchronous = NORMAL;
|
|
1692
2181
|
PRAGMA temp_store = MEMORY;
|
|
1693
2182
|
CREATE TABLE IF NOT EXISTS meta (
|
|
1694
|
-
key_hash
|
|
1695
|
-
file_path
|
|
1696
|
-
expires_at
|
|
1697
|
-
size
|
|
2183
|
+
key_hash TEXT PRIMARY KEY,
|
|
2184
|
+
file_path TEXT NOT NULL,
|
|
2185
|
+
expires_at INTEGER NOT NULL,
|
|
2186
|
+
size INTEGER NOT NULL DEFAULT 0,
|
|
2187
|
+
priority INTEGER NOT NULL DEFAULT 2,
|
|
2188
|
+
last_accessed_at INTEGER NOT NULL DEFAULT 0
|
|
1698
2189
|
);
|
|
1699
2190
|
CREATE INDEX IF NOT EXISTS idx_expires ON meta (expires_at);
|
|
2191
|
+
CREATE INDEX IF NOT EXISTS idx_priority_access ON meta (priority ASC, last_accessed_at ASC);
|
|
1700
2192
|
`);
|
|
2193
|
+
try {
|
|
2194
|
+
this._db.exec("ALTER TABLE meta ADD COLUMN priority INTEGER NOT NULL DEFAULT 2;");
|
|
2195
|
+
} catch {
|
|
2196
|
+
}
|
|
2197
|
+
try {
|
|
2198
|
+
this._db.exec("ALTER TABLE meta ADD COLUMN last_accessed_at INTEGER NOT NULL DEFAULT 0;");
|
|
2199
|
+
} catch {
|
|
2200
|
+
}
|
|
2201
|
+
try {
|
|
2202
|
+
this._db.exec("CREATE INDEX IF NOT EXISTS idx_priority_access ON meta (priority ASC, last_accessed_at ASC);");
|
|
2203
|
+
} catch {
|
|
2204
|
+
}
|
|
1701
2205
|
this._stmtInsert = this._db.prepare(
|
|
1702
|
-
"INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size) VALUES (
|
|
2206
|
+
"INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size, priority, last_accessed_at) VALUES (?,?,?,?,?,?)"
|
|
1703
2207
|
);
|
|
1704
2208
|
this._stmtSelect = this._db.prepare(
|
|
1705
2209
|
"SELECT file_path, expires_at FROM meta WHERE key_hash = ?"
|
|
@@ -1712,13 +2216,16 @@ var DiskTier = class {
|
|
|
1712
2216
|
this._stmtStats = this._db.prepare(
|
|
1713
2217
|
"SELECT COUNT(*) AS cnt, COALESCE(SUM(size), 0) AS bytes FROM meta"
|
|
1714
2218
|
);
|
|
2219
|
+
this._stmtPruneChunk = this._db.prepare(
|
|
2220
|
+
"SELECT key_hash, file_path, size FROM meta ORDER BY priority ASC, last_accessed_at ASC LIMIT 500"
|
|
2221
|
+
);
|
|
1715
2222
|
const row = this._stmtStats.get();
|
|
1716
2223
|
this.fileCount = row.cnt;
|
|
1717
2224
|
this.diskUsageBytes = row.bytes;
|
|
1718
2225
|
this.usageCounted = true;
|
|
1719
2226
|
this.opts.logger.debug("DiskTier: SQLite index ready", { entries: row.cnt });
|
|
1720
2227
|
} catch (err) {
|
|
1721
|
-
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
|
|
2228
|
+
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = this._stmtPruneChunk = null;
|
|
1722
2229
|
this.opts.logger.warn("DiskTier: SQLite init failed, using file-only mode", {
|
|
1723
2230
|
error: err.message
|
|
1724
2231
|
});
|
|
@@ -1813,7 +2320,7 @@ var DiskTier = class {
|
|
|
1813
2320
|
return results;
|
|
1814
2321
|
}
|
|
1815
2322
|
isForbidden(key) {
|
|
1816
|
-
return this.opts.forbiddenPrefixes
|
|
2323
|
+
return this.opts.forbiddenPrefixes?.some((p) => key.startsWith(p)) ?? false;
|
|
1817
2324
|
}
|
|
1818
2325
|
encrypt(data) {
|
|
1819
2326
|
if (!this.opts.encryption) return data;
|
|
@@ -1865,7 +2372,16 @@ var DiskTier = class {
|
|
|
1865
2372
|
this.ensureDir();
|
|
1866
2373
|
if (!this.dirReady) return;
|
|
1867
2374
|
this.ensureUsageCounted();
|
|
1868
|
-
if (this.
|
|
2375
|
+
if (++this._writeCounter % 2e3 === 0) {
|
|
2376
|
+
this.checkHostVolumeHealth();
|
|
2377
|
+
}
|
|
2378
|
+
if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes >= this.opts.maxBytes) {
|
|
2379
|
+
this._spillsShedTotal++;
|
|
2380
|
+
return;
|
|
2381
|
+
}
|
|
2382
|
+
if (this.diskUsageBytes >= this.opts.maxBytes * 0.8 && !this._isPruning) {
|
|
2383
|
+
void this.triggerChunkedPrune();
|
|
2384
|
+
}
|
|
1869
2385
|
let final;
|
|
1870
2386
|
try {
|
|
1871
2387
|
const payload = {
|
|
@@ -1877,7 +2393,7 @@ var DiskTier = class {
|
|
|
1877
2393
|
},
|
|
1878
2394
|
writtenAt: Date.now()
|
|
1879
2395
|
};
|
|
1880
|
-
const packed =
|
|
2396
|
+
const packed = this.codec.encode(payload);
|
|
1881
2397
|
if (packed.length > this.opts.entryMaxBytes) return;
|
|
1882
2398
|
let toEncrypt = packed;
|
|
1883
2399
|
if (this.opts.compression && this.opts.compression !== "none" && packed.length > (this.opts.compressionThresholdBytes ?? 1024)) {
|
|
@@ -1893,39 +2409,52 @@ var DiskTier = class {
|
|
|
1893
2409
|
}
|
|
1894
2410
|
const hash = this.keyToHash(key);
|
|
1895
2411
|
const filePath = this.hashToWritePath(hash, entry.expiresAt);
|
|
1896
|
-
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${
|
|
2412
|
+
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${import_crypto2.default.randomBytes(6).toString("hex")}.tmp`;
|
|
1897
2413
|
this.diskUsageBytes += final.length;
|
|
1898
2414
|
this.fileCount++;
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
2415
|
+
if (this.diskUsageBytes >= this.opts.maxBytes * 0.8 && !this._isPruning) {
|
|
2416
|
+
void this.triggerChunkedPrune();
|
|
2417
|
+
}
|
|
2418
|
+
const result = await this.diskQueue.schedule(async () => {
|
|
1902
2419
|
try {
|
|
1903
|
-
await import_fs2.default.promises.
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
if (code === "EBUSY" || code === "EPERM") {
|
|
1907
|
-
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
2420
|
+
await import_fs2.default.promises.mkdir(import_path2.default.dirname(filePath), { recursive: true });
|
|
2421
|
+
await import_fs2.default.promises.writeFile(tmpPath, final, { mode: 384 });
|
|
2422
|
+
try {
|
|
1908
2423
|
await import_fs2.default.promises.rename(tmpPath, filePath);
|
|
1909
|
-
}
|
|
1910
|
-
|
|
2424
|
+
} catch (renameErr) {
|
|
2425
|
+
const code = renameErr?.code;
|
|
2426
|
+
if (code === "EBUSY" || code === "EPERM") {
|
|
2427
|
+
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
2428
|
+
await import_fs2.default.promises.rename(tmpPath, filePath);
|
|
2429
|
+
} else {
|
|
2430
|
+
throw renameErr;
|
|
2431
|
+
}
|
|
1911
2432
|
}
|
|
2433
|
+
if (this._db) {
|
|
2434
|
+
const priority = typeof entry.priority === "number" ? entry.priority : 2;
|
|
2435
|
+
const lastAccess = typeof entry.lastAccess === "number" ? entry.lastAccess : Date.now();
|
|
2436
|
+
this._stmtInsert.run(hash, filePath, entry.expiresAt, final.length, priority, lastAccess);
|
|
2437
|
+
}
|
|
2438
|
+
this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
|
|
2439
|
+
return true;
|
|
2440
|
+
} catch (err) {
|
|
2441
|
+
try {
|
|
2442
|
+
await import_fs2.default.promises.unlink(tmpPath);
|
|
2443
|
+
} catch {
|
|
2444
|
+
}
|
|
2445
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
|
|
2446
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2447
|
+
if (this._db) try {
|
|
2448
|
+
this._stmtDelete.run(hash);
|
|
2449
|
+
} catch {
|
|
2450
|
+
}
|
|
2451
|
+
this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
|
|
2452
|
+
throw err;
|
|
1912
2453
|
}
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
}
|
|
1916
|
-
this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
|
|
1917
|
-
} catch (err) {
|
|
1918
|
-
try {
|
|
1919
|
-
await import_fs2.default.promises.unlink(tmpPath);
|
|
1920
|
-
} catch {
|
|
1921
|
-
}
|
|
2454
|
+
});
|
|
2455
|
+
if (result === null) {
|
|
1922
2456
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
|
|
1923
2457
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1924
|
-
if (this._db) try {
|
|
1925
|
-
this._stmtDelete.run(hash);
|
|
1926
|
-
} catch {
|
|
1927
|
-
}
|
|
1928
|
-
this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
|
|
1929
2458
|
}
|
|
1930
2459
|
}
|
|
1931
2460
|
/** Load a key from disk, or return null on miss/expiry/corruption. */
|
|
@@ -2003,7 +2532,7 @@ var DiskTier = class {
|
|
|
2003
2532
|
}
|
|
2004
2533
|
}
|
|
2005
2534
|
const uncompressed = decompressWithHeader(decrypted, this.opts.compression ?? "brotli");
|
|
2006
|
-
const payload =
|
|
2535
|
+
const payload = this.codec.decode(uncompressed);
|
|
2007
2536
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
|
|
2008
2537
|
if (payload.entry.expiresAt <= Date.now()) return null;
|
|
2009
2538
|
const entry = payload.entry;
|
|
@@ -2126,7 +2655,7 @@ var DiskTier = class {
|
|
|
2126
2655
|
purged++;
|
|
2127
2656
|
continue;
|
|
2128
2657
|
}
|
|
2129
|
-
const payload =
|
|
2658
|
+
const payload = this.codec.decode(dec);
|
|
2130
2659
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
2131
2660
|
import_fs2.default.unlinkSync(filePath);
|
|
2132
2661
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
@@ -2290,7 +2819,7 @@ var DiskTier = class {
|
|
|
2290
2819
|
purged++;
|
|
2291
2820
|
continue;
|
|
2292
2821
|
}
|
|
2293
|
-
const payload =
|
|
2822
|
+
const payload = this.codec.decode(dec);
|
|
2294
2823
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
2295
2824
|
import_fs2.default.unlinkSync(filePath);
|
|
2296
2825
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
@@ -2329,13 +2858,141 @@ var DiskTier = class {
|
|
|
2329
2858
|
}
|
|
2330
2859
|
return cleared;
|
|
2331
2860
|
}
|
|
2861
|
+
/**
|
|
2862
|
+
* Proactively checks host volume free space via statfsSync.
|
|
2863
|
+
* If free space on the volume drops below 10%, pauses spills to prevent
|
|
2864
|
+
* Kubernetes pod eviction (DiskPressure / EphemeralStorageExceeded).
|
|
2865
|
+
*/
|
|
2866
|
+
checkHostVolumeHealth() {
|
|
2867
|
+
try {
|
|
2868
|
+
if (typeof import_fs2.default.statfsSync === "function") {
|
|
2869
|
+
const stats = import_fs2.default.statfsSync(this.opts.dir);
|
|
2870
|
+
const total = Number(stats.blocks);
|
|
2871
|
+
const avail = Number(stats.bavail);
|
|
2872
|
+
if (total > 0) {
|
|
2873
|
+
const freeRatio = avail / total;
|
|
2874
|
+
if (freeRatio < 0.1) {
|
|
2875
|
+
if (!this._hostVolumeLowSpace) {
|
|
2876
|
+
this._hostVolumeLowSpace = true;
|
|
2877
|
+
this._hostVolumeLowSpacePauses++;
|
|
2878
|
+
this.opts.logger.warn(
|
|
2879
|
+
"DiskTier: host volume has <10% free space. Pausing disk cache spills to prevent Kubernetes eviction.",
|
|
2880
|
+
{ dir: this.opts.dir, freePct: Number((freeRatio * 100).toFixed(1)) }
|
|
2881
|
+
);
|
|
2882
|
+
}
|
|
2883
|
+
return false;
|
|
2884
|
+
} else if (this._hostVolumeLowSpace) {
|
|
2885
|
+
this._hostVolumeLowSpace = false;
|
|
2886
|
+
this.opts.logger.info(
|
|
2887
|
+
"DiskTier: host volume space recovered (>=10% free). Resuming disk cache spills.",
|
|
2888
|
+
{ dir: this.opts.dir, freePct: Number((freeRatio * 100).toFixed(1)) }
|
|
2889
|
+
);
|
|
2890
|
+
return true;
|
|
2891
|
+
}
|
|
2892
|
+
}
|
|
2893
|
+
}
|
|
2894
|
+
} catch {
|
|
2895
|
+
}
|
|
2896
|
+
return true;
|
|
2897
|
+
}
|
|
2898
|
+
/**
|
|
2899
|
+
* Non-blocking chunked pruning:
|
|
2900
|
+
* Evicts oldest entries in 500-entry chunks down to 60% watermark,
|
|
2901
|
+
* yielding to the event loop via setImmediate between chunks.
|
|
2902
|
+
*/
|
|
2903
|
+
async triggerChunkedPrune() {
|
|
2904
|
+
if (this._isPruning) return 0;
|
|
2905
|
+
this._isPruning = true;
|
|
2906
|
+
this._pruneRounds++;
|
|
2907
|
+
let prunedInThisRound = 0;
|
|
2908
|
+
try {
|
|
2909
|
+
this.ensureUsageCounted();
|
|
2910
|
+
const targetBytes = Math.floor(this.opts.maxBytes * 0.6);
|
|
2911
|
+
if (this._db && this._stmtPruneChunk) {
|
|
2912
|
+
while (this.diskUsageBytes > targetBytes) {
|
|
2913
|
+
const rows = this._stmtPruneChunk.all();
|
|
2914
|
+
if (!rows || rows.length === 0) break;
|
|
2915
|
+
for (const row of rows) {
|
|
2916
|
+
try {
|
|
2917
|
+
import_fs2.default.unlinkSync(row.file_path);
|
|
2918
|
+
} catch {
|
|
2919
|
+
}
|
|
2920
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
|
|
2921
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2922
|
+
this._entriesPruned++;
|
|
2923
|
+
prunedInThisRound++;
|
|
2924
|
+
try {
|
|
2925
|
+
this._stmtDelete.run(row.key_hash);
|
|
2926
|
+
} catch {
|
|
2927
|
+
}
|
|
2928
|
+
if (this.diskUsageBytes <= targetBytes) break;
|
|
2929
|
+
}
|
|
2930
|
+
if (this.diskUsageBytes > targetBytes) {
|
|
2931
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
2932
|
+
}
|
|
2933
|
+
}
|
|
2934
|
+
} else {
|
|
2935
|
+
while (this.diskUsageBytes > targetBytes) {
|
|
2936
|
+
const files = this.walkCacheFiles();
|
|
2937
|
+
if (files.length === 0) break;
|
|
2938
|
+
const chunk = files.slice(0, 500);
|
|
2939
|
+
for (const filePath of chunk) {
|
|
2940
|
+
try {
|
|
2941
|
+
const stat = import_fs2.default.statSync(filePath);
|
|
2942
|
+
import_fs2.default.unlinkSync(filePath);
|
|
2943
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
2944
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2945
|
+
this._entriesPruned++;
|
|
2946
|
+
prunedInThisRound++;
|
|
2947
|
+
} catch {
|
|
2948
|
+
}
|
|
2949
|
+
if (this.diskUsageBytes <= targetBytes) break;
|
|
2950
|
+
}
|
|
2951
|
+
if (this.diskUsageBytes > targetBytes) {
|
|
2952
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
2953
|
+
}
|
|
2954
|
+
}
|
|
2955
|
+
}
|
|
2956
|
+
} finally {
|
|
2957
|
+
this._isPruning = false;
|
|
2958
|
+
}
|
|
2959
|
+
return prunedInThisRound;
|
|
2960
|
+
}
|
|
2961
|
+
get isPruning() {
|
|
2962
|
+
return this._isPruning;
|
|
2963
|
+
}
|
|
2964
|
+
get hostVolumeLowSpace() {
|
|
2965
|
+
return this._hostVolumeLowSpace;
|
|
2966
|
+
}
|
|
2967
|
+
get spillsShedTotal() {
|
|
2968
|
+
return this._spillsShedTotal;
|
|
2969
|
+
}
|
|
2970
|
+
getPruningStats() {
|
|
2971
|
+
return {
|
|
2972
|
+
active: this._isPruning,
|
|
2973
|
+
pruneRounds: this._pruneRounds,
|
|
2974
|
+
entriesPruned: this._entriesPruned,
|
|
2975
|
+
spillsShedTotal: this._spillsShedTotal,
|
|
2976
|
+
hostVolumeLowSpacePauses: this._hostVolumeLowSpacePauses
|
|
2977
|
+
};
|
|
2978
|
+
}
|
|
2332
2979
|
get stats() {
|
|
2333
2980
|
if (this._db) {
|
|
2334
2981
|
const row = this._stmtStats.get();
|
|
2335
2982
|
this.fileCount = row.cnt;
|
|
2336
2983
|
this.diskUsageBytes = row.bytes;
|
|
2337
2984
|
}
|
|
2338
|
-
return {
|
|
2985
|
+
return {
|
|
2986
|
+
files: this.fileCount,
|
|
2987
|
+
sizeKB: Math.round(this.diskUsageBytes / 1024),
|
|
2988
|
+
maxKB: Math.round(this.opts.maxBytes / 1024),
|
|
2989
|
+
backpressure: this.diskQueue.getStats(),
|
|
2990
|
+
pruning: this.getPruningStats()
|
|
2991
|
+
};
|
|
2992
|
+
}
|
|
2993
|
+
/** Direct access to the bounded write queue for chaos diagnostics and canary controls. */
|
|
2994
|
+
get backpressure() {
|
|
2995
|
+
return this.diskQueue;
|
|
2339
2996
|
}
|
|
2340
2997
|
/** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
|
|
2341
2998
|
get indexMode() {
|
|
@@ -2348,72 +3005,831 @@ var DiskTier = class {
|
|
|
2348
3005
|
this._db.close();
|
|
2349
3006
|
} catch {
|
|
2350
3007
|
}
|
|
2351
|
-
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
|
|
3008
|
+
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = this._stmtPruneChunk = null;
|
|
2352
3009
|
}
|
|
2353
3010
|
}
|
|
2354
3011
|
};
|
|
2355
3012
|
|
|
2356
|
-
// src/
|
|
2357
|
-
var
|
|
2358
|
-
|
|
2359
|
-
|
|
2360
|
-
|
|
2361
|
-
end
|
|
2362
|
-
return 0
|
|
2363
|
-
`;
|
|
2364
|
-
var SNAPSHOT_VERSION = 1;
|
|
2365
|
-
var DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
|
|
2366
|
-
var INDEFINITE_TTL_SECONDS = 31536e3;
|
|
2367
|
-
var SNAPSHOT_MAX_FILE_BYTES = 220 * 1024 * 1024;
|
|
2368
|
-
var DEFAULT_CATEGORY_LIMITS = {
|
|
2369
|
-
"default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
|
|
2370
|
-
};
|
|
2371
|
-
var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
|
|
2372
|
-
var DEFAULT_COUNTER_TTL_SECONDS = 60;
|
|
2373
|
-
var GLOB_REGEX_CACHE_MAX = 256;
|
|
2374
|
-
var globRegexCache = /* @__PURE__ */ new Map();
|
|
2375
|
-
function getGlobRegex(pattern) {
|
|
2376
|
-
let re = globRegexCache.get(pattern);
|
|
2377
|
-
if (re) {
|
|
2378
|
-
globRegexCache.delete(pattern);
|
|
2379
|
-
globRegexCache.set(pattern, re);
|
|
2380
|
-
return re;
|
|
2381
|
-
}
|
|
2382
|
-
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*+/g, ".*");
|
|
2383
|
-
re = new RegExp("^" + escaped + "$");
|
|
2384
|
-
if (globRegexCache.size >= GLOB_REGEX_CACHE_MAX) {
|
|
2385
|
-
const oldestKey = globRegexCache.keys().next().value;
|
|
2386
|
-
if (oldestKey !== void 0) globRegexCache.delete(oldestKey);
|
|
2387
|
-
}
|
|
2388
|
-
globRegexCache.set(pattern, re);
|
|
2389
|
-
return re;
|
|
2390
|
-
}
|
|
2391
|
-
var L2CircuitBreaker = class {
|
|
2392
|
-
constructor(threshold, cooldownMs) {
|
|
2393
|
-
this.threshold = threshold;
|
|
2394
|
-
this.cooldownMs = cooldownMs;
|
|
2395
|
-
}
|
|
2396
|
-
threshold;
|
|
3013
|
+
// src/latency-watchdog.ts
|
|
3014
|
+
var TierLatencyWatchdog = class {
|
|
3015
|
+
enabled;
|
|
3016
|
+
minDiskBypassMs;
|
|
3017
|
+
bypassRatio;
|
|
2397
3018
|
cooldownMs;
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
|
|
3019
|
+
redisCutoffMs;
|
|
3020
|
+
redisRecoveryFloorMs;
|
|
3021
|
+
minSamples;
|
|
3022
|
+
disableRedis;
|
|
3023
|
+
// Zero-allocation rolling ring buffers
|
|
3024
|
+
diskRing = new Float32Array(32);
|
|
3025
|
+
redisRing = new Float32Array(32);
|
|
3026
|
+
scratch = new Float32Array(32);
|
|
3027
|
+
diskIdx = 0;
|
|
3028
|
+
redisIdx = 0;
|
|
3029
|
+
diskCount = 0;
|
|
3030
|
+
redisCount = 0;
|
|
3031
|
+
// Cached amortized p95 values
|
|
3032
|
+
cachedDiskP95 = 0;
|
|
3033
|
+
cachedRedisP95 = 0;
|
|
3034
|
+
// State machine & control-theory flags
|
|
3035
|
+
stage = 0;
|
|
3036
|
+
redisDampened = false;
|
|
3037
|
+
// Asymmetric hysteresis latch
|
|
3038
|
+
redisRecoveryConsecutiveSamples = 0;
|
|
3039
|
+
bypassedUntilMonotonic = 0;
|
|
3040
|
+
canaryInFlight = false;
|
|
3041
|
+
bypassedTotal = 0;
|
|
3042
|
+
constructor(options = {}) {
|
|
3043
|
+
this.enabled = options.enabled ?? true;
|
|
3044
|
+
this.minDiskBypassMs = options.minDiskBypassMs ?? 10;
|
|
3045
|
+
this.bypassRatio = options.bypassRatio ?? 1.5;
|
|
3046
|
+
this.cooldownMs = options.cooldownMs ?? 3e4;
|
|
3047
|
+
this.redisCutoffMs = options.redisCutoffMs ?? 15;
|
|
3048
|
+
this.redisRecoveryFloorMs = options.redisRecoveryFloorMs ?? 10;
|
|
3049
|
+
this.minSamples = options.minSamples ?? 16;
|
|
3050
|
+
this.disableRedis = options.disableRedis ?? false;
|
|
3051
|
+
}
|
|
3052
|
+
setDisableRedis(disabled) {
|
|
3053
|
+
this.disableRedis = disabled;
|
|
3054
|
+
if (disabled) {
|
|
3055
|
+
this.stage = 0;
|
|
3056
|
+
this.bypassedUntilMonotonic = 0;
|
|
3057
|
+
this.canaryInFlight = false;
|
|
3058
|
+
this.redisRecoveryConsecutiveSamples = 0;
|
|
3059
|
+
}
|
|
3060
|
+
}
|
|
2403
3061
|
/**
|
|
2404
|
-
*
|
|
2405
|
-
* In HALF_OPEN, only ONE probe is permitted at a time — concurrent callers
|
|
2406
|
-
* arriving while a probe is outstanding are rejected (return false) so a
|
|
2407
|
-
* recovering Redis node is not stampeded.
|
|
3062
|
+
* Record disk read duration in milliseconds (zero-allocation hot path).
|
|
2408
3063
|
*/
|
|
2409
|
-
|
|
3064
|
+
recordDisk(ms) {
|
|
3065
|
+
if (!this.enabled) return;
|
|
3066
|
+
this.diskRing[this.diskIdx++ & 31] = ms;
|
|
3067
|
+
this.diskCount++;
|
|
3068
|
+
if ((this.diskIdx & 31) === 0) {
|
|
3069
|
+
this.recalculateP95();
|
|
3070
|
+
}
|
|
3071
|
+
}
|
|
3072
|
+
/**
|
|
3073
|
+
* Record Redis read duration in milliseconds (zero-allocation hot path).
|
|
3074
|
+
*/
|
|
3075
|
+
recordRedis(ms) {
|
|
3076
|
+
if (!this.enabled || this.disableRedis) return;
|
|
3077
|
+
this.redisRing[this.redisIdx++ & 31] = ms;
|
|
3078
|
+
this.redisCount++;
|
|
3079
|
+
if (ms <= this.redisRecoveryFloorMs) {
|
|
3080
|
+
this.redisRecoveryConsecutiveSamples++;
|
|
3081
|
+
} else {
|
|
3082
|
+
this.redisRecoveryConsecutiveSamples = 0;
|
|
3083
|
+
}
|
|
3084
|
+
if ((this.redisIdx & 31) === 0) {
|
|
3085
|
+
this.recalculateP95();
|
|
3086
|
+
}
|
|
3087
|
+
}
|
|
3088
|
+
recalculateP95() {
|
|
3089
|
+
if (this.diskCount >= this.minSamples) {
|
|
3090
|
+
this.cachedDiskP95 = this.computeP95(this.diskRing, Math.min(this.diskCount, 32));
|
|
3091
|
+
}
|
|
3092
|
+
if (this.redisCount >= this.minSamples) {
|
|
3093
|
+
this.cachedRedisP95 = this.computeP95(this.redisRing, Math.min(this.redisCount, 32));
|
|
3094
|
+
}
|
|
3095
|
+
this.evaluateControlLoop();
|
|
3096
|
+
}
|
|
3097
|
+
computeP95(ring, count) {
|
|
3098
|
+
for (let i = 0; i < count; i++) {
|
|
3099
|
+
this.scratch[i] = ring[i];
|
|
3100
|
+
}
|
|
3101
|
+
this.scratch.subarray(0, count).sort();
|
|
3102
|
+
const rank = Math.min(count - 1, Math.max(0, Math.floor((count - 1) * 0.95)));
|
|
3103
|
+
return this.scratch[rank];
|
|
3104
|
+
}
|
|
3105
|
+
/**
|
|
3106
|
+
* Core Control Loop:
|
|
3107
|
+
* - Evaluates asymmetric hysteresis on Redis circuit.
|
|
3108
|
+
* - Assigns graduated stage (0, 1, 2, 3) with anti-synchronicity jitter.
|
|
3109
|
+
*/
|
|
3110
|
+
evaluateControlLoop() {
|
|
3111
|
+
if (this.disableRedis) {
|
|
3112
|
+
this.stage = 0;
|
|
3113
|
+
return;
|
|
3114
|
+
}
|
|
3115
|
+
if (this.cachedRedisP95 >= this.redisCutoffMs) {
|
|
3116
|
+
this.redisDampened = true;
|
|
3117
|
+
} else if (this.redisDampened && this.cachedRedisP95 <= this.redisRecoveryFloorMs && this.redisRecoveryConsecutiveSamples >= this.minSamples) {
|
|
3118
|
+
this.redisDampened = false;
|
|
3119
|
+
}
|
|
3120
|
+
if (this.redisDampened) {
|
|
3121
|
+
this.stage = 0;
|
|
3122
|
+
return;
|
|
3123
|
+
}
|
|
3124
|
+
if (this.diskCount < this.minSamples || this.redisCount < this.minSamples) {
|
|
3125
|
+
return;
|
|
3126
|
+
}
|
|
3127
|
+
const diskP95 = this.cachedDiskP95;
|
|
3128
|
+
const redisP95 = Math.max(0.1, this.cachedRedisP95);
|
|
3129
|
+
if (diskP95 >= 50) {
|
|
3130
|
+
if (this.stage !== 3) {
|
|
3131
|
+
this.stage = 3;
|
|
3132
|
+
this.bypassedUntilMonotonic = performance.now() + this.calculateJitteredCooldown();
|
|
3133
|
+
this.bypassedTotal++;
|
|
3134
|
+
}
|
|
3135
|
+
} else if (diskP95 >= this.minDiskBypassMs * 2.5 && diskP95 >= redisP95 * (this.bypassRatio * 1.5)) {
|
|
3136
|
+
if (this.stage !== 2) {
|
|
3137
|
+
this.stage = 2;
|
|
3138
|
+
this.bypassedTotal++;
|
|
3139
|
+
}
|
|
3140
|
+
} else if (diskP95 >= this.minDiskBypassMs && diskP95 >= redisP95 * this.bypassRatio) {
|
|
3141
|
+
if (this.stage !== 1) {
|
|
3142
|
+
this.stage = 1;
|
|
3143
|
+
this.bypassedTotal++;
|
|
3144
|
+
}
|
|
3145
|
+
} else {
|
|
3146
|
+
this.stage = 0;
|
|
3147
|
+
this.bypassedUntilMonotonic = 0;
|
|
3148
|
+
this.canaryInFlight = false;
|
|
3149
|
+
}
|
|
3150
|
+
}
|
|
3151
|
+
calculateJitteredCooldown() {
|
|
3152
|
+
const jitterFactor = 0.7 + Math.random() * 0.6;
|
|
3153
|
+
return this.cooldownMs * jitterFactor;
|
|
3154
|
+
}
|
|
3155
|
+
/**
|
|
3156
|
+
* Determine whether a read is permitted to check the disk tier.
|
|
3157
|
+
*
|
|
3158
|
+
* In Stage 1 and 2, sheds traffic probabilistically.
|
|
3159
|
+
* In Stage 3, blocks all reads except for a single canary probe once cooldown expires.
|
|
3160
|
+
*
|
|
3161
|
+
* @param randomOverride Optional seeded random number [0, 1) for deterministic unit testing.
|
|
3162
|
+
*/
|
|
3163
|
+
isDiskAllowed(randomOverride) {
|
|
3164
|
+
if (!this.enabled || this.disableRedis) return true;
|
|
3165
|
+
if (this.stage === 0) return true;
|
|
3166
|
+
const rand = randomOverride !== void 0 ? randomOverride : Math.random();
|
|
3167
|
+
if (this.stage === 1) {
|
|
3168
|
+
return rand > 0.25;
|
|
3169
|
+
}
|
|
3170
|
+
if (this.stage === 2) {
|
|
3171
|
+
return rand > 0.75;
|
|
3172
|
+
}
|
|
3173
|
+
const now = performance.now();
|
|
3174
|
+
if (now < this.bypassedUntilMonotonic) {
|
|
3175
|
+
return false;
|
|
3176
|
+
}
|
|
3177
|
+
if (!this.canaryInFlight) {
|
|
3178
|
+
this.canaryInFlight = true;
|
|
3179
|
+
return true;
|
|
3180
|
+
}
|
|
3181
|
+
return false;
|
|
3182
|
+
}
|
|
3183
|
+
/**
|
|
3184
|
+
* Callback invoked when the single canary read probe completes.
|
|
3185
|
+
*/
|
|
3186
|
+
onCanaryResult(success, elapsedMs) {
|
|
3187
|
+
if (!this.canaryInFlight) return;
|
|
3188
|
+
this.canaryInFlight = false;
|
|
3189
|
+
if (success && elapsedMs < this.minDiskBypassMs) {
|
|
3190
|
+
this.stage = 0;
|
|
3191
|
+
this.bypassedUntilMonotonic = 0;
|
|
3192
|
+
this.recordDisk(elapsedMs);
|
|
3193
|
+
} else {
|
|
3194
|
+
this.bypassedUntilMonotonic = performance.now() + this.calculateJitteredCooldown();
|
|
3195
|
+
this.bypassedTotal++;
|
|
3196
|
+
}
|
|
3197
|
+
}
|
|
3198
|
+
getTelemetry() {
|
|
3199
|
+
return {
|
|
3200
|
+
bypassActive: this.stage > 0,
|
|
3201
|
+
bypassStage: this.stage,
|
|
3202
|
+
diskP95Ms: Number(this.cachedDiskP95.toFixed(2)),
|
|
3203
|
+
redisP95Ms: Number(this.cachedRedisP95.toFixed(2)),
|
|
3204
|
+
redisDampened: this.redisDampened,
|
|
3205
|
+
bypassedTotal: this.bypassedTotal
|
|
3206
|
+
};
|
|
3207
|
+
}
|
|
3208
|
+
};
|
|
3209
|
+
|
|
3210
|
+
// src/utils/cgroup.ts
|
|
3211
|
+
var import_node_fs = __toESM(require("fs"), 1);
|
|
3212
|
+
var import_node_v8 = __toESM(require("v8"), 1);
|
|
3213
|
+
var UNBOUNDED_CGROUP_THRESHOLD = 9e18;
|
|
3214
|
+
var DEFAULT_AUTONOMOUS_L1_CEILING_BYTES = 512 * 1024 * 1024;
|
|
3215
|
+
var MIN_AUTONOMOUS_L1_FLOOR_BYTES = 16 * 1024 * 1024;
|
|
3216
|
+
function readCgroupMemoryLimit() {
|
|
3217
|
+
if (process.platform !== "linux") {
|
|
3218
|
+
return Infinity;
|
|
3219
|
+
}
|
|
3220
|
+
try {
|
|
3221
|
+
if (import_node_fs.default.existsSync("/sys/fs/cgroup/memory.max")) {
|
|
3222
|
+
const raw = import_node_fs.default.readFileSync("/sys/fs/cgroup/memory.max", "utf8").trim();
|
|
3223
|
+
if (raw === "max") {
|
|
3224
|
+
return Infinity;
|
|
3225
|
+
}
|
|
3226
|
+
const bytes = parseInt(raw, 10);
|
|
3227
|
+
if (Number.isFinite(bytes) && bytes > 0 && bytes < UNBOUNDED_CGROUP_THRESHOLD) {
|
|
3228
|
+
return bytes;
|
|
3229
|
+
}
|
|
3230
|
+
}
|
|
3231
|
+
} catch {
|
|
3232
|
+
}
|
|
3233
|
+
try {
|
|
3234
|
+
if (import_node_fs.default.existsSync("/sys/fs/cgroup/memory/memory.limit_in_bytes")) {
|
|
3235
|
+
const raw = import_node_fs.default.readFileSync("/sys/fs/cgroup/memory/memory.limit_in_bytes", "utf8").trim();
|
|
3236
|
+
const bytes = parseInt(raw, 10);
|
|
3237
|
+
if (Number.isFinite(bytes) && bytes > 0 && bytes < UNBOUNDED_CGROUP_THRESHOLD) {
|
|
3238
|
+
return bytes;
|
|
3239
|
+
}
|
|
3240
|
+
}
|
|
3241
|
+
} catch {
|
|
3242
|
+
}
|
|
3243
|
+
return Infinity;
|
|
3244
|
+
}
|
|
3245
|
+
function getV8HeapLimit() {
|
|
3246
|
+
try {
|
|
3247
|
+
const stats = import_node_v8.default.getHeapStatistics();
|
|
3248
|
+
if (stats && Number.isFinite(stats.heap_size_limit) && stats.heap_size_limit > 0) {
|
|
3249
|
+
return stats.heap_size_limit;
|
|
3250
|
+
}
|
|
3251
|
+
} catch {
|
|
3252
|
+
}
|
|
3253
|
+
return Infinity;
|
|
3254
|
+
}
|
|
3255
|
+
function resolveAutonomousL1MaxBytes(options) {
|
|
3256
|
+
const cgroup = options?.cgroupLimit !== void 0 ? options.cgroupLimit : readCgroupMemoryLimit();
|
|
3257
|
+
const v8Limit = options?.v8HeapLimit !== void 0 ? options.v8HeapLimit : getV8HeapLimit();
|
|
3258
|
+
const ceiling = options?.defaultCeilingBytes ?? DEFAULT_AUTONOMOUS_L1_CEILING_BYTES;
|
|
3259
|
+
const cgroupCap = Number.isFinite(cgroup) && cgroup > 0 ? cgroup * 0.4 : Infinity;
|
|
3260
|
+
const v8Cap = Number.isFinite(v8Limit) && v8Limit > 0 ? v8Limit * 0.5 : Infinity;
|
|
3261
|
+
const resolved = Math.min(cgroupCap, v8Cap, ceiling);
|
|
3262
|
+
if (!Number.isFinite(resolved) || resolved <= 0) {
|
|
3263
|
+
return ceiling;
|
|
3264
|
+
}
|
|
3265
|
+
return Math.max(MIN_AUTONOMOUS_L1_FLOOR_BYTES, Math.floor(resolved));
|
|
3266
|
+
}
|
|
3267
|
+
|
|
3268
|
+
// src/adapters/auto-pipeliner.ts
|
|
3269
|
+
var AutoPipeliner = class {
|
|
3270
|
+
constructor(client, options) {
|
|
3271
|
+
this.client = client;
|
|
3272
|
+
this.maxBatchSize = options?.maxBatchSize ?? 100;
|
|
3273
|
+
this.enabled = options?.enabled ?? true;
|
|
3274
|
+
}
|
|
3275
|
+
client;
|
|
3276
|
+
maxBatchSize;
|
|
3277
|
+
enabled;
|
|
3278
|
+
queue = [];
|
|
3279
|
+
scheduled = false;
|
|
3280
|
+
inFlight = false;
|
|
3281
|
+
statsInternal = {
|
|
3282
|
+
batchesDispatched: 0,
|
|
3283
|
+
operationsBatched: 0
|
|
3284
|
+
};
|
|
3285
|
+
get stats() {
|
|
3286
|
+
return {
|
|
3287
|
+
batchesDispatched: this.statsInternal.batchesDispatched,
|
|
3288
|
+
operationsBatched: this.statsInternal.operationsBatched,
|
|
3289
|
+
pendingQueueSize: this.queue.length
|
|
3290
|
+
};
|
|
3291
|
+
}
|
|
3292
|
+
async get(key) {
|
|
3293
|
+
if (!this.enabled || !this.supportsPipelines()) {
|
|
3294
|
+
return this.client.get(key);
|
|
3295
|
+
}
|
|
3296
|
+
return new Promise((resolve, reject) => {
|
|
3297
|
+
this.enqueue({ type: "get", key, resolve, reject });
|
|
3298
|
+
});
|
|
3299
|
+
}
|
|
3300
|
+
async setex(key, seconds, value) {
|
|
3301
|
+
if (!this.enabled || !this.supportsPipelines()) {
|
|
3302
|
+
if (typeof this.client.setex === "function") {
|
|
3303
|
+
await this.client.setex(key, seconds, value);
|
|
3304
|
+
} else {
|
|
3305
|
+
await this.client.set(key, value, "EX", seconds);
|
|
3306
|
+
}
|
|
3307
|
+
return;
|
|
3308
|
+
}
|
|
3309
|
+
return new Promise((resolve, reject) => {
|
|
3310
|
+
this.enqueue({ type: "setex", key, seconds, value, resolve, reject });
|
|
3311
|
+
});
|
|
3312
|
+
}
|
|
3313
|
+
async del(...keys) {
|
|
3314
|
+
if (keys.length === 0) return 0;
|
|
3315
|
+
if (!this.enabled || !this.supportsPipelines()) {
|
|
3316
|
+
return this.client.del(...keys);
|
|
3317
|
+
}
|
|
3318
|
+
return new Promise((resolve, reject) => {
|
|
3319
|
+
this.enqueue({ type: "del", keys, resolve, reject });
|
|
3320
|
+
});
|
|
3321
|
+
}
|
|
3322
|
+
supportsPipelines() {
|
|
3323
|
+
return Boolean(
|
|
3324
|
+
typeof this.client?.pipeline === "function" || typeof this.client?.multi === "function"
|
|
3325
|
+
);
|
|
3326
|
+
}
|
|
3327
|
+
enqueue(op) {
|
|
3328
|
+
this.queue.push(op);
|
|
3329
|
+
if (this.queue.length >= this.maxBatchSize) {
|
|
3330
|
+
void this.flush();
|
|
3331
|
+
return;
|
|
3332
|
+
}
|
|
3333
|
+
if (!this.scheduled) {
|
|
3334
|
+
this.scheduled = true;
|
|
3335
|
+
queueMicrotask(() => {
|
|
3336
|
+
this.scheduled = false;
|
|
3337
|
+
void this.flush();
|
|
3338
|
+
});
|
|
3339
|
+
}
|
|
3340
|
+
}
|
|
3341
|
+
async flush() {
|
|
3342
|
+
if (this.queue.length === 0) return;
|
|
3343
|
+
const batch = this.queue;
|
|
3344
|
+
this.queue = [];
|
|
3345
|
+
this.scheduled = false;
|
|
3346
|
+
this.statsInternal.batchesDispatched++;
|
|
3347
|
+
this.statsInternal.operationsBatched += batch.length;
|
|
3348
|
+
const pipe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
|
|
3349
|
+
for (const op of batch) {
|
|
3350
|
+
switch (op.type) {
|
|
3351
|
+
case "get":
|
|
3352
|
+
pipe.get(op.key);
|
|
3353
|
+
break;
|
|
3354
|
+
case "setex":
|
|
3355
|
+
pipe.setex(op.key, op.seconds, op.value);
|
|
3356
|
+
break;
|
|
3357
|
+
case "del":
|
|
3358
|
+
pipe.del(...op.keys);
|
|
3359
|
+
break;
|
|
3360
|
+
}
|
|
3361
|
+
}
|
|
3362
|
+
try {
|
|
3363
|
+
const results = await pipe.exec();
|
|
3364
|
+
if (!results) {
|
|
3365
|
+
for (const op of batch) {
|
|
3366
|
+
if (op.type === "get") op.resolve(null);
|
|
3367
|
+
else if (op.type === "del") op.resolve(0);
|
|
3368
|
+
else op.resolve();
|
|
3369
|
+
}
|
|
3370
|
+
return;
|
|
3371
|
+
}
|
|
3372
|
+
for (let i = 0; i < batch.length; i++) {
|
|
3373
|
+
const op = batch[i];
|
|
3374
|
+
const resTuple = results[i];
|
|
3375
|
+
if (!resTuple) {
|
|
3376
|
+
if (op.type === "get") op.resolve(null);
|
|
3377
|
+
else if (op.type === "del") op.resolve(0);
|
|
3378
|
+
else op.resolve();
|
|
3379
|
+
continue;
|
|
3380
|
+
}
|
|
3381
|
+
const [err, val] = resTuple;
|
|
3382
|
+
if (err) {
|
|
3383
|
+
op.reject(err instanceof Error ? err : new Error(String(err)));
|
|
3384
|
+
} else {
|
|
3385
|
+
if (op.type === "get") {
|
|
3386
|
+
op.resolve(val != null ? String(val) : null);
|
|
3387
|
+
} else if (op.type === "del") {
|
|
3388
|
+
op.resolve(typeof val === "number" ? val : Number(val) || 0);
|
|
3389
|
+
} else {
|
|
3390
|
+
op.resolve();
|
|
3391
|
+
}
|
|
3392
|
+
}
|
|
3393
|
+
}
|
|
3394
|
+
} catch (err) {
|
|
3395
|
+
for (const op of batch) {
|
|
3396
|
+
op.reject(err instanceof Error ? err : new Error(String(err)));
|
|
3397
|
+
}
|
|
3398
|
+
}
|
|
3399
|
+
}
|
|
3400
|
+
};
|
|
3401
|
+
|
|
3402
|
+
// src/ipc-telemetry.ts
|
|
3403
|
+
var import_node_net = __toESM(require("net"), 1);
|
|
3404
|
+
var import_node_fs2 = __toESM(require("fs"), 1);
|
|
3405
|
+
var import_node_path = __toESM(require("path"), 1);
|
|
3406
|
+
function resolveIpcSocketPath(id = process.pid) {
|
|
3407
|
+
if (process.platform === "win32") {
|
|
3408
|
+
return `\\\\.\\pipe\\tricache-${id}`;
|
|
3409
|
+
}
|
|
3410
|
+
const dir = process.env.TMPDIR || "/tmp";
|
|
3411
|
+
return import_node_path.default.join(dir, `tricache-${id}.sock`);
|
|
3412
|
+
}
|
|
3413
|
+
var IpcTelemetryServer = class {
|
|
3414
|
+
constructor(cache, customSocketPath) {
|
|
3415
|
+
this.cache = cache;
|
|
3416
|
+
this.socketPath = customSocketPath || resolveIpcSocketPath();
|
|
3417
|
+
}
|
|
3418
|
+
cache;
|
|
3419
|
+
server = null;
|
|
3420
|
+
socketPath;
|
|
3421
|
+
_closed = false;
|
|
3422
|
+
_exitHandler = null;
|
|
3423
|
+
_sigintHandler = null;
|
|
3424
|
+
_sigtermHandler = null;
|
|
3425
|
+
/**
|
|
3426
|
+
* Start listening on the IPC socket / pipe.
|
|
3427
|
+
*/
|
|
3428
|
+
async start() {
|
|
3429
|
+
if (this.server && this.server.listening) return;
|
|
3430
|
+
if (process.platform !== "win32" && import_node_fs2.default.existsSync(this.socketPath)) {
|
|
3431
|
+
await new Promise((resolve) => {
|
|
3432
|
+
const testSocket = import_node_net.default.createConnection(this.socketPath);
|
|
3433
|
+
testSocket.once("connect", () => {
|
|
3434
|
+
testSocket.destroy();
|
|
3435
|
+
resolve();
|
|
3436
|
+
});
|
|
3437
|
+
testSocket.once("error", () => {
|
|
3438
|
+
testSocket.destroy();
|
|
3439
|
+
try {
|
|
3440
|
+
import_node_fs2.default.unlinkSync(this.socketPath);
|
|
3441
|
+
} catch {
|
|
3442
|
+
}
|
|
3443
|
+
resolve();
|
|
3444
|
+
});
|
|
3445
|
+
});
|
|
3446
|
+
}
|
|
3447
|
+
this.server = import_node_net.default.createServer((socket) => {
|
|
3448
|
+
let buffer = "";
|
|
3449
|
+
socket.on("data", (chunk) => {
|
|
3450
|
+
buffer += chunk.toString("utf8");
|
|
3451
|
+
let newlineIndex;
|
|
3452
|
+
while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
|
|
3453
|
+
const line = buffer.slice(0, newlineIndex).trim();
|
|
3454
|
+
buffer = buffer.slice(newlineIndex + 1);
|
|
3455
|
+
if (!line) continue;
|
|
3456
|
+
setImmediate(() => {
|
|
3457
|
+
if (socket.destroyed) return;
|
|
3458
|
+
try {
|
|
3459
|
+
let cmd = line;
|
|
3460
|
+
try {
|
|
3461
|
+
const parsed = JSON.parse(line);
|
|
3462
|
+
if (parsed && typeof parsed.cmd === "string") {
|
|
3463
|
+
cmd = parsed.cmd;
|
|
3464
|
+
}
|
|
3465
|
+
} catch {
|
|
3466
|
+
}
|
|
3467
|
+
if (cmd === "PING") {
|
|
3468
|
+
socket.write(JSON.stringify({ pong: true, timestamp: Date.now() }) + "\n");
|
|
3469
|
+
return;
|
|
3470
|
+
}
|
|
3471
|
+
if (cmd === "GET_METRICS" || cmd === "INSPECT") {
|
|
3472
|
+
const payload = this.getSnapshot();
|
|
3473
|
+
const serialized = JSON.stringify(payload) + "\n";
|
|
3474
|
+
socket.write(serialized);
|
|
3475
|
+
return;
|
|
3476
|
+
}
|
|
3477
|
+
socket.write(JSON.stringify({ error: `Unknown command: ${cmd}` }) + "\n");
|
|
3478
|
+
} catch (err) {
|
|
3479
|
+
if (!socket.destroyed) {
|
|
3480
|
+
socket.write(JSON.stringify({ error: err.message }) + "\n");
|
|
3481
|
+
}
|
|
3482
|
+
}
|
|
3483
|
+
});
|
|
3484
|
+
}
|
|
3485
|
+
});
|
|
3486
|
+
socket.on("error", () => {
|
|
3487
|
+
});
|
|
3488
|
+
});
|
|
3489
|
+
await new Promise((resolve, reject) => {
|
|
3490
|
+
this.server.once("error", reject);
|
|
3491
|
+
this.server.listen(this.socketPath, () => {
|
|
3492
|
+
this.server.removeListener("error", reject);
|
|
3493
|
+
resolve();
|
|
3494
|
+
});
|
|
3495
|
+
});
|
|
3496
|
+
this._exitHandler = () => this._unlinkSocket();
|
|
3497
|
+
this._sigintHandler = () => {
|
|
3498
|
+
this._unlinkSocket();
|
|
3499
|
+
process.exit(0);
|
|
3500
|
+
};
|
|
3501
|
+
this._sigtermHandler = () => {
|
|
3502
|
+
this._unlinkSocket();
|
|
3503
|
+
process.exit(0);
|
|
3504
|
+
};
|
|
3505
|
+
process.once("exit", this._exitHandler);
|
|
3506
|
+
process.once("SIGINT", this._sigintHandler);
|
|
3507
|
+
process.once("SIGTERM", this._sigtermHandler);
|
|
3508
|
+
}
|
|
3509
|
+
/**
|
|
3510
|
+
* Build a complete telemetry snapshot from the underlying cache provider.
|
|
3511
|
+
*/
|
|
3512
|
+
getSnapshot() {
|
|
3513
|
+
const metrics = this.cache.metrics();
|
|
3514
|
+
const stats = typeof this.cache.stats === "function" ? this.cache.stats() : void 0;
|
|
3515
|
+
const hotKeys = typeof this.cache.hotKeys === "function" ? this.cache.hotKeys(10) : void 0;
|
|
3516
|
+
const health = typeof this.cache.health === "function" ? this.cache.health() : void 0;
|
|
3517
|
+
const l1MaxBytes = this.cache.options?.l1MaxBytes ?? metrics.l1?.maxBytes;
|
|
3518
|
+
return {
|
|
3519
|
+
pid: process.pid,
|
|
3520
|
+
uptimeMs: metrics.uptimeMs,
|
|
3521
|
+
timestamp: Date.now(),
|
|
3522
|
+
namespace: this.cache.options?.namespace || metrics.namespace,
|
|
3523
|
+
l1MaxBytes,
|
|
3524
|
+
metrics,
|
|
3525
|
+
stats,
|
|
3526
|
+
hotKeys,
|
|
3527
|
+
health
|
|
3528
|
+
};
|
|
3529
|
+
}
|
|
3530
|
+
_unlinkSocket() {
|
|
3531
|
+
if (this._closed) return;
|
|
3532
|
+
this._closed = true;
|
|
3533
|
+
try {
|
|
3534
|
+
this.server?.close();
|
|
3535
|
+
} catch {
|
|
3536
|
+
}
|
|
3537
|
+
if (process.platform !== "win32") {
|
|
3538
|
+
try {
|
|
3539
|
+
if (import_node_fs2.default.existsSync(this.socketPath)) {
|
|
3540
|
+
import_node_fs2.default.unlinkSync(this.socketPath);
|
|
3541
|
+
}
|
|
3542
|
+
} catch {
|
|
3543
|
+
}
|
|
3544
|
+
}
|
|
3545
|
+
}
|
|
3546
|
+
/**
|
|
3547
|
+
* Gracefully close the IPC telemetry server and clean up handlers and sockets.
|
|
3548
|
+
*/
|
|
3549
|
+
async close() {
|
|
3550
|
+
if (this._exitHandler) {
|
|
3551
|
+
process.removeListener("exit", this._exitHandler);
|
|
3552
|
+
this._exitHandler = null;
|
|
3553
|
+
}
|
|
3554
|
+
if (this._sigintHandler) {
|
|
3555
|
+
process.removeListener("SIGINT", this._sigintHandler);
|
|
3556
|
+
this._sigintHandler = null;
|
|
3557
|
+
}
|
|
3558
|
+
if (this._sigtermHandler) {
|
|
3559
|
+
process.removeListener("SIGTERM", this._sigtermHandler);
|
|
3560
|
+
this._sigtermHandler = null;
|
|
3561
|
+
}
|
|
3562
|
+
this._unlinkSocket();
|
|
3563
|
+
return new Promise((resolve) => {
|
|
3564
|
+
if (!this.server || !this.server.listening) {
|
|
3565
|
+
resolve();
|
|
3566
|
+
return;
|
|
3567
|
+
}
|
|
3568
|
+
this.server.close(() => resolve());
|
|
3569
|
+
});
|
|
3570
|
+
}
|
|
3571
|
+
get isListening() {
|
|
3572
|
+
return Boolean(this.server && this.server.listening);
|
|
3573
|
+
}
|
|
3574
|
+
};
|
|
3575
|
+
var IpcTelemetryClient = class {
|
|
3576
|
+
socketPath;
|
|
3577
|
+
constructor(socketPath) {
|
|
3578
|
+
this.socketPath = socketPath || resolveIpcSocketPath();
|
|
3579
|
+
}
|
|
3580
|
+
/**
|
|
3581
|
+
* Fetch a live metrics snapshot from the IPC server.
|
|
3582
|
+
*/
|
|
3583
|
+
async getMetrics(timeoutMs = 3e3) {
|
|
3584
|
+
return new Promise((resolve, reject) => {
|
|
3585
|
+
const socket = import_node_net.default.createConnection(this.socketPath);
|
|
3586
|
+
let buffer = "";
|
|
3587
|
+
let timer = setTimeout(() => {
|
|
3588
|
+
socket.destroy();
|
|
3589
|
+
reject(new Error(`IPC connection timeout (${timeoutMs}ms) to ${this.socketPath}`));
|
|
3590
|
+
}, timeoutMs);
|
|
3591
|
+
socket.once("connect", () => {
|
|
3592
|
+
socket.write("GET_METRICS\n");
|
|
3593
|
+
});
|
|
3594
|
+
socket.on("data", (chunk) => {
|
|
3595
|
+
buffer += chunk.toString("utf8");
|
|
3596
|
+
const newlineIdx = buffer.indexOf("\n");
|
|
3597
|
+
if (newlineIdx !== -1) {
|
|
3598
|
+
if (timer) {
|
|
3599
|
+
clearTimeout(timer);
|
|
3600
|
+
timer = null;
|
|
3601
|
+
}
|
|
3602
|
+
const line = buffer.slice(0, newlineIdx).trim();
|
|
3603
|
+
socket.end();
|
|
3604
|
+
try {
|
|
3605
|
+
const data = JSON.parse(line);
|
|
3606
|
+
if (data.error) {
|
|
3607
|
+
reject(new Error(data.error));
|
|
3608
|
+
} else {
|
|
3609
|
+
resolve(data);
|
|
3610
|
+
}
|
|
3611
|
+
} catch (e) {
|
|
3612
|
+
reject(new Error(`Failed to parse IPC payload: ${e.message}`));
|
|
3613
|
+
}
|
|
3614
|
+
}
|
|
3615
|
+
});
|
|
3616
|
+
socket.once("error", (err) => {
|
|
3617
|
+
if (timer) {
|
|
3618
|
+
clearTimeout(timer);
|
|
3619
|
+
timer = null;
|
|
3620
|
+
}
|
|
3621
|
+
reject(err);
|
|
3622
|
+
});
|
|
3623
|
+
});
|
|
3624
|
+
}
|
|
3625
|
+
/**
|
|
3626
|
+
* Send a ping over the IPC bridge and measure round-trip latency.
|
|
3627
|
+
*/
|
|
3628
|
+
async ping(timeoutMs = 1e3) {
|
|
3629
|
+
const start = Date.now();
|
|
3630
|
+
return new Promise((resolve, reject) => {
|
|
3631
|
+
const socket = import_node_net.default.createConnection(this.socketPath);
|
|
3632
|
+
let timer = setTimeout(() => {
|
|
3633
|
+
socket.destroy();
|
|
3634
|
+
reject(new Error(`IPC ping timeout (${timeoutMs}ms)`));
|
|
3635
|
+
}, timeoutMs);
|
|
3636
|
+
socket.once("connect", () => {
|
|
3637
|
+
socket.write("PING\n");
|
|
3638
|
+
});
|
|
3639
|
+
socket.on("data", () => {
|
|
3640
|
+
if (timer) {
|
|
3641
|
+
clearTimeout(timer);
|
|
3642
|
+
timer = null;
|
|
3643
|
+
}
|
|
3644
|
+
socket.end();
|
|
3645
|
+
resolve(Date.now() - start);
|
|
3646
|
+
});
|
|
3647
|
+
socket.once("error", (err) => {
|
|
3648
|
+
if (timer) {
|
|
3649
|
+
clearTimeout(timer);
|
|
3650
|
+
timer = null;
|
|
3651
|
+
}
|
|
3652
|
+
reject(err);
|
|
3653
|
+
});
|
|
3654
|
+
});
|
|
3655
|
+
}
|
|
3656
|
+
};
|
|
3657
|
+
async function findActiveSockets() {
|
|
3658
|
+
const active = [];
|
|
3659
|
+
if (process.platform === "win32") {
|
|
3660
|
+
const currentPipe = resolveIpcSocketPath(process.pid);
|
|
3661
|
+
const client = new IpcTelemetryClient(currentPipe);
|
|
3662
|
+
try {
|
|
3663
|
+
await client.ping(100);
|
|
3664
|
+
active.push(currentPipe);
|
|
3665
|
+
} catch {
|
|
3666
|
+
}
|
|
3667
|
+
return active;
|
|
3668
|
+
}
|
|
3669
|
+
const dir = process.env.TMPDIR || "/tmp";
|
|
3670
|
+
try {
|
|
3671
|
+
if (!import_node_fs2.default.existsSync(dir)) return active;
|
|
3672
|
+
const entries = import_node_fs2.default.readdirSync(dir);
|
|
3673
|
+
const candidates = entries.filter((name) => name.startsWith("tricache-") && name.endsWith(".sock")).map((name) => import_node_path.default.join(dir, name));
|
|
3674
|
+
await Promise.all(
|
|
3675
|
+
candidates.map(async (sockPath) => {
|
|
3676
|
+
const client = new IpcTelemetryClient(sockPath);
|
|
3677
|
+
try {
|
|
3678
|
+
await client.ping(100);
|
|
3679
|
+
active.push(sockPath);
|
|
3680
|
+
} catch {
|
|
3681
|
+
}
|
|
3682
|
+
})
|
|
3683
|
+
);
|
|
3684
|
+
} catch {
|
|
3685
|
+
}
|
|
3686
|
+
return active;
|
|
3687
|
+
}
|
|
3688
|
+
function renderProgressBar(ratio, width = 18) {
|
|
3689
|
+
const clamped = Math.max(0, Math.min(1, isNaN(ratio) ? 0 : ratio));
|
|
3690
|
+
const filled = Math.round(clamped * width);
|
|
3691
|
+
const empty = width - filled;
|
|
3692
|
+
return "\u2588".repeat(filled) + "\u2591".repeat(empty);
|
|
3693
|
+
}
|
|
3694
|
+
function formatBytes(bytes) {
|
|
3695
|
+
if (!bytes || isNaN(bytes) || bytes < 0) return "0 B";
|
|
3696
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
3697
|
+
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
|
3698
|
+
if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
3699
|
+
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
|
|
3700
|
+
}
|
|
3701
|
+
function formatNumber(n) {
|
|
3702
|
+
return (n ?? 0).toLocaleString();
|
|
3703
|
+
}
|
|
3704
|
+
function formatDuration(ms) {
|
|
3705
|
+
if (ms < 1e3) return `${ms}ms`;
|
|
3706
|
+
const s = Math.floor(ms / 1e3);
|
|
3707
|
+
if (s < 60) return `${s}s`;
|
|
3708
|
+
const m = Math.floor(s / 60);
|
|
3709
|
+
const remS = s % 60;
|
|
3710
|
+
if (m < 60) return `${m}m ${remS}s`;
|
|
3711
|
+
const h = Math.floor(m / 60);
|
|
3712
|
+
const remM = m % 60;
|
|
3713
|
+
return `${h}h ${remM}m`;
|
|
3714
|
+
}
|
|
3715
|
+
function renderTopDashboard(payload) {
|
|
3716
|
+
const m = payload.metrics;
|
|
3717
|
+
const gets = m.gets;
|
|
3718
|
+
const l1Max = payload.l1MaxBytes || 200 * 1024 * 1024;
|
|
3719
|
+
const l1Used = m.l1.sizeBytes;
|
|
3720
|
+
const l1Pct = l1Max > 0 ? l1Used / l1Max : 0;
|
|
3721
|
+
const uptime = formatDuration(payload.uptimeMs);
|
|
3722
|
+
const ns = payload.namespace || "(default)";
|
|
3723
|
+
const pct = (r) => `${((r || 0) * 100).toFixed(1)}%`;
|
|
3724
|
+
const lines = [];
|
|
3725
|
+
lines.push("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557");
|
|
3726
|
+
lines.push(`\u2551 TriCache Monitor [PID: ${String(payload.pid).padEnd(6)}] Uptime: ${uptime.padEnd(8)} Namespace: ${ns.padEnd(16)}\u2551`);
|
|
3727
|
+
lines.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563");
|
|
3728
|
+
lines.push(`\u2551 Hit Ratios & Tier Breakdown (Total Gets: ${formatNumber(gets.total).padEnd(12)}) \u2551`);
|
|
3729
|
+
lines.push(`\u2551 L1 (RAM): [${renderProgressBar(gets.l1HitRate)}] ${pct(gets.l1HitRate).padStart(6)} (${formatNumber(gets.l1Hits).padStart(8)} hits) \u2551`);
|
|
3730
|
+
lines.push(`\u2551 L1.5(Disk): [${renderProgressBar(gets.diskHitRate)}] ${pct(gets.diskHitRate).padStart(6)} (${formatNumber(gets.diskHits).padStart(8)} hits) \u2551`);
|
|
3731
|
+
lines.push(`\u2551 L2 (Redis): [${renderProgressBar(gets.l2HitRate)}] ${pct(gets.l2HitRate).padStart(6)} (${formatNumber(gets.l2Hits).padStart(8)} hits) \u2551`);
|
|
3732
|
+
lines.push(`\u2551 Misses: [${renderProgressBar(gets.fetchRate)}] ${pct(gets.fetchRate).padStart(6)} (${formatNumber(gets.fetches).padStart(8)} fetches) \u2551`);
|
|
3733
|
+
lines.push(`\u2551 Stampedes Saved: ${formatNumber(gets.stampedePrevented).padEnd(8)} coalesced concurrent requests \u2551`);
|
|
3734
|
+
lines.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563");
|
|
3735
|
+
lines.push(`\u2551 Memory & Storage Headroom \u2551`);
|
|
3736
|
+
lines.push(`\u2551 L1 Memory: [${renderProgressBar(l1Pct)}] ${formatBytes(l1Used).padStart(8)} / ${formatBytes(l1Max).padEnd(8)} (${formatNumber(m.l1.entries).padStart(6)} entries) \u2551`);
|
|
3737
|
+
const diskFiles = m.disk?.files ?? 0;
|
|
3738
|
+
const diskKB = m.disk?.sizeKB ?? 0;
|
|
3739
|
+
const diskMaxKB = m.disk?.maxKB ?? 0;
|
|
3740
|
+
lines.push(`\u2551 Disk Spill: ${formatBytes(diskKB * 1024).padStart(8)} / ${formatBytes(diskMaxKB * 1024).padEnd(8)} (${formatNumber(diskFiles).padStart(6)} files) \u2551`);
|
|
3741
|
+
lines.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563");
|
|
3742
|
+
lines.push(`\u2551 Protection & Health Diagnostics \u2551`);
|
|
3743
|
+
const watchdog = m.disk?.latencyWatchdog;
|
|
3744
|
+
const bypassStage = watchdog ? `Stage ${watchdog.bypassStage} (${watchdog.bypassActive ? "ACTIVE" : "Normal"})` : "Stage 0 (Normal)";
|
|
3745
|
+
const cbState = m.l2CircuitBreaker?.state || "closed";
|
|
3746
|
+
lines.push(`\u2551 Watchdog: ${bypassStage.padEnd(20)} L2 Circuit Breaker: ${cbState.padEnd(20)}\u2551`);
|
|
3747
|
+
if (watchdog) {
|
|
3748
|
+
const diskP95 = `${watchdog.diskP95Ms.toFixed(2)}ms`;
|
|
3749
|
+
const redisP95 = `${watchdog.redisP95Ms.toFixed(2)}ms`;
|
|
3750
|
+
lines.push(`\u2551 Disk p95: ${diskP95.padEnd(10)} Redis p95: ${redisP95.padEnd(10)} Bypassed: ${formatNumber(watchdog.bypassedTotal).padEnd(16)}\u2551`);
|
|
3751
|
+
}
|
|
3752
|
+
const oomEvict = m.oom?.evictions ?? 0;
|
|
3753
|
+
lines.push(`\u2551 OOM Evictions: ${formatNumber(oomEvict).padEnd(6)} SWR Revalidations: ${formatNumber(m.revalidations?.total ?? 0).padEnd(14)} \u2551`);
|
|
3754
|
+
lines.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563");
|
|
3755
|
+
lines.push(`\u2551 \u{1F525} Top Hot Keys (Count-Min Sketch) \u2551`);
|
|
3756
|
+
if (!payload.hotKeys || payload.hotKeys.length === 0) {
|
|
3757
|
+
lines.push("\u2551 (no hot keys recorded yet) \u2551");
|
|
3758
|
+
} else {
|
|
3759
|
+
payload.hotKeys.slice(0, 5).forEach(({ key, hits, sizeBytes }, idx) => {
|
|
3760
|
+
const displayKey = key.length > 34 ? `${key.slice(0, 31)}...` : key;
|
|
3761
|
+
const hitStr = `${formatNumber(hits)} hits`;
|
|
3762
|
+
const sizeStr = formatBytes(sizeBytes);
|
|
3763
|
+
const row = ` ${idx + 1}. ${displayKey.padEnd(36)} ${hitStr.padStart(14)} (${sizeStr})`;
|
|
3764
|
+
lines.push(`\u2551${row.padEnd(86)}\u2551`);
|
|
3765
|
+
});
|
|
3766
|
+
}
|
|
3767
|
+
lines.push("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D");
|
|
3768
|
+
return lines.join("\n");
|
|
3769
|
+
}
|
|
3770
|
+
|
|
3771
|
+
// src/cache-service.ts
|
|
3772
|
+
var LUA_COMPARE_AND_DELETE = `
|
|
3773
|
+
local currentTs = redis.call('HGET', KEYS[1], 't')
|
|
3774
|
+
if currentTs and currentTs == ARGV[1] then
|
|
3775
|
+
return redis.call('DEL', KEYS[1])
|
|
3776
|
+
end
|
|
3777
|
+
return 0
|
|
3778
|
+
`;
|
|
3779
|
+
var SNAPSHOT_VERSION = 1;
|
|
3780
|
+
var DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
|
|
3781
|
+
var INDEFINITE_TTL_SECONDS = 31536e3;
|
|
3782
|
+
var SNAPSHOT_MAX_FILE_BYTES = 220 * 1024 * 1024;
|
|
3783
|
+
var DEFAULT_CATEGORY_LIMITS = {
|
|
3784
|
+
"default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
|
|
3785
|
+
};
|
|
3786
|
+
var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
|
|
3787
|
+
var DEFAULT_COUNTER_TTL_SECONDS = 60;
|
|
3788
|
+
var GLOB_REGEX_CACHE_MAX = 256;
|
|
3789
|
+
var globRegexCache = /* @__PURE__ */ new Map();
|
|
3790
|
+
function getGlobRegex(pattern) {
|
|
3791
|
+
let re = globRegexCache.get(pattern);
|
|
3792
|
+
if (re) {
|
|
3793
|
+
globRegexCache.delete(pattern);
|
|
3794
|
+
globRegexCache.set(pattern, re);
|
|
3795
|
+
return re;
|
|
3796
|
+
}
|
|
3797
|
+
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*+/g, ".*");
|
|
3798
|
+
re = new RegExp("^" + escaped + "$");
|
|
3799
|
+
if (globRegexCache.size >= GLOB_REGEX_CACHE_MAX) {
|
|
3800
|
+
const oldestKey = globRegexCache.keys().next().value;
|
|
3801
|
+
if (oldestKey !== void 0) globRegexCache.delete(oldestKey);
|
|
3802
|
+
}
|
|
3803
|
+
globRegexCache.set(pattern, re);
|
|
3804
|
+
return re;
|
|
3805
|
+
}
|
|
3806
|
+
var L2CircuitBreaker = class {
|
|
3807
|
+
constructor(threshold, cooldownMs) {
|
|
3808
|
+
this.threshold = threshold;
|
|
3809
|
+
this.cooldownMs = cooldownMs;
|
|
3810
|
+
}
|
|
3811
|
+
threshold;
|
|
3812
|
+
cooldownMs;
|
|
3813
|
+
state = 0 /* CLOSED */;
|
|
3814
|
+
failures = 0;
|
|
3815
|
+
openedAt = performance.now();
|
|
3816
|
+
/** True while the single permitted HALF_OPEN probe is in flight. */
|
|
3817
|
+
probing = false;
|
|
3818
|
+
/**
|
|
3819
|
+
* Call before each Redis attempt. Returns false when the circuit is open.
|
|
3820
|
+
* In HALF_OPEN, only ONE probe is permitted at a time — concurrent callers
|
|
3821
|
+
* arriving while a probe is outstanding are rejected (return false) so a
|
|
3822
|
+
* recovering Redis node is not stampeded.
|
|
3823
|
+
*/
|
|
3824
|
+
isAllowed() {
|
|
2410
3825
|
if (this.state === 0 /* CLOSED */) return true;
|
|
2411
3826
|
if (this.state === 2 /* HALF_OPEN */) {
|
|
2412
3827
|
if (this.probing) return false;
|
|
2413
3828
|
this.probing = true;
|
|
2414
3829
|
return true;
|
|
2415
3830
|
}
|
|
2416
|
-
|
|
3831
|
+
const now = this.openedAt > 1e12 ? Date.now() : performance.now();
|
|
3832
|
+
if (now - this.openedAt >= this.cooldownMs) {
|
|
2417
3833
|
this.state = 2 /* HALF_OPEN */;
|
|
2418
3834
|
this.probing = true;
|
|
2419
3835
|
return true;
|
|
@@ -2432,7 +3848,7 @@ var L2CircuitBreaker = class {
|
|
|
2432
3848
|
this.probing = false;
|
|
2433
3849
|
if (this.state === 2 /* HALF_OPEN */ || this.failures >= this.threshold) {
|
|
2434
3850
|
this.state = 1 /* OPEN */;
|
|
2435
|
-
this.openedAt =
|
|
3851
|
+
this.openedAt = performance.now();
|
|
2436
3852
|
this.failures = 0;
|
|
2437
3853
|
}
|
|
2438
3854
|
}
|
|
@@ -2549,9 +3965,86 @@ function detectServerlessRuntime() {
|
|
|
2549
3965
|
if (process.env["VERCEL"]) return "Vercel";
|
|
2550
3966
|
return null;
|
|
2551
3967
|
}
|
|
3968
|
+
var ProcessTerminationBus = class {
|
|
3969
|
+
static instances = /* @__PURE__ */ new Set();
|
|
3970
|
+
static registered = false;
|
|
3971
|
+
static sigtermHandler = null;
|
|
3972
|
+
static sigintHandler = null;
|
|
3973
|
+
static register(instance) {
|
|
3974
|
+
this.instances.add(instance);
|
|
3975
|
+
if (!this.registered) {
|
|
3976
|
+
this.registered = true;
|
|
3977
|
+
this.sigtermHandler = () => {
|
|
3978
|
+
for (const inst of this.instances) {
|
|
3979
|
+
try {
|
|
3980
|
+
inst._triggerShutdown();
|
|
3981
|
+
} catch {
|
|
3982
|
+
}
|
|
3983
|
+
}
|
|
3984
|
+
};
|
|
3985
|
+
this.sigintHandler = () => {
|
|
3986
|
+
for (const inst of this.instances) {
|
|
3987
|
+
try {
|
|
3988
|
+
inst._triggerShutdown();
|
|
3989
|
+
} catch {
|
|
3990
|
+
}
|
|
3991
|
+
}
|
|
3992
|
+
};
|
|
3993
|
+
process.on("SIGTERM", this.sigtermHandler);
|
|
3994
|
+
process.on("SIGINT", this.sigintHandler);
|
|
3995
|
+
}
|
|
3996
|
+
}
|
|
3997
|
+
static unregister(instance) {
|
|
3998
|
+
this.instances.delete(instance);
|
|
3999
|
+
if (this.instances.size === 0 && this.registered) {
|
|
4000
|
+
if (this.sigtermHandler) process.removeListener("SIGTERM", this.sigtermHandler);
|
|
4001
|
+
if (this.sigintHandler) process.removeListener("SIGINT", this.sigintHandler);
|
|
4002
|
+
this.sigtermHandler = null;
|
|
4003
|
+
this.sigintHandler = null;
|
|
4004
|
+
this.registered = false;
|
|
4005
|
+
}
|
|
4006
|
+
}
|
|
4007
|
+
/**
|
|
4008
|
+
* Flushes snapshots across all active registered cache instances concurrently.
|
|
4009
|
+
* Awaits both local disk and remote cloud snapshot uploads with timeout protection.
|
|
4010
|
+
*
|
|
4011
|
+
* @param timeoutMs Timeout in milliseconds per instance before aborting slow flushes. Default: 8000ms.
|
|
4012
|
+
*/
|
|
4013
|
+
static async flushAll(timeoutMs = 8e3) {
|
|
4014
|
+
if (this.instances.size === 0) return;
|
|
4015
|
+
const tasks = Array.from(this.instances).map((inst) => inst.flushSnapshotOnShutdown(timeoutMs));
|
|
4016
|
+
await Promise.allSettled(tasks);
|
|
4017
|
+
}
|
|
4018
|
+
/** For testing diagnostics and assertions */
|
|
4019
|
+
static get size() {
|
|
4020
|
+
return this.instances.size;
|
|
4021
|
+
}
|
|
4022
|
+
static get isRegistered() {
|
|
4023
|
+
return this.registered;
|
|
4024
|
+
}
|
|
4025
|
+
};
|
|
4026
|
+
function isPlainObject(item) {
|
|
4027
|
+
return typeof item === "object" && item !== null && item.constructor === Object;
|
|
4028
|
+
}
|
|
4029
|
+
function deepMergeOptions(base, overrides) {
|
|
4030
|
+
if (!overrides) return { ...base };
|
|
4031
|
+
const output = { ...base };
|
|
4032
|
+
for (const key of Object.keys(overrides)) {
|
|
4033
|
+
const sourceVal = overrides[key];
|
|
4034
|
+
if (sourceVal === void 0) continue;
|
|
4035
|
+
const targetVal = output[key];
|
|
4036
|
+
if (isPlainObject(targetVal) && isPlainObject(sourceVal)) {
|
|
4037
|
+
output[key] = deepMergeOptions(targetVal, sourceVal);
|
|
4038
|
+
} else {
|
|
4039
|
+
output[key] = sourceVal;
|
|
4040
|
+
}
|
|
4041
|
+
}
|
|
4042
|
+
return output;
|
|
4043
|
+
}
|
|
2552
4044
|
var CacheService = class _CacheService {
|
|
2553
4045
|
logger;
|
|
2554
4046
|
enc;
|
|
4047
|
+
codec;
|
|
2555
4048
|
l1;
|
|
2556
4049
|
disk;
|
|
2557
4050
|
/** When true, all disk-tier and snapshot operations are skipped. */
|
|
@@ -2563,6 +4056,8 @@ var CacheService = class _CacheService {
|
|
|
2563
4056
|
_namespace;
|
|
2564
4057
|
/** Pre-computed once — disableRedis and redisHost never change after construction. */
|
|
2565
4058
|
_redisDisabled;
|
|
4059
|
+
watchdog;
|
|
4060
|
+
pipeliner = null;
|
|
2566
4061
|
inflight = /* @__PURE__ */ new Map();
|
|
2567
4062
|
revalidating = /* @__PURE__ */ new Set();
|
|
2568
4063
|
_l1Counters = /* @__PURE__ */ new Map();
|
|
@@ -2588,6 +4083,7 @@ var CacheService = class _CacheService {
|
|
|
2588
4083
|
diskJanitorInterval = null;
|
|
2589
4084
|
oomInterval = null;
|
|
2590
4085
|
metricsInterval = null;
|
|
4086
|
+
remoteSnapshotInterval = null;
|
|
2591
4087
|
_shutdownHandler = null;
|
|
2592
4088
|
latencyTracker = null;
|
|
2593
4089
|
instanceId;
|
|
@@ -2597,8 +4093,11 @@ var CacheService = class _CacheService {
|
|
|
2597
4093
|
streamClient = null;
|
|
2598
4094
|
_lastStreamId = "$";
|
|
2599
4095
|
_destroyed = false;
|
|
4096
|
+
_ipcServer;
|
|
2600
4097
|
/** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
|
|
2601
4098
|
_subDisconnectedAt = null;
|
|
4099
|
+
/** Deduplication ring buffer for incoming and outgoing cross-region invalidations (loop prevention) */
|
|
4100
|
+
_seenCrossRegionEvents = /* @__PURE__ */ new Map();
|
|
2602
4101
|
counters = {
|
|
2603
4102
|
gets: 0,
|
|
2604
4103
|
l1Hits: 0,
|
|
@@ -2623,7 +4122,16 @@ var CacheService = class _CacheService {
|
|
|
2623
4122
|
singletonDivergences: 0,
|
|
2624
4123
|
startedAt: Date.now(),
|
|
2625
4124
|
bloomChecks: 0,
|
|
2626
|
-
bloomFalsePositives: 0
|
|
4125
|
+
bloomFalsePositives: 0,
|
|
4126
|
+
remoteSnapshotUploads: 0,
|
|
4127
|
+
remoteSnapshotDownloads: 0,
|
|
4128
|
+
remoteSnapshotErrors: 0,
|
|
4129
|
+
remoteSnapshotLastUploadedAt: null,
|
|
4130
|
+
remoteSnapshotLastDownloadedAt: null,
|
|
4131
|
+
crossRegionSent: 0,
|
|
4132
|
+
crossRegionReceived: 0,
|
|
4133
|
+
crossRegionDeduplicated: 0,
|
|
4134
|
+
crossRegionErrors: 0
|
|
2627
4135
|
};
|
|
2628
4136
|
/** One-time guard so the in-process increment() fallback warning fires only once. */
|
|
2629
4137
|
_incrementFallbackWarned = false;
|
|
@@ -2646,16 +4154,14 @@ var CacheService = class _CacheService {
|
|
|
2646
4154
|
this.opts = {
|
|
2647
4155
|
namespace: ns,
|
|
2648
4156
|
logger,
|
|
2649
|
-
l1MaxBytes: options.l1MaxBytes ??
|
|
4157
|
+
l1MaxBytes: options.l1MaxBytes ?? resolveAutonomousL1MaxBytes(),
|
|
2650
4158
|
l1MaxEntries: options.l1MaxEntries ?? 2e3,
|
|
2651
4159
|
categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...options.categoryLimits },
|
|
2652
4160
|
forbiddenSnapshotPrefixes: forbiddenPrefixes,
|
|
2653
4161
|
// Namespace-isolated defaults: separate dir / snapshot per namespace so
|
|
2654
4162
|
// two instances with different namespaces never share cache files.
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
ns ? `tricache-disk-${ns}` : "tricache-disk"
|
|
2658
|
-
),
|
|
4163
|
+
// Automatically probes /dev/shm tmpfs on Linux (>=256MB capacity and >=128MB free) for off-heap RAM speed.
|
|
4164
|
+
diskCacheDir: options.diskCacheDir ?? resolveDefaultDiskDir(ns, logger).dir,
|
|
2659
4165
|
diskMaxBytes: options.diskMaxBytes ?? 500 * 1024 * 1024,
|
|
2660
4166
|
diskEntryMaxBytes: options.diskEntryMaxBytes ?? 10 * 1024 * 1024,
|
|
2661
4167
|
redisHost: options.redisHost ?? process.env.REDIS_HOST ?? "",
|
|
@@ -2663,14 +4169,14 @@ var CacheService = class _CacheService {
|
|
|
2663
4169
|
redisTls: options.redisTls ?? process.env.NODE_ENV === "production",
|
|
2664
4170
|
disableRedis: options.disableRedis ?? (() => {
|
|
2665
4171
|
const explicitConfig = Boolean(
|
|
2666
|
-
options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
|
|
4172
|
+
options.redisClient || options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
|
|
2667
4173
|
);
|
|
2668
4174
|
return !explicitConfig && process.env.NODE_ENV !== "production";
|
|
2669
4175
|
})(),
|
|
2670
4176
|
encryptionKey: encKeyRaw,
|
|
2671
4177
|
encryptionMode: options.encryptionMode,
|
|
2672
4178
|
snapshotPath: options.snapshotPath ?? import_path3.default.join(
|
|
2673
|
-
|
|
4179
|
+
import_os3.default.tmpdir(),
|
|
2674
4180
|
ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
|
|
2675
4181
|
),
|
|
2676
4182
|
snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
|
|
@@ -2718,8 +4224,35 @@ var CacheService = class _CacheService {
|
|
|
2718
4224
|
backplaneMode: options.backplaneMode ?? "pubsub",
|
|
2719
4225
|
backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
|
|
2720
4226
|
backplaneStreamBlockMs: options.backplaneStreamBlockMs ?? 2e3,
|
|
2721
|
-
backplaneStreamKey: options.backplaneStreamKey
|
|
4227
|
+
backplaneStreamKey: options.backplaneStreamKey,
|
|
4228
|
+
serializeToJSON: options.serializeToJSON ?? true,
|
|
4229
|
+
remoteSnapshot: options.remoteSnapshot,
|
|
4230
|
+
crossRegion: options.crossRegion,
|
|
4231
|
+
redisClient: options.redisClient,
|
|
4232
|
+
redisSubClient: options.redisSubClient,
|
|
4233
|
+
diskMaxConcurrentWrites: options.diskMaxConcurrentWrites,
|
|
4234
|
+
diskMaxPendingWrites: options.diskMaxPendingWrites,
|
|
4235
|
+
diskWriteTimeoutMs: options.diskWriteTimeoutMs,
|
|
4236
|
+
diskCircuitBreakerThreshold: options.diskCircuitBreakerThreshold,
|
|
4237
|
+
diskCircuitBreakerCooldownMs: options.diskCircuitBreakerCooldownMs,
|
|
4238
|
+
redisCommandTimeoutMs: options.redisCommandTimeoutMs,
|
|
4239
|
+
clockSkewToleranceMs: options.clockSkewToleranceMs ?? 250,
|
|
4240
|
+
l1AdmissionPolicy: options.l1AdmissionPolicy,
|
|
4241
|
+
diskLatencyWatchdog: options.diskLatencyWatchdog ?? true,
|
|
4242
|
+
diskLatencyBypassRatio: options.diskLatencyBypassRatio ?? 1.5,
|
|
4243
|
+
diskLatencyBypassMinMs: options.diskLatencyBypassMinMs ?? 10,
|
|
4244
|
+
diskLatencyBypassCooldownMs: options.diskLatencyBypassCooldownMs ?? 3e4,
|
|
4245
|
+
failReadinessOnDegraded: options.failReadinessOnDegraded ?? false,
|
|
4246
|
+
autoPipeline: options.autoPipeline ?? false,
|
|
4247
|
+
maxPipelineBatchSize: options.maxPipelineBatchSize ?? 100,
|
|
4248
|
+
enableIpc: options.enableIpc ?? false,
|
|
4249
|
+
ipcSocketPath: options.ipcSocketPath
|
|
2722
4250
|
};
|
|
4251
|
+
this.codec = new CacheCodec({
|
|
4252
|
+
useToJSON: this.opts.serializeToJSON,
|
|
4253
|
+
useRecords: true,
|
|
4254
|
+
moreTypes: true
|
|
4255
|
+
});
|
|
2723
4256
|
const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
|
|
2724
4257
|
const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
|
|
2725
4258
|
this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
|
|
@@ -2750,15 +4283,33 @@ var CacheService = class _CacheService {
|
|
|
2750
4283
|
encryption: this.enc.isEnabled ? this.enc : null,
|
|
2751
4284
|
compression: this.opts.compression,
|
|
2752
4285
|
compressionThresholdBytes: this.opts.compressionThresholdBytes,
|
|
2753
|
-
logger
|
|
4286
|
+
logger,
|
|
4287
|
+
codec: this.codec,
|
|
4288
|
+
diskMaxConcurrentWrites: this.opts.diskMaxConcurrentWrites,
|
|
4289
|
+
diskMaxPendingWrites: this.opts.diskMaxPendingWrites,
|
|
4290
|
+
diskWriteTimeoutMs: this.opts.diskWriteTimeoutMs,
|
|
4291
|
+
diskCircuitBreakerThreshold: this.opts.diskCircuitBreakerThreshold,
|
|
4292
|
+
diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs
|
|
2754
4293
|
});
|
|
2755
4294
|
this._namespace = ns;
|
|
2756
|
-
this._redisDisabled = this.opts.disableRedis || !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
|
|
4295
|
+
this._redisDisabled = this.opts.disableRedis || !this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
|
|
4296
|
+
this.watchdog = new TierLatencyWatchdog({
|
|
4297
|
+
enabled: options.diskLatencyWatchdog ?? true,
|
|
4298
|
+
minDiskBypassMs: options.diskLatencyBypassMinMs ?? 10,
|
|
4299
|
+
bypassRatio: options.diskLatencyBypassRatio ?? 1.5,
|
|
4300
|
+
cooldownMs: options.diskLatencyBypassCooldownMs ?? 3e4,
|
|
4301
|
+
redisCutoffMs: 15,
|
|
4302
|
+
redisRecoveryFloorMs: 10,
|
|
4303
|
+
minSamples: 16,
|
|
4304
|
+
disableRedis: this._redisDisabled
|
|
4305
|
+
});
|
|
2757
4306
|
this.l1 = new SmartMemoryCache({
|
|
2758
4307
|
maxBytes: this.opts.l1MaxBytes,
|
|
2759
4308
|
maxEntries: this.opts.l1MaxEntries,
|
|
2760
4309
|
categories: this.opts.categoryLimits,
|
|
2761
4310
|
evictionWatermark: this.opts.l1EvictionWatermark,
|
|
4311
|
+
admissionPolicy: this.opts.l1AdmissionPolicy,
|
|
4312
|
+
codec: this.codec,
|
|
2762
4313
|
diskSpill: (key, entry) => {
|
|
2763
4314
|
if (this._diskDisabled) return;
|
|
2764
4315
|
setImmediate(() => {
|
|
@@ -2773,10 +4324,9 @@ var CacheService = class _CacheService {
|
|
|
2773
4324
|
if (!this._diskDisabled) this.loadSnapshot();
|
|
2774
4325
|
}
|
|
2775
4326
|
this._shutdownHandler = () => {
|
|
2776
|
-
|
|
4327
|
+
this._triggerShutdown();
|
|
2777
4328
|
};
|
|
2778
|
-
|
|
2779
|
-
process.once("SIGINT", this._shutdownHandler);
|
|
4329
|
+
ProcessTerminationBus.register(this);
|
|
2780
4330
|
if (this.opts.workerThreads) {
|
|
2781
4331
|
try {
|
|
2782
4332
|
const encRef = this.enc.toWorkerInit();
|
|
@@ -2816,7 +4366,7 @@ var CacheService = class _CacheService {
|
|
|
2816
4366
|
}
|
|
2817
4367
|
if (this.opts.oomProtection) {
|
|
2818
4368
|
this.oomInterval = setInterval(() => {
|
|
2819
|
-
const heap =
|
|
4369
|
+
const heap = import_node_v82.default.getHeapStatistics();
|
|
2820
4370
|
const used = heap.used_heap_size / heap.heap_size_limit;
|
|
2821
4371
|
if (used >= this.opts.oomHeapThreshold) {
|
|
2822
4372
|
const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
|
|
@@ -2840,12 +4390,25 @@ var CacheService = class _CacheService {
|
|
|
2840
4390
|
}, this.opts.metricsIntervalMs);
|
|
2841
4391
|
if (this.metricsInterval.unref) this.metricsInterval.unref();
|
|
2842
4392
|
}
|
|
4393
|
+
if (this.opts.remoteSnapshot?.intervalMs && this.opts.remoteSnapshot.intervalMs > 0) {
|
|
4394
|
+
this.remoteSnapshotInterval = setInterval(() => {
|
|
4395
|
+
void this.writeRemoteSnapshot();
|
|
4396
|
+
}, this.opts.remoteSnapshot.intervalMs);
|
|
4397
|
+
if (this.remoteSnapshotInterval.unref) this.remoteSnapshotInterval.unref();
|
|
4398
|
+
}
|
|
2843
4399
|
this.instanceId = import_crypto3.default.randomBytes(8).toString("hex");
|
|
2844
4400
|
this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
|
|
2845
4401
|
this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
|
|
2846
4402
|
this.initBackplane();
|
|
4403
|
+
const startupPromises = [];
|
|
4404
|
+
if (this.opts.remoteSnapshot) {
|
|
4405
|
+
startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
|
|
4406
|
+
}
|
|
2847
4407
|
if (this.opts.warmKeys) {
|
|
2848
|
-
|
|
4408
|
+
startupPromises.push(this.warmFromL2(this.opts.warmKeys).then(() => void 0));
|
|
4409
|
+
}
|
|
4410
|
+
if (startupPromises.length > 0) {
|
|
4411
|
+
this._readyPromise = Promise.all(startupPromises).then(() => void 0);
|
|
2849
4412
|
}
|
|
2850
4413
|
if (this.opts.meter) {
|
|
2851
4414
|
this._initOtelMetrics(this.opts.meter);
|
|
@@ -2866,8 +4429,71 @@ var CacheService = class _CacheService {
|
|
|
2866
4429
|
}
|
|
2867
4430
|
});
|
|
2868
4431
|
}
|
|
4432
|
+
if (this.opts.enableIpc) {
|
|
4433
|
+
this._ipcServer = new IpcTelemetryServer(this, this.opts.ipcSocketPath);
|
|
4434
|
+
this._ipcServer.start().catch((err) => {
|
|
4435
|
+
this.logger.warn("Failed to start IPC telemetry server", { error: err.message });
|
|
4436
|
+
});
|
|
4437
|
+
}
|
|
4438
|
+
}
|
|
4439
|
+
// ── Singleton factory & Presets ───────────────────────────────────────────
|
|
4440
|
+
/**
|
|
4441
|
+
* Pre-configured production presets tailored for specific deployment environments.
|
|
4442
|
+
*
|
|
4443
|
+
* - `'nextjs'`: W-TinyLFU, zero-copy cloneStrategy: 'none' (React 19 RSC stream optimized),
|
|
4444
|
+
* generational tags, and Redis stream backplane.
|
|
4445
|
+
* - `'microservice'`: High-throughput Node.js microservice with W-TinyLFU, Streams backplane,
|
|
4446
|
+
* TTL jitter, and L2 circuit breaking.
|
|
4447
|
+
* - `'serverless'`: Stateless Lambda / Cloud Run isolate with memory-only L1, fast timeouts,
|
|
4448
|
+
* and Pub/Sub backplane.
|
|
4449
|
+
* - `'enterprise-hardened'`: Zero-trust production setup with generational tagging, Streams backplane,
|
|
4450
|
+
* fail-closed rate-limits, strict singleton assertions, and 80% OOM guard.
|
|
4451
|
+
*
|
|
4452
|
+
* @param type The preset identifier ('nextjs' | 'microservice' | 'serverless' | 'enterprise-hardened')
|
|
4453
|
+
* @param overrides Optional configuration overrides merged deeply over preset defaults
|
|
4454
|
+
* @returns Singleton CacheService instance configured according to the preset
|
|
4455
|
+
*/
|
|
4456
|
+
static preset(type, overrides) {
|
|
4457
|
+
const PRESETS = {
|
|
4458
|
+
"nextjs": {
|
|
4459
|
+
l1AdmissionPolicy: "wtinylfu",
|
|
4460
|
+
cloneStrategy: "none",
|
|
4461
|
+
tagStrategy: "generational",
|
|
4462
|
+
tagVersionTtlMs: 2e3,
|
|
4463
|
+
backplaneMode: "stream",
|
|
4464
|
+
staleIfError: 300,
|
|
4465
|
+
compression: "none"
|
|
4466
|
+
},
|
|
4467
|
+
"microservice": {
|
|
4468
|
+
l1AdmissionPolicy: "wtinylfu",
|
|
4469
|
+
backplaneMode: "stream",
|
|
4470
|
+
ttlJitterFactor: 0.15,
|
|
4471
|
+
l2CircuitBreakerThreshold: 5,
|
|
4472
|
+
l2CircuitBreakerCooldownMs: 15e3
|
|
4473
|
+
},
|
|
4474
|
+
"serverless": {
|
|
4475
|
+
disableDisk: true,
|
|
4476
|
+
l1AdmissionPolicy: "wtinylfu",
|
|
4477
|
+
backplaneMode: "pubsub",
|
|
4478
|
+
redisCommandTimeoutMs: 1e3
|
|
4479
|
+
},
|
|
4480
|
+
"enterprise-hardened": {
|
|
4481
|
+
l1AdmissionPolicy: "wtinylfu",
|
|
4482
|
+
tagStrategy: "generational",
|
|
4483
|
+
backplaneMode: "stream",
|
|
4484
|
+
strictSingleton: true,
|
|
4485
|
+
failClosed: true,
|
|
4486
|
+
oomProtection: true,
|
|
4487
|
+
oomHeapThreshold: 0.8
|
|
4488
|
+
}
|
|
4489
|
+
};
|
|
4490
|
+
const base = PRESETS[type];
|
|
4491
|
+
if (!base) {
|
|
4492
|
+
throw new Error(`tricache: unknown preset '${type}'. Supported presets: 'nextjs', 'microservice', 'serverless', 'enterprise-hardened'`);
|
|
4493
|
+
}
|
|
4494
|
+
const merged = deepMergeOptions(base, overrides);
|
|
4495
|
+
return _CacheService.create(merged);
|
|
2869
4496
|
}
|
|
2870
|
-
// ── Singleton factory ─────────────────────────────────────────────────────
|
|
2871
4497
|
/**
|
|
2872
4498
|
* Get (or create) the process-level singleton CacheService instance.
|
|
2873
4499
|
*
|
|
@@ -2961,7 +4587,9 @@ var CacheService = class _CacheService {
|
|
|
2961
4587
|
frozen: o.frozen,
|
|
2962
4588
|
adaptiveTtl: o.adaptiveTtl,
|
|
2963
4589
|
invalidationBackplane: o.invalidationBackplane,
|
|
2964
|
-
strictSingleton: o.strictSingleton
|
|
4590
|
+
strictSingleton: o.strictSingleton,
|
|
4591
|
+
remoteSnapshot: o.remoteSnapshot,
|
|
4592
|
+
crossRegion: o.crossRegion
|
|
2965
4593
|
};
|
|
2966
4594
|
}
|
|
2967
4595
|
/**
|
|
@@ -3020,15 +4648,30 @@ var CacheService = class _CacheService {
|
|
|
3020
4648
|
setStatus() {
|
|
3021
4649
|
return this;
|
|
3022
4650
|
},
|
|
4651
|
+
recordException() {
|
|
4652
|
+
return this;
|
|
4653
|
+
},
|
|
3023
4654
|
end() {
|
|
3024
4655
|
}
|
|
3025
4656
|
};
|
|
3026
4657
|
/** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
|
|
3027
|
-
_startSpan(name) {
|
|
3028
|
-
if (this.opts.tracer)
|
|
4658
|
+
_startSpan(name, links) {
|
|
4659
|
+
if (this.opts.tracer) {
|
|
4660
|
+
const span = this.opts.tracer.startSpan(name, links?.length ? { links } : void 0);
|
|
4661
|
+
if (this.opts.namespace) {
|
|
4662
|
+
span.setAttribute("cache.namespace", this.opts.namespace);
|
|
4663
|
+
}
|
|
4664
|
+
return span;
|
|
4665
|
+
}
|
|
3029
4666
|
return _CacheService._nullSpan;
|
|
3030
4667
|
}
|
|
3031
4668
|
createDedicatedRedisClient() {
|
|
4669
|
+
if (this.opts.redisSubClient) {
|
|
4670
|
+
return this.opts.redisSubClient;
|
|
4671
|
+
}
|
|
4672
|
+
if (this.opts.redisClient && typeof this.opts.redisClient.duplicate === "function") {
|
|
4673
|
+
return this.opts.redisClient.duplicate();
|
|
4674
|
+
}
|
|
3032
4675
|
if (this.opts.redisClusterNodes?.length) {
|
|
3033
4676
|
return new import_ioredis.Cluster(this.opts.redisClusterNodes, {
|
|
3034
4677
|
redisOptions: {
|
|
@@ -3262,7 +4905,13 @@ var CacheService = class _CacheService {
|
|
|
3262
4905
|
this.logger.warn("Backplane: malformed message JSON parse failed");
|
|
3263
4906
|
}
|
|
3264
4907
|
}
|
|
3265
|
-
async publishInvalidation(op, key, tagVersion) {
|
|
4908
|
+
async publishInvalidation(op, key, tagVersion, isCrossRegionRelay = false, isExplicitInvalidation = false) {
|
|
4909
|
+
if (!isCrossRegionRelay && this.opts.crossRegion) {
|
|
4910
|
+
const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
|
|
4911
|
+
if (shouldBroadcast) {
|
|
4912
|
+
void this._broadcastCrossRegion(op, key, tagVersion);
|
|
4913
|
+
}
|
|
4914
|
+
}
|
|
3266
4915
|
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
3267
4916
|
try {
|
|
3268
4917
|
const client = await this.getRedis();
|
|
@@ -3304,7 +4953,80 @@ var CacheService = class _CacheService {
|
|
|
3304
4953
|
} catch {
|
|
3305
4954
|
}
|
|
3306
4955
|
}
|
|
3307
|
-
|
|
4956
|
+
_markCrossRegionEventSeen(id) {
|
|
4957
|
+
const maxDedup = this.opts.crossRegion?.dedupCacheSize ?? 1e4;
|
|
4958
|
+
if (this._seenCrossRegionEvents.size >= maxDedup) {
|
|
4959
|
+
const oldestKey = this._seenCrossRegionEvents.keys().next().value;
|
|
4960
|
+
if (oldestKey !== void 0) this._seenCrossRegionEvents.delete(oldestKey);
|
|
4961
|
+
}
|
|
4962
|
+
this._seenCrossRegionEvents.set(id, Date.now());
|
|
4963
|
+
}
|
|
4964
|
+
_isCrossRegionEventSeen(id) {
|
|
4965
|
+
return this._seenCrossRegionEvents.has(id);
|
|
4966
|
+
}
|
|
4967
|
+
async _broadcastCrossRegion(op, key, tagVersion) {
|
|
4968
|
+
const cr = this.opts.crossRegion;
|
|
4969
|
+
if (!cr) return;
|
|
4970
|
+
try {
|
|
4971
|
+
const eventId = import_crypto3.default.randomUUID();
|
|
4972
|
+
this._markCrossRegionEventSeen(eventId);
|
|
4973
|
+
const event = {
|
|
4974
|
+
id: eventId,
|
|
4975
|
+
originRegion: cr.currentRegion,
|
|
4976
|
+
originInstanceId: this.instanceId,
|
|
4977
|
+
op,
|
|
4978
|
+
key,
|
|
4979
|
+
tagVersion,
|
|
4980
|
+
timestamp: Date.now(),
|
|
4981
|
+
namespace: this._namespace || void 0
|
|
4982
|
+
};
|
|
4983
|
+
this.counters.crossRegionSent++;
|
|
4984
|
+
await cr.relay.broadcast(event);
|
|
4985
|
+
this.logger.debug("Cross-region invalidation broadcast", { op, key, region: cr.currentRegion });
|
|
4986
|
+
} catch (err) {
|
|
4987
|
+
this.counters.crossRegionSent = Math.max(0, this.counters.crossRegionSent - 1);
|
|
4988
|
+
this.counters.crossRegionErrors++;
|
|
4989
|
+
this.logger.warn("Cross-region invalidation broadcast failed", { error: err.message });
|
|
4990
|
+
}
|
|
4991
|
+
}
|
|
4992
|
+
/**
|
|
4993
|
+
* Receives an invalidation event from another region (e.g. via HTTP webhook or broker subscriber).
|
|
4994
|
+
* Validates origin, deduplicates to prevent loops, applies locally to L1/disk,
|
|
4995
|
+
* and fans out to the local Redis backplane so all regional peers invalidate as well.
|
|
4996
|
+
*
|
|
4997
|
+
* Returns true if the event was accepted and applied, or false if ignored/deduplicated.
|
|
4998
|
+
*/
|
|
4999
|
+
async receiveCrossRegionInvalidation(event) {
|
|
5000
|
+
const cr = this.opts.crossRegion;
|
|
5001
|
+
if (!cr) return false;
|
|
5002
|
+
if (!event || typeof event !== "object" || !event.id || !event.originRegion || !event.op || !event.key) {
|
|
5003
|
+
this.counters.crossRegionErrors++;
|
|
5004
|
+
this.logger.warn("Cross-region: rejected invalid event payload", { event });
|
|
5005
|
+
return false;
|
|
5006
|
+
}
|
|
5007
|
+
if (event.originRegion === cr.currentRegion) {
|
|
5008
|
+
this.counters.crossRegionDeduplicated++;
|
|
5009
|
+
return false;
|
|
5010
|
+
}
|
|
5011
|
+
if (this._isCrossRegionEventSeen(event.id)) {
|
|
5012
|
+
this.counters.crossRegionDeduplicated++;
|
|
5013
|
+
return false;
|
|
5014
|
+
}
|
|
5015
|
+
this._markCrossRegionEventSeen(event.id);
|
|
5016
|
+
if (event.namespace !== void 0 && event.namespace !== (this._namespace || void 0)) {
|
|
5017
|
+
return false;
|
|
5018
|
+
}
|
|
5019
|
+
this.counters.crossRegionReceived++;
|
|
5020
|
+
this._applyInvalidationEvent(event.op, event.key, event.tagVersion);
|
|
5021
|
+
void this.publishInvalidation(event.op, event.key, event.tagVersion, true);
|
|
5022
|
+
this.logger.info("Cross-region invalidation applied", {
|
|
5023
|
+
op: event.op,
|
|
5024
|
+
key: event.key,
|
|
5025
|
+
originRegion: event.originRegion
|
|
5026
|
+
});
|
|
5027
|
+
return true;
|
|
5028
|
+
}
|
|
5029
|
+
_setLocalTagVersion(tag, version, now = performance.now()) {
|
|
3308
5030
|
const existing = this.tagVersions.get(tag)?.version ?? 0;
|
|
3309
5031
|
const finalVersion = Math.max(existing, version);
|
|
3310
5032
|
if (this.tagVersions.size >= 1e4 && !this.tagVersions.has(tag)) {
|
|
@@ -3314,7 +5036,7 @@ var CacheService = class _CacheService {
|
|
|
3314
5036
|
this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
|
|
3315
5037
|
}
|
|
3316
5038
|
async _getTagVersion(tag) {
|
|
3317
|
-
const now =
|
|
5039
|
+
const now = performance.now();
|
|
3318
5040
|
const local = this.tagVersions.get(tag);
|
|
3319
5041
|
if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
|
|
3320
5042
|
return local.version;
|
|
@@ -3400,13 +5122,25 @@ var CacheService = class _CacheService {
|
|
|
3400
5122
|
stream.on("error", reject);
|
|
3401
5123
|
})
|
|
3402
5124
|
));
|
|
3403
|
-
} else {
|
|
5125
|
+
} else if (typeof client.scanStream === "function") {
|
|
3404
5126
|
await new Promise((resolve, reject) => {
|
|
3405
5127
|
const stream = client.scanStream({ match: pattern, count: 100 });
|
|
3406
5128
|
stream.on("data", (chunk) => keys.push(...chunk));
|
|
3407
5129
|
stream.on("end", resolve);
|
|
3408
5130
|
stream.on("error", reject);
|
|
3409
5131
|
});
|
|
5132
|
+
} else if (typeof client.scanIterator === "function") {
|
|
5133
|
+
for await (const key of client.scanIterator({ MATCH: pattern, COUNT: 100 })) {
|
|
5134
|
+
keys.push(key);
|
|
5135
|
+
}
|
|
5136
|
+
} else if (typeof client.scan === "function") {
|
|
5137
|
+
let cursor = "0";
|
|
5138
|
+
do {
|
|
5139
|
+
const res = await client.scan(cursor, "MATCH", pattern, "COUNT", 100);
|
|
5140
|
+
cursor = String(res[0]);
|
|
5141
|
+
const chunk = res[1];
|
|
5142
|
+
if (chunk?.length) keys.push(...chunk);
|
|
5143
|
+
} while (cursor !== "0");
|
|
3410
5144
|
}
|
|
3411
5145
|
return keys;
|
|
3412
5146
|
}
|
|
@@ -3423,6 +5157,19 @@ var CacheService = class _CacheService {
|
|
|
3423
5157
|
if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
|
|
3424
5158
|
if (this.redis) return this.redis;
|
|
3425
5159
|
if (this.redisConnecting) return this.redisConnecting;
|
|
5160
|
+
if (this.opts.redisClient) {
|
|
5161
|
+
const client = this.opts.redisClient;
|
|
5162
|
+
if (typeof client.connect === "function" && client.isOpen === false) {
|
|
5163
|
+
await client.connect();
|
|
5164
|
+
}
|
|
5165
|
+
this.cb.onSuccess();
|
|
5166
|
+
this.redis = client;
|
|
5167
|
+
this.pipeliner = new AutoPipeliner(client, {
|
|
5168
|
+
enabled: this.opts.autoPipeline,
|
|
5169
|
+
maxBatchSize: this.opts.maxPipelineBatchSize
|
|
5170
|
+
});
|
|
5171
|
+
return client;
|
|
5172
|
+
}
|
|
3426
5173
|
this.redisConnecting = (async () => {
|
|
3427
5174
|
try {
|
|
3428
5175
|
let client;
|
|
@@ -3431,6 +5178,7 @@ var CacheService = class _CacheService {
|
|
|
3431
5178
|
redisOptions: {
|
|
3432
5179
|
tls: this.opts.redisTls ? {} : void 0,
|
|
3433
5180
|
connectTimeout: 1e4,
|
|
5181
|
+
commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
|
|
3434
5182
|
maxRetriesPerRequest: 3,
|
|
3435
5183
|
keepAlive: 3e4,
|
|
3436
5184
|
...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
|
|
@@ -3451,6 +5199,7 @@ var CacheService = class _CacheService {
|
|
|
3451
5199
|
name: this.opts.redisSentinel.name,
|
|
3452
5200
|
tls: this.opts.redisTls ? {} : void 0,
|
|
3453
5201
|
connectTimeout: 1e4,
|
|
5202
|
+
commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
|
|
3454
5203
|
lazyConnect: false,
|
|
3455
5204
|
maxRetriesPerRequest: 3,
|
|
3456
5205
|
enableAutoPipelining: true,
|
|
@@ -3470,6 +5219,7 @@ var CacheService = class _CacheService {
|
|
|
3470
5219
|
port: this.opts.redisPort,
|
|
3471
5220
|
tls: this.opts.redisTls ? {} : void 0,
|
|
3472
5221
|
connectTimeout: 1e4,
|
|
5222
|
+
commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
|
|
3473
5223
|
lazyConnect: false,
|
|
3474
5224
|
maxRetriesPerRequest: 3,
|
|
3475
5225
|
enableAutoPipelining: true,
|
|
@@ -3495,6 +5245,10 @@ var CacheService = class _CacheService {
|
|
|
3495
5245
|
});
|
|
3496
5246
|
this.cb.onSuccess();
|
|
3497
5247
|
this.redis = client;
|
|
5248
|
+
this.pipeliner = new AutoPipeliner(client, {
|
|
5249
|
+
enabled: this.opts.autoPipeline,
|
|
5250
|
+
maxBatchSize: this.opts.maxPipelineBatchSize
|
|
5251
|
+
});
|
|
3498
5252
|
this.redisConnecting = null;
|
|
3499
5253
|
return client;
|
|
3500
5254
|
} catch (err) {
|
|
@@ -3507,12 +5261,18 @@ var CacheService = class _CacheService {
|
|
|
3507
5261
|
return this.redisConnecting;
|
|
3508
5262
|
}
|
|
3509
5263
|
// ── Snapshot (cold-start persistence) ────────────────────────────────────
|
|
5264
|
+
/**
|
|
5265
|
+
* Writes the cold-start snapshot to disk.
|
|
5266
|
+
* NOTE: fs.writeFileSync is INTENTIONAL here: this method is invoked during SIGTERM/SIGINT
|
|
5267
|
+
* process termination hooks where asynchronous I/O would risk the Node.js event loop dying or
|
|
5268
|
+
* process.exit() being called before the snapshot is physically written to disk.
|
|
5269
|
+
*/
|
|
3510
5270
|
writeSnapshot(altPath) {
|
|
3511
5271
|
try {
|
|
3512
5272
|
const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
|
|
3513
5273
|
if (entries.length === 0) return;
|
|
3514
5274
|
const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
|
|
3515
|
-
const packed =
|
|
5275
|
+
const packed = this.codec.encode(payload);
|
|
3516
5276
|
const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
|
|
3517
5277
|
const dest = altPath ?? this.opts.snapshotPath;
|
|
3518
5278
|
import_fs3.default.mkdirSync(import_path3.default.dirname(dest), { recursive: true });
|
|
@@ -3527,6 +5287,12 @@ var CacheService = class _CacheService {
|
|
|
3527
5287
|
this.logger.warn("Cache snapshot write failed", { error: err.message });
|
|
3528
5288
|
}
|
|
3529
5289
|
}
|
|
5290
|
+
/**
|
|
5291
|
+
* Loads cold-start snapshot from disk into L1 memory.
|
|
5292
|
+
* NOTE: fs.readFileSync is INTENTIONAL here: this method is invoked synchronously inside the
|
|
5293
|
+
* CacheService constructor so that the cache is atomically populated before any subsequent
|
|
5294
|
+
* cache.get() or cache.set() operations run, eliminating cold-start race conditions.
|
|
5295
|
+
*/
|
|
3530
5296
|
loadSnapshot() {
|
|
3531
5297
|
const snapshotPath = this.opts.snapshotPath;
|
|
3532
5298
|
try {
|
|
@@ -3546,13 +5312,25 @@ var CacheService = class _CacheService {
|
|
|
3546
5312
|
this.logger.warn("Snapshot rejected: decryption failed", { error: e.message });
|
|
3547
5313
|
return;
|
|
3548
5314
|
}
|
|
3549
|
-
const snapshot =
|
|
5315
|
+
const snapshot = this.codec.decode(buf);
|
|
3550
5316
|
if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
|
|
3551
5317
|
this.logger.warn("Snapshot rejected: version mismatch", { got: snapshot?.version });
|
|
3552
5318
|
return;
|
|
3553
5319
|
}
|
|
3554
|
-
const
|
|
3555
|
-
|
|
5320
|
+
const now = Date.now();
|
|
5321
|
+
const writtenAt = snapshot.writtenAt ?? 0;
|
|
5322
|
+
const tolerance = this.opts.clockSkewToleranceMs ?? 250;
|
|
5323
|
+
if (writtenAt - now > tolerance) {
|
|
5324
|
+
this.logger.warn("Snapshot rejected: timestamp too far in future (exceeds clock skew tolerance)", {
|
|
5325
|
+
writtenAt,
|
|
5326
|
+
now,
|
|
5327
|
+
skewMs: writtenAt - now,
|
|
5328
|
+
tolerance
|
|
5329
|
+
});
|
|
5330
|
+
return;
|
|
5331
|
+
}
|
|
5332
|
+
const ageMs = Math.max(0, now - writtenAt);
|
|
5333
|
+
if (ageMs > this.opts.snapshotMaxAgeMs) {
|
|
3556
5334
|
this.logger.warn("Snapshot rejected: too old", { ageMinutes: Math.round(ageMs / 6e4) });
|
|
3557
5335
|
return;
|
|
3558
5336
|
}
|
|
@@ -3574,6 +5352,115 @@ var CacheService = class _CacheService {
|
|
|
3574
5352
|
}
|
|
3575
5353
|
}
|
|
3576
5354
|
}
|
|
5355
|
+
// ── Remote Snapshot (cold-start persistence for stateless containers) ───────
|
|
5356
|
+
/**
|
|
5357
|
+
* Persists the cold-start snapshot to remote blob storage (S3, GCS, R2, HTTP).
|
|
5358
|
+
* Can be awaited during graceful application shutdown (e.g. Kubernetes preStop or NestJS shutdown).
|
|
5359
|
+
* Returns true if a snapshot was successfully exported and written; false otherwise.
|
|
5360
|
+
*/
|
|
5361
|
+
async writeRemoteSnapshot() {
|
|
5362
|
+
if (!this.opts.remoteSnapshot) return false;
|
|
5363
|
+
try {
|
|
5364
|
+
const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
|
|
5365
|
+
if (entries.length === 0) return false;
|
|
5366
|
+
const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
|
|
5367
|
+
const packed = this.codec.encode(payload);
|
|
5368
|
+
let final;
|
|
5369
|
+
if (this.opts.remoteSnapshot.envelope) {
|
|
5370
|
+
final = await EnvelopeEncryption.encrypt(packed, this.opts.remoteSnapshot.envelope);
|
|
5371
|
+
} else {
|
|
5372
|
+
final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
|
|
5373
|
+
}
|
|
5374
|
+
await this.opts.remoteSnapshot.adapter.put(final);
|
|
5375
|
+
this.counters.remoteSnapshotUploads++;
|
|
5376
|
+
this.counters.remoteSnapshotLastUploadedAt = Date.now();
|
|
5377
|
+
this.logger.info("Remote cache snapshot uploaded", {
|
|
5378
|
+
entries: entries.length,
|
|
5379
|
+
sizeKB: Math.round(final.length / 1024),
|
|
5380
|
+
encrypted: Boolean(this.opts.remoteSnapshot.envelope || this.enc.isEnabled)
|
|
5381
|
+
});
|
|
5382
|
+
return true;
|
|
5383
|
+
} catch (err) {
|
|
5384
|
+
this.counters.remoteSnapshotErrors++;
|
|
5385
|
+
this.logger.warn("Remote cache snapshot upload failed", { error: err.message });
|
|
5386
|
+
return false;
|
|
5387
|
+
}
|
|
5388
|
+
}
|
|
5389
|
+
/**
|
|
5390
|
+
* Hydrates L1 memory from remote blob storage (S3, GCS, R2, HTTP).
|
|
5391
|
+
* Called automatically during startup (chained into `cache.ready()`).
|
|
5392
|
+
* Returns the number of entries successfully imported.
|
|
5393
|
+
*/
|
|
5394
|
+
async loadRemoteSnapshot() {
|
|
5395
|
+
if (!this.opts.remoteSnapshot) return 0;
|
|
5396
|
+
const maxAgeMs = this.opts.remoteSnapshot.maxAgeMs ?? this.opts.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE;
|
|
5397
|
+
try {
|
|
5398
|
+
const raw = await this.opts.remoteSnapshot.adapter.get();
|
|
5399
|
+
if (!raw || raw.length === 0) {
|
|
5400
|
+
this.logger.debug("Remote snapshot not found or empty \u2014 starting cold");
|
|
5401
|
+
return 0;
|
|
5402
|
+
}
|
|
5403
|
+
const rawBuf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
|
|
5404
|
+
let buf;
|
|
5405
|
+
try {
|
|
5406
|
+
if (EnvelopeEncryption.isEnvelope(rawBuf)) {
|
|
5407
|
+
if (!this.opts.remoteSnapshot.envelope) {
|
|
5408
|
+
throw new Error("Remote snapshot is envelope-encrypted but no envelope options (privateKey or kmsDecrypt) were configured");
|
|
5409
|
+
}
|
|
5410
|
+
buf = await EnvelopeEncryption.decrypt(rawBuf, this.opts.remoteSnapshot.envelope);
|
|
5411
|
+
} else {
|
|
5412
|
+
buf = this.enc.decryptBuffer(rawBuf);
|
|
5413
|
+
}
|
|
5414
|
+
} catch (e) {
|
|
5415
|
+
this.counters.remoteSnapshotErrors++;
|
|
5416
|
+
this.logger.warn("Remote snapshot rejected: decryption failed", { error: e.message });
|
|
5417
|
+
return 0;
|
|
5418
|
+
}
|
|
5419
|
+
const snapshot = this.codec.decode(buf);
|
|
5420
|
+
if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
|
|
5421
|
+
this.counters.remoteSnapshotErrors++;
|
|
5422
|
+
this.logger.warn("Remote snapshot rejected: version mismatch", { got: snapshot?.version });
|
|
5423
|
+
return 0;
|
|
5424
|
+
}
|
|
5425
|
+
const now = Date.now();
|
|
5426
|
+
const writtenAt = snapshot.writtenAt ?? 0;
|
|
5427
|
+
const tolerance = this.opts.clockSkewToleranceMs ?? 250;
|
|
5428
|
+
if (writtenAt - now > tolerance) {
|
|
5429
|
+
this.counters.remoteSnapshotErrors++;
|
|
5430
|
+
this.logger.warn("Remote snapshot rejected: timestamp too far in future (exceeds clock skew tolerance)", {
|
|
5431
|
+
writtenAt,
|
|
5432
|
+
now,
|
|
5433
|
+
skewMs: writtenAt - now,
|
|
5434
|
+
tolerance
|
|
5435
|
+
});
|
|
5436
|
+
return 0;
|
|
5437
|
+
}
|
|
5438
|
+
const ageMs = Math.max(0, now - writtenAt);
|
|
5439
|
+
if (maxAgeMs <= 0 || ageMs > maxAgeMs) {
|
|
5440
|
+
this.counters.remoteSnapshotErrors++;
|
|
5441
|
+
this.logger.warn("Remote snapshot rejected: too old", { ageMinutes: Math.round(ageMs / 6e4) });
|
|
5442
|
+
return 0;
|
|
5443
|
+
}
|
|
5444
|
+
if (!Array.isArray(snapshot.entries)) {
|
|
5445
|
+
this.counters.remoteSnapshotErrors++;
|
|
5446
|
+
this.logger.warn("Remote snapshot rejected: entries is not an array");
|
|
5447
|
+
return 0;
|
|
5448
|
+
}
|
|
5449
|
+
const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
|
|
5450
|
+
this.counters.remoteSnapshotDownloads++;
|
|
5451
|
+
this.counters.remoteSnapshotLastDownloadedAt = Date.now();
|
|
5452
|
+
this.logger.info("Remote cache snapshot loaded (L1 hydrated)", {
|
|
5453
|
+
loaded,
|
|
5454
|
+
total: snapshot.entries.length,
|
|
5455
|
+
sizeKB: this.l1.getStats().sizeKB
|
|
5456
|
+
});
|
|
5457
|
+
return loaded;
|
|
5458
|
+
} catch (err) {
|
|
5459
|
+
this.counters.remoteSnapshotErrors++;
|
|
5460
|
+
this.logger.warn("Remote snapshot load failed \u2014 starting cold", { error: err.message });
|
|
5461
|
+
return 0;
|
|
5462
|
+
}
|
|
5463
|
+
}
|
|
3577
5464
|
// ── Core get (L1 → L1.5 → L2 → fetch) ───────────────────────────────────
|
|
3578
5465
|
/**
|
|
3579
5466
|
* Get a value from cache, or fetch and cache it.
|
|
@@ -3609,9 +5496,10 @@ var CacheService = class _CacheService {
|
|
|
3609
5496
|
if (l1Hit !== null) {
|
|
3610
5497
|
let isGenerationalStale = false;
|
|
3611
5498
|
if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
|
|
3612
|
-
|
|
3613
|
-
|
|
3614
|
-
|
|
5499
|
+
const tags = Object.keys(l1Hit.tagVersions);
|
|
5500
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5501
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5502
|
+
if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
|
|
3615
5503
|
isGenerationalStale = true;
|
|
3616
5504
|
break;
|
|
3617
5505
|
}
|
|
@@ -3656,116 +5544,140 @@ var CacheService = class _CacheService {
|
|
|
3656
5544
|
this.counters.l1Hits++;
|
|
3657
5545
|
this.opts.onHit?.(cacheKey, "l1");
|
|
3658
5546
|
if (this.opts.frozen) deepFreeze(l1Hit.value);
|
|
3659
|
-
span.setAttribute("cache.hit", "l1").end();
|
|
5547
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "memory").setAttribute("cache.hit_tier", "l1").end();
|
|
3660
5548
|
return this.opts.cloneStrategy === "structuredClone" && l1Hit.value != null && typeof l1Hit.value === "object" ? structuredClone(l1Hit.value) : l1Hit.value;
|
|
3661
5549
|
}
|
|
3662
5550
|
}
|
|
3663
5551
|
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
3664
5552
|
const swrGraceMs = optSwr * 1e3;
|
|
3665
5553
|
const priority = optPriority ?? inferPriority(cacheKey);
|
|
3666
|
-
|
|
5554
|
+
const existing = this.inflight.get(k);
|
|
5555
|
+
if (existing) {
|
|
5556
|
+
this.counters.stampedes++;
|
|
5557
|
+
this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch/read", { cacheKey });
|
|
5558
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
|
|
5559
|
+
return existing;
|
|
5560
|
+
}
|
|
5561
|
+
const executionPromise = (async () => {
|
|
3667
5562
|
try {
|
|
3668
|
-
|
|
3669
|
-
|
|
3670
|
-
|
|
3671
|
-
|
|
3672
|
-
|
|
3673
|
-
|
|
3674
|
-
|
|
3675
|
-
|
|
3676
|
-
|
|
3677
|
-
|
|
3678
|
-
|
|
5563
|
+
if (!this._diskDisabled) {
|
|
5564
|
+
const isDiskAllowed = this.watchdog.isDiskAllowed();
|
|
5565
|
+
if (isDiskAllowed) {
|
|
5566
|
+
const diskStart = performance.now();
|
|
5567
|
+
const diskHit = this.disk.load(k);
|
|
5568
|
+
const diskElapsed = performance.now() - diskStart;
|
|
5569
|
+
this.watchdog.recordDisk(diskElapsed);
|
|
5570
|
+
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
5571
|
+
if (diskHit !== null) {
|
|
5572
|
+
let isDiskStale = false;
|
|
5573
|
+
if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
|
|
5574
|
+
const tags = Object.keys(diskHit.tagVersions);
|
|
5575
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5576
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5577
|
+
if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
|
|
5578
|
+
isDiskStale = true;
|
|
5579
|
+
break;
|
|
5580
|
+
}
|
|
5581
|
+
}
|
|
3679
5582
|
}
|
|
3680
|
-
|
|
3681
|
-
|
|
3682
|
-
|
|
3683
|
-
|
|
3684
|
-
|
|
3685
|
-
|
|
5583
|
+
if (isDiskStale) {
|
|
5584
|
+
this.disk.delete(k);
|
|
5585
|
+
} else {
|
|
5586
|
+
const promoted = this.l1.importEntries(
|
|
5587
|
+
[{ key: k, entry: diskHit }],
|
|
5588
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
5589
|
+
);
|
|
5590
|
+
if (promoted > 0) {
|
|
5591
|
+
const l1Check = this.l1.get(k);
|
|
5592
|
+
if (l1Check !== null) {
|
|
5593
|
+
this.counters.diskHits++;
|
|
5594
|
+
this.opts.onHit?.(cacheKey, "disk");
|
|
5595
|
+
this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
|
|
5596
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
|
|
5597
|
+
if (this.opts.frozen) deepFreeze(l1Check.value);
|
|
5598
|
+
return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
|
|
5599
|
+
}
|
|
5600
|
+
}
|
|
3686
5601
|
}
|
|
3687
5602
|
}
|
|
3688
|
-
if (isStale) {
|
|
3689
|
-
const setAtMs = parseInt(hashData.t, 10) || 0;
|
|
3690
|
-
this._deleteIfStale(k, setAtMs);
|
|
3691
|
-
} else {
|
|
3692
|
-
const parsed = await this._decryptAndDeserialize(hashData.d);
|
|
3693
|
-
this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
|
|
3694
|
-
this.counters.l2Hits++;
|
|
3695
|
-
this.opts.onHit?.(cacheKey, "l2");
|
|
3696
|
-
this.logger.debug("L2 hit (Redis hash)", { cacheKey });
|
|
3697
|
-
span.setAttribute("cache.hit", "l2").end();
|
|
3698
|
-
if (this.opts.frozen) deepFreeze(parsed);
|
|
3699
|
-
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
3700
|
-
}
|
|
3701
|
-
}
|
|
3702
|
-
} else {
|
|
3703
|
-
const raw = await client.get(k);
|
|
3704
|
-
this.cb.onSuccess();
|
|
3705
|
-
if (raw) {
|
|
3706
|
-
const parsed = await this._decryptAndDeserialize(raw);
|
|
3707
|
-
this.l1.set(k, parsed, ttlMs, priority);
|
|
3708
|
-
this.counters.l2Hits++;
|
|
3709
|
-
this.opts.onHit?.(cacheKey, "l2");
|
|
3710
|
-
this.logger.debug("L2 hit (Redis)", { cacheKey });
|
|
3711
|
-
span.setAttribute("cache.hit", "l2").end();
|
|
3712
|
-
if (this.opts.frozen) deepFreeze(parsed);
|
|
3713
|
-
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
3714
5603
|
}
|
|
3715
5604
|
}
|
|
3716
|
-
|
|
3717
|
-
|
|
3718
|
-
|
|
3719
|
-
|
|
3720
|
-
|
|
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
|
-
|
|
5605
|
+
if (!this._redisDisabled) {
|
|
5606
|
+
try {
|
|
5607
|
+
const client = await this.getRedis();
|
|
5608
|
+
const redisStart = performance.now();
|
|
5609
|
+
if (this.opts.tagStrategy === "generational") {
|
|
5610
|
+
const hashData = await client.hgetall(k);
|
|
5611
|
+
const redisElapsed = performance.now() - redisStart;
|
|
5612
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
5613
|
+
this.cb.onSuccess();
|
|
5614
|
+
if (hashData && hashData.d) {
|
|
5615
|
+
let isStale = false;
|
|
5616
|
+
let storedTagVersions = {};
|
|
5617
|
+
if (hashData.tv) {
|
|
5618
|
+
try {
|
|
5619
|
+
storedTagVersions = JSON.parse(hashData.tv);
|
|
5620
|
+
} catch {
|
|
5621
|
+
}
|
|
5622
|
+
}
|
|
5623
|
+
const tags = Object.keys(storedTagVersions);
|
|
5624
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5625
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5626
|
+
if (currentVers[i] > storedTagVersions[tags[i]]) {
|
|
5627
|
+
isStale = true;
|
|
5628
|
+
break;
|
|
5629
|
+
}
|
|
5630
|
+
}
|
|
5631
|
+
if (isStale) {
|
|
5632
|
+
const setAtMs = parseInt(hashData.t, 10) || 0;
|
|
5633
|
+
this._deleteIfStale(k, setAtMs);
|
|
5634
|
+
} else {
|
|
5635
|
+
const parsed = await this._decryptAndDeserialize(hashData.d);
|
|
5636
|
+
this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
|
|
5637
|
+
this.counters.l2Hits++;
|
|
5638
|
+
this.opts.onHit?.(cacheKey, "l2");
|
|
5639
|
+
this.logger.debug("L2 hit (Redis hash)", { cacheKey });
|
|
5640
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
5641
|
+
if (this.opts.frozen) deepFreeze(parsed);
|
|
5642
|
+
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
5643
|
+
}
|
|
5644
|
+
}
|
|
5645
|
+
} else {
|
|
5646
|
+
const raw = this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
|
|
5647
|
+
const redisElapsed = performance.now() - redisStart;
|
|
5648
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
5649
|
+
this.cb.onSuccess();
|
|
5650
|
+
if (raw) {
|
|
5651
|
+
const parsed = await this._decryptAndDeserialize(raw);
|
|
5652
|
+
this.l1.set(k, parsed, ttlMs, priority);
|
|
5653
|
+
this.counters.l2Hits++;
|
|
5654
|
+
this.opts.onHit?.(cacheKey, "l2");
|
|
5655
|
+
this.logger.debug("L2 hit (Redis)", { cacheKey });
|
|
5656
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
5657
|
+
if (this.opts.frozen) deepFreeze(parsed);
|
|
5658
|
+
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
5659
|
+
}
|
|
3750
5660
|
}
|
|
5661
|
+
} catch (err) {
|
|
5662
|
+
this.cb.onFailure();
|
|
5663
|
+
this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
|
|
3751
5664
|
}
|
|
3752
5665
|
}
|
|
3753
|
-
|
|
3754
|
-
|
|
3755
|
-
span.setAttribute("cache.hit", "miss");
|
|
3756
|
-
this.opts.onMiss?.(cacheKey);
|
|
3757
|
-
const existing = this.inflight.get(k);
|
|
3758
|
-
if (existing) {
|
|
3759
|
-
this.counters.stampedes++;
|
|
3760
|
-
this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch", { cacheKey });
|
|
3761
|
-
span.end();
|
|
3762
|
-
return existing;
|
|
3763
|
-
}
|
|
3764
|
-
const fetchPromise = (async () => {
|
|
3765
|
-
try {
|
|
5666
|
+
span.setAttribute("cache.hit", false).setAttribute("cache.hit_tier", "miss");
|
|
5667
|
+
this.opts.onMiss?.(cacheKey);
|
|
3766
5668
|
this.counters.fetches++;
|
|
3767
5669
|
const fetchStart = Date.now();
|
|
3768
|
-
|
|
5670
|
+
let data;
|
|
5671
|
+
try {
|
|
5672
|
+
data = await fetchFn();
|
|
5673
|
+
} catch (fetchErr) {
|
|
5674
|
+
span.setStatus({
|
|
5675
|
+
code: 2,
|
|
5676
|
+
message: fetchErr instanceof Error ? fetchErr.message : String(fetchErr)
|
|
5677
|
+
});
|
|
5678
|
+
span.recordException?.(fetchErr);
|
|
5679
|
+
throw fetchErr;
|
|
5680
|
+
}
|
|
3769
5681
|
const delta = Date.now() - fetchStart;
|
|
3770
5682
|
const notFoundTtlMs = (optNotFoundTtl ?? this.opts.notFoundTtl) * 1e3;
|
|
3771
5683
|
let effectiveTtl = data == null && notFoundTtlMs > 0 ? notFoundTtlMs : ttlMs;
|
|
@@ -3785,9 +5697,10 @@ var CacheService = class _CacheService {
|
|
|
3785
5697
|
let activeTagVersions;
|
|
3786
5698
|
if (optTags?.length) {
|
|
3787
5699
|
if (this.opts.tagStrategy === "generational") {
|
|
5700
|
+
const vers = await Promise.all(optTags.map((tag) => this._getTagVersion(tag)));
|
|
3788
5701
|
activeTagVersions = {};
|
|
3789
|
-
for (
|
|
3790
|
-
activeTagVersions[
|
|
5702
|
+
for (let i = 0; i < optTags.length; i++) {
|
|
5703
|
+
activeTagVersions[optTags[i]] = vers[i];
|
|
3791
5704
|
}
|
|
3792
5705
|
} else {
|
|
3793
5706
|
await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
|
|
@@ -3829,8 +5742,64 @@ var CacheService = class _CacheService {
|
|
|
3829
5742
|
span.end();
|
|
3830
5743
|
}
|
|
3831
5744
|
})();
|
|
3832
|
-
this.inflight.set(k,
|
|
3833
|
-
return
|
|
5745
|
+
this.inflight.set(k, executionPromise);
|
|
5746
|
+
return executionPromise;
|
|
5747
|
+
}
|
|
5748
|
+
/**
|
|
5749
|
+
* Graceful shutdown flusher for Kubernetes preStop hooks, NestJS onApplicationShutdown,
|
|
5750
|
+
* or manual microservice teardown.
|
|
5751
|
+
*
|
|
5752
|
+
* Flushes both local disk and remote cloud snapshots (S3/R2/GCS), returning a Promise
|
|
5753
|
+
* that resolves when the upload completes or after `timeoutMs` expires.
|
|
5754
|
+
*
|
|
5755
|
+
* @param timeoutMs Maximum time permitted for snapshot persistence before timing out. Default: 8000ms.
|
|
5756
|
+
*/
|
|
5757
|
+
async flushSnapshotOnShutdown(timeoutMs = 8e3) {
|
|
5758
|
+
const flusher = async () => {
|
|
5759
|
+
let localOk = true;
|
|
5760
|
+
let remoteOk = true;
|
|
5761
|
+
if (!this._diskDisabled) {
|
|
5762
|
+
try {
|
|
5763
|
+
this.writeSnapshot();
|
|
5764
|
+
} catch (err) {
|
|
5765
|
+
localOk = false;
|
|
5766
|
+
this.logger.warn("flushSnapshotOnShutdown: disk snapshot write failed", { error: err.message });
|
|
5767
|
+
}
|
|
5768
|
+
}
|
|
5769
|
+
if (this.opts.remoteSnapshot && this.opts.remoteSnapshot.saveOnShutdown !== false) {
|
|
5770
|
+
try {
|
|
5771
|
+
remoteOk = await this.writeRemoteSnapshot();
|
|
5772
|
+
} catch (err) {
|
|
5773
|
+
remoteOk = false;
|
|
5774
|
+
this.logger.warn("flushSnapshotOnShutdown: remote snapshot upload failed", { error: err.message });
|
|
5775
|
+
}
|
|
5776
|
+
}
|
|
5777
|
+
return localOk && remoteOk;
|
|
5778
|
+
};
|
|
5779
|
+
let timer = null;
|
|
5780
|
+
try {
|
|
5781
|
+
return await Promise.race([
|
|
5782
|
+
flusher(),
|
|
5783
|
+
new Promise((resolve) => {
|
|
5784
|
+
timer = setTimeout(() => {
|
|
5785
|
+
this.logger.warn(`flushSnapshotOnShutdown timed out after ${timeoutMs}ms`);
|
|
5786
|
+
resolve(false);
|
|
5787
|
+
}, timeoutMs);
|
|
5788
|
+
if (timer.unref) timer.unref();
|
|
5789
|
+
})
|
|
5790
|
+
]);
|
|
5791
|
+
} finally {
|
|
5792
|
+
if (timer) clearTimeout(timer);
|
|
5793
|
+
}
|
|
5794
|
+
}
|
|
5795
|
+
/**
|
|
5796
|
+
* Internal graceful shutdown trigger invoked by ProcessTerminationBus.
|
|
5797
|
+
*/
|
|
5798
|
+
_triggerShutdown() {
|
|
5799
|
+
if (!this._diskDisabled) this.writeSnapshot();
|
|
5800
|
+
if (this.opts.remoteSnapshot && this.opts.remoteSnapshot.saveOnShutdown !== false) {
|
|
5801
|
+
void this.flushSnapshotOnShutdown();
|
|
5802
|
+
}
|
|
3834
5803
|
}
|
|
3835
5804
|
/**
|
|
3836
5805
|
* Universal fetch-and-cache wrapper with an ergonomic options object.
|
|
@@ -3863,9 +5832,11 @@ var CacheService = class _CacheService {
|
|
|
3863
5832
|
let activeTagVersions;
|
|
3864
5833
|
const l1Existing = this.l1.get(cacheKey);
|
|
3865
5834
|
if (this.opts.tagStrategy === "generational" && l1Existing?.tagVersions) {
|
|
5835
|
+
const tags = Object.keys(l1Existing.tagVersions);
|
|
5836
|
+
const vers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
3866
5837
|
activeTagVersions = {};
|
|
3867
|
-
for (
|
|
3868
|
-
activeTagVersions[
|
|
5838
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5839
|
+
activeTagVersions[tags[i]] = vers[i];
|
|
3869
5840
|
}
|
|
3870
5841
|
}
|
|
3871
5842
|
this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
|
|
@@ -3911,62 +5882,77 @@ var CacheService = class _CacheService {
|
|
|
3911
5882
|
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
3912
5883
|
async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
|
|
3913
5884
|
const span = this._startSpan("tricache.set");
|
|
3914
|
-
if (this.opts.tracer)
|
|
3915
|
-
|
|
3916
|
-
|
|
3917
|
-
|
|
3918
|
-
|
|
3919
|
-
|
|
3920
|
-
|
|
3921
|
-
|
|
3922
|
-
|
|
3923
|
-
|
|
3924
|
-
|
|
3925
|
-
|
|
5885
|
+
if (this.opts.tracer) {
|
|
5886
|
+
span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
5887
|
+
span.setAttribute("cache.ttl", ttlSeconds);
|
|
5888
|
+
}
|
|
5889
|
+
try {
|
|
5890
|
+
const effectiveTtlSeconds = ttlSeconds > 0 ? ttlSeconds : ttlSeconds === 0 ? INDEFINITE_TTL_SECONDS : ttlSeconds;
|
|
5891
|
+
const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
|
|
5892
|
+
const p = priority ?? inferPriority(cacheKey);
|
|
5893
|
+
const k = this.nk(cacheKey);
|
|
5894
|
+
this.counters.sets++;
|
|
5895
|
+
let activeTagVersions;
|
|
5896
|
+
if (opts?.tags?.length) {
|
|
5897
|
+
if (this.opts.tagStrategy === "generational") {
|
|
5898
|
+
const vers = await Promise.all(opts.tags.map((tag) => this._getTagVersion(tag)));
|
|
5899
|
+
activeTagVersions = {};
|
|
5900
|
+
for (let i = 0; i < opts.tags.length; i++) {
|
|
5901
|
+
activeTagVersions[opts.tags[i]] = vers[i];
|
|
5902
|
+
}
|
|
5903
|
+
} else {
|
|
5904
|
+
await this._registerTags(k, opts.tags, ttlSeconds);
|
|
3926
5905
|
}
|
|
3927
|
-
} else {
|
|
3928
|
-
await this._registerTags(k, opts.tags, ttlSeconds);
|
|
3929
5906
|
}
|
|
3930
|
-
|
|
3931
|
-
|
|
3932
|
-
|
|
3933
|
-
|
|
3934
|
-
|
|
3935
|
-
|
|
3936
|
-
|
|
3937
|
-
|
|
3938
|
-
|
|
5907
|
+
this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
|
|
5908
|
+
if (opts?.dependsOn?.length) {
|
|
5909
|
+
for (const pattern of opts.dependsOn) {
|
|
5910
|
+
const nsPattern = this.nk(pattern);
|
|
5911
|
+
let deps = this.dependencyIndex.get(nsPattern);
|
|
5912
|
+
if (!deps) {
|
|
5913
|
+
deps = /* @__PURE__ */ new Set();
|
|
5914
|
+
this.dependencyIndex.set(nsPattern, deps);
|
|
5915
|
+
}
|
|
5916
|
+
deps.add(k);
|
|
3939
5917
|
}
|
|
3940
|
-
deps.add(k);
|
|
3941
5918
|
}
|
|
3942
|
-
|
|
3943
|
-
|
|
3944
|
-
|
|
3945
|
-
|
|
3946
|
-
|
|
3947
|
-
|
|
3948
|
-
|
|
3949
|
-
|
|
3950
|
-
|
|
3951
|
-
|
|
3952
|
-
|
|
3953
|
-
|
|
3954
|
-
|
|
3955
|
-
|
|
3956
|
-
|
|
3957
|
-
|
|
3958
|
-
|
|
3959
|
-
|
|
3960
|
-
|
|
5919
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5920
|
+
try {
|
|
5921
|
+
const client = await this.getRedis();
|
|
5922
|
+
const s = JSON.stringify(data);
|
|
5923
|
+
const stored = await this._serializeAndEncrypt(s);
|
|
5924
|
+
const ttlSec = Math.ceil(ttlMs / 1e3);
|
|
5925
|
+
if (this.opts.tagStrategy === "generational" && activeTagVersions) {
|
|
5926
|
+
const now = Date.now();
|
|
5927
|
+
const tx = client.multi();
|
|
5928
|
+
tx.hset(k, {
|
|
5929
|
+
d: stored,
|
|
5930
|
+
t: String(now),
|
|
5931
|
+
tv: JSON.stringify(activeTagVersions)
|
|
5932
|
+
});
|
|
5933
|
+
tx.expire(k, ttlSec);
|
|
5934
|
+
await tx.exec();
|
|
5935
|
+
} else {
|
|
5936
|
+
if (this.opts.autoPipeline && this.pipeliner) {
|
|
5937
|
+
await this.pipeliner.setex(k, ttlSec, stored);
|
|
5938
|
+
} else {
|
|
5939
|
+
await client.setex(k, ttlSec, stored);
|
|
5940
|
+
}
|
|
5941
|
+
}
|
|
5942
|
+
this.cb.onSuccess();
|
|
5943
|
+
} catch (err) {
|
|
5944
|
+
this.cb.onFailure();
|
|
5945
|
+
this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
|
|
3961
5946
|
}
|
|
3962
|
-
this.cb.onSuccess();
|
|
3963
|
-
} catch (err) {
|
|
3964
|
-
this.cb.onFailure();
|
|
3965
|
-
this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
|
|
3966
5947
|
}
|
|
5948
|
+
void this.publishInvalidation("del", k);
|
|
5949
|
+
} catch (err) {
|
|
5950
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
5951
|
+
span.recordException?.(err);
|
|
5952
|
+
throw err;
|
|
5953
|
+
} finally {
|
|
5954
|
+
span.end();
|
|
3967
5955
|
}
|
|
3968
|
-
void this.publishInvalidation("del", k);
|
|
3969
|
-
span.end();
|
|
3970
5956
|
}
|
|
3971
5957
|
/**
|
|
3972
5958
|
* Register tags for a cache key in the in-process index and (if Redis is enabled) in
|
|
@@ -4008,36 +5994,47 @@ var CacheService = class _CacheService {
|
|
|
4008
5994
|
async delete(cacheKey) {
|
|
4009
5995
|
const span = this._startSpan("tricache.delete");
|
|
4010
5996
|
if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
4011
|
-
|
|
4012
|
-
|
|
4013
|
-
|
|
4014
|
-
|
|
4015
|
-
|
|
4016
|
-
|
|
4017
|
-
|
|
4018
|
-
|
|
4019
|
-
|
|
4020
|
-
|
|
4021
|
-
|
|
4022
|
-
|
|
4023
|
-
|
|
4024
|
-
|
|
4025
|
-
|
|
4026
|
-
|
|
4027
|
-
|
|
4028
|
-
|
|
4029
|
-
|
|
4030
|
-
|
|
4031
|
-
|
|
5997
|
+
try {
|
|
5998
|
+
const isPattern = cacheKey.includes("*");
|
|
5999
|
+
const k = this.nk(cacheKey);
|
|
6000
|
+
this.counters.deletes++;
|
|
6001
|
+
if (isPattern) {
|
|
6002
|
+
this.l1.deletePattern(k);
|
|
6003
|
+
} else {
|
|
6004
|
+
this.l1.delete(k);
|
|
6005
|
+
setImmediate(() => {
|
|
6006
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
6007
|
+
});
|
|
6008
|
+
this._cascadeDependencies(k);
|
|
6009
|
+
for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
|
|
6010
|
+
}
|
|
6011
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
6012
|
+
try {
|
|
6013
|
+
const client = await this.getRedis();
|
|
6014
|
+
if (isPattern) {
|
|
6015
|
+
const keys = await this._scanKeys(client, k);
|
|
6016
|
+
if (keys.length > 0) await client.del(...keys);
|
|
6017
|
+
} else {
|
|
6018
|
+
if (this.opts.autoPipeline && this.pipeliner) {
|
|
6019
|
+
await this.pipeliner.del(k);
|
|
6020
|
+
} else {
|
|
6021
|
+
await client.del(k);
|
|
6022
|
+
}
|
|
6023
|
+
}
|
|
6024
|
+
this.cb.onSuccess();
|
|
6025
|
+
} catch (err) {
|
|
6026
|
+
this.cb.onFailure();
|
|
6027
|
+
this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
|
|
4032
6028
|
}
|
|
4033
|
-
this.cb.onSuccess();
|
|
4034
|
-
} catch (err) {
|
|
4035
|
-
this.cb.onFailure();
|
|
4036
|
-
this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
|
|
4037
6029
|
}
|
|
6030
|
+
void this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
|
|
6031
|
+
} catch (err) {
|
|
6032
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6033
|
+
span.recordException?.(err);
|
|
6034
|
+
throw err;
|
|
6035
|
+
} finally {
|
|
6036
|
+
span.end();
|
|
4038
6037
|
}
|
|
4039
|
-
void this.publishInvalidation(isPattern ? "del-glob" : "del", k);
|
|
4040
|
-
span.end();
|
|
4041
6038
|
}
|
|
4042
6039
|
// ── Counter (distributed rate limiting) ──────────────────────────────────
|
|
4043
6040
|
/**
|
|
@@ -4098,31 +6095,44 @@ var CacheService = class _CacheService {
|
|
|
4098
6095
|
* await cache.clear('user:abc'); // flush all keys for one user
|
|
4099
6096
|
*/
|
|
4100
6097
|
async clear(prefix) {
|
|
4101
|
-
this.
|
|
4102
|
-
|
|
4103
|
-
|
|
4104
|
-
this.
|
|
4105
|
-
|
|
4106
|
-
|
|
4107
|
-
|
|
4108
|
-
|
|
4109
|
-
|
|
4110
|
-
|
|
4111
|
-
|
|
4112
|
-
|
|
4113
|
-
|
|
4114
|
-
const client = await this.getRedis();
|
|
4115
|
-
const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
|
|
4116
|
-
const keys = await this._scanKeys(client, pattern);
|
|
4117
|
-
if (keys.length > 0) await client.del(...keys);
|
|
4118
|
-
} catch (err) {
|
|
4119
|
-
this.logger.debug("clear: Redis unavailable", { error: err.message });
|
|
6098
|
+
const span = this._startSpan("tricache.clear");
|
|
6099
|
+
if (this.opts.tracer) span.setAttribute("cache.prefix", prefix || "*");
|
|
6100
|
+
try {
|
|
6101
|
+
this.counters.deletes++;
|
|
6102
|
+
const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
|
|
6103
|
+
if (k) {
|
|
6104
|
+
this.l1.deletePattern(k);
|
|
6105
|
+
} else {
|
|
6106
|
+
this.l1.clear();
|
|
6107
|
+
if (!this._diskDisabled) this.disk.clear();
|
|
6108
|
+
this._l1Counters.clear();
|
|
6109
|
+
this.tagIndex.clear();
|
|
6110
|
+
this.tagVersions.clear();
|
|
4120
6111
|
}
|
|
6112
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
6113
|
+
try {
|
|
6114
|
+
const client = await this.getRedis();
|
|
6115
|
+
const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
|
|
6116
|
+
const keys = await this._scanKeys(client, pattern);
|
|
6117
|
+
if (keys.length > 0) await client.del(...keys);
|
|
6118
|
+
} catch (err) {
|
|
6119
|
+
this.logger.debug("clear: Redis unavailable", { error: err.message });
|
|
6120
|
+
}
|
|
6121
|
+
}
|
|
6122
|
+
void this.publishInvalidation(
|
|
6123
|
+
"del-glob",
|
|
6124
|
+
k ?? (this._namespace ? `${this._namespace}:*` : "*"),
|
|
6125
|
+
void 0,
|
|
6126
|
+
false,
|
|
6127
|
+
true
|
|
6128
|
+
);
|
|
6129
|
+
} catch (err) {
|
|
6130
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6131
|
+
span.recordException?.(err);
|
|
6132
|
+
throw err;
|
|
6133
|
+
} finally {
|
|
6134
|
+
span.end();
|
|
4121
6135
|
}
|
|
4122
|
-
void this.publishInvalidation(
|
|
4123
|
-
"del-glob",
|
|
4124
|
-
k ?? (this._namespace ? `${this._namespace}:*` : "*")
|
|
4125
|
-
);
|
|
4126
6136
|
}
|
|
4127
6137
|
/**
|
|
4128
6138
|
* Evict L1 entries that violate the current category or global capacity limits.
|
|
@@ -4253,7 +6263,7 @@ var CacheService = class _CacheService {
|
|
|
4253
6263
|
const now = Date.now();
|
|
4254
6264
|
if (entry.expiresAt <= now) return null;
|
|
4255
6265
|
if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
|
|
4256
|
-
return entry.value !== void 0 ? entry.value :
|
|
6266
|
+
return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
4257
6267
|
}
|
|
4258
6268
|
/**
|
|
4259
6269
|
* Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
|
|
@@ -4273,8 +6283,12 @@ var CacheService = class _CacheService {
|
|
|
4273
6283
|
if (this.opts.frozen) deepFreeze(val);
|
|
4274
6284
|
return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
|
|
4275
6285
|
}
|
|
4276
|
-
if (!this._diskDisabled) {
|
|
6286
|
+
if (!this._diskDisabled && this.watchdog.isDiskAllowed()) {
|
|
6287
|
+
const diskStart = performance.now();
|
|
4277
6288
|
const diskHit = this.disk.load(k);
|
|
6289
|
+
const diskElapsed = performance.now() - diskStart;
|
|
6290
|
+
this.watchdog.recordDisk(diskElapsed);
|
|
6291
|
+
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
4278
6292
|
if (diskHit !== null) {
|
|
4279
6293
|
const promoted = this.l1.importEntries(
|
|
4280
6294
|
[{ key: k, entry: diskHit }],
|
|
@@ -4295,7 +6309,10 @@ var CacheService = class _CacheService {
|
|
|
4295
6309
|
if (!this._redisDisabled && !this.cb.isOpen) {
|
|
4296
6310
|
try {
|
|
4297
6311
|
const client = await this.getRedis();
|
|
6312
|
+
const redisStart = performance.now();
|
|
4298
6313
|
const raw = await client.get(k);
|
|
6314
|
+
const redisElapsed = performance.now() - redisStart;
|
|
6315
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
4299
6316
|
if (raw !== null) {
|
|
4300
6317
|
const parsed = await this._decryptAndDeserialize(raw);
|
|
4301
6318
|
this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
|
|
@@ -4322,90 +6339,129 @@ var CacheService = class _CacheService {
|
|
|
4322
6339
|
* `(key) => number` so heterogeneous TTLs can be batched in one call.
|
|
4323
6340
|
*/
|
|
4324
6341
|
async mget(keys, fetchFn, ttl = 300, priority) {
|
|
4325
|
-
const
|
|
4326
|
-
|
|
4327
|
-
|
|
4328
|
-
for (let i = 0; i < keys.length; i++) {
|
|
4329
|
-
const k = this.nk(keys[i]);
|
|
4330
|
-
const entry = this.l1.getEntry(k);
|
|
4331
|
-
if (entry && entry.expiresAt > Date.now()) {
|
|
4332
|
-
result[i] = entry.value !== void 0 ? entry.value : (0, import_msgpackr3.unpack)(entry.data);
|
|
4333
|
-
this.counters.l1Hits++;
|
|
4334
|
-
} else {
|
|
4335
|
-
missIndexes.push(i);
|
|
4336
|
-
missKeys.push(keys[i]);
|
|
4337
|
-
}
|
|
6342
|
+
const span = this._startSpan("tricache.mget");
|
|
6343
|
+
if (this.opts.tracer) {
|
|
6344
|
+
span.setAttribute("cache.batch.size", keys.length);
|
|
4338
6345
|
}
|
|
4339
|
-
|
|
4340
|
-
|
|
4341
|
-
|
|
4342
|
-
|
|
4343
|
-
|
|
4344
|
-
const
|
|
4345
|
-
|
|
4346
|
-
|
|
4347
|
-
|
|
4348
|
-
|
|
4349
|
-
|
|
4350
|
-
|
|
4351
|
-
|
|
4352
|
-
|
|
4353
|
-
|
|
4354
|
-
|
|
4355
|
-
|
|
4356
|
-
|
|
4357
|
-
|
|
4358
|
-
|
|
4359
|
-
|
|
6346
|
+
try {
|
|
6347
|
+
const result = Array.from({ length: keys.length });
|
|
6348
|
+
const missIndexes = [];
|
|
6349
|
+
const missKeys = [];
|
|
6350
|
+
for (let i = 0; i < keys.length; i++) {
|
|
6351
|
+
const k = this.nk(keys[i]);
|
|
6352
|
+
const entry = this.l1.getEntry(k);
|
|
6353
|
+
if (entry && entry.expiresAt > Date.now()) {
|
|
6354
|
+
result[i] = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
6355
|
+
this.counters.l1Hits++;
|
|
6356
|
+
} else {
|
|
6357
|
+
missIndexes.push(i);
|
|
6358
|
+
missKeys.push(keys[i]);
|
|
6359
|
+
}
|
|
6360
|
+
}
|
|
6361
|
+
if (missKeys.length === 0) {
|
|
6362
|
+
if (this.opts.tracer) {
|
|
6363
|
+
span.setAttribute("cache.hits", keys.length);
|
|
6364
|
+
span.setAttribute("cache.misses", 0);
|
|
6365
|
+
span.setAttribute("cache.l1_hits", keys.length);
|
|
6366
|
+
span.setAttribute("cache.l2_hits", 0);
|
|
6367
|
+
}
|
|
6368
|
+
return result;
|
|
6369
|
+
}
|
|
6370
|
+
let l2HitCount = 0;
|
|
6371
|
+
if (!this._redisDisabled) {
|
|
6372
|
+
try {
|
|
6373
|
+
const client = await this.getRedis();
|
|
6374
|
+
const nsKeys = missKeys.map((k) => this.nk(k));
|
|
6375
|
+
const pipeline = client.multi();
|
|
6376
|
+
for (const nk of nsKeys) pipeline.get(nk);
|
|
6377
|
+
const redisStart = performance.now();
|
|
6378
|
+
const raws = await pipeline.exec();
|
|
6379
|
+
const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
|
|
6380
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
6381
|
+
this.cb.onSuccess();
|
|
6382
|
+
for (let j = 0; j < missKeys.length; j++) {
|
|
6383
|
+
const raw = raws[j] ? raws[j][1] : null;
|
|
6384
|
+
const idx = missIndexes[j];
|
|
6385
|
+
if (raw) {
|
|
6386
|
+
const parsed = await this._decryptAndDeserialize(raw);
|
|
6387
|
+
const k = nsKeys[j];
|
|
6388
|
+
const p = priority ?? inferPriority(missKeys[j]);
|
|
6389
|
+
this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
|
|
6390
|
+
this.counters.l2Hits++;
|
|
6391
|
+
l2HitCount++;
|
|
6392
|
+
result[idx] = parsed;
|
|
6393
|
+
missIndexes[j] = -1;
|
|
6394
|
+
missKeys[j] = "";
|
|
6395
|
+
}
|
|
4360
6396
|
}
|
|
6397
|
+
const remainingIdx = missIndexes.filter((i) => i >= 0);
|
|
6398
|
+
const remainingKeys = missKeys.filter((k) => k !== "");
|
|
6399
|
+
missIndexes.length = 0;
|
|
6400
|
+
missKeys.length = 0;
|
|
6401
|
+
missIndexes.push(...remainingIdx);
|
|
6402
|
+
missKeys.push(...remainingKeys);
|
|
6403
|
+
} catch (err) {
|
|
6404
|
+
this.cb.onFailure();
|
|
6405
|
+
this.logger.debug("mget: Redis unavailable, continuing to disk/fetch", { error: err.message });
|
|
4361
6406
|
}
|
|
4362
|
-
const remainingIdx = missIndexes.filter((i) => i >= 0);
|
|
4363
|
-
const remainingKeys = missKeys.filter((k) => k !== "");
|
|
4364
|
-
missIndexes.length = 0;
|
|
4365
|
-
missKeys.length = 0;
|
|
4366
|
-
missIndexes.push(...remainingIdx);
|
|
4367
|
-
missKeys.push(...remainingKeys);
|
|
4368
|
-
if (missKeys.length === 0) return result;
|
|
4369
|
-
} catch (err) {
|
|
4370
|
-
this.cb.onFailure();
|
|
4371
|
-
this.logger.debug("mget: Redis unavailable, continuing to disk/fetch", { error: err.message });
|
|
4372
6407
|
}
|
|
4373
|
-
|
|
4374
|
-
|
|
4375
|
-
|
|
4376
|
-
|
|
4377
|
-
|
|
4378
|
-
|
|
4379
|
-
const
|
|
4380
|
-
|
|
4381
|
-
|
|
4382
|
-
)
|
|
4383
|
-
|
|
4384
|
-
|
|
4385
|
-
|
|
4386
|
-
|
|
4387
|
-
|
|
4388
|
-
|
|
4389
|
-
|
|
6408
|
+
if (!this._diskDisabled && missKeys.length > 0) {
|
|
6409
|
+
for (let j = missKeys.length - 1; j >= 0; j--) {
|
|
6410
|
+
if (!this.watchdog.isDiskAllowed()) continue;
|
|
6411
|
+
const k = this.nk(missKeys[j]);
|
|
6412
|
+
const diskStart = performance.now();
|
|
6413
|
+
const diskHit = this.disk.load(k);
|
|
6414
|
+
const diskElapsed = performance.now() - diskStart;
|
|
6415
|
+
this.watchdog.recordDisk(diskElapsed);
|
|
6416
|
+
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
6417
|
+
if (diskHit !== null) {
|
|
6418
|
+
const promoted = this.l1.importEntries(
|
|
6419
|
+
[{ key: k, entry: diskHit }],
|
|
6420
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
6421
|
+
);
|
|
6422
|
+
if (promoted > 0) {
|
|
6423
|
+
const l1Check = this.l1.get(k);
|
|
6424
|
+
if (l1Check !== null) {
|
|
6425
|
+
this.counters.diskHits++;
|
|
6426
|
+
result[missIndexes[j]] = l1Check.value;
|
|
6427
|
+
missIndexes.splice(j, 1);
|
|
6428
|
+
missKeys.splice(j, 1);
|
|
6429
|
+
}
|
|
4390
6430
|
}
|
|
4391
6431
|
}
|
|
4392
6432
|
}
|
|
4393
6433
|
}
|
|
4394
|
-
if (missKeys.length
|
|
4395
|
-
|
|
4396
|
-
|
|
4397
|
-
|
|
4398
|
-
|
|
4399
|
-
|
|
4400
|
-
|
|
4401
|
-
|
|
4402
|
-
|
|
4403
|
-
|
|
4404
|
-
|
|
6434
|
+
if (missKeys.length > 0) {
|
|
6435
|
+
this.counters.fetches++;
|
|
6436
|
+
const fetched = await fetchFn(missKeys);
|
|
6437
|
+
const setPromises = [];
|
|
6438
|
+
for (let j = 0; j < missKeys.length; j++) {
|
|
6439
|
+
const v = fetched[missKeys[j]];
|
|
6440
|
+
result[missIndexes[j]] = v;
|
|
6441
|
+
if (v !== void 0) {
|
|
6442
|
+
const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
|
|
6443
|
+
setPromises.push(this.set(missKeys[j], v, resolvedTtl, priority));
|
|
6444
|
+
}
|
|
4405
6445
|
}
|
|
6446
|
+
if (setPromises.length > 0) {
|
|
6447
|
+
await Promise.all(setPromises);
|
|
6448
|
+
}
|
|
6449
|
+
}
|
|
6450
|
+
if (this.opts.tracer) {
|
|
6451
|
+
const finalMisses = missKeys.length;
|
|
6452
|
+
const totalHits = keys.length - finalMisses;
|
|
6453
|
+
span.setAttribute("cache.hits", totalHits);
|
|
6454
|
+
span.setAttribute("cache.misses", finalMisses);
|
|
6455
|
+
span.setAttribute("cache.l2_hits", l2HitCount);
|
|
4406
6456
|
}
|
|
6457
|
+
return result;
|
|
6458
|
+
} catch (err) {
|
|
6459
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6460
|
+
span.recordException?.(err);
|
|
6461
|
+
throw err;
|
|
6462
|
+
} finally {
|
|
6463
|
+
span.end();
|
|
4407
6464
|
}
|
|
4408
|
-
return result;
|
|
4409
6465
|
}
|
|
4410
6466
|
/**
|
|
4411
6467
|
* Returns a Promise that resolves once the cache is fully initialised and any
|
|
@@ -4432,12 +6488,24 @@ var CacheService = class _CacheService {
|
|
|
4432
6488
|
* });
|
|
4433
6489
|
*/
|
|
4434
6490
|
async mset(entries) {
|
|
6491
|
+
const span = this._startSpan("tricache.mset");
|
|
4435
6492
|
const keys = Object.keys(entries);
|
|
4436
|
-
|
|
4437
|
-
|
|
4438
|
-
|
|
4439
|
-
|
|
4440
|
-
|
|
6493
|
+
if (this.opts.tracer) {
|
|
6494
|
+
span.setAttribute("cache.batch.size", keys.length);
|
|
6495
|
+
}
|
|
6496
|
+
try {
|
|
6497
|
+
await Promise.all(keys.map((key) => {
|
|
6498
|
+
const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
|
|
6499
|
+
const hasOpts = tags?.length || dependsOn?.length;
|
|
6500
|
+
return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
|
|
6501
|
+
}));
|
|
6502
|
+
} catch (err) {
|
|
6503
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6504
|
+
span.recordException?.(err);
|
|
6505
|
+
throw err;
|
|
6506
|
+
} finally {
|
|
6507
|
+
span.end();
|
|
6508
|
+
}
|
|
4441
6509
|
}
|
|
4442
6510
|
/**
|
|
4443
6511
|
* Batch delete — delete multiple exact keys in a single call.
|
|
@@ -4447,7 +6515,19 @@ var CacheService = class _CacheService {
|
|
|
4447
6515
|
* await cache.mdel(['user:1', 'user:2', 'user:3']);
|
|
4448
6516
|
*/
|
|
4449
6517
|
async mdel(keys) {
|
|
4450
|
-
|
|
6518
|
+
const span = this._startSpan("tricache.mdel");
|
|
6519
|
+
if (this.opts.tracer) {
|
|
6520
|
+
span.setAttribute("cache.batch.size", keys.length);
|
|
6521
|
+
}
|
|
6522
|
+
try {
|
|
6523
|
+
await Promise.all(keys.map((k) => this.delete(k)));
|
|
6524
|
+
} catch (err) {
|
|
6525
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6526
|
+
span.recordException?.(err);
|
|
6527
|
+
throw err;
|
|
6528
|
+
} finally {
|
|
6529
|
+
span.end();
|
|
6530
|
+
}
|
|
4451
6531
|
}
|
|
4452
6532
|
/**
|
|
4453
6533
|
* Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
|
|
@@ -4476,7 +6556,6 @@ var CacheService = class _CacheService {
|
|
|
4476
6556
|
const results = await pl.exec();
|
|
4477
6557
|
this.cb.onSuccess();
|
|
4478
6558
|
let loaded = 0;
|
|
4479
|
-
const now = Date.now();
|
|
4480
6559
|
for (let i = 0; i < matchedKeys.length; i++) {
|
|
4481
6560
|
const [err, raw] = results[i];
|
|
4482
6561
|
if (err || raw == null) continue;
|
|
@@ -4488,7 +6567,6 @@ var CacheService = class _CacheService {
|
|
|
4488
6567
|
} catch {
|
|
4489
6568
|
}
|
|
4490
6569
|
}
|
|
4491
|
-
void now;
|
|
4492
6570
|
this.logger.info("warmFromL2 complete", {
|
|
4493
6571
|
pattern,
|
|
4494
6572
|
matched: matchedKeys.length,
|
|
@@ -4510,45 +6588,58 @@ var CacheService = class _CacheService {
|
|
|
4510
6588
|
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
4511
6589
|
*/
|
|
4512
6590
|
async invalidateTag(tag) {
|
|
4513
|
-
|
|
4514
|
-
|
|
6591
|
+
const span = this._startSpan("tricache.invalidate_tag");
|
|
6592
|
+
if (this.opts.tracer) {
|
|
6593
|
+
span.setAttribute("cache.tag", tag);
|
|
6594
|
+
span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
|
|
6595
|
+
}
|
|
6596
|
+
try {
|
|
6597
|
+
if (this.opts.tagStrategy === "generational") {
|
|
6598
|
+
let newVer = 1;
|
|
6599
|
+
if (!this._redisDisabled) {
|
|
6600
|
+
try {
|
|
6601
|
+
const client = await this.getRedis();
|
|
6602
|
+
newVer = await client.incr(this.nk(`tag_ver:${tag}`));
|
|
6603
|
+
} catch (err) {
|
|
6604
|
+
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
6605
|
+
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
6606
|
+
newVer = current + 1;
|
|
6607
|
+
}
|
|
6608
|
+
} else {
|
|
6609
|
+
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
6610
|
+
newVer = current + 1;
|
|
6611
|
+
}
|
|
6612
|
+
this._setLocalTagVersion(tag, newVer, Date.now());
|
|
6613
|
+
void this.publishInvalidation("tag_incr", tag, newVer, false, true);
|
|
6614
|
+
return;
|
|
6615
|
+
}
|
|
6616
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
6617
|
+
const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
|
|
6618
|
+
for (const k of members) {
|
|
6619
|
+
this.l1.delete(k);
|
|
6620
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
6621
|
+
}
|
|
6622
|
+
this.tagIndex.delete(tagKey);
|
|
4515
6623
|
if (!this._redisDisabled) {
|
|
4516
6624
|
try {
|
|
4517
6625
|
const client = await this.getRedis();
|
|
4518
|
-
|
|
6626
|
+
const redisMembers = await client.smembers(tagKey);
|
|
6627
|
+
const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
|
|
6628
|
+
if (toDelete.length > 0) {
|
|
6629
|
+
await client.del(...toDelete, tagKey);
|
|
6630
|
+
} else {
|
|
6631
|
+
await client.del(tagKey);
|
|
6632
|
+
}
|
|
4519
6633
|
} catch (err) {
|
|
4520
6634
|
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
4521
|
-
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
4522
|
-
newVer = current + 1;
|
|
4523
|
-
}
|
|
4524
|
-
} else {
|
|
4525
|
-
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
4526
|
-
newVer = current + 1;
|
|
4527
|
-
}
|
|
4528
|
-
this._setLocalTagVersion(tag, newVer, Date.now());
|
|
4529
|
-
void this.publishInvalidation("tag_incr", tag, newVer);
|
|
4530
|
-
return;
|
|
4531
|
-
}
|
|
4532
|
-
const tagKey = this.nk(`_tag_:${tag}`);
|
|
4533
|
-
const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
|
|
4534
|
-
for (const k of members) {
|
|
4535
|
-
this.l1.delete(k);
|
|
4536
|
-
if (!this._diskDisabled) this.disk.delete(k);
|
|
4537
|
-
}
|
|
4538
|
-
this.tagIndex.delete(tagKey);
|
|
4539
|
-
if (!this._redisDisabled) {
|
|
4540
|
-
try {
|
|
4541
|
-
const client = await this.getRedis();
|
|
4542
|
-
const redisMembers = await client.smembers(tagKey);
|
|
4543
|
-
const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
|
|
4544
|
-
if (toDelete.length > 0) {
|
|
4545
|
-
await client.del(...toDelete, tagKey);
|
|
4546
|
-
} else {
|
|
4547
|
-
await client.del(tagKey);
|
|
4548
6635
|
}
|
|
4549
|
-
} catch (err) {
|
|
4550
|
-
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
4551
6636
|
}
|
|
6637
|
+
} catch (err) {
|
|
6638
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6639
|
+
span.recordException?.(err);
|
|
6640
|
+
throw err;
|
|
6641
|
+
} finally {
|
|
6642
|
+
span.end();
|
|
4552
6643
|
}
|
|
4553
6644
|
}
|
|
4554
6645
|
/**
|
|
@@ -4581,7 +6672,7 @@ var CacheService = class _CacheService {
|
|
|
4581
6672
|
const [err, newVer] = results[i] ?? [null, null];
|
|
4582
6673
|
const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
|
|
4583
6674
|
this._setLocalTagVersion(tags[i], ver, now);
|
|
4584
|
-
void this.publishInvalidation("tag_incr", tags[i], ver);
|
|
6675
|
+
void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
|
|
4585
6676
|
}
|
|
4586
6677
|
return;
|
|
4587
6678
|
} catch (err) {
|
|
@@ -4591,7 +6682,7 @@ var CacheService = class _CacheService {
|
|
|
4591
6682
|
for (const tag of tags) {
|
|
4592
6683
|
const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
4593
6684
|
this._setLocalTagVersion(tag, ver, now);
|
|
4594
|
-
void this.publishInvalidation("tag_incr", tag, ver);
|
|
6685
|
+
void this.publishInvalidation("tag_incr", tag, ver, false, true);
|
|
4595
6686
|
}
|
|
4596
6687
|
return;
|
|
4597
6688
|
}
|
|
@@ -4662,6 +6753,60 @@ var CacheService = class _CacheService {
|
|
|
4662
6753
|
}
|
|
4663
6754
|
return { l1, disk, l2 };
|
|
4664
6755
|
}
|
|
6756
|
+
/**
|
|
6757
|
+
* Health and readiness diagnostics for container orchestrators (e.g. Kubernetes, ECS, Nomad).
|
|
6758
|
+
*
|
|
6759
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
6760
|
+
* ⚠️ CRITICAL CONTAINER PROBE SEMANTICS (Liveness vs. Readiness):
|
|
6761
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
6762
|
+
* ❌ NEVER bind `degraded` checks or `cache.health()` to your Liveness Probe (/livez, /healthz).
|
|
6763
|
+
* If an SRE hooks degraded status into liveness, a storage-starved or EBS-throttled pod
|
|
6764
|
+
* will be killed by the kubelet, triggering a cluster-wide cascading restart shockwave.
|
|
6765
|
+
* Liveness probes must only check that the event loop / process is alive.
|
|
6766
|
+
*
|
|
6767
|
+
* ✅ BIND degraded checks strictly to your Readiness Probe (/ready, /readyz).
|
|
6768
|
+
* A degraded cache (e.g. EBS latency spike, quota watermark pruning, or open Redis circuit)
|
|
6769
|
+
* can shed traffic at the ingress load balancer while the Node.js process remains
|
|
6770
|
+
* alive to drain in-flight promises and heal its local storage.
|
|
6771
|
+
*
|
|
6772
|
+
* By default, `healthy` remains `true` even when degraded (graceful local degradation).
|
|
6773
|
+
* Set `failReadinessOnDegraded: true` in CacheOptions if you want your Readiness probe
|
|
6774
|
+
* to route ingress traffic away while degraded.
|
|
6775
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
6776
|
+
*/
|
|
6777
|
+
health() {
|
|
6778
|
+
const watchdogTel = this.watchdog.getTelemetry();
|
|
6779
|
+
const diskPruning = !this._diskDisabled && this.disk.isPruning;
|
|
6780
|
+
const diskLowSpace = !this._diskDisabled && this.disk.hostVolumeLowSpace;
|
|
6781
|
+
const circuitOpen = this.cb.isOpen;
|
|
6782
|
+
const latencyBypass = watchdogTel.bypassActive;
|
|
6783
|
+
const degraded = circuitOpen || latencyBypass || diskPruning || diskLowSpace;
|
|
6784
|
+
const healthy = this.opts.failReadinessOnDegraded ? !degraded : true;
|
|
6785
|
+
const reasons = [];
|
|
6786
|
+
if (circuitOpen) reasons.push("redis_circuit_breaker_open");
|
|
6787
|
+
if (latencyBypass) reasons.push(`disk_latency_bypass_stage_${watchdogTel.bypassStage}`);
|
|
6788
|
+
if (diskPruning) reasons.push("disk_quota_watermark_pruning_active");
|
|
6789
|
+
if (diskLowSpace) reasons.push("disk_host_volume_low_space");
|
|
6790
|
+
return {
|
|
6791
|
+
healthy,
|
|
6792
|
+
degraded,
|
|
6793
|
+
reasons,
|
|
6794
|
+
details: {
|
|
6795
|
+
redisConnected: !circuitOpen && !this._redisDisabled,
|
|
6796
|
+
circuitBreakerState: this.cb.currentState,
|
|
6797
|
+
diskPruningActive: diskPruning,
|
|
6798
|
+
diskHostVolumeLowSpace: diskLowSpace,
|
|
6799
|
+
watchdog: watchdogTel
|
|
6800
|
+
}
|
|
6801
|
+
};
|
|
6802
|
+
}
|
|
6803
|
+
/**
|
|
6804
|
+
* Direct access to the internal tier latency watchdog instance.
|
|
6805
|
+
* Used for diagnostics, canary probes, and control-loop tuning.
|
|
6806
|
+
*/
|
|
6807
|
+
getLatencyWatchdog() {
|
|
6808
|
+
return this.watchdog;
|
|
6809
|
+
}
|
|
4665
6810
|
/**
|
|
4666
6811
|
* Export all live L1 entries to Redis via a single pipeline.
|
|
4667
6812
|
* Useful for warming a new Redis instance or for zero-downtime failover.
|
|
@@ -4909,7 +7054,7 @@ var CacheService = class _CacheService {
|
|
|
4909
7054
|
if (visited.has(dep)) continue;
|
|
4910
7055
|
this.l1.delete(dep);
|
|
4911
7056
|
if (!this._diskDisabled) this.disk.delete(dep);
|
|
4912
|
-
void this.publishInvalidation("del", dep);
|
|
7057
|
+
void this.publishInvalidation("del", dep, void 0, false, true);
|
|
4913
7058
|
this.logger.debug("Dependency cascade: invalidated dependent key", {
|
|
4914
7059
|
trigger: deletedKey.slice(0, 60),
|
|
4915
7060
|
dependent: dep.slice(0, 60)
|
|
@@ -4974,12 +7119,36 @@ var CacheService = class _CacheService {
|
|
|
4974
7119
|
evictions: c.oomEvictions,
|
|
4975
7120
|
lastTriggeredAt: c.oomLastAt
|
|
4976
7121
|
},
|
|
7122
|
+
...this.opts.remoteSnapshot && {
|
|
7123
|
+
remoteSnapshot: {
|
|
7124
|
+
enabled: true,
|
|
7125
|
+
uploads: c.remoteSnapshotUploads,
|
|
7126
|
+
downloads: c.remoteSnapshotDownloads,
|
|
7127
|
+
errors: c.remoteSnapshotErrors,
|
|
7128
|
+
lastUploadedAt: c.remoteSnapshotLastUploadedAt,
|
|
7129
|
+
lastDownloadedAt: c.remoteSnapshotLastDownloadedAt
|
|
7130
|
+
}
|
|
7131
|
+
},
|
|
7132
|
+
...this.opts.crossRegion && {
|
|
7133
|
+
crossRegion: {
|
|
7134
|
+
enabled: true,
|
|
7135
|
+
currentRegion: this.opts.crossRegion.currentRegion,
|
|
7136
|
+
sent: c.crossRegionSent,
|
|
7137
|
+
received: c.crossRegionReceived,
|
|
7138
|
+
deduplicated: c.crossRegionDeduplicated,
|
|
7139
|
+
errors: c.crossRegionErrors
|
|
7140
|
+
}
|
|
7141
|
+
},
|
|
4977
7142
|
l1: {
|
|
4978
7143
|
entries: l1s.entries,
|
|
4979
7144
|
sizeBytes: this.l1.memoryUsage,
|
|
4980
7145
|
maxBytes: this.opts.l1MaxBytes
|
|
4981
7146
|
},
|
|
4982
|
-
disk: {
|
|
7147
|
+
disk: {
|
|
7148
|
+
...this.disk.stats,
|
|
7149
|
+
disabled: this._diskDisabled,
|
|
7150
|
+
latencyWatchdog: this.watchdog.getTelemetry()
|
|
7151
|
+
},
|
|
4983
7152
|
...this.latencyTracker && {
|
|
4984
7153
|
adaptiveTtl: {
|
|
4985
7154
|
enabled: true,
|
|
@@ -4992,9 +7161,16 @@ var CacheService = class _CacheService {
|
|
|
4992
7161
|
this.opts.adaptiveTtlMaxMs
|
|
4993
7162
|
)
|
|
4994
7163
|
}
|
|
7164
|
+
},
|
|
7165
|
+
...this.pipeliner && {
|
|
7166
|
+
pipelining: this.pipeliner.stats
|
|
4995
7167
|
}
|
|
4996
7168
|
};
|
|
4997
7169
|
}
|
|
7170
|
+
/** Return auto-pipelining metrics, or null if pipelining is disabled. */
|
|
7171
|
+
getPipelinerStats() {
|
|
7172
|
+
return this.pipeliner ? this.pipeliner.stats : null;
|
|
7173
|
+
}
|
|
4998
7174
|
/**
|
|
4999
7175
|
* Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
|
|
5000
7176
|
* Paste the result into your `/metrics` endpoint.
|
|
@@ -5034,6 +7210,18 @@ var CacheService = class _CacheService {
|
|
|
5034
7210
|
gauge("l1_entries", m.l1.entries, "Current L1 entry count");
|
|
5035
7211
|
gauge("l1_size_bytes", m.l1.sizeBytes, "Current L1 used bytes");
|
|
5036
7212
|
gauge("disk_files", m.disk.files, "Current L1.5 disk file count");
|
|
7213
|
+
if (m.disk.latencyWatchdog) {
|
|
7214
|
+
gauge("disk_latency_bypass_stage", m.disk.latencyWatchdog.bypassStage, "Disk latency watchdog bypass stage (0: normal, 1: 25%, 2: 75%, 3: 100%)");
|
|
7215
|
+
gauge("disk_p95_ms", m.disk.latencyWatchdog.diskP95Ms, "Disk read p95 latency in ms");
|
|
7216
|
+
gauge("redis_p95_ms", m.disk.latencyWatchdog.redisP95Ms, "Redis read p95 latency in ms");
|
|
7217
|
+
counter("disk_bypassed_events", m.disk.latencyWatchdog.bypassedTotal, "Total disk bypass activation events");
|
|
7218
|
+
}
|
|
7219
|
+
if (m.disk.pruning) {
|
|
7220
|
+
counter("disk_spills_shed", m.disk.pruning.spillsShedTotal, "Total disk spills shed due to pruning or low disk space");
|
|
7221
|
+
counter("disk_prune_rounds", m.disk.pruning.pruneRounds, "Total high-watermark disk prune rounds");
|
|
7222
|
+
counter("disk_entries_pruned", m.disk.pruning.entriesPruned, "Total entries removed by watermark pruning");
|
|
7223
|
+
counter("disk_low_space_pauses", m.disk.pruning.hostVolumeLowSpacePauses, "Total times spills paused due to <10% host volume space");
|
|
7224
|
+
}
|
|
5037
7225
|
gauge(
|
|
5038
7226
|
"bloom_false_positive_rate",
|
|
5039
7227
|
m.bloom.falsePositiveRate,
|
|
@@ -5055,6 +7243,17 @@ var CacheService = class _CacheService {
|
|
|
5055
7243
|
"Emergency L1 eviction rounds triggered by heap pressure"
|
|
5056
7244
|
);
|
|
5057
7245
|
}
|
|
7246
|
+
if (m.remoteSnapshot?.enabled) {
|
|
7247
|
+
counter("remote_snapshot_uploads", m.remoteSnapshot.uploads, "Total remote snapshot uploads");
|
|
7248
|
+
counter("remote_snapshot_downloads", m.remoteSnapshot.downloads, "Total remote snapshot downloads");
|
|
7249
|
+
counter("remote_snapshot_errors", m.remoteSnapshot.errors, "Total remote snapshot errors");
|
|
7250
|
+
}
|
|
7251
|
+
if (m.crossRegion?.enabled) {
|
|
7252
|
+
counter("cross_region_sent", m.crossRegion.sent, "Total cross-region invalidations broadcast");
|
|
7253
|
+
counter("cross_region_received", m.crossRegion.received, "Total cross-region invalidations received");
|
|
7254
|
+
counter("cross_region_deduplicated", m.crossRegion.deduplicated, "Total cross-region invalidations deduplicated or self-filtered");
|
|
7255
|
+
counter("cross_region_errors", m.crossRegion.errors, "Total cross-region relay errors");
|
|
7256
|
+
}
|
|
5058
7257
|
return lines.join("\n");
|
|
5059
7258
|
}
|
|
5060
7259
|
// ── Lifecycle ────────────────────────────────────────────────────────────
|
|
@@ -5073,23 +7272,31 @@ var CacheService = class _CacheService {
|
|
|
5073
7272
|
/** Close Redis connections and stop all background timers. */
|
|
5074
7273
|
async destroy() {
|
|
5075
7274
|
this._destroyed = true;
|
|
7275
|
+
const g = globalThis;
|
|
7276
|
+
const key = _CacheService.globalKey(this.opts);
|
|
7277
|
+
if (g[key] === this) {
|
|
7278
|
+
delete g[key];
|
|
7279
|
+
}
|
|
5076
7280
|
if (this.cleanupInterval) clearInterval(this.cleanupInterval);
|
|
5077
7281
|
if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
|
|
5078
7282
|
if (this.oomInterval) clearInterval(this.oomInterval);
|
|
5079
7283
|
if (this.metricsInterval) clearInterval(this.metricsInterval);
|
|
5080
|
-
if (this.
|
|
5081
|
-
|
|
5082
|
-
|
|
5083
|
-
this._shutdownHandler = null;
|
|
7284
|
+
if (this.remoteSnapshotInterval) {
|
|
7285
|
+
clearInterval(this.remoteSnapshotInterval);
|
|
7286
|
+
this.remoteSnapshotInterval = null;
|
|
5084
7287
|
}
|
|
7288
|
+
ProcessTerminationBus.unregister(this);
|
|
7289
|
+
this._shutdownHandler = null;
|
|
5085
7290
|
if (this._workerPool) {
|
|
5086
7291
|
await this._workerPool.destroy();
|
|
5087
7292
|
this._workerPool = null;
|
|
5088
7293
|
}
|
|
5089
7294
|
if (this.subClient) {
|
|
5090
|
-
|
|
5091
|
-
|
|
5092
|
-
|
|
7295
|
+
if (!this.opts.redisSubClient) {
|
|
7296
|
+
try {
|
|
7297
|
+
this.subClient.disconnect();
|
|
7298
|
+
} catch {
|
|
7299
|
+
}
|
|
5093
7300
|
}
|
|
5094
7301
|
this.subClient = null;
|
|
5095
7302
|
}
|
|
@@ -5101,14 +7308,33 @@ var CacheService = class _CacheService {
|
|
|
5101
7308
|
this.streamClient = null;
|
|
5102
7309
|
}
|
|
5103
7310
|
if (this.redis) {
|
|
5104
|
-
|
|
5105
|
-
|
|
5106
|
-
|
|
7311
|
+
if (!this.opts.redisClient) {
|
|
7312
|
+
try {
|
|
7313
|
+
await this.redis.disconnect();
|
|
7314
|
+
} catch {
|
|
7315
|
+
}
|
|
5107
7316
|
}
|
|
5108
7317
|
this.redis = null;
|
|
5109
7318
|
}
|
|
7319
|
+
if (this._ipcServer) {
|
|
7320
|
+
await this._ipcServer.close();
|
|
7321
|
+
this._ipcServer = void 0;
|
|
7322
|
+
}
|
|
5110
7323
|
if (!this._diskDisabled) this.disk.close();
|
|
5111
7324
|
}
|
|
7325
|
+
/**
|
|
7326
|
+
* Return the active IPC telemetry server instance, if enabled.
|
|
7327
|
+
*/
|
|
7328
|
+
getIpcServer() {
|
|
7329
|
+
return this._ipcServer;
|
|
7330
|
+
}
|
|
7331
|
+
/**
|
|
7332
|
+
* Return real-time telemetry and metrics for the Window TinyLFU admission policy.
|
|
7333
|
+
* Returns `undefined` if W-TinyLFU admission is not active.
|
|
7334
|
+
*/
|
|
7335
|
+
getWTinyLfuStats() {
|
|
7336
|
+
return this.l1.getWTinyLfuStats();
|
|
7337
|
+
}
|
|
5112
7338
|
};
|
|
5113
7339
|
|
|
5114
7340
|
// src/cli.ts
|
|
@@ -5119,6 +7345,11 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
5119
7345
|
namespace: { type: "string", short: "n" },
|
|
5120
7346
|
prefix: { type: "string" },
|
|
5121
7347
|
disk: { type: "string", short: "d" },
|
|
7348
|
+
pid: { type: "string" },
|
|
7349
|
+
socket: { type: "string", short: "s" },
|
|
7350
|
+
interval: { type: "string", short: "i" },
|
|
7351
|
+
once: { type: "boolean" },
|
|
7352
|
+
json: { type: "boolean" },
|
|
5122
7353
|
help: { type: "boolean", short: "h" },
|
|
5123
7354
|
version: { type: "boolean", short: "v" }
|
|
5124
7355
|
};
|
|
@@ -5143,7 +7374,89 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
5143
7374
|
return;
|
|
5144
7375
|
}
|
|
5145
7376
|
if (values.version || command === "version") {
|
|
5146
|
-
console.log("tricache v0.
|
|
7377
|
+
console.log("tricache v0.8.0");
|
|
7378
|
+
return;
|
|
7379
|
+
}
|
|
7380
|
+
if (command === "top") {
|
|
7381
|
+
let targetSocket = typeof values.socket === "string" ? values.socket : void 0;
|
|
7382
|
+
if (!targetSocket && typeof values.pid === "string") {
|
|
7383
|
+
targetSocket = resolveIpcSocketPath(values.pid);
|
|
7384
|
+
}
|
|
7385
|
+
if (!targetSocket) {
|
|
7386
|
+
const active = await findActiveSockets();
|
|
7387
|
+
if (active.length > 0) {
|
|
7388
|
+
targetSocket = active[0];
|
|
7389
|
+
} else {
|
|
7390
|
+
targetSocket = resolveIpcSocketPath(process.pid);
|
|
7391
|
+
}
|
|
7392
|
+
}
|
|
7393
|
+
const client = new IpcTelemetryClient(targetSocket);
|
|
7394
|
+
const intervalMs = typeof values.interval === "string" ? Math.max(200, parseInt(values.interval, 10)) : 1e3;
|
|
7395
|
+
const isOnce = Boolean(values.once || !process.stdout.isTTY);
|
|
7396
|
+
const asJson = Boolean(values.json);
|
|
7397
|
+
if (isOnce) {
|
|
7398
|
+
try {
|
|
7399
|
+
const payload = await client.getMetrics();
|
|
7400
|
+
if (asJson) {
|
|
7401
|
+
console.log(JSON.stringify(payload, null, 2));
|
|
7402
|
+
} else {
|
|
7403
|
+
console.log(renderTopDashboard(payload));
|
|
7404
|
+
}
|
|
7405
|
+
return;
|
|
7406
|
+
} catch (err) {
|
|
7407
|
+
console.error(`Failed to connect to TriCache IPC at ${targetSocket}: ${err.message}`);
|
|
7408
|
+
process.exit(1);
|
|
7409
|
+
}
|
|
7410
|
+
}
|
|
7411
|
+
process.stdout.write("\x1B[?1049h\x1B[?25l");
|
|
7412
|
+
let activeInterval = null;
|
|
7413
|
+
let cleaningUp = false;
|
|
7414
|
+
const cleanup = () => {
|
|
7415
|
+
if (cleaningUp) return;
|
|
7416
|
+
cleaningUp = true;
|
|
7417
|
+
if (activeInterval) clearInterval(activeInterval);
|
|
7418
|
+
if (process.stdout.isTTY) {
|
|
7419
|
+
process.stdout.write("\x1B[?25h\x1B[?1049l");
|
|
7420
|
+
}
|
|
7421
|
+
if (process.stdin.isTTY && typeof process.stdin.setRawMode === "function") {
|
|
7422
|
+
try {
|
|
7423
|
+
process.stdin.setRawMode(false);
|
|
7424
|
+
process.stdin.pause();
|
|
7425
|
+
} catch {
|
|
7426
|
+
}
|
|
7427
|
+
}
|
|
7428
|
+
process.exit(0);
|
|
7429
|
+
};
|
|
7430
|
+
process.once("SIGINT", cleanup);
|
|
7431
|
+
process.once("SIGTERM", cleanup);
|
|
7432
|
+
if (process.stdin.isTTY && typeof process.stdin.setRawMode === "function") {
|
|
7433
|
+
try {
|
|
7434
|
+
process.stdin.setRawMode(true);
|
|
7435
|
+
process.stdin.resume();
|
|
7436
|
+
process.stdin.setEncoding("utf8");
|
|
7437
|
+
process.stdin.on("data", (key) => {
|
|
7438
|
+
if (key === "q" || key === "Q" || key === "") {
|
|
7439
|
+
cleanup();
|
|
7440
|
+
}
|
|
7441
|
+
});
|
|
7442
|
+
} catch {
|
|
7443
|
+
}
|
|
7444
|
+
}
|
|
7445
|
+
const tick = async () => {
|
|
7446
|
+
try {
|
|
7447
|
+
const payload = await client.getMetrics();
|
|
7448
|
+
const screen = renderTopDashboard(payload);
|
|
7449
|
+
process.stdout.write("\x1B[H" + screen + '\n Press "q" or Ctrl+C to exit\n');
|
|
7450
|
+
} catch (err) {
|
|
7451
|
+
process.stdout.write(`\x1B[HConnecting to ${targetSocket}...
|
|
7452
|
+
Error: ${err.message}
|
|
7453
|
+
`);
|
|
7454
|
+
}
|
|
7455
|
+
};
|
|
7456
|
+
await tick();
|
|
7457
|
+
activeInterval = setInterval(tick, intervalMs);
|
|
7458
|
+
await new Promise(() => {
|
|
7459
|
+
});
|
|
5147
7460
|
return;
|
|
5148
7461
|
}
|
|
5149
7462
|
const redisStr = typeof values.redis === "string" ? values.redis : void 0;
|
|
@@ -5218,15 +7531,21 @@ Usage:
|
|
|
5218
7531
|
tricache <command> [options]
|
|
5219
7532
|
|
|
5220
7533
|
Commands:
|
|
7534
|
+
top Live ASCII terminal dashboard monitoring an active TriCache process
|
|
5221
7535
|
inspect Display full dashboard including hit ratios, latencies, and hot keys (default)
|
|
5222
7536
|
ping Measure response latency across L1 (RAM), L1.5 (Disk), and L2 (Redis)
|
|
5223
7537
|
clear Flush all entries or keys matching a prefix
|
|
5224
7538
|
|
|
5225
7539
|
Options:
|
|
7540
|
+
-s, --socket <path> IPC socket path or Windows named pipe
|
|
7541
|
+
--pid <pid> Process ID of the target TriCache process to monitor
|
|
7542
|
+
-i, --interval <ms> Refresh interval in milliseconds for top (default: 1000)
|
|
7543
|
+
--once Output single snapshot and exit (non-interactive)
|
|
7544
|
+
--json Format output as raw JSON
|
|
5226
7545
|
-r, --redis <host|url> Redis connection host or URL (e.g. localhost, redis://127.0.0.1:6379)
|
|
5227
7546
|
-p, --port <port> Redis port (default: 6379)
|
|
5228
7547
|
-n, --namespace <ns> Cache namespace
|
|
5229
|
-
|
|
7548
|
+
--prefix <prefix> Key prefix filter for clear command
|
|
5230
7549
|
-d, --disk <path> Custom disk cache directory path
|
|
5231
7550
|
-h, --help Show this help message
|
|
5232
7551
|
-v, --version Display version number
|