tricache 0.7.1 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +89 -1371
- package/dashboards/prometheus-scrape.yml +18 -0
- package/dashboards/tricache-alerts.yaml +54 -0
- package/dashboards/tricache-grafana.json +548 -0
- package/dist/cache-service-DVvroyqA.d.ts +886 -0
- package/dist/cache-service-KI5ACF3F.js +12 -0
- package/dist/chunk-7RV5ZVBB.js +1023 -0
- package/dist/chunk-BQRURGGD.js +60 -0
- package/dist/chunk-IITRFWHY.js +196 -0
- package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
- package/dist/{chunk-EUGYR7KR.js → chunk-PL5J3ZNT.js} +3184 -514
- package/dist/chunk-QNU7B43J.js +687 -0
- package/dist/chunk-UGD4VEPD.js +138 -0
- package/dist/chunk-XZL45ABR.js +108 -0
- package/dist/cli.cjs +3122 -495
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +121 -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 +2846 -494
- package/dist/drizzle/index.d.ts +3 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +1559 -0
- package/dist/edge/index.d.ts +127 -0
- package/dist/edge/index.js +1109 -0
- package/dist/hono/index.cjs +7760 -0
- package/dist/hono/index.d.ts +91 -0
- package/dist/hono/index.js +185 -0
- package/dist/hono-VA9A1m0I.d.ts +371 -0
- package/dist/http/index.cjs +3281 -587
- package/dist/http/index.d.ts +85 -23
- package/dist/http/index.js +176 -78
- package/dist/index.cjs +7212 -2505
- 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 +2787 -487
- package/dist/nestjs/index.d.ts +3 -1
- package/dist/nestjs/index.js +6 -3
- package/dist/next/index.cjs +2804 -501
- 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-B_QkVwJ7.d.ts} +622 -662
- package/dist/utils-CEsU_Z0s.d.ts +27 -0
- package/package.json +48 -10
- package/src/adapters/auto-pipeliner.ts +206 -0
- package/src/adapters/node-redis.ts +370 -0
- package/src/cache-service.ts +1619 -415
- package/src/cli.ts +137 -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 +284 -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/hono/index.ts +316 -0
- package/src/http/express.ts +195 -0
- package/src/http/fastify.ts +260 -0
- package/src/http/index.ts +44 -258
- package/src/http/utils.ts +92 -0
- package/src/index.ts +149 -47
- package/src/ipc-telemetry.ts +509 -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 +315 -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
|
@@ -33,13 +33,48 @@ __export(cli_exports, {
|
|
|
33
33
|
runCli: () => runCli
|
|
34
34
|
});
|
|
35
35
|
module.exports = __toCommonJS(cli_exports);
|
|
36
|
+
var import_node_fs3 = require("fs");
|
|
36
37
|
var import_node_util = require("util");
|
|
37
38
|
|
|
38
39
|
// src/cache-service.ts
|
|
39
40
|
var import_ioredis = require("ioredis");
|
|
40
|
-
|
|
41
|
+
|
|
42
|
+
// src/codec.ts
|
|
43
|
+
var import_msgpackr = require("msgpackr");
|
|
44
|
+
var CacheCodec = class {
|
|
45
|
+
packr;
|
|
46
|
+
constructor(options) {
|
|
47
|
+
const packrOptions = {
|
|
48
|
+
useToJSON: options?.useToJSON ?? true,
|
|
49
|
+
useRecords: options?.useRecords ?? true,
|
|
50
|
+
moreTypes: options?.moreTypes ?? true,
|
|
51
|
+
mapsAsObjects: options?.mapsAsObjects ?? true
|
|
52
|
+
};
|
|
53
|
+
this.packr = new import_msgpackr.Packr(packrOptions);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Serializes a JavaScript value to a binary MessagePack Buffer.
|
|
57
|
+
*/
|
|
58
|
+
encode(data) {
|
|
59
|
+
const packed = this.packr.pack(data);
|
|
60
|
+
return Buffer.isBuffer(packed) ? packed : Buffer.from(packed.buffer, packed.byteOffset, packed.byteLength);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Deserializes a binary MessagePack Buffer or Uint8Array back to a JavaScript value.
|
|
64
|
+
*/
|
|
65
|
+
decode(data) {
|
|
66
|
+
return this.packr.unpack(data);
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
var defaultCodec = new CacheCodec({
|
|
70
|
+
useToJSON: true,
|
|
71
|
+
useRecords: true,
|
|
72
|
+
moreTypes: true
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
// src/cache-service.ts
|
|
41
76
|
var import_crypto3 = __toESM(require("crypto"), 1);
|
|
42
|
-
var
|
|
77
|
+
var import_os3 = __toESM(require("os"), 1);
|
|
43
78
|
|
|
44
79
|
// src/worker-pool.ts
|
|
45
80
|
var import_worker_threads = require("worker_threads");
|
|
@@ -244,7 +279,7 @@ function availableCpus() {
|
|
|
244
279
|
}
|
|
245
280
|
|
|
246
281
|
// src/cache-service.ts
|
|
247
|
-
var
|
|
282
|
+
var import_node_v82 = __toESM(require("v8"), 1);
|
|
248
283
|
var import_fs3 = __toESM(require("fs"), 1);
|
|
249
284
|
var import_path3 = __toESM(require("path"), 1);
|
|
250
285
|
|
|
@@ -375,17 +410,17 @@ var CacheEncryption = class {
|
|
|
375
410
|
throw new Error("XOR key must be at least 1 byte");
|
|
376
411
|
}
|
|
377
412
|
this._key = buf;
|
|
378
|
-
if (
|
|
413
|
+
if (resolvedMode !== "xor") {
|
|
379
414
|
this._keyObj = (0, import_crypto.createSecretKey)(buf);
|
|
380
415
|
const _wc = (0, import_crypto.createCipheriv)(
|
|
381
|
-
|
|
416
|
+
resolvedMode,
|
|
382
417
|
this._keyObj,
|
|
383
|
-
Buffer.alloc(
|
|
418
|
+
Buffer.alloc(resolvedMode === "aes-128-ctr" ? CTR_IV_BYTES : IV_BYTES)
|
|
384
419
|
);
|
|
385
420
|
_wc.update(Buffer.alloc(0));
|
|
386
421
|
_wc.final();
|
|
387
422
|
}
|
|
388
|
-
if (
|
|
423
|
+
if (resolvedMode === "xor") {
|
|
389
424
|
logger.warn(
|
|
390
425
|
"Cache obfuscation enabled (XOR). WARNING: XOR is NOT cryptographic \u2014 use only for dev or non-sensitive data."
|
|
391
426
|
);
|
|
@@ -653,15 +688,257 @@ var CacheEncryption = class {
|
|
|
653
688
|
return plain;
|
|
654
689
|
}
|
|
655
690
|
};
|
|
691
|
+
var MAGIC_ENVELOPE = Buffer.from([84, 82, 73, 67, 69, 78, 86, 49]);
|
|
692
|
+
var EnvelopeEncryption = class {
|
|
693
|
+
static isEnvelope(data) {
|
|
694
|
+
return data.length >= MAGIC_LEN && data.subarray(0, MAGIC_LEN).equals(MAGIC_ENVELOPE);
|
|
695
|
+
}
|
|
696
|
+
static async encrypt(data, options) {
|
|
697
|
+
const dek = (0, import_crypto.randomBytes)(32);
|
|
698
|
+
let encryptedKey;
|
|
699
|
+
if (options.kmsEncrypt) {
|
|
700
|
+
encryptedKey = await options.kmsEncrypt(dek);
|
|
701
|
+
} else if (options.publicKey) {
|
|
702
|
+
encryptedKey = (0, import_crypto.publicEncrypt)(
|
|
703
|
+
{
|
|
704
|
+
key: options.publicKey,
|
|
705
|
+
padding: import_crypto.constants.RSA_PKCS1_OAEP_PADDING,
|
|
706
|
+
oaepHash: "sha256"
|
|
707
|
+
},
|
|
708
|
+
dek
|
|
709
|
+
);
|
|
710
|
+
} else {
|
|
711
|
+
throw new Error("EnvelopeEncryption: either publicKey or kmsEncrypt must be provided to encrypt");
|
|
712
|
+
}
|
|
713
|
+
const iv = (0, import_crypto.randomBytes)(IV_BYTES);
|
|
714
|
+
const cipher = (0, import_crypto.createCipheriv)("aes-256-gcm", dek, iv);
|
|
715
|
+
const ct = cipher.update(data);
|
|
716
|
+
cipher.final();
|
|
717
|
+
const tag = cipher.getAuthTag();
|
|
718
|
+
const keyLen = encryptedKey.length;
|
|
719
|
+
const out = Buffer.allocUnsafe(MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES + ct.length);
|
|
720
|
+
MAGIC_ENVELOPE.copy(out, 0);
|
|
721
|
+
out.writeUInt32BE(keyLen, MAGIC_LEN);
|
|
722
|
+
encryptedKey.copy(out, MAGIC_LEN + 4);
|
|
723
|
+
iv.copy(out, MAGIC_LEN + 4 + keyLen);
|
|
724
|
+
tag.copy(out, MAGIC_LEN + 4 + keyLen + IV_BYTES);
|
|
725
|
+
ct.copy(out, MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES);
|
|
726
|
+
return out;
|
|
727
|
+
}
|
|
728
|
+
static async decrypt(data, options) {
|
|
729
|
+
if (!this.isEnvelope(data)) {
|
|
730
|
+
throw new Error("EnvelopeEncryption: invalid header, expected TRICENV1");
|
|
731
|
+
}
|
|
732
|
+
if (data.length < MAGIC_LEN + 4 + IV_BYTES + TAG_BYTES) {
|
|
733
|
+
throw new Error("EnvelopeEncryption: truncated envelope buffer");
|
|
734
|
+
}
|
|
735
|
+
const keyLen = data.readUInt32BE(MAGIC_LEN);
|
|
736
|
+
const minExpected = MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES;
|
|
737
|
+
if (data.length < minExpected) {
|
|
738
|
+
throw new Error("EnvelopeEncryption: truncated envelope buffer (key length mismatch)");
|
|
739
|
+
}
|
|
740
|
+
const encryptedKey = data.subarray(MAGIC_LEN + 4, MAGIC_LEN + 4 + keyLen);
|
|
741
|
+
const iv = data.subarray(MAGIC_LEN + 4 + keyLen, MAGIC_LEN + 4 + keyLen + IV_BYTES);
|
|
742
|
+
const tag = data.subarray(MAGIC_LEN + 4 + keyLen + IV_BYTES, MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES);
|
|
743
|
+
const ct = data.subarray(MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES);
|
|
744
|
+
let dek;
|
|
745
|
+
if (options.kmsDecrypt) {
|
|
746
|
+
dek = await options.kmsDecrypt(encryptedKey);
|
|
747
|
+
} else if (options.privateKey) {
|
|
748
|
+
dek = (0, import_crypto.privateDecrypt)(
|
|
749
|
+
{
|
|
750
|
+
key: options.privateKey,
|
|
751
|
+
padding: import_crypto.constants.RSA_PKCS1_OAEP_PADDING,
|
|
752
|
+
oaepHash: "sha256"
|
|
753
|
+
},
|
|
754
|
+
encryptedKey
|
|
755
|
+
);
|
|
756
|
+
} else {
|
|
757
|
+
throw new Error("EnvelopeEncryption: either privateKey or kmsDecrypt must be provided to decrypt");
|
|
758
|
+
}
|
|
759
|
+
const decipher = (0, import_crypto.createDecipheriv)("aes-256-gcm", dek, iv);
|
|
760
|
+
decipher.setAuthTag(tag);
|
|
761
|
+
const pt = decipher.update(ct);
|
|
762
|
+
decipher.final();
|
|
763
|
+
return pt;
|
|
764
|
+
}
|
|
765
|
+
};
|
|
656
766
|
|
|
657
|
-
// src/
|
|
658
|
-
var
|
|
767
|
+
// src/wtiny-lfu.ts
|
|
768
|
+
var WTinyLfuPolicy = class {
|
|
769
|
+
constructor(capacity, sketch, windowPercent = 0.01, protectedPercent = 0.8) {
|
|
770
|
+
this.sketch = sketch;
|
|
771
|
+
this.maxTotal = Math.max(2, capacity);
|
|
772
|
+
this.maxWindow = Math.max(1, Math.floor(this.maxTotal * windowPercent));
|
|
773
|
+
const mainCapacity = Math.max(1, this.maxTotal - this.maxWindow);
|
|
774
|
+
this.maxProtected = Math.max(1, Math.floor(mainCapacity * protectedPercent));
|
|
775
|
+
this.maxProbation = Math.max(1, mainCapacity - this.maxProtected);
|
|
776
|
+
}
|
|
777
|
+
sketch;
|
|
778
|
+
maxTotal;
|
|
779
|
+
maxWindow;
|
|
780
|
+
maxProtected;
|
|
781
|
+
maxProbation;
|
|
782
|
+
window = /* @__PURE__ */ new Set();
|
|
783
|
+
probation = /* @__PURE__ */ new Set();
|
|
784
|
+
protected_ = /* @__PURE__ */ new Set();
|
|
785
|
+
// Telemetry metrics
|
|
786
|
+
hitCount = 0;
|
|
787
|
+
missCount = 0;
|
|
788
|
+
admissionCount = 0;
|
|
789
|
+
rejectionCount = 0;
|
|
790
|
+
promotionCount = 0;
|
|
791
|
+
demotionCount = 0;
|
|
792
|
+
get windowSize() {
|
|
793
|
+
return this.window.size;
|
|
794
|
+
}
|
|
795
|
+
get probationSize() {
|
|
796
|
+
return this.probation.size;
|
|
797
|
+
}
|
|
798
|
+
get protectedSize() {
|
|
799
|
+
return this.protected_.size;
|
|
800
|
+
}
|
|
801
|
+
onAccess(key) {
|
|
802
|
+
if (this.window.has(key)) {
|
|
803
|
+
this.window.delete(key);
|
|
804
|
+
this.window.add(key);
|
|
805
|
+
this.hitCount++;
|
|
806
|
+
return;
|
|
807
|
+
}
|
|
808
|
+
if (this.protected_.has(key)) {
|
|
809
|
+
this.protected_.delete(key);
|
|
810
|
+
this.protected_.add(key);
|
|
811
|
+
this.hitCount++;
|
|
812
|
+
return;
|
|
813
|
+
}
|
|
814
|
+
if (this.probation.has(key)) {
|
|
815
|
+
this.probation.delete(key);
|
|
816
|
+
this.protected_.add(key);
|
|
817
|
+
this.promotionCount++;
|
|
818
|
+
this.hitCount++;
|
|
819
|
+
if (this.protected_.size > this.maxProtected) {
|
|
820
|
+
const oldestProtKey = this.protected_.values().next().value;
|
|
821
|
+
this.protected_.delete(oldestProtKey);
|
|
822
|
+
this.probation.add(oldestProtKey);
|
|
823
|
+
this.demotionCount++;
|
|
824
|
+
}
|
|
825
|
+
return;
|
|
826
|
+
}
|
|
827
|
+
this.missCount++;
|
|
828
|
+
}
|
|
829
|
+
onSet(key, isUpdate) {
|
|
830
|
+
if (isUpdate) {
|
|
831
|
+
if (this.window.has(key)) {
|
|
832
|
+
this.window.delete(key);
|
|
833
|
+
this.window.add(key);
|
|
834
|
+
} else if (this.protected_.has(key)) {
|
|
835
|
+
this.protected_.delete(key);
|
|
836
|
+
this.protected_.add(key);
|
|
837
|
+
} else if (this.probation.has(key)) {
|
|
838
|
+
this.probation.delete(key);
|
|
839
|
+
this.probation.add(key);
|
|
840
|
+
}
|
|
841
|
+
return { admit: true };
|
|
842
|
+
}
|
|
843
|
+
this.window.add(key);
|
|
844
|
+
if (this.window.size <= this.maxWindow) {
|
|
845
|
+
this.admissionCount++;
|
|
846
|
+
return { admit: true };
|
|
847
|
+
}
|
|
848
|
+
const candKey = this.window.values().next().value;
|
|
849
|
+
this.window.delete(candKey);
|
|
850
|
+
if (this.probation.size + this.protected_.size < this.maxProbation + this.maxProtected) {
|
|
851
|
+
this.probation.add(candKey);
|
|
852
|
+
this.admissionCount++;
|
|
853
|
+
return { admit: true };
|
|
854
|
+
}
|
|
855
|
+
let victimKey;
|
|
856
|
+
let victimIsProbation = true;
|
|
857
|
+
if (this.probation.size > 0) {
|
|
858
|
+
victimKey = this.probation.values().next().value;
|
|
859
|
+
} else {
|
|
860
|
+
victimKey = this.protected_.values().next().value;
|
|
861
|
+
victimIsProbation = false;
|
|
862
|
+
}
|
|
863
|
+
const candFreq = this.sketch.estimate(candKey);
|
|
864
|
+
const victimFreq = this.sketch.estimate(victimKey);
|
|
865
|
+
if (candFreq > victimFreq) {
|
|
866
|
+
if (victimIsProbation) {
|
|
867
|
+
this.probation.delete(victimKey);
|
|
868
|
+
} else {
|
|
869
|
+
this.protected_.delete(victimKey);
|
|
870
|
+
}
|
|
871
|
+
this.probation.add(candKey);
|
|
872
|
+
this.admissionCount++;
|
|
873
|
+
return { admit: true, evictKey: victimKey, candidateKey: candKey };
|
|
874
|
+
} else {
|
|
875
|
+
this.rejectionCount++;
|
|
876
|
+
return { admit: false, candidateKey: candKey };
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
onDelete(key) {
|
|
880
|
+
this.window.delete(key);
|
|
881
|
+
this.probation.delete(key);
|
|
882
|
+
this.protected_.delete(key);
|
|
883
|
+
}
|
|
884
|
+
clear() {
|
|
885
|
+
this.window.clear();
|
|
886
|
+
this.probation.clear();
|
|
887
|
+
this.protected_.clear();
|
|
888
|
+
this.hitCount = 0;
|
|
889
|
+
this.missCount = 0;
|
|
890
|
+
this.admissionCount = 0;
|
|
891
|
+
this.rejectionCount = 0;
|
|
892
|
+
this.promotionCount = 0;
|
|
893
|
+
this.demotionCount = 0;
|
|
894
|
+
}
|
|
895
|
+
getStats() {
|
|
896
|
+
const totalRequests = this.hitCount + this.missCount;
|
|
897
|
+
return {
|
|
898
|
+
capacity: this.maxTotal,
|
|
899
|
+
size: this.window.size + this.probation.size + this.protected_.size,
|
|
900
|
+
windowSize: this.window.size,
|
|
901
|
+
probationSize: this.probation.size,
|
|
902
|
+
protectedSize: this.protected_.size,
|
|
903
|
+
hits: this.hitCount,
|
|
904
|
+
misses: this.missCount,
|
|
905
|
+
hitRate: totalRequests > 0 ? this.hitCount / totalRequests : 0,
|
|
906
|
+
admissions: this.admissionCount,
|
|
907
|
+
rejections: this.rejectionCount,
|
|
908
|
+
promotions: this.promotionCount,
|
|
909
|
+
demotions: this.demotionCount
|
|
910
|
+
};
|
|
911
|
+
}
|
|
912
|
+
getSegment(key) {
|
|
913
|
+
if (this.window.has(key)) return "window";
|
|
914
|
+
if (this.probation.has(key)) return "probation";
|
|
915
|
+
if (this.protected_.has(key)) return "protected";
|
|
916
|
+
return null;
|
|
917
|
+
}
|
|
918
|
+
};
|
|
919
|
+
|
|
920
|
+
// src/edge/utils/base64.ts
|
|
921
|
+
function base64ToUint8Array(base64) {
|
|
922
|
+
const modernU8 = Uint8Array;
|
|
923
|
+
if (typeof modernU8.fromBase64 === "function") {
|
|
924
|
+
return modernU8.fromBase64(base64);
|
|
925
|
+
}
|
|
926
|
+
const binary = globalThis.atob(base64);
|
|
927
|
+
const len = binary.length;
|
|
928
|
+
const bytes = new Uint8Array(len);
|
|
929
|
+
for (let i = 0; i < len; i++) {
|
|
930
|
+
bytes[i] = binary.charCodeAt(i);
|
|
931
|
+
}
|
|
932
|
+
return bytes;
|
|
933
|
+
}
|
|
659
934
|
|
|
660
935
|
// src/wasm/bloom-filter-wasm.ts
|
|
661
936
|
var BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
|
|
662
937
|
var KEY_STAGING_OFFSET = 2e4;
|
|
663
938
|
var MAX_KEY_BYTES = 512;
|
|
664
|
-
var BLOOM_WASM_MODULE = new WebAssembly.Module(
|
|
939
|
+
var BLOOM_WASM_MODULE = new WebAssembly.Module(
|
|
940
|
+
base64ToUint8Array(BLOOM_WASM_BASE64)
|
|
941
|
+
);
|
|
665
942
|
var WasmBloomFilter = class {
|
|
666
943
|
exports;
|
|
667
944
|
mem;
|
|
@@ -896,11 +1173,13 @@ function globMatchParts(parts, first, last, key) {
|
|
|
896
1173
|
var SmartMemoryCache = class {
|
|
897
1174
|
cache = /* @__PURE__ */ new Map();
|
|
898
1175
|
opts;
|
|
1176
|
+
codec;
|
|
899
1177
|
bloom;
|
|
900
1178
|
/** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
|
|
901
1179
|
categoryPrefixes;
|
|
902
1180
|
/** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
|
|
903
1181
|
sketch = new CountMinSketch();
|
|
1182
|
+
wtinyPolicy;
|
|
904
1183
|
totalSize = 0;
|
|
905
1184
|
categoryCount = /* @__PURE__ */ new Map();
|
|
906
1185
|
categorySize = /* @__PURE__ */ new Map();
|
|
@@ -924,8 +1203,12 @@ var SmartMemoryCache = class {
|
|
|
924
1203
|
_evictGPool = Array.from({ length: EVICTION_SAMPLE }, () => ({ key: "", score: 0 }));
|
|
925
1204
|
constructor(opts, existing) {
|
|
926
1205
|
this.opts = opts;
|
|
1206
|
+
this.codec = opts.codec ?? defaultCodec;
|
|
927
1207
|
this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
|
|
928
1208
|
this.categoryPrefixes = Object.keys(opts.categories).filter((k) => k !== "default");
|
|
1209
|
+
if (opts.admissionPolicy === "wtinylfu") {
|
|
1210
|
+
this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch);
|
|
1211
|
+
}
|
|
929
1212
|
if (existing) {
|
|
930
1213
|
for (const [k, v] of existing) this.cache.set(k, v);
|
|
931
1214
|
this.recalculateStats();
|
|
@@ -938,6 +1221,12 @@ var SmartMemoryCache = class {
|
|
|
938
1221
|
this.categoryCount.clear();
|
|
939
1222
|
this.categorySize.clear();
|
|
940
1223
|
this.categoryKeys.clear();
|
|
1224
|
+
if (this.wtinyPolicy) {
|
|
1225
|
+
this.wtinyPolicy.clear();
|
|
1226
|
+
for (const key of this.cache.keys()) {
|
|
1227
|
+
this.wtinyPolicy.onSet(key, false);
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
941
1230
|
for (const [key, entry] of this.cache) {
|
|
942
1231
|
this.totalSize += entry.size;
|
|
943
1232
|
const cat = this.getCategory(key);
|
|
@@ -963,6 +1252,7 @@ var SmartMemoryCache = class {
|
|
|
963
1252
|
_delete(key, reason = "manual") {
|
|
964
1253
|
const entry = this.cache.get(key);
|
|
965
1254
|
if (!entry) return false;
|
|
1255
|
+
this.wtinyPolicy?.onDelete(key);
|
|
966
1256
|
const cat = this.getCategory(key);
|
|
967
1257
|
this.totalSize -= entry.size;
|
|
968
1258
|
this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
|
|
@@ -1123,7 +1413,8 @@ var SmartMemoryCache = class {
|
|
|
1123
1413
|
entry.hits++;
|
|
1124
1414
|
entry.lastAccess = now;
|
|
1125
1415
|
if ((entry.hits & 3) === 0) this.sketch.increment(key);
|
|
1126
|
-
|
|
1416
|
+
this.wtinyPolicy?.onAccess(key);
|
|
1417
|
+
const value = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
1127
1418
|
const hit = {
|
|
1128
1419
|
value,
|
|
1129
1420
|
isStale: entry.staleAt !== void 0 && now > entry.staleAt,
|
|
@@ -1137,7 +1428,7 @@ var SmartMemoryCache = class {
|
|
|
1137
1428
|
return hit;
|
|
1138
1429
|
}
|
|
1139
1430
|
set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
|
|
1140
|
-
const packed =
|
|
1431
|
+
const packed = this.codec.encode(data);
|
|
1141
1432
|
const size = packed.byteLength;
|
|
1142
1433
|
this.compressions++;
|
|
1143
1434
|
this.sketch.increment(key);
|
|
@@ -1154,7 +1445,51 @@ var SmartMemoryCache = class {
|
|
|
1154
1445
|
this.categorySize.set(cat, (this.categorySize.get(cat) ?? existingEntry.size) - existingEntry.size);
|
|
1155
1446
|
this.cache.delete(key);
|
|
1156
1447
|
}
|
|
1157
|
-
this.
|
|
1448
|
+
if (this.wtinyPolicy) {
|
|
1449
|
+
const decision = this.wtinyPolicy.onSet(key, Boolean(existingEntry));
|
|
1450
|
+
if (!decision.admit) {
|
|
1451
|
+
if (decision.candidateKey === key) {
|
|
1452
|
+
if (this.opts.diskSpill) {
|
|
1453
|
+
const now2 = Date.now();
|
|
1454
|
+
const liveValue2 = size <= LARGE_VALUE_BYTES ? data : void 0;
|
|
1455
|
+
this.opts.diskSpill(key, {
|
|
1456
|
+
data: packed,
|
|
1457
|
+
value: liveValue2,
|
|
1458
|
+
isCompressed: true,
|
|
1459
|
+
expiresAt: now2 + ttlMs,
|
|
1460
|
+
staleAt,
|
|
1461
|
+
size,
|
|
1462
|
+
hits: 1,
|
|
1463
|
+
lastAccess: now2,
|
|
1464
|
+
priority,
|
|
1465
|
+
ttlMs,
|
|
1466
|
+
delta,
|
|
1467
|
+
setAt: now2,
|
|
1468
|
+
tagVersions
|
|
1469
|
+
});
|
|
1470
|
+
}
|
|
1471
|
+
return;
|
|
1472
|
+
} else if (decision.candidateKey) {
|
|
1473
|
+
const candEntry = this.cache.get(decision.candidateKey);
|
|
1474
|
+
if (candEntry && this.opts.diskSpill) {
|
|
1475
|
+
this.opts.diskSpill(decision.candidateKey, candEntry);
|
|
1476
|
+
}
|
|
1477
|
+
this._delete(decision.candidateKey, "capacity");
|
|
1478
|
+
}
|
|
1479
|
+
} else if (decision.evictKey) {
|
|
1480
|
+
const victimEntry = this.cache.get(decision.evictKey);
|
|
1481
|
+
if (victimEntry && this.opts.diskSpill) {
|
|
1482
|
+
this.opts.diskSpill(decision.evictKey, victimEntry);
|
|
1483
|
+
}
|
|
1484
|
+
this._delete(decision.evictKey, "capacity");
|
|
1485
|
+
}
|
|
1486
|
+
const catSz = this.categorySize.get(cat) ?? 0;
|
|
1487
|
+
if (catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
|
|
1488
|
+
this.ensureCapacity(cat, size);
|
|
1489
|
+
}
|
|
1490
|
+
} else {
|
|
1491
|
+
this.ensureCapacity(cat, size);
|
|
1492
|
+
}
|
|
1158
1493
|
const now = Date.now();
|
|
1159
1494
|
const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
|
|
1160
1495
|
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 +1549,7 @@ var SmartMemoryCache = class {
|
|
|
1214
1549
|
}
|
|
1215
1550
|
const count = this.cache.size;
|
|
1216
1551
|
this.cache.clear();
|
|
1552
|
+
this.wtinyPolicy?.clear();
|
|
1217
1553
|
this.totalSize = 0;
|
|
1218
1554
|
this.categoryCount.clear();
|
|
1219
1555
|
this.categorySize.clear();
|
|
@@ -1381,8 +1717,8 @@ var SmartMemoryCache = class {
|
|
|
1381
1717
|
if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
|
|
1382
1718
|
if (this.cache.has(key)) continue;
|
|
1383
1719
|
const rawData = entry.data;
|
|
1384
|
-
const data = !entry.isCompressed ?
|
|
1385
|
-
const value = entry.size <= LARGE_VALUE_BYTES ?
|
|
1720
|
+
const data = !entry.isCompressed ? this.codec.encode(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
|
|
1721
|
+
const value = entry.size <= LARGE_VALUE_BYTES ? this.codec.decode(data) : void 0;
|
|
1386
1722
|
this.cache.set(key, { ...entry, data, value, isCompressed: true });
|
|
1387
1723
|
this.bloom.add(key);
|
|
1388
1724
|
loaded++;
|
|
@@ -1453,7 +1789,7 @@ var SmartMemoryCache = class {
|
|
|
1453
1789
|
* if the live object was not cached (large-entry optimisation or disk-restored entry).
|
|
1454
1790
|
*/
|
|
1455
1791
|
resolveValue(entry) {
|
|
1456
|
-
return entry.value !== void 0 ? entry.value :
|
|
1792
|
+
return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
1457
1793
|
}
|
|
1458
1794
|
// ── Stats ─────────────────────────────────────────────────────────────────
|
|
1459
1795
|
get size() {
|
|
@@ -1558,13 +1894,20 @@ var SmartMemoryCache = class {
|
|
|
1558
1894
|
out.sort((a, b) => b.hits - a.hits);
|
|
1559
1895
|
return out.slice(0, n);
|
|
1560
1896
|
}
|
|
1897
|
+
/**
|
|
1898
|
+
* Return real-time metrics and telemetry for the Window TinyLFU admission policy.
|
|
1899
|
+
* Returns `undefined` when running under default adaptive eviction.
|
|
1900
|
+
*/
|
|
1901
|
+
getWTinyLfuStats() {
|
|
1902
|
+
return this.wtinyPolicy?.getStats();
|
|
1903
|
+
}
|
|
1561
1904
|
};
|
|
1562
1905
|
|
|
1563
1906
|
// src/disk-tier.ts
|
|
1564
1907
|
var import_fs2 = __toESM(require("fs"), 1);
|
|
1565
1908
|
var import_path2 = __toESM(require("path"), 1);
|
|
1566
1909
|
var import_crypto2 = __toESM(require("crypto"), 1);
|
|
1567
|
-
var
|
|
1910
|
+
var import_os2 = __toESM(require("os"), 1);
|
|
1568
1911
|
|
|
1569
1912
|
// src/compression.ts
|
|
1570
1913
|
var import_zlib = __toESM(require("zlib"), 1);
|
|
@@ -1622,18 +1965,146 @@ function decompressWithHeader(buf, algorithm = "brotli") {
|
|
|
1622
1965
|
}
|
|
1623
1966
|
|
|
1624
1967
|
// src/disk-tier.ts
|
|
1968
|
+
var BoundedDiskQueue = class {
|
|
1969
|
+
constructor(maxConcurrent = Math.min(4, Math.max(1, Math.floor((import_os2.default?.availableParallelism?.() ?? 4) / 4))), maxPending = 512, writeTimeoutMs = 500, failureThreshold = 5, cooldownMs = 5e3) {
|
|
1970
|
+
this.maxConcurrent = maxConcurrent;
|
|
1971
|
+
this.maxPending = maxPending;
|
|
1972
|
+
this.writeTimeoutMs = writeTimeoutMs;
|
|
1973
|
+
this.failureThreshold = failureThreshold;
|
|
1974
|
+
this.cooldownMs = cooldownMs;
|
|
1975
|
+
}
|
|
1976
|
+
maxConcurrent;
|
|
1977
|
+
maxPending;
|
|
1978
|
+
writeTimeoutMs;
|
|
1979
|
+
failureThreshold;
|
|
1980
|
+
cooldownMs;
|
|
1981
|
+
active = 0;
|
|
1982
|
+
queue = [];
|
|
1983
|
+
spillsDropped = 0;
|
|
1984
|
+
consecutiveFailures = 0;
|
|
1985
|
+
circuitState = "closed";
|
|
1986
|
+
lastStateChangeMonotonic = performance.now();
|
|
1987
|
+
async schedule(task) {
|
|
1988
|
+
const now = performance.now();
|
|
1989
|
+
if (this.circuitState === "open") {
|
|
1990
|
+
if (now - this.lastStateChangeMonotonic > this.cooldownMs) {
|
|
1991
|
+
this.circuitState = "half-open";
|
|
1992
|
+
this.lastStateChangeMonotonic = now;
|
|
1993
|
+
} else {
|
|
1994
|
+
this.spillsDropped++;
|
|
1995
|
+
return null;
|
|
1996
|
+
}
|
|
1997
|
+
}
|
|
1998
|
+
if (this.circuitState === "half-open" && this.active > 0) {
|
|
1999
|
+
this.spillsDropped++;
|
|
2000
|
+
return null;
|
|
2001
|
+
}
|
|
2002
|
+
if (this.queue.length >= this.maxPending) {
|
|
2003
|
+
this.spillsDropped++;
|
|
2004
|
+
return null;
|
|
2005
|
+
}
|
|
2006
|
+
if (this.active >= this.maxConcurrent) {
|
|
2007
|
+
await new Promise((resolve) => this.queue.push(resolve));
|
|
2008
|
+
}
|
|
2009
|
+
this.active++;
|
|
2010
|
+
let timeoutId = null;
|
|
2011
|
+
try {
|
|
2012
|
+
const result = await Promise.race([
|
|
2013
|
+
task(),
|
|
2014
|
+
new Promise((_, reject) => {
|
|
2015
|
+
timeoutId = setTimeout(
|
|
2016
|
+
() => reject(new Error(`Disk write exceeded timeout of ${this.writeTimeoutMs}ms`)),
|
|
2017
|
+
this.writeTimeoutMs
|
|
2018
|
+
);
|
|
2019
|
+
})
|
|
2020
|
+
]);
|
|
2021
|
+
this.consecutiveFailures = 0;
|
|
2022
|
+
if (this.circuitState === "half-open") {
|
|
2023
|
+
this.circuitState = "closed";
|
|
2024
|
+
this.lastStateChangeMonotonic = performance.now();
|
|
2025
|
+
}
|
|
2026
|
+
return result;
|
|
2027
|
+
} catch {
|
|
2028
|
+
this.consecutiveFailures++;
|
|
2029
|
+
if (this.consecutiveFailures >= this.failureThreshold || this.circuitState === "half-open") {
|
|
2030
|
+
this.circuitState = "open";
|
|
2031
|
+
this.lastStateChangeMonotonic = performance.now();
|
|
2032
|
+
}
|
|
2033
|
+
this.spillsDropped++;
|
|
2034
|
+
return null;
|
|
2035
|
+
} finally {
|
|
2036
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
2037
|
+
this.active--;
|
|
2038
|
+
const next = this.queue.shift();
|
|
2039
|
+
if (next) next();
|
|
2040
|
+
}
|
|
2041
|
+
}
|
|
2042
|
+
getStats() {
|
|
2043
|
+
return {
|
|
2044
|
+
activeWrites: this.active,
|
|
2045
|
+
pendingWrites: this.queue.length,
|
|
2046
|
+
spillsDropped: this.spillsDropped,
|
|
2047
|
+
circuitState: this.circuitState,
|
|
2048
|
+
lastTripTimestamp: this.lastStateChangeMonotonic
|
|
2049
|
+
};
|
|
2050
|
+
}
|
|
2051
|
+
reset() {
|
|
2052
|
+
this.consecutiveFailures = 0;
|
|
2053
|
+
this.circuitState = "closed";
|
|
2054
|
+
this.lastStateChangeMonotonic = performance.now();
|
|
2055
|
+
}
|
|
2056
|
+
};
|
|
1625
2057
|
var _SqliteDB = null;
|
|
1626
2058
|
try {
|
|
1627
|
-
const
|
|
1628
|
-
|
|
2059
|
+
const proc = process;
|
|
2060
|
+
if (typeof proc.getBuiltinModule === "function") {
|
|
2061
|
+
const sqlite = proc.getBuiltinModule("node:sqlite");
|
|
2062
|
+
_SqliteDB = sqlite?.DatabaseSync ?? null;
|
|
2063
|
+
}
|
|
1629
2064
|
} catch {
|
|
1630
2065
|
}
|
|
1631
2066
|
var DISK_MAGIC = Buffer.from([68, 84, 73, 69, 82, 86, 49, 0]);
|
|
1632
2067
|
var DISK_MAGIC_V2 = Buffer.from([68, 84, 73, 69, 82, 86, 50, 0]);
|
|
1633
2068
|
var V2_HEADER_LEN = 16;
|
|
1634
2069
|
var DISK_TIER_VERSION = 1;
|
|
2070
|
+
function resolveDefaultDiskDir(namespace, logger) {
|
|
2071
|
+
const ns = namespace?.trim() ?? "";
|
|
2072
|
+
const nsDir = ns ? `tricache-disk-${ns}` : "tricache-disk";
|
|
2073
|
+
if (process.platform === "linux") {
|
|
2074
|
+
const shmPath = "/dev/shm";
|
|
2075
|
+
try {
|
|
2076
|
+
import_fs2.default.accessSync(shmPath, import_fs2.default.constants.W_OK | import_fs2.default.constants.R_OK);
|
|
2077
|
+
if (typeof import_fs2.default.statfsSync === "function") {
|
|
2078
|
+
const stats = import_fs2.default.statfsSync(shmPath);
|
|
2079
|
+
const totalBytes = Number(stats.blocks) * Number(stats.bsize);
|
|
2080
|
+
const freeBytes = Number(stats.bavail) * Number(stats.bsize);
|
|
2081
|
+
if (totalBytes >= 256 * 1024 * 1024 && freeBytes >= 128 * 1024 * 1024) {
|
|
2082
|
+
const targetDir = import_path2.default.join(shmPath, nsDir);
|
|
2083
|
+
logger?.info?.("DiskTier: Targeting Linux /dev/shm tmpfs for off-heap storage", {
|
|
2084
|
+
path: targetDir,
|
|
2085
|
+
totalBytes,
|
|
2086
|
+
freeBytes
|
|
2087
|
+
});
|
|
2088
|
+
return { dir: targetDir, isShm: true };
|
|
2089
|
+
} else {
|
|
2090
|
+
logger?.info?.("DiskTier: /dev/shm capacity or free space insufficient (<256MB total or <128MB free); falling back to tmpdir", {
|
|
2091
|
+
totalBytes,
|
|
2092
|
+
freeBytes
|
|
2093
|
+
});
|
|
2094
|
+
}
|
|
2095
|
+
}
|
|
2096
|
+
} catch (err) {
|
|
2097
|
+
logger?.debug?.("DiskTier: /dev/shm not usable, falling back to tmpdir", {
|
|
2098
|
+
error: err.message
|
|
2099
|
+
});
|
|
2100
|
+
}
|
|
2101
|
+
}
|
|
2102
|
+
return { dir: import_path2.default.join(import_os2.default.tmpdir(), nsDir), isShm: false };
|
|
2103
|
+
}
|
|
1635
2104
|
var DiskTier = class {
|
|
1636
2105
|
opts;
|
|
2106
|
+
codec;
|
|
2107
|
+
diskQueue;
|
|
1637
2108
|
dirReady = false;
|
|
1638
2109
|
diskUsageBytes = 0;
|
|
1639
2110
|
usageCounted = false;
|
|
@@ -1641,6 +2112,14 @@ var DiskTier = class {
|
|
|
1641
2112
|
// maintained in-memory; avoids walkCacheFiles() in stats
|
|
1642
2113
|
/** Next bucket index (0–255) for the staggered janitor wheel. */
|
|
1643
2114
|
_nextJanitorBucket = 0;
|
|
2115
|
+
// ── High-watermark pruning & host volume health state ─────────────────────
|
|
2116
|
+
_isPruning = false;
|
|
2117
|
+
_pruneRounds = 0;
|
|
2118
|
+
_entriesPruned = 0;
|
|
2119
|
+
_spillsShedTotal = 0;
|
|
2120
|
+
_hostVolumeLowSpace = false;
|
|
2121
|
+
_hostVolumeLowSpacePauses = 0;
|
|
2122
|
+
_writeCounter = 0;
|
|
1644
2123
|
// ── SQLite metadata index (optional, requires node:sqlite) ───────────────
|
|
1645
2124
|
_db = null;
|
|
1646
2125
|
_stmtInsert = null;
|
|
@@ -1655,8 +2134,19 @@ var DiskTier = class {
|
|
|
1655
2134
|
// DELETE expired rows
|
|
1656
2135
|
_stmtStats = null;
|
|
1657
2136
|
// COUNT + SUM(size)
|
|
2137
|
+
_stmtPruneChunk = null;
|
|
2138
|
+
// SELECT chunk for watermark pruning
|
|
1658
2139
|
constructor(opts) {
|
|
1659
2140
|
this.opts = opts;
|
|
2141
|
+
this.codec = opts.codec ?? defaultCodec;
|
|
2142
|
+
const defaultConcurrent = Math.min(4, Math.max(1, Math.floor((import_os2.default?.availableParallelism?.() ?? 4) / 4)));
|
|
2143
|
+
this.diskQueue = new BoundedDiskQueue(
|
|
2144
|
+
opts.diskMaxConcurrentWrites ?? defaultConcurrent,
|
|
2145
|
+
opts.diskMaxPendingWrites ?? 512,
|
|
2146
|
+
opts.diskWriteTimeoutMs ?? 500,
|
|
2147
|
+
opts.diskCircuitBreakerThreshold ?? 5,
|
|
2148
|
+
opts.diskCircuitBreakerCooldownMs ?? 5e3
|
|
2149
|
+
);
|
|
1660
2150
|
}
|
|
1661
2151
|
// ── Helpers ───────────────────────────────────────────────────────────────
|
|
1662
2152
|
ensureDir() {
|
|
@@ -1691,15 +2181,30 @@ var DiskTier = class {
|
|
|
1691
2181
|
PRAGMA synchronous = NORMAL;
|
|
1692
2182
|
PRAGMA temp_store = MEMORY;
|
|
1693
2183
|
CREATE TABLE IF NOT EXISTS meta (
|
|
1694
|
-
key_hash
|
|
1695
|
-
file_path
|
|
1696
|
-
expires_at
|
|
1697
|
-
size
|
|
2184
|
+
key_hash TEXT PRIMARY KEY,
|
|
2185
|
+
file_path TEXT NOT NULL,
|
|
2186
|
+
expires_at INTEGER NOT NULL,
|
|
2187
|
+
size INTEGER NOT NULL DEFAULT 0,
|
|
2188
|
+
priority INTEGER NOT NULL DEFAULT 2,
|
|
2189
|
+
last_accessed_at INTEGER NOT NULL DEFAULT 0
|
|
1698
2190
|
);
|
|
1699
2191
|
CREATE INDEX IF NOT EXISTS idx_expires ON meta (expires_at);
|
|
2192
|
+
CREATE INDEX IF NOT EXISTS idx_priority_access ON meta (priority ASC, last_accessed_at ASC);
|
|
1700
2193
|
`);
|
|
2194
|
+
try {
|
|
2195
|
+
this._db.exec("ALTER TABLE meta ADD COLUMN priority INTEGER NOT NULL DEFAULT 2;");
|
|
2196
|
+
} catch {
|
|
2197
|
+
}
|
|
2198
|
+
try {
|
|
2199
|
+
this._db.exec("ALTER TABLE meta ADD COLUMN last_accessed_at INTEGER NOT NULL DEFAULT 0;");
|
|
2200
|
+
} catch {
|
|
2201
|
+
}
|
|
2202
|
+
try {
|
|
2203
|
+
this._db.exec("CREATE INDEX IF NOT EXISTS idx_priority_access ON meta (priority ASC, last_accessed_at ASC);");
|
|
2204
|
+
} catch {
|
|
2205
|
+
}
|
|
1701
2206
|
this._stmtInsert = this._db.prepare(
|
|
1702
|
-
"INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size) VALUES (
|
|
2207
|
+
"INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size, priority, last_accessed_at) VALUES (?,?,?,?,?,?)"
|
|
1703
2208
|
);
|
|
1704
2209
|
this._stmtSelect = this._db.prepare(
|
|
1705
2210
|
"SELECT file_path, expires_at FROM meta WHERE key_hash = ?"
|
|
@@ -1712,13 +2217,16 @@ var DiskTier = class {
|
|
|
1712
2217
|
this._stmtStats = this._db.prepare(
|
|
1713
2218
|
"SELECT COUNT(*) AS cnt, COALESCE(SUM(size), 0) AS bytes FROM meta"
|
|
1714
2219
|
);
|
|
2220
|
+
this._stmtPruneChunk = this._db.prepare(
|
|
2221
|
+
"SELECT key_hash, file_path, size FROM meta ORDER BY priority ASC, last_accessed_at ASC LIMIT 500"
|
|
2222
|
+
);
|
|
1715
2223
|
const row = this._stmtStats.get();
|
|
1716
2224
|
this.fileCount = row.cnt;
|
|
1717
2225
|
this.diskUsageBytes = row.bytes;
|
|
1718
2226
|
this.usageCounted = true;
|
|
1719
2227
|
this.opts.logger.debug("DiskTier: SQLite index ready", { entries: row.cnt });
|
|
1720
2228
|
} catch (err) {
|
|
1721
|
-
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
|
|
2229
|
+
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = this._stmtPruneChunk = null;
|
|
1722
2230
|
this.opts.logger.warn("DiskTier: SQLite init failed, using file-only mode", {
|
|
1723
2231
|
error: err.message
|
|
1724
2232
|
});
|
|
@@ -1813,7 +2321,7 @@ var DiskTier = class {
|
|
|
1813
2321
|
return results;
|
|
1814
2322
|
}
|
|
1815
2323
|
isForbidden(key) {
|
|
1816
|
-
return this.opts.forbiddenPrefixes
|
|
2324
|
+
return this.opts.forbiddenPrefixes?.some((p) => key.startsWith(p)) ?? false;
|
|
1817
2325
|
}
|
|
1818
2326
|
encrypt(data) {
|
|
1819
2327
|
if (!this.opts.encryption) return data;
|
|
@@ -1865,7 +2373,16 @@ var DiskTier = class {
|
|
|
1865
2373
|
this.ensureDir();
|
|
1866
2374
|
if (!this.dirReady) return;
|
|
1867
2375
|
this.ensureUsageCounted();
|
|
1868
|
-
if (this.
|
|
2376
|
+
if (++this._writeCounter % 2e3 === 0) {
|
|
2377
|
+
this.checkHostVolumeHealth();
|
|
2378
|
+
}
|
|
2379
|
+
if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes >= this.opts.maxBytes) {
|
|
2380
|
+
this._spillsShedTotal++;
|
|
2381
|
+
return;
|
|
2382
|
+
}
|
|
2383
|
+
if (this.diskUsageBytes >= this.opts.maxBytes * 0.8 && !this._isPruning) {
|
|
2384
|
+
void this.triggerChunkedPrune();
|
|
2385
|
+
}
|
|
1869
2386
|
let final;
|
|
1870
2387
|
try {
|
|
1871
2388
|
const payload = {
|
|
@@ -1877,7 +2394,7 @@ var DiskTier = class {
|
|
|
1877
2394
|
},
|
|
1878
2395
|
writtenAt: Date.now()
|
|
1879
2396
|
};
|
|
1880
|
-
const packed =
|
|
2397
|
+
const packed = this.codec.encode(payload);
|
|
1881
2398
|
if (packed.length > this.opts.entryMaxBytes) return;
|
|
1882
2399
|
let toEncrypt = packed;
|
|
1883
2400
|
if (this.opts.compression && this.opts.compression !== "none" && packed.length > (this.opts.compressionThresholdBytes ?? 1024)) {
|
|
@@ -1893,39 +2410,52 @@ var DiskTier = class {
|
|
|
1893
2410
|
}
|
|
1894
2411
|
const hash = this.keyToHash(key);
|
|
1895
2412
|
const filePath = this.hashToWritePath(hash, entry.expiresAt);
|
|
1896
|
-
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${
|
|
2413
|
+
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${import_crypto2.default.randomBytes(6).toString("hex")}.tmp`;
|
|
1897
2414
|
this.diskUsageBytes += final.length;
|
|
1898
2415
|
this.fileCount++;
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
2416
|
+
if (this.diskUsageBytes >= this.opts.maxBytes * 0.8 && !this._isPruning) {
|
|
2417
|
+
void this.triggerChunkedPrune();
|
|
2418
|
+
}
|
|
2419
|
+
const result = await this.diskQueue.schedule(async () => {
|
|
1902
2420
|
try {
|
|
1903
|
-
await import_fs2.default.promises.
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
if (code === "EBUSY" || code === "EPERM") {
|
|
1907
|
-
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
2421
|
+
await import_fs2.default.promises.mkdir(import_path2.default.dirname(filePath), { recursive: true });
|
|
2422
|
+
await import_fs2.default.promises.writeFile(tmpPath, final, { mode: 384 });
|
|
2423
|
+
try {
|
|
1908
2424
|
await import_fs2.default.promises.rename(tmpPath, filePath);
|
|
1909
|
-
}
|
|
1910
|
-
|
|
2425
|
+
} catch (renameErr) {
|
|
2426
|
+
const code = renameErr?.code;
|
|
2427
|
+
if (code === "EBUSY" || code === "EPERM") {
|
|
2428
|
+
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
2429
|
+
await import_fs2.default.promises.rename(tmpPath, filePath);
|
|
2430
|
+
} else {
|
|
2431
|
+
throw renameErr;
|
|
2432
|
+
}
|
|
1911
2433
|
}
|
|
2434
|
+
if (this._db) {
|
|
2435
|
+
const priority = typeof entry.priority === "number" ? entry.priority : 2;
|
|
2436
|
+
const lastAccess = typeof entry.lastAccess === "number" ? entry.lastAccess : Date.now();
|
|
2437
|
+
this._stmtInsert.run(hash, filePath, entry.expiresAt, final.length, priority, lastAccess);
|
|
2438
|
+
}
|
|
2439
|
+
this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
|
|
2440
|
+
return true;
|
|
2441
|
+
} catch (err) {
|
|
2442
|
+
try {
|
|
2443
|
+
await import_fs2.default.promises.unlink(tmpPath);
|
|
2444
|
+
} catch {
|
|
2445
|
+
}
|
|
2446
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
|
|
2447
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2448
|
+
if (this._db) try {
|
|
2449
|
+
this._stmtDelete.run(hash);
|
|
2450
|
+
} catch {
|
|
2451
|
+
}
|
|
2452
|
+
this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
|
|
2453
|
+
throw err;
|
|
1912
2454
|
}
|
|
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
|
-
}
|
|
2455
|
+
});
|
|
2456
|
+
if (result === null) {
|
|
1922
2457
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
|
|
1923
2458
|
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
2459
|
}
|
|
1930
2460
|
}
|
|
1931
2461
|
/** Load a key from disk, or return null on miss/expiry/corruption. */
|
|
@@ -2003,7 +2533,7 @@ var DiskTier = class {
|
|
|
2003
2533
|
}
|
|
2004
2534
|
}
|
|
2005
2535
|
const uncompressed = decompressWithHeader(decrypted, this.opts.compression ?? "brotli");
|
|
2006
|
-
const payload =
|
|
2536
|
+
const payload = this.codec.decode(uncompressed);
|
|
2007
2537
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
|
|
2008
2538
|
if (payload.entry.expiresAt <= Date.now()) return null;
|
|
2009
2539
|
const entry = payload.entry;
|
|
@@ -2126,7 +2656,7 @@ var DiskTier = class {
|
|
|
2126
2656
|
purged++;
|
|
2127
2657
|
continue;
|
|
2128
2658
|
}
|
|
2129
|
-
const payload =
|
|
2659
|
+
const payload = this.codec.decode(dec);
|
|
2130
2660
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
2131
2661
|
import_fs2.default.unlinkSync(filePath);
|
|
2132
2662
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
@@ -2290,7 +2820,7 @@ var DiskTier = class {
|
|
|
2290
2820
|
purged++;
|
|
2291
2821
|
continue;
|
|
2292
2822
|
}
|
|
2293
|
-
const payload =
|
|
2823
|
+
const payload = this.codec.decode(dec);
|
|
2294
2824
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
2295
2825
|
import_fs2.default.unlinkSync(filePath);
|
|
2296
2826
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
@@ -2329,13 +2859,141 @@ var DiskTier = class {
|
|
|
2329
2859
|
}
|
|
2330
2860
|
return cleared;
|
|
2331
2861
|
}
|
|
2862
|
+
/**
|
|
2863
|
+
* Proactively checks host volume free space via statfsSync.
|
|
2864
|
+
* If free space on the volume drops below 10%, pauses spills to prevent
|
|
2865
|
+
* Kubernetes pod eviction (DiskPressure / EphemeralStorageExceeded).
|
|
2866
|
+
*/
|
|
2867
|
+
checkHostVolumeHealth() {
|
|
2868
|
+
try {
|
|
2869
|
+
if (typeof import_fs2.default.statfsSync === "function") {
|
|
2870
|
+
const stats = import_fs2.default.statfsSync(this.opts.dir);
|
|
2871
|
+
const total = Number(stats.blocks);
|
|
2872
|
+
const avail = Number(stats.bavail);
|
|
2873
|
+
if (total > 0) {
|
|
2874
|
+
const freeRatio = avail / total;
|
|
2875
|
+
if (freeRatio < 0.1) {
|
|
2876
|
+
if (!this._hostVolumeLowSpace) {
|
|
2877
|
+
this._hostVolumeLowSpace = true;
|
|
2878
|
+
this._hostVolumeLowSpacePauses++;
|
|
2879
|
+
this.opts.logger.warn(
|
|
2880
|
+
"DiskTier: host volume has <10% free space. Pausing disk cache spills to prevent Kubernetes eviction.",
|
|
2881
|
+
{ dir: this.opts.dir, freePct: Number((freeRatio * 100).toFixed(1)) }
|
|
2882
|
+
);
|
|
2883
|
+
}
|
|
2884
|
+
return false;
|
|
2885
|
+
} else if (this._hostVolumeLowSpace) {
|
|
2886
|
+
this._hostVolumeLowSpace = false;
|
|
2887
|
+
this.opts.logger.info(
|
|
2888
|
+
"DiskTier: host volume space recovered (>=10% free). Resuming disk cache spills.",
|
|
2889
|
+
{ dir: this.opts.dir, freePct: Number((freeRatio * 100).toFixed(1)) }
|
|
2890
|
+
);
|
|
2891
|
+
return true;
|
|
2892
|
+
}
|
|
2893
|
+
}
|
|
2894
|
+
}
|
|
2895
|
+
} catch {
|
|
2896
|
+
}
|
|
2897
|
+
return true;
|
|
2898
|
+
}
|
|
2899
|
+
/**
|
|
2900
|
+
* Non-blocking chunked pruning:
|
|
2901
|
+
* Evicts oldest entries in 500-entry chunks down to 60% watermark,
|
|
2902
|
+
* yielding to the event loop via setImmediate between chunks.
|
|
2903
|
+
*/
|
|
2904
|
+
async triggerChunkedPrune() {
|
|
2905
|
+
if (this._isPruning) return 0;
|
|
2906
|
+
this._isPruning = true;
|
|
2907
|
+
this._pruneRounds++;
|
|
2908
|
+
let prunedInThisRound = 0;
|
|
2909
|
+
try {
|
|
2910
|
+
this.ensureUsageCounted();
|
|
2911
|
+
const targetBytes = Math.floor(this.opts.maxBytes * 0.6);
|
|
2912
|
+
if (this._db && this._stmtPruneChunk) {
|
|
2913
|
+
while (this.diskUsageBytes > targetBytes) {
|
|
2914
|
+
const rows = this._stmtPruneChunk.all();
|
|
2915
|
+
if (!rows || rows.length === 0) break;
|
|
2916
|
+
for (const row of rows) {
|
|
2917
|
+
try {
|
|
2918
|
+
import_fs2.default.unlinkSync(row.file_path);
|
|
2919
|
+
} catch {
|
|
2920
|
+
}
|
|
2921
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
|
|
2922
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2923
|
+
this._entriesPruned++;
|
|
2924
|
+
prunedInThisRound++;
|
|
2925
|
+
try {
|
|
2926
|
+
this._stmtDelete.run(row.key_hash);
|
|
2927
|
+
} catch {
|
|
2928
|
+
}
|
|
2929
|
+
if (this.diskUsageBytes <= targetBytes) break;
|
|
2930
|
+
}
|
|
2931
|
+
if (this.diskUsageBytes > targetBytes) {
|
|
2932
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
2933
|
+
}
|
|
2934
|
+
}
|
|
2935
|
+
} else {
|
|
2936
|
+
while (this.diskUsageBytes > targetBytes) {
|
|
2937
|
+
const files = this.walkCacheFiles();
|
|
2938
|
+
if (files.length === 0) break;
|
|
2939
|
+
const chunk = files.slice(0, 500);
|
|
2940
|
+
for (const filePath of chunk) {
|
|
2941
|
+
try {
|
|
2942
|
+
const stat = import_fs2.default.statSync(filePath);
|
|
2943
|
+
import_fs2.default.unlinkSync(filePath);
|
|
2944
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
2945
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2946
|
+
this._entriesPruned++;
|
|
2947
|
+
prunedInThisRound++;
|
|
2948
|
+
} catch {
|
|
2949
|
+
}
|
|
2950
|
+
if (this.diskUsageBytes <= targetBytes) break;
|
|
2951
|
+
}
|
|
2952
|
+
if (this.diskUsageBytes > targetBytes) {
|
|
2953
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
2954
|
+
}
|
|
2955
|
+
}
|
|
2956
|
+
}
|
|
2957
|
+
} finally {
|
|
2958
|
+
this._isPruning = false;
|
|
2959
|
+
}
|
|
2960
|
+
return prunedInThisRound;
|
|
2961
|
+
}
|
|
2962
|
+
get isPruning() {
|
|
2963
|
+
return this._isPruning;
|
|
2964
|
+
}
|
|
2965
|
+
get hostVolumeLowSpace() {
|
|
2966
|
+
return this._hostVolumeLowSpace;
|
|
2967
|
+
}
|
|
2968
|
+
get spillsShedTotal() {
|
|
2969
|
+
return this._spillsShedTotal;
|
|
2970
|
+
}
|
|
2971
|
+
getPruningStats() {
|
|
2972
|
+
return {
|
|
2973
|
+
active: this._isPruning,
|
|
2974
|
+
pruneRounds: this._pruneRounds,
|
|
2975
|
+
entriesPruned: this._entriesPruned,
|
|
2976
|
+
spillsShedTotal: this._spillsShedTotal,
|
|
2977
|
+
hostVolumeLowSpacePauses: this._hostVolumeLowSpacePauses
|
|
2978
|
+
};
|
|
2979
|
+
}
|
|
2332
2980
|
get stats() {
|
|
2333
2981
|
if (this._db) {
|
|
2334
2982
|
const row = this._stmtStats.get();
|
|
2335
2983
|
this.fileCount = row.cnt;
|
|
2336
2984
|
this.diskUsageBytes = row.bytes;
|
|
2337
2985
|
}
|
|
2338
|
-
return {
|
|
2986
|
+
return {
|
|
2987
|
+
files: this.fileCount,
|
|
2988
|
+
sizeKB: Math.round(this.diskUsageBytes / 1024),
|
|
2989
|
+
maxKB: Math.round(this.opts.maxBytes / 1024),
|
|
2990
|
+
backpressure: this.diskQueue.getStats(),
|
|
2991
|
+
pruning: this.getPruningStats()
|
|
2992
|
+
};
|
|
2993
|
+
}
|
|
2994
|
+
/** Direct access to the bounded write queue for chaos diagnostics and canary controls. */
|
|
2995
|
+
get backpressure() {
|
|
2996
|
+
return this.diskQueue;
|
|
2339
2997
|
}
|
|
2340
2998
|
/** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
|
|
2341
2999
|
get indexMode() {
|
|
@@ -2348,72 +3006,851 @@ var DiskTier = class {
|
|
|
2348
3006
|
this._db.close();
|
|
2349
3007
|
} catch {
|
|
2350
3008
|
}
|
|
2351
|
-
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
|
|
3009
|
+
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = this._stmtPruneChunk = null;
|
|
2352
3010
|
}
|
|
2353
3011
|
}
|
|
2354
3012
|
};
|
|
2355
3013
|
|
|
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;
|
|
3014
|
+
// src/latency-watchdog.ts
|
|
3015
|
+
var TierLatencyWatchdog = class {
|
|
3016
|
+
enabled;
|
|
3017
|
+
minDiskBypassMs;
|
|
3018
|
+
bypassRatio;
|
|
2397
3019
|
cooldownMs;
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
|
|
3020
|
+
redisCutoffMs;
|
|
3021
|
+
redisRecoveryFloorMs;
|
|
3022
|
+
minSamples;
|
|
3023
|
+
disableRedis;
|
|
3024
|
+
// Zero-allocation rolling ring buffers
|
|
3025
|
+
diskRing = new Float32Array(32);
|
|
3026
|
+
redisRing = new Float32Array(32);
|
|
3027
|
+
scratch = new Float32Array(32);
|
|
3028
|
+
diskIdx = 0;
|
|
3029
|
+
redisIdx = 0;
|
|
3030
|
+
diskCount = 0;
|
|
3031
|
+
redisCount = 0;
|
|
3032
|
+
// Cached amortized p95 values
|
|
3033
|
+
cachedDiskP95 = 0;
|
|
3034
|
+
cachedRedisP95 = 0;
|
|
3035
|
+
// State machine & control-theory flags
|
|
3036
|
+
stage = 0;
|
|
3037
|
+
redisDampened = false;
|
|
3038
|
+
// Asymmetric hysteresis latch
|
|
3039
|
+
redisRecoveryConsecutiveSamples = 0;
|
|
3040
|
+
bypassedUntilMonotonic = 0;
|
|
3041
|
+
canaryInFlight = false;
|
|
3042
|
+
bypassedTotal = 0;
|
|
3043
|
+
constructor(options = {}) {
|
|
3044
|
+
this.enabled = options.enabled ?? true;
|
|
3045
|
+
this.minDiskBypassMs = options.minDiskBypassMs ?? 10;
|
|
3046
|
+
this.bypassRatio = options.bypassRatio ?? 1.5;
|
|
3047
|
+
this.cooldownMs = options.cooldownMs ?? 3e4;
|
|
3048
|
+
this.redisCutoffMs = options.redisCutoffMs ?? 15;
|
|
3049
|
+
this.redisRecoveryFloorMs = options.redisRecoveryFloorMs ?? 10;
|
|
3050
|
+
this.minSamples = options.minSamples ?? 16;
|
|
3051
|
+
this.disableRedis = options.disableRedis ?? false;
|
|
3052
|
+
}
|
|
3053
|
+
setDisableRedis(disabled) {
|
|
3054
|
+
this.disableRedis = disabled;
|
|
3055
|
+
if (disabled) {
|
|
3056
|
+
this.stage = 0;
|
|
3057
|
+
this.bypassedUntilMonotonic = 0;
|
|
3058
|
+
this.canaryInFlight = false;
|
|
3059
|
+
this.redisRecoveryConsecutiveSamples = 0;
|
|
3060
|
+
}
|
|
3061
|
+
}
|
|
2403
3062
|
/**
|
|
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.
|
|
3063
|
+
* Record disk read duration in milliseconds (zero-allocation hot path).
|
|
2408
3064
|
*/
|
|
2409
|
-
|
|
3065
|
+
recordDisk(ms) {
|
|
3066
|
+
if (!this.enabled) return;
|
|
3067
|
+
this.diskRing[this.diskIdx++ & 31] = ms;
|
|
3068
|
+
this.diskCount++;
|
|
3069
|
+
if ((this.diskIdx & 31) === 0) {
|
|
3070
|
+
this.recalculateP95();
|
|
3071
|
+
}
|
|
3072
|
+
}
|
|
3073
|
+
/**
|
|
3074
|
+
* Record Redis read duration in milliseconds (zero-allocation hot path).
|
|
3075
|
+
*/
|
|
3076
|
+
recordRedis(ms) {
|
|
3077
|
+
if (!this.enabled || this.disableRedis) return;
|
|
3078
|
+
this.redisRing[this.redisIdx++ & 31] = ms;
|
|
3079
|
+
this.redisCount++;
|
|
3080
|
+
if (ms <= this.redisRecoveryFloorMs) {
|
|
3081
|
+
this.redisRecoveryConsecutiveSamples++;
|
|
3082
|
+
} else {
|
|
3083
|
+
this.redisRecoveryConsecutiveSamples = 0;
|
|
3084
|
+
}
|
|
3085
|
+
if ((this.redisIdx & 31) === 0) {
|
|
3086
|
+
this.recalculateP95();
|
|
3087
|
+
}
|
|
3088
|
+
}
|
|
3089
|
+
recalculateP95() {
|
|
3090
|
+
if (this.diskCount >= this.minSamples) {
|
|
3091
|
+
this.cachedDiskP95 = this.computeP95(this.diskRing, Math.min(this.diskCount, 32));
|
|
3092
|
+
}
|
|
3093
|
+
if (this.redisCount >= this.minSamples) {
|
|
3094
|
+
this.cachedRedisP95 = this.computeP95(this.redisRing, Math.min(this.redisCount, 32));
|
|
3095
|
+
}
|
|
3096
|
+
this.evaluateControlLoop();
|
|
3097
|
+
}
|
|
3098
|
+
computeP95(ring, count) {
|
|
3099
|
+
for (let i = 0; i < count; i++) {
|
|
3100
|
+
this.scratch[i] = ring[i];
|
|
3101
|
+
}
|
|
3102
|
+
this.scratch.subarray(0, count).sort();
|
|
3103
|
+
const rank = Math.min(count - 1, Math.max(0, Math.floor((count - 1) * 0.95)));
|
|
3104
|
+
return this.scratch[rank];
|
|
3105
|
+
}
|
|
3106
|
+
/**
|
|
3107
|
+
* Core Control Loop:
|
|
3108
|
+
* - Evaluates asymmetric hysteresis on Redis circuit.
|
|
3109
|
+
* - Assigns graduated stage (0, 1, 2, 3) with anti-synchronicity jitter.
|
|
3110
|
+
*/
|
|
3111
|
+
evaluateControlLoop() {
|
|
3112
|
+
if (this.disableRedis) {
|
|
3113
|
+
this.stage = 0;
|
|
3114
|
+
return;
|
|
3115
|
+
}
|
|
3116
|
+
if (this.cachedRedisP95 >= this.redisCutoffMs) {
|
|
3117
|
+
this.redisDampened = true;
|
|
3118
|
+
} else if (this.redisDampened && this.cachedRedisP95 <= this.redisRecoveryFloorMs && this.redisRecoveryConsecutiveSamples >= this.minSamples) {
|
|
3119
|
+
this.redisDampened = false;
|
|
3120
|
+
}
|
|
3121
|
+
if (this.redisDampened) {
|
|
3122
|
+
this.stage = 0;
|
|
3123
|
+
return;
|
|
3124
|
+
}
|
|
3125
|
+
if (this.diskCount < this.minSamples || this.redisCount < this.minSamples) {
|
|
3126
|
+
return;
|
|
3127
|
+
}
|
|
3128
|
+
const diskP95 = this.cachedDiskP95;
|
|
3129
|
+
const redisP95 = Math.max(0.1, this.cachedRedisP95);
|
|
3130
|
+
if (diskP95 >= 50) {
|
|
3131
|
+
if (this.stage !== 3) {
|
|
3132
|
+
this.stage = 3;
|
|
3133
|
+
this.bypassedUntilMonotonic = performance.now() + this.calculateJitteredCooldown();
|
|
3134
|
+
this.bypassedTotal++;
|
|
3135
|
+
}
|
|
3136
|
+
} else if (diskP95 >= this.minDiskBypassMs * 2.5 && diskP95 >= redisP95 * (this.bypassRatio * 1.5)) {
|
|
3137
|
+
if (this.stage !== 2) {
|
|
3138
|
+
this.stage = 2;
|
|
3139
|
+
this.bypassedTotal++;
|
|
3140
|
+
}
|
|
3141
|
+
} else if (diskP95 >= this.minDiskBypassMs && diskP95 >= redisP95 * this.bypassRatio) {
|
|
3142
|
+
if (this.stage !== 1) {
|
|
3143
|
+
this.stage = 1;
|
|
3144
|
+
this.bypassedTotal++;
|
|
3145
|
+
}
|
|
3146
|
+
} else {
|
|
3147
|
+
this.stage = 0;
|
|
3148
|
+
this.bypassedUntilMonotonic = 0;
|
|
3149
|
+
this.canaryInFlight = false;
|
|
3150
|
+
}
|
|
3151
|
+
}
|
|
3152
|
+
calculateJitteredCooldown() {
|
|
3153
|
+
const jitterFactor = 0.7 + Math.random() * 0.6;
|
|
3154
|
+
return this.cooldownMs * jitterFactor;
|
|
3155
|
+
}
|
|
3156
|
+
/**
|
|
3157
|
+
* Determine whether a read is permitted to check the disk tier.
|
|
3158
|
+
*
|
|
3159
|
+
* In Stage 1 and 2, sheds traffic probabilistically.
|
|
3160
|
+
* In Stage 3, blocks all reads except for a single canary probe once cooldown expires.
|
|
3161
|
+
*
|
|
3162
|
+
* @param randomOverride Optional seeded random number [0, 1) for deterministic unit testing.
|
|
3163
|
+
*/
|
|
3164
|
+
isDiskAllowed(randomOverride) {
|
|
3165
|
+
if (!this.enabled || this.disableRedis) return true;
|
|
3166
|
+
if (this.stage === 0) return true;
|
|
3167
|
+
const rand = randomOverride !== void 0 ? randomOverride : Math.random();
|
|
3168
|
+
if (this.stage === 1) {
|
|
3169
|
+
return rand > 0.25;
|
|
3170
|
+
}
|
|
3171
|
+
if (this.stage === 2) {
|
|
3172
|
+
return rand > 0.75;
|
|
3173
|
+
}
|
|
3174
|
+
const now = performance.now();
|
|
3175
|
+
if (now < this.bypassedUntilMonotonic) {
|
|
3176
|
+
return false;
|
|
3177
|
+
}
|
|
3178
|
+
if (!this.canaryInFlight) {
|
|
3179
|
+
this.canaryInFlight = true;
|
|
3180
|
+
return true;
|
|
3181
|
+
}
|
|
3182
|
+
return false;
|
|
3183
|
+
}
|
|
3184
|
+
/**
|
|
3185
|
+
* Callback invoked when the single canary read probe completes.
|
|
3186
|
+
*/
|
|
3187
|
+
onCanaryResult(success, elapsedMs) {
|
|
3188
|
+
if (!this.canaryInFlight) return;
|
|
3189
|
+
this.canaryInFlight = false;
|
|
3190
|
+
if (success && elapsedMs < this.minDiskBypassMs) {
|
|
3191
|
+
this.stage = 0;
|
|
3192
|
+
this.bypassedUntilMonotonic = 0;
|
|
3193
|
+
this.recordDisk(elapsedMs);
|
|
3194
|
+
} else {
|
|
3195
|
+
this.bypassedUntilMonotonic = performance.now() + this.calculateJitteredCooldown();
|
|
3196
|
+
this.bypassedTotal++;
|
|
3197
|
+
}
|
|
3198
|
+
}
|
|
3199
|
+
getTelemetry() {
|
|
3200
|
+
return {
|
|
3201
|
+
bypassActive: this.stage > 0,
|
|
3202
|
+
bypassStage: this.stage,
|
|
3203
|
+
diskP95Ms: Number(this.cachedDiskP95.toFixed(2)),
|
|
3204
|
+
redisP95Ms: Number(this.cachedRedisP95.toFixed(2)),
|
|
3205
|
+
redisDampened: this.redisDampened,
|
|
3206
|
+
bypassedTotal: this.bypassedTotal
|
|
3207
|
+
};
|
|
3208
|
+
}
|
|
3209
|
+
};
|
|
3210
|
+
|
|
3211
|
+
// src/utils/cgroup.ts
|
|
3212
|
+
var import_node_fs = __toESM(require("fs"), 1);
|
|
3213
|
+
var import_node_v8 = __toESM(require("v8"), 1);
|
|
3214
|
+
var UNBOUNDED_CGROUP_THRESHOLD = 9e18;
|
|
3215
|
+
var DEFAULT_AUTONOMOUS_L1_CEILING_BYTES = 512 * 1024 * 1024;
|
|
3216
|
+
var MIN_AUTONOMOUS_L1_FLOOR_BYTES = 16 * 1024 * 1024;
|
|
3217
|
+
function readCgroupMemoryLimit() {
|
|
3218
|
+
if (process.platform !== "linux") {
|
|
3219
|
+
return Infinity;
|
|
3220
|
+
}
|
|
3221
|
+
try {
|
|
3222
|
+
if (import_node_fs.default.existsSync("/sys/fs/cgroup/memory.max")) {
|
|
3223
|
+
const raw = import_node_fs.default.readFileSync("/sys/fs/cgroup/memory.max", "utf8").trim();
|
|
3224
|
+
if (raw === "max") {
|
|
3225
|
+
return Infinity;
|
|
3226
|
+
}
|
|
3227
|
+
const bytes = parseInt(raw, 10);
|
|
3228
|
+
if (Number.isFinite(bytes) && bytes > 0 && bytes < UNBOUNDED_CGROUP_THRESHOLD) {
|
|
3229
|
+
return bytes;
|
|
3230
|
+
}
|
|
3231
|
+
}
|
|
3232
|
+
} catch {
|
|
3233
|
+
}
|
|
3234
|
+
try {
|
|
3235
|
+
if (import_node_fs.default.existsSync("/sys/fs/cgroup/memory/memory.limit_in_bytes")) {
|
|
3236
|
+
const raw = import_node_fs.default.readFileSync("/sys/fs/cgroup/memory/memory.limit_in_bytes", "utf8").trim();
|
|
3237
|
+
const bytes = parseInt(raw, 10);
|
|
3238
|
+
if (Number.isFinite(bytes) && bytes > 0 && bytes < UNBOUNDED_CGROUP_THRESHOLD) {
|
|
3239
|
+
return bytes;
|
|
3240
|
+
}
|
|
3241
|
+
}
|
|
3242
|
+
} catch {
|
|
3243
|
+
}
|
|
3244
|
+
return Infinity;
|
|
3245
|
+
}
|
|
3246
|
+
function getV8HeapLimit() {
|
|
3247
|
+
try {
|
|
3248
|
+
const stats = import_node_v8.default.getHeapStatistics();
|
|
3249
|
+
if (stats && Number.isFinite(stats.heap_size_limit) && stats.heap_size_limit > 0) {
|
|
3250
|
+
return stats.heap_size_limit;
|
|
3251
|
+
}
|
|
3252
|
+
} catch {
|
|
3253
|
+
}
|
|
3254
|
+
return Infinity;
|
|
3255
|
+
}
|
|
3256
|
+
function resolveAutonomousL1MaxBytes(options) {
|
|
3257
|
+
const cgroup = options?.cgroupLimit !== void 0 ? options.cgroupLimit : readCgroupMemoryLimit();
|
|
3258
|
+
const v8Limit = options?.v8HeapLimit !== void 0 ? options.v8HeapLimit : getV8HeapLimit();
|
|
3259
|
+
const ceiling = options?.defaultCeilingBytes ?? DEFAULT_AUTONOMOUS_L1_CEILING_BYTES;
|
|
3260
|
+
const cgroupCap = Number.isFinite(cgroup) && cgroup > 0 ? cgroup * 0.4 : Infinity;
|
|
3261
|
+
const v8Cap = Number.isFinite(v8Limit) && v8Limit > 0 ? v8Limit * 0.5 : Infinity;
|
|
3262
|
+
const resolved = Math.min(cgroupCap, v8Cap, ceiling);
|
|
3263
|
+
if (!Number.isFinite(resolved) || resolved <= 0) {
|
|
3264
|
+
return ceiling;
|
|
3265
|
+
}
|
|
3266
|
+
return Math.max(MIN_AUTONOMOUS_L1_FLOOR_BYTES, Math.floor(resolved));
|
|
3267
|
+
}
|
|
3268
|
+
|
|
3269
|
+
// src/adapters/auto-pipeliner.ts
|
|
3270
|
+
var AutoPipeliner = class {
|
|
3271
|
+
constructor(client, options) {
|
|
3272
|
+
this.client = client;
|
|
3273
|
+
this.maxBatchSize = options?.maxBatchSize ?? 100;
|
|
3274
|
+
this.enabled = options?.enabled ?? true;
|
|
3275
|
+
}
|
|
3276
|
+
client;
|
|
3277
|
+
maxBatchSize;
|
|
3278
|
+
enabled;
|
|
3279
|
+
queue = [];
|
|
3280
|
+
scheduled = false;
|
|
3281
|
+
inFlight = false;
|
|
3282
|
+
statsInternal = {
|
|
3283
|
+
batchesDispatched: 0,
|
|
3284
|
+
operationsBatched: 0
|
|
3285
|
+
};
|
|
3286
|
+
get stats() {
|
|
3287
|
+
return {
|
|
3288
|
+
batchesDispatched: this.statsInternal.batchesDispatched,
|
|
3289
|
+
operationsBatched: this.statsInternal.operationsBatched,
|
|
3290
|
+
pendingQueueSize: this.queue.length
|
|
3291
|
+
};
|
|
3292
|
+
}
|
|
3293
|
+
async get(key) {
|
|
3294
|
+
if (!this.enabled || !this.supportsPipelines()) {
|
|
3295
|
+
return this.client.get(key);
|
|
3296
|
+
}
|
|
3297
|
+
return new Promise((resolve, reject) => {
|
|
3298
|
+
this.enqueue({ type: "get", key, resolve, reject });
|
|
3299
|
+
});
|
|
3300
|
+
}
|
|
3301
|
+
async setex(key, seconds, value) {
|
|
3302
|
+
if (!this.enabled || !this.supportsPipelines()) {
|
|
3303
|
+
if (typeof this.client.setex === "function") {
|
|
3304
|
+
await this.client.setex(key, seconds, value);
|
|
3305
|
+
} else {
|
|
3306
|
+
await this.client.set(key, value, "EX", seconds);
|
|
3307
|
+
}
|
|
3308
|
+
return;
|
|
3309
|
+
}
|
|
3310
|
+
return new Promise((resolve, reject) => {
|
|
3311
|
+
this.enqueue({ type: "setex", key, seconds, value, resolve, reject });
|
|
3312
|
+
});
|
|
3313
|
+
}
|
|
3314
|
+
async del(...keys) {
|
|
3315
|
+
if (keys.length === 0) return 0;
|
|
3316
|
+
if (!this.enabled || !this.supportsPipelines()) {
|
|
3317
|
+
return this.client.del(...keys);
|
|
3318
|
+
}
|
|
3319
|
+
return new Promise((resolve, reject) => {
|
|
3320
|
+
this.enqueue({ type: "del", keys, resolve, reject });
|
|
3321
|
+
});
|
|
3322
|
+
}
|
|
3323
|
+
supportsPipelines() {
|
|
3324
|
+
return Boolean(
|
|
3325
|
+
typeof this.client?.pipeline === "function" || typeof this.client?.multi === "function"
|
|
3326
|
+
);
|
|
3327
|
+
}
|
|
3328
|
+
enqueue(op) {
|
|
3329
|
+
this.queue.push(op);
|
|
3330
|
+
if (this.queue.length >= this.maxBatchSize) {
|
|
3331
|
+
void this.flush();
|
|
3332
|
+
return;
|
|
3333
|
+
}
|
|
3334
|
+
if (!this.scheduled) {
|
|
3335
|
+
this.scheduled = true;
|
|
3336
|
+
queueMicrotask(() => {
|
|
3337
|
+
this.scheduled = false;
|
|
3338
|
+
void this.flush();
|
|
3339
|
+
});
|
|
3340
|
+
}
|
|
3341
|
+
}
|
|
3342
|
+
async flush() {
|
|
3343
|
+
if (this.queue.length === 0) return;
|
|
3344
|
+
const batch = this.queue;
|
|
3345
|
+
this.queue = [];
|
|
3346
|
+
this.scheduled = false;
|
|
3347
|
+
this.statsInternal.batchesDispatched++;
|
|
3348
|
+
this.statsInternal.operationsBatched += batch.length;
|
|
3349
|
+
const pipe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
|
|
3350
|
+
for (const op of batch) {
|
|
3351
|
+
switch (op.type) {
|
|
3352
|
+
case "get":
|
|
3353
|
+
pipe.get(op.key);
|
|
3354
|
+
break;
|
|
3355
|
+
case "setex":
|
|
3356
|
+
pipe.setex(op.key, op.seconds, op.value);
|
|
3357
|
+
break;
|
|
3358
|
+
case "del":
|
|
3359
|
+
pipe.del(...op.keys);
|
|
3360
|
+
break;
|
|
3361
|
+
}
|
|
3362
|
+
}
|
|
3363
|
+
try {
|
|
3364
|
+
const results = await pipe.exec();
|
|
3365
|
+
if (!results) {
|
|
3366
|
+
for (const op of batch) {
|
|
3367
|
+
if (op.type === "get") op.resolve(null);
|
|
3368
|
+
else if (op.type === "del") op.resolve(0);
|
|
3369
|
+
else op.resolve();
|
|
3370
|
+
}
|
|
3371
|
+
return;
|
|
3372
|
+
}
|
|
3373
|
+
for (let i = 0; i < batch.length; i++) {
|
|
3374
|
+
const op = batch[i];
|
|
3375
|
+
const resTuple = results[i];
|
|
3376
|
+
if (!resTuple) {
|
|
3377
|
+
if (op.type === "get") op.resolve(null);
|
|
3378
|
+
else if (op.type === "del") op.resolve(0);
|
|
3379
|
+
else op.resolve();
|
|
3380
|
+
continue;
|
|
3381
|
+
}
|
|
3382
|
+
const [err, val] = resTuple;
|
|
3383
|
+
if (err) {
|
|
3384
|
+
op.reject(err instanceof Error ? err : new Error(String(err)));
|
|
3385
|
+
} else {
|
|
3386
|
+
if (op.type === "get") {
|
|
3387
|
+
op.resolve(val != null ? String(val) : null);
|
|
3388
|
+
} else if (op.type === "del") {
|
|
3389
|
+
op.resolve(typeof val === "number" ? val : Number(val) || 0);
|
|
3390
|
+
} else {
|
|
3391
|
+
op.resolve();
|
|
3392
|
+
}
|
|
3393
|
+
}
|
|
3394
|
+
}
|
|
3395
|
+
} catch (err) {
|
|
3396
|
+
for (const op of batch) {
|
|
3397
|
+
op.reject(err instanceof Error ? err : new Error(String(err)));
|
|
3398
|
+
}
|
|
3399
|
+
}
|
|
3400
|
+
}
|
|
3401
|
+
};
|
|
3402
|
+
|
|
3403
|
+
// src/ipc-telemetry.ts
|
|
3404
|
+
var import_node_net = __toESM(require("net"), 1);
|
|
3405
|
+
var import_node_fs2 = __toESM(require("fs"), 1);
|
|
3406
|
+
var import_node_path = __toESM(require("path"), 1);
|
|
3407
|
+
function resolveIpcSocketPath(id = process.pid) {
|
|
3408
|
+
if (process.platform === "win32") {
|
|
3409
|
+
return `\\\\.\\pipe\\tricache-${id}`;
|
|
3410
|
+
}
|
|
3411
|
+
const dir = process.env.TMPDIR || "/tmp";
|
|
3412
|
+
return import_node_path.default.join(dir, `tricache-${id}.sock`);
|
|
3413
|
+
}
|
|
3414
|
+
var IpcTelemetryServer = class {
|
|
3415
|
+
constructor(cache, customSocketPath) {
|
|
3416
|
+
this.cache = cache;
|
|
3417
|
+
this.socketPath = customSocketPath || resolveIpcSocketPath();
|
|
3418
|
+
}
|
|
3419
|
+
cache;
|
|
3420
|
+
server = null;
|
|
3421
|
+
socketPath;
|
|
3422
|
+
_closed = false;
|
|
3423
|
+
_exitHandler = null;
|
|
3424
|
+
_sigintHandler = null;
|
|
3425
|
+
_sigtermHandler = null;
|
|
3426
|
+
/**
|
|
3427
|
+
* Start listening on the IPC socket / pipe.
|
|
3428
|
+
*/
|
|
3429
|
+
async start() {
|
|
3430
|
+
if (this.server && this.server.listening) return;
|
|
3431
|
+
if (process.platform !== "win32" && import_node_fs2.default.existsSync(this.socketPath)) {
|
|
3432
|
+
await new Promise((resolve) => {
|
|
3433
|
+
const testSocket = import_node_net.default.createConnection(this.socketPath);
|
|
3434
|
+
testSocket.once("connect", () => {
|
|
3435
|
+
testSocket.destroy();
|
|
3436
|
+
resolve();
|
|
3437
|
+
});
|
|
3438
|
+
testSocket.once("error", () => {
|
|
3439
|
+
testSocket.destroy();
|
|
3440
|
+
try {
|
|
3441
|
+
import_node_fs2.default.unlinkSync(this.socketPath);
|
|
3442
|
+
} catch {
|
|
3443
|
+
}
|
|
3444
|
+
resolve();
|
|
3445
|
+
});
|
|
3446
|
+
});
|
|
3447
|
+
}
|
|
3448
|
+
this.server = import_node_net.default.createServer((socket) => {
|
|
3449
|
+
let buffer = "";
|
|
3450
|
+
socket.on("data", (chunk) => {
|
|
3451
|
+
buffer += chunk.toString("utf8");
|
|
3452
|
+
let newlineIndex;
|
|
3453
|
+
while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
|
|
3454
|
+
const line = buffer.slice(0, newlineIndex).trim();
|
|
3455
|
+
buffer = buffer.slice(newlineIndex + 1);
|
|
3456
|
+
if (!line) continue;
|
|
3457
|
+
setImmediate(() => {
|
|
3458
|
+
if (socket.destroyed) return;
|
|
3459
|
+
try {
|
|
3460
|
+
let cmd = line;
|
|
3461
|
+
try {
|
|
3462
|
+
const parsed = JSON.parse(line);
|
|
3463
|
+
if (parsed && typeof parsed.cmd === "string") {
|
|
3464
|
+
cmd = parsed.cmd;
|
|
3465
|
+
}
|
|
3466
|
+
} catch {
|
|
3467
|
+
}
|
|
3468
|
+
if (cmd === "PING") {
|
|
3469
|
+
socket.write(JSON.stringify({ pong: true, timestamp: Date.now() }) + "\n");
|
|
3470
|
+
return;
|
|
3471
|
+
}
|
|
3472
|
+
if (cmd === "GET_METRICS" || cmd === "INSPECT") {
|
|
3473
|
+
const payload = this.getSnapshot();
|
|
3474
|
+
const serialized = JSON.stringify(payload) + "\n";
|
|
3475
|
+
socket.write(serialized);
|
|
3476
|
+
return;
|
|
3477
|
+
}
|
|
3478
|
+
socket.write(JSON.stringify({ error: `Unknown command: ${cmd}` }) + "\n");
|
|
3479
|
+
} catch (err) {
|
|
3480
|
+
if (!socket.destroyed) {
|
|
3481
|
+
socket.write(JSON.stringify({ error: err.message }) + "\n");
|
|
3482
|
+
}
|
|
3483
|
+
}
|
|
3484
|
+
});
|
|
3485
|
+
}
|
|
3486
|
+
});
|
|
3487
|
+
socket.on("error", () => {
|
|
3488
|
+
});
|
|
3489
|
+
});
|
|
3490
|
+
await new Promise((resolve, reject) => {
|
|
3491
|
+
this.server.once("error", reject);
|
|
3492
|
+
this.server.listen(this.socketPath, () => {
|
|
3493
|
+
this.server.removeListener("error", reject);
|
|
3494
|
+
resolve();
|
|
3495
|
+
});
|
|
3496
|
+
});
|
|
3497
|
+
this._exitHandler = () => this._unlinkSocket();
|
|
3498
|
+
this._sigintHandler = () => {
|
|
3499
|
+
this._unlinkSocket();
|
|
3500
|
+
process.exit(0);
|
|
3501
|
+
};
|
|
3502
|
+
this._sigtermHandler = () => {
|
|
3503
|
+
this._unlinkSocket();
|
|
3504
|
+
process.exit(0);
|
|
3505
|
+
};
|
|
3506
|
+
process.once("exit", this._exitHandler);
|
|
3507
|
+
process.once("SIGINT", this._sigintHandler);
|
|
3508
|
+
process.once("SIGTERM", this._sigtermHandler);
|
|
3509
|
+
}
|
|
3510
|
+
/**
|
|
3511
|
+
* Build a complete telemetry snapshot from the underlying cache provider.
|
|
3512
|
+
*/
|
|
3513
|
+
getSnapshot() {
|
|
3514
|
+
const metrics = this.cache.metrics();
|
|
3515
|
+
const stats = typeof this.cache.stats === "function" ? this.cache.stats() : void 0;
|
|
3516
|
+
const hotKeys = typeof this.cache.hotKeys === "function" ? this.cache.hotKeys(10) : void 0;
|
|
3517
|
+
const health = typeof this.cache.health === "function" ? this.cache.health() : void 0;
|
|
3518
|
+
const l1MaxBytes = this.cache.options?.l1MaxBytes ?? metrics.l1?.maxBytes;
|
|
3519
|
+
return {
|
|
3520
|
+
pid: process.pid,
|
|
3521
|
+
uptimeMs: metrics.uptimeMs,
|
|
3522
|
+
timestamp: Date.now(),
|
|
3523
|
+
namespace: this.cache.options?.namespace || metrics.namespace,
|
|
3524
|
+
l1MaxBytes,
|
|
3525
|
+
metrics,
|
|
3526
|
+
stats,
|
|
3527
|
+
hotKeys,
|
|
3528
|
+
health
|
|
3529
|
+
};
|
|
3530
|
+
}
|
|
3531
|
+
_unlinkSocket() {
|
|
3532
|
+
if (this._closed) return;
|
|
3533
|
+
this._closed = true;
|
|
3534
|
+
try {
|
|
3535
|
+
this.server?.close();
|
|
3536
|
+
} catch {
|
|
3537
|
+
}
|
|
3538
|
+
if (process.platform !== "win32") {
|
|
3539
|
+
try {
|
|
3540
|
+
if (import_node_fs2.default.existsSync(this.socketPath)) {
|
|
3541
|
+
import_node_fs2.default.unlinkSync(this.socketPath);
|
|
3542
|
+
}
|
|
3543
|
+
} catch {
|
|
3544
|
+
}
|
|
3545
|
+
}
|
|
3546
|
+
}
|
|
3547
|
+
/**
|
|
3548
|
+
* Gracefully close the IPC telemetry server and clean up handlers and sockets.
|
|
3549
|
+
*/
|
|
3550
|
+
async close() {
|
|
3551
|
+
if (this._exitHandler) {
|
|
3552
|
+
process.removeListener("exit", this._exitHandler);
|
|
3553
|
+
this._exitHandler = null;
|
|
3554
|
+
}
|
|
3555
|
+
if (this._sigintHandler) {
|
|
3556
|
+
process.removeListener("SIGINT", this._sigintHandler);
|
|
3557
|
+
this._sigintHandler = null;
|
|
3558
|
+
}
|
|
3559
|
+
if (this._sigtermHandler) {
|
|
3560
|
+
process.removeListener("SIGTERM", this._sigtermHandler);
|
|
3561
|
+
this._sigtermHandler = null;
|
|
3562
|
+
}
|
|
3563
|
+
this._unlinkSocket();
|
|
3564
|
+
return new Promise((resolve) => {
|
|
3565
|
+
if (!this.server || !this.server.listening) {
|
|
3566
|
+
resolve();
|
|
3567
|
+
return;
|
|
3568
|
+
}
|
|
3569
|
+
this.server.close(() => resolve());
|
|
3570
|
+
});
|
|
3571
|
+
}
|
|
3572
|
+
get isListening() {
|
|
3573
|
+
return Boolean(this.server && this.server.listening);
|
|
3574
|
+
}
|
|
3575
|
+
};
|
|
3576
|
+
var IpcTelemetryClient = class {
|
|
3577
|
+
socketPath;
|
|
3578
|
+
constructor(socketPath) {
|
|
3579
|
+
this.socketPath = socketPath || resolveIpcSocketPath();
|
|
3580
|
+
}
|
|
3581
|
+
/**
|
|
3582
|
+
* Fetch a live metrics snapshot from the IPC server.
|
|
3583
|
+
*/
|
|
3584
|
+
async getMetrics(timeoutMs = 3e3) {
|
|
3585
|
+
return new Promise((resolve, reject) => {
|
|
3586
|
+
const socket = import_node_net.default.createConnection(this.socketPath);
|
|
3587
|
+
let buffer = "";
|
|
3588
|
+
let timer = setTimeout(() => {
|
|
3589
|
+
socket.destroy();
|
|
3590
|
+
reject(new Error(`IPC connection timeout (${timeoutMs}ms) to ${this.socketPath}`));
|
|
3591
|
+
}, timeoutMs);
|
|
3592
|
+
socket.once("connect", () => {
|
|
3593
|
+
socket.write("GET_METRICS\n");
|
|
3594
|
+
});
|
|
3595
|
+
socket.on("data", (chunk) => {
|
|
3596
|
+
buffer += chunk.toString("utf8");
|
|
3597
|
+
const newlineIdx = buffer.indexOf("\n");
|
|
3598
|
+
if (newlineIdx !== -1) {
|
|
3599
|
+
if (timer) {
|
|
3600
|
+
clearTimeout(timer);
|
|
3601
|
+
timer = null;
|
|
3602
|
+
}
|
|
3603
|
+
const line = buffer.slice(0, newlineIdx).trim();
|
|
3604
|
+
socket.end();
|
|
3605
|
+
try {
|
|
3606
|
+
const data = JSON.parse(line);
|
|
3607
|
+
if (data.error) {
|
|
3608
|
+
reject(new Error(data.error));
|
|
3609
|
+
} else {
|
|
3610
|
+
resolve(data);
|
|
3611
|
+
}
|
|
3612
|
+
} catch (e) {
|
|
3613
|
+
reject(new Error(`Failed to parse IPC payload: ${e.message}`));
|
|
3614
|
+
}
|
|
3615
|
+
}
|
|
3616
|
+
});
|
|
3617
|
+
socket.once("error", (err) => {
|
|
3618
|
+
if (timer) {
|
|
3619
|
+
clearTimeout(timer);
|
|
3620
|
+
timer = null;
|
|
3621
|
+
}
|
|
3622
|
+
reject(err);
|
|
3623
|
+
});
|
|
3624
|
+
});
|
|
3625
|
+
}
|
|
3626
|
+
/**
|
|
3627
|
+
* Send a ping over the IPC bridge and measure round-trip latency.
|
|
3628
|
+
*/
|
|
3629
|
+
async ping(timeoutMs = 1e3) {
|
|
3630
|
+
const start = Date.now();
|
|
3631
|
+
return new Promise((resolve, reject) => {
|
|
3632
|
+
const socket = import_node_net.default.createConnection(this.socketPath);
|
|
3633
|
+
let timer = setTimeout(() => {
|
|
3634
|
+
socket.destroy();
|
|
3635
|
+
reject(new Error(`IPC ping timeout (${timeoutMs}ms)`));
|
|
3636
|
+
}, timeoutMs);
|
|
3637
|
+
socket.once("connect", () => {
|
|
3638
|
+
socket.write("PING\n");
|
|
3639
|
+
});
|
|
3640
|
+
socket.on("data", () => {
|
|
3641
|
+
if (timer) {
|
|
3642
|
+
clearTimeout(timer);
|
|
3643
|
+
timer = null;
|
|
3644
|
+
}
|
|
3645
|
+
socket.end();
|
|
3646
|
+
resolve(Date.now() - start);
|
|
3647
|
+
});
|
|
3648
|
+
socket.once("error", (err) => {
|
|
3649
|
+
if (timer) {
|
|
3650
|
+
clearTimeout(timer);
|
|
3651
|
+
timer = null;
|
|
3652
|
+
}
|
|
3653
|
+
reject(err);
|
|
3654
|
+
});
|
|
3655
|
+
});
|
|
3656
|
+
}
|
|
3657
|
+
};
|
|
3658
|
+
async function findActiveSockets() {
|
|
3659
|
+
const active = [];
|
|
3660
|
+
if (process.platform === "win32") {
|
|
3661
|
+
const currentPipe = resolveIpcSocketPath(process.pid);
|
|
3662
|
+
const client = new IpcTelemetryClient(currentPipe);
|
|
3663
|
+
try {
|
|
3664
|
+
await client.ping(100);
|
|
3665
|
+
active.push(currentPipe);
|
|
3666
|
+
} catch {
|
|
3667
|
+
}
|
|
3668
|
+
try {
|
|
3669
|
+
const { execFileSync } = await import("child_process");
|
|
3670
|
+
const stdout = execFileSync(
|
|
3671
|
+
"powershell.exe",
|
|
3672
|
+
["-NoProfile", "-NonInteractive", "-Command", '[System.IO.Directory]::GetFiles("\\\\.\\pipe\\") | Where-Object { $_ -like "*tricache-*" }'],
|
|
3673
|
+
{ timeout: 1500, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }
|
|
3674
|
+
);
|
|
3675
|
+
const candidates = stdout.split(/\r?\n/).map((name) => name.trim()).filter((name) => name.length > 0 && !active.includes(name));
|
|
3676
|
+
await Promise.all(
|
|
3677
|
+
candidates.map(async (pipePath) => {
|
|
3678
|
+
const testClient = new IpcTelemetryClient(pipePath);
|
|
3679
|
+
try {
|
|
3680
|
+
await testClient.ping(100);
|
|
3681
|
+
active.push(pipePath);
|
|
3682
|
+
} catch {
|
|
3683
|
+
}
|
|
3684
|
+
})
|
|
3685
|
+
);
|
|
3686
|
+
} catch {
|
|
3687
|
+
}
|
|
3688
|
+
return active;
|
|
3689
|
+
}
|
|
3690
|
+
const dir = process.env.TMPDIR || "/tmp";
|
|
3691
|
+
try {
|
|
3692
|
+
if (!import_node_fs2.default.existsSync(dir)) return active;
|
|
3693
|
+
const entries = import_node_fs2.default.readdirSync(dir);
|
|
3694
|
+
const candidates = entries.filter((name) => name.startsWith("tricache-") && name.endsWith(".sock")).map((name) => import_node_path.default.join(dir, name));
|
|
3695
|
+
await Promise.all(
|
|
3696
|
+
candidates.map(async (sockPath) => {
|
|
3697
|
+
const client = new IpcTelemetryClient(sockPath);
|
|
3698
|
+
try {
|
|
3699
|
+
await client.ping(100);
|
|
3700
|
+
active.push(sockPath);
|
|
3701
|
+
} catch {
|
|
3702
|
+
}
|
|
3703
|
+
})
|
|
3704
|
+
);
|
|
3705
|
+
} catch {
|
|
3706
|
+
}
|
|
3707
|
+
return active;
|
|
3708
|
+
}
|
|
3709
|
+
function renderProgressBar(ratio, width = 18) {
|
|
3710
|
+
const clamped = Math.max(0, Math.min(1, isNaN(ratio) ? 0 : ratio));
|
|
3711
|
+
const filled = Math.round(clamped * width);
|
|
3712
|
+
const empty = width - filled;
|
|
3713
|
+
return "\u2588".repeat(filled) + "\u2591".repeat(empty);
|
|
3714
|
+
}
|
|
3715
|
+
function formatBytes(bytes) {
|
|
3716
|
+
if (!bytes || isNaN(bytes) || bytes < 0) return "0 B";
|
|
3717
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
3718
|
+
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
|
3719
|
+
if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
3720
|
+
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
|
|
3721
|
+
}
|
|
3722
|
+
function formatNumber(n) {
|
|
3723
|
+
return (n ?? 0).toLocaleString();
|
|
3724
|
+
}
|
|
3725
|
+
function formatDuration(ms) {
|
|
3726
|
+
if (ms < 1e3) return `${ms}ms`;
|
|
3727
|
+
const s = Math.floor(ms / 1e3);
|
|
3728
|
+
if (s < 60) return `${s}s`;
|
|
3729
|
+
const m = Math.floor(s / 60);
|
|
3730
|
+
const remS = s % 60;
|
|
3731
|
+
if (m < 60) return `${m}m ${remS}s`;
|
|
3732
|
+
const h = Math.floor(m / 60);
|
|
3733
|
+
const remM = m % 60;
|
|
3734
|
+
return `${h}h ${remM}m`;
|
|
3735
|
+
}
|
|
3736
|
+
function renderTopDashboard(payload) {
|
|
3737
|
+
const m = payload.metrics;
|
|
3738
|
+
const gets = m.gets;
|
|
3739
|
+
const l1Max = payload.l1MaxBytes || 200 * 1024 * 1024;
|
|
3740
|
+
const l1Used = m.l1.sizeBytes;
|
|
3741
|
+
const l1Pct = l1Max > 0 ? l1Used / l1Max : 0;
|
|
3742
|
+
const uptime = formatDuration(payload.uptimeMs);
|
|
3743
|
+
const ns = payload.namespace || "(default)";
|
|
3744
|
+
const pct = (r) => `${((r || 0) * 100).toFixed(1)}%`;
|
|
3745
|
+
const lines = [];
|
|
3746
|
+
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");
|
|
3747
|
+
lines.push(`\u2551 TriCache Monitor [PID: ${String(payload.pid).padEnd(6)}] Uptime: ${uptime.padEnd(8)} Namespace: ${ns.padEnd(16)}\u2551`);
|
|
3748
|
+
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");
|
|
3749
|
+
lines.push(`\u2551 Hit Ratios & Tier Breakdown (Total Gets: ${formatNumber(gets.total).padEnd(12)}) \u2551`);
|
|
3750
|
+
lines.push(`\u2551 L1 (RAM): [${renderProgressBar(gets.l1HitRate)}] ${pct(gets.l1HitRate).padStart(6)} (${formatNumber(gets.l1Hits).padStart(8)} hits) \u2551`);
|
|
3751
|
+
lines.push(`\u2551 L1.5(Disk): [${renderProgressBar(gets.diskHitRate)}] ${pct(gets.diskHitRate).padStart(6)} (${formatNumber(gets.diskHits).padStart(8)} hits) \u2551`);
|
|
3752
|
+
lines.push(`\u2551 L2 (Redis): [${renderProgressBar(gets.l2HitRate)}] ${pct(gets.l2HitRate).padStart(6)} (${formatNumber(gets.l2Hits).padStart(8)} hits) \u2551`);
|
|
3753
|
+
lines.push(`\u2551 Misses: [${renderProgressBar(gets.fetchRate)}] ${pct(gets.fetchRate).padStart(6)} (${formatNumber(gets.fetches).padStart(8)} fetches) \u2551`);
|
|
3754
|
+
lines.push(`\u2551 Stampedes Saved: ${formatNumber(gets.stampedePrevented).padEnd(8)} coalesced concurrent requests \u2551`);
|
|
3755
|
+
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");
|
|
3756
|
+
lines.push(`\u2551 Memory & Storage Headroom \u2551`);
|
|
3757
|
+
lines.push(`\u2551 L1 Memory: [${renderProgressBar(l1Pct)}] ${formatBytes(l1Used).padStart(8)} / ${formatBytes(l1Max).padEnd(8)} (${formatNumber(m.l1.entries).padStart(6)} entries) \u2551`);
|
|
3758
|
+
const diskFiles = m.disk?.files ?? 0;
|
|
3759
|
+
const diskKB = m.disk?.sizeKB ?? 0;
|
|
3760
|
+
const diskMaxKB = m.disk?.maxKB ?? 0;
|
|
3761
|
+
lines.push(`\u2551 Disk Spill: ${formatBytes(diskKB * 1024).padStart(8)} / ${formatBytes(diskMaxKB * 1024).padEnd(8)} (${formatNumber(diskFiles).padStart(6)} files) \u2551`);
|
|
3762
|
+
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");
|
|
3763
|
+
lines.push(`\u2551 Protection & Health Diagnostics \u2551`);
|
|
3764
|
+
const watchdog = m.disk?.latencyWatchdog;
|
|
3765
|
+
const bypassStage = watchdog ? `Stage ${watchdog.bypassStage} (${watchdog.bypassActive ? "ACTIVE" : "Normal"})` : "Stage 0 (Normal)";
|
|
3766
|
+
const cbState = m.l2CircuitBreaker?.state || "closed";
|
|
3767
|
+
lines.push(`\u2551 Watchdog: ${bypassStage.padEnd(20)} L2 Circuit Breaker: ${cbState.padEnd(20)}\u2551`);
|
|
3768
|
+
if (watchdog) {
|
|
3769
|
+
const diskP95 = `${watchdog.diskP95Ms.toFixed(2)}ms`;
|
|
3770
|
+
const redisP95 = `${watchdog.redisP95Ms.toFixed(2)}ms`;
|
|
3771
|
+
lines.push(`\u2551 Disk p95: ${diskP95.padEnd(10)} Redis p95: ${redisP95.padEnd(10)} Bypassed: ${formatNumber(watchdog.bypassedTotal).padEnd(16)}\u2551`);
|
|
3772
|
+
}
|
|
3773
|
+
const oomEvict = m.oom?.evictions ?? 0;
|
|
3774
|
+
lines.push(`\u2551 OOM Evictions: ${formatNumber(oomEvict).padEnd(6)} SWR Revalidations: ${formatNumber(m.revalidations?.total ?? 0).padEnd(14)} \u2551`);
|
|
3775
|
+
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");
|
|
3776
|
+
lines.push(`\u2551 \u{1F525} Top Hot Keys (Count-Min Sketch) \u2551`);
|
|
3777
|
+
if (!payload.hotKeys || payload.hotKeys.length === 0) {
|
|
3778
|
+
lines.push("\u2551 (no hot keys recorded yet) \u2551");
|
|
3779
|
+
} else {
|
|
3780
|
+
payload.hotKeys.slice(0, 5).forEach(({ key, hits, sizeBytes }, idx) => {
|
|
3781
|
+
const displayKey = key.length > 34 ? `${key.slice(0, 31)}...` : key;
|
|
3782
|
+
const hitStr = `${formatNumber(hits)} hits`;
|
|
3783
|
+
const sizeStr = formatBytes(sizeBytes);
|
|
3784
|
+
const row = ` ${idx + 1}. ${displayKey.padEnd(36)} ${hitStr.padStart(14)} (${sizeStr})`;
|
|
3785
|
+
lines.push(`\u2551${row.padEnd(86)}\u2551`);
|
|
3786
|
+
});
|
|
3787
|
+
}
|
|
3788
|
+
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");
|
|
3789
|
+
return lines.join("\n");
|
|
3790
|
+
}
|
|
3791
|
+
|
|
3792
|
+
// src/cache-service.ts
|
|
3793
|
+
var LUA_COMPARE_AND_DELETE = `
|
|
3794
|
+
local currentTs = redis.call('HGET', KEYS[1], 't')
|
|
3795
|
+
if currentTs and currentTs == ARGV[1] then
|
|
3796
|
+
return redis.call('DEL', KEYS[1])
|
|
3797
|
+
end
|
|
3798
|
+
return 0
|
|
3799
|
+
`;
|
|
3800
|
+
var SNAPSHOT_VERSION = 1;
|
|
3801
|
+
var DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
|
|
3802
|
+
var INDEFINITE_TTL_SECONDS = 31536e3;
|
|
3803
|
+
var SNAPSHOT_MAX_FILE_BYTES = 220 * 1024 * 1024;
|
|
3804
|
+
var DEFAULT_CATEGORY_LIMITS = {
|
|
3805
|
+
"default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
|
|
3806
|
+
};
|
|
3807
|
+
var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
|
|
3808
|
+
var DEFAULT_COUNTER_TTL_SECONDS = 60;
|
|
3809
|
+
var GLOB_REGEX_CACHE_MAX = 256;
|
|
3810
|
+
var globRegexCache = /* @__PURE__ */ new Map();
|
|
3811
|
+
function getGlobRegex(pattern) {
|
|
3812
|
+
let re = globRegexCache.get(pattern);
|
|
3813
|
+
if (re) {
|
|
3814
|
+
globRegexCache.delete(pattern);
|
|
3815
|
+
globRegexCache.set(pattern, re);
|
|
3816
|
+
return re;
|
|
3817
|
+
}
|
|
3818
|
+
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*+/g, ".*");
|
|
3819
|
+
re = new RegExp("^" + escaped + "$");
|
|
3820
|
+
if (globRegexCache.size >= GLOB_REGEX_CACHE_MAX) {
|
|
3821
|
+
const oldestKey = globRegexCache.keys().next().value;
|
|
3822
|
+
if (oldestKey !== void 0) globRegexCache.delete(oldestKey);
|
|
3823
|
+
}
|
|
3824
|
+
globRegexCache.set(pattern, re);
|
|
3825
|
+
return re;
|
|
3826
|
+
}
|
|
3827
|
+
var L2CircuitBreaker = class {
|
|
3828
|
+
constructor(threshold, cooldownMs) {
|
|
3829
|
+
this.threshold = threshold;
|
|
3830
|
+
this.cooldownMs = cooldownMs;
|
|
3831
|
+
}
|
|
3832
|
+
threshold;
|
|
3833
|
+
cooldownMs;
|
|
3834
|
+
state = 0 /* CLOSED */;
|
|
3835
|
+
failures = 0;
|
|
3836
|
+
openedAt = performance.now();
|
|
3837
|
+
/** True while the single permitted HALF_OPEN probe is in flight. */
|
|
3838
|
+
probing = false;
|
|
3839
|
+
/**
|
|
3840
|
+
* Call before each Redis attempt. Returns false when the circuit is open.
|
|
3841
|
+
* In HALF_OPEN, only ONE probe is permitted at a time — concurrent callers
|
|
3842
|
+
* arriving while a probe is outstanding are rejected (return false) so a
|
|
3843
|
+
* recovering Redis node is not stampeded.
|
|
3844
|
+
*/
|
|
3845
|
+
isAllowed() {
|
|
2410
3846
|
if (this.state === 0 /* CLOSED */) return true;
|
|
2411
3847
|
if (this.state === 2 /* HALF_OPEN */) {
|
|
2412
3848
|
if (this.probing) return false;
|
|
2413
3849
|
this.probing = true;
|
|
2414
3850
|
return true;
|
|
2415
3851
|
}
|
|
2416
|
-
|
|
3852
|
+
const now = this.openedAt > 1e12 ? Date.now() : performance.now();
|
|
3853
|
+
if (now - this.openedAt >= this.cooldownMs) {
|
|
2417
3854
|
this.state = 2 /* HALF_OPEN */;
|
|
2418
3855
|
this.probing = true;
|
|
2419
3856
|
return true;
|
|
@@ -2432,7 +3869,7 @@ var L2CircuitBreaker = class {
|
|
|
2432
3869
|
this.probing = false;
|
|
2433
3870
|
if (this.state === 2 /* HALF_OPEN */ || this.failures >= this.threshold) {
|
|
2434
3871
|
this.state = 1 /* OPEN */;
|
|
2435
|
-
this.openedAt =
|
|
3872
|
+
this.openedAt = performance.now();
|
|
2436
3873
|
this.failures = 0;
|
|
2437
3874
|
}
|
|
2438
3875
|
}
|
|
@@ -2549,9 +3986,86 @@ function detectServerlessRuntime() {
|
|
|
2549
3986
|
if (process.env["VERCEL"]) return "Vercel";
|
|
2550
3987
|
return null;
|
|
2551
3988
|
}
|
|
3989
|
+
var ProcessTerminationBus = class {
|
|
3990
|
+
static instances = /* @__PURE__ */ new Set();
|
|
3991
|
+
static registered = false;
|
|
3992
|
+
static sigtermHandler = null;
|
|
3993
|
+
static sigintHandler = null;
|
|
3994
|
+
static register(instance) {
|
|
3995
|
+
this.instances.add(instance);
|
|
3996
|
+
if (!this.registered) {
|
|
3997
|
+
this.registered = true;
|
|
3998
|
+
this.sigtermHandler = () => {
|
|
3999
|
+
for (const inst of this.instances) {
|
|
4000
|
+
try {
|
|
4001
|
+
inst._triggerShutdown();
|
|
4002
|
+
} catch {
|
|
4003
|
+
}
|
|
4004
|
+
}
|
|
4005
|
+
};
|
|
4006
|
+
this.sigintHandler = () => {
|
|
4007
|
+
for (const inst of this.instances) {
|
|
4008
|
+
try {
|
|
4009
|
+
inst._triggerShutdown();
|
|
4010
|
+
} catch {
|
|
4011
|
+
}
|
|
4012
|
+
}
|
|
4013
|
+
};
|
|
4014
|
+
process.on("SIGTERM", this.sigtermHandler);
|
|
4015
|
+
process.on("SIGINT", this.sigintHandler);
|
|
4016
|
+
}
|
|
4017
|
+
}
|
|
4018
|
+
static unregister(instance) {
|
|
4019
|
+
this.instances.delete(instance);
|
|
4020
|
+
if (this.instances.size === 0 && this.registered) {
|
|
4021
|
+
if (this.sigtermHandler) process.removeListener("SIGTERM", this.sigtermHandler);
|
|
4022
|
+
if (this.sigintHandler) process.removeListener("SIGINT", this.sigintHandler);
|
|
4023
|
+
this.sigtermHandler = null;
|
|
4024
|
+
this.sigintHandler = null;
|
|
4025
|
+
this.registered = false;
|
|
4026
|
+
}
|
|
4027
|
+
}
|
|
4028
|
+
/**
|
|
4029
|
+
* Flushes snapshots across all active registered cache instances concurrently.
|
|
4030
|
+
* Awaits both local disk and remote cloud snapshot uploads with timeout protection.
|
|
4031
|
+
*
|
|
4032
|
+
* @param timeoutMs Timeout in milliseconds per instance before aborting slow flushes. Default: 8000ms.
|
|
4033
|
+
*/
|
|
4034
|
+
static async flushAll(timeoutMs = 8e3) {
|
|
4035
|
+
if (this.instances.size === 0) return;
|
|
4036
|
+
const tasks = Array.from(this.instances).map((inst) => inst.flushSnapshotOnShutdown(timeoutMs));
|
|
4037
|
+
await Promise.allSettled(tasks);
|
|
4038
|
+
}
|
|
4039
|
+
/** For testing diagnostics and assertions */
|
|
4040
|
+
static get size() {
|
|
4041
|
+
return this.instances.size;
|
|
4042
|
+
}
|
|
4043
|
+
static get isRegistered() {
|
|
4044
|
+
return this.registered;
|
|
4045
|
+
}
|
|
4046
|
+
};
|
|
4047
|
+
function isPlainObject(item) {
|
|
4048
|
+
return typeof item === "object" && item !== null && item.constructor === Object;
|
|
4049
|
+
}
|
|
4050
|
+
function deepMergeOptions(base, overrides) {
|
|
4051
|
+
if (!overrides) return { ...base };
|
|
4052
|
+
const output = { ...base };
|
|
4053
|
+
for (const key of Object.keys(overrides)) {
|
|
4054
|
+
const sourceVal = overrides[key];
|
|
4055
|
+
if (sourceVal === void 0) continue;
|
|
4056
|
+
const targetVal = output[key];
|
|
4057
|
+
if (isPlainObject(targetVal) && isPlainObject(sourceVal)) {
|
|
4058
|
+
output[key] = deepMergeOptions(targetVal, sourceVal);
|
|
4059
|
+
} else {
|
|
4060
|
+
output[key] = sourceVal;
|
|
4061
|
+
}
|
|
4062
|
+
}
|
|
4063
|
+
return output;
|
|
4064
|
+
}
|
|
2552
4065
|
var CacheService = class _CacheService {
|
|
2553
4066
|
logger;
|
|
2554
4067
|
enc;
|
|
4068
|
+
codec;
|
|
2555
4069
|
l1;
|
|
2556
4070
|
disk;
|
|
2557
4071
|
/** When true, all disk-tier and snapshot operations are skipped. */
|
|
@@ -2563,6 +4077,8 @@ var CacheService = class _CacheService {
|
|
|
2563
4077
|
_namespace;
|
|
2564
4078
|
/** Pre-computed once — disableRedis and redisHost never change after construction. */
|
|
2565
4079
|
_redisDisabled;
|
|
4080
|
+
watchdog;
|
|
4081
|
+
pipeliner = null;
|
|
2566
4082
|
inflight = /* @__PURE__ */ new Map();
|
|
2567
4083
|
revalidating = /* @__PURE__ */ new Set();
|
|
2568
4084
|
_l1Counters = /* @__PURE__ */ new Map();
|
|
@@ -2588,6 +4104,7 @@ var CacheService = class _CacheService {
|
|
|
2588
4104
|
diskJanitorInterval = null;
|
|
2589
4105
|
oomInterval = null;
|
|
2590
4106
|
metricsInterval = null;
|
|
4107
|
+
remoteSnapshotInterval = null;
|
|
2591
4108
|
_shutdownHandler = null;
|
|
2592
4109
|
latencyTracker = null;
|
|
2593
4110
|
instanceId;
|
|
@@ -2597,8 +4114,57 @@ var CacheService = class _CacheService {
|
|
|
2597
4114
|
streamClient = null;
|
|
2598
4115
|
_lastStreamId = "$";
|
|
2599
4116
|
_destroyed = false;
|
|
4117
|
+
_pendingDiskDeletes = /* @__PURE__ */ new Set();
|
|
4118
|
+
_globalEpoch = 0;
|
|
4119
|
+
_keyMutationEpochs = /* @__PURE__ */ new Map();
|
|
4120
|
+
/**
|
|
4121
|
+
* Pattern tombstones for disk tier.
|
|
4122
|
+
* Files in the disk tier are keyed by SHA-256 of namespacedKey.
|
|
4123
|
+
* Wildcard pattern deletes cannot scan the filesystem synchronously, so we maintain
|
|
4124
|
+
* pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
|
|
4125
|
+
*/
|
|
4126
|
+
_patternTombstones = [];
|
|
4127
|
+
_addPatternTombstone(prefix) {
|
|
4128
|
+
const now = Date.now();
|
|
4129
|
+
while (this._patternTombstones.length > 0 && now - this._patternTombstones[0].createdAt > 36e5) {
|
|
4130
|
+
this._patternTombstones.shift();
|
|
4131
|
+
}
|
|
4132
|
+
if (this._patternTombstones.length >= 2e3) {
|
|
4133
|
+
this._patternTombstones.shift();
|
|
4134
|
+
}
|
|
4135
|
+
this._patternTombstones.push({ prefix, createdAt: now });
|
|
4136
|
+
}
|
|
4137
|
+
_isTombstonedByPattern(namespacedKey) {
|
|
4138
|
+
if (this._patternTombstones.length === 0) return false;
|
|
4139
|
+
for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
|
|
4140
|
+
if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
|
|
4141
|
+
return true;
|
|
4142
|
+
}
|
|
4143
|
+
}
|
|
4144
|
+
return false;
|
|
4145
|
+
}
|
|
4146
|
+
_assertActive(operation) {
|
|
4147
|
+
if (this._destroyed) {
|
|
4148
|
+
throw new Error(`TriCacheError: Cannot perform '${operation}' on a destroyed CacheService instance (namespace: '${this._namespace || "(default)"}').`);
|
|
4149
|
+
}
|
|
4150
|
+
}
|
|
4151
|
+
_bumpKeyMutation(namespacedKey) {
|
|
4152
|
+
const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
|
|
4153
|
+
this._keyMutationEpochs.set(namespacedKey, next);
|
|
4154
|
+
if (this._keyMutationEpochs.size > 5e4) {
|
|
4155
|
+
const oldest = this._keyMutationEpochs.keys().next().value;
|
|
4156
|
+
if (oldest !== void 0) this._keyMutationEpochs.delete(oldest);
|
|
4157
|
+
}
|
|
4158
|
+
return next;
|
|
4159
|
+
}
|
|
4160
|
+
_getKeyMutationEpoch(namespacedKey) {
|
|
4161
|
+
return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
|
|
4162
|
+
}
|
|
4163
|
+
_ipcServer;
|
|
2600
4164
|
/** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
|
|
2601
4165
|
_subDisconnectedAt = null;
|
|
4166
|
+
/** Deduplication ring buffer for incoming and outgoing cross-region invalidations (loop prevention) */
|
|
4167
|
+
_seenCrossRegionEvents = /* @__PURE__ */ new Map();
|
|
2602
4168
|
counters = {
|
|
2603
4169
|
gets: 0,
|
|
2604
4170
|
l1Hits: 0,
|
|
@@ -2623,7 +4189,16 @@ var CacheService = class _CacheService {
|
|
|
2623
4189
|
singletonDivergences: 0,
|
|
2624
4190
|
startedAt: Date.now(),
|
|
2625
4191
|
bloomChecks: 0,
|
|
2626
|
-
bloomFalsePositives: 0
|
|
4192
|
+
bloomFalsePositives: 0,
|
|
4193
|
+
remoteSnapshotUploads: 0,
|
|
4194
|
+
remoteSnapshotDownloads: 0,
|
|
4195
|
+
remoteSnapshotErrors: 0,
|
|
4196
|
+
remoteSnapshotLastUploadedAt: null,
|
|
4197
|
+
remoteSnapshotLastDownloadedAt: null,
|
|
4198
|
+
crossRegionSent: 0,
|
|
4199
|
+
crossRegionReceived: 0,
|
|
4200
|
+
crossRegionDeduplicated: 0,
|
|
4201
|
+
crossRegionErrors: 0
|
|
2627
4202
|
};
|
|
2628
4203
|
/** One-time guard so the in-process increment() fallback warning fires only once. */
|
|
2629
4204
|
_incrementFallbackWarned = false;
|
|
@@ -2646,16 +4221,14 @@ var CacheService = class _CacheService {
|
|
|
2646
4221
|
this.opts = {
|
|
2647
4222
|
namespace: ns,
|
|
2648
4223
|
logger,
|
|
2649
|
-
l1MaxBytes: options.l1MaxBytes ??
|
|
4224
|
+
l1MaxBytes: options.l1MaxBytes ?? resolveAutonomousL1MaxBytes(),
|
|
2650
4225
|
l1MaxEntries: options.l1MaxEntries ?? 2e3,
|
|
2651
4226
|
categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...options.categoryLimits },
|
|
2652
4227
|
forbiddenSnapshotPrefixes: forbiddenPrefixes,
|
|
2653
4228
|
// Namespace-isolated defaults: separate dir / snapshot per namespace so
|
|
2654
4229
|
// two instances with different namespaces never share cache files.
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
ns ? `tricache-disk-${ns}` : "tricache-disk"
|
|
2658
|
-
),
|
|
4230
|
+
// Automatically probes /dev/shm tmpfs on Linux (>=256MB capacity and >=128MB free) for off-heap RAM speed.
|
|
4231
|
+
diskCacheDir: options.diskCacheDir ?? resolveDefaultDiskDir(ns, logger).dir,
|
|
2659
4232
|
diskMaxBytes: options.diskMaxBytes ?? 500 * 1024 * 1024,
|
|
2660
4233
|
diskEntryMaxBytes: options.diskEntryMaxBytes ?? 10 * 1024 * 1024,
|
|
2661
4234
|
redisHost: options.redisHost ?? process.env.REDIS_HOST ?? "",
|
|
@@ -2663,18 +4236,20 @@ var CacheService = class _CacheService {
|
|
|
2663
4236
|
redisTls: options.redisTls ?? process.env.NODE_ENV === "production",
|
|
2664
4237
|
disableRedis: options.disableRedis ?? (() => {
|
|
2665
4238
|
const explicitConfig = Boolean(
|
|
2666
|
-
options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
|
|
4239
|
+
options.redisClient || options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
|
|
2667
4240
|
);
|
|
2668
4241
|
return !explicitConfig && process.env.NODE_ENV !== "production";
|
|
2669
4242
|
})(),
|
|
2670
4243
|
encryptionKey: encKeyRaw,
|
|
2671
4244
|
encryptionMode: options.encryptionMode,
|
|
2672
4245
|
snapshotPath: options.snapshotPath ?? import_path3.default.join(
|
|
2673
|
-
|
|
4246
|
+
import_os3.default.tmpdir(),
|
|
2674
4247
|
ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
|
|
2675
4248
|
),
|
|
2676
4249
|
snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
|
|
2677
4250
|
invalidationBackplane: options.invalidationBackplane ?? true,
|
|
4251
|
+
awaitInvalidationBackplane: options.awaitInvalidationBackplane ?? false,
|
|
4252
|
+
lockFailClosed: options.lockFailClosed ?? false,
|
|
2678
4253
|
oomProtection: options.oomProtection ?? true,
|
|
2679
4254
|
oomHeapThreshold: options.oomHeapThreshold ?? 0.85,
|
|
2680
4255
|
oomCheckIntervalMs: options.oomCheckIntervalMs ?? 1e4,
|
|
@@ -2718,8 +4293,35 @@ var CacheService = class _CacheService {
|
|
|
2718
4293
|
backplaneMode: options.backplaneMode ?? "pubsub",
|
|
2719
4294
|
backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
|
|
2720
4295
|
backplaneStreamBlockMs: options.backplaneStreamBlockMs ?? 2e3,
|
|
2721
|
-
backplaneStreamKey: options.backplaneStreamKey
|
|
4296
|
+
backplaneStreamKey: options.backplaneStreamKey,
|
|
4297
|
+
serializeToJSON: options.serializeToJSON ?? true,
|
|
4298
|
+
remoteSnapshot: options.remoteSnapshot,
|
|
4299
|
+
crossRegion: options.crossRegion,
|
|
4300
|
+
redisClient: options.redisClient,
|
|
4301
|
+
redisSubClient: options.redisSubClient,
|
|
4302
|
+
diskMaxConcurrentWrites: options.diskMaxConcurrentWrites,
|
|
4303
|
+
diskMaxPendingWrites: options.diskMaxPendingWrites,
|
|
4304
|
+
diskWriteTimeoutMs: options.diskWriteTimeoutMs,
|
|
4305
|
+
diskCircuitBreakerThreshold: options.diskCircuitBreakerThreshold,
|
|
4306
|
+
diskCircuitBreakerCooldownMs: options.diskCircuitBreakerCooldownMs,
|
|
4307
|
+
redisCommandTimeoutMs: options.redisCommandTimeoutMs,
|
|
4308
|
+
clockSkewToleranceMs: options.clockSkewToleranceMs ?? 250,
|
|
4309
|
+
l1AdmissionPolicy: options.l1AdmissionPolicy,
|
|
4310
|
+
diskLatencyWatchdog: options.diskLatencyWatchdog ?? true,
|
|
4311
|
+
diskLatencyBypassRatio: options.diskLatencyBypassRatio ?? 1.5,
|
|
4312
|
+
diskLatencyBypassMinMs: options.diskLatencyBypassMinMs ?? 10,
|
|
4313
|
+
diskLatencyBypassCooldownMs: options.diskLatencyBypassCooldownMs ?? 3e4,
|
|
4314
|
+
failReadinessOnDegraded: options.failReadinessOnDegraded ?? false,
|
|
4315
|
+
autoPipeline: options.autoPipeline ?? false,
|
|
4316
|
+
maxPipelineBatchSize: options.maxPipelineBatchSize ?? 100,
|
|
4317
|
+
enableIpc: options.enableIpc ?? false,
|
|
4318
|
+
ipcSocketPath: options.ipcSocketPath
|
|
2722
4319
|
};
|
|
4320
|
+
this.codec = new CacheCodec({
|
|
4321
|
+
useToJSON: this.opts.serializeToJSON,
|
|
4322
|
+
useRecords: true,
|
|
4323
|
+
moreTypes: true
|
|
4324
|
+
});
|
|
2723
4325
|
const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
|
|
2724
4326
|
const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
|
|
2725
4327
|
this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
|
|
@@ -2750,15 +4352,33 @@ var CacheService = class _CacheService {
|
|
|
2750
4352
|
encryption: this.enc.isEnabled ? this.enc : null,
|
|
2751
4353
|
compression: this.opts.compression,
|
|
2752
4354
|
compressionThresholdBytes: this.opts.compressionThresholdBytes,
|
|
2753
|
-
logger
|
|
4355
|
+
logger,
|
|
4356
|
+
codec: this.codec,
|
|
4357
|
+
diskMaxConcurrentWrites: this.opts.diskMaxConcurrentWrites,
|
|
4358
|
+
diskMaxPendingWrites: this.opts.diskMaxPendingWrites,
|
|
4359
|
+
diskWriteTimeoutMs: this.opts.diskWriteTimeoutMs,
|
|
4360
|
+
diskCircuitBreakerThreshold: this.opts.diskCircuitBreakerThreshold,
|
|
4361
|
+
diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs
|
|
2754
4362
|
});
|
|
2755
4363
|
this._namespace = ns;
|
|
2756
|
-
this._redisDisabled = this.opts.disableRedis || !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
|
|
4364
|
+
this._redisDisabled = this.opts.disableRedis || !this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
|
|
4365
|
+
this.watchdog = new TierLatencyWatchdog({
|
|
4366
|
+
enabled: options.diskLatencyWatchdog ?? true,
|
|
4367
|
+
minDiskBypassMs: options.diskLatencyBypassMinMs ?? 10,
|
|
4368
|
+
bypassRatio: options.diskLatencyBypassRatio ?? 1.5,
|
|
4369
|
+
cooldownMs: options.diskLatencyBypassCooldownMs ?? 3e4,
|
|
4370
|
+
redisCutoffMs: 15,
|
|
4371
|
+
redisRecoveryFloorMs: 10,
|
|
4372
|
+
minSamples: 16,
|
|
4373
|
+
disableRedis: this._redisDisabled
|
|
4374
|
+
});
|
|
2757
4375
|
this.l1 = new SmartMemoryCache({
|
|
2758
4376
|
maxBytes: this.opts.l1MaxBytes,
|
|
2759
4377
|
maxEntries: this.opts.l1MaxEntries,
|
|
2760
4378
|
categories: this.opts.categoryLimits,
|
|
2761
4379
|
evictionWatermark: this.opts.l1EvictionWatermark,
|
|
4380
|
+
admissionPolicy: this.opts.l1AdmissionPolicy,
|
|
4381
|
+
codec: this.codec,
|
|
2762
4382
|
diskSpill: (key, entry) => {
|
|
2763
4383
|
if (this._diskDisabled) return;
|
|
2764
4384
|
setImmediate(() => {
|
|
@@ -2773,10 +4393,9 @@ var CacheService = class _CacheService {
|
|
|
2773
4393
|
if (!this._diskDisabled) this.loadSnapshot();
|
|
2774
4394
|
}
|
|
2775
4395
|
this._shutdownHandler = () => {
|
|
2776
|
-
|
|
4396
|
+
this._triggerShutdown();
|
|
2777
4397
|
};
|
|
2778
|
-
|
|
2779
|
-
process.once("SIGINT", this._shutdownHandler);
|
|
4398
|
+
ProcessTerminationBus.register(this);
|
|
2780
4399
|
if (this.opts.workerThreads) {
|
|
2781
4400
|
try {
|
|
2782
4401
|
const encRef = this.enc.toWorkerInit();
|
|
@@ -2816,7 +4435,7 @@ var CacheService = class _CacheService {
|
|
|
2816
4435
|
}
|
|
2817
4436
|
if (this.opts.oomProtection) {
|
|
2818
4437
|
this.oomInterval = setInterval(() => {
|
|
2819
|
-
const heap =
|
|
4438
|
+
const heap = import_node_v82.default.getHeapStatistics();
|
|
2820
4439
|
const used = heap.used_heap_size / heap.heap_size_limit;
|
|
2821
4440
|
if (used >= this.opts.oomHeapThreshold) {
|
|
2822
4441
|
const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
|
|
@@ -2840,12 +4459,25 @@ var CacheService = class _CacheService {
|
|
|
2840
4459
|
}, this.opts.metricsIntervalMs);
|
|
2841
4460
|
if (this.metricsInterval.unref) this.metricsInterval.unref();
|
|
2842
4461
|
}
|
|
4462
|
+
if (this.opts.remoteSnapshot?.intervalMs && this.opts.remoteSnapshot.intervalMs > 0) {
|
|
4463
|
+
this.remoteSnapshotInterval = setInterval(() => {
|
|
4464
|
+
void this.writeRemoteSnapshot();
|
|
4465
|
+
}, this.opts.remoteSnapshot.intervalMs);
|
|
4466
|
+
if (this.remoteSnapshotInterval.unref) this.remoteSnapshotInterval.unref();
|
|
4467
|
+
}
|
|
2843
4468
|
this.instanceId = import_crypto3.default.randomBytes(8).toString("hex");
|
|
2844
4469
|
this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
|
|
2845
4470
|
this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
|
|
2846
4471
|
this.initBackplane();
|
|
4472
|
+
const startupPromises = [];
|
|
4473
|
+
if (this.opts.remoteSnapshot) {
|
|
4474
|
+
startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
|
|
4475
|
+
}
|
|
2847
4476
|
if (this.opts.warmKeys) {
|
|
2848
|
-
|
|
4477
|
+
startupPromises.push(this.warmFromL2(this.opts.warmKeys).then(() => void 0));
|
|
4478
|
+
}
|
|
4479
|
+
if (startupPromises.length > 0) {
|
|
4480
|
+
this._readyPromise = Promise.all(startupPromises).then(() => void 0);
|
|
2849
4481
|
}
|
|
2850
4482
|
if (this.opts.meter) {
|
|
2851
4483
|
this._initOtelMetrics(this.opts.meter);
|
|
@@ -2866,8 +4498,71 @@ var CacheService = class _CacheService {
|
|
|
2866
4498
|
}
|
|
2867
4499
|
});
|
|
2868
4500
|
}
|
|
4501
|
+
if (this.opts.enableIpc) {
|
|
4502
|
+
this._ipcServer = new IpcTelemetryServer(this, this.opts.ipcSocketPath);
|
|
4503
|
+
this._ipcServer.start().catch((err) => {
|
|
4504
|
+
this.logger.warn("Failed to start IPC telemetry server", { error: err.message });
|
|
4505
|
+
});
|
|
4506
|
+
}
|
|
4507
|
+
}
|
|
4508
|
+
// ── Singleton factory & Presets ───────────────────────────────────────────
|
|
4509
|
+
/**
|
|
4510
|
+
* Pre-configured production presets tailored for specific deployment environments.
|
|
4511
|
+
*
|
|
4512
|
+
* - `'nextjs'`: W-TinyLFU, zero-copy cloneStrategy: 'none' (React 19 RSC stream optimized),
|
|
4513
|
+
* generational tags, and Redis stream backplane.
|
|
4514
|
+
* - `'microservice'`: High-throughput Node.js microservice with W-TinyLFU, Streams backplane,
|
|
4515
|
+
* TTL jitter, and L2 circuit breaking.
|
|
4516
|
+
* - `'serverless'`: Stateless Lambda / Cloud Run isolate with memory-only L1, fast timeouts,
|
|
4517
|
+
* and Pub/Sub backplane.
|
|
4518
|
+
* - `'enterprise-hardened'`: Zero-trust production setup with generational tagging, Streams backplane,
|
|
4519
|
+
* fail-closed rate-limits, strict singleton assertions, and 80% OOM guard.
|
|
4520
|
+
*
|
|
4521
|
+
* @param type The preset identifier ('nextjs' | 'microservice' | 'serverless' | 'enterprise-hardened')
|
|
4522
|
+
* @param overrides Optional configuration overrides merged deeply over preset defaults
|
|
4523
|
+
* @returns Singleton CacheService instance configured according to the preset
|
|
4524
|
+
*/
|
|
4525
|
+
static preset(type, overrides) {
|
|
4526
|
+
const PRESETS = {
|
|
4527
|
+
"nextjs": {
|
|
4528
|
+
l1AdmissionPolicy: "wtinylfu",
|
|
4529
|
+
cloneStrategy: "none",
|
|
4530
|
+
tagStrategy: "generational",
|
|
4531
|
+
tagVersionTtlMs: 2e3,
|
|
4532
|
+
backplaneMode: "stream",
|
|
4533
|
+
staleIfError: 300,
|
|
4534
|
+
compression: "none"
|
|
4535
|
+
},
|
|
4536
|
+
"microservice": {
|
|
4537
|
+
l1AdmissionPolicy: "wtinylfu",
|
|
4538
|
+
backplaneMode: "stream",
|
|
4539
|
+
ttlJitterFactor: 0.15,
|
|
4540
|
+
l2CircuitBreakerThreshold: 5,
|
|
4541
|
+
l2CircuitBreakerCooldownMs: 15e3
|
|
4542
|
+
},
|
|
4543
|
+
"serverless": {
|
|
4544
|
+
disableDisk: true,
|
|
4545
|
+
l1AdmissionPolicy: "wtinylfu",
|
|
4546
|
+
backplaneMode: "pubsub",
|
|
4547
|
+
redisCommandTimeoutMs: 1e3
|
|
4548
|
+
},
|
|
4549
|
+
"enterprise-hardened": {
|
|
4550
|
+
l1AdmissionPolicy: "wtinylfu",
|
|
4551
|
+
tagStrategy: "generational",
|
|
4552
|
+
backplaneMode: "stream",
|
|
4553
|
+
strictSingleton: true,
|
|
4554
|
+
failClosed: true,
|
|
4555
|
+
oomProtection: true,
|
|
4556
|
+
oomHeapThreshold: 0.8
|
|
4557
|
+
}
|
|
4558
|
+
};
|
|
4559
|
+
const base = PRESETS[type];
|
|
4560
|
+
if (!base) {
|
|
4561
|
+
throw new Error(`tricache: unknown preset '${type}'. Supported presets: 'nextjs', 'microservice', 'serverless', 'enterprise-hardened'`);
|
|
4562
|
+
}
|
|
4563
|
+
const merged = deepMergeOptions(base, overrides);
|
|
4564
|
+
return _CacheService.create(merged);
|
|
2869
4565
|
}
|
|
2870
|
-
// ── Singleton factory ─────────────────────────────────────────────────────
|
|
2871
4566
|
/**
|
|
2872
4567
|
* Get (or create) the process-level singleton CacheService instance.
|
|
2873
4568
|
*
|
|
@@ -2920,7 +4615,9 @@ var CacheService = class _CacheService {
|
|
|
2920
4615
|
"adaptiveTtl",
|
|
2921
4616
|
"l2WriteMode",
|
|
2922
4617
|
"instanceName",
|
|
2923
|
-
"invalidationBackplane"
|
|
4618
|
+
"invalidationBackplane",
|
|
4619
|
+
"awaitInvalidationBackplane",
|
|
4620
|
+
"lockFailClosed"
|
|
2924
4621
|
];
|
|
2925
4622
|
/** Returns the names of options that differ between `a` and the live `b`. */
|
|
2926
4623
|
static optionsDiff(a, b) {
|
|
@@ -2961,7 +4658,11 @@ var CacheService = class _CacheService {
|
|
|
2961
4658
|
frozen: o.frozen,
|
|
2962
4659
|
adaptiveTtl: o.adaptiveTtl,
|
|
2963
4660
|
invalidationBackplane: o.invalidationBackplane,
|
|
2964
|
-
|
|
4661
|
+
awaitInvalidationBackplane: o.awaitInvalidationBackplane,
|
|
4662
|
+
lockFailClosed: o.lockFailClosed,
|
|
4663
|
+
strictSingleton: o.strictSingleton,
|
|
4664
|
+
remoteSnapshot: o.remoteSnapshot,
|
|
4665
|
+
crossRegion: o.crossRegion
|
|
2965
4666
|
};
|
|
2966
4667
|
}
|
|
2967
4668
|
/**
|
|
@@ -3020,15 +4721,30 @@ var CacheService = class _CacheService {
|
|
|
3020
4721
|
setStatus() {
|
|
3021
4722
|
return this;
|
|
3022
4723
|
},
|
|
4724
|
+
recordException() {
|
|
4725
|
+
return this;
|
|
4726
|
+
},
|
|
3023
4727
|
end() {
|
|
3024
4728
|
}
|
|
3025
4729
|
};
|
|
3026
4730
|
/** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
|
|
3027
|
-
_startSpan(name) {
|
|
3028
|
-
if (this.opts.tracer)
|
|
4731
|
+
_startSpan(name, links) {
|
|
4732
|
+
if (this.opts.tracer) {
|
|
4733
|
+
const span = this.opts.tracer.startSpan(name, links?.length ? { links } : void 0);
|
|
4734
|
+
if (this.opts.namespace) {
|
|
4735
|
+
span.setAttribute("cache.namespace", this.opts.namespace);
|
|
4736
|
+
}
|
|
4737
|
+
return span;
|
|
4738
|
+
}
|
|
3029
4739
|
return _CacheService._nullSpan;
|
|
3030
4740
|
}
|
|
3031
4741
|
createDedicatedRedisClient() {
|
|
4742
|
+
if (this.opts.redisSubClient) {
|
|
4743
|
+
return this.opts.redisSubClient;
|
|
4744
|
+
}
|
|
4745
|
+
if (this.opts.redisClient && typeof this.opts.redisClient.duplicate === "function") {
|
|
4746
|
+
return this.opts.redisClient.duplicate();
|
|
4747
|
+
}
|
|
3032
4748
|
if (this.opts.redisClusterNodes?.length) {
|
|
3033
4749
|
return new import_ioredis.Cluster(this.opts.redisClusterNodes, {
|
|
3034
4750
|
redisOptions: {
|
|
@@ -3229,16 +4945,36 @@ var CacheService = class _CacheService {
|
|
|
3229
4945
|
_applyInvalidationEvent(op, key, tagVersion) {
|
|
3230
4946
|
if (op === "del") {
|
|
3231
4947
|
this.l1.delete(key);
|
|
4948
|
+
this._bumpKeyMutation(key);
|
|
4949
|
+
this.inflight.delete(key);
|
|
4950
|
+
this._pendingDiskDeletes.add(key);
|
|
3232
4951
|
setImmediate(() => {
|
|
3233
|
-
|
|
4952
|
+
try {
|
|
4953
|
+
if (!this._diskDisabled) this.disk.delete(key);
|
|
4954
|
+
} finally {
|
|
4955
|
+
this._pendingDiskDeletes.delete(key);
|
|
4956
|
+
}
|
|
3234
4957
|
});
|
|
3235
4958
|
this._cascadeDependencies(key);
|
|
3236
4959
|
} else if (op === "del-glob") {
|
|
3237
4960
|
this.l1.deletePattern(key);
|
|
4961
|
+
const pfx = key.endsWith("*") ? key.slice(0, -1) : key;
|
|
4962
|
+
for (const liveKey of this.l1.liveKeys()) {
|
|
4963
|
+
if (liveKey.startsWith(pfx)) {
|
|
4964
|
+
this._bumpKeyMutation(liveKey);
|
|
4965
|
+
}
|
|
4966
|
+
}
|
|
4967
|
+
for (const inflightKey of Array.from(this.inflight.keys())) {
|
|
4968
|
+
if (inflightKey.startsWith(pfx)) {
|
|
4969
|
+
this._bumpKeyMutation(inflightKey);
|
|
4970
|
+
this.inflight.delete(inflightKey);
|
|
4971
|
+
}
|
|
4972
|
+
}
|
|
4973
|
+
this._addPatternTombstone(pfx);
|
|
3238
4974
|
} else if (op === "tag_incr") {
|
|
3239
4975
|
const tag = key;
|
|
3240
4976
|
const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
3241
|
-
this._setLocalTagVersion(tag, ver,
|
|
4977
|
+
this._setLocalTagVersion(tag, ver, performance.now());
|
|
3242
4978
|
}
|
|
3243
4979
|
this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
|
|
3244
4980
|
}
|
|
@@ -3262,7 +4998,17 @@ var CacheService = class _CacheService {
|
|
|
3262
4998
|
this.logger.warn("Backplane: malformed message JSON parse failed");
|
|
3263
4999
|
}
|
|
3264
5000
|
}
|
|
3265
|
-
async publishInvalidation(op, key, tagVersion) {
|
|
5001
|
+
async publishInvalidation(op, key, tagVersion, isCrossRegionRelay = false, isExplicitInvalidation = false) {
|
|
5002
|
+
if (!isCrossRegionRelay && this.opts.crossRegion) {
|
|
5003
|
+
const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
|
|
5004
|
+
if (shouldBroadcast) {
|
|
5005
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
5006
|
+
await this._broadcastCrossRegion(op, key, tagVersion);
|
|
5007
|
+
} else {
|
|
5008
|
+
void this._broadcastCrossRegion(op, key, tagVersion);
|
|
5009
|
+
}
|
|
5010
|
+
}
|
|
5011
|
+
}
|
|
3266
5012
|
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
3267
5013
|
try {
|
|
3268
5014
|
const client = await this.getRedis();
|
|
@@ -3301,10 +5047,87 @@ var CacheService = class _CacheService {
|
|
|
3301
5047
|
);
|
|
3302
5048
|
}
|
|
3303
5049
|
this.counters.invSent++;
|
|
3304
|
-
} catch {
|
|
5050
|
+
} catch (err) {
|
|
5051
|
+
this.logger.warn("Backplane invalidation publish failed", { op, key, error: err.message });
|
|
5052
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
5053
|
+
throw err;
|
|
5054
|
+
}
|
|
5055
|
+
}
|
|
5056
|
+
}
|
|
5057
|
+
_markCrossRegionEventSeen(id) {
|
|
5058
|
+
const maxDedup = this.opts.crossRegion?.dedupCacheSize ?? 1e4;
|
|
5059
|
+
if (this._seenCrossRegionEvents.size >= maxDedup) {
|
|
5060
|
+
const oldestKey = this._seenCrossRegionEvents.keys().next().value;
|
|
5061
|
+
if (oldestKey !== void 0) this._seenCrossRegionEvents.delete(oldestKey);
|
|
5062
|
+
}
|
|
5063
|
+
this._seenCrossRegionEvents.set(id, Date.now());
|
|
5064
|
+
}
|
|
5065
|
+
_isCrossRegionEventSeen(id) {
|
|
5066
|
+
return this._seenCrossRegionEvents.has(id);
|
|
5067
|
+
}
|
|
5068
|
+
async _broadcastCrossRegion(op, key, tagVersion) {
|
|
5069
|
+
const cr = this.opts.crossRegion;
|
|
5070
|
+
if (!cr) return;
|
|
5071
|
+
try {
|
|
5072
|
+
const eventId = import_crypto3.default.randomUUID();
|
|
5073
|
+
this._markCrossRegionEventSeen(eventId);
|
|
5074
|
+
const event = {
|
|
5075
|
+
id: eventId,
|
|
5076
|
+
originRegion: cr.currentRegion,
|
|
5077
|
+
originInstanceId: this.instanceId,
|
|
5078
|
+
op,
|
|
5079
|
+
key,
|
|
5080
|
+
tagVersion,
|
|
5081
|
+
timestamp: Date.now(),
|
|
5082
|
+
namespace: this._namespace || void 0
|
|
5083
|
+
};
|
|
5084
|
+
this.counters.crossRegionSent++;
|
|
5085
|
+
await cr.relay.broadcast(event);
|
|
5086
|
+
this.logger.debug("Cross-region invalidation broadcast", { op, key, region: cr.currentRegion });
|
|
5087
|
+
} catch (err) {
|
|
5088
|
+
this.counters.crossRegionSent = Math.max(0, this.counters.crossRegionSent - 1);
|
|
5089
|
+
this.counters.crossRegionErrors++;
|
|
5090
|
+
this.logger.warn("Cross-region invalidation broadcast failed", { error: err.message });
|
|
5091
|
+
}
|
|
5092
|
+
}
|
|
5093
|
+
/**
|
|
5094
|
+
* Receives an invalidation event from another region (e.g. via HTTP webhook or broker subscriber).
|
|
5095
|
+
* Validates origin, deduplicates to prevent loops, applies locally to L1/disk,
|
|
5096
|
+
* and fans out to the local Redis backplane so all regional peers invalidate as well.
|
|
5097
|
+
*
|
|
5098
|
+
* Returns true if the event was accepted and applied, or false if ignored/deduplicated.
|
|
5099
|
+
*/
|
|
5100
|
+
async receiveCrossRegionInvalidation(event) {
|
|
5101
|
+
const cr = this.opts.crossRegion;
|
|
5102
|
+
if (!cr) return false;
|
|
5103
|
+
if (!event || typeof event !== "object" || !event.id || !event.originRegion || !event.op || !event.key) {
|
|
5104
|
+
this.counters.crossRegionErrors++;
|
|
5105
|
+
this.logger.warn("Cross-region: rejected invalid event payload", { event });
|
|
5106
|
+
return false;
|
|
5107
|
+
}
|
|
5108
|
+
if (event.originRegion === cr.currentRegion) {
|
|
5109
|
+
this.counters.crossRegionDeduplicated++;
|
|
5110
|
+
return false;
|
|
5111
|
+
}
|
|
5112
|
+
if (this._isCrossRegionEventSeen(event.id)) {
|
|
5113
|
+
this.counters.crossRegionDeduplicated++;
|
|
5114
|
+
return false;
|
|
5115
|
+
}
|
|
5116
|
+
this._markCrossRegionEventSeen(event.id);
|
|
5117
|
+
if (event.namespace !== void 0 && event.namespace !== (this._namespace || void 0)) {
|
|
5118
|
+
return false;
|
|
3305
5119
|
}
|
|
5120
|
+
this.counters.crossRegionReceived++;
|
|
5121
|
+
this._applyInvalidationEvent(event.op, event.key, event.tagVersion);
|
|
5122
|
+
void this.publishInvalidation(event.op, event.key, event.tagVersion, true);
|
|
5123
|
+
this.logger.info("Cross-region invalidation applied", {
|
|
5124
|
+
op: event.op,
|
|
5125
|
+
key: event.key,
|
|
5126
|
+
originRegion: event.originRegion
|
|
5127
|
+
});
|
|
5128
|
+
return true;
|
|
3306
5129
|
}
|
|
3307
|
-
_setLocalTagVersion(tag, version, now =
|
|
5130
|
+
_setLocalTagVersion(tag, version, now = performance.now()) {
|
|
3308
5131
|
const existing = this.tagVersions.get(tag)?.version ?? 0;
|
|
3309
5132
|
const finalVersion = Math.max(existing, version);
|
|
3310
5133
|
if (this.tagVersions.size >= 1e4 && !this.tagVersions.has(tag)) {
|
|
@@ -3314,7 +5137,7 @@ var CacheService = class _CacheService {
|
|
|
3314
5137
|
this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
|
|
3315
5138
|
}
|
|
3316
5139
|
async _getTagVersion(tag) {
|
|
3317
|
-
const now =
|
|
5140
|
+
const now = performance.now();
|
|
3318
5141
|
const local = this.tagVersions.get(tag);
|
|
3319
5142
|
if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
|
|
3320
5143
|
return local.version;
|
|
@@ -3400,13 +5223,25 @@ var CacheService = class _CacheService {
|
|
|
3400
5223
|
stream.on("error", reject);
|
|
3401
5224
|
})
|
|
3402
5225
|
));
|
|
3403
|
-
} else {
|
|
5226
|
+
} else if (typeof client.scanStream === "function") {
|
|
3404
5227
|
await new Promise((resolve, reject) => {
|
|
3405
5228
|
const stream = client.scanStream({ match: pattern, count: 100 });
|
|
3406
5229
|
stream.on("data", (chunk) => keys.push(...chunk));
|
|
3407
5230
|
stream.on("end", resolve);
|
|
3408
5231
|
stream.on("error", reject);
|
|
3409
5232
|
});
|
|
5233
|
+
} else if (typeof client.scanIterator === "function") {
|
|
5234
|
+
for await (const key of client.scanIterator({ MATCH: pattern, COUNT: 100 })) {
|
|
5235
|
+
keys.push(key);
|
|
5236
|
+
}
|
|
5237
|
+
} else if (typeof client.scan === "function") {
|
|
5238
|
+
let cursor = "0";
|
|
5239
|
+
do {
|
|
5240
|
+
const res = await client.scan(cursor, "MATCH", pattern, "COUNT", 100);
|
|
5241
|
+
cursor = String(res[0]);
|
|
5242
|
+
const chunk = res[1];
|
|
5243
|
+
if (chunk?.length) keys.push(...chunk);
|
|
5244
|
+
} while (cursor !== "0");
|
|
3410
5245
|
}
|
|
3411
5246
|
return keys;
|
|
3412
5247
|
}
|
|
@@ -3420,9 +5255,23 @@ var CacheService = class _CacheService {
|
|
|
3420
5255
|
}
|
|
3421
5256
|
}
|
|
3422
5257
|
async getRedis() {
|
|
5258
|
+
this._assertActive("getRedis");
|
|
3423
5259
|
if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
|
|
3424
5260
|
if (this.redis) return this.redis;
|
|
3425
5261
|
if (this.redisConnecting) return this.redisConnecting;
|
|
5262
|
+
if (this.opts.redisClient) {
|
|
5263
|
+
const client = this.opts.redisClient;
|
|
5264
|
+
if (typeof client.connect === "function" && client.isOpen === false) {
|
|
5265
|
+
await client.connect();
|
|
5266
|
+
}
|
|
5267
|
+
this.cb.onSuccess();
|
|
5268
|
+
this.redis = client;
|
|
5269
|
+
this.pipeliner = new AutoPipeliner(client, {
|
|
5270
|
+
enabled: this.opts.autoPipeline,
|
|
5271
|
+
maxBatchSize: this.opts.maxPipelineBatchSize
|
|
5272
|
+
});
|
|
5273
|
+
return client;
|
|
5274
|
+
}
|
|
3426
5275
|
this.redisConnecting = (async () => {
|
|
3427
5276
|
try {
|
|
3428
5277
|
let client;
|
|
@@ -3431,6 +5280,7 @@ var CacheService = class _CacheService {
|
|
|
3431
5280
|
redisOptions: {
|
|
3432
5281
|
tls: this.opts.redisTls ? {} : void 0,
|
|
3433
5282
|
connectTimeout: 1e4,
|
|
5283
|
+
commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
|
|
3434
5284
|
maxRetriesPerRequest: 3,
|
|
3435
5285
|
keepAlive: 3e4,
|
|
3436
5286
|
...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
|
|
@@ -3451,6 +5301,7 @@ var CacheService = class _CacheService {
|
|
|
3451
5301
|
name: this.opts.redisSentinel.name,
|
|
3452
5302
|
tls: this.opts.redisTls ? {} : void 0,
|
|
3453
5303
|
connectTimeout: 1e4,
|
|
5304
|
+
commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
|
|
3454
5305
|
lazyConnect: false,
|
|
3455
5306
|
maxRetriesPerRequest: 3,
|
|
3456
5307
|
enableAutoPipelining: true,
|
|
@@ -3470,6 +5321,7 @@ var CacheService = class _CacheService {
|
|
|
3470
5321
|
port: this.opts.redisPort,
|
|
3471
5322
|
tls: this.opts.redisTls ? {} : void 0,
|
|
3472
5323
|
connectTimeout: 1e4,
|
|
5324
|
+
commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
|
|
3473
5325
|
lazyConnect: false,
|
|
3474
5326
|
maxRetriesPerRequest: 3,
|
|
3475
5327
|
enableAutoPipelining: true,
|
|
@@ -3495,6 +5347,10 @@ var CacheService = class _CacheService {
|
|
|
3495
5347
|
});
|
|
3496
5348
|
this.cb.onSuccess();
|
|
3497
5349
|
this.redis = client;
|
|
5350
|
+
this.pipeliner = new AutoPipeliner(client, {
|
|
5351
|
+
enabled: this.opts.autoPipeline,
|
|
5352
|
+
maxBatchSize: this.opts.maxPipelineBatchSize
|
|
5353
|
+
});
|
|
3498
5354
|
this.redisConnecting = null;
|
|
3499
5355
|
return client;
|
|
3500
5356
|
} catch (err) {
|
|
@@ -3507,12 +5363,18 @@ var CacheService = class _CacheService {
|
|
|
3507
5363
|
return this.redisConnecting;
|
|
3508
5364
|
}
|
|
3509
5365
|
// ── Snapshot (cold-start persistence) ────────────────────────────────────
|
|
5366
|
+
/**
|
|
5367
|
+
* Writes the cold-start snapshot to disk.
|
|
5368
|
+
* NOTE: fs.writeFileSync is INTENTIONAL here: this method is invoked during SIGTERM/SIGINT
|
|
5369
|
+
* process termination hooks where asynchronous I/O would risk the Node.js event loop dying or
|
|
5370
|
+
* process.exit() being called before the snapshot is physically written to disk.
|
|
5371
|
+
*/
|
|
3510
5372
|
writeSnapshot(altPath) {
|
|
3511
5373
|
try {
|
|
3512
5374
|
const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
|
|
3513
5375
|
if (entries.length === 0) return;
|
|
3514
5376
|
const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
|
|
3515
|
-
const packed =
|
|
5377
|
+
const packed = this.codec.encode(payload);
|
|
3516
5378
|
const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
|
|
3517
5379
|
const dest = altPath ?? this.opts.snapshotPath;
|
|
3518
5380
|
import_fs3.default.mkdirSync(import_path3.default.dirname(dest), { recursive: true });
|
|
@@ -3527,6 +5389,12 @@ var CacheService = class _CacheService {
|
|
|
3527
5389
|
this.logger.warn("Cache snapshot write failed", { error: err.message });
|
|
3528
5390
|
}
|
|
3529
5391
|
}
|
|
5392
|
+
/**
|
|
5393
|
+
* Loads cold-start snapshot from disk into L1 memory.
|
|
5394
|
+
* NOTE: fs.readFileSync is INTENTIONAL here: this method is invoked synchronously inside the
|
|
5395
|
+
* CacheService constructor so that the cache is atomically populated before any subsequent
|
|
5396
|
+
* cache.get() or cache.set() operations run, eliminating cold-start race conditions.
|
|
5397
|
+
*/
|
|
3530
5398
|
loadSnapshot() {
|
|
3531
5399
|
const snapshotPath = this.opts.snapshotPath;
|
|
3532
5400
|
try {
|
|
@@ -3546,13 +5414,25 @@ var CacheService = class _CacheService {
|
|
|
3546
5414
|
this.logger.warn("Snapshot rejected: decryption failed", { error: e.message });
|
|
3547
5415
|
return;
|
|
3548
5416
|
}
|
|
3549
|
-
const snapshot =
|
|
5417
|
+
const snapshot = this.codec.decode(buf);
|
|
3550
5418
|
if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
|
|
3551
5419
|
this.logger.warn("Snapshot rejected: version mismatch", { got: snapshot?.version });
|
|
3552
5420
|
return;
|
|
3553
5421
|
}
|
|
3554
|
-
const
|
|
3555
|
-
|
|
5422
|
+
const now = Date.now();
|
|
5423
|
+
const writtenAt = snapshot.writtenAt ?? 0;
|
|
5424
|
+
const tolerance = this.opts.clockSkewToleranceMs ?? 250;
|
|
5425
|
+
if (writtenAt - now > tolerance) {
|
|
5426
|
+
this.logger.warn("Snapshot rejected: timestamp too far in future (exceeds clock skew tolerance)", {
|
|
5427
|
+
writtenAt,
|
|
5428
|
+
now,
|
|
5429
|
+
skewMs: writtenAt - now,
|
|
5430
|
+
tolerance
|
|
5431
|
+
});
|
|
5432
|
+
return;
|
|
5433
|
+
}
|
|
5434
|
+
const ageMs = Math.max(0, now - writtenAt);
|
|
5435
|
+
if (ageMs > this.opts.snapshotMaxAgeMs) {
|
|
3556
5436
|
this.logger.warn("Snapshot rejected: too old", { ageMinutes: Math.round(ageMs / 6e4) });
|
|
3557
5437
|
return;
|
|
3558
5438
|
}
|
|
@@ -3574,6 +5454,115 @@ var CacheService = class _CacheService {
|
|
|
3574
5454
|
}
|
|
3575
5455
|
}
|
|
3576
5456
|
}
|
|
5457
|
+
// ── Remote Snapshot (cold-start persistence for stateless containers) ───────
|
|
5458
|
+
/**
|
|
5459
|
+
* Persists the cold-start snapshot to remote blob storage (S3, GCS, R2, HTTP).
|
|
5460
|
+
* Can be awaited during graceful application shutdown (e.g. Kubernetes preStop or NestJS shutdown).
|
|
5461
|
+
* Returns true if a snapshot was successfully exported and written; false otherwise.
|
|
5462
|
+
*/
|
|
5463
|
+
async writeRemoteSnapshot() {
|
|
5464
|
+
if (!this.opts.remoteSnapshot) return false;
|
|
5465
|
+
try {
|
|
5466
|
+
const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
|
|
5467
|
+
if (entries.length === 0) return false;
|
|
5468
|
+
const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
|
|
5469
|
+
const packed = this.codec.encode(payload);
|
|
5470
|
+
let final;
|
|
5471
|
+
if (this.opts.remoteSnapshot.envelope) {
|
|
5472
|
+
final = await EnvelopeEncryption.encrypt(packed, this.opts.remoteSnapshot.envelope);
|
|
5473
|
+
} else {
|
|
5474
|
+
final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
|
|
5475
|
+
}
|
|
5476
|
+
await this.opts.remoteSnapshot.adapter.put(final);
|
|
5477
|
+
this.counters.remoteSnapshotUploads++;
|
|
5478
|
+
this.counters.remoteSnapshotLastUploadedAt = Date.now();
|
|
5479
|
+
this.logger.info("Remote cache snapshot uploaded", {
|
|
5480
|
+
entries: entries.length,
|
|
5481
|
+
sizeKB: Math.round(final.length / 1024),
|
|
5482
|
+
encrypted: Boolean(this.opts.remoteSnapshot.envelope || this.enc.isEnabled)
|
|
5483
|
+
});
|
|
5484
|
+
return true;
|
|
5485
|
+
} catch (err) {
|
|
5486
|
+
this.counters.remoteSnapshotErrors++;
|
|
5487
|
+
this.logger.warn("Remote cache snapshot upload failed", { error: err.message });
|
|
5488
|
+
return false;
|
|
5489
|
+
}
|
|
5490
|
+
}
|
|
5491
|
+
/**
|
|
5492
|
+
* Hydrates L1 memory from remote blob storage (S3, GCS, R2, HTTP).
|
|
5493
|
+
* Called automatically during startup (chained into `cache.ready()`).
|
|
5494
|
+
* Returns the number of entries successfully imported.
|
|
5495
|
+
*/
|
|
5496
|
+
async loadRemoteSnapshot() {
|
|
5497
|
+
if (!this.opts.remoteSnapshot) return 0;
|
|
5498
|
+
const maxAgeMs = this.opts.remoteSnapshot.maxAgeMs ?? this.opts.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE;
|
|
5499
|
+
try {
|
|
5500
|
+
const raw = await this.opts.remoteSnapshot.adapter.get();
|
|
5501
|
+
if (!raw || raw.length === 0) {
|
|
5502
|
+
this.logger.debug("Remote snapshot not found or empty \u2014 starting cold");
|
|
5503
|
+
return 0;
|
|
5504
|
+
}
|
|
5505
|
+
const rawBuf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
|
|
5506
|
+
let buf;
|
|
5507
|
+
try {
|
|
5508
|
+
if (EnvelopeEncryption.isEnvelope(rawBuf)) {
|
|
5509
|
+
if (!this.opts.remoteSnapshot.envelope) {
|
|
5510
|
+
throw new Error("Remote snapshot is envelope-encrypted but no envelope options (privateKey or kmsDecrypt) were configured");
|
|
5511
|
+
}
|
|
5512
|
+
buf = await EnvelopeEncryption.decrypt(rawBuf, this.opts.remoteSnapshot.envelope);
|
|
5513
|
+
} else {
|
|
5514
|
+
buf = this.enc.decryptBuffer(rawBuf);
|
|
5515
|
+
}
|
|
5516
|
+
} catch (e) {
|
|
5517
|
+
this.counters.remoteSnapshotErrors++;
|
|
5518
|
+
this.logger.warn("Remote snapshot rejected: decryption failed", { error: e.message });
|
|
5519
|
+
return 0;
|
|
5520
|
+
}
|
|
5521
|
+
const snapshot = this.codec.decode(buf);
|
|
5522
|
+
if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
|
|
5523
|
+
this.counters.remoteSnapshotErrors++;
|
|
5524
|
+
this.logger.warn("Remote snapshot rejected: version mismatch", { got: snapshot?.version });
|
|
5525
|
+
return 0;
|
|
5526
|
+
}
|
|
5527
|
+
const now = Date.now();
|
|
5528
|
+
const writtenAt = snapshot.writtenAt ?? 0;
|
|
5529
|
+
const tolerance = this.opts.clockSkewToleranceMs ?? 250;
|
|
5530
|
+
if (writtenAt - now > tolerance) {
|
|
5531
|
+
this.counters.remoteSnapshotErrors++;
|
|
5532
|
+
this.logger.warn("Remote snapshot rejected: timestamp too far in future (exceeds clock skew tolerance)", {
|
|
5533
|
+
writtenAt,
|
|
5534
|
+
now,
|
|
5535
|
+
skewMs: writtenAt - now,
|
|
5536
|
+
tolerance
|
|
5537
|
+
});
|
|
5538
|
+
return 0;
|
|
5539
|
+
}
|
|
5540
|
+
const ageMs = Math.max(0, now - writtenAt);
|
|
5541
|
+
if (maxAgeMs <= 0 || ageMs > maxAgeMs) {
|
|
5542
|
+
this.counters.remoteSnapshotErrors++;
|
|
5543
|
+
this.logger.warn("Remote snapshot rejected: too old", { ageMinutes: Math.round(ageMs / 6e4) });
|
|
5544
|
+
return 0;
|
|
5545
|
+
}
|
|
5546
|
+
if (!Array.isArray(snapshot.entries)) {
|
|
5547
|
+
this.counters.remoteSnapshotErrors++;
|
|
5548
|
+
this.logger.warn("Remote snapshot rejected: entries is not an array");
|
|
5549
|
+
return 0;
|
|
5550
|
+
}
|
|
5551
|
+
const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
|
|
5552
|
+
this.counters.remoteSnapshotDownloads++;
|
|
5553
|
+
this.counters.remoteSnapshotLastDownloadedAt = Date.now();
|
|
5554
|
+
this.logger.info("Remote cache snapshot loaded (L1 hydrated)", {
|
|
5555
|
+
loaded,
|
|
5556
|
+
total: snapshot.entries.length,
|
|
5557
|
+
sizeKB: this.l1.getStats().sizeKB
|
|
5558
|
+
});
|
|
5559
|
+
return loaded;
|
|
5560
|
+
} catch (err) {
|
|
5561
|
+
this.counters.remoteSnapshotErrors++;
|
|
5562
|
+
this.logger.warn("Remote snapshot load failed \u2014 starting cold", { error: err.message });
|
|
5563
|
+
return 0;
|
|
5564
|
+
}
|
|
5565
|
+
}
|
|
3577
5566
|
// ── Core get (L1 → L1.5 → L2 → fetch) ───────────────────────────────────
|
|
3578
5567
|
/**
|
|
3579
5568
|
* Get a value from cache, or fetch and cache it.
|
|
@@ -3595,6 +5584,7 @@ var CacheService = class _CacheService {
|
|
|
3595
5584
|
* Caches negative lookups to avoid repeated DB hits for missing keys.
|
|
3596
5585
|
*/
|
|
3597
5586
|
async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
|
|
5587
|
+
this._assertActive("get");
|
|
3598
5588
|
const span = this._startSpan("tricache.get");
|
|
3599
5589
|
if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
3600
5590
|
const k = this.nk(cacheKey);
|
|
@@ -3609,9 +5599,10 @@ var CacheService = class _CacheService {
|
|
|
3609
5599
|
if (l1Hit !== null) {
|
|
3610
5600
|
let isGenerationalStale = false;
|
|
3611
5601
|
if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
|
|
3612
|
-
|
|
3613
|
-
|
|
3614
|
-
|
|
5602
|
+
const tags = Object.keys(l1Hit.tagVersions);
|
|
5603
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5604
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5605
|
+
if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
|
|
3615
5606
|
isGenerationalStale = true;
|
|
3616
5607
|
break;
|
|
3617
5608
|
}
|
|
@@ -3625,7 +5616,14 @@ var CacheService = class _CacheService {
|
|
|
3625
5616
|
if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
|
|
3626
5617
|
const priority2 = optPriority ?? inferPriority(cacheKey);
|
|
3627
5618
|
this.revalidating.add(k);
|
|
3628
|
-
void this._revalidate(
|
|
5619
|
+
void this._revalidate(
|
|
5620
|
+
k,
|
|
5621
|
+
fetchFn,
|
|
5622
|
+
ttlSeconds * 1e3,
|
|
5623
|
+
swrGraceMs2,
|
|
5624
|
+
priority2,
|
|
5625
|
+
l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
|
|
5626
|
+
);
|
|
3629
5627
|
this.counters.swrRevalidations++;
|
|
3630
5628
|
this.logger.debug("SWR: serving stale, revalidating", { cacheKey });
|
|
3631
5629
|
} else {
|
|
@@ -3644,7 +5642,14 @@ var CacheService = class _CacheService {
|
|
|
3644
5642
|
if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
|
|
3645
5643
|
const priority2 = optPriority ?? inferPriority(cacheKey);
|
|
3646
5644
|
this.revalidating.add(k);
|
|
3647
|
-
void this._revalidate(
|
|
5645
|
+
void this._revalidate(
|
|
5646
|
+
k,
|
|
5647
|
+
fetchFn,
|
|
5648
|
+
entryTtl,
|
|
5649
|
+
optSwr * 1e3,
|
|
5650
|
+
priority2,
|
|
5651
|
+
l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
|
|
5652
|
+
);
|
|
3648
5653
|
this.counters.swrRevalidations++;
|
|
3649
5654
|
this.logger.debug(
|
|
3650
5655
|
shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
|
|
@@ -3656,116 +5661,148 @@ var CacheService = class _CacheService {
|
|
|
3656
5661
|
this.counters.l1Hits++;
|
|
3657
5662
|
this.opts.onHit?.(cacheKey, "l1");
|
|
3658
5663
|
if (this.opts.frozen) deepFreeze(l1Hit.value);
|
|
3659
|
-
span.setAttribute("cache.hit", "l1").end();
|
|
5664
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "memory").setAttribute("cache.hit_tier", "l1").end();
|
|
3660
5665
|
return this.opts.cloneStrategy === "structuredClone" && l1Hit.value != null && typeof l1Hit.value === "object" ? structuredClone(l1Hit.value) : l1Hit.value;
|
|
3661
5666
|
}
|
|
3662
5667
|
}
|
|
3663
5668
|
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
3664
5669
|
const swrGraceMs = optSwr * 1e3;
|
|
3665
5670
|
const priority = optPriority ?? inferPriority(cacheKey);
|
|
3666
|
-
|
|
5671
|
+
const existing = this.inflight.get(k);
|
|
5672
|
+
if (existing) {
|
|
5673
|
+
this.counters.stampedes++;
|
|
5674
|
+
this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch/read", { cacheKey });
|
|
5675
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
|
|
5676
|
+
return existing;
|
|
5677
|
+
}
|
|
5678
|
+
const mutationEpochAtStart = this._getKeyMutationEpoch(k);
|
|
5679
|
+
const executionPromise = (async () => {
|
|
3667
5680
|
try {
|
|
3668
|
-
|
|
3669
|
-
|
|
3670
|
-
|
|
3671
|
-
|
|
3672
|
-
|
|
3673
|
-
let isStale = false;
|
|
3674
|
-
let storedTagVersions = {};
|
|
3675
|
-
if (hashData.tv) {
|
|
3676
|
-
try {
|
|
3677
|
-
storedTagVersions = JSON.parse(hashData.tv);
|
|
3678
|
-
} catch {
|
|
3679
|
-
}
|
|
5681
|
+
if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
|
|
5682
|
+
if (this._isTombstonedByPattern(k)) {
|
|
5683
|
+
try {
|
|
5684
|
+
this.disk.delete(k);
|
|
5685
|
+
} catch {
|
|
3680
5686
|
}
|
|
3681
|
-
|
|
3682
|
-
|
|
3683
|
-
|
|
3684
|
-
|
|
3685
|
-
|
|
5687
|
+
} else {
|
|
5688
|
+
const isDiskAllowed = this.watchdog.isDiskAllowed();
|
|
5689
|
+
if (isDiskAllowed) {
|
|
5690
|
+
const diskStart = performance.now();
|
|
5691
|
+
const diskHit = this.disk.load(k);
|
|
5692
|
+
const diskElapsed = performance.now() - diskStart;
|
|
5693
|
+
this.watchdog.recordDisk(diskElapsed);
|
|
5694
|
+
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
5695
|
+
if (diskHit !== null) {
|
|
5696
|
+
let isDiskStale = false;
|
|
5697
|
+
if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
|
|
5698
|
+
const tags = Object.keys(diskHit.tagVersions);
|
|
5699
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5700
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5701
|
+
if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
|
|
5702
|
+
isDiskStale = true;
|
|
5703
|
+
break;
|
|
5704
|
+
}
|
|
5705
|
+
}
|
|
5706
|
+
}
|
|
5707
|
+
if (isDiskStale) {
|
|
5708
|
+
this.disk.delete(k);
|
|
5709
|
+
} else {
|
|
5710
|
+
const promoted = this.l1.importEntries(
|
|
5711
|
+
[{ key: k, entry: diskHit }],
|
|
5712
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
5713
|
+
);
|
|
5714
|
+
if (promoted > 0) {
|
|
5715
|
+
const l1Check = this.l1.get(k);
|
|
5716
|
+
if (l1Check !== null) {
|
|
5717
|
+
this.counters.diskHits++;
|
|
5718
|
+
this.opts.onHit?.(cacheKey, "disk");
|
|
5719
|
+
this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
|
|
5720
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
|
|
5721
|
+
if (this.opts.frozen) deepFreeze(l1Check.value);
|
|
5722
|
+
return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
|
|
5723
|
+
}
|
|
5724
|
+
}
|
|
5725
|
+
}
|
|
3686
5726
|
}
|
|
3687
5727
|
}
|
|
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
|
-
}
|
|
3715
|
-
}
|
|
3716
|
-
} catch (err) {
|
|
3717
|
-
this.cb.onFailure();
|
|
3718
|
-
this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
|
|
3719
|
-
}
|
|
3720
|
-
}
|
|
3721
|
-
if (!this._diskDisabled) {
|
|
3722
|
-
const diskHit = this.disk.load(k);
|
|
3723
|
-
if (diskHit !== null) {
|
|
3724
|
-
let isDiskStale = false;
|
|
3725
|
-
if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
|
|
3726
|
-
for (const [tag, entryVer] of Object.entries(diskHit.tagVersions)) {
|
|
3727
|
-
const currentVer = await this._getTagVersion(tag);
|
|
3728
|
-
if (currentVer > entryVer) {
|
|
3729
|
-
isDiskStale = true;
|
|
3730
|
-
break;
|
|
3731
|
-
}
|
|
3732
5728
|
}
|
|
3733
5729
|
}
|
|
3734
|
-
if (
|
|
3735
|
-
|
|
3736
|
-
|
|
3737
|
-
|
|
3738
|
-
|
|
3739
|
-
|
|
3740
|
-
|
|
3741
|
-
|
|
3742
|
-
|
|
3743
|
-
|
|
3744
|
-
|
|
3745
|
-
|
|
3746
|
-
|
|
3747
|
-
|
|
3748
|
-
|
|
3749
|
-
|
|
5730
|
+
if (!this._redisDisabled) {
|
|
5731
|
+
try {
|
|
5732
|
+
const client = await this.getRedis();
|
|
5733
|
+
const redisStart = performance.now();
|
|
5734
|
+
if (this.opts.tagStrategy === "generational") {
|
|
5735
|
+
const hashData = await client.hgetall(k);
|
|
5736
|
+
const redisElapsed = performance.now() - redisStart;
|
|
5737
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
5738
|
+
this.cb.onSuccess();
|
|
5739
|
+
if (hashData && hashData.d) {
|
|
5740
|
+
let isStale = false;
|
|
5741
|
+
let storedTagVersions = {};
|
|
5742
|
+
if (hashData.tv) {
|
|
5743
|
+
try {
|
|
5744
|
+
storedTagVersions = JSON.parse(hashData.tv);
|
|
5745
|
+
} catch {
|
|
5746
|
+
}
|
|
5747
|
+
}
|
|
5748
|
+
const tags = Object.keys(storedTagVersions);
|
|
5749
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5750
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5751
|
+
if (currentVers[i] > storedTagVersions[tags[i]]) {
|
|
5752
|
+
isStale = true;
|
|
5753
|
+
break;
|
|
5754
|
+
}
|
|
5755
|
+
}
|
|
5756
|
+
if (isStale) {
|
|
5757
|
+
const setAtMs = parseInt(hashData.t, 10) || 0;
|
|
5758
|
+
this._deleteIfStale(k, setAtMs);
|
|
5759
|
+
} else {
|
|
5760
|
+
const parsed = await this._decryptAndDeserialize(hashData.d);
|
|
5761
|
+
this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
|
|
5762
|
+
this.counters.l2Hits++;
|
|
5763
|
+
this.opts.onHit?.(cacheKey, "l2");
|
|
5764
|
+
this.logger.debug("L2 hit (Redis hash)", { cacheKey });
|
|
5765
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
5766
|
+
if (this.opts.frozen) deepFreeze(parsed);
|
|
5767
|
+
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
5768
|
+
}
|
|
5769
|
+
}
|
|
5770
|
+
} else {
|
|
5771
|
+
const raw = this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
|
|
5772
|
+
const redisElapsed = performance.now() - redisStart;
|
|
5773
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
5774
|
+
this.cb.onSuccess();
|
|
5775
|
+
if (raw) {
|
|
5776
|
+
const parsed = await this._decryptAndDeserialize(raw);
|
|
5777
|
+
this.l1.set(k, parsed, ttlMs, priority);
|
|
5778
|
+
this.counters.l2Hits++;
|
|
5779
|
+
this.opts.onHit?.(cacheKey, "l2");
|
|
5780
|
+
this.logger.debug("L2 hit (Redis)", { cacheKey });
|
|
5781
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
5782
|
+
if (this.opts.frozen) deepFreeze(parsed);
|
|
5783
|
+
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
5784
|
+
}
|
|
3750
5785
|
}
|
|
5786
|
+
} catch (err) {
|
|
5787
|
+
this.cb.onFailure();
|
|
5788
|
+
this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
|
|
3751
5789
|
}
|
|
3752
5790
|
}
|
|
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 {
|
|
5791
|
+
span.setAttribute("cache.hit", false).setAttribute("cache.hit_tier", "miss");
|
|
5792
|
+
this.opts.onMiss?.(cacheKey);
|
|
3766
5793
|
this.counters.fetches++;
|
|
3767
5794
|
const fetchStart = Date.now();
|
|
3768
|
-
|
|
5795
|
+
let data;
|
|
5796
|
+
try {
|
|
5797
|
+
data = await fetchFn();
|
|
5798
|
+
} catch (fetchErr) {
|
|
5799
|
+
span.setStatus({
|
|
5800
|
+
code: 2,
|
|
5801
|
+
message: fetchErr instanceof Error ? fetchErr.message : String(fetchErr)
|
|
5802
|
+
});
|
|
5803
|
+
span.recordException?.(fetchErr);
|
|
5804
|
+
throw fetchErr;
|
|
5805
|
+
}
|
|
3769
5806
|
const delta = Date.now() - fetchStart;
|
|
3770
5807
|
const notFoundTtlMs = (optNotFoundTtl ?? this.opts.notFoundTtl) * 1e3;
|
|
3771
5808
|
let effectiveTtl = data == null && notFoundTtlMs > 0 ? notFoundTtlMs : ttlMs;
|
|
@@ -3785,14 +5822,27 @@ var CacheService = class _CacheService {
|
|
|
3785
5822
|
let activeTagVersions;
|
|
3786
5823
|
if (optTags?.length) {
|
|
3787
5824
|
if (this.opts.tagStrategy === "generational") {
|
|
5825
|
+
const vers = await Promise.all(optTags.map((tag) => this._getTagVersion(tag)));
|
|
3788
5826
|
activeTagVersions = {};
|
|
3789
|
-
for (
|
|
3790
|
-
activeTagVersions[
|
|
5827
|
+
for (let i = 0; i < optTags.length; i++) {
|
|
5828
|
+
activeTagVersions[optTags[i]] = vers[i];
|
|
3791
5829
|
}
|
|
3792
5830
|
} else {
|
|
3793
5831
|
await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
|
|
3794
5832
|
}
|
|
3795
5833
|
}
|
|
5834
|
+
if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
|
|
5835
|
+
this.logger.debug("Aborting in-flight cache commit \u2014 key was mutated or deleted during fetch", { cacheKey });
|
|
5836
|
+
span.setAttribute("cache.aborted_mutation_race", true);
|
|
5837
|
+
const current = this.l1.get(k);
|
|
5838
|
+
if (current && !current.isStale && current.value !== void 0) {
|
|
5839
|
+
const freshVal = current.value;
|
|
5840
|
+
if (this.opts.frozen) deepFreeze(freshVal);
|
|
5841
|
+
return this.opts.cloneStrategy === "structuredClone" && freshVal != null && typeof freshVal === "object" ? structuredClone(freshVal) : freshVal;
|
|
5842
|
+
}
|
|
5843
|
+
if (this.opts.frozen) deepFreeze(data);
|
|
5844
|
+
return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
|
|
5845
|
+
}
|
|
3796
5846
|
this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
|
|
3797
5847
|
if (!this._redisDisabled) {
|
|
3798
5848
|
try {
|
|
@@ -3829,8 +5879,64 @@ var CacheService = class _CacheService {
|
|
|
3829
5879
|
span.end();
|
|
3830
5880
|
}
|
|
3831
5881
|
})();
|
|
3832
|
-
this.inflight.set(k,
|
|
3833
|
-
return
|
|
5882
|
+
this.inflight.set(k, executionPromise);
|
|
5883
|
+
return executionPromise;
|
|
5884
|
+
}
|
|
5885
|
+
/**
|
|
5886
|
+
* Graceful shutdown flusher for Kubernetes preStop hooks, NestJS onApplicationShutdown,
|
|
5887
|
+
* or manual microservice teardown.
|
|
5888
|
+
*
|
|
5889
|
+
* Flushes both local disk and remote cloud snapshots (S3/R2/GCS), returning a Promise
|
|
5890
|
+
* that resolves when the upload completes or after `timeoutMs` expires.
|
|
5891
|
+
*
|
|
5892
|
+
* @param timeoutMs Maximum time permitted for snapshot persistence before timing out. Default: 8000ms.
|
|
5893
|
+
*/
|
|
5894
|
+
async flushSnapshotOnShutdown(timeoutMs = 8e3) {
|
|
5895
|
+
const flusher = async () => {
|
|
5896
|
+
let localOk = true;
|
|
5897
|
+
let remoteOk = true;
|
|
5898
|
+
if (!this._diskDisabled) {
|
|
5899
|
+
try {
|
|
5900
|
+
this.writeSnapshot();
|
|
5901
|
+
} catch (err) {
|
|
5902
|
+
localOk = false;
|
|
5903
|
+
this.logger.warn("flushSnapshotOnShutdown: disk snapshot write failed", { error: err.message });
|
|
5904
|
+
}
|
|
5905
|
+
}
|
|
5906
|
+
if (this.opts.remoteSnapshot && this.opts.remoteSnapshot.saveOnShutdown !== false) {
|
|
5907
|
+
try {
|
|
5908
|
+
remoteOk = await this.writeRemoteSnapshot();
|
|
5909
|
+
} catch (err) {
|
|
5910
|
+
remoteOk = false;
|
|
5911
|
+
this.logger.warn("flushSnapshotOnShutdown: remote snapshot upload failed", { error: err.message });
|
|
5912
|
+
}
|
|
5913
|
+
}
|
|
5914
|
+
return localOk && remoteOk;
|
|
5915
|
+
};
|
|
5916
|
+
let timer = null;
|
|
5917
|
+
try {
|
|
5918
|
+
return await Promise.race([
|
|
5919
|
+
flusher(),
|
|
5920
|
+
new Promise((resolve) => {
|
|
5921
|
+
timer = setTimeout(() => {
|
|
5922
|
+
this.logger.warn(`flushSnapshotOnShutdown timed out after ${timeoutMs}ms`);
|
|
5923
|
+
resolve(false);
|
|
5924
|
+
}, timeoutMs);
|
|
5925
|
+
if (timer.unref) timer.unref();
|
|
5926
|
+
})
|
|
5927
|
+
]);
|
|
5928
|
+
} finally {
|
|
5929
|
+
if (timer) clearTimeout(timer);
|
|
5930
|
+
}
|
|
5931
|
+
}
|
|
5932
|
+
/**
|
|
5933
|
+
* Internal graceful shutdown trigger invoked by ProcessTerminationBus.
|
|
5934
|
+
*/
|
|
5935
|
+
_triggerShutdown() {
|
|
5936
|
+
if (!this._diskDisabled) this.writeSnapshot();
|
|
5937
|
+
if (this.opts.remoteSnapshot && this.opts.remoteSnapshot.saveOnShutdown !== false) {
|
|
5938
|
+
void this.flushSnapshotOnShutdown();
|
|
5939
|
+
}
|
|
3834
5940
|
}
|
|
3835
5941
|
/**
|
|
3836
5942
|
* Universal fetch-and-cache wrapper with an ergonomic options object.
|
|
@@ -3853,21 +5959,41 @@ var CacheService = class _CacheService {
|
|
|
3853
5959
|
const ttl = options?.ttl ?? 300;
|
|
3854
5960
|
return this.get(cacheKey, fetchFn, ttl, options);
|
|
3855
5961
|
}
|
|
3856
|
-
async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
|
|
5962
|
+
async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority, knownTagVersions) {
|
|
5963
|
+
const startEpoch = this._getKeyMutationEpoch(cacheKey);
|
|
3857
5964
|
try {
|
|
3858
5965
|
const fetchStart = Date.now();
|
|
3859
5966
|
const data = await fetchFn();
|
|
3860
5967
|
const delta = Date.now() - fetchStart;
|
|
3861
5968
|
const staleAt = Date.now() + ttlMs;
|
|
5969
|
+
if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
|
|
5970
|
+
this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during fetch", { cacheKey });
|
|
5971
|
+
return;
|
|
5972
|
+
}
|
|
3862
5973
|
if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
|
|
3863
5974
|
let activeTagVersions;
|
|
3864
5975
|
const l1Existing = this.l1.get(cacheKey);
|
|
3865
|
-
|
|
5976
|
+
const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
|
|
5977
|
+
if (this.opts.tagStrategy === "generational" && tagVersionsSource) {
|
|
5978
|
+
const tags = Object.keys(tagVersionsSource);
|
|
5979
|
+
const vers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
3866
5980
|
activeTagVersions = {};
|
|
3867
|
-
for (
|
|
3868
|
-
activeTagVersions[
|
|
5981
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5982
|
+
activeTagVersions[tags[i]] = vers[i];
|
|
5983
|
+
}
|
|
5984
|
+
if (knownTagVersions) {
|
|
5985
|
+
for (const t of tags) {
|
|
5986
|
+
if (knownTagVersions[t] !== void 0 && activeTagVersions[t] !== knownTagVersions[t]) {
|
|
5987
|
+
this.logger.debug("SWR: aborting revalidation commit \u2014 tag version bumped during revalidation", { cacheKey, tag: t });
|
|
5988
|
+
return;
|
|
5989
|
+
}
|
|
5990
|
+
}
|
|
3869
5991
|
}
|
|
3870
5992
|
}
|
|
5993
|
+
if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
|
|
5994
|
+
this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
|
|
5995
|
+
return;
|
|
5996
|
+
}
|
|
3871
5997
|
this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
|
|
3872
5998
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
3873
5999
|
try {
|
|
@@ -3910,63 +6036,86 @@ var CacheService = class _CacheService {
|
|
|
3910
6036
|
// ── Explicit set / delete ─────────────────────────────────────────────────
|
|
3911
6037
|
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
3912
6038
|
async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
|
|
6039
|
+
this._assertActive("set");
|
|
3913
6040
|
const span = this._startSpan("tricache.set");
|
|
3914
|
-
if (this.opts.tracer)
|
|
3915
|
-
|
|
3916
|
-
|
|
3917
|
-
|
|
3918
|
-
|
|
3919
|
-
|
|
3920
|
-
|
|
3921
|
-
|
|
3922
|
-
|
|
3923
|
-
|
|
3924
|
-
|
|
3925
|
-
|
|
6041
|
+
if (this.opts.tracer) {
|
|
6042
|
+
span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
6043
|
+
span.setAttribute("cache.ttl", ttlSeconds);
|
|
6044
|
+
}
|
|
6045
|
+
try {
|
|
6046
|
+
const effectiveTtlSeconds = ttlSeconds > 0 ? ttlSeconds : ttlSeconds === 0 ? INDEFINITE_TTL_SECONDS : ttlSeconds;
|
|
6047
|
+
const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
|
|
6048
|
+
const p = priority ?? inferPriority(cacheKey);
|
|
6049
|
+
const k = this.nk(cacheKey);
|
|
6050
|
+
this._bumpKeyMutation(k);
|
|
6051
|
+
this.inflight.delete(k);
|
|
6052
|
+
this._pendingDiskDeletes.delete(k);
|
|
6053
|
+
this.counters.sets++;
|
|
6054
|
+
let activeTagVersions;
|
|
6055
|
+
if (opts?.tags?.length) {
|
|
6056
|
+
if (this.opts.tagStrategy === "generational") {
|
|
6057
|
+
const vers = await Promise.all(opts.tags.map((tag) => this._getTagVersion(tag)));
|
|
6058
|
+
activeTagVersions = {};
|
|
6059
|
+
for (let i = 0; i < opts.tags.length; i++) {
|
|
6060
|
+
activeTagVersions[opts.tags[i]] = vers[i];
|
|
6061
|
+
}
|
|
6062
|
+
} else {
|
|
6063
|
+
await this._registerTags(k, opts.tags, ttlSeconds);
|
|
3926
6064
|
}
|
|
3927
|
-
} else {
|
|
3928
|
-
await this._registerTags(k, opts.tags, ttlSeconds);
|
|
3929
6065
|
}
|
|
3930
|
-
|
|
3931
|
-
|
|
3932
|
-
|
|
3933
|
-
|
|
3934
|
-
|
|
3935
|
-
|
|
3936
|
-
|
|
3937
|
-
|
|
3938
|
-
|
|
6066
|
+
this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
|
|
6067
|
+
if (opts?.dependsOn?.length) {
|
|
6068
|
+
for (const pattern of opts.dependsOn) {
|
|
6069
|
+
const nsPattern = this.nk(pattern);
|
|
6070
|
+
let deps = this.dependencyIndex.get(nsPattern);
|
|
6071
|
+
if (!deps) {
|
|
6072
|
+
deps = /* @__PURE__ */ new Set();
|
|
6073
|
+
this.dependencyIndex.set(nsPattern, deps);
|
|
6074
|
+
}
|
|
6075
|
+
deps.add(k);
|
|
3939
6076
|
}
|
|
3940
|
-
deps.add(k);
|
|
3941
6077
|
}
|
|
3942
|
-
|
|
3943
|
-
|
|
3944
|
-
|
|
3945
|
-
|
|
3946
|
-
|
|
3947
|
-
|
|
3948
|
-
|
|
3949
|
-
|
|
3950
|
-
|
|
3951
|
-
|
|
3952
|
-
|
|
3953
|
-
|
|
3954
|
-
|
|
3955
|
-
|
|
3956
|
-
|
|
3957
|
-
|
|
3958
|
-
|
|
3959
|
-
|
|
3960
|
-
|
|
6078
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
6079
|
+
try {
|
|
6080
|
+
const client = await this.getRedis();
|
|
6081
|
+
const s = JSON.stringify(data);
|
|
6082
|
+
const stored = await this._serializeAndEncrypt(s);
|
|
6083
|
+
const ttlSec = Math.ceil(ttlMs / 1e3);
|
|
6084
|
+
if (this.opts.tagStrategy === "generational" && activeTagVersions) {
|
|
6085
|
+
const now = Date.now();
|
|
6086
|
+
const tx = client.multi();
|
|
6087
|
+
tx.hset(k, {
|
|
6088
|
+
d: stored,
|
|
6089
|
+
t: String(now),
|
|
6090
|
+
tv: JSON.stringify(activeTagVersions)
|
|
6091
|
+
});
|
|
6092
|
+
tx.expire(k, ttlSec);
|
|
6093
|
+
await tx.exec();
|
|
6094
|
+
} else {
|
|
6095
|
+
if (this.opts.autoPipeline && this.pipeliner) {
|
|
6096
|
+
await this.pipeliner.setex(k, ttlSec, stored);
|
|
6097
|
+
} else {
|
|
6098
|
+
await client.setex(k, ttlSec, stored);
|
|
6099
|
+
}
|
|
6100
|
+
}
|
|
6101
|
+
this.cb.onSuccess();
|
|
6102
|
+
} catch (err) {
|
|
6103
|
+
this.cb.onFailure();
|
|
6104
|
+
this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
|
|
3961
6105
|
}
|
|
3962
|
-
this.cb.onSuccess();
|
|
3963
|
-
} catch (err) {
|
|
3964
|
-
this.cb.onFailure();
|
|
3965
|
-
this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
|
|
3966
6106
|
}
|
|
6107
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6108
|
+
await this.publishInvalidation("del", k);
|
|
6109
|
+
} else {
|
|
6110
|
+
void this.publishInvalidation("del", k);
|
|
6111
|
+
}
|
|
6112
|
+
} catch (err) {
|
|
6113
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6114
|
+
span.recordException?.(err);
|
|
6115
|
+
throw err;
|
|
6116
|
+
} finally {
|
|
6117
|
+
span.end();
|
|
3967
6118
|
}
|
|
3968
|
-
void this.publishInvalidation("del", k);
|
|
3969
|
-
span.end();
|
|
3970
6119
|
}
|
|
3971
6120
|
/**
|
|
3972
6121
|
* Register tags for a cache key in the in-process index and (if Redis is enabled) in
|
|
@@ -4006,38 +6155,74 @@ var CacheService = class _CacheService {
|
|
|
4006
6155
|
* await cache.delete('user:abc:*'); // all keys for user abc
|
|
4007
6156
|
*/
|
|
4008
6157
|
async delete(cacheKey) {
|
|
6158
|
+
this._assertActive("delete");
|
|
4009
6159
|
const span = this._startSpan("tricache.delete");
|
|
4010
6160
|
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
|
-
|
|
6161
|
+
try {
|
|
6162
|
+
const isPattern = cacheKey.includes("*");
|
|
6163
|
+
const k = this.nk(cacheKey);
|
|
6164
|
+
this.counters.deletes++;
|
|
6165
|
+
if (isPattern) {
|
|
6166
|
+
const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
|
|
6167
|
+
for (const liveKey of this.l1.liveKeys()) {
|
|
6168
|
+
if (liveKey.startsWith(pfx)) {
|
|
6169
|
+
this._bumpKeyMutation(liveKey);
|
|
6170
|
+
}
|
|
6171
|
+
}
|
|
6172
|
+
for (const inflightKey of Array.from(this.inflight.keys())) {
|
|
6173
|
+
if (inflightKey.startsWith(pfx)) {
|
|
6174
|
+
this._bumpKeyMutation(inflightKey);
|
|
6175
|
+
this.inflight.delete(inflightKey);
|
|
6176
|
+
}
|
|
6177
|
+
}
|
|
6178
|
+
this._addPatternTombstone(pfx);
|
|
6179
|
+
this.l1.deletePattern(k);
|
|
6180
|
+
} else {
|
|
6181
|
+
this._bumpKeyMutation(k);
|
|
6182
|
+
this.inflight.delete(k);
|
|
6183
|
+
this.l1.delete(k);
|
|
6184
|
+
this._pendingDiskDeletes.add(k);
|
|
6185
|
+
setImmediate(() => {
|
|
6186
|
+
try {
|
|
6187
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
6188
|
+
} finally {
|
|
6189
|
+
this._pendingDiskDeletes.delete(k);
|
|
6190
|
+
}
|
|
6191
|
+
});
|
|
6192
|
+
this._cascadeDependencies(k);
|
|
6193
|
+
for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
|
|
6194
|
+
}
|
|
6195
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
6196
|
+
try {
|
|
6197
|
+
const client = await this.getRedis();
|
|
6198
|
+
if (isPattern) {
|
|
6199
|
+
const keys = await this._scanKeys(client, k);
|
|
6200
|
+
if (keys.length > 0) await client.del(...keys);
|
|
6201
|
+
} else {
|
|
6202
|
+
if (this.opts.autoPipeline && this.pipeliner) {
|
|
6203
|
+
await this.pipeliner.del(k);
|
|
6204
|
+
} else {
|
|
6205
|
+
await client.del(k);
|
|
6206
|
+
}
|
|
6207
|
+
}
|
|
6208
|
+
this.cb.onSuccess();
|
|
6209
|
+
} catch (err) {
|
|
6210
|
+
this.cb.onFailure();
|
|
6211
|
+
this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
|
|
4032
6212
|
}
|
|
4033
|
-
this.cb.onSuccess();
|
|
4034
|
-
} catch (err) {
|
|
4035
|
-
this.cb.onFailure();
|
|
4036
|
-
this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
|
|
4037
6213
|
}
|
|
6214
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6215
|
+
await this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
|
|
6216
|
+
} else {
|
|
6217
|
+
void this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
|
|
6218
|
+
}
|
|
6219
|
+
} catch (err) {
|
|
6220
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6221
|
+
span.recordException?.(err);
|
|
6222
|
+
throw err;
|
|
6223
|
+
} finally {
|
|
6224
|
+
span.end();
|
|
4038
6225
|
}
|
|
4039
|
-
void this.publishInvalidation(isPattern ? "del-glob" : "del", k);
|
|
4040
|
-
span.end();
|
|
4041
6226
|
}
|
|
4042
6227
|
// ── Counter (distributed rate limiting) ──────────────────────────────────
|
|
4043
6228
|
/**
|
|
@@ -4057,6 +6242,7 @@ var CacheService = class _CacheService {
|
|
|
4057
6242
|
* fleet-wide.
|
|
4058
6243
|
*/
|
|
4059
6244
|
async increment(cacheKey, ttlSeconds) {
|
|
6245
|
+
this._assertActive("increment");
|
|
4060
6246
|
const k = this.nk(cacheKey);
|
|
4061
6247
|
if (this._redisDisabled) {
|
|
4062
6248
|
if (!this._incrementFallbackWarned) {
|
|
@@ -4098,31 +6284,73 @@ var CacheService = class _CacheService {
|
|
|
4098
6284
|
* await cache.clear('user:abc'); // flush all keys for one user
|
|
4099
6285
|
*/
|
|
4100
6286
|
async clear(prefix) {
|
|
4101
|
-
this.
|
|
4102
|
-
const
|
|
4103
|
-
if (
|
|
4104
|
-
|
|
4105
|
-
|
|
4106
|
-
this.
|
|
4107
|
-
if (
|
|
4108
|
-
|
|
4109
|
-
|
|
4110
|
-
|
|
4111
|
-
|
|
4112
|
-
|
|
4113
|
-
|
|
4114
|
-
const
|
|
4115
|
-
|
|
4116
|
-
|
|
4117
|
-
|
|
4118
|
-
|
|
4119
|
-
|
|
6287
|
+
this._assertActive("clear");
|
|
6288
|
+
const span = this._startSpan("tricache.clear");
|
|
6289
|
+
if (this.opts.tracer) span.setAttribute("cache.prefix", prefix || "*");
|
|
6290
|
+
try {
|
|
6291
|
+
this.counters.deletes++;
|
|
6292
|
+
const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
|
|
6293
|
+
if (k) {
|
|
6294
|
+
const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
|
|
6295
|
+
for (const liveKey of this.l1.liveKeys()) {
|
|
6296
|
+
if (liveKey.startsWith(pfx)) {
|
|
6297
|
+
this._bumpKeyMutation(liveKey);
|
|
6298
|
+
}
|
|
6299
|
+
}
|
|
6300
|
+
for (const inflightKey of Array.from(this.inflight.keys())) {
|
|
6301
|
+
if (inflightKey.startsWith(pfx)) {
|
|
6302
|
+
this._bumpKeyMutation(inflightKey);
|
|
6303
|
+
this.inflight.delete(inflightKey);
|
|
6304
|
+
}
|
|
6305
|
+
}
|
|
6306
|
+
this._addPatternTombstone(pfx);
|
|
6307
|
+
this.l1.deletePattern(k);
|
|
6308
|
+
} else {
|
|
6309
|
+
this._globalEpoch++;
|
|
6310
|
+
this.inflight.clear();
|
|
6311
|
+
this._patternTombstones.length = 0;
|
|
6312
|
+
this.l1.clear();
|
|
6313
|
+
if (!this._diskDisabled) this.disk.clear();
|
|
6314
|
+
this._l1Counters.clear();
|
|
6315
|
+
this.tagIndex.clear();
|
|
6316
|
+
this.tagVersions.clear();
|
|
6317
|
+
this._pendingDiskDeletes.clear();
|
|
6318
|
+
this._keyMutationEpochs.clear();
|
|
6319
|
+
}
|
|
6320
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
6321
|
+
try {
|
|
6322
|
+
const client = await this.getRedis();
|
|
6323
|
+
const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
|
|
6324
|
+
const keys = await this._scanKeys(client, pattern);
|
|
6325
|
+
if (keys.length > 0) await client.del(...keys);
|
|
6326
|
+
} catch (err) {
|
|
6327
|
+
this.logger.debug("clear: Redis unavailable", { error: err.message });
|
|
6328
|
+
}
|
|
6329
|
+
}
|
|
6330
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6331
|
+
await this.publishInvalidation(
|
|
6332
|
+
"del-glob",
|
|
6333
|
+
k ?? (this._namespace ? `${this._namespace}:*` : "*"),
|
|
6334
|
+
void 0,
|
|
6335
|
+
false,
|
|
6336
|
+
true
|
|
6337
|
+
);
|
|
6338
|
+
} else {
|
|
6339
|
+
void this.publishInvalidation(
|
|
6340
|
+
"del-glob",
|
|
6341
|
+
k ?? (this._namespace ? `${this._namespace}:*` : "*"),
|
|
6342
|
+
void 0,
|
|
6343
|
+
false,
|
|
6344
|
+
true
|
|
6345
|
+
);
|
|
4120
6346
|
}
|
|
6347
|
+
} catch (err) {
|
|
6348
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6349
|
+
span.recordException?.(err);
|
|
6350
|
+
throw err;
|
|
6351
|
+
} finally {
|
|
6352
|
+
span.end();
|
|
4121
6353
|
}
|
|
4122
|
-
void this.publishInvalidation(
|
|
4123
|
-
"del-glob",
|
|
4124
|
-
k ?? (this._namespace ? `${this._namespace}:*` : "*")
|
|
4125
|
-
);
|
|
4126
6354
|
}
|
|
4127
6355
|
/**
|
|
4128
6356
|
* Evict L1 entries that violate the current category or global capacity limits.
|
|
@@ -4130,6 +6358,7 @@ var CacheService = class _CacheService {
|
|
|
4130
6358
|
* Returns the number of entries evicted.
|
|
4131
6359
|
*/
|
|
4132
6360
|
rebalance() {
|
|
6361
|
+
this._assertActive("rebalance");
|
|
4133
6362
|
return this.l1.rebalance();
|
|
4134
6363
|
}
|
|
4135
6364
|
/**
|
|
@@ -4138,6 +6367,7 @@ var CacheService = class _CacheService {
|
|
|
4138
6367
|
* Only reflects L1 state — does not query Redis or disk.
|
|
4139
6368
|
*/
|
|
4140
6369
|
ttl(cacheKey) {
|
|
6370
|
+
this._assertActive("ttl");
|
|
4141
6371
|
return this.l1.ttl(this.nk(cacheKey));
|
|
4142
6372
|
}
|
|
4143
6373
|
/**
|
|
@@ -4145,6 +6375,7 @@ var CacheService = class _CacheService {
|
|
|
4145
6375
|
* Bloom-filter fast path — no fetch, no disk or Redis round-trip.
|
|
4146
6376
|
*/
|
|
4147
6377
|
has(cacheKey) {
|
|
6378
|
+
this._assertActive("has");
|
|
4148
6379
|
return this.l1.has(this.nk(cacheKey));
|
|
4149
6380
|
}
|
|
4150
6381
|
// ── Iteration ─────────────────────────────────────────────────────────────
|
|
@@ -4155,6 +6386,7 @@ var CacheService = class _CacheService {
|
|
|
4155
6386
|
* for (const key of cache.keys()) console.log(key);
|
|
4156
6387
|
*/
|
|
4157
6388
|
*keys() {
|
|
6389
|
+
this._assertActive("keys");
|
|
4158
6390
|
const prefix = this._namespace ? this._namespace + ":" : "";
|
|
4159
6391
|
for (const key of this.l1.liveKeys()) {
|
|
4160
6392
|
if (prefix && !key.startsWith(prefix)) continue;
|
|
@@ -4169,6 +6401,7 @@ var CacheService = class _CacheService {
|
|
|
4169
6401
|
* for (const val of cache.values<User>()) console.log(val.id);
|
|
4170
6402
|
*/
|
|
4171
6403
|
*values() {
|
|
6404
|
+
this._assertActive("values");
|
|
4172
6405
|
const prefix = this._namespace ? this._namespace + ":" : "";
|
|
4173
6406
|
if (!prefix) {
|
|
4174
6407
|
yield* this.l1.liveValues();
|
|
@@ -4187,6 +6420,7 @@ var CacheService = class _CacheService {
|
|
|
4187
6420
|
* for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
|
|
4188
6421
|
*/
|
|
4189
6422
|
*entries() {
|
|
6423
|
+
this._assertActive("entries");
|
|
4190
6424
|
const prefix = this._namespace ? this._namespace + ":" : "";
|
|
4191
6425
|
for (const [key, entry] of this.l1.liveEntries()) {
|
|
4192
6426
|
if (prefix && !key.startsWith(prefix)) continue;
|
|
@@ -4214,6 +6448,7 @@ var CacheService = class _CacheService {
|
|
|
4214
6448
|
* `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
|
|
4215
6449
|
*/
|
|
4216
6450
|
scan(fn) {
|
|
6451
|
+
this._assertActive("scan");
|
|
4217
6452
|
const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
|
|
4218
6453
|
this.l1.scan((key, entry, pfx) => {
|
|
4219
6454
|
const value = entry.value !== void 0 ? entry.value : entry.data;
|
|
@@ -4227,6 +6462,7 @@ var CacheService = class _CacheService {
|
|
|
4227
6462
|
* @param newTtlSeconds - The new TTL from now, in seconds.
|
|
4228
6463
|
*/
|
|
4229
6464
|
async touch(cacheKey, newTtlSeconds) {
|
|
6465
|
+
this._assertActive("touch");
|
|
4230
6466
|
const k = this.nk(cacheKey);
|
|
4231
6467
|
const hit = this.l1.touch(k, newTtlSeconds * 1e3);
|
|
4232
6468
|
if (hit && !this._redisDisabled) {
|
|
@@ -4247,13 +6483,14 @@ var CacheService = class _CacheService {
|
|
|
4247
6483
|
* if (fresh !== null) return fresh; // serve from L1, no network hop
|
|
4248
6484
|
*/
|
|
4249
6485
|
getIfFresh(cacheKey) {
|
|
6486
|
+
this._assertActive("getIfFresh");
|
|
4250
6487
|
const k = this.nk(cacheKey);
|
|
4251
6488
|
const entry = this.l1.getEntry(k);
|
|
4252
6489
|
if (!entry) return null;
|
|
4253
6490
|
const now = Date.now();
|
|
4254
6491
|
if (entry.expiresAt <= now) return null;
|
|
4255
6492
|
if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
|
|
4256
|
-
return entry.value !== void 0 ? entry.value :
|
|
6493
|
+
return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
4257
6494
|
}
|
|
4258
6495
|
/**
|
|
4259
6496
|
* Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
|
|
@@ -4264,6 +6501,7 @@ var CacheService = class _CacheService {
|
|
|
4264
6501
|
* const val = await cache.peek<User>('user:123');
|
|
4265
6502
|
*/
|
|
4266
6503
|
async peek(cacheKey) {
|
|
6504
|
+
this._assertActive("peek");
|
|
4267
6505
|
const k = this.nk(cacheKey);
|
|
4268
6506
|
const l1Hit = this.l1.get(k);
|
|
4269
6507
|
if (l1Hit !== null) {
|
|
@@ -4273,21 +6511,32 @@ var CacheService = class _CacheService {
|
|
|
4273
6511
|
if (this.opts.frozen) deepFreeze(val);
|
|
4274
6512
|
return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
|
|
4275
6513
|
}
|
|
4276
|
-
if (!this._diskDisabled) {
|
|
4277
|
-
|
|
4278
|
-
|
|
4279
|
-
|
|
4280
|
-
|
|
4281
|
-
|
|
4282
|
-
|
|
4283
|
-
|
|
4284
|
-
|
|
4285
|
-
|
|
4286
|
-
|
|
4287
|
-
|
|
4288
|
-
|
|
4289
|
-
|
|
4290
|
-
|
|
6514
|
+
if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
|
|
6515
|
+
if (this._isTombstonedByPattern(k)) {
|
|
6516
|
+
try {
|
|
6517
|
+
this.disk.delete(k);
|
|
6518
|
+
} catch {
|
|
6519
|
+
}
|
|
6520
|
+
} else if (this.watchdog.isDiskAllowed()) {
|
|
6521
|
+
const diskStart = performance.now();
|
|
6522
|
+
const diskHit = this.disk.load(k);
|
|
6523
|
+
const diskElapsed = performance.now() - diskStart;
|
|
6524
|
+
this.watchdog.recordDisk(diskElapsed);
|
|
6525
|
+
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
6526
|
+
if (diskHit !== null) {
|
|
6527
|
+
const promoted = this.l1.importEntries(
|
|
6528
|
+
[{ key: k, entry: diskHit }],
|
|
6529
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
6530
|
+
);
|
|
6531
|
+
if (promoted > 0) {
|
|
6532
|
+
const l1Check = this.l1.get(k);
|
|
6533
|
+
if (l1Check !== null) {
|
|
6534
|
+
this.counters.gets++;
|
|
6535
|
+
this.counters.diskHits++;
|
|
6536
|
+
const val = l1Check.value;
|
|
6537
|
+
if (this.opts.frozen) deepFreeze(val);
|
|
6538
|
+
return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
|
|
6539
|
+
}
|
|
4291
6540
|
}
|
|
4292
6541
|
}
|
|
4293
6542
|
}
|
|
@@ -4295,7 +6544,10 @@ var CacheService = class _CacheService {
|
|
|
4295
6544
|
if (!this._redisDisabled && !this.cb.isOpen) {
|
|
4296
6545
|
try {
|
|
4297
6546
|
const client = await this.getRedis();
|
|
6547
|
+
const redisStart = performance.now();
|
|
4298
6548
|
const raw = await client.get(k);
|
|
6549
|
+
const redisElapsed = performance.now() - redisStart;
|
|
6550
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
4299
6551
|
if (raw !== null) {
|
|
4300
6552
|
const parsed = await this._decryptAndDeserialize(raw);
|
|
4301
6553
|
this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
|
|
@@ -4322,90 +6574,138 @@ var CacheService = class _CacheService {
|
|
|
4322
6574
|
* `(key) => number` so heterogeneous TTLs can be batched in one call.
|
|
4323
6575
|
*/
|
|
4324
6576
|
async mget(keys, fetchFn, ttl = 300, priority) {
|
|
4325
|
-
|
|
4326
|
-
const
|
|
4327
|
-
|
|
4328
|
-
|
|
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
|
-
}
|
|
6577
|
+
this._assertActive("mget");
|
|
6578
|
+
const span = this._startSpan("tricache.mget");
|
|
6579
|
+
if (this.opts.tracer) {
|
|
6580
|
+
span.setAttribute("cache.batch.size", keys.length);
|
|
4338
6581
|
}
|
|
4339
|
-
|
|
4340
|
-
|
|
4341
|
-
|
|
4342
|
-
|
|
4343
|
-
|
|
4344
|
-
const
|
|
4345
|
-
|
|
4346
|
-
|
|
4347
|
-
|
|
4348
|
-
|
|
4349
|
-
|
|
4350
|
-
|
|
4351
|
-
|
|
4352
|
-
|
|
4353
|
-
|
|
4354
|
-
|
|
4355
|
-
|
|
4356
|
-
|
|
4357
|
-
|
|
4358
|
-
|
|
4359
|
-
|
|
6582
|
+
try {
|
|
6583
|
+
const result = Array.from({ length: keys.length });
|
|
6584
|
+
const missIndexes = [];
|
|
6585
|
+
const missKeys = [];
|
|
6586
|
+
for (let i = 0; i < keys.length; i++) {
|
|
6587
|
+
const k = this.nk(keys[i]);
|
|
6588
|
+
const entry = this.l1.getEntry(k);
|
|
6589
|
+
if (entry && entry.expiresAt > Date.now()) {
|
|
6590
|
+
result[i] = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
6591
|
+
this.counters.l1Hits++;
|
|
6592
|
+
} else {
|
|
6593
|
+
missIndexes.push(i);
|
|
6594
|
+
missKeys.push(keys[i]);
|
|
6595
|
+
}
|
|
6596
|
+
}
|
|
6597
|
+
if (missKeys.length === 0) {
|
|
6598
|
+
if (this.opts.tracer) {
|
|
6599
|
+
span.setAttribute("cache.hits", keys.length);
|
|
6600
|
+
span.setAttribute("cache.misses", 0);
|
|
6601
|
+
span.setAttribute("cache.l1_hits", keys.length);
|
|
6602
|
+
span.setAttribute("cache.l2_hits", 0);
|
|
6603
|
+
}
|
|
6604
|
+
return result;
|
|
6605
|
+
}
|
|
6606
|
+
let l2HitCount = 0;
|
|
6607
|
+
if (!this._redisDisabled) {
|
|
6608
|
+
try {
|
|
6609
|
+
const client = await this.getRedis();
|
|
6610
|
+
const nsKeys = missKeys.map((k) => this.nk(k));
|
|
6611
|
+
const pipeline = client.multi();
|
|
6612
|
+
for (const nk of nsKeys) pipeline.get(nk);
|
|
6613
|
+
const redisStart = performance.now();
|
|
6614
|
+
const raws = await pipeline.exec();
|
|
6615
|
+
const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
|
|
6616
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
6617
|
+
this.cb.onSuccess();
|
|
6618
|
+
for (let j = 0; j < missKeys.length; j++) {
|
|
6619
|
+
const raw = raws[j] ? raws[j][1] : null;
|
|
6620
|
+
const idx = missIndexes[j];
|
|
6621
|
+
if (raw) {
|
|
6622
|
+
const parsed = await this._decryptAndDeserialize(raw);
|
|
6623
|
+
const k = nsKeys[j];
|
|
6624
|
+
const p = priority ?? inferPriority(missKeys[j]);
|
|
6625
|
+
this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
|
|
6626
|
+
this.counters.l2Hits++;
|
|
6627
|
+
l2HitCount++;
|
|
6628
|
+
result[idx] = parsed;
|
|
6629
|
+
missIndexes[j] = -1;
|
|
6630
|
+
missKeys[j] = "";
|
|
6631
|
+
}
|
|
4360
6632
|
}
|
|
6633
|
+
const remainingIdx = missIndexes.filter((i) => i >= 0);
|
|
6634
|
+
const remainingKeys = missKeys.filter((k) => k !== "");
|
|
6635
|
+
missIndexes.length = 0;
|
|
6636
|
+
missKeys.length = 0;
|
|
6637
|
+
missIndexes.push(...remainingIdx);
|
|
6638
|
+
missKeys.push(...remainingKeys);
|
|
6639
|
+
} catch (err) {
|
|
6640
|
+
this.cb.onFailure();
|
|
6641
|
+
this.logger.debug("mget: Redis unavailable, continuing to disk/fetch", { error: err.message });
|
|
4361
6642
|
}
|
|
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
6643
|
}
|
|
4373
|
-
|
|
4374
|
-
|
|
4375
|
-
|
|
4376
|
-
|
|
4377
|
-
|
|
4378
|
-
|
|
4379
|
-
|
|
4380
|
-
|
|
4381
|
-
|
|
4382
|
-
|
|
4383
|
-
|
|
4384
|
-
|
|
4385
|
-
|
|
4386
|
-
|
|
4387
|
-
|
|
4388
|
-
|
|
4389
|
-
|
|
6644
|
+
if (!this._diskDisabled && missKeys.length > 0) {
|
|
6645
|
+
for (let j = missKeys.length - 1; j >= 0; j--) {
|
|
6646
|
+
const k = this.nk(missKeys[j]);
|
|
6647
|
+
if (this._pendingDiskDeletes.has(k)) continue;
|
|
6648
|
+
if (this._isTombstonedByPattern(k)) {
|
|
6649
|
+
try {
|
|
6650
|
+
this.disk.delete(k);
|
|
6651
|
+
} catch {
|
|
6652
|
+
}
|
|
6653
|
+
continue;
|
|
6654
|
+
}
|
|
6655
|
+
if (!this.watchdog.isDiskAllowed()) continue;
|
|
6656
|
+
const diskStart = performance.now();
|
|
6657
|
+
const diskHit = this.disk.load(k);
|
|
6658
|
+
const diskElapsed = performance.now() - diskStart;
|
|
6659
|
+
this.watchdog.recordDisk(diskElapsed);
|
|
6660
|
+
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
6661
|
+
if (diskHit !== null) {
|
|
6662
|
+
const promoted = this.l1.importEntries(
|
|
6663
|
+
[{ key: k, entry: diskHit }],
|
|
6664
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
6665
|
+
);
|
|
6666
|
+
if (promoted > 0) {
|
|
6667
|
+
const l1Check = this.l1.get(k);
|
|
6668
|
+
if (l1Check !== null) {
|
|
6669
|
+
this.counters.diskHits++;
|
|
6670
|
+
result[missIndexes[j]] = l1Check.value;
|
|
6671
|
+
missIndexes.splice(j, 1);
|
|
6672
|
+
missKeys.splice(j, 1);
|
|
6673
|
+
}
|
|
4390
6674
|
}
|
|
4391
6675
|
}
|
|
4392
6676
|
}
|
|
4393
6677
|
}
|
|
4394
|
-
if (missKeys.length
|
|
4395
|
-
|
|
4396
|
-
|
|
4397
|
-
|
|
4398
|
-
|
|
4399
|
-
|
|
4400
|
-
|
|
4401
|
-
|
|
4402
|
-
|
|
4403
|
-
|
|
4404
|
-
|
|
6678
|
+
if (missKeys.length > 0) {
|
|
6679
|
+
this.counters.fetches++;
|
|
6680
|
+
const fetched = await fetchFn(missKeys);
|
|
6681
|
+
const setPromises = [];
|
|
6682
|
+
for (let j = 0; j < missKeys.length; j++) {
|
|
6683
|
+
const v = fetched[missKeys[j]];
|
|
6684
|
+
result[missIndexes[j]] = v;
|
|
6685
|
+
if (v !== void 0) {
|
|
6686
|
+
const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
|
|
6687
|
+
setPromises.push(this.set(missKeys[j], v, resolvedTtl, priority));
|
|
6688
|
+
}
|
|
6689
|
+
}
|
|
6690
|
+
if (setPromises.length > 0) {
|
|
6691
|
+
await Promise.all(setPromises);
|
|
4405
6692
|
}
|
|
4406
6693
|
}
|
|
6694
|
+
if (this.opts.tracer) {
|
|
6695
|
+
const finalMisses = missKeys.length;
|
|
6696
|
+
const totalHits = keys.length - finalMisses;
|
|
6697
|
+
span.setAttribute("cache.hits", totalHits);
|
|
6698
|
+
span.setAttribute("cache.misses", finalMisses);
|
|
6699
|
+
span.setAttribute("cache.l2_hits", l2HitCount);
|
|
6700
|
+
}
|
|
6701
|
+
return result;
|
|
6702
|
+
} catch (err) {
|
|
6703
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6704
|
+
span.recordException?.(err);
|
|
6705
|
+
throw err;
|
|
6706
|
+
} finally {
|
|
6707
|
+
span.end();
|
|
4407
6708
|
}
|
|
4408
|
-
return result;
|
|
4409
6709
|
}
|
|
4410
6710
|
/**
|
|
4411
6711
|
* Returns a Promise that resolves once the cache is fully initialised and any
|
|
@@ -4432,12 +6732,25 @@ var CacheService = class _CacheService {
|
|
|
4432
6732
|
* });
|
|
4433
6733
|
*/
|
|
4434
6734
|
async mset(entries) {
|
|
6735
|
+
this._assertActive("mset");
|
|
6736
|
+
const span = this._startSpan("tricache.mset");
|
|
4435
6737
|
const keys = Object.keys(entries);
|
|
4436
|
-
|
|
4437
|
-
|
|
4438
|
-
|
|
4439
|
-
|
|
4440
|
-
|
|
6738
|
+
if (this.opts.tracer) {
|
|
6739
|
+
span.setAttribute("cache.batch.size", keys.length);
|
|
6740
|
+
}
|
|
6741
|
+
try {
|
|
6742
|
+
await Promise.all(keys.map((key) => {
|
|
6743
|
+
const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
|
|
6744
|
+
const hasOpts = tags?.length || dependsOn?.length;
|
|
6745
|
+
return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
|
|
6746
|
+
}));
|
|
6747
|
+
} catch (err) {
|
|
6748
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6749
|
+
span.recordException?.(err);
|
|
6750
|
+
throw err;
|
|
6751
|
+
} finally {
|
|
6752
|
+
span.end();
|
|
6753
|
+
}
|
|
4441
6754
|
}
|
|
4442
6755
|
/**
|
|
4443
6756
|
* Batch delete — delete multiple exact keys in a single call.
|
|
@@ -4447,7 +6760,20 @@ var CacheService = class _CacheService {
|
|
|
4447
6760
|
* await cache.mdel(['user:1', 'user:2', 'user:3']);
|
|
4448
6761
|
*/
|
|
4449
6762
|
async mdel(keys) {
|
|
4450
|
-
|
|
6763
|
+
this._assertActive("mdel");
|
|
6764
|
+
const span = this._startSpan("tricache.mdel");
|
|
6765
|
+
if (this.opts.tracer) {
|
|
6766
|
+
span.setAttribute("cache.batch.size", keys.length);
|
|
6767
|
+
}
|
|
6768
|
+
try {
|
|
6769
|
+
await Promise.all(keys.map((k) => this.delete(k)));
|
|
6770
|
+
} catch (err) {
|
|
6771
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6772
|
+
span.recordException?.(err);
|
|
6773
|
+
throw err;
|
|
6774
|
+
} finally {
|
|
6775
|
+
span.end();
|
|
6776
|
+
}
|
|
4451
6777
|
}
|
|
4452
6778
|
/**
|
|
4453
6779
|
* Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
|
|
@@ -4462,6 +6788,7 @@ var CacheService = class _CacheService {
|
|
|
4462
6788
|
* console.log(`Warmed ${loaded} keys from Redis`);
|
|
4463
6789
|
*/
|
|
4464
6790
|
async warmFromL2(pattern, opts) {
|
|
6791
|
+
this._assertActive("warmFromL2");
|
|
4465
6792
|
if (this._redisDisabled) return 0;
|
|
4466
6793
|
try {
|
|
4467
6794
|
const client = await this.getRedis();
|
|
@@ -4476,7 +6803,6 @@ var CacheService = class _CacheService {
|
|
|
4476
6803
|
const results = await pl.exec();
|
|
4477
6804
|
this.cb.onSuccess();
|
|
4478
6805
|
let loaded = 0;
|
|
4479
|
-
const now = Date.now();
|
|
4480
6806
|
for (let i = 0; i < matchedKeys.length; i++) {
|
|
4481
6807
|
const [err, raw] = results[i];
|
|
4482
6808
|
if (err || raw == null) continue;
|
|
@@ -4488,7 +6814,6 @@ var CacheService = class _CacheService {
|
|
|
4488
6814
|
} catch {
|
|
4489
6815
|
}
|
|
4490
6816
|
}
|
|
4491
|
-
void now;
|
|
4492
6817
|
this.logger.info("warmFromL2 complete", {
|
|
4493
6818
|
pattern,
|
|
4494
6819
|
matched: matchedKeys.length,
|
|
@@ -4510,45 +6835,71 @@ var CacheService = class _CacheService {
|
|
|
4510
6835
|
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
4511
6836
|
*/
|
|
4512
6837
|
async invalidateTag(tag) {
|
|
4513
|
-
|
|
4514
|
-
|
|
6838
|
+
this._assertActive("invalidateTag");
|
|
6839
|
+
const span = this._startSpan("tricache.invalidate_tag");
|
|
6840
|
+
if (this.opts.tracer) {
|
|
6841
|
+
span.setAttribute("cache.tag", tag);
|
|
6842
|
+
span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
|
|
6843
|
+
}
|
|
6844
|
+
try {
|
|
6845
|
+
if (this.opts.tagStrategy === "generational") {
|
|
6846
|
+
let newVer = 1;
|
|
6847
|
+
if (!this._redisDisabled) {
|
|
6848
|
+
try {
|
|
6849
|
+
const client = await this.getRedis();
|
|
6850
|
+
newVer = await client.incr(this.nk(`tag_ver:${tag}`));
|
|
6851
|
+
} catch (err) {
|
|
6852
|
+
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
6853
|
+
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
6854
|
+
newVer = current + 1;
|
|
6855
|
+
}
|
|
6856
|
+
} else {
|
|
6857
|
+
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
6858
|
+
newVer = current + 1;
|
|
6859
|
+
}
|
|
6860
|
+
this._setLocalTagVersion(tag, newVer, performance.now());
|
|
6861
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6862
|
+
await this.publishInvalidation("tag_incr", tag, newVer, false, true);
|
|
6863
|
+
} else {
|
|
6864
|
+
void this.publishInvalidation("tag_incr", tag, newVer, false, true);
|
|
6865
|
+
}
|
|
6866
|
+
return;
|
|
6867
|
+
}
|
|
6868
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
6869
|
+
const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
|
|
6870
|
+
for (const k of members) {
|
|
6871
|
+
this.l1.delete(k);
|
|
6872
|
+
this._bumpKeyMutation(k);
|
|
6873
|
+
this._pendingDiskDeletes.add(k);
|
|
6874
|
+
setImmediate(() => {
|
|
6875
|
+
try {
|
|
6876
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
6877
|
+
} finally {
|
|
6878
|
+
this._pendingDiskDeletes.delete(k);
|
|
6879
|
+
}
|
|
6880
|
+
});
|
|
6881
|
+
}
|
|
6882
|
+
this.tagIndex.delete(tagKey);
|
|
4515
6883
|
if (!this._redisDisabled) {
|
|
4516
6884
|
try {
|
|
4517
6885
|
const client = await this.getRedis();
|
|
4518
|
-
|
|
6886
|
+
const redisMembers = await client.smembers(tagKey);
|
|
6887
|
+
const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
|
|
6888
|
+
if (toDelete.length > 0) {
|
|
6889
|
+
await client.del(...toDelete, tagKey);
|
|
6890
|
+
} else {
|
|
6891
|
+
await client.del(tagKey);
|
|
6892
|
+
}
|
|
4519
6893
|
} catch (err) {
|
|
4520
6894
|
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
6895
|
}
|
|
4549
|
-
} catch (err) {
|
|
4550
|
-
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
4551
6896
|
}
|
|
6897
|
+
} catch (err) {
|
|
6898
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6899
|
+
span.recordException?.(err);
|
|
6900
|
+
throw err;
|
|
6901
|
+
} finally {
|
|
6902
|
+
span.end();
|
|
4552
6903
|
}
|
|
4553
6904
|
}
|
|
4554
6905
|
/**
|
|
@@ -4564,13 +6915,14 @@ var CacheService = class _CacheService {
|
|
|
4564
6915
|
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
|
|
4565
6916
|
*/
|
|
4566
6917
|
async invalidateTags(tags) {
|
|
6918
|
+
this._assertActive("invalidateTags");
|
|
4567
6919
|
if (tags.length === 0) return;
|
|
4568
6920
|
if (tags.length === 1) {
|
|
4569
6921
|
await this.invalidateTag(tags[0]);
|
|
4570
6922
|
return;
|
|
4571
6923
|
}
|
|
4572
6924
|
if (this.opts.tagStrategy === "generational") {
|
|
4573
|
-
const now =
|
|
6925
|
+
const now = performance.now();
|
|
4574
6926
|
if (!this._redisDisabled) {
|
|
4575
6927
|
try {
|
|
4576
6928
|
const client = await this.getRedis();
|
|
@@ -4581,7 +6933,11 @@ var CacheService = class _CacheService {
|
|
|
4581
6933
|
const [err, newVer] = results[i] ?? [null, null];
|
|
4582
6934
|
const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
|
|
4583
6935
|
this._setLocalTagVersion(tags[i], ver, now);
|
|
4584
|
-
|
|
6936
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6937
|
+
await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
|
|
6938
|
+
} else {
|
|
6939
|
+
void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
|
|
6940
|
+
}
|
|
4585
6941
|
}
|
|
4586
6942
|
return;
|
|
4587
6943
|
} catch (err) {
|
|
@@ -4591,7 +6947,11 @@ var CacheService = class _CacheService {
|
|
|
4591
6947
|
for (const tag of tags) {
|
|
4592
6948
|
const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
4593
6949
|
this._setLocalTagVersion(tag, ver, now);
|
|
4594
|
-
|
|
6950
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6951
|
+
await this.publishInvalidation("tag_incr", tag, ver, false, true);
|
|
6952
|
+
} else {
|
|
6953
|
+
void this.publishInvalidation("tag_incr", tag, ver, false, true);
|
|
6954
|
+
}
|
|
4595
6955
|
}
|
|
4596
6956
|
return;
|
|
4597
6957
|
}
|
|
@@ -4606,7 +6966,15 @@ var CacheService = class _CacheService {
|
|
|
4606
6966
|
}
|
|
4607
6967
|
for (const k of allMembers) {
|
|
4608
6968
|
this.l1.delete(k);
|
|
4609
|
-
this.
|
|
6969
|
+
this._bumpKeyMutation(k);
|
|
6970
|
+
this._pendingDiskDeletes.add(k);
|
|
6971
|
+
setImmediate(() => {
|
|
6972
|
+
try {
|
|
6973
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
6974
|
+
} finally {
|
|
6975
|
+
this._pendingDiskDeletes.delete(k);
|
|
6976
|
+
}
|
|
6977
|
+
});
|
|
4610
6978
|
}
|
|
4611
6979
|
if (!this._redisDisabled) {
|
|
4612
6980
|
try {
|
|
@@ -4643,6 +7011,7 @@ var CacheService = class _CacheService {
|
|
|
4643
7011
|
* `l2` is `null` when Redis is disabled.
|
|
4644
7012
|
*/
|
|
4645
7013
|
async ping() {
|
|
7014
|
+
this._assertActive("ping");
|
|
4646
7015
|
const t0 = Date.now();
|
|
4647
7016
|
this.l1.has("__ping__");
|
|
4648
7017
|
const l1 = Date.now() - t0;
|
|
@@ -4662,12 +7031,67 @@ var CacheService = class _CacheService {
|
|
|
4662
7031
|
}
|
|
4663
7032
|
return { l1, disk, l2 };
|
|
4664
7033
|
}
|
|
7034
|
+
/**
|
|
7035
|
+
* Health and readiness diagnostics for container orchestrators (e.g. Kubernetes, ECS, Nomad).
|
|
7036
|
+
*
|
|
7037
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
7038
|
+
* ⚠️ CRITICAL CONTAINER PROBE SEMANTICS (Liveness vs. Readiness):
|
|
7039
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
7040
|
+
* ❌ NEVER bind `degraded` checks or `cache.health()` to your Liveness Probe (/livez, /healthz).
|
|
7041
|
+
* If an SRE hooks degraded status into liveness, a storage-starved or EBS-throttled pod
|
|
7042
|
+
* will be killed by the kubelet, triggering a cluster-wide cascading restart shockwave.
|
|
7043
|
+
* Liveness probes must only check that the event loop / process is alive.
|
|
7044
|
+
*
|
|
7045
|
+
* ✅ BIND degraded checks strictly to your Readiness Probe (/ready, /readyz).
|
|
7046
|
+
* A degraded cache (e.g. EBS latency spike, quota watermark pruning, or open Redis circuit)
|
|
7047
|
+
* can shed traffic at the ingress load balancer while the Node.js process remains
|
|
7048
|
+
* alive to drain in-flight promises and heal its local storage.
|
|
7049
|
+
*
|
|
7050
|
+
* By default, `healthy` remains `true` even when degraded (graceful local degradation).
|
|
7051
|
+
* Set `failReadinessOnDegraded: true` in CacheOptions if you want your Readiness probe
|
|
7052
|
+
* to route ingress traffic away while degraded.
|
|
7053
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
7054
|
+
*/
|
|
7055
|
+
health() {
|
|
7056
|
+
const watchdogTel = this.watchdog.getTelemetry();
|
|
7057
|
+
const diskPruning = !this._diskDisabled && this.disk.isPruning;
|
|
7058
|
+
const diskLowSpace = !this._diskDisabled && this.disk.hostVolumeLowSpace;
|
|
7059
|
+
const circuitOpen = this.cb.isOpen;
|
|
7060
|
+
const latencyBypass = watchdogTel.bypassActive;
|
|
7061
|
+
const degraded = circuitOpen || latencyBypass || diskPruning || diskLowSpace;
|
|
7062
|
+
const healthy = this.opts.failReadinessOnDegraded ? !degraded : true;
|
|
7063
|
+
const reasons = [];
|
|
7064
|
+
if (circuitOpen) reasons.push("redis_circuit_breaker_open");
|
|
7065
|
+
if (latencyBypass) reasons.push(`disk_latency_bypass_stage_${watchdogTel.bypassStage}`);
|
|
7066
|
+
if (diskPruning) reasons.push("disk_quota_watermark_pruning_active");
|
|
7067
|
+
if (diskLowSpace) reasons.push("disk_host_volume_low_space");
|
|
7068
|
+
return {
|
|
7069
|
+
healthy,
|
|
7070
|
+
degraded,
|
|
7071
|
+
reasons,
|
|
7072
|
+
details: {
|
|
7073
|
+
redisConnected: !circuitOpen && !this._redisDisabled,
|
|
7074
|
+
circuitBreakerState: this.cb.currentState,
|
|
7075
|
+
diskPruningActive: diskPruning,
|
|
7076
|
+
diskHostVolumeLowSpace: diskLowSpace,
|
|
7077
|
+
watchdog: watchdogTel
|
|
7078
|
+
}
|
|
7079
|
+
};
|
|
7080
|
+
}
|
|
7081
|
+
/**
|
|
7082
|
+
* Direct access to the internal tier latency watchdog instance.
|
|
7083
|
+
* Used for diagnostics, canary probes, and control-loop tuning.
|
|
7084
|
+
*/
|
|
7085
|
+
getLatencyWatchdog() {
|
|
7086
|
+
return this.watchdog;
|
|
7087
|
+
}
|
|
4665
7088
|
/**
|
|
4666
7089
|
* Export all live L1 entries to Redis via a single pipeline.
|
|
4667
7090
|
* Useful for warming a new Redis instance or for zero-downtime failover.
|
|
4668
7091
|
* Returns the number of keys written.
|
|
4669
7092
|
*/
|
|
4670
7093
|
async drainToL2() {
|
|
7094
|
+
this._assertActive("drainToL2");
|
|
4671
7095
|
if (this._redisDisabled) return 0;
|
|
4672
7096
|
try {
|
|
4673
7097
|
const client = await this.getRedis();
|
|
@@ -4711,6 +7135,7 @@ var CacheService = class _CacheService {
|
|
|
4711
7135
|
* if (!claimed) return res.status(409).json({ error: 'duplicate request' });
|
|
4712
7136
|
*/
|
|
4713
7137
|
async setIfAbsent(cacheKey, value, ttlSeconds = 300, priority) {
|
|
7138
|
+
this._assertActive("setIfAbsent");
|
|
4714
7139
|
const k = this.nk(cacheKey);
|
|
4715
7140
|
if (this.l1.has(k)) return false;
|
|
4716
7141
|
if (!this._redisDisabled) {
|
|
@@ -4729,6 +7154,8 @@ var CacheService = class _CacheService {
|
|
|
4729
7154
|
}
|
|
4730
7155
|
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
4731
7156
|
const p = priority ?? inferPriority(cacheKey);
|
|
7157
|
+
this._bumpKeyMutation(k);
|
|
7158
|
+
this._pendingDiskDeletes.delete(k);
|
|
4732
7159
|
this.l1.set(k, value, ttlMs, p);
|
|
4733
7160
|
this.counters.sets++;
|
|
4734
7161
|
return true;
|
|
@@ -4747,6 +7174,7 @@ var CacheService = class _CacheService {
|
|
|
4747
7174
|
* @param options TTL, acquire timeout, and retry polling intervals.
|
|
4748
7175
|
*/
|
|
4749
7176
|
async lock(resourceKey, fn, options) {
|
|
7177
|
+
this._assertActive("lock");
|
|
4750
7178
|
const ttlSeconds = Math.max(1, options?.ttl ?? 30);
|
|
4751
7179
|
const acquireTimeout = Math.max(0, options?.acquireTimeout ?? 5e3);
|
|
4752
7180
|
const retryInterval = Math.max(10, options?.retryInterval ?? 100);
|
|
@@ -4773,6 +7201,10 @@ var CacheService = class _CacheService {
|
|
|
4773
7201
|
}
|
|
4774
7202
|
} catch (err) {
|
|
4775
7203
|
if (err.message.startsWith("Failed to acquire lock")) throw err;
|
|
7204
|
+
const failClosed = options?.failClosedOnRedisError ?? this.opts.lockFailClosed;
|
|
7205
|
+
if (failClosed) {
|
|
7206
|
+
throw new Error(`Distributed lock acquisition failed for resource "${resourceKey}" due to Redis error: ${err.message}`);
|
|
7207
|
+
}
|
|
4776
7208
|
this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
|
|
4777
7209
|
resourceKey,
|
|
4778
7210
|
error: err.message
|
|
@@ -4909,7 +7341,7 @@ var CacheService = class _CacheService {
|
|
|
4909
7341
|
if (visited.has(dep)) continue;
|
|
4910
7342
|
this.l1.delete(dep);
|
|
4911
7343
|
if (!this._diskDisabled) this.disk.delete(dep);
|
|
4912
|
-
void this.publishInvalidation("del", dep);
|
|
7344
|
+
void this.publishInvalidation("del", dep, void 0, false, true);
|
|
4913
7345
|
this.logger.debug("Dependency cascade: invalidated dependent key", {
|
|
4914
7346
|
trigger: deletedKey.slice(0, 60),
|
|
4915
7347
|
dependent: dep.slice(0, 60)
|
|
@@ -4974,12 +7406,36 @@ var CacheService = class _CacheService {
|
|
|
4974
7406
|
evictions: c.oomEvictions,
|
|
4975
7407
|
lastTriggeredAt: c.oomLastAt
|
|
4976
7408
|
},
|
|
7409
|
+
...this.opts.remoteSnapshot && {
|
|
7410
|
+
remoteSnapshot: {
|
|
7411
|
+
enabled: true,
|
|
7412
|
+
uploads: c.remoteSnapshotUploads,
|
|
7413
|
+
downloads: c.remoteSnapshotDownloads,
|
|
7414
|
+
errors: c.remoteSnapshotErrors,
|
|
7415
|
+
lastUploadedAt: c.remoteSnapshotLastUploadedAt,
|
|
7416
|
+
lastDownloadedAt: c.remoteSnapshotLastDownloadedAt
|
|
7417
|
+
}
|
|
7418
|
+
},
|
|
7419
|
+
...this.opts.crossRegion && {
|
|
7420
|
+
crossRegion: {
|
|
7421
|
+
enabled: true,
|
|
7422
|
+
currentRegion: this.opts.crossRegion.currentRegion,
|
|
7423
|
+
sent: c.crossRegionSent,
|
|
7424
|
+
received: c.crossRegionReceived,
|
|
7425
|
+
deduplicated: c.crossRegionDeduplicated,
|
|
7426
|
+
errors: c.crossRegionErrors
|
|
7427
|
+
}
|
|
7428
|
+
},
|
|
4977
7429
|
l1: {
|
|
4978
7430
|
entries: l1s.entries,
|
|
4979
7431
|
sizeBytes: this.l1.memoryUsage,
|
|
4980
7432
|
maxBytes: this.opts.l1MaxBytes
|
|
4981
7433
|
},
|
|
4982
|
-
disk: {
|
|
7434
|
+
disk: {
|
|
7435
|
+
...this.disk.stats,
|
|
7436
|
+
disabled: this._diskDisabled,
|
|
7437
|
+
latencyWatchdog: this.watchdog.getTelemetry()
|
|
7438
|
+
},
|
|
4983
7439
|
...this.latencyTracker && {
|
|
4984
7440
|
adaptiveTtl: {
|
|
4985
7441
|
enabled: true,
|
|
@@ -4992,9 +7448,16 @@ var CacheService = class _CacheService {
|
|
|
4992
7448
|
this.opts.adaptiveTtlMaxMs
|
|
4993
7449
|
)
|
|
4994
7450
|
}
|
|
7451
|
+
},
|
|
7452
|
+
...this.pipeliner && {
|
|
7453
|
+
pipelining: this.pipeliner.stats
|
|
4995
7454
|
}
|
|
4996
7455
|
};
|
|
4997
7456
|
}
|
|
7457
|
+
/** Return auto-pipelining metrics, or null if pipelining is disabled. */
|
|
7458
|
+
getPipelinerStats() {
|
|
7459
|
+
return this.pipeliner ? this.pipeliner.stats : null;
|
|
7460
|
+
}
|
|
4998
7461
|
/**
|
|
4999
7462
|
* Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
|
|
5000
7463
|
* Paste the result into your `/metrics` endpoint.
|
|
@@ -5034,6 +7497,18 @@ var CacheService = class _CacheService {
|
|
|
5034
7497
|
gauge("l1_entries", m.l1.entries, "Current L1 entry count");
|
|
5035
7498
|
gauge("l1_size_bytes", m.l1.sizeBytes, "Current L1 used bytes");
|
|
5036
7499
|
gauge("disk_files", m.disk.files, "Current L1.5 disk file count");
|
|
7500
|
+
if (m.disk.latencyWatchdog) {
|
|
7501
|
+
gauge("disk_latency_bypass_stage", m.disk.latencyWatchdog.bypassStage, "Disk latency watchdog bypass stage (0: normal, 1: 25%, 2: 75%, 3: 100%)");
|
|
7502
|
+
gauge("disk_p95_ms", m.disk.latencyWatchdog.diskP95Ms, "Disk read p95 latency in ms");
|
|
7503
|
+
gauge("redis_p95_ms", m.disk.latencyWatchdog.redisP95Ms, "Redis read p95 latency in ms");
|
|
7504
|
+
counter("disk_bypassed_events", m.disk.latencyWatchdog.bypassedTotal, "Total disk bypass activation events");
|
|
7505
|
+
}
|
|
7506
|
+
if (m.disk.pruning) {
|
|
7507
|
+
counter("disk_spills_shed", m.disk.pruning.spillsShedTotal, "Total disk spills shed due to pruning or low disk space");
|
|
7508
|
+
counter("disk_prune_rounds", m.disk.pruning.pruneRounds, "Total high-watermark disk prune rounds");
|
|
7509
|
+
counter("disk_entries_pruned", m.disk.pruning.entriesPruned, "Total entries removed by watermark pruning");
|
|
7510
|
+
counter("disk_low_space_pauses", m.disk.pruning.hostVolumeLowSpacePauses, "Total times spills paused due to <10% host volume space");
|
|
7511
|
+
}
|
|
5037
7512
|
gauge(
|
|
5038
7513
|
"bloom_false_positive_rate",
|
|
5039
7514
|
m.bloom.falsePositiveRate,
|
|
@@ -5055,6 +7530,17 @@ var CacheService = class _CacheService {
|
|
|
5055
7530
|
"Emergency L1 eviction rounds triggered by heap pressure"
|
|
5056
7531
|
);
|
|
5057
7532
|
}
|
|
7533
|
+
if (m.remoteSnapshot?.enabled) {
|
|
7534
|
+
counter("remote_snapshot_uploads", m.remoteSnapshot.uploads, "Total remote snapshot uploads");
|
|
7535
|
+
counter("remote_snapshot_downloads", m.remoteSnapshot.downloads, "Total remote snapshot downloads");
|
|
7536
|
+
counter("remote_snapshot_errors", m.remoteSnapshot.errors, "Total remote snapshot errors");
|
|
7537
|
+
}
|
|
7538
|
+
if (m.crossRegion?.enabled) {
|
|
7539
|
+
counter("cross_region_sent", m.crossRegion.sent, "Total cross-region invalidations broadcast");
|
|
7540
|
+
counter("cross_region_received", m.crossRegion.received, "Total cross-region invalidations received");
|
|
7541
|
+
counter("cross_region_deduplicated", m.crossRegion.deduplicated, "Total cross-region invalidations deduplicated or self-filtered");
|
|
7542
|
+
counter("cross_region_errors", m.crossRegion.errors, "Total cross-region relay errors");
|
|
7543
|
+
}
|
|
5058
7544
|
return lines.join("\n");
|
|
5059
7545
|
}
|
|
5060
7546
|
// ── Lifecycle ────────────────────────────────────────────────────────────
|
|
@@ -5064,6 +7550,7 @@ var CacheService = class _CacheService {
|
|
|
5064
7550
|
* the previous key for seamless fallback decryption of existing cache entries.
|
|
5065
7551
|
*/
|
|
5066
7552
|
async rotateEncryptionKey(newKeyBase64, newMode) {
|
|
7553
|
+
this._assertActive("rotateEncryptionKey");
|
|
5067
7554
|
this.enc.rotateKey(newKeyBase64, newMode);
|
|
5068
7555
|
if (this._workerPool) {
|
|
5069
7556
|
await this._workerPool.drainAndReinit(this.enc.toWorkerInit());
|
|
@@ -5073,23 +7560,33 @@ var CacheService = class _CacheService {
|
|
|
5073
7560
|
/** Close Redis connections and stop all background timers. */
|
|
5074
7561
|
async destroy() {
|
|
5075
7562
|
this._destroyed = true;
|
|
7563
|
+
this._pendingDiskDeletes.clear();
|
|
7564
|
+
this._keyMutationEpochs.clear();
|
|
7565
|
+
const g = globalThis;
|
|
7566
|
+
const key = _CacheService.globalKey(this.opts);
|
|
7567
|
+
if (g[key] === this) {
|
|
7568
|
+
delete g[key];
|
|
7569
|
+
}
|
|
5076
7570
|
if (this.cleanupInterval) clearInterval(this.cleanupInterval);
|
|
5077
7571
|
if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
|
|
5078
7572
|
if (this.oomInterval) clearInterval(this.oomInterval);
|
|
5079
7573
|
if (this.metricsInterval) clearInterval(this.metricsInterval);
|
|
5080
|
-
if (this.
|
|
5081
|
-
|
|
5082
|
-
|
|
5083
|
-
this._shutdownHandler = null;
|
|
7574
|
+
if (this.remoteSnapshotInterval) {
|
|
7575
|
+
clearInterval(this.remoteSnapshotInterval);
|
|
7576
|
+
this.remoteSnapshotInterval = null;
|
|
5084
7577
|
}
|
|
7578
|
+
ProcessTerminationBus.unregister(this);
|
|
7579
|
+
this._shutdownHandler = null;
|
|
5085
7580
|
if (this._workerPool) {
|
|
5086
7581
|
await this._workerPool.destroy();
|
|
5087
7582
|
this._workerPool = null;
|
|
5088
7583
|
}
|
|
5089
7584
|
if (this.subClient) {
|
|
5090
|
-
|
|
5091
|
-
|
|
5092
|
-
|
|
7585
|
+
if (!this.opts.redisSubClient) {
|
|
7586
|
+
try {
|
|
7587
|
+
this.subClient.disconnect();
|
|
7588
|
+
} catch {
|
|
7589
|
+
}
|
|
5093
7590
|
}
|
|
5094
7591
|
this.subClient = null;
|
|
5095
7592
|
}
|
|
@@ -5101,17 +7598,37 @@ var CacheService = class _CacheService {
|
|
|
5101
7598
|
this.streamClient = null;
|
|
5102
7599
|
}
|
|
5103
7600
|
if (this.redis) {
|
|
5104
|
-
|
|
5105
|
-
|
|
5106
|
-
|
|
7601
|
+
if (!this.opts.redisClient) {
|
|
7602
|
+
try {
|
|
7603
|
+
await this.redis.disconnect();
|
|
7604
|
+
} catch {
|
|
7605
|
+
}
|
|
5107
7606
|
}
|
|
5108
7607
|
this.redis = null;
|
|
5109
7608
|
}
|
|
7609
|
+
if (this._ipcServer) {
|
|
7610
|
+
await this._ipcServer.close();
|
|
7611
|
+
this._ipcServer = void 0;
|
|
7612
|
+
}
|
|
5110
7613
|
if (!this._diskDisabled) this.disk.close();
|
|
5111
7614
|
}
|
|
7615
|
+
/**
|
|
7616
|
+
* Return the active IPC telemetry server instance, if enabled.
|
|
7617
|
+
*/
|
|
7618
|
+
getIpcServer() {
|
|
7619
|
+
return this._ipcServer;
|
|
7620
|
+
}
|
|
7621
|
+
/**
|
|
7622
|
+
* Return real-time telemetry and metrics for the Window TinyLFU admission policy.
|
|
7623
|
+
* Returns `undefined` if W-TinyLFU admission is not active.
|
|
7624
|
+
*/
|
|
7625
|
+
getWTinyLfuStats() {
|
|
7626
|
+
return this.l1.getWTinyLfuStats();
|
|
7627
|
+
}
|
|
5112
7628
|
};
|
|
5113
7629
|
|
|
5114
7630
|
// src/cli.ts
|
|
7631
|
+
var import_meta2 = {};
|
|
5115
7632
|
async function runCli(args = process.argv.slice(2)) {
|
|
5116
7633
|
const options = {
|
|
5117
7634
|
redis: { type: "string", short: "r" },
|
|
@@ -5119,6 +7636,11 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
5119
7636
|
namespace: { type: "string", short: "n" },
|
|
5120
7637
|
prefix: { type: "string" },
|
|
5121
7638
|
disk: { type: "string", short: "d" },
|
|
7639
|
+
pid: { type: "string" },
|
|
7640
|
+
socket: { type: "string", short: "s" },
|
|
7641
|
+
interval: { type: "string", short: "i" },
|
|
7642
|
+
once: { type: "boolean" },
|
|
7643
|
+
json: { type: "boolean" },
|
|
5122
7644
|
help: { type: "boolean", short: "h" },
|
|
5123
7645
|
version: { type: "boolean", short: "v" }
|
|
5124
7646
|
};
|
|
@@ -5143,7 +7665,106 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
5143
7665
|
return;
|
|
5144
7666
|
}
|
|
5145
7667
|
if (values.version || command === "version") {
|
|
5146
|
-
|
|
7668
|
+
let version = "0.9.0";
|
|
7669
|
+
try {
|
|
7670
|
+
const pkg = JSON.parse((0, import_node_fs3.readFileSync)(new URL("../package.json", import_meta2.url), "utf8"));
|
|
7671
|
+
if (pkg?.version) version = pkg.version;
|
|
7672
|
+
} catch {
|
|
7673
|
+
}
|
|
7674
|
+
console.log(`tricache v${version}`);
|
|
7675
|
+
return;
|
|
7676
|
+
}
|
|
7677
|
+
if (command === "top") {
|
|
7678
|
+
let targetSocket = typeof values.socket === "string" ? values.socket : void 0;
|
|
7679
|
+
if (!targetSocket && typeof values.pid === "string") {
|
|
7680
|
+
targetSocket = resolveIpcSocketPath(values.pid);
|
|
7681
|
+
}
|
|
7682
|
+
if (!targetSocket) {
|
|
7683
|
+
const active = await findActiveSockets();
|
|
7684
|
+
if (active.length > 0) {
|
|
7685
|
+
targetSocket = active[0];
|
|
7686
|
+
}
|
|
7687
|
+
}
|
|
7688
|
+
if (!targetSocket) {
|
|
7689
|
+
console.error("No active TriCache instances found to monitor.\n");
|
|
7690
|
+
console.error("To use `tricache top`:");
|
|
7691
|
+
console.error(" 1. Ensure your running application enables IPC telemetry:");
|
|
7692
|
+
console.error(" const cache = new CacheService({ namespace: 'my-app', enableIpc: true, ... });\n");
|
|
7693
|
+
console.error(" 2. If the application is already running, specify its PID or socket:");
|
|
7694
|
+
console.error(" npx tricache top --pid <pid>");
|
|
7695
|
+
console.error(" npx tricache top --socket <path>\n");
|
|
7696
|
+
process.exit(1);
|
|
7697
|
+
}
|
|
7698
|
+
const client = new IpcTelemetryClient(targetSocket);
|
|
7699
|
+
const intervalMs = typeof values.interval === "string" ? Math.max(200, parseInt(values.interval, 10)) : 1e3;
|
|
7700
|
+
const isOnce = Boolean(values.once || !process.stdout.isTTY);
|
|
7701
|
+
const asJson = Boolean(values.json);
|
|
7702
|
+
if (isOnce) {
|
|
7703
|
+
try {
|
|
7704
|
+
const payload = await client.getMetrics();
|
|
7705
|
+
if (asJson) {
|
|
7706
|
+
console.log(JSON.stringify(payload, null, 2));
|
|
7707
|
+
} else {
|
|
7708
|
+
console.log(renderTopDashboard(payload));
|
|
7709
|
+
}
|
|
7710
|
+
return;
|
|
7711
|
+
} catch (err) {
|
|
7712
|
+
console.error(`Failed to connect to TriCache IPC at ${targetSocket}: ${err.message}`);
|
|
7713
|
+
process.exit(1);
|
|
7714
|
+
}
|
|
7715
|
+
}
|
|
7716
|
+
process.stdout.write("\x1B[?1049h\x1B[?25l");
|
|
7717
|
+
let activeInterval = null;
|
|
7718
|
+
let cleaningUp = false;
|
|
7719
|
+
const cleanup = () => {
|
|
7720
|
+
if (cleaningUp) return;
|
|
7721
|
+
cleaningUp = true;
|
|
7722
|
+
if (activeInterval) clearInterval(activeInterval);
|
|
7723
|
+
if (process.stdout.isTTY) {
|
|
7724
|
+
process.stdout.write("\x1B[?25h\x1B[?1049l");
|
|
7725
|
+
}
|
|
7726
|
+
if (process.stdin.isTTY && typeof process.stdin.setRawMode === "function") {
|
|
7727
|
+
try {
|
|
7728
|
+
process.stdin.setRawMode(false);
|
|
7729
|
+
process.stdin.pause();
|
|
7730
|
+
} catch {
|
|
7731
|
+
}
|
|
7732
|
+
}
|
|
7733
|
+
process.exit(0);
|
|
7734
|
+
};
|
|
7735
|
+
process.once("SIGINT", cleanup);
|
|
7736
|
+
process.once("SIGTERM", cleanup);
|
|
7737
|
+
if (process.stdin.isTTY && typeof process.stdin.setRawMode === "function") {
|
|
7738
|
+
try {
|
|
7739
|
+
process.stdin.setRawMode(true);
|
|
7740
|
+
process.stdin.resume();
|
|
7741
|
+
process.stdin.setEncoding("utf8");
|
|
7742
|
+
process.stdin.on("data", (key) => {
|
|
7743
|
+
if (key === "q" || key === "Q" || key === "") {
|
|
7744
|
+
cleanup();
|
|
7745
|
+
}
|
|
7746
|
+
});
|
|
7747
|
+
} catch {
|
|
7748
|
+
}
|
|
7749
|
+
}
|
|
7750
|
+
const tick = async () => {
|
|
7751
|
+
try {
|
|
7752
|
+
const payload = await client.getMetrics();
|
|
7753
|
+
const screen = renderTopDashboard(payload);
|
|
7754
|
+
process.stdout.write("\x1B[H" + screen + '\n Press "q" or Ctrl+C to exit\n');
|
|
7755
|
+
} catch (err) {
|
|
7756
|
+
process.stdout.write(`\x1B[HConnecting to ${targetSocket}...
|
|
7757
|
+
Error: ${err.message}
|
|
7758
|
+
|
|
7759
|
+
Waiting for TriCache IPC server. Ensure the target process is running with enableIpc: true.
|
|
7760
|
+
Press "q" or Ctrl+C to exit
|
|
7761
|
+
`);
|
|
7762
|
+
}
|
|
7763
|
+
};
|
|
7764
|
+
await tick();
|
|
7765
|
+
activeInterval = setInterval(tick, intervalMs);
|
|
7766
|
+
await new Promise(() => {
|
|
7767
|
+
});
|
|
5147
7768
|
return;
|
|
5148
7769
|
}
|
|
5149
7770
|
const redisStr = typeof values.redis === "string" ? values.redis : void 0;
|
|
@@ -5218,15 +7839,21 @@ Usage:
|
|
|
5218
7839
|
tricache <command> [options]
|
|
5219
7840
|
|
|
5220
7841
|
Commands:
|
|
7842
|
+
top Live ASCII terminal dashboard monitoring an active TriCache process
|
|
5221
7843
|
inspect Display full dashboard including hit ratios, latencies, and hot keys (default)
|
|
5222
7844
|
ping Measure response latency across L1 (RAM), L1.5 (Disk), and L2 (Redis)
|
|
5223
7845
|
clear Flush all entries or keys matching a prefix
|
|
5224
7846
|
|
|
5225
7847
|
Options:
|
|
7848
|
+
-s, --socket <path> IPC socket path or Windows named pipe
|
|
7849
|
+
--pid <pid> Process ID of the target TriCache process to monitor
|
|
7850
|
+
-i, --interval <ms> Refresh interval in milliseconds for top (default: 1000)
|
|
7851
|
+
--once Output single snapshot and exit (non-interactive)
|
|
7852
|
+
--json Format output as raw JSON
|
|
5226
7853
|
-r, --redis <host|url> Redis connection host or URL (e.g. localhost, redis://127.0.0.1:6379)
|
|
5227
7854
|
-p, --port <port> Redis port (default: 6379)
|
|
5228
7855
|
-n, --namespace <ns> Cache namespace
|
|
5229
|
-
|
|
7856
|
+
--prefix <prefix> Key prefix filter for clear command
|
|
5230
7857
|
-d, --disk <path> Custom disk cache directory path
|
|
5231
7858
|
-h, --help Show this help message
|
|
5232
7859
|
-v, --version Display version number
|