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