tricache 0.7.1 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +89 -1371
- package/dashboards/prometheus-scrape.yml +18 -0
- package/dashboards/tricache-alerts.yaml +54 -0
- package/dashboards/tricache-grafana.json +548 -0
- package/dist/cache-service-DVvroyqA.d.ts +886 -0
- package/dist/cache-service-KI5ACF3F.js +12 -0
- package/dist/chunk-7RV5ZVBB.js +1023 -0
- package/dist/chunk-BQRURGGD.js +60 -0
- package/dist/chunk-IITRFWHY.js +196 -0
- package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
- package/dist/{chunk-EUGYR7KR.js → chunk-PL5J3ZNT.js} +3184 -514
- package/dist/chunk-QNU7B43J.js +687 -0
- package/dist/chunk-UGD4VEPD.js +138 -0
- package/dist/chunk-XZL45ABR.js +108 -0
- package/dist/cli.cjs +3122 -495
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +121 -5
- package/dist/dashboard/index.cjs +1065 -0
- package/dist/dashboard/index.d.ts +183 -0
- package/dist/dashboard/index.js +22 -0
- package/dist/drizzle/index.cjs +2846 -494
- package/dist/drizzle/index.d.ts +3 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +1559 -0
- package/dist/edge/index.d.ts +127 -0
- package/dist/edge/index.js +1109 -0
- package/dist/hono/index.cjs +7760 -0
- package/dist/hono/index.d.ts +91 -0
- package/dist/hono/index.js +185 -0
- package/dist/hono-VA9A1m0I.d.ts +371 -0
- package/dist/http/index.cjs +3281 -587
- package/dist/http/index.d.ts +85 -23
- package/dist/http/index.js +176 -78
- package/dist/index.cjs +7212 -2505
- package/dist/index.d.ts +547 -30
- package/dist/index.js +104 -5
- package/dist/murmur3-CMGw9PbV.d.ts +98 -0
- package/dist/nestjs/index.cjs +2787 -487
- package/dist/nestjs/index.d.ts +3 -1
- package/dist/nestjs/index.js +6 -3
- package/dist/next/index.cjs +2804 -501
- package/dist/next/index.d.ts +4 -2
- package/dist/next/index.js +14 -10
- package/dist/prisma/index.d.ts +3 -1
- package/dist/serialize-worker.cjs +5 -4
- package/dist/serialize-worker.js +1 -1
- package/dist/{cache-service-D8tIXmzb.d.ts → types-B_QkVwJ7.d.ts} +622 -662
- package/dist/utils-CEsU_Z0s.d.ts +27 -0
- package/package.json +48 -10
- package/src/adapters/auto-pipeliner.ts +206 -0
- package/src/adapters/node-redis.ts +370 -0
- package/src/cache-service.ts +1619 -415
- package/src/cli.ts +137 -2
- package/src/codec.ts +72 -0
- package/src/cross-region.ts +245 -0
- package/src/dashboard/handler.ts +392 -0
- package/src/dashboard/html.ts +594 -0
- package/src/dashboard/index.ts +195 -0
- package/src/dashboard/types.ts +96 -0
- package/src/disk-tier.ts +449 -47
- package/src/drizzle/index.ts +86 -86
- package/src/edge/adapters/cloudflare-do.ts +130 -0
- package/src/edge/adapters/cloudflare-kv.ts +115 -0
- package/src/edge/adapters/upstash.ts +143 -0
- package/src/edge/cache.ts +797 -0
- package/src/edge/crypto.ts +182 -0
- package/src/edge/hono.ts +284 -0
- package/src/edge/index.ts +37 -0
- package/src/edge/types.ts +230 -0
- package/src/edge/utils/base64.ts +63 -0
- package/src/edge/utils/murmur3.ts +179 -0
- package/src/encryption.ts +127 -5
- package/src/hono/index.ts +316 -0
- package/src/http/express.ts +195 -0
- package/src/http/fastify.ts +260 -0
- package/src/http/index.ts +44 -258
- package/src/http/utils.ts +92 -0
- package/src/index.ts +149 -47
- package/src/ipc-telemetry.ts +509 -0
- package/src/latency-watchdog.ts +282 -0
- package/src/nestjs/decorators.ts +161 -161
- package/src/nestjs/index.ts +23 -23
- package/src/nestjs/tricache.module.ts +104 -104
- package/src/nestjs/tricache.store.ts +97 -97
- package/src/nestjs/types.ts +79 -79
- package/src/next/cache-handler.ts +12 -9
- package/src/next/index.ts +37 -37
- package/src/next/isr-handler.ts +105 -105
- package/src/next/types.ts +130 -130
- package/src/remote-snapshot.ts +153 -0
- package/src/serialize-worker.ts +120 -120
- package/src/sigv4-snapshot-adapter.ts +260 -0
- package/src/smart-memory-cache.ts +91 -8
- package/src/types.ts +315 -2
- package/src/utils/cgroup.ts +100 -0
- package/src/utils/tracing.ts +54 -0
- package/src/wasm/bloom-filter-wasm.ts +109 -102
- package/src/worker-pool.ts +299 -299
- package/src/wtiny-lfu.ts +624 -0
- package/dist/cache-service-5GATUYAK.js +0 -7
- package/dist/chunk-UBSR5UYA.js +0 -0
package/dist/nestjs/index.cjs
CHANGED
|
@@ -42,9 +42,43 @@ module.exports = __toCommonJS(nestjs_exports);
|
|
|
42
42
|
|
|
43
43
|
// src/cache-service.ts
|
|
44
44
|
var import_ioredis = require("ioredis");
|
|
45
|
-
|
|
45
|
+
|
|
46
|
+
// src/codec.ts
|
|
47
|
+
var import_msgpackr = require("msgpackr");
|
|
48
|
+
var CacheCodec = class {
|
|
49
|
+
packr;
|
|
50
|
+
constructor(options) {
|
|
51
|
+
const packrOptions = {
|
|
52
|
+
useToJSON: options?.useToJSON ?? true,
|
|
53
|
+
useRecords: options?.useRecords ?? true,
|
|
54
|
+
moreTypes: options?.moreTypes ?? true,
|
|
55
|
+
mapsAsObjects: options?.mapsAsObjects ?? true
|
|
56
|
+
};
|
|
57
|
+
this.packr = new import_msgpackr.Packr(packrOptions);
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Serializes a JavaScript value to a binary MessagePack Buffer.
|
|
61
|
+
*/
|
|
62
|
+
encode(data) {
|
|
63
|
+
const packed = this.packr.pack(data);
|
|
64
|
+
return Buffer.isBuffer(packed) ? packed : Buffer.from(packed.buffer, packed.byteOffset, packed.byteLength);
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Deserializes a binary MessagePack Buffer or Uint8Array back to a JavaScript value.
|
|
68
|
+
*/
|
|
69
|
+
decode(data) {
|
|
70
|
+
return this.packr.unpack(data);
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
var defaultCodec = new CacheCodec({
|
|
74
|
+
useToJSON: true,
|
|
75
|
+
useRecords: true,
|
|
76
|
+
moreTypes: true
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
// src/cache-service.ts
|
|
46
80
|
var import_crypto3 = __toESM(require("crypto"), 1);
|
|
47
|
-
var
|
|
81
|
+
var import_os3 = __toESM(require("os"), 1);
|
|
48
82
|
|
|
49
83
|
// src/worker-pool.ts
|
|
50
84
|
var import_worker_threads = require("worker_threads");
|
|
@@ -249,7 +283,7 @@ function availableCpus() {
|
|
|
249
283
|
}
|
|
250
284
|
|
|
251
285
|
// src/cache-service.ts
|
|
252
|
-
var
|
|
286
|
+
var import_node_v82 = __toESM(require("v8"), 1);
|
|
253
287
|
var import_fs3 = __toESM(require("fs"), 1);
|
|
254
288
|
var import_path3 = __toESM(require("path"), 1);
|
|
255
289
|
|
|
@@ -380,17 +414,17 @@ var CacheEncryption = class {
|
|
|
380
414
|
throw new Error("XOR key must be at least 1 byte");
|
|
381
415
|
}
|
|
382
416
|
this._key = buf;
|
|
383
|
-
if (
|
|
417
|
+
if (resolvedMode !== "xor") {
|
|
384
418
|
this._keyObj = (0, import_crypto.createSecretKey)(buf);
|
|
385
419
|
const _wc = (0, import_crypto.createCipheriv)(
|
|
386
|
-
|
|
420
|
+
resolvedMode,
|
|
387
421
|
this._keyObj,
|
|
388
|
-
Buffer.alloc(
|
|
422
|
+
Buffer.alloc(resolvedMode === "aes-128-ctr" ? CTR_IV_BYTES : IV_BYTES)
|
|
389
423
|
);
|
|
390
424
|
_wc.update(Buffer.alloc(0));
|
|
391
425
|
_wc.final();
|
|
392
426
|
}
|
|
393
|
-
if (
|
|
427
|
+
if (resolvedMode === "xor") {
|
|
394
428
|
logger.warn(
|
|
395
429
|
"Cache obfuscation enabled (XOR). WARNING: XOR is NOT cryptographic \u2014 use only for dev or non-sensitive data."
|
|
396
430
|
);
|
|
@@ -658,15 +692,257 @@ var CacheEncryption = class {
|
|
|
658
692
|
return plain;
|
|
659
693
|
}
|
|
660
694
|
};
|
|
695
|
+
var MAGIC_ENVELOPE = Buffer.from([84, 82, 73, 67, 69, 78, 86, 49]);
|
|
696
|
+
var EnvelopeEncryption = class {
|
|
697
|
+
static isEnvelope(data) {
|
|
698
|
+
return data.length >= MAGIC_LEN && data.subarray(0, MAGIC_LEN).equals(MAGIC_ENVELOPE);
|
|
699
|
+
}
|
|
700
|
+
static async encrypt(data, options) {
|
|
701
|
+
const dek = (0, import_crypto.randomBytes)(32);
|
|
702
|
+
let encryptedKey;
|
|
703
|
+
if (options.kmsEncrypt) {
|
|
704
|
+
encryptedKey = await options.kmsEncrypt(dek);
|
|
705
|
+
} else if (options.publicKey) {
|
|
706
|
+
encryptedKey = (0, import_crypto.publicEncrypt)(
|
|
707
|
+
{
|
|
708
|
+
key: options.publicKey,
|
|
709
|
+
padding: import_crypto.constants.RSA_PKCS1_OAEP_PADDING,
|
|
710
|
+
oaepHash: "sha256"
|
|
711
|
+
},
|
|
712
|
+
dek
|
|
713
|
+
);
|
|
714
|
+
} else {
|
|
715
|
+
throw new Error("EnvelopeEncryption: either publicKey or kmsEncrypt must be provided to encrypt");
|
|
716
|
+
}
|
|
717
|
+
const iv = (0, import_crypto.randomBytes)(IV_BYTES);
|
|
718
|
+
const cipher = (0, import_crypto.createCipheriv)("aes-256-gcm", dek, iv);
|
|
719
|
+
const ct = cipher.update(data);
|
|
720
|
+
cipher.final();
|
|
721
|
+
const tag = cipher.getAuthTag();
|
|
722
|
+
const keyLen = encryptedKey.length;
|
|
723
|
+
const out = Buffer.allocUnsafe(MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES + ct.length);
|
|
724
|
+
MAGIC_ENVELOPE.copy(out, 0);
|
|
725
|
+
out.writeUInt32BE(keyLen, MAGIC_LEN);
|
|
726
|
+
encryptedKey.copy(out, MAGIC_LEN + 4);
|
|
727
|
+
iv.copy(out, MAGIC_LEN + 4 + keyLen);
|
|
728
|
+
tag.copy(out, MAGIC_LEN + 4 + keyLen + IV_BYTES);
|
|
729
|
+
ct.copy(out, MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES);
|
|
730
|
+
return out;
|
|
731
|
+
}
|
|
732
|
+
static async decrypt(data, options) {
|
|
733
|
+
if (!this.isEnvelope(data)) {
|
|
734
|
+
throw new Error("EnvelopeEncryption: invalid header, expected TRICENV1");
|
|
735
|
+
}
|
|
736
|
+
if (data.length < MAGIC_LEN + 4 + IV_BYTES + TAG_BYTES) {
|
|
737
|
+
throw new Error("EnvelopeEncryption: truncated envelope buffer");
|
|
738
|
+
}
|
|
739
|
+
const keyLen = data.readUInt32BE(MAGIC_LEN);
|
|
740
|
+
const minExpected = MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES;
|
|
741
|
+
if (data.length < minExpected) {
|
|
742
|
+
throw new Error("EnvelopeEncryption: truncated envelope buffer (key length mismatch)");
|
|
743
|
+
}
|
|
744
|
+
const encryptedKey = data.subarray(MAGIC_LEN + 4, MAGIC_LEN + 4 + keyLen);
|
|
745
|
+
const iv = data.subarray(MAGIC_LEN + 4 + keyLen, MAGIC_LEN + 4 + keyLen + IV_BYTES);
|
|
746
|
+
const tag = data.subarray(MAGIC_LEN + 4 + keyLen + IV_BYTES, MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES);
|
|
747
|
+
const ct = data.subarray(MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES);
|
|
748
|
+
let dek;
|
|
749
|
+
if (options.kmsDecrypt) {
|
|
750
|
+
dek = await options.kmsDecrypt(encryptedKey);
|
|
751
|
+
} else if (options.privateKey) {
|
|
752
|
+
dek = (0, import_crypto.privateDecrypt)(
|
|
753
|
+
{
|
|
754
|
+
key: options.privateKey,
|
|
755
|
+
padding: import_crypto.constants.RSA_PKCS1_OAEP_PADDING,
|
|
756
|
+
oaepHash: "sha256"
|
|
757
|
+
},
|
|
758
|
+
encryptedKey
|
|
759
|
+
);
|
|
760
|
+
} else {
|
|
761
|
+
throw new Error("EnvelopeEncryption: either privateKey or kmsDecrypt must be provided to decrypt");
|
|
762
|
+
}
|
|
763
|
+
const decipher = (0, import_crypto.createDecipheriv)("aes-256-gcm", dek, iv);
|
|
764
|
+
decipher.setAuthTag(tag);
|
|
765
|
+
const pt = decipher.update(ct);
|
|
766
|
+
decipher.final();
|
|
767
|
+
return pt;
|
|
768
|
+
}
|
|
769
|
+
};
|
|
661
770
|
|
|
662
|
-
// src/
|
|
663
|
-
var
|
|
771
|
+
// src/wtiny-lfu.ts
|
|
772
|
+
var WTinyLfuPolicy = class {
|
|
773
|
+
constructor(capacity, sketch, windowPercent = 0.01, protectedPercent = 0.8) {
|
|
774
|
+
this.sketch = sketch;
|
|
775
|
+
this.maxTotal = Math.max(2, capacity);
|
|
776
|
+
this.maxWindow = Math.max(1, Math.floor(this.maxTotal * windowPercent));
|
|
777
|
+
const mainCapacity = Math.max(1, this.maxTotal - this.maxWindow);
|
|
778
|
+
this.maxProtected = Math.max(1, Math.floor(mainCapacity * protectedPercent));
|
|
779
|
+
this.maxProbation = Math.max(1, mainCapacity - this.maxProtected);
|
|
780
|
+
}
|
|
781
|
+
sketch;
|
|
782
|
+
maxTotal;
|
|
783
|
+
maxWindow;
|
|
784
|
+
maxProtected;
|
|
785
|
+
maxProbation;
|
|
786
|
+
window = /* @__PURE__ */ new Set();
|
|
787
|
+
probation = /* @__PURE__ */ new Set();
|
|
788
|
+
protected_ = /* @__PURE__ */ new Set();
|
|
789
|
+
// Telemetry metrics
|
|
790
|
+
hitCount = 0;
|
|
791
|
+
missCount = 0;
|
|
792
|
+
admissionCount = 0;
|
|
793
|
+
rejectionCount = 0;
|
|
794
|
+
promotionCount = 0;
|
|
795
|
+
demotionCount = 0;
|
|
796
|
+
get windowSize() {
|
|
797
|
+
return this.window.size;
|
|
798
|
+
}
|
|
799
|
+
get probationSize() {
|
|
800
|
+
return this.probation.size;
|
|
801
|
+
}
|
|
802
|
+
get protectedSize() {
|
|
803
|
+
return this.protected_.size;
|
|
804
|
+
}
|
|
805
|
+
onAccess(key) {
|
|
806
|
+
if (this.window.has(key)) {
|
|
807
|
+
this.window.delete(key);
|
|
808
|
+
this.window.add(key);
|
|
809
|
+
this.hitCount++;
|
|
810
|
+
return;
|
|
811
|
+
}
|
|
812
|
+
if (this.protected_.has(key)) {
|
|
813
|
+
this.protected_.delete(key);
|
|
814
|
+
this.protected_.add(key);
|
|
815
|
+
this.hitCount++;
|
|
816
|
+
return;
|
|
817
|
+
}
|
|
818
|
+
if (this.probation.has(key)) {
|
|
819
|
+
this.probation.delete(key);
|
|
820
|
+
this.protected_.add(key);
|
|
821
|
+
this.promotionCount++;
|
|
822
|
+
this.hitCount++;
|
|
823
|
+
if (this.protected_.size > this.maxProtected) {
|
|
824
|
+
const oldestProtKey = this.protected_.values().next().value;
|
|
825
|
+
this.protected_.delete(oldestProtKey);
|
|
826
|
+
this.probation.add(oldestProtKey);
|
|
827
|
+
this.demotionCount++;
|
|
828
|
+
}
|
|
829
|
+
return;
|
|
830
|
+
}
|
|
831
|
+
this.missCount++;
|
|
832
|
+
}
|
|
833
|
+
onSet(key, isUpdate) {
|
|
834
|
+
if (isUpdate) {
|
|
835
|
+
if (this.window.has(key)) {
|
|
836
|
+
this.window.delete(key);
|
|
837
|
+
this.window.add(key);
|
|
838
|
+
} else if (this.protected_.has(key)) {
|
|
839
|
+
this.protected_.delete(key);
|
|
840
|
+
this.protected_.add(key);
|
|
841
|
+
} else if (this.probation.has(key)) {
|
|
842
|
+
this.probation.delete(key);
|
|
843
|
+
this.probation.add(key);
|
|
844
|
+
}
|
|
845
|
+
return { admit: true };
|
|
846
|
+
}
|
|
847
|
+
this.window.add(key);
|
|
848
|
+
if (this.window.size <= this.maxWindow) {
|
|
849
|
+
this.admissionCount++;
|
|
850
|
+
return { admit: true };
|
|
851
|
+
}
|
|
852
|
+
const candKey = this.window.values().next().value;
|
|
853
|
+
this.window.delete(candKey);
|
|
854
|
+
if (this.probation.size + this.protected_.size < this.maxProbation + this.maxProtected) {
|
|
855
|
+
this.probation.add(candKey);
|
|
856
|
+
this.admissionCount++;
|
|
857
|
+
return { admit: true };
|
|
858
|
+
}
|
|
859
|
+
let victimKey;
|
|
860
|
+
let victimIsProbation = true;
|
|
861
|
+
if (this.probation.size > 0) {
|
|
862
|
+
victimKey = this.probation.values().next().value;
|
|
863
|
+
} else {
|
|
864
|
+
victimKey = this.protected_.values().next().value;
|
|
865
|
+
victimIsProbation = false;
|
|
866
|
+
}
|
|
867
|
+
const candFreq = this.sketch.estimate(candKey);
|
|
868
|
+
const victimFreq = this.sketch.estimate(victimKey);
|
|
869
|
+
if (candFreq > victimFreq) {
|
|
870
|
+
if (victimIsProbation) {
|
|
871
|
+
this.probation.delete(victimKey);
|
|
872
|
+
} else {
|
|
873
|
+
this.protected_.delete(victimKey);
|
|
874
|
+
}
|
|
875
|
+
this.probation.add(candKey);
|
|
876
|
+
this.admissionCount++;
|
|
877
|
+
return { admit: true, evictKey: victimKey, candidateKey: candKey };
|
|
878
|
+
} else {
|
|
879
|
+
this.rejectionCount++;
|
|
880
|
+
return { admit: false, candidateKey: candKey };
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
onDelete(key) {
|
|
884
|
+
this.window.delete(key);
|
|
885
|
+
this.probation.delete(key);
|
|
886
|
+
this.protected_.delete(key);
|
|
887
|
+
}
|
|
888
|
+
clear() {
|
|
889
|
+
this.window.clear();
|
|
890
|
+
this.probation.clear();
|
|
891
|
+
this.protected_.clear();
|
|
892
|
+
this.hitCount = 0;
|
|
893
|
+
this.missCount = 0;
|
|
894
|
+
this.admissionCount = 0;
|
|
895
|
+
this.rejectionCount = 0;
|
|
896
|
+
this.promotionCount = 0;
|
|
897
|
+
this.demotionCount = 0;
|
|
898
|
+
}
|
|
899
|
+
getStats() {
|
|
900
|
+
const totalRequests = this.hitCount + this.missCount;
|
|
901
|
+
return {
|
|
902
|
+
capacity: this.maxTotal,
|
|
903
|
+
size: this.window.size + this.probation.size + this.protected_.size,
|
|
904
|
+
windowSize: this.window.size,
|
|
905
|
+
probationSize: this.probation.size,
|
|
906
|
+
protectedSize: this.protected_.size,
|
|
907
|
+
hits: this.hitCount,
|
|
908
|
+
misses: this.missCount,
|
|
909
|
+
hitRate: totalRequests > 0 ? this.hitCount / totalRequests : 0,
|
|
910
|
+
admissions: this.admissionCount,
|
|
911
|
+
rejections: this.rejectionCount,
|
|
912
|
+
promotions: this.promotionCount,
|
|
913
|
+
demotions: this.demotionCount
|
|
914
|
+
};
|
|
915
|
+
}
|
|
916
|
+
getSegment(key) {
|
|
917
|
+
if (this.window.has(key)) return "window";
|
|
918
|
+
if (this.probation.has(key)) return "probation";
|
|
919
|
+
if (this.protected_.has(key)) return "protected";
|
|
920
|
+
return null;
|
|
921
|
+
}
|
|
922
|
+
};
|
|
923
|
+
|
|
924
|
+
// src/edge/utils/base64.ts
|
|
925
|
+
function base64ToUint8Array(base64) {
|
|
926
|
+
const modernU8 = Uint8Array;
|
|
927
|
+
if (typeof modernU8.fromBase64 === "function") {
|
|
928
|
+
return modernU8.fromBase64(base64);
|
|
929
|
+
}
|
|
930
|
+
const binary = globalThis.atob(base64);
|
|
931
|
+
const len = binary.length;
|
|
932
|
+
const bytes = new Uint8Array(len);
|
|
933
|
+
for (let i = 0; i < len; i++) {
|
|
934
|
+
bytes[i] = binary.charCodeAt(i);
|
|
935
|
+
}
|
|
936
|
+
return bytes;
|
|
937
|
+
}
|
|
664
938
|
|
|
665
939
|
// src/wasm/bloom-filter-wasm.ts
|
|
666
940
|
var BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
|
|
667
941
|
var KEY_STAGING_OFFSET = 2e4;
|
|
668
942
|
var MAX_KEY_BYTES = 512;
|
|
669
|
-
var BLOOM_WASM_MODULE = new WebAssembly.Module(
|
|
943
|
+
var BLOOM_WASM_MODULE = new WebAssembly.Module(
|
|
944
|
+
base64ToUint8Array(BLOOM_WASM_BASE64)
|
|
945
|
+
);
|
|
670
946
|
var WasmBloomFilter = class {
|
|
671
947
|
exports;
|
|
672
948
|
mem;
|
|
@@ -901,11 +1177,13 @@ function globMatchParts(parts, first, last, key) {
|
|
|
901
1177
|
var SmartMemoryCache = class {
|
|
902
1178
|
cache = /* @__PURE__ */ new Map();
|
|
903
1179
|
opts;
|
|
1180
|
+
codec;
|
|
904
1181
|
bloom;
|
|
905
1182
|
/** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
|
|
906
1183
|
categoryPrefixes;
|
|
907
1184
|
/** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
|
|
908
1185
|
sketch = new CountMinSketch();
|
|
1186
|
+
wtinyPolicy;
|
|
909
1187
|
totalSize = 0;
|
|
910
1188
|
categoryCount = /* @__PURE__ */ new Map();
|
|
911
1189
|
categorySize = /* @__PURE__ */ new Map();
|
|
@@ -929,8 +1207,12 @@ var SmartMemoryCache = class {
|
|
|
929
1207
|
_evictGPool = Array.from({ length: EVICTION_SAMPLE }, () => ({ key: "", score: 0 }));
|
|
930
1208
|
constructor(opts, existing) {
|
|
931
1209
|
this.opts = opts;
|
|
1210
|
+
this.codec = opts.codec ?? defaultCodec;
|
|
932
1211
|
this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
|
|
933
1212
|
this.categoryPrefixes = Object.keys(opts.categories).filter((k) => k !== "default");
|
|
1213
|
+
if (opts.admissionPolicy === "wtinylfu") {
|
|
1214
|
+
this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch);
|
|
1215
|
+
}
|
|
934
1216
|
if (existing) {
|
|
935
1217
|
for (const [k, v] of existing) this.cache.set(k, v);
|
|
936
1218
|
this.recalculateStats();
|
|
@@ -943,6 +1225,12 @@ var SmartMemoryCache = class {
|
|
|
943
1225
|
this.categoryCount.clear();
|
|
944
1226
|
this.categorySize.clear();
|
|
945
1227
|
this.categoryKeys.clear();
|
|
1228
|
+
if (this.wtinyPolicy) {
|
|
1229
|
+
this.wtinyPolicy.clear();
|
|
1230
|
+
for (const key of this.cache.keys()) {
|
|
1231
|
+
this.wtinyPolicy.onSet(key, false);
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
946
1234
|
for (const [key, entry] of this.cache) {
|
|
947
1235
|
this.totalSize += entry.size;
|
|
948
1236
|
const cat = this.getCategory(key);
|
|
@@ -968,6 +1256,7 @@ var SmartMemoryCache = class {
|
|
|
968
1256
|
_delete(key, reason = "manual") {
|
|
969
1257
|
const entry = this.cache.get(key);
|
|
970
1258
|
if (!entry) return false;
|
|
1259
|
+
this.wtinyPolicy?.onDelete(key);
|
|
971
1260
|
const cat = this.getCategory(key);
|
|
972
1261
|
this.totalSize -= entry.size;
|
|
973
1262
|
this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
|
|
@@ -1128,7 +1417,8 @@ var SmartMemoryCache = class {
|
|
|
1128
1417
|
entry.hits++;
|
|
1129
1418
|
entry.lastAccess = now;
|
|
1130
1419
|
if ((entry.hits & 3) === 0) this.sketch.increment(key);
|
|
1131
|
-
|
|
1420
|
+
this.wtinyPolicy?.onAccess(key);
|
|
1421
|
+
const value = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
1132
1422
|
const hit = {
|
|
1133
1423
|
value,
|
|
1134
1424
|
isStale: entry.staleAt !== void 0 && now > entry.staleAt,
|
|
@@ -1142,7 +1432,7 @@ var SmartMemoryCache = class {
|
|
|
1142
1432
|
return hit;
|
|
1143
1433
|
}
|
|
1144
1434
|
set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
|
|
1145
|
-
const packed =
|
|
1435
|
+
const packed = this.codec.encode(data);
|
|
1146
1436
|
const size = packed.byteLength;
|
|
1147
1437
|
this.compressions++;
|
|
1148
1438
|
this.sketch.increment(key);
|
|
@@ -1159,7 +1449,51 @@ var SmartMemoryCache = class {
|
|
|
1159
1449
|
this.categorySize.set(cat, (this.categorySize.get(cat) ?? existingEntry.size) - existingEntry.size);
|
|
1160
1450
|
this.cache.delete(key);
|
|
1161
1451
|
}
|
|
1162
|
-
this.
|
|
1452
|
+
if (this.wtinyPolicy) {
|
|
1453
|
+
const decision = this.wtinyPolicy.onSet(key, Boolean(existingEntry));
|
|
1454
|
+
if (!decision.admit) {
|
|
1455
|
+
if (decision.candidateKey === key) {
|
|
1456
|
+
if (this.opts.diskSpill) {
|
|
1457
|
+
const now2 = Date.now();
|
|
1458
|
+
const liveValue2 = size <= LARGE_VALUE_BYTES ? data : void 0;
|
|
1459
|
+
this.opts.diskSpill(key, {
|
|
1460
|
+
data: packed,
|
|
1461
|
+
value: liveValue2,
|
|
1462
|
+
isCompressed: true,
|
|
1463
|
+
expiresAt: now2 + ttlMs,
|
|
1464
|
+
staleAt,
|
|
1465
|
+
size,
|
|
1466
|
+
hits: 1,
|
|
1467
|
+
lastAccess: now2,
|
|
1468
|
+
priority,
|
|
1469
|
+
ttlMs,
|
|
1470
|
+
delta,
|
|
1471
|
+
setAt: now2,
|
|
1472
|
+
tagVersions
|
|
1473
|
+
});
|
|
1474
|
+
}
|
|
1475
|
+
return;
|
|
1476
|
+
} else if (decision.candidateKey) {
|
|
1477
|
+
const candEntry = this.cache.get(decision.candidateKey);
|
|
1478
|
+
if (candEntry && this.opts.diskSpill) {
|
|
1479
|
+
this.opts.diskSpill(decision.candidateKey, candEntry);
|
|
1480
|
+
}
|
|
1481
|
+
this._delete(decision.candidateKey, "capacity");
|
|
1482
|
+
}
|
|
1483
|
+
} else if (decision.evictKey) {
|
|
1484
|
+
const victimEntry = this.cache.get(decision.evictKey);
|
|
1485
|
+
if (victimEntry && this.opts.diskSpill) {
|
|
1486
|
+
this.opts.diskSpill(decision.evictKey, victimEntry);
|
|
1487
|
+
}
|
|
1488
|
+
this._delete(decision.evictKey, "capacity");
|
|
1489
|
+
}
|
|
1490
|
+
const catSz = this.categorySize.get(cat) ?? 0;
|
|
1491
|
+
if (catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
|
|
1492
|
+
this.ensureCapacity(cat, size);
|
|
1493
|
+
}
|
|
1494
|
+
} else {
|
|
1495
|
+
this.ensureCapacity(cat, size);
|
|
1496
|
+
}
|
|
1163
1497
|
const now = Date.now();
|
|
1164
1498
|
const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
|
|
1165
1499
|
this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: now, tagVersions });
|
|
@@ -1219,6 +1553,7 @@ var SmartMemoryCache = class {
|
|
|
1219
1553
|
}
|
|
1220
1554
|
const count = this.cache.size;
|
|
1221
1555
|
this.cache.clear();
|
|
1556
|
+
this.wtinyPolicy?.clear();
|
|
1222
1557
|
this.totalSize = 0;
|
|
1223
1558
|
this.categoryCount.clear();
|
|
1224
1559
|
this.categorySize.clear();
|
|
@@ -1386,8 +1721,8 @@ var SmartMemoryCache = class {
|
|
|
1386
1721
|
if (forbiddenPrefixes.some((p) => key.startsWith(p))) continue;
|
|
1387
1722
|
if (this.cache.has(key)) continue;
|
|
1388
1723
|
const rawData = entry.data;
|
|
1389
|
-
const data = !entry.isCompressed ?
|
|
1390
|
-
const value = entry.size <= LARGE_VALUE_BYTES ?
|
|
1724
|
+
const data = !entry.isCompressed ? this.codec.encode(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
|
|
1725
|
+
const value = entry.size <= LARGE_VALUE_BYTES ? this.codec.decode(data) : void 0;
|
|
1391
1726
|
this.cache.set(key, { ...entry, data, value, isCompressed: true });
|
|
1392
1727
|
this.bloom.add(key);
|
|
1393
1728
|
loaded++;
|
|
@@ -1458,7 +1793,7 @@ var SmartMemoryCache = class {
|
|
|
1458
1793
|
* if the live object was not cached (large-entry optimisation or disk-restored entry).
|
|
1459
1794
|
*/
|
|
1460
1795
|
resolveValue(entry) {
|
|
1461
|
-
return entry.value !== void 0 ? entry.value :
|
|
1796
|
+
return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
1462
1797
|
}
|
|
1463
1798
|
// ── Stats ─────────────────────────────────────────────────────────────────
|
|
1464
1799
|
get size() {
|
|
@@ -1563,13 +1898,20 @@ var SmartMemoryCache = class {
|
|
|
1563
1898
|
out.sort((a, b) => b.hits - a.hits);
|
|
1564
1899
|
return out.slice(0, n);
|
|
1565
1900
|
}
|
|
1901
|
+
/**
|
|
1902
|
+
* Return real-time metrics and telemetry for the Window TinyLFU admission policy.
|
|
1903
|
+
* Returns `undefined` when running under default adaptive eviction.
|
|
1904
|
+
*/
|
|
1905
|
+
getWTinyLfuStats() {
|
|
1906
|
+
return this.wtinyPolicy?.getStats();
|
|
1907
|
+
}
|
|
1566
1908
|
};
|
|
1567
1909
|
|
|
1568
1910
|
// src/disk-tier.ts
|
|
1569
1911
|
var import_fs2 = __toESM(require("fs"), 1);
|
|
1570
1912
|
var import_path2 = __toESM(require("path"), 1);
|
|
1571
1913
|
var import_crypto2 = __toESM(require("crypto"), 1);
|
|
1572
|
-
var
|
|
1914
|
+
var import_os2 = __toESM(require("os"), 1);
|
|
1573
1915
|
|
|
1574
1916
|
// src/compression.ts
|
|
1575
1917
|
var import_zlib = __toESM(require("zlib"), 1);
|
|
@@ -1627,18 +1969,146 @@ function decompressWithHeader(buf, algorithm = "brotli") {
|
|
|
1627
1969
|
}
|
|
1628
1970
|
|
|
1629
1971
|
// src/disk-tier.ts
|
|
1972
|
+
var BoundedDiskQueue = class {
|
|
1973
|
+
constructor(maxConcurrent = Math.min(4, Math.max(1, Math.floor((import_os2.default?.availableParallelism?.() ?? 4) / 4))), maxPending = 512, writeTimeoutMs = 500, failureThreshold = 5, cooldownMs = 5e3) {
|
|
1974
|
+
this.maxConcurrent = maxConcurrent;
|
|
1975
|
+
this.maxPending = maxPending;
|
|
1976
|
+
this.writeTimeoutMs = writeTimeoutMs;
|
|
1977
|
+
this.failureThreshold = failureThreshold;
|
|
1978
|
+
this.cooldownMs = cooldownMs;
|
|
1979
|
+
}
|
|
1980
|
+
maxConcurrent;
|
|
1981
|
+
maxPending;
|
|
1982
|
+
writeTimeoutMs;
|
|
1983
|
+
failureThreshold;
|
|
1984
|
+
cooldownMs;
|
|
1985
|
+
active = 0;
|
|
1986
|
+
queue = [];
|
|
1987
|
+
spillsDropped = 0;
|
|
1988
|
+
consecutiveFailures = 0;
|
|
1989
|
+
circuitState = "closed";
|
|
1990
|
+
lastStateChangeMonotonic = performance.now();
|
|
1991
|
+
async schedule(task) {
|
|
1992
|
+
const now = performance.now();
|
|
1993
|
+
if (this.circuitState === "open") {
|
|
1994
|
+
if (now - this.lastStateChangeMonotonic > this.cooldownMs) {
|
|
1995
|
+
this.circuitState = "half-open";
|
|
1996
|
+
this.lastStateChangeMonotonic = now;
|
|
1997
|
+
} else {
|
|
1998
|
+
this.spillsDropped++;
|
|
1999
|
+
return null;
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
if (this.circuitState === "half-open" && this.active > 0) {
|
|
2003
|
+
this.spillsDropped++;
|
|
2004
|
+
return null;
|
|
2005
|
+
}
|
|
2006
|
+
if (this.queue.length >= this.maxPending) {
|
|
2007
|
+
this.spillsDropped++;
|
|
2008
|
+
return null;
|
|
2009
|
+
}
|
|
2010
|
+
if (this.active >= this.maxConcurrent) {
|
|
2011
|
+
await new Promise((resolve) => this.queue.push(resolve));
|
|
2012
|
+
}
|
|
2013
|
+
this.active++;
|
|
2014
|
+
let timeoutId = null;
|
|
2015
|
+
try {
|
|
2016
|
+
const result = await Promise.race([
|
|
2017
|
+
task(),
|
|
2018
|
+
new Promise((_, reject) => {
|
|
2019
|
+
timeoutId = setTimeout(
|
|
2020
|
+
() => reject(new Error(`Disk write exceeded timeout of ${this.writeTimeoutMs}ms`)),
|
|
2021
|
+
this.writeTimeoutMs
|
|
2022
|
+
);
|
|
2023
|
+
})
|
|
2024
|
+
]);
|
|
2025
|
+
this.consecutiveFailures = 0;
|
|
2026
|
+
if (this.circuitState === "half-open") {
|
|
2027
|
+
this.circuitState = "closed";
|
|
2028
|
+
this.lastStateChangeMonotonic = performance.now();
|
|
2029
|
+
}
|
|
2030
|
+
return result;
|
|
2031
|
+
} catch {
|
|
2032
|
+
this.consecutiveFailures++;
|
|
2033
|
+
if (this.consecutiveFailures >= this.failureThreshold || this.circuitState === "half-open") {
|
|
2034
|
+
this.circuitState = "open";
|
|
2035
|
+
this.lastStateChangeMonotonic = performance.now();
|
|
2036
|
+
}
|
|
2037
|
+
this.spillsDropped++;
|
|
2038
|
+
return null;
|
|
2039
|
+
} finally {
|
|
2040
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
2041
|
+
this.active--;
|
|
2042
|
+
const next = this.queue.shift();
|
|
2043
|
+
if (next) next();
|
|
2044
|
+
}
|
|
2045
|
+
}
|
|
2046
|
+
getStats() {
|
|
2047
|
+
return {
|
|
2048
|
+
activeWrites: this.active,
|
|
2049
|
+
pendingWrites: this.queue.length,
|
|
2050
|
+
spillsDropped: this.spillsDropped,
|
|
2051
|
+
circuitState: this.circuitState,
|
|
2052
|
+
lastTripTimestamp: this.lastStateChangeMonotonic
|
|
2053
|
+
};
|
|
2054
|
+
}
|
|
2055
|
+
reset() {
|
|
2056
|
+
this.consecutiveFailures = 0;
|
|
2057
|
+
this.circuitState = "closed";
|
|
2058
|
+
this.lastStateChangeMonotonic = performance.now();
|
|
2059
|
+
}
|
|
2060
|
+
};
|
|
1630
2061
|
var _SqliteDB = null;
|
|
1631
2062
|
try {
|
|
1632
|
-
const
|
|
1633
|
-
|
|
2063
|
+
const proc = process;
|
|
2064
|
+
if (typeof proc.getBuiltinModule === "function") {
|
|
2065
|
+
const sqlite = proc.getBuiltinModule("node:sqlite");
|
|
2066
|
+
_SqliteDB = sqlite?.DatabaseSync ?? null;
|
|
2067
|
+
}
|
|
1634
2068
|
} catch {
|
|
1635
2069
|
}
|
|
1636
2070
|
var DISK_MAGIC = Buffer.from([68, 84, 73, 69, 82, 86, 49, 0]);
|
|
1637
2071
|
var DISK_MAGIC_V2 = Buffer.from([68, 84, 73, 69, 82, 86, 50, 0]);
|
|
1638
2072
|
var V2_HEADER_LEN = 16;
|
|
1639
2073
|
var DISK_TIER_VERSION = 1;
|
|
2074
|
+
function resolveDefaultDiskDir(namespace, logger) {
|
|
2075
|
+
const ns = namespace?.trim() ?? "";
|
|
2076
|
+
const nsDir = ns ? `tricache-disk-${ns}` : "tricache-disk";
|
|
2077
|
+
if (process.platform === "linux") {
|
|
2078
|
+
const shmPath = "/dev/shm";
|
|
2079
|
+
try {
|
|
2080
|
+
import_fs2.default.accessSync(shmPath, import_fs2.default.constants.W_OK | import_fs2.default.constants.R_OK);
|
|
2081
|
+
if (typeof import_fs2.default.statfsSync === "function") {
|
|
2082
|
+
const stats = import_fs2.default.statfsSync(shmPath);
|
|
2083
|
+
const totalBytes = Number(stats.blocks) * Number(stats.bsize);
|
|
2084
|
+
const freeBytes = Number(stats.bavail) * Number(stats.bsize);
|
|
2085
|
+
if (totalBytes >= 256 * 1024 * 1024 && freeBytes >= 128 * 1024 * 1024) {
|
|
2086
|
+
const targetDir = import_path2.default.join(shmPath, nsDir);
|
|
2087
|
+
logger?.info?.("DiskTier: Targeting Linux /dev/shm tmpfs for off-heap storage", {
|
|
2088
|
+
path: targetDir,
|
|
2089
|
+
totalBytes,
|
|
2090
|
+
freeBytes
|
|
2091
|
+
});
|
|
2092
|
+
return { dir: targetDir, isShm: true };
|
|
2093
|
+
} else {
|
|
2094
|
+
logger?.info?.("DiskTier: /dev/shm capacity or free space insufficient (<256MB total or <128MB free); falling back to tmpdir", {
|
|
2095
|
+
totalBytes,
|
|
2096
|
+
freeBytes
|
|
2097
|
+
});
|
|
2098
|
+
}
|
|
2099
|
+
}
|
|
2100
|
+
} catch (err) {
|
|
2101
|
+
logger?.debug?.("DiskTier: /dev/shm not usable, falling back to tmpdir", {
|
|
2102
|
+
error: err.message
|
|
2103
|
+
});
|
|
2104
|
+
}
|
|
2105
|
+
}
|
|
2106
|
+
return { dir: import_path2.default.join(import_os2.default.tmpdir(), nsDir), isShm: false };
|
|
2107
|
+
}
|
|
1640
2108
|
var DiskTier = class {
|
|
1641
2109
|
opts;
|
|
2110
|
+
codec;
|
|
2111
|
+
diskQueue;
|
|
1642
2112
|
dirReady = false;
|
|
1643
2113
|
diskUsageBytes = 0;
|
|
1644
2114
|
usageCounted = false;
|
|
@@ -1646,6 +2116,14 @@ var DiskTier = class {
|
|
|
1646
2116
|
// maintained in-memory; avoids walkCacheFiles() in stats
|
|
1647
2117
|
/** Next bucket index (0–255) for the staggered janitor wheel. */
|
|
1648
2118
|
_nextJanitorBucket = 0;
|
|
2119
|
+
// ── High-watermark pruning & host volume health state ─────────────────────
|
|
2120
|
+
_isPruning = false;
|
|
2121
|
+
_pruneRounds = 0;
|
|
2122
|
+
_entriesPruned = 0;
|
|
2123
|
+
_spillsShedTotal = 0;
|
|
2124
|
+
_hostVolumeLowSpace = false;
|
|
2125
|
+
_hostVolumeLowSpacePauses = 0;
|
|
2126
|
+
_writeCounter = 0;
|
|
1649
2127
|
// ── SQLite metadata index (optional, requires node:sqlite) ───────────────
|
|
1650
2128
|
_db = null;
|
|
1651
2129
|
_stmtInsert = null;
|
|
@@ -1660,8 +2138,19 @@ var DiskTier = class {
|
|
|
1660
2138
|
// DELETE expired rows
|
|
1661
2139
|
_stmtStats = null;
|
|
1662
2140
|
// COUNT + SUM(size)
|
|
2141
|
+
_stmtPruneChunk = null;
|
|
2142
|
+
// SELECT chunk for watermark pruning
|
|
1663
2143
|
constructor(opts) {
|
|
1664
2144
|
this.opts = opts;
|
|
2145
|
+
this.codec = opts.codec ?? defaultCodec;
|
|
2146
|
+
const defaultConcurrent = Math.min(4, Math.max(1, Math.floor((import_os2.default?.availableParallelism?.() ?? 4) / 4)));
|
|
2147
|
+
this.diskQueue = new BoundedDiskQueue(
|
|
2148
|
+
opts.diskMaxConcurrentWrites ?? defaultConcurrent,
|
|
2149
|
+
opts.diskMaxPendingWrites ?? 512,
|
|
2150
|
+
opts.diskWriteTimeoutMs ?? 500,
|
|
2151
|
+
opts.diskCircuitBreakerThreshold ?? 5,
|
|
2152
|
+
opts.diskCircuitBreakerCooldownMs ?? 5e3
|
|
2153
|
+
);
|
|
1665
2154
|
}
|
|
1666
2155
|
// ── Helpers ───────────────────────────────────────────────────────────────
|
|
1667
2156
|
ensureDir() {
|
|
@@ -1696,15 +2185,30 @@ var DiskTier = class {
|
|
|
1696
2185
|
PRAGMA synchronous = NORMAL;
|
|
1697
2186
|
PRAGMA temp_store = MEMORY;
|
|
1698
2187
|
CREATE TABLE IF NOT EXISTS meta (
|
|
1699
|
-
key_hash
|
|
1700
|
-
file_path
|
|
1701
|
-
expires_at
|
|
1702
|
-
size
|
|
2188
|
+
key_hash TEXT PRIMARY KEY,
|
|
2189
|
+
file_path TEXT NOT NULL,
|
|
2190
|
+
expires_at INTEGER NOT NULL,
|
|
2191
|
+
size INTEGER NOT NULL DEFAULT 0,
|
|
2192
|
+
priority INTEGER NOT NULL DEFAULT 2,
|
|
2193
|
+
last_accessed_at INTEGER NOT NULL DEFAULT 0
|
|
1703
2194
|
);
|
|
1704
2195
|
CREATE INDEX IF NOT EXISTS idx_expires ON meta (expires_at);
|
|
2196
|
+
CREATE INDEX IF NOT EXISTS idx_priority_access ON meta (priority ASC, last_accessed_at ASC);
|
|
1705
2197
|
`);
|
|
2198
|
+
try {
|
|
2199
|
+
this._db.exec("ALTER TABLE meta ADD COLUMN priority INTEGER NOT NULL DEFAULT 2;");
|
|
2200
|
+
} catch {
|
|
2201
|
+
}
|
|
2202
|
+
try {
|
|
2203
|
+
this._db.exec("ALTER TABLE meta ADD COLUMN last_accessed_at INTEGER NOT NULL DEFAULT 0;");
|
|
2204
|
+
} catch {
|
|
2205
|
+
}
|
|
2206
|
+
try {
|
|
2207
|
+
this._db.exec("CREATE INDEX IF NOT EXISTS idx_priority_access ON meta (priority ASC, last_accessed_at ASC);");
|
|
2208
|
+
} catch {
|
|
2209
|
+
}
|
|
1706
2210
|
this._stmtInsert = this._db.prepare(
|
|
1707
|
-
"INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size) VALUES (
|
|
2211
|
+
"INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size, priority, last_accessed_at) VALUES (?,?,?,?,?,?)"
|
|
1708
2212
|
);
|
|
1709
2213
|
this._stmtSelect = this._db.prepare(
|
|
1710
2214
|
"SELECT file_path, expires_at FROM meta WHERE key_hash = ?"
|
|
@@ -1717,13 +2221,16 @@ var DiskTier = class {
|
|
|
1717
2221
|
this._stmtStats = this._db.prepare(
|
|
1718
2222
|
"SELECT COUNT(*) AS cnt, COALESCE(SUM(size), 0) AS bytes FROM meta"
|
|
1719
2223
|
);
|
|
2224
|
+
this._stmtPruneChunk = this._db.prepare(
|
|
2225
|
+
"SELECT key_hash, file_path, size FROM meta ORDER BY priority ASC, last_accessed_at ASC LIMIT 500"
|
|
2226
|
+
);
|
|
1720
2227
|
const row = this._stmtStats.get();
|
|
1721
2228
|
this.fileCount = row.cnt;
|
|
1722
2229
|
this.diskUsageBytes = row.bytes;
|
|
1723
2230
|
this.usageCounted = true;
|
|
1724
2231
|
this.opts.logger.debug("DiskTier: SQLite index ready", { entries: row.cnt });
|
|
1725
2232
|
} catch (err) {
|
|
1726
|
-
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
|
|
2233
|
+
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = this._stmtPruneChunk = null;
|
|
1727
2234
|
this.opts.logger.warn("DiskTier: SQLite init failed, using file-only mode", {
|
|
1728
2235
|
error: err.message
|
|
1729
2236
|
});
|
|
@@ -1818,7 +2325,7 @@ var DiskTier = class {
|
|
|
1818
2325
|
return results;
|
|
1819
2326
|
}
|
|
1820
2327
|
isForbidden(key) {
|
|
1821
|
-
return this.opts.forbiddenPrefixes
|
|
2328
|
+
return this.opts.forbiddenPrefixes?.some((p) => key.startsWith(p)) ?? false;
|
|
1822
2329
|
}
|
|
1823
2330
|
encrypt(data) {
|
|
1824
2331
|
if (!this.opts.encryption) return data;
|
|
@@ -1870,7 +2377,16 @@ var DiskTier = class {
|
|
|
1870
2377
|
this.ensureDir();
|
|
1871
2378
|
if (!this.dirReady) return;
|
|
1872
2379
|
this.ensureUsageCounted();
|
|
1873
|
-
if (this.
|
|
2380
|
+
if (++this._writeCounter % 2e3 === 0) {
|
|
2381
|
+
this.checkHostVolumeHealth();
|
|
2382
|
+
}
|
|
2383
|
+
if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes >= this.opts.maxBytes) {
|
|
2384
|
+
this._spillsShedTotal++;
|
|
2385
|
+
return;
|
|
2386
|
+
}
|
|
2387
|
+
if (this.diskUsageBytes >= this.opts.maxBytes * 0.8 && !this._isPruning) {
|
|
2388
|
+
void this.triggerChunkedPrune();
|
|
2389
|
+
}
|
|
1874
2390
|
let final;
|
|
1875
2391
|
try {
|
|
1876
2392
|
const payload = {
|
|
@@ -1882,7 +2398,7 @@ var DiskTier = class {
|
|
|
1882
2398
|
},
|
|
1883
2399
|
writtenAt: Date.now()
|
|
1884
2400
|
};
|
|
1885
|
-
const packed =
|
|
2401
|
+
const packed = this.codec.encode(payload);
|
|
1886
2402
|
if (packed.length > this.opts.entryMaxBytes) return;
|
|
1887
2403
|
let toEncrypt = packed;
|
|
1888
2404
|
if (this.opts.compression && this.opts.compression !== "none" && packed.length > (this.opts.compressionThresholdBytes ?? 1024)) {
|
|
@@ -1898,39 +2414,52 @@ var DiskTier = class {
|
|
|
1898
2414
|
}
|
|
1899
2415
|
const hash = this.keyToHash(key);
|
|
1900
2416
|
const filePath = this.hashToWritePath(hash, entry.expiresAt);
|
|
1901
|
-
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${
|
|
2417
|
+
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${import_crypto2.default.randomBytes(6).toString("hex")}.tmp`;
|
|
1902
2418
|
this.diskUsageBytes += final.length;
|
|
1903
2419
|
this.fileCount++;
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
2420
|
+
if (this.diskUsageBytes >= this.opts.maxBytes * 0.8 && !this._isPruning) {
|
|
2421
|
+
void this.triggerChunkedPrune();
|
|
2422
|
+
}
|
|
2423
|
+
const result = await this.diskQueue.schedule(async () => {
|
|
1907
2424
|
try {
|
|
1908
|
-
await import_fs2.default.promises.
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
if (code === "EBUSY" || code === "EPERM") {
|
|
1912
|
-
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
2425
|
+
await import_fs2.default.promises.mkdir(import_path2.default.dirname(filePath), { recursive: true });
|
|
2426
|
+
await import_fs2.default.promises.writeFile(tmpPath, final, { mode: 384 });
|
|
2427
|
+
try {
|
|
1913
2428
|
await import_fs2.default.promises.rename(tmpPath, filePath);
|
|
1914
|
-
}
|
|
1915
|
-
|
|
2429
|
+
} catch (renameErr) {
|
|
2430
|
+
const code = renameErr?.code;
|
|
2431
|
+
if (code === "EBUSY" || code === "EPERM") {
|
|
2432
|
+
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
2433
|
+
await import_fs2.default.promises.rename(tmpPath, filePath);
|
|
2434
|
+
} else {
|
|
2435
|
+
throw renameErr;
|
|
2436
|
+
}
|
|
1916
2437
|
}
|
|
2438
|
+
if (this._db) {
|
|
2439
|
+
const priority = typeof entry.priority === "number" ? entry.priority : 2;
|
|
2440
|
+
const lastAccess = typeof entry.lastAccess === "number" ? entry.lastAccess : Date.now();
|
|
2441
|
+
this._stmtInsert.run(hash, filePath, entry.expiresAt, final.length, priority, lastAccess);
|
|
2442
|
+
}
|
|
2443
|
+
this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
|
|
2444
|
+
return true;
|
|
2445
|
+
} catch (err) {
|
|
2446
|
+
try {
|
|
2447
|
+
await import_fs2.default.promises.unlink(tmpPath);
|
|
2448
|
+
} catch {
|
|
2449
|
+
}
|
|
2450
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
|
|
2451
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2452
|
+
if (this._db) try {
|
|
2453
|
+
this._stmtDelete.run(hash);
|
|
2454
|
+
} catch {
|
|
2455
|
+
}
|
|
2456
|
+
this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
|
|
2457
|
+
throw err;
|
|
1917
2458
|
}
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
}
|
|
1921
|
-
this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
|
|
1922
|
-
} catch (err) {
|
|
1923
|
-
try {
|
|
1924
|
-
await import_fs2.default.promises.unlink(tmpPath);
|
|
1925
|
-
} catch {
|
|
1926
|
-
}
|
|
2459
|
+
});
|
|
2460
|
+
if (result === null) {
|
|
1927
2461
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
|
|
1928
2462
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1929
|
-
if (this._db) try {
|
|
1930
|
-
this._stmtDelete.run(hash);
|
|
1931
|
-
} catch {
|
|
1932
|
-
}
|
|
1933
|
-
this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
|
|
1934
2463
|
}
|
|
1935
2464
|
}
|
|
1936
2465
|
/** Load a key from disk, or return null on miss/expiry/corruption. */
|
|
@@ -2008,7 +2537,7 @@ var DiskTier = class {
|
|
|
2008
2537
|
}
|
|
2009
2538
|
}
|
|
2010
2539
|
const uncompressed = decompressWithHeader(decrypted, this.opts.compression ?? "brotli");
|
|
2011
|
-
const payload =
|
|
2540
|
+
const payload = this.codec.decode(uncompressed);
|
|
2012
2541
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
|
|
2013
2542
|
if (payload.entry.expiresAt <= Date.now()) return null;
|
|
2014
2543
|
const entry = payload.entry;
|
|
@@ -2131,7 +2660,7 @@ var DiskTier = class {
|
|
|
2131
2660
|
purged++;
|
|
2132
2661
|
continue;
|
|
2133
2662
|
}
|
|
2134
|
-
const payload =
|
|
2663
|
+
const payload = this.codec.decode(dec);
|
|
2135
2664
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
2136
2665
|
import_fs2.default.unlinkSync(filePath);
|
|
2137
2666
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
@@ -2295,7 +2824,7 @@ var DiskTier = class {
|
|
|
2295
2824
|
purged++;
|
|
2296
2825
|
continue;
|
|
2297
2826
|
}
|
|
2298
|
-
const payload =
|
|
2827
|
+
const payload = this.codec.decode(dec);
|
|
2299
2828
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
2300
2829
|
import_fs2.default.unlinkSync(filePath);
|
|
2301
2830
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
@@ -2334,13 +2863,141 @@ var DiskTier = class {
|
|
|
2334
2863
|
}
|
|
2335
2864
|
return cleared;
|
|
2336
2865
|
}
|
|
2866
|
+
/**
|
|
2867
|
+
* Proactively checks host volume free space via statfsSync.
|
|
2868
|
+
* If free space on the volume drops below 10%, pauses spills to prevent
|
|
2869
|
+
* Kubernetes pod eviction (DiskPressure / EphemeralStorageExceeded).
|
|
2870
|
+
*/
|
|
2871
|
+
checkHostVolumeHealth() {
|
|
2872
|
+
try {
|
|
2873
|
+
if (typeof import_fs2.default.statfsSync === "function") {
|
|
2874
|
+
const stats = import_fs2.default.statfsSync(this.opts.dir);
|
|
2875
|
+
const total = Number(stats.blocks);
|
|
2876
|
+
const avail = Number(stats.bavail);
|
|
2877
|
+
if (total > 0) {
|
|
2878
|
+
const freeRatio = avail / total;
|
|
2879
|
+
if (freeRatio < 0.1) {
|
|
2880
|
+
if (!this._hostVolumeLowSpace) {
|
|
2881
|
+
this._hostVolumeLowSpace = true;
|
|
2882
|
+
this._hostVolumeLowSpacePauses++;
|
|
2883
|
+
this.opts.logger.warn(
|
|
2884
|
+
"DiskTier: host volume has <10% free space. Pausing disk cache spills to prevent Kubernetes eviction.",
|
|
2885
|
+
{ dir: this.opts.dir, freePct: Number((freeRatio * 100).toFixed(1)) }
|
|
2886
|
+
);
|
|
2887
|
+
}
|
|
2888
|
+
return false;
|
|
2889
|
+
} else if (this._hostVolumeLowSpace) {
|
|
2890
|
+
this._hostVolumeLowSpace = false;
|
|
2891
|
+
this.opts.logger.info(
|
|
2892
|
+
"DiskTier: host volume space recovered (>=10% free). Resuming disk cache spills.",
|
|
2893
|
+
{ dir: this.opts.dir, freePct: Number((freeRatio * 100).toFixed(1)) }
|
|
2894
|
+
);
|
|
2895
|
+
return true;
|
|
2896
|
+
}
|
|
2897
|
+
}
|
|
2898
|
+
}
|
|
2899
|
+
} catch {
|
|
2900
|
+
}
|
|
2901
|
+
return true;
|
|
2902
|
+
}
|
|
2903
|
+
/**
|
|
2904
|
+
* Non-blocking chunked pruning:
|
|
2905
|
+
* Evicts oldest entries in 500-entry chunks down to 60% watermark,
|
|
2906
|
+
* yielding to the event loop via setImmediate between chunks.
|
|
2907
|
+
*/
|
|
2908
|
+
async triggerChunkedPrune() {
|
|
2909
|
+
if (this._isPruning) return 0;
|
|
2910
|
+
this._isPruning = true;
|
|
2911
|
+
this._pruneRounds++;
|
|
2912
|
+
let prunedInThisRound = 0;
|
|
2913
|
+
try {
|
|
2914
|
+
this.ensureUsageCounted();
|
|
2915
|
+
const targetBytes = Math.floor(this.opts.maxBytes * 0.6);
|
|
2916
|
+
if (this._db && this._stmtPruneChunk) {
|
|
2917
|
+
while (this.diskUsageBytes > targetBytes) {
|
|
2918
|
+
const rows = this._stmtPruneChunk.all();
|
|
2919
|
+
if (!rows || rows.length === 0) break;
|
|
2920
|
+
for (const row of rows) {
|
|
2921
|
+
try {
|
|
2922
|
+
import_fs2.default.unlinkSync(row.file_path);
|
|
2923
|
+
} catch {
|
|
2924
|
+
}
|
|
2925
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
|
|
2926
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2927
|
+
this._entriesPruned++;
|
|
2928
|
+
prunedInThisRound++;
|
|
2929
|
+
try {
|
|
2930
|
+
this._stmtDelete.run(row.key_hash);
|
|
2931
|
+
} catch {
|
|
2932
|
+
}
|
|
2933
|
+
if (this.diskUsageBytes <= targetBytes) break;
|
|
2934
|
+
}
|
|
2935
|
+
if (this.diskUsageBytes > targetBytes) {
|
|
2936
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
2937
|
+
}
|
|
2938
|
+
}
|
|
2939
|
+
} else {
|
|
2940
|
+
while (this.diskUsageBytes > targetBytes) {
|
|
2941
|
+
const files = this.walkCacheFiles();
|
|
2942
|
+
if (files.length === 0) break;
|
|
2943
|
+
const chunk = files.slice(0, 500);
|
|
2944
|
+
for (const filePath of chunk) {
|
|
2945
|
+
try {
|
|
2946
|
+
const stat = import_fs2.default.statSync(filePath);
|
|
2947
|
+
import_fs2.default.unlinkSync(filePath);
|
|
2948
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
2949
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2950
|
+
this._entriesPruned++;
|
|
2951
|
+
prunedInThisRound++;
|
|
2952
|
+
} catch {
|
|
2953
|
+
}
|
|
2954
|
+
if (this.diskUsageBytes <= targetBytes) break;
|
|
2955
|
+
}
|
|
2956
|
+
if (this.diskUsageBytes > targetBytes) {
|
|
2957
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
2958
|
+
}
|
|
2959
|
+
}
|
|
2960
|
+
}
|
|
2961
|
+
} finally {
|
|
2962
|
+
this._isPruning = false;
|
|
2963
|
+
}
|
|
2964
|
+
return prunedInThisRound;
|
|
2965
|
+
}
|
|
2966
|
+
get isPruning() {
|
|
2967
|
+
return this._isPruning;
|
|
2968
|
+
}
|
|
2969
|
+
get hostVolumeLowSpace() {
|
|
2970
|
+
return this._hostVolumeLowSpace;
|
|
2971
|
+
}
|
|
2972
|
+
get spillsShedTotal() {
|
|
2973
|
+
return this._spillsShedTotal;
|
|
2974
|
+
}
|
|
2975
|
+
getPruningStats() {
|
|
2976
|
+
return {
|
|
2977
|
+
active: this._isPruning,
|
|
2978
|
+
pruneRounds: this._pruneRounds,
|
|
2979
|
+
entriesPruned: this._entriesPruned,
|
|
2980
|
+
spillsShedTotal: this._spillsShedTotal,
|
|
2981
|
+
hostVolumeLowSpacePauses: this._hostVolumeLowSpacePauses
|
|
2982
|
+
};
|
|
2983
|
+
}
|
|
2337
2984
|
get stats() {
|
|
2338
2985
|
if (this._db) {
|
|
2339
2986
|
const row = this._stmtStats.get();
|
|
2340
2987
|
this.fileCount = row.cnt;
|
|
2341
2988
|
this.diskUsageBytes = row.bytes;
|
|
2342
2989
|
}
|
|
2343
|
-
return {
|
|
2990
|
+
return {
|
|
2991
|
+
files: this.fileCount,
|
|
2992
|
+
sizeKB: Math.round(this.diskUsageBytes / 1024),
|
|
2993
|
+
maxKB: Math.round(this.opts.maxBytes / 1024),
|
|
2994
|
+
backpressure: this.diskQueue.getStats(),
|
|
2995
|
+
pruning: this.getPruningStats()
|
|
2996
|
+
};
|
|
2997
|
+
}
|
|
2998
|
+
/** Direct access to the bounded write queue for chaos diagnostics and canary controls. */
|
|
2999
|
+
get backpressure() {
|
|
3000
|
+
return this.diskQueue;
|
|
2344
3001
|
}
|
|
2345
3002
|
/** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
|
|
2346
3003
|
get indexMode() {
|
|
@@ -2353,58 +3010,621 @@ var DiskTier = class {
|
|
|
2353
3010
|
this._db.close();
|
|
2354
3011
|
} catch {
|
|
2355
3012
|
}
|
|
2356
|
-
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
|
|
3013
|
+
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = this._stmtPruneChunk = null;
|
|
2357
3014
|
}
|
|
2358
3015
|
}
|
|
2359
3016
|
};
|
|
2360
3017
|
|
|
2361
|
-
// src/
|
|
2362
|
-
var
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
2384
|
-
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
|
|
3018
|
+
// src/latency-watchdog.ts
|
|
3019
|
+
var TierLatencyWatchdog = class {
|
|
3020
|
+
enabled;
|
|
3021
|
+
minDiskBypassMs;
|
|
3022
|
+
bypassRatio;
|
|
3023
|
+
cooldownMs;
|
|
3024
|
+
redisCutoffMs;
|
|
3025
|
+
redisRecoveryFloorMs;
|
|
3026
|
+
minSamples;
|
|
3027
|
+
disableRedis;
|
|
3028
|
+
// Zero-allocation rolling ring buffers
|
|
3029
|
+
diskRing = new Float32Array(32);
|
|
3030
|
+
redisRing = new Float32Array(32);
|
|
3031
|
+
scratch = new Float32Array(32);
|
|
3032
|
+
diskIdx = 0;
|
|
3033
|
+
redisIdx = 0;
|
|
3034
|
+
diskCount = 0;
|
|
3035
|
+
redisCount = 0;
|
|
3036
|
+
// Cached amortized p95 values
|
|
3037
|
+
cachedDiskP95 = 0;
|
|
3038
|
+
cachedRedisP95 = 0;
|
|
3039
|
+
// State machine & control-theory flags
|
|
3040
|
+
stage = 0;
|
|
3041
|
+
redisDampened = false;
|
|
3042
|
+
// Asymmetric hysteresis latch
|
|
3043
|
+
redisRecoveryConsecutiveSamples = 0;
|
|
3044
|
+
bypassedUntilMonotonic = 0;
|
|
3045
|
+
canaryInFlight = false;
|
|
3046
|
+
bypassedTotal = 0;
|
|
3047
|
+
constructor(options = {}) {
|
|
3048
|
+
this.enabled = options.enabled ?? true;
|
|
3049
|
+
this.minDiskBypassMs = options.minDiskBypassMs ?? 10;
|
|
3050
|
+
this.bypassRatio = options.bypassRatio ?? 1.5;
|
|
3051
|
+
this.cooldownMs = options.cooldownMs ?? 3e4;
|
|
3052
|
+
this.redisCutoffMs = options.redisCutoffMs ?? 15;
|
|
3053
|
+
this.redisRecoveryFloorMs = options.redisRecoveryFloorMs ?? 10;
|
|
3054
|
+
this.minSamples = options.minSamples ?? 16;
|
|
3055
|
+
this.disableRedis = options.disableRedis ?? false;
|
|
3056
|
+
}
|
|
3057
|
+
setDisableRedis(disabled) {
|
|
3058
|
+
this.disableRedis = disabled;
|
|
3059
|
+
if (disabled) {
|
|
3060
|
+
this.stage = 0;
|
|
3061
|
+
this.bypassedUntilMonotonic = 0;
|
|
3062
|
+
this.canaryInFlight = false;
|
|
3063
|
+
this.redisRecoveryConsecutiveSamples = 0;
|
|
3064
|
+
}
|
|
2392
3065
|
}
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
this.
|
|
2399
|
-
this.
|
|
3066
|
+
/**
|
|
3067
|
+
* Record disk read duration in milliseconds (zero-allocation hot path).
|
|
3068
|
+
*/
|
|
3069
|
+
recordDisk(ms) {
|
|
3070
|
+
if (!this.enabled) return;
|
|
3071
|
+
this.diskRing[this.diskIdx++ & 31] = ms;
|
|
3072
|
+
this.diskCount++;
|
|
3073
|
+
if ((this.diskIdx & 31) === 0) {
|
|
3074
|
+
this.recalculateP95();
|
|
3075
|
+
}
|
|
2400
3076
|
}
|
|
2401
|
-
|
|
2402
|
-
|
|
2403
|
-
|
|
2404
|
-
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
3077
|
+
/**
|
|
3078
|
+
* Record Redis read duration in milliseconds (zero-allocation hot path).
|
|
3079
|
+
*/
|
|
3080
|
+
recordRedis(ms) {
|
|
3081
|
+
if (!this.enabled || this.disableRedis) return;
|
|
3082
|
+
this.redisRing[this.redisIdx++ & 31] = ms;
|
|
3083
|
+
this.redisCount++;
|
|
3084
|
+
if (ms <= this.redisRecoveryFloorMs) {
|
|
3085
|
+
this.redisRecoveryConsecutiveSamples++;
|
|
3086
|
+
} else {
|
|
3087
|
+
this.redisRecoveryConsecutiveSamples = 0;
|
|
3088
|
+
}
|
|
3089
|
+
if ((this.redisIdx & 31) === 0) {
|
|
3090
|
+
this.recalculateP95();
|
|
3091
|
+
}
|
|
3092
|
+
}
|
|
3093
|
+
recalculateP95() {
|
|
3094
|
+
if (this.diskCount >= this.minSamples) {
|
|
3095
|
+
this.cachedDiskP95 = this.computeP95(this.diskRing, Math.min(this.diskCount, 32));
|
|
3096
|
+
}
|
|
3097
|
+
if (this.redisCount >= this.minSamples) {
|
|
3098
|
+
this.cachedRedisP95 = this.computeP95(this.redisRing, Math.min(this.redisCount, 32));
|
|
3099
|
+
}
|
|
3100
|
+
this.evaluateControlLoop();
|
|
3101
|
+
}
|
|
3102
|
+
computeP95(ring, count) {
|
|
3103
|
+
for (let i = 0; i < count; i++) {
|
|
3104
|
+
this.scratch[i] = ring[i];
|
|
3105
|
+
}
|
|
3106
|
+
this.scratch.subarray(0, count).sort();
|
|
3107
|
+
const rank = Math.min(count - 1, Math.max(0, Math.floor((count - 1) * 0.95)));
|
|
3108
|
+
return this.scratch[rank];
|
|
3109
|
+
}
|
|
3110
|
+
/**
|
|
3111
|
+
* Core Control Loop:
|
|
3112
|
+
* - Evaluates asymmetric hysteresis on Redis circuit.
|
|
3113
|
+
* - Assigns graduated stage (0, 1, 2, 3) with anti-synchronicity jitter.
|
|
3114
|
+
*/
|
|
3115
|
+
evaluateControlLoop() {
|
|
3116
|
+
if (this.disableRedis) {
|
|
3117
|
+
this.stage = 0;
|
|
3118
|
+
return;
|
|
3119
|
+
}
|
|
3120
|
+
if (this.cachedRedisP95 >= this.redisCutoffMs) {
|
|
3121
|
+
this.redisDampened = true;
|
|
3122
|
+
} else if (this.redisDampened && this.cachedRedisP95 <= this.redisRecoveryFloorMs && this.redisRecoveryConsecutiveSamples >= this.minSamples) {
|
|
3123
|
+
this.redisDampened = false;
|
|
3124
|
+
}
|
|
3125
|
+
if (this.redisDampened) {
|
|
3126
|
+
this.stage = 0;
|
|
3127
|
+
return;
|
|
3128
|
+
}
|
|
3129
|
+
if (this.diskCount < this.minSamples || this.redisCount < this.minSamples) {
|
|
3130
|
+
return;
|
|
3131
|
+
}
|
|
3132
|
+
const diskP95 = this.cachedDiskP95;
|
|
3133
|
+
const redisP95 = Math.max(0.1, this.cachedRedisP95);
|
|
3134
|
+
if (diskP95 >= 50) {
|
|
3135
|
+
if (this.stage !== 3) {
|
|
3136
|
+
this.stage = 3;
|
|
3137
|
+
this.bypassedUntilMonotonic = performance.now() + this.calculateJitteredCooldown();
|
|
3138
|
+
this.bypassedTotal++;
|
|
3139
|
+
}
|
|
3140
|
+
} else if (diskP95 >= this.minDiskBypassMs * 2.5 && diskP95 >= redisP95 * (this.bypassRatio * 1.5)) {
|
|
3141
|
+
if (this.stage !== 2) {
|
|
3142
|
+
this.stage = 2;
|
|
3143
|
+
this.bypassedTotal++;
|
|
3144
|
+
}
|
|
3145
|
+
} else if (diskP95 >= this.minDiskBypassMs && diskP95 >= redisP95 * this.bypassRatio) {
|
|
3146
|
+
if (this.stage !== 1) {
|
|
3147
|
+
this.stage = 1;
|
|
3148
|
+
this.bypassedTotal++;
|
|
3149
|
+
}
|
|
3150
|
+
} else {
|
|
3151
|
+
this.stage = 0;
|
|
3152
|
+
this.bypassedUntilMonotonic = 0;
|
|
3153
|
+
this.canaryInFlight = false;
|
|
3154
|
+
}
|
|
3155
|
+
}
|
|
3156
|
+
calculateJitteredCooldown() {
|
|
3157
|
+
const jitterFactor = 0.7 + Math.random() * 0.6;
|
|
3158
|
+
return this.cooldownMs * jitterFactor;
|
|
3159
|
+
}
|
|
3160
|
+
/**
|
|
3161
|
+
* Determine whether a read is permitted to check the disk tier.
|
|
3162
|
+
*
|
|
3163
|
+
* In Stage 1 and 2, sheds traffic probabilistically.
|
|
3164
|
+
* In Stage 3, blocks all reads except for a single canary probe once cooldown expires.
|
|
3165
|
+
*
|
|
3166
|
+
* @param randomOverride Optional seeded random number [0, 1) for deterministic unit testing.
|
|
3167
|
+
*/
|
|
3168
|
+
isDiskAllowed(randomOverride) {
|
|
3169
|
+
if (!this.enabled || this.disableRedis) return true;
|
|
3170
|
+
if (this.stage === 0) return true;
|
|
3171
|
+
const rand = randomOverride !== void 0 ? randomOverride : Math.random();
|
|
3172
|
+
if (this.stage === 1) {
|
|
3173
|
+
return rand > 0.25;
|
|
3174
|
+
}
|
|
3175
|
+
if (this.stage === 2) {
|
|
3176
|
+
return rand > 0.75;
|
|
3177
|
+
}
|
|
3178
|
+
const now = performance.now();
|
|
3179
|
+
if (now < this.bypassedUntilMonotonic) {
|
|
3180
|
+
return false;
|
|
3181
|
+
}
|
|
3182
|
+
if (!this.canaryInFlight) {
|
|
3183
|
+
this.canaryInFlight = true;
|
|
3184
|
+
return true;
|
|
3185
|
+
}
|
|
3186
|
+
return false;
|
|
3187
|
+
}
|
|
3188
|
+
/**
|
|
3189
|
+
* Callback invoked when the single canary read probe completes.
|
|
3190
|
+
*/
|
|
3191
|
+
onCanaryResult(success, elapsedMs) {
|
|
3192
|
+
if (!this.canaryInFlight) return;
|
|
3193
|
+
this.canaryInFlight = false;
|
|
3194
|
+
if (success && elapsedMs < this.minDiskBypassMs) {
|
|
3195
|
+
this.stage = 0;
|
|
3196
|
+
this.bypassedUntilMonotonic = 0;
|
|
3197
|
+
this.recordDisk(elapsedMs);
|
|
3198
|
+
} else {
|
|
3199
|
+
this.bypassedUntilMonotonic = performance.now() + this.calculateJitteredCooldown();
|
|
3200
|
+
this.bypassedTotal++;
|
|
3201
|
+
}
|
|
3202
|
+
}
|
|
3203
|
+
getTelemetry() {
|
|
3204
|
+
return {
|
|
3205
|
+
bypassActive: this.stage > 0,
|
|
3206
|
+
bypassStage: this.stage,
|
|
3207
|
+
diskP95Ms: Number(this.cachedDiskP95.toFixed(2)),
|
|
3208
|
+
redisP95Ms: Number(this.cachedRedisP95.toFixed(2)),
|
|
3209
|
+
redisDampened: this.redisDampened,
|
|
3210
|
+
bypassedTotal: this.bypassedTotal
|
|
3211
|
+
};
|
|
3212
|
+
}
|
|
3213
|
+
};
|
|
3214
|
+
|
|
3215
|
+
// src/utils/cgroup.ts
|
|
3216
|
+
var import_node_fs = __toESM(require("fs"), 1);
|
|
3217
|
+
var import_node_v8 = __toESM(require("v8"), 1);
|
|
3218
|
+
var UNBOUNDED_CGROUP_THRESHOLD = 9e18;
|
|
3219
|
+
var DEFAULT_AUTONOMOUS_L1_CEILING_BYTES = 512 * 1024 * 1024;
|
|
3220
|
+
var MIN_AUTONOMOUS_L1_FLOOR_BYTES = 16 * 1024 * 1024;
|
|
3221
|
+
function readCgroupMemoryLimit() {
|
|
3222
|
+
if (process.platform !== "linux") {
|
|
3223
|
+
return Infinity;
|
|
3224
|
+
}
|
|
3225
|
+
try {
|
|
3226
|
+
if (import_node_fs.default.existsSync("/sys/fs/cgroup/memory.max")) {
|
|
3227
|
+
const raw = import_node_fs.default.readFileSync("/sys/fs/cgroup/memory.max", "utf8").trim();
|
|
3228
|
+
if (raw === "max") {
|
|
3229
|
+
return Infinity;
|
|
3230
|
+
}
|
|
3231
|
+
const bytes = parseInt(raw, 10);
|
|
3232
|
+
if (Number.isFinite(bytes) && bytes > 0 && bytes < UNBOUNDED_CGROUP_THRESHOLD) {
|
|
3233
|
+
return bytes;
|
|
3234
|
+
}
|
|
3235
|
+
}
|
|
3236
|
+
} catch {
|
|
3237
|
+
}
|
|
3238
|
+
try {
|
|
3239
|
+
if (import_node_fs.default.existsSync("/sys/fs/cgroup/memory/memory.limit_in_bytes")) {
|
|
3240
|
+
const raw = import_node_fs.default.readFileSync("/sys/fs/cgroup/memory/memory.limit_in_bytes", "utf8").trim();
|
|
3241
|
+
const bytes = parseInt(raw, 10);
|
|
3242
|
+
if (Number.isFinite(bytes) && bytes > 0 && bytes < UNBOUNDED_CGROUP_THRESHOLD) {
|
|
3243
|
+
return bytes;
|
|
3244
|
+
}
|
|
3245
|
+
}
|
|
3246
|
+
} catch {
|
|
3247
|
+
}
|
|
3248
|
+
return Infinity;
|
|
3249
|
+
}
|
|
3250
|
+
function getV8HeapLimit() {
|
|
3251
|
+
try {
|
|
3252
|
+
const stats = import_node_v8.default.getHeapStatistics();
|
|
3253
|
+
if (stats && Number.isFinite(stats.heap_size_limit) && stats.heap_size_limit > 0) {
|
|
3254
|
+
return stats.heap_size_limit;
|
|
3255
|
+
}
|
|
3256
|
+
} catch {
|
|
3257
|
+
}
|
|
3258
|
+
return Infinity;
|
|
3259
|
+
}
|
|
3260
|
+
function resolveAutonomousL1MaxBytes(options) {
|
|
3261
|
+
const cgroup = options?.cgroupLimit !== void 0 ? options.cgroupLimit : readCgroupMemoryLimit();
|
|
3262
|
+
const v8Limit = options?.v8HeapLimit !== void 0 ? options.v8HeapLimit : getV8HeapLimit();
|
|
3263
|
+
const ceiling = options?.defaultCeilingBytes ?? DEFAULT_AUTONOMOUS_L1_CEILING_BYTES;
|
|
3264
|
+
const cgroupCap = Number.isFinite(cgroup) && cgroup > 0 ? cgroup * 0.4 : Infinity;
|
|
3265
|
+
const v8Cap = Number.isFinite(v8Limit) && v8Limit > 0 ? v8Limit * 0.5 : Infinity;
|
|
3266
|
+
const resolved = Math.min(cgroupCap, v8Cap, ceiling);
|
|
3267
|
+
if (!Number.isFinite(resolved) || resolved <= 0) {
|
|
3268
|
+
return ceiling;
|
|
3269
|
+
}
|
|
3270
|
+
return Math.max(MIN_AUTONOMOUS_L1_FLOOR_BYTES, Math.floor(resolved));
|
|
3271
|
+
}
|
|
3272
|
+
|
|
3273
|
+
// src/adapters/auto-pipeliner.ts
|
|
3274
|
+
var AutoPipeliner = class {
|
|
3275
|
+
constructor(client, options) {
|
|
3276
|
+
this.client = client;
|
|
3277
|
+
this.maxBatchSize = options?.maxBatchSize ?? 100;
|
|
3278
|
+
this.enabled = options?.enabled ?? true;
|
|
3279
|
+
}
|
|
3280
|
+
client;
|
|
3281
|
+
maxBatchSize;
|
|
3282
|
+
enabled;
|
|
3283
|
+
queue = [];
|
|
3284
|
+
scheduled = false;
|
|
3285
|
+
inFlight = false;
|
|
3286
|
+
statsInternal = {
|
|
3287
|
+
batchesDispatched: 0,
|
|
3288
|
+
operationsBatched: 0
|
|
3289
|
+
};
|
|
3290
|
+
get stats() {
|
|
3291
|
+
return {
|
|
3292
|
+
batchesDispatched: this.statsInternal.batchesDispatched,
|
|
3293
|
+
operationsBatched: this.statsInternal.operationsBatched,
|
|
3294
|
+
pendingQueueSize: this.queue.length
|
|
3295
|
+
};
|
|
3296
|
+
}
|
|
3297
|
+
async get(key) {
|
|
3298
|
+
if (!this.enabled || !this.supportsPipelines()) {
|
|
3299
|
+
return this.client.get(key);
|
|
3300
|
+
}
|
|
3301
|
+
return new Promise((resolve, reject) => {
|
|
3302
|
+
this.enqueue({ type: "get", key, resolve, reject });
|
|
3303
|
+
});
|
|
3304
|
+
}
|
|
3305
|
+
async setex(key, seconds, value) {
|
|
3306
|
+
if (!this.enabled || !this.supportsPipelines()) {
|
|
3307
|
+
if (typeof this.client.setex === "function") {
|
|
3308
|
+
await this.client.setex(key, seconds, value);
|
|
3309
|
+
} else {
|
|
3310
|
+
await this.client.set(key, value, "EX", seconds);
|
|
3311
|
+
}
|
|
3312
|
+
return;
|
|
3313
|
+
}
|
|
3314
|
+
return new Promise((resolve, reject) => {
|
|
3315
|
+
this.enqueue({ type: "setex", key, seconds, value, resolve, reject });
|
|
3316
|
+
});
|
|
3317
|
+
}
|
|
3318
|
+
async del(...keys) {
|
|
3319
|
+
if (keys.length === 0) return 0;
|
|
3320
|
+
if (!this.enabled || !this.supportsPipelines()) {
|
|
3321
|
+
return this.client.del(...keys);
|
|
3322
|
+
}
|
|
3323
|
+
return new Promise((resolve, reject) => {
|
|
3324
|
+
this.enqueue({ type: "del", keys, resolve, reject });
|
|
3325
|
+
});
|
|
3326
|
+
}
|
|
3327
|
+
supportsPipelines() {
|
|
3328
|
+
return Boolean(
|
|
3329
|
+
typeof this.client?.pipeline === "function" || typeof this.client?.multi === "function"
|
|
3330
|
+
);
|
|
3331
|
+
}
|
|
3332
|
+
enqueue(op) {
|
|
3333
|
+
this.queue.push(op);
|
|
3334
|
+
if (this.queue.length >= this.maxBatchSize) {
|
|
3335
|
+
void this.flush();
|
|
3336
|
+
return;
|
|
3337
|
+
}
|
|
3338
|
+
if (!this.scheduled) {
|
|
3339
|
+
this.scheduled = true;
|
|
3340
|
+
queueMicrotask(() => {
|
|
3341
|
+
this.scheduled = false;
|
|
3342
|
+
void this.flush();
|
|
3343
|
+
});
|
|
3344
|
+
}
|
|
3345
|
+
}
|
|
3346
|
+
async flush() {
|
|
3347
|
+
if (this.queue.length === 0) return;
|
|
3348
|
+
const batch = this.queue;
|
|
3349
|
+
this.queue = [];
|
|
3350
|
+
this.scheduled = false;
|
|
3351
|
+
this.statsInternal.batchesDispatched++;
|
|
3352
|
+
this.statsInternal.operationsBatched += batch.length;
|
|
3353
|
+
const pipe = typeof this.client.pipeline === "function" ? this.client.pipeline() : this.client.multi();
|
|
3354
|
+
for (const op of batch) {
|
|
3355
|
+
switch (op.type) {
|
|
3356
|
+
case "get":
|
|
3357
|
+
pipe.get(op.key);
|
|
3358
|
+
break;
|
|
3359
|
+
case "setex":
|
|
3360
|
+
pipe.setex(op.key, op.seconds, op.value);
|
|
3361
|
+
break;
|
|
3362
|
+
case "del":
|
|
3363
|
+
pipe.del(...op.keys);
|
|
3364
|
+
break;
|
|
3365
|
+
}
|
|
3366
|
+
}
|
|
3367
|
+
try {
|
|
3368
|
+
const results = await pipe.exec();
|
|
3369
|
+
if (!results) {
|
|
3370
|
+
for (const op of batch) {
|
|
3371
|
+
if (op.type === "get") op.resolve(null);
|
|
3372
|
+
else if (op.type === "del") op.resolve(0);
|
|
3373
|
+
else op.resolve();
|
|
3374
|
+
}
|
|
3375
|
+
return;
|
|
3376
|
+
}
|
|
3377
|
+
for (let i = 0; i < batch.length; i++) {
|
|
3378
|
+
const op = batch[i];
|
|
3379
|
+
const resTuple = results[i];
|
|
3380
|
+
if (!resTuple) {
|
|
3381
|
+
if (op.type === "get") op.resolve(null);
|
|
3382
|
+
else if (op.type === "del") op.resolve(0);
|
|
3383
|
+
else op.resolve();
|
|
3384
|
+
continue;
|
|
3385
|
+
}
|
|
3386
|
+
const [err, val] = resTuple;
|
|
3387
|
+
if (err) {
|
|
3388
|
+
op.reject(err instanceof Error ? err : new Error(String(err)));
|
|
3389
|
+
} else {
|
|
3390
|
+
if (op.type === "get") {
|
|
3391
|
+
op.resolve(val != null ? String(val) : null);
|
|
3392
|
+
} else if (op.type === "del") {
|
|
3393
|
+
op.resolve(typeof val === "number" ? val : Number(val) || 0);
|
|
3394
|
+
} else {
|
|
3395
|
+
op.resolve();
|
|
3396
|
+
}
|
|
3397
|
+
}
|
|
3398
|
+
}
|
|
3399
|
+
} catch (err) {
|
|
3400
|
+
for (const op of batch) {
|
|
3401
|
+
op.reject(err instanceof Error ? err : new Error(String(err)));
|
|
3402
|
+
}
|
|
3403
|
+
}
|
|
3404
|
+
}
|
|
3405
|
+
};
|
|
3406
|
+
|
|
3407
|
+
// src/ipc-telemetry.ts
|
|
3408
|
+
var import_node_net = __toESM(require("net"), 1);
|
|
3409
|
+
var import_node_fs2 = __toESM(require("fs"), 1);
|
|
3410
|
+
var import_node_path = __toESM(require("path"), 1);
|
|
3411
|
+
function resolveIpcSocketPath(id = process.pid) {
|
|
3412
|
+
if (process.platform === "win32") {
|
|
3413
|
+
return `\\\\.\\pipe\\tricache-${id}`;
|
|
3414
|
+
}
|
|
3415
|
+
const dir = process.env.TMPDIR || "/tmp";
|
|
3416
|
+
return import_node_path.default.join(dir, `tricache-${id}.sock`);
|
|
3417
|
+
}
|
|
3418
|
+
var IpcTelemetryServer = class {
|
|
3419
|
+
constructor(cache, customSocketPath) {
|
|
3420
|
+
this.cache = cache;
|
|
3421
|
+
this.socketPath = customSocketPath || resolveIpcSocketPath();
|
|
3422
|
+
}
|
|
3423
|
+
cache;
|
|
3424
|
+
server = null;
|
|
3425
|
+
socketPath;
|
|
3426
|
+
_closed = false;
|
|
3427
|
+
_exitHandler = null;
|
|
3428
|
+
_sigintHandler = null;
|
|
3429
|
+
_sigtermHandler = null;
|
|
3430
|
+
/**
|
|
3431
|
+
* Start listening on the IPC socket / pipe.
|
|
3432
|
+
*/
|
|
3433
|
+
async start() {
|
|
3434
|
+
if (this.server && this.server.listening) return;
|
|
3435
|
+
if (process.platform !== "win32" && import_node_fs2.default.existsSync(this.socketPath)) {
|
|
3436
|
+
await new Promise((resolve) => {
|
|
3437
|
+
const testSocket = import_node_net.default.createConnection(this.socketPath);
|
|
3438
|
+
testSocket.once("connect", () => {
|
|
3439
|
+
testSocket.destroy();
|
|
3440
|
+
resolve();
|
|
3441
|
+
});
|
|
3442
|
+
testSocket.once("error", () => {
|
|
3443
|
+
testSocket.destroy();
|
|
3444
|
+
try {
|
|
3445
|
+
import_node_fs2.default.unlinkSync(this.socketPath);
|
|
3446
|
+
} catch {
|
|
3447
|
+
}
|
|
3448
|
+
resolve();
|
|
3449
|
+
});
|
|
3450
|
+
});
|
|
3451
|
+
}
|
|
3452
|
+
this.server = import_node_net.default.createServer((socket) => {
|
|
3453
|
+
let buffer = "";
|
|
3454
|
+
socket.on("data", (chunk) => {
|
|
3455
|
+
buffer += chunk.toString("utf8");
|
|
3456
|
+
let newlineIndex;
|
|
3457
|
+
while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
|
|
3458
|
+
const line = buffer.slice(0, newlineIndex).trim();
|
|
3459
|
+
buffer = buffer.slice(newlineIndex + 1);
|
|
3460
|
+
if (!line) continue;
|
|
3461
|
+
setImmediate(() => {
|
|
3462
|
+
if (socket.destroyed) return;
|
|
3463
|
+
try {
|
|
3464
|
+
let cmd = line;
|
|
3465
|
+
try {
|
|
3466
|
+
const parsed = JSON.parse(line);
|
|
3467
|
+
if (parsed && typeof parsed.cmd === "string") {
|
|
3468
|
+
cmd = parsed.cmd;
|
|
3469
|
+
}
|
|
3470
|
+
} catch {
|
|
3471
|
+
}
|
|
3472
|
+
if (cmd === "PING") {
|
|
3473
|
+
socket.write(JSON.stringify({ pong: true, timestamp: Date.now() }) + "\n");
|
|
3474
|
+
return;
|
|
3475
|
+
}
|
|
3476
|
+
if (cmd === "GET_METRICS" || cmd === "INSPECT") {
|
|
3477
|
+
const payload = this.getSnapshot();
|
|
3478
|
+
const serialized = JSON.stringify(payload) + "\n";
|
|
3479
|
+
socket.write(serialized);
|
|
3480
|
+
return;
|
|
3481
|
+
}
|
|
3482
|
+
socket.write(JSON.stringify({ error: `Unknown command: ${cmd}` }) + "\n");
|
|
3483
|
+
} catch (err) {
|
|
3484
|
+
if (!socket.destroyed) {
|
|
3485
|
+
socket.write(JSON.stringify({ error: err.message }) + "\n");
|
|
3486
|
+
}
|
|
3487
|
+
}
|
|
3488
|
+
});
|
|
3489
|
+
}
|
|
3490
|
+
});
|
|
3491
|
+
socket.on("error", () => {
|
|
3492
|
+
});
|
|
3493
|
+
});
|
|
3494
|
+
await new Promise((resolve, reject) => {
|
|
3495
|
+
this.server.once("error", reject);
|
|
3496
|
+
this.server.listen(this.socketPath, () => {
|
|
3497
|
+
this.server.removeListener("error", reject);
|
|
3498
|
+
resolve();
|
|
3499
|
+
});
|
|
3500
|
+
});
|
|
3501
|
+
this._exitHandler = () => this._unlinkSocket();
|
|
3502
|
+
this._sigintHandler = () => {
|
|
3503
|
+
this._unlinkSocket();
|
|
3504
|
+
process.exit(0);
|
|
3505
|
+
};
|
|
3506
|
+
this._sigtermHandler = () => {
|
|
3507
|
+
this._unlinkSocket();
|
|
3508
|
+
process.exit(0);
|
|
3509
|
+
};
|
|
3510
|
+
process.once("exit", this._exitHandler);
|
|
3511
|
+
process.once("SIGINT", this._sigintHandler);
|
|
3512
|
+
process.once("SIGTERM", this._sigtermHandler);
|
|
3513
|
+
}
|
|
3514
|
+
/**
|
|
3515
|
+
* Build a complete telemetry snapshot from the underlying cache provider.
|
|
3516
|
+
*/
|
|
3517
|
+
getSnapshot() {
|
|
3518
|
+
const metrics = this.cache.metrics();
|
|
3519
|
+
const stats = typeof this.cache.stats === "function" ? this.cache.stats() : void 0;
|
|
3520
|
+
const hotKeys = typeof this.cache.hotKeys === "function" ? this.cache.hotKeys(10) : void 0;
|
|
3521
|
+
const health = typeof this.cache.health === "function" ? this.cache.health() : void 0;
|
|
3522
|
+
const l1MaxBytes = this.cache.options?.l1MaxBytes ?? metrics.l1?.maxBytes;
|
|
3523
|
+
return {
|
|
3524
|
+
pid: process.pid,
|
|
3525
|
+
uptimeMs: metrics.uptimeMs,
|
|
3526
|
+
timestamp: Date.now(),
|
|
3527
|
+
namespace: this.cache.options?.namespace || metrics.namespace,
|
|
3528
|
+
l1MaxBytes,
|
|
3529
|
+
metrics,
|
|
3530
|
+
stats,
|
|
3531
|
+
hotKeys,
|
|
3532
|
+
health
|
|
3533
|
+
};
|
|
3534
|
+
}
|
|
3535
|
+
_unlinkSocket() {
|
|
3536
|
+
if (this._closed) return;
|
|
3537
|
+
this._closed = true;
|
|
3538
|
+
try {
|
|
3539
|
+
this.server?.close();
|
|
3540
|
+
} catch {
|
|
3541
|
+
}
|
|
3542
|
+
if (process.platform !== "win32") {
|
|
3543
|
+
try {
|
|
3544
|
+
if (import_node_fs2.default.existsSync(this.socketPath)) {
|
|
3545
|
+
import_node_fs2.default.unlinkSync(this.socketPath);
|
|
3546
|
+
}
|
|
3547
|
+
} catch {
|
|
3548
|
+
}
|
|
3549
|
+
}
|
|
3550
|
+
}
|
|
3551
|
+
/**
|
|
3552
|
+
* Gracefully close the IPC telemetry server and clean up handlers and sockets.
|
|
3553
|
+
*/
|
|
3554
|
+
async close() {
|
|
3555
|
+
if (this._exitHandler) {
|
|
3556
|
+
process.removeListener("exit", this._exitHandler);
|
|
3557
|
+
this._exitHandler = null;
|
|
3558
|
+
}
|
|
3559
|
+
if (this._sigintHandler) {
|
|
3560
|
+
process.removeListener("SIGINT", this._sigintHandler);
|
|
3561
|
+
this._sigintHandler = null;
|
|
3562
|
+
}
|
|
3563
|
+
if (this._sigtermHandler) {
|
|
3564
|
+
process.removeListener("SIGTERM", this._sigtermHandler);
|
|
3565
|
+
this._sigtermHandler = null;
|
|
3566
|
+
}
|
|
3567
|
+
this._unlinkSocket();
|
|
3568
|
+
return new Promise((resolve) => {
|
|
3569
|
+
if (!this.server || !this.server.listening) {
|
|
3570
|
+
resolve();
|
|
3571
|
+
return;
|
|
3572
|
+
}
|
|
3573
|
+
this.server.close(() => resolve());
|
|
3574
|
+
});
|
|
3575
|
+
}
|
|
3576
|
+
get isListening() {
|
|
3577
|
+
return Boolean(this.server && this.server.listening);
|
|
3578
|
+
}
|
|
3579
|
+
};
|
|
3580
|
+
|
|
3581
|
+
// src/cache-service.ts
|
|
3582
|
+
var LUA_COMPARE_AND_DELETE = `
|
|
3583
|
+
local currentTs = redis.call('HGET', KEYS[1], 't')
|
|
3584
|
+
if currentTs and currentTs == ARGV[1] then
|
|
3585
|
+
return redis.call('DEL', KEYS[1])
|
|
3586
|
+
end
|
|
3587
|
+
return 0
|
|
3588
|
+
`;
|
|
3589
|
+
var SNAPSHOT_VERSION = 1;
|
|
3590
|
+
var DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
|
|
3591
|
+
var INDEFINITE_TTL_SECONDS = 31536e3;
|
|
3592
|
+
var SNAPSHOT_MAX_FILE_BYTES = 220 * 1024 * 1024;
|
|
3593
|
+
var DEFAULT_CATEGORY_LIMITS = {
|
|
3594
|
+
"default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
|
|
3595
|
+
};
|
|
3596
|
+
var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
|
|
3597
|
+
var DEFAULT_COUNTER_TTL_SECONDS = 60;
|
|
3598
|
+
var GLOB_REGEX_CACHE_MAX = 256;
|
|
3599
|
+
var globRegexCache = /* @__PURE__ */ new Map();
|
|
3600
|
+
function getGlobRegex(pattern) {
|
|
3601
|
+
let re = globRegexCache.get(pattern);
|
|
3602
|
+
if (re) {
|
|
3603
|
+
globRegexCache.delete(pattern);
|
|
3604
|
+
globRegexCache.set(pattern, re);
|
|
3605
|
+
return re;
|
|
3606
|
+
}
|
|
3607
|
+
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*+/g, ".*");
|
|
3608
|
+
re = new RegExp("^" + escaped + "$");
|
|
3609
|
+
if (globRegexCache.size >= GLOB_REGEX_CACHE_MAX) {
|
|
3610
|
+
const oldestKey = globRegexCache.keys().next().value;
|
|
3611
|
+
if (oldestKey !== void 0) globRegexCache.delete(oldestKey);
|
|
3612
|
+
}
|
|
3613
|
+
globRegexCache.set(pattern, re);
|
|
3614
|
+
return re;
|
|
3615
|
+
}
|
|
3616
|
+
var L2CircuitBreaker = class {
|
|
3617
|
+
constructor(threshold, cooldownMs) {
|
|
3618
|
+
this.threshold = threshold;
|
|
3619
|
+
this.cooldownMs = cooldownMs;
|
|
3620
|
+
}
|
|
3621
|
+
threshold;
|
|
3622
|
+
cooldownMs;
|
|
3623
|
+
state = 0 /* CLOSED */;
|
|
3624
|
+
failures = 0;
|
|
3625
|
+
openedAt = performance.now();
|
|
3626
|
+
/** True while the single permitted HALF_OPEN probe is in flight. */
|
|
3627
|
+
probing = false;
|
|
2408
3628
|
/**
|
|
2409
3629
|
* Call before each Redis attempt. Returns false when the circuit is open.
|
|
2410
3630
|
* In HALF_OPEN, only ONE probe is permitted at a time — concurrent callers
|
|
@@ -2418,7 +3638,8 @@ var L2CircuitBreaker = class {
|
|
|
2418
3638
|
this.probing = true;
|
|
2419
3639
|
return true;
|
|
2420
3640
|
}
|
|
2421
|
-
|
|
3641
|
+
const now = this.openedAt > 1e12 ? Date.now() : performance.now();
|
|
3642
|
+
if (now - this.openedAt >= this.cooldownMs) {
|
|
2422
3643
|
this.state = 2 /* HALF_OPEN */;
|
|
2423
3644
|
this.probing = true;
|
|
2424
3645
|
return true;
|
|
@@ -2437,7 +3658,7 @@ var L2CircuitBreaker = class {
|
|
|
2437
3658
|
this.probing = false;
|
|
2438
3659
|
if (this.state === 2 /* HALF_OPEN */ || this.failures >= this.threshold) {
|
|
2439
3660
|
this.state = 1 /* OPEN */;
|
|
2440
|
-
this.openedAt =
|
|
3661
|
+
this.openedAt = performance.now();
|
|
2441
3662
|
this.failures = 0;
|
|
2442
3663
|
}
|
|
2443
3664
|
}
|
|
@@ -2554,9 +3775,86 @@ function detectServerlessRuntime() {
|
|
|
2554
3775
|
if (process.env["VERCEL"]) return "Vercel";
|
|
2555
3776
|
return null;
|
|
2556
3777
|
}
|
|
3778
|
+
var ProcessTerminationBus = class {
|
|
3779
|
+
static instances = /* @__PURE__ */ new Set();
|
|
3780
|
+
static registered = false;
|
|
3781
|
+
static sigtermHandler = null;
|
|
3782
|
+
static sigintHandler = null;
|
|
3783
|
+
static register(instance) {
|
|
3784
|
+
this.instances.add(instance);
|
|
3785
|
+
if (!this.registered) {
|
|
3786
|
+
this.registered = true;
|
|
3787
|
+
this.sigtermHandler = () => {
|
|
3788
|
+
for (const inst of this.instances) {
|
|
3789
|
+
try {
|
|
3790
|
+
inst._triggerShutdown();
|
|
3791
|
+
} catch {
|
|
3792
|
+
}
|
|
3793
|
+
}
|
|
3794
|
+
};
|
|
3795
|
+
this.sigintHandler = () => {
|
|
3796
|
+
for (const inst of this.instances) {
|
|
3797
|
+
try {
|
|
3798
|
+
inst._triggerShutdown();
|
|
3799
|
+
} catch {
|
|
3800
|
+
}
|
|
3801
|
+
}
|
|
3802
|
+
};
|
|
3803
|
+
process.on("SIGTERM", this.sigtermHandler);
|
|
3804
|
+
process.on("SIGINT", this.sigintHandler);
|
|
3805
|
+
}
|
|
3806
|
+
}
|
|
3807
|
+
static unregister(instance) {
|
|
3808
|
+
this.instances.delete(instance);
|
|
3809
|
+
if (this.instances.size === 0 && this.registered) {
|
|
3810
|
+
if (this.sigtermHandler) process.removeListener("SIGTERM", this.sigtermHandler);
|
|
3811
|
+
if (this.sigintHandler) process.removeListener("SIGINT", this.sigintHandler);
|
|
3812
|
+
this.sigtermHandler = null;
|
|
3813
|
+
this.sigintHandler = null;
|
|
3814
|
+
this.registered = false;
|
|
3815
|
+
}
|
|
3816
|
+
}
|
|
3817
|
+
/**
|
|
3818
|
+
* Flushes snapshots across all active registered cache instances concurrently.
|
|
3819
|
+
* Awaits both local disk and remote cloud snapshot uploads with timeout protection.
|
|
3820
|
+
*
|
|
3821
|
+
* @param timeoutMs Timeout in milliseconds per instance before aborting slow flushes. Default: 8000ms.
|
|
3822
|
+
*/
|
|
3823
|
+
static async flushAll(timeoutMs = 8e3) {
|
|
3824
|
+
if (this.instances.size === 0) return;
|
|
3825
|
+
const tasks = Array.from(this.instances).map((inst) => inst.flushSnapshotOnShutdown(timeoutMs));
|
|
3826
|
+
await Promise.allSettled(tasks);
|
|
3827
|
+
}
|
|
3828
|
+
/** For testing diagnostics and assertions */
|
|
3829
|
+
static get size() {
|
|
3830
|
+
return this.instances.size;
|
|
3831
|
+
}
|
|
3832
|
+
static get isRegistered() {
|
|
3833
|
+
return this.registered;
|
|
3834
|
+
}
|
|
3835
|
+
};
|
|
3836
|
+
function isPlainObject(item) {
|
|
3837
|
+
return typeof item === "object" && item !== null && item.constructor === Object;
|
|
3838
|
+
}
|
|
3839
|
+
function deepMergeOptions(base, overrides) {
|
|
3840
|
+
if (!overrides) return { ...base };
|
|
3841
|
+
const output = { ...base };
|
|
3842
|
+
for (const key of Object.keys(overrides)) {
|
|
3843
|
+
const sourceVal = overrides[key];
|
|
3844
|
+
if (sourceVal === void 0) continue;
|
|
3845
|
+
const targetVal = output[key];
|
|
3846
|
+
if (isPlainObject(targetVal) && isPlainObject(sourceVal)) {
|
|
3847
|
+
output[key] = deepMergeOptions(targetVal, sourceVal);
|
|
3848
|
+
} else {
|
|
3849
|
+
output[key] = sourceVal;
|
|
3850
|
+
}
|
|
3851
|
+
}
|
|
3852
|
+
return output;
|
|
3853
|
+
}
|
|
2557
3854
|
var CacheService = class _CacheService {
|
|
2558
3855
|
logger;
|
|
2559
3856
|
enc;
|
|
3857
|
+
codec;
|
|
2560
3858
|
l1;
|
|
2561
3859
|
disk;
|
|
2562
3860
|
/** When true, all disk-tier and snapshot operations are skipped. */
|
|
@@ -2568,6 +3866,8 @@ var CacheService = class _CacheService {
|
|
|
2568
3866
|
_namespace;
|
|
2569
3867
|
/** Pre-computed once — disableRedis and redisHost never change after construction. */
|
|
2570
3868
|
_redisDisabled;
|
|
3869
|
+
watchdog;
|
|
3870
|
+
pipeliner = null;
|
|
2571
3871
|
inflight = /* @__PURE__ */ new Map();
|
|
2572
3872
|
revalidating = /* @__PURE__ */ new Set();
|
|
2573
3873
|
_l1Counters = /* @__PURE__ */ new Map();
|
|
@@ -2593,6 +3893,7 @@ var CacheService = class _CacheService {
|
|
|
2593
3893
|
diskJanitorInterval = null;
|
|
2594
3894
|
oomInterval = null;
|
|
2595
3895
|
metricsInterval = null;
|
|
3896
|
+
remoteSnapshotInterval = null;
|
|
2596
3897
|
_shutdownHandler = null;
|
|
2597
3898
|
latencyTracker = null;
|
|
2598
3899
|
instanceId;
|
|
@@ -2602,8 +3903,57 @@ var CacheService = class _CacheService {
|
|
|
2602
3903
|
streamClient = null;
|
|
2603
3904
|
_lastStreamId = "$";
|
|
2604
3905
|
_destroyed = false;
|
|
3906
|
+
_pendingDiskDeletes = /* @__PURE__ */ new Set();
|
|
3907
|
+
_globalEpoch = 0;
|
|
3908
|
+
_keyMutationEpochs = /* @__PURE__ */ new Map();
|
|
3909
|
+
/**
|
|
3910
|
+
* Pattern tombstones for disk tier.
|
|
3911
|
+
* Files in the disk tier are keyed by SHA-256 of namespacedKey.
|
|
3912
|
+
* Wildcard pattern deletes cannot scan the filesystem synchronously, so we maintain
|
|
3913
|
+
* pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
|
|
3914
|
+
*/
|
|
3915
|
+
_patternTombstones = [];
|
|
3916
|
+
_addPatternTombstone(prefix) {
|
|
3917
|
+
const now = Date.now();
|
|
3918
|
+
while (this._patternTombstones.length > 0 && now - this._patternTombstones[0].createdAt > 36e5) {
|
|
3919
|
+
this._patternTombstones.shift();
|
|
3920
|
+
}
|
|
3921
|
+
if (this._patternTombstones.length >= 2e3) {
|
|
3922
|
+
this._patternTombstones.shift();
|
|
3923
|
+
}
|
|
3924
|
+
this._patternTombstones.push({ prefix, createdAt: now });
|
|
3925
|
+
}
|
|
3926
|
+
_isTombstonedByPattern(namespacedKey) {
|
|
3927
|
+
if (this._patternTombstones.length === 0) return false;
|
|
3928
|
+
for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
|
|
3929
|
+
if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
|
|
3930
|
+
return true;
|
|
3931
|
+
}
|
|
3932
|
+
}
|
|
3933
|
+
return false;
|
|
3934
|
+
}
|
|
3935
|
+
_assertActive(operation) {
|
|
3936
|
+
if (this._destroyed) {
|
|
3937
|
+
throw new Error(`TriCacheError: Cannot perform '${operation}' on a destroyed CacheService instance (namespace: '${this._namespace || "(default)"}').`);
|
|
3938
|
+
}
|
|
3939
|
+
}
|
|
3940
|
+
_bumpKeyMutation(namespacedKey) {
|
|
3941
|
+
const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
|
|
3942
|
+
this._keyMutationEpochs.set(namespacedKey, next);
|
|
3943
|
+
if (this._keyMutationEpochs.size > 5e4) {
|
|
3944
|
+
const oldest = this._keyMutationEpochs.keys().next().value;
|
|
3945
|
+
if (oldest !== void 0) this._keyMutationEpochs.delete(oldest);
|
|
3946
|
+
}
|
|
3947
|
+
return next;
|
|
3948
|
+
}
|
|
3949
|
+
_getKeyMutationEpoch(namespacedKey) {
|
|
3950
|
+
return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
|
|
3951
|
+
}
|
|
3952
|
+
_ipcServer;
|
|
2605
3953
|
/** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
|
|
2606
3954
|
_subDisconnectedAt = null;
|
|
3955
|
+
/** Deduplication ring buffer for incoming and outgoing cross-region invalidations (loop prevention) */
|
|
3956
|
+
_seenCrossRegionEvents = /* @__PURE__ */ new Map();
|
|
2607
3957
|
counters = {
|
|
2608
3958
|
gets: 0,
|
|
2609
3959
|
l1Hits: 0,
|
|
@@ -2628,7 +3978,16 @@ var CacheService = class _CacheService {
|
|
|
2628
3978
|
singletonDivergences: 0,
|
|
2629
3979
|
startedAt: Date.now(),
|
|
2630
3980
|
bloomChecks: 0,
|
|
2631
|
-
bloomFalsePositives: 0
|
|
3981
|
+
bloomFalsePositives: 0,
|
|
3982
|
+
remoteSnapshotUploads: 0,
|
|
3983
|
+
remoteSnapshotDownloads: 0,
|
|
3984
|
+
remoteSnapshotErrors: 0,
|
|
3985
|
+
remoteSnapshotLastUploadedAt: null,
|
|
3986
|
+
remoteSnapshotLastDownloadedAt: null,
|
|
3987
|
+
crossRegionSent: 0,
|
|
3988
|
+
crossRegionReceived: 0,
|
|
3989
|
+
crossRegionDeduplicated: 0,
|
|
3990
|
+
crossRegionErrors: 0
|
|
2632
3991
|
};
|
|
2633
3992
|
/** One-time guard so the in-process increment() fallback warning fires only once. */
|
|
2634
3993
|
_incrementFallbackWarned = false;
|
|
@@ -2651,16 +4010,14 @@ var CacheService = class _CacheService {
|
|
|
2651
4010
|
this.opts = {
|
|
2652
4011
|
namespace: ns,
|
|
2653
4012
|
logger,
|
|
2654
|
-
l1MaxBytes: options.l1MaxBytes ??
|
|
4013
|
+
l1MaxBytes: options.l1MaxBytes ?? resolveAutonomousL1MaxBytes(),
|
|
2655
4014
|
l1MaxEntries: options.l1MaxEntries ?? 2e3,
|
|
2656
4015
|
categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...options.categoryLimits },
|
|
2657
4016
|
forbiddenSnapshotPrefixes: forbiddenPrefixes,
|
|
2658
4017
|
// Namespace-isolated defaults: separate dir / snapshot per namespace so
|
|
2659
4018
|
// two instances with different namespaces never share cache files.
|
|
2660
|
-
|
|
2661
|
-
|
|
2662
|
-
ns ? `tricache-disk-${ns}` : "tricache-disk"
|
|
2663
|
-
),
|
|
4019
|
+
// Automatically probes /dev/shm tmpfs on Linux (>=256MB capacity and >=128MB free) for off-heap RAM speed.
|
|
4020
|
+
diskCacheDir: options.diskCacheDir ?? resolveDefaultDiskDir(ns, logger).dir,
|
|
2664
4021
|
diskMaxBytes: options.diskMaxBytes ?? 500 * 1024 * 1024,
|
|
2665
4022
|
diskEntryMaxBytes: options.diskEntryMaxBytes ?? 10 * 1024 * 1024,
|
|
2666
4023
|
redisHost: options.redisHost ?? process.env.REDIS_HOST ?? "",
|
|
@@ -2668,18 +4025,20 @@ var CacheService = class _CacheService {
|
|
|
2668
4025
|
redisTls: options.redisTls ?? process.env.NODE_ENV === "production",
|
|
2669
4026
|
disableRedis: options.disableRedis ?? (() => {
|
|
2670
4027
|
const explicitConfig = Boolean(
|
|
2671
|
-
options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
|
|
4028
|
+
options.redisClient || options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
|
|
2672
4029
|
);
|
|
2673
4030
|
return !explicitConfig && process.env.NODE_ENV !== "production";
|
|
2674
4031
|
})(),
|
|
2675
4032
|
encryptionKey: encKeyRaw,
|
|
2676
4033
|
encryptionMode: options.encryptionMode,
|
|
2677
4034
|
snapshotPath: options.snapshotPath ?? import_path3.default.join(
|
|
2678
|
-
|
|
4035
|
+
import_os3.default.tmpdir(),
|
|
2679
4036
|
ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
|
|
2680
4037
|
),
|
|
2681
4038
|
snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
|
|
2682
4039
|
invalidationBackplane: options.invalidationBackplane ?? true,
|
|
4040
|
+
awaitInvalidationBackplane: options.awaitInvalidationBackplane ?? false,
|
|
4041
|
+
lockFailClosed: options.lockFailClosed ?? false,
|
|
2683
4042
|
oomProtection: options.oomProtection ?? true,
|
|
2684
4043
|
oomHeapThreshold: options.oomHeapThreshold ?? 0.85,
|
|
2685
4044
|
oomCheckIntervalMs: options.oomCheckIntervalMs ?? 1e4,
|
|
@@ -2723,8 +4082,35 @@ var CacheService = class _CacheService {
|
|
|
2723
4082
|
backplaneMode: options.backplaneMode ?? "pubsub",
|
|
2724
4083
|
backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
|
|
2725
4084
|
backplaneStreamBlockMs: options.backplaneStreamBlockMs ?? 2e3,
|
|
2726
|
-
backplaneStreamKey: options.backplaneStreamKey
|
|
4085
|
+
backplaneStreamKey: options.backplaneStreamKey,
|
|
4086
|
+
serializeToJSON: options.serializeToJSON ?? true,
|
|
4087
|
+
remoteSnapshot: options.remoteSnapshot,
|
|
4088
|
+
crossRegion: options.crossRegion,
|
|
4089
|
+
redisClient: options.redisClient,
|
|
4090
|
+
redisSubClient: options.redisSubClient,
|
|
4091
|
+
diskMaxConcurrentWrites: options.diskMaxConcurrentWrites,
|
|
4092
|
+
diskMaxPendingWrites: options.diskMaxPendingWrites,
|
|
4093
|
+
diskWriteTimeoutMs: options.diskWriteTimeoutMs,
|
|
4094
|
+
diskCircuitBreakerThreshold: options.diskCircuitBreakerThreshold,
|
|
4095
|
+
diskCircuitBreakerCooldownMs: options.diskCircuitBreakerCooldownMs,
|
|
4096
|
+
redisCommandTimeoutMs: options.redisCommandTimeoutMs,
|
|
4097
|
+
clockSkewToleranceMs: options.clockSkewToleranceMs ?? 250,
|
|
4098
|
+
l1AdmissionPolicy: options.l1AdmissionPolicy,
|
|
4099
|
+
diskLatencyWatchdog: options.diskLatencyWatchdog ?? true,
|
|
4100
|
+
diskLatencyBypassRatio: options.diskLatencyBypassRatio ?? 1.5,
|
|
4101
|
+
diskLatencyBypassMinMs: options.diskLatencyBypassMinMs ?? 10,
|
|
4102
|
+
diskLatencyBypassCooldownMs: options.diskLatencyBypassCooldownMs ?? 3e4,
|
|
4103
|
+
failReadinessOnDegraded: options.failReadinessOnDegraded ?? false,
|
|
4104
|
+
autoPipeline: options.autoPipeline ?? false,
|
|
4105
|
+
maxPipelineBatchSize: options.maxPipelineBatchSize ?? 100,
|
|
4106
|
+
enableIpc: options.enableIpc ?? false,
|
|
4107
|
+
ipcSocketPath: options.ipcSocketPath
|
|
2727
4108
|
};
|
|
4109
|
+
this.codec = new CacheCodec({
|
|
4110
|
+
useToJSON: this.opts.serializeToJSON,
|
|
4111
|
+
useRecords: true,
|
|
4112
|
+
moreTypes: true
|
|
4113
|
+
});
|
|
2728
4114
|
const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
|
|
2729
4115
|
const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
|
|
2730
4116
|
this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
|
|
@@ -2755,15 +4141,33 @@ var CacheService = class _CacheService {
|
|
|
2755
4141
|
encryption: this.enc.isEnabled ? this.enc : null,
|
|
2756
4142
|
compression: this.opts.compression,
|
|
2757
4143
|
compressionThresholdBytes: this.opts.compressionThresholdBytes,
|
|
2758
|
-
logger
|
|
4144
|
+
logger,
|
|
4145
|
+
codec: this.codec,
|
|
4146
|
+
diskMaxConcurrentWrites: this.opts.diskMaxConcurrentWrites,
|
|
4147
|
+
diskMaxPendingWrites: this.opts.diskMaxPendingWrites,
|
|
4148
|
+
diskWriteTimeoutMs: this.opts.diskWriteTimeoutMs,
|
|
4149
|
+
diskCircuitBreakerThreshold: this.opts.diskCircuitBreakerThreshold,
|
|
4150
|
+
diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs
|
|
2759
4151
|
});
|
|
2760
4152
|
this._namespace = ns;
|
|
2761
|
-
this._redisDisabled = this.opts.disableRedis || !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
|
|
4153
|
+
this._redisDisabled = this.opts.disableRedis || !this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
|
|
4154
|
+
this.watchdog = new TierLatencyWatchdog({
|
|
4155
|
+
enabled: options.diskLatencyWatchdog ?? true,
|
|
4156
|
+
minDiskBypassMs: options.diskLatencyBypassMinMs ?? 10,
|
|
4157
|
+
bypassRatio: options.diskLatencyBypassRatio ?? 1.5,
|
|
4158
|
+
cooldownMs: options.diskLatencyBypassCooldownMs ?? 3e4,
|
|
4159
|
+
redisCutoffMs: 15,
|
|
4160
|
+
redisRecoveryFloorMs: 10,
|
|
4161
|
+
minSamples: 16,
|
|
4162
|
+
disableRedis: this._redisDisabled
|
|
4163
|
+
});
|
|
2762
4164
|
this.l1 = new SmartMemoryCache({
|
|
2763
4165
|
maxBytes: this.opts.l1MaxBytes,
|
|
2764
4166
|
maxEntries: this.opts.l1MaxEntries,
|
|
2765
4167
|
categories: this.opts.categoryLimits,
|
|
2766
4168
|
evictionWatermark: this.opts.l1EvictionWatermark,
|
|
4169
|
+
admissionPolicy: this.opts.l1AdmissionPolicy,
|
|
4170
|
+
codec: this.codec,
|
|
2767
4171
|
diskSpill: (key, entry) => {
|
|
2768
4172
|
if (this._diskDisabled) return;
|
|
2769
4173
|
setImmediate(() => {
|
|
@@ -2778,10 +4182,9 @@ var CacheService = class _CacheService {
|
|
|
2778
4182
|
if (!this._diskDisabled) this.loadSnapshot();
|
|
2779
4183
|
}
|
|
2780
4184
|
this._shutdownHandler = () => {
|
|
2781
|
-
|
|
4185
|
+
this._triggerShutdown();
|
|
2782
4186
|
};
|
|
2783
|
-
|
|
2784
|
-
process.once("SIGINT", this._shutdownHandler);
|
|
4187
|
+
ProcessTerminationBus.register(this);
|
|
2785
4188
|
if (this.opts.workerThreads) {
|
|
2786
4189
|
try {
|
|
2787
4190
|
const encRef = this.enc.toWorkerInit();
|
|
@@ -2821,7 +4224,7 @@ var CacheService = class _CacheService {
|
|
|
2821
4224
|
}
|
|
2822
4225
|
if (this.opts.oomProtection) {
|
|
2823
4226
|
this.oomInterval = setInterval(() => {
|
|
2824
|
-
const heap =
|
|
4227
|
+
const heap = import_node_v82.default.getHeapStatistics();
|
|
2825
4228
|
const used = heap.used_heap_size / heap.heap_size_limit;
|
|
2826
4229
|
if (used >= this.opts.oomHeapThreshold) {
|
|
2827
4230
|
const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
|
|
@@ -2845,12 +4248,25 @@ var CacheService = class _CacheService {
|
|
|
2845
4248
|
}, this.opts.metricsIntervalMs);
|
|
2846
4249
|
if (this.metricsInterval.unref) this.metricsInterval.unref();
|
|
2847
4250
|
}
|
|
4251
|
+
if (this.opts.remoteSnapshot?.intervalMs && this.opts.remoteSnapshot.intervalMs > 0) {
|
|
4252
|
+
this.remoteSnapshotInterval = setInterval(() => {
|
|
4253
|
+
void this.writeRemoteSnapshot();
|
|
4254
|
+
}, this.opts.remoteSnapshot.intervalMs);
|
|
4255
|
+
if (this.remoteSnapshotInterval.unref) this.remoteSnapshotInterval.unref();
|
|
4256
|
+
}
|
|
2848
4257
|
this.instanceId = import_crypto3.default.randomBytes(8).toString("hex");
|
|
2849
4258
|
this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
|
|
2850
4259
|
this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
|
|
2851
4260
|
this.initBackplane();
|
|
4261
|
+
const startupPromises = [];
|
|
4262
|
+
if (this.opts.remoteSnapshot) {
|
|
4263
|
+
startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
|
|
4264
|
+
}
|
|
2852
4265
|
if (this.opts.warmKeys) {
|
|
2853
|
-
|
|
4266
|
+
startupPromises.push(this.warmFromL2(this.opts.warmKeys).then(() => void 0));
|
|
4267
|
+
}
|
|
4268
|
+
if (startupPromises.length > 0) {
|
|
4269
|
+
this._readyPromise = Promise.all(startupPromises).then(() => void 0);
|
|
2854
4270
|
}
|
|
2855
4271
|
if (this.opts.meter) {
|
|
2856
4272
|
this._initOtelMetrics(this.opts.meter);
|
|
@@ -2871,8 +4287,71 @@ var CacheService = class _CacheService {
|
|
|
2871
4287
|
}
|
|
2872
4288
|
});
|
|
2873
4289
|
}
|
|
4290
|
+
if (this.opts.enableIpc) {
|
|
4291
|
+
this._ipcServer = new IpcTelemetryServer(this, this.opts.ipcSocketPath);
|
|
4292
|
+
this._ipcServer.start().catch((err) => {
|
|
4293
|
+
this.logger.warn("Failed to start IPC telemetry server", { error: err.message });
|
|
4294
|
+
});
|
|
4295
|
+
}
|
|
4296
|
+
}
|
|
4297
|
+
// ── Singleton factory & Presets ───────────────────────────────────────────
|
|
4298
|
+
/**
|
|
4299
|
+
* Pre-configured production presets tailored for specific deployment environments.
|
|
4300
|
+
*
|
|
4301
|
+
* - `'nextjs'`: W-TinyLFU, zero-copy cloneStrategy: 'none' (React 19 RSC stream optimized),
|
|
4302
|
+
* generational tags, and Redis stream backplane.
|
|
4303
|
+
* - `'microservice'`: High-throughput Node.js microservice with W-TinyLFU, Streams backplane,
|
|
4304
|
+
* TTL jitter, and L2 circuit breaking.
|
|
4305
|
+
* - `'serverless'`: Stateless Lambda / Cloud Run isolate with memory-only L1, fast timeouts,
|
|
4306
|
+
* and Pub/Sub backplane.
|
|
4307
|
+
* - `'enterprise-hardened'`: Zero-trust production setup with generational tagging, Streams backplane,
|
|
4308
|
+
* fail-closed rate-limits, strict singleton assertions, and 80% OOM guard.
|
|
4309
|
+
*
|
|
4310
|
+
* @param type The preset identifier ('nextjs' | 'microservice' | 'serverless' | 'enterprise-hardened')
|
|
4311
|
+
* @param overrides Optional configuration overrides merged deeply over preset defaults
|
|
4312
|
+
* @returns Singleton CacheService instance configured according to the preset
|
|
4313
|
+
*/
|
|
4314
|
+
static preset(type, overrides) {
|
|
4315
|
+
const PRESETS = {
|
|
4316
|
+
"nextjs": {
|
|
4317
|
+
l1AdmissionPolicy: "wtinylfu",
|
|
4318
|
+
cloneStrategy: "none",
|
|
4319
|
+
tagStrategy: "generational",
|
|
4320
|
+
tagVersionTtlMs: 2e3,
|
|
4321
|
+
backplaneMode: "stream",
|
|
4322
|
+
staleIfError: 300,
|
|
4323
|
+
compression: "none"
|
|
4324
|
+
},
|
|
4325
|
+
"microservice": {
|
|
4326
|
+
l1AdmissionPolicy: "wtinylfu",
|
|
4327
|
+
backplaneMode: "stream",
|
|
4328
|
+
ttlJitterFactor: 0.15,
|
|
4329
|
+
l2CircuitBreakerThreshold: 5,
|
|
4330
|
+
l2CircuitBreakerCooldownMs: 15e3
|
|
4331
|
+
},
|
|
4332
|
+
"serverless": {
|
|
4333
|
+
disableDisk: true,
|
|
4334
|
+
l1AdmissionPolicy: "wtinylfu",
|
|
4335
|
+
backplaneMode: "pubsub",
|
|
4336
|
+
redisCommandTimeoutMs: 1e3
|
|
4337
|
+
},
|
|
4338
|
+
"enterprise-hardened": {
|
|
4339
|
+
l1AdmissionPolicy: "wtinylfu",
|
|
4340
|
+
tagStrategy: "generational",
|
|
4341
|
+
backplaneMode: "stream",
|
|
4342
|
+
strictSingleton: true,
|
|
4343
|
+
failClosed: true,
|
|
4344
|
+
oomProtection: true,
|
|
4345
|
+
oomHeapThreshold: 0.8
|
|
4346
|
+
}
|
|
4347
|
+
};
|
|
4348
|
+
const base = PRESETS[type];
|
|
4349
|
+
if (!base) {
|
|
4350
|
+
throw new Error(`tricache: unknown preset '${type}'. Supported presets: 'nextjs', 'microservice', 'serverless', 'enterprise-hardened'`);
|
|
4351
|
+
}
|
|
4352
|
+
const merged = deepMergeOptions(base, overrides);
|
|
4353
|
+
return _CacheService.create(merged);
|
|
2874
4354
|
}
|
|
2875
|
-
// ── Singleton factory ─────────────────────────────────────────────────────
|
|
2876
4355
|
/**
|
|
2877
4356
|
* Get (or create) the process-level singleton CacheService instance.
|
|
2878
4357
|
*
|
|
@@ -2925,7 +4404,9 @@ var CacheService = class _CacheService {
|
|
|
2925
4404
|
"adaptiveTtl",
|
|
2926
4405
|
"l2WriteMode",
|
|
2927
4406
|
"instanceName",
|
|
2928
|
-
"invalidationBackplane"
|
|
4407
|
+
"invalidationBackplane",
|
|
4408
|
+
"awaitInvalidationBackplane",
|
|
4409
|
+
"lockFailClosed"
|
|
2929
4410
|
];
|
|
2930
4411
|
/** Returns the names of options that differ between `a` and the live `b`. */
|
|
2931
4412
|
static optionsDiff(a, b) {
|
|
@@ -2966,7 +4447,11 @@ var CacheService = class _CacheService {
|
|
|
2966
4447
|
frozen: o.frozen,
|
|
2967
4448
|
adaptiveTtl: o.adaptiveTtl,
|
|
2968
4449
|
invalidationBackplane: o.invalidationBackplane,
|
|
2969
|
-
|
|
4450
|
+
awaitInvalidationBackplane: o.awaitInvalidationBackplane,
|
|
4451
|
+
lockFailClosed: o.lockFailClosed,
|
|
4452
|
+
strictSingleton: o.strictSingleton,
|
|
4453
|
+
remoteSnapshot: o.remoteSnapshot,
|
|
4454
|
+
crossRegion: o.crossRegion
|
|
2970
4455
|
};
|
|
2971
4456
|
}
|
|
2972
4457
|
/**
|
|
@@ -3025,15 +4510,30 @@ var CacheService = class _CacheService {
|
|
|
3025
4510
|
setStatus() {
|
|
3026
4511
|
return this;
|
|
3027
4512
|
},
|
|
4513
|
+
recordException() {
|
|
4514
|
+
return this;
|
|
4515
|
+
},
|
|
3028
4516
|
end() {
|
|
3029
4517
|
}
|
|
3030
4518
|
};
|
|
3031
4519
|
/** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
|
|
3032
|
-
_startSpan(name) {
|
|
3033
|
-
if (this.opts.tracer)
|
|
4520
|
+
_startSpan(name, links) {
|
|
4521
|
+
if (this.opts.tracer) {
|
|
4522
|
+
const span = this.opts.tracer.startSpan(name, links?.length ? { links } : void 0);
|
|
4523
|
+
if (this.opts.namespace) {
|
|
4524
|
+
span.setAttribute("cache.namespace", this.opts.namespace);
|
|
4525
|
+
}
|
|
4526
|
+
return span;
|
|
4527
|
+
}
|
|
3034
4528
|
return _CacheService._nullSpan;
|
|
3035
4529
|
}
|
|
3036
4530
|
createDedicatedRedisClient() {
|
|
4531
|
+
if (this.opts.redisSubClient) {
|
|
4532
|
+
return this.opts.redisSubClient;
|
|
4533
|
+
}
|
|
4534
|
+
if (this.opts.redisClient && typeof this.opts.redisClient.duplicate === "function") {
|
|
4535
|
+
return this.opts.redisClient.duplicate();
|
|
4536
|
+
}
|
|
3037
4537
|
if (this.opts.redisClusterNodes?.length) {
|
|
3038
4538
|
return new import_ioredis.Cluster(this.opts.redisClusterNodes, {
|
|
3039
4539
|
redisOptions: {
|
|
@@ -3234,16 +4734,36 @@ var CacheService = class _CacheService {
|
|
|
3234
4734
|
_applyInvalidationEvent(op, key, tagVersion) {
|
|
3235
4735
|
if (op === "del") {
|
|
3236
4736
|
this.l1.delete(key);
|
|
4737
|
+
this._bumpKeyMutation(key);
|
|
4738
|
+
this.inflight.delete(key);
|
|
4739
|
+
this._pendingDiskDeletes.add(key);
|
|
3237
4740
|
setImmediate(() => {
|
|
3238
|
-
|
|
4741
|
+
try {
|
|
4742
|
+
if (!this._diskDisabled) this.disk.delete(key);
|
|
4743
|
+
} finally {
|
|
4744
|
+
this._pendingDiskDeletes.delete(key);
|
|
4745
|
+
}
|
|
3239
4746
|
});
|
|
3240
4747
|
this._cascadeDependencies(key);
|
|
3241
4748
|
} else if (op === "del-glob") {
|
|
3242
4749
|
this.l1.deletePattern(key);
|
|
4750
|
+
const pfx = key.endsWith("*") ? key.slice(0, -1) : key;
|
|
4751
|
+
for (const liveKey of this.l1.liveKeys()) {
|
|
4752
|
+
if (liveKey.startsWith(pfx)) {
|
|
4753
|
+
this._bumpKeyMutation(liveKey);
|
|
4754
|
+
}
|
|
4755
|
+
}
|
|
4756
|
+
for (const inflightKey of Array.from(this.inflight.keys())) {
|
|
4757
|
+
if (inflightKey.startsWith(pfx)) {
|
|
4758
|
+
this._bumpKeyMutation(inflightKey);
|
|
4759
|
+
this.inflight.delete(inflightKey);
|
|
4760
|
+
}
|
|
4761
|
+
}
|
|
4762
|
+
this._addPatternTombstone(pfx);
|
|
3243
4763
|
} else if (op === "tag_incr") {
|
|
3244
4764
|
const tag = key;
|
|
3245
4765
|
const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
3246
|
-
this._setLocalTagVersion(tag, ver,
|
|
4766
|
+
this._setLocalTagVersion(tag, ver, performance.now());
|
|
3247
4767
|
}
|
|
3248
4768
|
this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
|
|
3249
4769
|
}
|
|
@@ -3267,7 +4787,17 @@ var CacheService = class _CacheService {
|
|
|
3267
4787
|
this.logger.warn("Backplane: malformed message JSON parse failed");
|
|
3268
4788
|
}
|
|
3269
4789
|
}
|
|
3270
|
-
async publishInvalidation(op, key, tagVersion) {
|
|
4790
|
+
async publishInvalidation(op, key, tagVersion, isCrossRegionRelay = false, isExplicitInvalidation = false) {
|
|
4791
|
+
if (!isCrossRegionRelay && this.opts.crossRegion) {
|
|
4792
|
+
const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
|
|
4793
|
+
if (shouldBroadcast) {
|
|
4794
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
4795
|
+
await this._broadcastCrossRegion(op, key, tagVersion);
|
|
4796
|
+
} else {
|
|
4797
|
+
void this._broadcastCrossRegion(op, key, tagVersion);
|
|
4798
|
+
}
|
|
4799
|
+
}
|
|
4800
|
+
}
|
|
3271
4801
|
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
3272
4802
|
try {
|
|
3273
4803
|
const client = await this.getRedis();
|
|
@@ -3306,10 +4836,87 @@ var CacheService = class _CacheService {
|
|
|
3306
4836
|
);
|
|
3307
4837
|
}
|
|
3308
4838
|
this.counters.invSent++;
|
|
3309
|
-
} catch {
|
|
4839
|
+
} catch (err) {
|
|
4840
|
+
this.logger.warn("Backplane invalidation publish failed", { op, key, error: err.message });
|
|
4841
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
4842
|
+
throw err;
|
|
4843
|
+
}
|
|
4844
|
+
}
|
|
4845
|
+
}
|
|
4846
|
+
_markCrossRegionEventSeen(id) {
|
|
4847
|
+
const maxDedup = this.opts.crossRegion?.dedupCacheSize ?? 1e4;
|
|
4848
|
+
if (this._seenCrossRegionEvents.size >= maxDedup) {
|
|
4849
|
+
const oldestKey = this._seenCrossRegionEvents.keys().next().value;
|
|
4850
|
+
if (oldestKey !== void 0) this._seenCrossRegionEvents.delete(oldestKey);
|
|
4851
|
+
}
|
|
4852
|
+
this._seenCrossRegionEvents.set(id, Date.now());
|
|
4853
|
+
}
|
|
4854
|
+
_isCrossRegionEventSeen(id) {
|
|
4855
|
+
return this._seenCrossRegionEvents.has(id);
|
|
4856
|
+
}
|
|
4857
|
+
async _broadcastCrossRegion(op, key, tagVersion) {
|
|
4858
|
+
const cr = this.opts.crossRegion;
|
|
4859
|
+
if (!cr) return;
|
|
4860
|
+
try {
|
|
4861
|
+
const eventId = import_crypto3.default.randomUUID();
|
|
4862
|
+
this._markCrossRegionEventSeen(eventId);
|
|
4863
|
+
const event = {
|
|
4864
|
+
id: eventId,
|
|
4865
|
+
originRegion: cr.currentRegion,
|
|
4866
|
+
originInstanceId: this.instanceId,
|
|
4867
|
+
op,
|
|
4868
|
+
key,
|
|
4869
|
+
tagVersion,
|
|
4870
|
+
timestamp: Date.now(),
|
|
4871
|
+
namespace: this._namespace || void 0
|
|
4872
|
+
};
|
|
4873
|
+
this.counters.crossRegionSent++;
|
|
4874
|
+
await cr.relay.broadcast(event);
|
|
4875
|
+
this.logger.debug("Cross-region invalidation broadcast", { op, key, region: cr.currentRegion });
|
|
4876
|
+
} catch (err) {
|
|
4877
|
+
this.counters.crossRegionSent = Math.max(0, this.counters.crossRegionSent - 1);
|
|
4878
|
+
this.counters.crossRegionErrors++;
|
|
4879
|
+
this.logger.warn("Cross-region invalidation broadcast failed", { error: err.message });
|
|
4880
|
+
}
|
|
4881
|
+
}
|
|
4882
|
+
/**
|
|
4883
|
+
* Receives an invalidation event from another region (e.g. via HTTP webhook or broker subscriber).
|
|
4884
|
+
* Validates origin, deduplicates to prevent loops, applies locally to L1/disk,
|
|
4885
|
+
* and fans out to the local Redis backplane so all regional peers invalidate as well.
|
|
4886
|
+
*
|
|
4887
|
+
* Returns true if the event was accepted and applied, or false if ignored/deduplicated.
|
|
4888
|
+
*/
|
|
4889
|
+
async receiveCrossRegionInvalidation(event) {
|
|
4890
|
+
const cr = this.opts.crossRegion;
|
|
4891
|
+
if (!cr) return false;
|
|
4892
|
+
if (!event || typeof event !== "object" || !event.id || !event.originRegion || !event.op || !event.key) {
|
|
4893
|
+
this.counters.crossRegionErrors++;
|
|
4894
|
+
this.logger.warn("Cross-region: rejected invalid event payload", { event });
|
|
4895
|
+
return false;
|
|
4896
|
+
}
|
|
4897
|
+
if (event.originRegion === cr.currentRegion) {
|
|
4898
|
+
this.counters.crossRegionDeduplicated++;
|
|
4899
|
+
return false;
|
|
3310
4900
|
}
|
|
4901
|
+
if (this._isCrossRegionEventSeen(event.id)) {
|
|
4902
|
+
this.counters.crossRegionDeduplicated++;
|
|
4903
|
+
return false;
|
|
4904
|
+
}
|
|
4905
|
+
this._markCrossRegionEventSeen(event.id);
|
|
4906
|
+
if (event.namespace !== void 0 && event.namespace !== (this._namespace || void 0)) {
|
|
4907
|
+
return false;
|
|
4908
|
+
}
|
|
4909
|
+
this.counters.crossRegionReceived++;
|
|
4910
|
+
this._applyInvalidationEvent(event.op, event.key, event.tagVersion);
|
|
4911
|
+
void this.publishInvalidation(event.op, event.key, event.tagVersion, true);
|
|
4912
|
+
this.logger.info("Cross-region invalidation applied", {
|
|
4913
|
+
op: event.op,
|
|
4914
|
+
key: event.key,
|
|
4915
|
+
originRegion: event.originRegion
|
|
4916
|
+
});
|
|
4917
|
+
return true;
|
|
3311
4918
|
}
|
|
3312
|
-
_setLocalTagVersion(tag, version, now =
|
|
4919
|
+
_setLocalTagVersion(tag, version, now = performance.now()) {
|
|
3313
4920
|
const existing = this.tagVersions.get(tag)?.version ?? 0;
|
|
3314
4921
|
const finalVersion = Math.max(existing, version);
|
|
3315
4922
|
if (this.tagVersions.size >= 1e4 && !this.tagVersions.has(tag)) {
|
|
@@ -3319,7 +4926,7 @@ var CacheService = class _CacheService {
|
|
|
3319
4926
|
this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
|
|
3320
4927
|
}
|
|
3321
4928
|
async _getTagVersion(tag) {
|
|
3322
|
-
const now =
|
|
4929
|
+
const now = performance.now();
|
|
3323
4930
|
const local = this.tagVersions.get(tag);
|
|
3324
4931
|
if (local && now - local.lastSyncedAt < this.opts.tagVersionTtlMs) {
|
|
3325
4932
|
return local.version;
|
|
@@ -3405,13 +5012,25 @@ var CacheService = class _CacheService {
|
|
|
3405
5012
|
stream.on("error", reject);
|
|
3406
5013
|
})
|
|
3407
5014
|
));
|
|
3408
|
-
} else {
|
|
5015
|
+
} else if (typeof client.scanStream === "function") {
|
|
3409
5016
|
await new Promise((resolve, reject) => {
|
|
3410
5017
|
const stream = client.scanStream({ match: pattern, count: 100 });
|
|
3411
5018
|
stream.on("data", (chunk) => keys.push(...chunk));
|
|
3412
5019
|
stream.on("end", resolve);
|
|
3413
5020
|
stream.on("error", reject);
|
|
3414
5021
|
});
|
|
5022
|
+
} else if (typeof client.scanIterator === "function") {
|
|
5023
|
+
for await (const key of client.scanIterator({ MATCH: pattern, COUNT: 100 })) {
|
|
5024
|
+
keys.push(key);
|
|
5025
|
+
}
|
|
5026
|
+
} else if (typeof client.scan === "function") {
|
|
5027
|
+
let cursor = "0";
|
|
5028
|
+
do {
|
|
5029
|
+
const res = await client.scan(cursor, "MATCH", pattern, "COUNT", 100);
|
|
5030
|
+
cursor = String(res[0]);
|
|
5031
|
+
const chunk = res[1];
|
|
5032
|
+
if (chunk?.length) keys.push(...chunk);
|
|
5033
|
+
} while (cursor !== "0");
|
|
3415
5034
|
}
|
|
3416
5035
|
return keys;
|
|
3417
5036
|
}
|
|
@@ -3425,9 +5044,23 @@ var CacheService = class _CacheService {
|
|
|
3425
5044
|
}
|
|
3426
5045
|
}
|
|
3427
5046
|
async getRedis() {
|
|
5047
|
+
this._assertActive("getRedis");
|
|
3428
5048
|
if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
|
|
3429
5049
|
if (this.redis) return this.redis;
|
|
3430
5050
|
if (this.redisConnecting) return this.redisConnecting;
|
|
5051
|
+
if (this.opts.redisClient) {
|
|
5052
|
+
const client = this.opts.redisClient;
|
|
5053
|
+
if (typeof client.connect === "function" && client.isOpen === false) {
|
|
5054
|
+
await client.connect();
|
|
5055
|
+
}
|
|
5056
|
+
this.cb.onSuccess();
|
|
5057
|
+
this.redis = client;
|
|
5058
|
+
this.pipeliner = new AutoPipeliner(client, {
|
|
5059
|
+
enabled: this.opts.autoPipeline,
|
|
5060
|
+
maxBatchSize: this.opts.maxPipelineBatchSize
|
|
5061
|
+
});
|
|
5062
|
+
return client;
|
|
5063
|
+
}
|
|
3431
5064
|
this.redisConnecting = (async () => {
|
|
3432
5065
|
try {
|
|
3433
5066
|
let client;
|
|
@@ -3436,6 +5069,7 @@ var CacheService = class _CacheService {
|
|
|
3436
5069
|
redisOptions: {
|
|
3437
5070
|
tls: this.opts.redisTls ? {} : void 0,
|
|
3438
5071
|
connectTimeout: 1e4,
|
|
5072
|
+
commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
|
|
3439
5073
|
maxRetriesPerRequest: 3,
|
|
3440
5074
|
keepAlive: 3e4,
|
|
3441
5075
|
...this.opts.redisProtocol && { protocol: this.opts.redisProtocol }
|
|
@@ -3456,6 +5090,7 @@ var CacheService = class _CacheService {
|
|
|
3456
5090
|
name: this.opts.redisSentinel.name,
|
|
3457
5091
|
tls: this.opts.redisTls ? {} : void 0,
|
|
3458
5092
|
connectTimeout: 1e4,
|
|
5093
|
+
commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
|
|
3459
5094
|
lazyConnect: false,
|
|
3460
5095
|
maxRetriesPerRequest: 3,
|
|
3461
5096
|
enableAutoPipelining: true,
|
|
@@ -3475,6 +5110,7 @@ var CacheService = class _CacheService {
|
|
|
3475
5110
|
port: this.opts.redisPort,
|
|
3476
5111
|
tls: this.opts.redisTls ? {} : void 0,
|
|
3477
5112
|
connectTimeout: 1e4,
|
|
5113
|
+
commandTimeout: this.opts.redisCommandTimeoutMs ?? 2500,
|
|
3478
5114
|
lazyConnect: false,
|
|
3479
5115
|
maxRetriesPerRequest: 3,
|
|
3480
5116
|
enableAutoPipelining: true,
|
|
@@ -3500,6 +5136,10 @@ var CacheService = class _CacheService {
|
|
|
3500
5136
|
});
|
|
3501
5137
|
this.cb.onSuccess();
|
|
3502
5138
|
this.redis = client;
|
|
5139
|
+
this.pipeliner = new AutoPipeliner(client, {
|
|
5140
|
+
enabled: this.opts.autoPipeline,
|
|
5141
|
+
maxBatchSize: this.opts.maxPipelineBatchSize
|
|
5142
|
+
});
|
|
3503
5143
|
this.redisConnecting = null;
|
|
3504
5144
|
return client;
|
|
3505
5145
|
} catch (err) {
|
|
@@ -3512,12 +5152,18 @@ var CacheService = class _CacheService {
|
|
|
3512
5152
|
return this.redisConnecting;
|
|
3513
5153
|
}
|
|
3514
5154
|
// ── Snapshot (cold-start persistence) ────────────────────────────────────
|
|
5155
|
+
/**
|
|
5156
|
+
* Writes the cold-start snapshot to disk.
|
|
5157
|
+
* NOTE: fs.writeFileSync is INTENTIONAL here: this method is invoked during SIGTERM/SIGINT
|
|
5158
|
+
* process termination hooks where asynchronous I/O would risk the Node.js event loop dying or
|
|
5159
|
+
* process.exit() being called before the snapshot is physically written to disk.
|
|
5160
|
+
*/
|
|
3515
5161
|
writeSnapshot(altPath) {
|
|
3516
5162
|
try {
|
|
3517
5163
|
const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
|
|
3518
5164
|
if (entries.length === 0) return;
|
|
3519
5165
|
const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
|
|
3520
|
-
const packed =
|
|
5166
|
+
const packed = this.codec.encode(payload);
|
|
3521
5167
|
const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
|
|
3522
5168
|
const dest = altPath ?? this.opts.snapshotPath;
|
|
3523
5169
|
import_fs3.default.mkdirSync(import_path3.default.dirname(dest), { recursive: true });
|
|
@@ -3532,6 +5178,12 @@ var CacheService = class _CacheService {
|
|
|
3532
5178
|
this.logger.warn("Cache snapshot write failed", { error: err.message });
|
|
3533
5179
|
}
|
|
3534
5180
|
}
|
|
5181
|
+
/**
|
|
5182
|
+
* Loads cold-start snapshot from disk into L1 memory.
|
|
5183
|
+
* NOTE: fs.readFileSync is INTENTIONAL here: this method is invoked synchronously inside the
|
|
5184
|
+
* CacheService constructor so that the cache is atomically populated before any subsequent
|
|
5185
|
+
* cache.get() or cache.set() operations run, eliminating cold-start race conditions.
|
|
5186
|
+
*/
|
|
3535
5187
|
loadSnapshot() {
|
|
3536
5188
|
const snapshotPath = this.opts.snapshotPath;
|
|
3537
5189
|
try {
|
|
@@ -3551,13 +5203,25 @@ var CacheService = class _CacheService {
|
|
|
3551
5203
|
this.logger.warn("Snapshot rejected: decryption failed", { error: e.message });
|
|
3552
5204
|
return;
|
|
3553
5205
|
}
|
|
3554
|
-
const snapshot =
|
|
5206
|
+
const snapshot = this.codec.decode(buf);
|
|
3555
5207
|
if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
|
|
3556
5208
|
this.logger.warn("Snapshot rejected: version mismatch", { got: snapshot?.version });
|
|
3557
5209
|
return;
|
|
3558
5210
|
}
|
|
3559
|
-
const
|
|
3560
|
-
|
|
5211
|
+
const now = Date.now();
|
|
5212
|
+
const writtenAt = snapshot.writtenAt ?? 0;
|
|
5213
|
+
const tolerance = this.opts.clockSkewToleranceMs ?? 250;
|
|
5214
|
+
if (writtenAt - now > tolerance) {
|
|
5215
|
+
this.logger.warn("Snapshot rejected: timestamp too far in future (exceeds clock skew tolerance)", {
|
|
5216
|
+
writtenAt,
|
|
5217
|
+
now,
|
|
5218
|
+
skewMs: writtenAt - now,
|
|
5219
|
+
tolerance
|
|
5220
|
+
});
|
|
5221
|
+
return;
|
|
5222
|
+
}
|
|
5223
|
+
const ageMs = Math.max(0, now - writtenAt);
|
|
5224
|
+
if (ageMs > this.opts.snapshotMaxAgeMs) {
|
|
3561
5225
|
this.logger.warn("Snapshot rejected: too old", { ageMinutes: Math.round(ageMs / 6e4) });
|
|
3562
5226
|
return;
|
|
3563
5227
|
}
|
|
@@ -3579,6 +5243,115 @@ var CacheService = class _CacheService {
|
|
|
3579
5243
|
}
|
|
3580
5244
|
}
|
|
3581
5245
|
}
|
|
5246
|
+
// ── Remote Snapshot (cold-start persistence for stateless containers) ───────
|
|
5247
|
+
/**
|
|
5248
|
+
* Persists the cold-start snapshot to remote blob storage (S3, GCS, R2, HTTP).
|
|
5249
|
+
* Can be awaited during graceful application shutdown (e.g. Kubernetes preStop or NestJS shutdown).
|
|
5250
|
+
* Returns true if a snapshot was successfully exported and written; false otherwise.
|
|
5251
|
+
*/
|
|
5252
|
+
async writeRemoteSnapshot() {
|
|
5253
|
+
if (!this.opts.remoteSnapshot) return false;
|
|
5254
|
+
try {
|
|
5255
|
+
const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
|
|
5256
|
+
if (entries.length === 0) return false;
|
|
5257
|
+
const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
|
|
5258
|
+
const packed = this.codec.encode(payload);
|
|
5259
|
+
let final;
|
|
5260
|
+
if (this.opts.remoteSnapshot.envelope) {
|
|
5261
|
+
final = await EnvelopeEncryption.encrypt(packed, this.opts.remoteSnapshot.envelope);
|
|
5262
|
+
} else {
|
|
5263
|
+
final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
|
|
5264
|
+
}
|
|
5265
|
+
await this.opts.remoteSnapshot.adapter.put(final);
|
|
5266
|
+
this.counters.remoteSnapshotUploads++;
|
|
5267
|
+
this.counters.remoteSnapshotLastUploadedAt = Date.now();
|
|
5268
|
+
this.logger.info("Remote cache snapshot uploaded", {
|
|
5269
|
+
entries: entries.length,
|
|
5270
|
+
sizeKB: Math.round(final.length / 1024),
|
|
5271
|
+
encrypted: Boolean(this.opts.remoteSnapshot.envelope || this.enc.isEnabled)
|
|
5272
|
+
});
|
|
5273
|
+
return true;
|
|
5274
|
+
} catch (err) {
|
|
5275
|
+
this.counters.remoteSnapshotErrors++;
|
|
5276
|
+
this.logger.warn("Remote cache snapshot upload failed", { error: err.message });
|
|
5277
|
+
return false;
|
|
5278
|
+
}
|
|
5279
|
+
}
|
|
5280
|
+
/**
|
|
5281
|
+
* Hydrates L1 memory from remote blob storage (S3, GCS, R2, HTTP).
|
|
5282
|
+
* Called automatically during startup (chained into `cache.ready()`).
|
|
5283
|
+
* Returns the number of entries successfully imported.
|
|
5284
|
+
*/
|
|
5285
|
+
async loadRemoteSnapshot() {
|
|
5286
|
+
if (!this.opts.remoteSnapshot) return 0;
|
|
5287
|
+
const maxAgeMs = this.opts.remoteSnapshot.maxAgeMs ?? this.opts.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE;
|
|
5288
|
+
try {
|
|
5289
|
+
const raw = await this.opts.remoteSnapshot.adapter.get();
|
|
5290
|
+
if (!raw || raw.length === 0) {
|
|
5291
|
+
this.logger.debug("Remote snapshot not found or empty \u2014 starting cold");
|
|
5292
|
+
return 0;
|
|
5293
|
+
}
|
|
5294
|
+
const rawBuf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
|
|
5295
|
+
let buf;
|
|
5296
|
+
try {
|
|
5297
|
+
if (EnvelopeEncryption.isEnvelope(rawBuf)) {
|
|
5298
|
+
if (!this.opts.remoteSnapshot.envelope) {
|
|
5299
|
+
throw new Error("Remote snapshot is envelope-encrypted but no envelope options (privateKey or kmsDecrypt) were configured");
|
|
5300
|
+
}
|
|
5301
|
+
buf = await EnvelopeEncryption.decrypt(rawBuf, this.opts.remoteSnapshot.envelope);
|
|
5302
|
+
} else {
|
|
5303
|
+
buf = this.enc.decryptBuffer(rawBuf);
|
|
5304
|
+
}
|
|
5305
|
+
} catch (e) {
|
|
5306
|
+
this.counters.remoteSnapshotErrors++;
|
|
5307
|
+
this.logger.warn("Remote snapshot rejected: decryption failed", { error: e.message });
|
|
5308
|
+
return 0;
|
|
5309
|
+
}
|
|
5310
|
+
const snapshot = this.codec.decode(buf);
|
|
5311
|
+
if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
|
|
5312
|
+
this.counters.remoteSnapshotErrors++;
|
|
5313
|
+
this.logger.warn("Remote snapshot rejected: version mismatch", { got: snapshot?.version });
|
|
5314
|
+
return 0;
|
|
5315
|
+
}
|
|
5316
|
+
const now = Date.now();
|
|
5317
|
+
const writtenAt = snapshot.writtenAt ?? 0;
|
|
5318
|
+
const tolerance = this.opts.clockSkewToleranceMs ?? 250;
|
|
5319
|
+
if (writtenAt - now > tolerance) {
|
|
5320
|
+
this.counters.remoteSnapshotErrors++;
|
|
5321
|
+
this.logger.warn("Remote snapshot rejected: timestamp too far in future (exceeds clock skew tolerance)", {
|
|
5322
|
+
writtenAt,
|
|
5323
|
+
now,
|
|
5324
|
+
skewMs: writtenAt - now,
|
|
5325
|
+
tolerance
|
|
5326
|
+
});
|
|
5327
|
+
return 0;
|
|
5328
|
+
}
|
|
5329
|
+
const ageMs = Math.max(0, now - writtenAt);
|
|
5330
|
+
if (maxAgeMs <= 0 || ageMs > maxAgeMs) {
|
|
5331
|
+
this.counters.remoteSnapshotErrors++;
|
|
5332
|
+
this.logger.warn("Remote snapshot rejected: too old", { ageMinutes: Math.round(ageMs / 6e4) });
|
|
5333
|
+
return 0;
|
|
5334
|
+
}
|
|
5335
|
+
if (!Array.isArray(snapshot.entries)) {
|
|
5336
|
+
this.counters.remoteSnapshotErrors++;
|
|
5337
|
+
this.logger.warn("Remote snapshot rejected: entries is not an array");
|
|
5338
|
+
return 0;
|
|
5339
|
+
}
|
|
5340
|
+
const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
|
|
5341
|
+
this.counters.remoteSnapshotDownloads++;
|
|
5342
|
+
this.counters.remoteSnapshotLastDownloadedAt = Date.now();
|
|
5343
|
+
this.logger.info("Remote cache snapshot loaded (L1 hydrated)", {
|
|
5344
|
+
loaded,
|
|
5345
|
+
total: snapshot.entries.length,
|
|
5346
|
+
sizeKB: this.l1.getStats().sizeKB
|
|
5347
|
+
});
|
|
5348
|
+
return loaded;
|
|
5349
|
+
} catch (err) {
|
|
5350
|
+
this.counters.remoteSnapshotErrors++;
|
|
5351
|
+
this.logger.warn("Remote snapshot load failed \u2014 starting cold", { error: err.message });
|
|
5352
|
+
return 0;
|
|
5353
|
+
}
|
|
5354
|
+
}
|
|
3582
5355
|
// ── Core get (L1 → L1.5 → L2 → fetch) ───────────────────────────────────
|
|
3583
5356
|
/**
|
|
3584
5357
|
* Get a value from cache, or fetch and cache it.
|
|
@@ -3600,6 +5373,7 @@ var CacheService = class _CacheService {
|
|
|
3600
5373
|
* Caches negative lookups to avoid repeated DB hits for missing keys.
|
|
3601
5374
|
*/
|
|
3602
5375
|
async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
|
|
5376
|
+
this._assertActive("get");
|
|
3603
5377
|
const span = this._startSpan("tricache.get");
|
|
3604
5378
|
if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
3605
5379
|
const k = this.nk(cacheKey);
|
|
@@ -3614,9 +5388,10 @@ var CacheService = class _CacheService {
|
|
|
3614
5388
|
if (l1Hit !== null) {
|
|
3615
5389
|
let isGenerationalStale = false;
|
|
3616
5390
|
if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
|
|
3617
|
-
|
|
3618
|
-
|
|
3619
|
-
|
|
5391
|
+
const tags = Object.keys(l1Hit.tagVersions);
|
|
5392
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5393
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5394
|
+
if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
|
|
3620
5395
|
isGenerationalStale = true;
|
|
3621
5396
|
break;
|
|
3622
5397
|
}
|
|
@@ -3630,7 +5405,14 @@ var CacheService = class _CacheService {
|
|
|
3630
5405
|
if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
|
|
3631
5406
|
const priority2 = optPriority ?? inferPriority(cacheKey);
|
|
3632
5407
|
this.revalidating.add(k);
|
|
3633
|
-
void this._revalidate(
|
|
5408
|
+
void this._revalidate(
|
|
5409
|
+
k,
|
|
5410
|
+
fetchFn,
|
|
5411
|
+
ttlSeconds * 1e3,
|
|
5412
|
+
swrGraceMs2,
|
|
5413
|
+
priority2,
|
|
5414
|
+
l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
|
|
5415
|
+
);
|
|
3634
5416
|
this.counters.swrRevalidations++;
|
|
3635
5417
|
this.logger.debug("SWR: serving stale, revalidating", { cacheKey });
|
|
3636
5418
|
} else {
|
|
@@ -3649,7 +5431,14 @@ var CacheService = class _CacheService {
|
|
|
3649
5431
|
if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
|
|
3650
5432
|
const priority2 = optPriority ?? inferPriority(cacheKey);
|
|
3651
5433
|
this.revalidating.add(k);
|
|
3652
|
-
void this._revalidate(
|
|
5434
|
+
void this._revalidate(
|
|
5435
|
+
k,
|
|
5436
|
+
fetchFn,
|
|
5437
|
+
entryTtl,
|
|
5438
|
+
optSwr * 1e3,
|
|
5439
|
+
priority2,
|
|
5440
|
+
l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
|
|
5441
|
+
);
|
|
3653
5442
|
this.counters.swrRevalidations++;
|
|
3654
5443
|
this.logger.debug(
|
|
3655
5444
|
shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
|
|
@@ -3661,116 +5450,148 @@ var CacheService = class _CacheService {
|
|
|
3661
5450
|
this.counters.l1Hits++;
|
|
3662
5451
|
this.opts.onHit?.(cacheKey, "l1");
|
|
3663
5452
|
if (this.opts.frozen) deepFreeze(l1Hit.value);
|
|
3664
|
-
span.setAttribute("cache.hit", "l1").end();
|
|
5453
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "memory").setAttribute("cache.hit_tier", "l1").end();
|
|
3665
5454
|
return this.opts.cloneStrategy === "structuredClone" && l1Hit.value != null && typeof l1Hit.value === "object" ? structuredClone(l1Hit.value) : l1Hit.value;
|
|
3666
5455
|
}
|
|
3667
5456
|
}
|
|
3668
5457
|
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
3669
5458
|
const swrGraceMs = optSwr * 1e3;
|
|
3670
5459
|
const priority = optPriority ?? inferPriority(cacheKey);
|
|
3671
|
-
|
|
5460
|
+
const existing = this.inflight.get(k);
|
|
5461
|
+
if (existing) {
|
|
5462
|
+
this.counters.stampedes++;
|
|
5463
|
+
this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch/read", { cacheKey });
|
|
5464
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
|
|
5465
|
+
return existing;
|
|
5466
|
+
}
|
|
5467
|
+
const mutationEpochAtStart = this._getKeyMutationEpoch(k);
|
|
5468
|
+
const executionPromise = (async () => {
|
|
3672
5469
|
try {
|
|
3673
|
-
|
|
3674
|
-
|
|
3675
|
-
|
|
3676
|
-
|
|
3677
|
-
|
|
3678
|
-
let isStale = false;
|
|
3679
|
-
let storedTagVersions = {};
|
|
3680
|
-
if (hashData.tv) {
|
|
3681
|
-
try {
|
|
3682
|
-
storedTagVersions = JSON.parse(hashData.tv);
|
|
3683
|
-
} catch {
|
|
3684
|
-
}
|
|
5470
|
+
if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
|
|
5471
|
+
if (this._isTombstonedByPattern(k)) {
|
|
5472
|
+
try {
|
|
5473
|
+
this.disk.delete(k);
|
|
5474
|
+
} catch {
|
|
3685
5475
|
}
|
|
3686
|
-
|
|
3687
|
-
|
|
3688
|
-
|
|
3689
|
-
|
|
3690
|
-
|
|
5476
|
+
} else {
|
|
5477
|
+
const isDiskAllowed = this.watchdog.isDiskAllowed();
|
|
5478
|
+
if (isDiskAllowed) {
|
|
5479
|
+
const diskStart = performance.now();
|
|
5480
|
+
const diskHit = this.disk.load(k);
|
|
5481
|
+
const diskElapsed = performance.now() - diskStart;
|
|
5482
|
+
this.watchdog.recordDisk(diskElapsed);
|
|
5483
|
+
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
5484
|
+
if (diskHit !== null) {
|
|
5485
|
+
let isDiskStale = false;
|
|
5486
|
+
if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
|
|
5487
|
+
const tags = Object.keys(diskHit.tagVersions);
|
|
5488
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5489
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5490
|
+
if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
|
|
5491
|
+
isDiskStale = true;
|
|
5492
|
+
break;
|
|
5493
|
+
}
|
|
5494
|
+
}
|
|
5495
|
+
}
|
|
5496
|
+
if (isDiskStale) {
|
|
5497
|
+
this.disk.delete(k);
|
|
5498
|
+
} else {
|
|
5499
|
+
const promoted = this.l1.importEntries(
|
|
5500
|
+
[{ key: k, entry: diskHit }],
|
|
5501
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
5502
|
+
);
|
|
5503
|
+
if (promoted > 0) {
|
|
5504
|
+
const l1Check = this.l1.get(k);
|
|
5505
|
+
if (l1Check !== null) {
|
|
5506
|
+
this.counters.diskHits++;
|
|
5507
|
+
this.opts.onHit?.(cacheKey, "disk");
|
|
5508
|
+
this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
|
|
5509
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
|
|
5510
|
+
if (this.opts.frozen) deepFreeze(l1Check.value);
|
|
5511
|
+
return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
|
|
5512
|
+
}
|
|
5513
|
+
}
|
|
5514
|
+
}
|
|
3691
5515
|
}
|
|
3692
5516
|
}
|
|
3693
|
-
if (isStale) {
|
|
3694
|
-
const setAtMs = parseInt(hashData.t, 10) || 0;
|
|
3695
|
-
this._deleteIfStale(k, setAtMs);
|
|
3696
|
-
} else {
|
|
3697
|
-
const parsed = await this._decryptAndDeserialize(hashData.d);
|
|
3698
|
-
this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
|
|
3699
|
-
this.counters.l2Hits++;
|
|
3700
|
-
this.opts.onHit?.(cacheKey, "l2");
|
|
3701
|
-
this.logger.debug("L2 hit (Redis hash)", { cacheKey });
|
|
3702
|
-
span.setAttribute("cache.hit", "l2").end();
|
|
3703
|
-
if (this.opts.frozen) deepFreeze(parsed);
|
|
3704
|
-
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
3705
|
-
}
|
|
3706
|
-
}
|
|
3707
|
-
} else {
|
|
3708
|
-
const raw = await client.get(k);
|
|
3709
|
-
this.cb.onSuccess();
|
|
3710
|
-
if (raw) {
|
|
3711
|
-
const parsed = await this._decryptAndDeserialize(raw);
|
|
3712
|
-
this.l1.set(k, parsed, ttlMs, priority);
|
|
3713
|
-
this.counters.l2Hits++;
|
|
3714
|
-
this.opts.onHit?.(cacheKey, "l2");
|
|
3715
|
-
this.logger.debug("L2 hit (Redis)", { cacheKey });
|
|
3716
|
-
span.setAttribute("cache.hit", "l2").end();
|
|
3717
|
-
if (this.opts.frozen) deepFreeze(parsed);
|
|
3718
|
-
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
3719
|
-
}
|
|
3720
|
-
}
|
|
3721
|
-
} catch (err) {
|
|
3722
|
-
this.cb.onFailure();
|
|
3723
|
-
this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
|
|
3724
|
-
}
|
|
3725
|
-
}
|
|
3726
|
-
if (!this._diskDisabled) {
|
|
3727
|
-
const diskHit = this.disk.load(k);
|
|
3728
|
-
if (diskHit !== null) {
|
|
3729
|
-
let isDiskStale = false;
|
|
3730
|
-
if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
|
|
3731
|
-
for (const [tag, entryVer] of Object.entries(diskHit.tagVersions)) {
|
|
3732
|
-
const currentVer = await this._getTagVersion(tag);
|
|
3733
|
-
if (currentVer > entryVer) {
|
|
3734
|
-
isDiskStale = true;
|
|
3735
|
-
break;
|
|
3736
|
-
}
|
|
3737
5517
|
}
|
|
3738
5518
|
}
|
|
3739
|
-
if (
|
|
3740
|
-
|
|
3741
|
-
|
|
3742
|
-
|
|
3743
|
-
|
|
3744
|
-
|
|
3745
|
-
|
|
3746
|
-
|
|
3747
|
-
|
|
3748
|
-
|
|
3749
|
-
|
|
3750
|
-
|
|
3751
|
-
|
|
3752
|
-
|
|
3753
|
-
|
|
3754
|
-
|
|
5519
|
+
if (!this._redisDisabled) {
|
|
5520
|
+
try {
|
|
5521
|
+
const client = await this.getRedis();
|
|
5522
|
+
const redisStart = performance.now();
|
|
5523
|
+
if (this.opts.tagStrategy === "generational") {
|
|
5524
|
+
const hashData = await client.hgetall(k);
|
|
5525
|
+
const redisElapsed = performance.now() - redisStart;
|
|
5526
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
5527
|
+
this.cb.onSuccess();
|
|
5528
|
+
if (hashData && hashData.d) {
|
|
5529
|
+
let isStale = false;
|
|
5530
|
+
let storedTagVersions = {};
|
|
5531
|
+
if (hashData.tv) {
|
|
5532
|
+
try {
|
|
5533
|
+
storedTagVersions = JSON.parse(hashData.tv);
|
|
5534
|
+
} catch {
|
|
5535
|
+
}
|
|
5536
|
+
}
|
|
5537
|
+
const tags = Object.keys(storedTagVersions);
|
|
5538
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5539
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5540
|
+
if (currentVers[i] > storedTagVersions[tags[i]]) {
|
|
5541
|
+
isStale = true;
|
|
5542
|
+
break;
|
|
5543
|
+
}
|
|
5544
|
+
}
|
|
5545
|
+
if (isStale) {
|
|
5546
|
+
const setAtMs = parseInt(hashData.t, 10) || 0;
|
|
5547
|
+
this._deleteIfStale(k, setAtMs);
|
|
5548
|
+
} else {
|
|
5549
|
+
const parsed = await this._decryptAndDeserialize(hashData.d);
|
|
5550
|
+
this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
|
|
5551
|
+
this.counters.l2Hits++;
|
|
5552
|
+
this.opts.onHit?.(cacheKey, "l2");
|
|
5553
|
+
this.logger.debug("L2 hit (Redis hash)", { cacheKey });
|
|
5554
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
5555
|
+
if (this.opts.frozen) deepFreeze(parsed);
|
|
5556
|
+
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
5557
|
+
}
|
|
5558
|
+
}
|
|
5559
|
+
} else {
|
|
5560
|
+
const raw = this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
|
|
5561
|
+
const redisElapsed = performance.now() - redisStart;
|
|
5562
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
5563
|
+
this.cb.onSuccess();
|
|
5564
|
+
if (raw) {
|
|
5565
|
+
const parsed = await this._decryptAndDeserialize(raw);
|
|
5566
|
+
this.l1.set(k, parsed, ttlMs, priority);
|
|
5567
|
+
this.counters.l2Hits++;
|
|
5568
|
+
this.opts.onHit?.(cacheKey, "l2");
|
|
5569
|
+
this.logger.debug("L2 hit (Redis)", { cacheKey });
|
|
5570
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
5571
|
+
if (this.opts.frozen) deepFreeze(parsed);
|
|
5572
|
+
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
5573
|
+
}
|
|
3755
5574
|
}
|
|
5575
|
+
} catch (err) {
|
|
5576
|
+
this.cb.onFailure();
|
|
5577
|
+
this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
|
|
3756
5578
|
}
|
|
3757
5579
|
}
|
|
3758
|
-
|
|
3759
|
-
|
|
3760
|
-
span.setAttribute("cache.hit", "miss");
|
|
3761
|
-
this.opts.onMiss?.(cacheKey);
|
|
3762
|
-
const existing = this.inflight.get(k);
|
|
3763
|
-
if (existing) {
|
|
3764
|
-
this.counters.stampedes++;
|
|
3765
|
-
this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch", { cacheKey });
|
|
3766
|
-
span.end();
|
|
3767
|
-
return existing;
|
|
3768
|
-
}
|
|
3769
|
-
const fetchPromise = (async () => {
|
|
3770
|
-
try {
|
|
5580
|
+
span.setAttribute("cache.hit", false).setAttribute("cache.hit_tier", "miss");
|
|
5581
|
+
this.opts.onMiss?.(cacheKey);
|
|
3771
5582
|
this.counters.fetches++;
|
|
3772
5583
|
const fetchStart = Date.now();
|
|
3773
|
-
|
|
5584
|
+
let data;
|
|
5585
|
+
try {
|
|
5586
|
+
data = await fetchFn();
|
|
5587
|
+
} catch (fetchErr) {
|
|
5588
|
+
span.setStatus({
|
|
5589
|
+
code: 2,
|
|
5590
|
+
message: fetchErr instanceof Error ? fetchErr.message : String(fetchErr)
|
|
5591
|
+
});
|
|
5592
|
+
span.recordException?.(fetchErr);
|
|
5593
|
+
throw fetchErr;
|
|
5594
|
+
}
|
|
3774
5595
|
const delta = Date.now() - fetchStart;
|
|
3775
5596
|
const notFoundTtlMs = (optNotFoundTtl ?? this.opts.notFoundTtl) * 1e3;
|
|
3776
5597
|
let effectiveTtl = data == null && notFoundTtlMs > 0 ? notFoundTtlMs : ttlMs;
|
|
@@ -3790,14 +5611,27 @@ var CacheService = class _CacheService {
|
|
|
3790
5611
|
let activeTagVersions;
|
|
3791
5612
|
if (optTags?.length) {
|
|
3792
5613
|
if (this.opts.tagStrategy === "generational") {
|
|
5614
|
+
const vers = await Promise.all(optTags.map((tag) => this._getTagVersion(tag)));
|
|
3793
5615
|
activeTagVersions = {};
|
|
3794
|
-
for (
|
|
3795
|
-
activeTagVersions[
|
|
5616
|
+
for (let i = 0; i < optTags.length; i++) {
|
|
5617
|
+
activeTagVersions[optTags[i]] = vers[i];
|
|
3796
5618
|
}
|
|
3797
5619
|
} else {
|
|
3798
5620
|
await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
|
|
3799
5621
|
}
|
|
3800
5622
|
}
|
|
5623
|
+
if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
|
|
5624
|
+
this.logger.debug("Aborting in-flight cache commit \u2014 key was mutated or deleted during fetch", { cacheKey });
|
|
5625
|
+
span.setAttribute("cache.aborted_mutation_race", true);
|
|
5626
|
+
const current = this.l1.get(k);
|
|
5627
|
+
if (current && !current.isStale && current.value !== void 0) {
|
|
5628
|
+
const freshVal = current.value;
|
|
5629
|
+
if (this.opts.frozen) deepFreeze(freshVal);
|
|
5630
|
+
return this.opts.cloneStrategy === "structuredClone" && freshVal != null && typeof freshVal === "object" ? structuredClone(freshVal) : freshVal;
|
|
5631
|
+
}
|
|
5632
|
+
if (this.opts.frozen) deepFreeze(data);
|
|
5633
|
+
return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
|
|
5634
|
+
}
|
|
3801
5635
|
this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
|
|
3802
5636
|
if (!this._redisDisabled) {
|
|
3803
5637
|
try {
|
|
@@ -3834,8 +5668,64 @@ var CacheService = class _CacheService {
|
|
|
3834
5668
|
span.end();
|
|
3835
5669
|
}
|
|
3836
5670
|
})();
|
|
3837
|
-
this.inflight.set(k,
|
|
3838
|
-
return
|
|
5671
|
+
this.inflight.set(k, executionPromise);
|
|
5672
|
+
return executionPromise;
|
|
5673
|
+
}
|
|
5674
|
+
/**
|
|
5675
|
+
* Graceful shutdown flusher for Kubernetes preStop hooks, NestJS onApplicationShutdown,
|
|
5676
|
+
* or manual microservice teardown.
|
|
5677
|
+
*
|
|
5678
|
+
* Flushes both local disk and remote cloud snapshots (S3/R2/GCS), returning a Promise
|
|
5679
|
+
* that resolves when the upload completes or after `timeoutMs` expires.
|
|
5680
|
+
*
|
|
5681
|
+
* @param timeoutMs Maximum time permitted for snapshot persistence before timing out. Default: 8000ms.
|
|
5682
|
+
*/
|
|
5683
|
+
async flushSnapshotOnShutdown(timeoutMs = 8e3) {
|
|
5684
|
+
const flusher = async () => {
|
|
5685
|
+
let localOk = true;
|
|
5686
|
+
let remoteOk = true;
|
|
5687
|
+
if (!this._diskDisabled) {
|
|
5688
|
+
try {
|
|
5689
|
+
this.writeSnapshot();
|
|
5690
|
+
} catch (err) {
|
|
5691
|
+
localOk = false;
|
|
5692
|
+
this.logger.warn("flushSnapshotOnShutdown: disk snapshot write failed", { error: err.message });
|
|
5693
|
+
}
|
|
5694
|
+
}
|
|
5695
|
+
if (this.opts.remoteSnapshot && this.opts.remoteSnapshot.saveOnShutdown !== false) {
|
|
5696
|
+
try {
|
|
5697
|
+
remoteOk = await this.writeRemoteSnapshot();
|
|
5698
|
+
} catch (err) {
|
|
5699
|
+
remoteOk = false;
|
|
5700
|
+
this.logger.warn("flushSnapshotOnShutdown: remote snapshot upload failed", { error: err.message });
|
|
5701
|
+
}
|
|
5702
|
+
}
|
|
5703
|
+
return localOk && remoteOk;
|
|
5704
|
+
};
|
|
5705
|
+
let timer = null;
|
|
5706
|
+
try {
|
|
5707
|
+
return await Promise.race([
|
|
5708
|
+
flusher(),
|
|
5709
|
+
new Promise((resolve) => {
|
|
5710
|
+
timer = setTimeout(() => {
|
|
5711
|
+
this.logger.warn(`flushSnapshotOnShutdown timed out after ${timeoutMs}ms`);
|
|
5712
|
+
resolve(false);
|
|
5713
|
+
}, timeoutMs);
|
|
5714
|
+
if (timer.unref) timer.unref();
|
|
5715
|
+
})
|
|
5716
|
+
]);
|
|
5717
|
+
} finally {
|
|
5718
|
+
if (timer) clearTimeout(timer);
|
|
5719
|
+
}
|
|
5720
|
+
}
|
|
5721
|
+
/**
|
|
5722
|
+
* Internal graceful shutdown trigger invoked by ProcessTerminationBus.
|
|
5723
|
+
*/
|
|
5724
|
+
_triggerShutdown() {
|
|
5725
|
+
if (!this._diskDisabled) this.writeSnapshot();
|
|
5726
|
+
if (this.opts.remoteSnapshot && this.opts.remoteSnapshot.saveOnShutdown !== false) {
|
|
5727
|
+
void this.flushSnapshotOnShutdown();
|
|
5728
|
+
}
|
|
3839
5729
|
}
|
|
3840
5730
|
/**
|
|
3841
5731
|
* Universal fetch-and-cache wrapper with an ergonomic options object.
|
|
@@ -3858,20 +5748,40 @@ var CacheService = class _CacheService {
|
|
|
3858
5748
|
const ttl = options?.ttl ?? 300;
|
|
3859
5749
|
return this.get(cacheKey, fetchFn, ttl, options);
|
|
3860
5750
|
}
|
|
3861
|
-
async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
|
|
5751
|
+
async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority, knownTagVersions) {
|
|
5752
|
+
const startEpoch = this._getKeyMutationEpoch(cacheKey);
|
|
3862
5753
|
try {
|
|
3863
5754
|
const fetchStart = Date.now();
|
|
3864
5755
|
const data = await fetchFn();
|
|
3865
5756
|
const delta = Date.now() - fetchStart;
|
|
3866
5757
|
const staleAt = Date.now() + ttlMs;
|
|
5758
|
+
if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
|
|
5759
|
+
this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during fetch", { cacheKey });
|
|
5760
|
+
return;
|
|
5761
|
+
}
|
|
3867
5762
|
if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
|
|
3868
5763
|
let activeTagVersions;
|
|
3869
5764
|
const l1Existing = this.l1.get(cacheKey);
|
|
3870
|
-
|
|
5765
|
+
const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
|
|
5766
|
+
if (this.opts.tagStrategy === "generational" && tagVersionsSource) {
|
|
5767
|
+
const tags = Object.keys(tagVersionsSource);
|
|
5768
|
+
const vers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
3871
5769
|
activeTagVersions = {};
|
|
3872
|
-
for (
|
|
3873
|
-
activeTagVersions[
|
|
5770
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5771
|
+
activeTagVersions[tags[i]] = vers[i];
|
|
3874
5772
|
}
|
|
5773
|
+
if (knownTagVersions) {
|
|
5774
|
+
for (const t of tags) {
|
|
5775
|
+
if (knownTagVersions[t] !== void 0 && activeTagVersions[t] !== knownTagVersions[t]) {
|
|
5776
|
+
this.logger.debug("SWR: aborting revalidation commit \u2014 tag version bumped during revalidation", { cacheKey, tag: t });
|
|
5777
|
+
return;
|
|
5778
|
+
}
|
|
5779
|
+
}
|
|
5780
|
+
}
|
|
5781
|
+
}
|
|
5782
|
+
if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
|
|
5783
|
+
this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
|
|
5784
|
+
return;
|
|
3875
5785
|
}
|
|
3876
5786
|
this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
|
|
3877
5787
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
@@ -3915,63 +5825,86 @@ var CacheService = class _CacheService {
|
|
|
3915
5825
|
// ── Explicit set / delete ─────────────────────────────────────────────────
|
|
3916
5826
|
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
3917
5827
|
async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
|
|
5828
|
+
this._assertActive("set");
|
|
3918
5829
|
const span = this._startSpan("tricache.set");
|
|
3919
|
-
if (this.opts.tracer)
|
|
3920
|
-
|
|
3921
|
-
|
|
3922
|
-
|
|
3923
|
-
|
|
3924
|
-
|
|
3925
|
-
|
|
3926
|
-
|
|
3927
|
-
|
|
3928
|
-
|
|
3929
|
-
|
|
3930
|
-
|
|
5830
|
+
if (this.opts.tracer) {
|
|
5831
|
+
span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
5832
|
+
span.setAttribute("cache.ttl", ttlSeconds);
|
|
5833
|
+
}
|
|
5834
|
+
try {
|
|
5835
|
+
const effectiveTtlSeconds = ttlSeconds > 0 ? ttlSeconds : ttlSeconds === 0 ? INDEFINITE_TTL_SECONDS : ttlSeconds;
|
|
5836
|
+
const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
|
|
5837
|
+
const p = priority ?? inferPriority(cacheKey);
|
|
5838
|
+
const k = this.nk(cacheKey);
|
|
5839
|
+
this._bumpKeyMutation(k);
|
|
5840
|
+
this.inflight.delete(k);
|
|
5841
|
+
this._pendingDiskDeletes.delete(k);
|
|
5842
|
+
this.counters.sets++;
|
|
5843
|
+
let activeTagVersions;
|
|
5844
|
+
if (opts?.tags?.length) {
|
|
5845
|
+
if (this.opts.tagStrategy === "generational") {
|
|
5846
|
+
const vers = await Promise.all(opts.tags.map((tag) => this._getTagVersion(tag)));
|
|
5847
|
+
activeTagVersions = {};
|
|
5848
|
+
for (let i = 0; i < opts.tags.length; i++) {
|
|
5849
|
+
activeTagVersions[opts.tags[i]] = vers[i];
|
|
5850
|
+
}
|
|
5851
|
+
} else {
|
|
5852
|
+
await this._registerTags(k, opts.tags, ttlSeconds);
|
|
3931
5853
|
}
|
|
3932
|
-
} else {
|
|
3933
|
-
await this._registerTags(k, opts.tags, ttlSeconds);
|
|
3934
5854
|
}
|
|
3935
|
-
|
|
3936
|
-
|
|
3937
|
-
|
|
3938
|
-
|
|
3939
|
-
|
|
3940
|
-
|
|
3941
|
-
|
|
3942
|
-
|
|
3943
|
-
|
|
5855
|
+
this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
|
|
5856
|
+
if (opts?.dependsOn?.length) {
|
|
5857
|
+
for (const pattern of opts.dependsOn) {
|
|
5858
|
+
const nsPattern = this.nk(pattern);
|
|
5859
|
+
let deps = this.dependencyIndex.get(nsPattern);
|
|
5860
|
+
if (!deps) {
|
|
5861
|
+
deps = /* @__PURE__ */ new Set();
|
|
5862
|
+
this.dependencyIndex.set(nsPattern, deps);
|
|
5863
|
+
}
|
|
5864
|
+
deps.add(k);
|
|
3944
5865
|
}
|
|
3945
|
-
deps.add(k);
|
|
3946
5866
|
}
|
|
3947
|
-
|
|
3948
|
-
|
|
3949
|
-
|
|
3950
|
-
|
|
3951
|
-
|
|
3952
|
-
|
|
3953
|
-
|
|
3954
|
-
|
|
3955
|
-
|
|
3956
|
-
|
|
3957
|
-
|
|
3958
|
-
|
|
3959
|
-
|
|
3960
|
-
|
|
3961
|
-
|
|
3962
|
-
|
|
3963
|
-
|
|
3964
|
-
|
|
3965
|
-
|
|
5867
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5868
|
+
try {
|
|
5869
|
+
const client = await this.getRedis();
|
|
5870
|
+
const s = JSON.stringify(data);
|
|
5871
|
+
const stored = await this._serializeAndEncrypt(s);
|
|
5872
|
+
const ttlSec = Math.ceil(ttlMs / 1e3);
|
|
5873
|
+
if (this.opts.tagStrategy === "generational" && activeTagVersions) {
|
|
5874
|
+
const now = Date.now();
|
|
5875
|
+
const tx = client.multi();
|
|
5876
|
+
tx.hset(k, {
|
|
5877
|
+
d: stored,
|
|
5878
|
+
t: String(now),
|
|
5879
|
+
tv: JSON.stringify(activeTagVersions)
|
|
5880
|
+
});
|
|
5881
|
+
tx.expire(k, ttlSec);
|
|
5882
|
+
await tx.exec();
|
|
5883
|
+
} else {
|
|
5884
|
+
if (this.opts.autoPipeline && this.pipeliner) {
|
|
5885
|
+
await this.pipeliner.setex(k, ttlSec, stored);
|
|
5886
|
+
} else {
|
|
5887
|
+
await client.setex(k, ttlSec, stored);
|
|
5888
|
+
}
|
|
5889
|
+
}
|
|
5890
|
+
this.cb.onSuccess();
|
|
5891
|
+
} catch (err) {
|
|
5892
|
+
this.cb.onFailure();
|
|
5893
|
+
this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
|
|
3966
5894
|
}
|
|
3967
|
-
this.cb.onSuccess();
|
|
3968
|
-
} catch (err) {
|
|
3969
|
-
this.cb.onFailure();
|
|
3970
|
-
this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
|
|
3971
5895
|
}
|
|
5896
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
5897
|
+
await this.publishInvalidation("del", k);
|
|
5898
|
+
} else {
|
|
5899
|
+
void this.publishInvalidation("del", k);
|
|
5900
|
+
}
|
|
5901
|
+
} catch (err) {
|
|
5902
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
5903
|
+
span.recordException?.(err);
|
|
5904
|
+
throw err;
|
|
5905
|
+
} finally {
|
|
5906
|
+
span.end();
|
|
3972
5907
|
}
|
|
3973
|
-
void this.publishInvalidation("del", k);
|
|
3974
|
-
span.end();
|
|
3975
5908
|
}
|
|
3976
5909
|
/**
|
|
3977
5910
|
* Register tags for a cache key in the in-process index and (if Redis is enabled) in
|
|
@@ -4011,38 +5944,74 @@ var CacheService = class _CacheService {
|
|
|
4011
5944
|
* await cache.delete('user:abc:*'); // all keys for user abc
|
|
4012
5945
|
*/
|
|
4013
5946
|
async delete(cacheKey) {
|
|
5947
|
+
this._assertActive("delete");
|
|
4014
5948
|
const span = this._startSpan("tricache.delete");
|
|
4015
5949
|
if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
4016
|
-
|
|
4017
|
-
|
|
4018
|
-
|
|
4019
|
-
|
|
4020
|
-
|
|
4021
|
-
|
|
4022
|
-
|
|
4023
|
-
|
|
4024
|
-
|
|
4025
|
-
|
|
4026
|
-
this._cascadeDependencies(k);
|
|
4027
|
-
for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
|
|
4028
|
-
}
|
|
4029
|
-
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
4030
|
-
try {
|
|
4031
|
-
const client = await this.getRedis();
|
|
4032
|
-
if (isPattern) {
|
|
4033
|
-
const keys = await this._scanKeys(client, k);
|
|
4034
|
-
if (keys.length > 0) await client.del(...keys);
|
|
4035
|
-
} else {
|
|
4036
|
-
await client.del(k);
|
|
5950
|
+
try {
|
|
5951
|
+
const isPattern = cacheKey.includes("*");
|
|
5952
|
+
const k = this.nk(cacheKey);
|
|
5953
|
+
this.counters.deletes++;
|
|
5954
|
+
if (isPattern) {
|
|
5955
|
+
const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
|
|
5956
|
+
for (const liveKey of this.l1.liveKeys()) {
|
|
5957
|
+
if (liveKey.startsWith(pfx)) {
|
|
5958
|
+
this._bumpKeyMutation(liveKey);
|
|
5959
|
+
}
|
|
4037
5960
|
}
|
|
4038
|
-
this.
|
|
4039
|
-
|
|
4040
|
-
|
|
4041
|
-
|
|
5961
|
+
for (const inflightKey of Array.from(this.inflight.keys())) {
|
|
5962
|
+
if (inflightKey.startsWith(pfx)) {
|
|
5963
|
+
this._bumpKeyMutation(inflightKey);
|
|
5964
|
+
this.inflight.delete(inflightKey);
|
|
5965
|
+
}
|
|
5966
|
+
}
|
|
5967
|
+
this._addPatternTombstone(pfx);
|
|
5968
|
+
this.l1.deletePattern(k);
|
|
5969
|
+
} else {
|
|
5970
|
+
this._bumpKeyMutation(k);
|
|
5971
|
+
this.inflight.delete(k);
|
|
5972
|
+
this.l1.delete(k);
|
|
5973
|
+
this._pendingDiskDeletes.add(k);
|
|
5974
|
+
setImmediate(() => {
|
|
5975
|
+
try {
|
|
5976
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
5977
|
+
} finally {
|
|
5978
|
+
this._pendingDiskDeletes.delete(k);
|
|
5979
|
+
}
|
|
5980
|
+
});
|
|
5981
|
+
this._cascadeDependencies(k);
|
|
5982
|
+
for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
|
|
5983
|
+
}
|
|
5984
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5985
|
+
try {
|
|
5986
|
+
const client = await this.getRedis();
|
|
5987
|
+
if (isPattern) {
|
|
5988
|
+
const keys = await this._scanKeys(client, k);
|
|
5989
|
+
if (keys.length > 0) await client.del(...keys);
|
|
5990
|
+
} else {
|
|
5991
|
+
if (this.opts.autoPipeline && this.pipeliner) {
|
|
5992
|
+
await this.pipeliner.del(k);
|
|
5993
|
+
} else {
|
|
5994
|
+
await client.del(k);
|
|
5995
|
+
}
|
|
5996
|
+
}
|
|
5997
|
+
this.cb.onSuccess();
|
|
5998
|
+
} catch (err) {
|
|
5999
|
+
this.cb.onFailure();
|
|
6000
|
+
this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
|
|
6001
|
+
}
|
|
6002
|
+
}
|
|
6003
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6004
|
+
await this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
|
|
6005
|
+
} else {
|
|
6006
|
+
void this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
|
|
4042
6007
|
}
|
|
6008
|
+
} catch (err) {
|
|
6009
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6010
|
+
span.recordException?.(err);
|
|
6011
|
+
throw err;
|
|
6012
|
+
} finally {
|
|
6013
|
+
span.end();
|
|
4043
6014
|
}
|
|
4044
|
-
void this.publishInvalidation(isPattern ? "del-glob" : "del", k);
|
|
4045
|
-
span.end();
|
|
4046
6015
|
}
|
|
4047
6016
|
// ── Counter (distributed rate limiting) ──────────────────────────────────
|
|
4048
6017
|
/**
|
|
@@ -4062,6 +6031,7 @@ var CacheService = class _CacheService {
|
|
|
4062
6031
|
* fleet-wide.
|
|
4063
6032
|
*/
|
|
4064
6033
|
async increment(cacheKey, ttlSeconds) {
|
|
6034
|
+
this._assertActive("increment");
|
|
4065
6035
|
const k = this.nk(cacheKey);
|
|
4066
6036
|
if (this._redisDisabled) {
|
|
4067
6037
|
if (!this._incrementFallbackWarned) {
|
|
@@ -4103,31 +6073,73 @@ var CacheService = class _CacheService {
|
|
|
4103
6073
|
* await cache.clear('user:abc'); // flush all keys for one user
|
|
4104
6074
|
*/
|
|
4105
6075
|
async clear(prefix) {
|
|
4106
|
-
this.
|
|
4107
|
-
const
|
|
4108
|
-
if (
|
|
4109
|
-
|
|
4110
|
-
|
|
4111
|
-
this.
|
|
4112
|
-
if (
|
|
4113
|
-
|
|
4114
|
-
|
|
4115
|
-
|
|
4116
|
-
|
|
4117
|
-
|
|
4118
|
-
|
|
4119
|
-
const
|
|
4120
|
-
|
|
4121
|
-
|
|
4122
|
-
|
|
4123
|
-
|
|
4124
|
-
|
|
6076
|
+
this._assertActive("clear");
|
|
6077
|
+
const span = this._startSpan("tricache.clear");
|
|
6078
|
+
if (this.opts.tracer) span.setAttribute("cache.prefix", prefix || "*");
|
|
6079
|
+
try {
|
|
6080
|
+
this.counters.deletes++;
|
|
6081
|
+
const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
|
|
6082
|
+
if (k) {
|
|
6083
|
+
const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
|
|
6084
|
+
for (const liveKey of this.l1.liveKeys()) {
|
|
6085
|
+
if (liveKey.startsWith(pfx)) {
|
|
6086
|
+
this._bumpKeyMutation(liveKey);
|
|
6087
|
+
}
|
|
6088
|
+
}
|
|
6089
|
+
for (const inflightKey of Array.from(this.inflight.keys())) {
|
|
6090
|
+
if (inflightKey.startsWith(pfx)) {
|
|
6091
|
+
this._bumpKeyMutation(inflightKey);
|
|
6092
|
+
this.inflight.delete(inflightKey);
|
|
6093
|
+
}
|
|
6094
|
+
}
|
|
6095
|
+
this._addPatternTombstone(pfx);
|
|
6096
|
+
this.l1.deletePattern(k);
|
|
6097
|
+
} else {
|
|
6098
|
+
this._globalEpoch++;
|
|
6099
|
+
this.inflight.clear();
|
|
6100
|
+
this._patternTombstones.length = 0;
|
|
6101
|
+
this.l1.clear();
|
|
6102
|
+
if (!this._diskDisabled) this.disk.clear();
|
|
6103
|
+
this._l1Counters.clear();
|
|
6104
|
+
this.tagIndex.clear();
|
|
6105
|
+
this.tagVersions.clear();
|
|
6106
|
+
this._pendingDiskDeletes.clear();
|
|
6107
|
+
this._keyMutationEpochs.clear();
|
|
6108
|
+
}
|
|
6109
|
+
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
6110
|
+
try {
|
|
6111
|
+
const client = await this.getRedis();
|
|
6112
|
+
const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
|
|
6113
|
+
const keys = await this._scanKeys(client, pattern);
|
|
6114
|
+
if (keys.length > 0) await client.del(...keys);
|
|
6115
|
+
} catch (err) {
|
|
6116
|
+
this.logger.debug("clear: Redis unavailable", { error: err.message });
|
|
6117
|
+
}
|
|
6118
|
+
}
|
|
6119
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6120
|
+
await this.publishInvalidation(
|
|
6121
|
+
"del-glob",
|
|
6122
|
+
k ?? (this._namespace ? `${this._namespace}:*` : "*"),
|
|
6123
|
+
void 0,
|
|
6124
|
+
false,
|
|
6125
|
+
true
|
|
6126
|
+
);
|
|
6127
|
+
} else {
|
|
6128
|
+
void this.publishInvalidation(
|
|
6129
|
+
"del-glob",
|
|
6130
|
+
k ?? (this._namespace ? `${this._namespace}:*` : "*"),
|
|
6131
|
+
void 0,
|
|
6132
|
+
false,
|
|
6133
|
+
true
|
|
6134
|
+
);
|
|
4125
6135
|
}
|
|
6136
|
+
} catch (err) {
|
|
6137
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6138
|
+
span.recordException?.(err);
|
|
6139
|
+
throw err;
|
|
6140
|
+
} finally {
|
|
6141
|
+
span.end();
|
|
4126
6142
|
}
|
|
4127
|
-
void this.publishInvalidation(
|
|
4128
|
-
"del-glob",
|
|
4129
|
-
k ?? (this._namespace ? `${this._namespace}:*` : "*")
|
|
4130
|
-
);
|
|
4131
6143
|
}
|
|
4132
6144
|
/**
|
|
4133
6145
|
* Evict L1 entries that violate the current category or global capacity limits.
|
|
@@ -4135,6 +6147,7 @@ var CacheService = class _CacheService {
|
|
|
4135
6147
|
* Returns the number of entries evicted.
|
|
4136
6148
|
*/
|
|
4137
6149
|
rebalance() {
|
|
6150
|
+
this._assertActive("rebalance");
|
|
4138
6151
|
return this.l1.rebalance();
|
|
4139
6152
|
}
|
|
4140
6153
|
/**
|
|
@@ -4143,6 +6156,7 @@ var CacheService = class _CacheService {
|
|
|
4143
6156
|
* Only reflects L1 state — does not query Redis or disk.
|
|
4144
6157
|
*/
|
|
4145
6158
|
ttl(cacheKey) {
|
|
6159
|
+
this._assertActive("ttl");
|
|
4146
6160
|
return this.l1.ttl(this.nk(cacheKey));
|
|
4147
6161
|
}
|
|
4148
6162
|
/**
|
|
@@ -4150,6 +6164,7 @@ var CacheService = class _CacheService {
|
|
|
4150
6164
|
* Bloom-filter fast path — no fetch, no disk or Redis round-trip.
|
|
4151
6165
|
*/
|
|
4152
6166
|
has(cacheKey) {
|
|
6167
|
+
this._assertActive("has");
|
|
4153
6168
|
return this.l1.has(this.nk(cacheKey));
|
|
4154
6169
|
}
|
|
4155
6170
|
// ── Iteration ─────────────────────────────────────────────────────────────
|
|
@@ -4160,6 +6175,7 @@ var CacheService = class _CacheService {
|
|
|
4160
6175
|
* for (const key of cache.keys()) console.log(key);
|
|
4161
6176
|
*/
|
|
4162
6177
|
*keys() {
|
|
6178
|
+
this._assertActive("keys");
|
|
4163
6179
|
const prefix = this._namespace ? this._namespace + ":" : "";
|
|
4164
6180
|
for (const key of this.l1.liveKeys()) {
|
|
4165
6181
|
if (prefix && !key.startsWith(prefix)) continue;
|
|
@@ -4174,6 +6190,7 @@ var CacheService = class _CacheService {
|
|
|
4174
6190
|
* for (const val of cache.values<User>()) console.log(val.id);
|
|
4175
6191
|
*/
|
|
4176
6192
|
*values() {
|
|
6193
|
+
this._assertActive("values");
|
|
4177
6194
|
const prefix = this._namespace ? this._namespace + ":" : "";
|
|
4178
6195
|
if (!prefix) {
|
|
4179
6196
|
yield* this.l1.liveValues();
|
|
@@ -4192,6 +6209,7 @@ var CacheService = class _CacheService {
|
|
|
4192
6209
|
* for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
|
|
4193
6210
|
*/
|
|
4194
6211
|
*entries() {
|
|
6212
|
+
this._assertActive("entries");
|
|
4195
6213
|
const prefix = this._namespace ? this._namespace + ":" : "";
|
|
4196
6214
|
for (const [key, entry] of this.l1.liveEntries()) {
|
|
4197
6215
|
if (prefix && !key.startsWith(prefix)) continue;
|
|
@@ -4219,6 +6237,7 @@ var CacheService = class _CacheService {
|
|
|
4219
6237
|
* `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
|
|
4220
6238
|
*/
|
|
4221
6239
|
scan(fn) {
|
|
6240
|
+
this._assertActive("scan");
|
|
4222
6241
|
const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
|
|
4223
6242
|
this.l1.scan((key, entry, pfx) => {
|
|
4224
6243
|
const value = entry.value !== void 0 ? entry.value : entry.data;
|
|
@@ -4232,6 +6251,7 @@ var CacheService = class _CacheService {
|
|
|
4232
6251
|
* @param newTtlSeconds - The new TTL from now, in seconds.
|
|
4233
6252
|
*/
|
|
4234
6253
|
async touch(cacheKey, newTtlSeconds) {
|
|
6254
|
+
this._assertActive("touch");
|
|
4235
6255
|
const k = this.nk(cacheKey);
|
|
4236
6256
|
const hit = this.l1.touch(k, newTtlSeconds * 1e3);
|
|
4237
6257
|
if (hit && !this._redisDisabled) {
|
|
@@ -4252,13 +6272,14 @@ var CacheService = class _CacheService {
|
|
|
4252
6272
|
* if (fresh !== null) return fresh; // serve from L1, no network hop
|
|
4253
6273
|
*/
|
|
4254
6274
|
getIfFresh(cacheKey) {
|
|
6275
|
+
this._assertActive("getIfFresh");
|
|
4255
6276
|
const k = this.nk(cacheKey);
|
|
4256
6277
|
const entry = this.l1.getEntry(k);
|
|
4257
6278
|
if (!entry) return null;
|
|
4258
6279
|
const now = Date.now();
|
|
4259
6280
|
if (entry.expiresAt <= now) return null;
|
|
4260
6281
|
if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
|
|
4261
|
-
return entry.value !== void 0 ? entry.value :
|
|
6282
|
+
return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
4262
6283
|
}
|
|
4263
6284
|
/**
|
|
4264
6285
|
* Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
|
|
@@ -4269,6 +6290,7 @@ var CacheService = class _CacheService {
|
|
|
4269
6290
|
* const val = await cache.peek<User>('user:123');
|
|
4270
6291
|
*/
|
|
4271
6292
|
async peek(cacheKey) {
|
|
6293
|
+
this._assertActive("peek");
|
|
4272
6294
|
const k = this.nk(cacheKey);
|
|
4273
6295
|
const l1Hit = this.l1.get(k);
|
|
4274
6296
|
if (l1Hit !== null) {
|
|
@@ -4278,21 +6300,32 @@ var CacheService = class _CacheService {
|
|
|
4278
6300
|
if (this.opts.frozen) deepFreeze(val);
|
|
4279
6301
|
return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
|
|
4280
6302
|
}
|
|
4281
|
-
if (!this._diskDisabled) {
|
|
4282
|
-
|
|
4283
|
-
|
|
4284
|
-
|
|
4285
|
-
|
|
4286
|
-
|
|
4287
|
-
|
|
4288
|
-
|
|
4289
|
-
|
|
4290
|
-
|
|
4291
|
-
|
|
4292
|
-
|
|
4293
|
-
|
|
4294
|
-
|
|
4295
|
-
|
|
6303
|
+
if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
|
|
6304
|
+
if (this._isTombstonedByPattern(k)) {
|
|
6305
|
+
try {
|
|
6306
|
+
this.disk.delete(k);
|
|
6307
|
+
} catch {
|
|
6308
|
+
}
|
|
6309
|
+
} else if (this.watchdog.isDiskAllowed()) {
|
|
6310
|
+
const diskStart = performance.now();
|
|
6311
|
+
const diskHit = this.disk.load(k);
|
|
6312
|
+
const diskElapsed = performance.now() - diskStart;
|
|
6313
|
+
this.watchdog.recordDisk(diskElapsed);
|
|
6314
|
+
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
6315
|
+
if (diskHit !== null) {
|
|
6316
|
+
const promoted = this.l1.importEntries(
|
|
6317
|
+
[{ key: k, entry: diskHit }],
|
|
6318
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
6319
|
+
);
|
|
6320
|
+
if (promoted > 0) {
|
|
6321
|
+
const l1Check = this.l1.get(k);
|
|
6322
|
+
if (l1Check !== null) {
|
|
6323
|
+
this.counters.gets++;
|
|
6324
|
+
this.counters.diskHits++;
|
|
6325
|
+
const val = l1Check.value;
|
|
6326
|
+
if (this.opts.frozen) deepFreeze(val);
|
|
6327
|
+
return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
|
|
6328
|
+
}
|
|
4296
6329
|
}
|
|
4297
6330
|
}
|
|
4298
6331
|
}
|
|
@@ -4300,7 +6333,10 @@ var CacheService = class _CacheService {
|
|
|
4300
6333
|
if (!this._redisDisabled && !this.cb.isOpen) {
|
|
4301
6334
|
try {
|
|
4302
6335
|
const client = await this.getRedis();
|
|
6336
|
+
const redisStart = performance.now();
|
|
4303
6337
|
const raw = await client.get(k);
|
|
6338
|
+
const redisElapsed = performance.now() - redisStart;
|
|
6339
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
4304
6340
|
if (raw !== null) {
|
|
4305
6341
|
const parsed = await this._decryptAndDeserialize(raw);
|
|
4306
6342
|
this.l1.set(k, parsed, 6e4, inferPriority(cacheKey));
|
|
@@ -4327,90 +6363,138 @@ var CacheService = class _CacheService {
|
|
|
4327
6363
|
* `(key) => number` so heterogeneous TTLs can be batched in one call.
|
|
4328
6364
|
*/
|
|
4329
6365
|
async mget(keys, fetchFn, ttl = 300, priority) {
|
|
4330
|
-
|
|
4331
|
-
const
|
|
4332
|
-
|
|
4333
|
-
|
|
4334
|
-
const k = this.nk(keys[i]);
|
|
4335
|
-
const entry = this.l1.getEntry(k);
|
|
4336
|
-
if (entry && entry.expiresAt > Date.now()) {
|
|
4337
|
-
result[i] = entry.value !== void 0 ? entry.value : (0, import_msgpackr3.unpack)(entry.data);
|
|
4338
|
-
this.counters.l1Hits++;
|
|
4339
|
-
} else {
|
|
4340
|
-
missIndexes.push(i);
|
|
4341
|
-
missKeys.push(keys[i]);
|
|
4342
|
-
}
|
|
6366
|
+
this._assertActive("mget");
|
|
6367
|
+
const span = this._startSpan("tricache.mget");
|
|
6368
|
+
if (this.opts.tracer) {
|
|
6369
|
+
span.setAttribute("cache.batch.size", keys.length);
|
|
4343
6370
|
}
|
|
4344
|
-
|
|
4345
|
-
|
|
4346
|
-
|
|
4347
|
-
|
|
4348
|
-
|
|
4349
|
-
const
|
|
4350
|
-
|
|
4351
|
-
|
|
4352
|
-
|
|
4353
|
-
|
|
4354
|
-
|
|
4355
|
-
|
|
4356
|
-
|
|
4357
|
-
|
|
4358
|
-
|
|
4359
|
-
|
|
4360
|
-
|
|
4361
|
-
|
|
4362
|
-
|
|
4363
|
-
|
|
4364
|
-
|
|
6371
|
+
try {
|
|
6372
|
+
const result = Array.from({ length: keys.length });
|
|
6373
|
+
const missIndexes = [];
|
|
6374
|
+
const missKeys = [];
|
|
6375
|
+
for (let i = 0; i < keys.length; i++) {
|
|
6376
|
+
const k = this.nk(keys[i]);
|
|
6377
|
+
const entry = this.l1.getEntry(k);
|
|
6378
|
+
if (entry && entry.expiresAt > Date.now()) {
|
|
6379
|
+
result[i] = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
6380
|
+
this.counters.l1Hits++;
|
|
6381
|
+
} else {
|
|
6382
|
+
missIndexes.push(i);
|
|
6383
|
+
missKeys.push(keys[i]);
|
|
6384
|
+
}
|
|
6385
|
+
}
|
|
6386
|
+
if (missKeys.length === 0) {
|
|
6387
|
+
if (this.opts.tracer) {
|
|
6388
|
+
span.setAttribute("cache.hits", keys.length);
|
|
6389
|
+
span.setAttribute("cache.misses", 0);
|
|
6390
|
+
span.setAttribute("cache.l1_hits", keys.length);
|
|
6391
|
+
span.setAttribute("cache.l2_hits", 0);
|
|
6392
|
+
}
|
|
6393
|
+
return result;
|
|
6394
|
+
}
|
|
6395
|
+
let l2HitCount = 0;
|
|
6396
|
+
if (!this._redisDisabled) {
|
|
6397
|
+
try {
|
|
6398
|
+
const client = await this.getRedis();
|
|
6399
|
+
const nsKeys = missKeys.map((k) => this.nk(k));
|
|
6400
|
+
const pipeline = client.multi();
|
|
6401
|
+
for (const nk of nsKeys) pipeline.get(nk);
|
|
6402
|
+
const redisStart = performance.now();
|
|
6403
|
+
const raws = await pipeline.exec();
|
|
6404
|
+
const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
|
|
6405
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
6406
|
+
this.cb.onSuccess();
|
|
6407
|
+
for (let j = 0; j < missKeys.length; j++) {
|
|
6408
|
+
const raw = raws[j] ? raws[j][1] : null;
|
|
6409
|
+
const idx = missIndexes[j];
|
|
6410
|
+
if (raw) {
|
|
6411
|
+
const parsed = await this._decryptAndDeserialize(raw);
|
|
6412
|
+
const k = nsKeys[j];
|
|
6413
|
+
const p = priority ?? inferPriority(missKeys[j]);
|
|
6414
|
+
this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
|
|
6415
|
+
this.counters.l2Hits++;
|
|
6416
|
+
l2HitCount++;
|
|
6417
|
+
result[idx] = parsed;
|
|
6418
|
+
missIndexes[j] = -1;
|
|
6419
|
+
missKeys[j] = "";
|
|
6420
|
+
}
|
|
4365
6421
|
}
|
|
6422
|
+
const remainingIdx = missIndexes.filter((i) => i >= 0);
|
|
6423
|
+
const remainingKeys = missKeys.filter((k) => k !== "");
|
|
6424
|
+
missIndexes.length = 0;
|
|
6425
|
+
missKeys.length = 0;
|
|
6426
|
+
missIndexes.push(...remainingIdx);
|
|
6427
|
+
missKeys.push(...remainingKeys);
|
|
6428
|
+
} catch (err) {
|
|
6429
|
+
this.cb.onFailure();
|
|
6430
|
+
this.logger.debug("mget: Redis unavailable, continuing to disk/fetch", { error: err.message });
|
|
4366
6431
|
}
|
|
4367
|
-
const remainingIdx = missIndexes.filter((i) => i >= 0);
|
|
4368
|
-
const remainingKeys = missKeys.filter((k) => k !== "");
|
|
4369
|
-
missIndexes.length = 0;
|
|
4370
|
-
missKeys.length = 0;
|
|
4371
|
-
missIndexes.push(...remainingIdx);
|
|
4372
|
-
missKeys.push(...remainingKeys);
|
|
4373
|
-
if (missKeys.length === 0) return result;
|
|
4374
|
-
} catch (err) {
|
|
4375
|
-
this.cb.onFailure();
|
|
4376
|
-
this.logger.debug("mget: Redis unavailable, continuing to disk/fetch", { error: err.message });
|
|
4377
6432
|
}
|
|
4378
|
-
|
|
4379
|
-
|
|
4380
|
-
|
|
4381
|
-
|
|
4382
|
-
|
|
4383
|
-
|
|
4384
|
-
|
|
4385
|
-
|
|
4386
|
-
|
|
4387
|
-
|
|
4388
|
-
|
|
4389
|
-
|
|
4390
|
-
|
|
4391
|
-
|
|
4392
|
-
|
|
4393
|
-
|
|
4394
|
-
|
|
6433
|
+
if (!this._diskDisabled && missKeys.length > 0) {
|
|
6434
|
+
for (let j = missKeys.length - 1; j >= 0; j--) {
|
|
6435
|
+
const k = this.nk(missKeys[j]);
|
|
6436
|
+
if (this._pendingDiskDeletes.has(k)) continue;
|
|
6437
|
+
if (this._isTombstonedByPattern(k)) {
|
|
6438
|
+
try {
|
|
6439
|
+
this.disk.delete(k);
|
|
6440
|
+
} catch {
|
|
6441
|
+
}
|
|
6442
|
+
continue;
|
|
6443
|
+
}
|
|
6444
|
+
if (!this.watchdog.isDiskAllowed()) continue;
|
|
6445
|
+
const diskStart = performance.now();
|
|
6446
|
+
const diskHit = this.disk.load(k);
|
|
6447
|
+
const diskElapsed = performance.now() - diskStart;
|
|
6448
|
+
this.watchdog.recordDisk(diskElapsed);
|
|
6449
|
+
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
6450
|
+
if (diskHit !== null) {
|
|
6451
|
+
const promoted = this.l1.importEntries(
|
|
6452
|
+
[{ key: k, entry: diskHit }],
|
|
6453
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
6454
|
+
);
|
|
6455
|
+
if (promoted > 0) {
|
|
6456
|
+
const l1Check = this.l1.get(k);
|
|
6457
|
+
if (l1Check !== null) {
|
|
6458
|
+
this.counters.diskHits++;
|
|
6459
|
+
result[missIndexes[j]] = l1Check.value;
|
|
6460
|
+
missIndexes.splice(j, 1);
|
|
6461
|
+
missKeys.splice(j, 1);
|
|
6462
|
+
}
|
|
4395
6463
|
}
|
|
4396
6464
|
}
|
|
4397
6465
|
}
|
|
4398
6466
|
}
|
|
4399
|
-
if (missKeys.length
|
|
4400
|
-
|
|
4401
|
-
|
|
4402
|
-
|
|
4403
|
-
|
|
4404
|
-
|
|
4405
|
-
|
|
4406
|
-
|
|
4407
|
-
|
|
4408
|
-
|
|
4409
|
-
|
|
6467
|
+
if (missKeys.length > 0) {
|
|
6468
|
+
this.counters.fetches++;
|
|
6469
|
+
const fetched = await fetchFn(missKeys);
|
|
6470
|
+
const setPromises = [];
|
|
6471
|
+
for (let j = 0; j < missKeys.length; j++) {
|
|
6472
|
+
const v = fetched[missKeys[j]];
|
|
6473
|
+
result[missIndexes[j]] = v;
|
|
6474
|
+
if (v !== void 0) {
|
|
6475
|
+
const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
|
|
6476
|
+
setPromises.push(this.set(missKeys[j], v, resolvedTtl, priority));
|
|
6477
|
+
}
|
|
4410
6478
|
}
|
|
6479
|
+
if (setPromises.length > 0) {
|
|
6480
|
+
await Promise.all(setPromises);
|
|
6481
|
+
}
|
|
6482
|
+
}
|
|
6483
|
+
if (this.opts.tracer) {
|
|
6484
|
+
const finalMisses = missKeys.length;
|
|
6485
|
+
const totalHits = keys.length - finalMisses;
|
|
6486
|
+
span.setAttribute("cache.hits", totalHits);
|
|
6487
|
+
span.setAttribute("cache.misses", finalMisses);
|
|
6488
|
+
span.setAttribute("cache.l2_hits", l2HitCount);
|
|
4411
6489
|
}
|
|
6490
|
+
return result;
|
|
6491
|
+
} catch (err) {
|
|
6492
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6493
|
+
span.recordException?.(err);
|
|
6494
|
+
throw err;
|
|
6495
|
+
} finally {
|
|
6496
|
+
span.end();
|
|
4412
6497
|
}
|
|
4413
|
-
return result;
|
|
4414
6498
|
}
|
|
4415
6499
|
/**
|
|
4416
6500
|
* Returns a Promise that resolves once the cache is fully initialised and any
|
|
@@ -4437,12 +6521,25 @@ var CacheService = class _CacheService {
|
|
|
4437
6521
|
* });
|
|
4438
6522
|
*/
|
|
4439
6523
|
async mset(entries) {
|
|
6524
|
+
this._assertActive("mset");
|
|
6525
|
+
const span = this._startSpan("tricache.mset");
|
|
4440
6526
|
const keys = Object.keys(entries);
|
|
4441
|
-
|
|
4442
|
-
|
|
4443
|
-
|
|
4444
|
-
|
|
4445
|
-
|
|
6527
|
+
if (this.opts.tracer) {
|
|
6528
|
+
span.setAttribute("cache.batch.size", keys.length);
|
|
6529
|
+
}
|
|
6530
|
+
try {
|
|
6531
|
+
await Promise.all(keys.map((key) => {
|
|
6532
|
+
const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
|
|
6533
|
+
const hasOpts = tags?.length || dependsOn?.length;
|
|
6534
|
+
return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
|
|
6535
|
+
}));
|
|
6536
|
+
} catch (err) {
|
|
6537
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6538
|
+
span.recordException?.(err);
|
|
6539
|
+
throw err;
|
|
6540
|
+
} finally {
|
|
6541
|
+
span.end();
|
|
6542
|
+
}
|
|
4446
6543
|
}
|
|
4447
6544
|
/**
|
|
4448
6545
|
* Batch delete — delete multiple exact keys in a single call.
|
|
@@ -4452,7 +6549,20 @@ var CacheService = class _CacheService {
|
|
|
4452
6549
|
* await cache.mdel(['user:1', 'user:2', 'user:3']);
|
|
4453
6550
|
*/
|
|
4454
6551
|
async mdel(keys) {
|
|
4455
|
-
|
|
6552
|
+
this._assertActive("mdel");
|
|
6553
|
+
const span = this._startSpan("tricache.mdel");
|
|
6554
|
+
if (this.opts.tracer) {
|
|
6555
|
+
span.setAttribute("cache.batch.size", keys.length);
|
|
6556
|
+
}
|
|
6557
|
+
try {
|
|
6558
|
+
await Promise.all(keys.map((k) => this.delete(k)));
|
|
6559
|
+
} catch (err) {
|
|
6560
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6561
|
+
span.recordException?.(err);
|
|
6562
|
+
throw err;
|
|
6563
|
+
} finally {
|
|
6564
|
+
span.end();
|
|
6565
|
+
}
|
|
4456
6566
|
}
|
|
4457
6567
|
/**
|
|
4458
6568
|
* Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
|
|
@@ -4467,6 +6577,7 @@ var CacheService = class _CacheService {
|
|
|
4467
6577
|
* console.log(`Warmed ${loaded} keys from Redis`);
|
|
4468
6578
|
*/
|
|
4469
6579
|
async warmFromL2(pattern, opts) {
|
|
6580
|
+
this._assertActive("warmFromL2");
|
|
4470
6581
|
if (this._redisDisabled) return 0;
|
|
4471
6582
|
try {
|
|
4472
6583
|
const client = await this.getRedis();
|
|
@@ -4481,7 +6592,6 @@ var CacheService = class _CacheService {
|
|
|
4481
6592
|
const results = await pl.exec();
|
|
4482
6593
|
this.cb.onSuccess();
|
|
4483
6594
|
let loaded = 0;
|
|
4484
|
-
const now = Date.now();
|
|
4485
6595
|
for (let i = 0; i < matchedKeys.length; i++) {
|
|
4486
6596
|
const [err, raw] = results[i];
|
|
4487
6597
|
if (err || raw == null) continue;
|
|
@@ -4493,7 +6603,6 @@ var CacheService = class _CacheService {
|
|
|
4493
6603
|
} catch {
|
|
4494
6604
|
}
|
|
4495
6605
|
}
|
|
4496
|
-
void now;
|
|
4497
6606
|
this.logger.info("warmFromL2 complete", {
|
|
4498
6607
|
pattern,
|
|
4499
6608
|
matched: matchedKeys.length,
|
|
@@ -4515,45 +6624,71 @@ var CacheService = class _CacheService {
|
|
|
4515
6624
|
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
4516
6625
|
*/
|
|
4517
6626
|
async invalidateTag(tag) {
|
|
4518
|
-
|
|
4519
|
-
|
|
6627
|
+
this._assertActive("invalidateTag");
|
|
6628
|
+
const span = this._startSpan("tricache.invalidate_tag");
|
|
6629
|
+
if (this.opts.tracer) {
|
|
6630
|
+
span.setAttribute("cache.tag", tag);
|
|
6631
|
+
span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
|
|
6632
|
+
}
|
|
6633
|
+
try {
|
|
6634
|
+
if (this.opts.tagStrategy === "generational") {
|
|
6635
|
+
let newVer = 1;
|
|
6636
|
+
if (!this._redisDisabled) {
|
|
6637
|
+
try {
|
|
6638
|
+
const client = await this.getRedis();
|
|
6639
|
+
newVer = await client.incr(this.nk(`tag_ver:${tag}`));
|
|
6640
|
+
} catch (err) {
|
|
6641
|
+
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
6642
|
+
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
6643
|
+
newVer = current + 1;
|
|
6644
|
+
}
|
|
6645
|
+
} else {
|
|
6646
|
+
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
6647
|
+
newVer = current + 1;
|
|
6648
|
+
}
|
|
6649
|
+
this._setLocalTagVersion(tag, newVer, performance.now());
|
|
6650
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6651
|
+
await this.publishInvalidation("tag_incr", tag, newVer, false, true);
|
|
6652
|
+
} else {
|
|
6653
|
+
void this.publishInvalidation("tag_incr", tag, newVer, false, true);
|
|
6654
|
+
}
|
|
6655
|
+
return;
|
|
6656
|
+
}
|
|
6657
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
6658
|
+
const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
|
|
6659
|
+
for (const k of members) {
|
|
6660
|
+
this.l1.delete(k);
|
|
6661
|
+
this._bumpKeyMutation(k);
|
|
6662
|
+
this._pendingDiskDeletes.add(k);
|
|
6663
|
+
setImmediate(() => {
|
|
6664
|
+
try {
|
|
6665
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
6666
|
+
} finally {
|
|
6667
|
+
this._pendingDiskDeletes.delete(k);
|
|
6668
|
+
}
|
|
6669
|
+
});
|
|
6670
|
+
}
|
|
6671
|
+
this.tagIndex.delete(tagKey);
|
|
4520
6672
|
if (!this._redisDisabled) {
|
|
4521
6673
|
try {
|
|
4522
6674
|
const client = await this.getRedis();
|
|
4523
|
-
|
|
6675
|
+
const redisMembers = await client.smembers(tagKey);
|
|
6676
|
+
const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
|
|
6677
|
+
if (toDelete.length > 0) {
|
|
6678
|
+
await client.del(...toDelete, tagKey);
|
|
6679
|
+
} else {
|
|
6680
|
+
await client.del(tagKey);
|
|
6681
|
+
}
|
|
4524
6682
|
} catch (err) {
|
|
4525
6683
|
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
4526
|
-
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
4527
|
-
newVer = current + 1;
|
|
4528
|
-
}
|
|
4529
|
-
} else {
|
|
4530
|
-
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
4531
|
-
newVer = current + 1;
|
|
4532
|
-
}
|
|
4533
|
-
this._setLocalTagVersion(tag, newVer, Date.now());
|
|
4534
|
-
void this.publishInvalidation("tag_incr", tag, newVer);
|
|
4535
|
-
return;
|
|
4536
|
-
}
|
|
4537
|
-
const tagKey = this.nk(`_tag_:${tag}`);
|
|
4538
|
-
const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
|
|
4539
|
-
for (const k of members) {
|
|
4540
|
-
this.l1.delete(k);
|
|
4541
|
-
if (!this._diskDisabled) this.disk.delete(k);
|
|
4542
|
-
}
|
|
4543
|
-
this.tagIndex.delete(tagKey);
|
|
4544
|
-
if (!this._redisDisabled) {
|
|
4545
|
-
try {
|
|
4546
|
-
const client = await this.getRedis();
|
|
4547
|
-
const redisMembers = await client.smembers(tagKey);
|
|
4548
|
-
const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
|
|
4549
|
-
if (toDelete.length > 0) {
|
|
4550
|
-
await client.del(...toDelete, tagKey);
|
|
4551
|
-
} else {
|
|
4552
|
-
await client.del(tagKey);
|
|
4553
6684
|
}
|
|
4554
|
-
} catch (err) {
|
|
4555
|
-
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
4556
6685
|
}
|
|
6686
|
+
} catch (err) {
|
|
6687
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6688
|
+
span.recordException?.(err);
|
|
6689
|
+
throw err;
|
|
6690
|
+
} finally {
|
|
6691
|
+
span.end();
|
|
4557
6692
|
}
|
|
4558
6693
|
}
|
|
4559
6694
|
/**
|
|
@@ -4569,13 +6704,14 @@ var CacheService = class _CacheService {
|
|
|
4569
6704
|
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
|
|
4570
6705
|
*/
|
|
4571
6706
|
async invalidateTags(tags) {
|
|
6707
|
+
this._assertActive("invalidateTags");
|
|
4572
6708
|
if (tags.length === 0) return;
|
|
4573
6709
|
if (tags.length === 1) {
|
|
4574
6710
|
await this.invalidateTag(tags[0]);
|
|
4575
6711
|
return;
|
|
4576
6712
|
}
|
|
4577
6713
|
if (this.opts.tagStrategy === "generational") {
|
|
4578
|
-
const now =
|
|
6714
|
+
const now = performance.now();
|
|
4579
6715
|
if (!this._redisDisabled) {
|
|
4580
6716
|
try {
|
|
4581
6717
|
const client = await this.getRedis();
|
|
@@ -4586,7 +6722,11 @@ var CacheService = class _CacheService {
|
|
|
4586
6722
|
const [err, newVer] = results[i] ?? [null, null];
|
|
4587
6723
|
const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
|
|
4588
6724
|
this._setLocalTagVersion(tags[i], ver, now);
|
|
4589
|
-
|
|
6725
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6726
|
+
await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
|
|
6727
|
+
} else {
|
|
6728
|
+
void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
|
|
6729
|
+
}
|
|
4590
6730
|
}
|
|
4591
6731
|
return;
|
|
4592
6732
|
} catch (err) {
|
|
@@ -4596,7 +6736,11 @@ var CacheService = class _CacheService {
|
|
|
4596
6736
|
for (const tag of tags) {
|
|
4597
6737
|
const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
4598
6738
|
this._setLocalTagVersion(tag, ver, now);
|
|
4599
|
-
|
|
6739
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6740
|
+
await this.publishInvalidation("tag_incr", tag, ver, false, true);
|
|
6741
|
+
} else {
|
|
6742
|
+
void this.publishInvalidation("tag_incr", tag, ver, false, true);
|
|
6743
|
+
}
|
|
4600
6744
|
}
|
|
4601
6745
|
return;
|
|
4602
6746
|
}
|
|
@@ -4611,7 +6755,15 @@ var CacheService = class _CacheService {
|
|
|
4611
6755
|
}
|
|
4612
6756
|
for (const k of allMembers) {
|
|
4613
6757
|
this.l1.delete(k);
|
|
4614
|
-
this.
|
|
6758
|
+
this._bumpKeyMutation(k);
|
|
6759
|
+
this._pendingDiskDeletes.add(k);
|
|
6760
|
+
setImmediate(() => {
|
|
6761
|
+
try {
|
|
6762
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
6763
|
+
} finally {
|
|
6764
|
+
this._pendingDiskDeletes.delete(k);
|
|
6765
|
+
}
|
|
6766
|
+
});
|
|
4615
6767
|
}
|
|
4616
6768
|
if (!this._redisDisabled) {
|
|
4617
6769
|
try {
|
|
@@ -4648,6 +6800,7 @@ var CacheService = class _CacheService {
|
|
|
4648
6800
|
* `l2` is `null` when Redis is disabled.
|
|
4649
6801
|
*/
|
|
4650
6802
|
async ping() {
|
|
6803
|
+
this._assertActive("ping");
|
|
4651
6804
|
const t0 = Date.now();
|
|
4652
6805
|
this.l1.has("__ping__");
|
|
4653
6806
|
const l1 = Date.now() - t0;
|
|
@@ -4667,12 +6820,67 @@ var CacheService = class _CacheService {
|
|
|
4667
6820
|
}
|
|
4668
6821
|
return { l1, disk, l2 };
|
|
4669
6822
|
}
|
|
6823
|
+
/**
|
|
6824
|
+
* Health and readiness diagnostics for container orchestrators (e.g. Kubernetes, ECS, Nomad).
|
|
6825
|
+
*
|
|
6826
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
6827
|
+
* ⚠️ CRITICAL CONTAINER PROBE SEMANTICS (Liveness vs. Readiness):
|
|
6828
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
6829
|
+
* ❌ NEVER bind `degraded` checks or `cache.health()` to your Liveness Probe (/livez, /healthz).
|
|
6830
|
+
* If an SRE hooks degraded status into liveness, a storage-starved or EBS-throttled pod
|
|
6831
|
+
* will be killed by the kubelet, triggering a cluster-wide cascading restart shockwave.
|
|
6832
|
+
* Liveness probes must only check that the event loop / process is alive.
|
|
6833
|
+
*
|
|
6834
|
+
* ✅ BIND degraded checks strictly to your Readiness Probe (/ready, /readyz).
|
|
6835
|
+
* A degraded cache (e.g. EBS latency spike, quota watermark pruning, or open Redis circuit)
|
|
6836
|
+
* can shed traffic at the ingress load balancer while the Node.js process remains
|
|
6837
|
+
* alive to drain in-flight promises and heal its local storage.
|
|
6838
|
+
*
|
|
6839
|
+
* By default, `healthy` remains `true` even when degraded (graceful local degradation).
|
|
6840
|
+
* Set `failReadinessOnDegraded: true` in CacheOptions if you want your Readiness probe
|
|
6841
|
+
* to route ingress traffic away while degraded.
|
|
6842
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
6843
|
+
*/
|
|
6844
|
+
health() {
|
|
6845
|
+
const watchdogTel = this.watchdog.getTelemetry();
|
|
6846
|
+
const diskPruning = !this._diskDisabled && this.disk.isPruning;
|
|
6847
|
+
const diskLowSpace = !this._diskDisabled && this.disk.hostVolumeLowSpace;
|
|
6848
|
+
const circuitOpen = this.cb.isOpen;
|
|
6849
|
+
const latencyBypass = watchdogTel.bypassActive;
|
|
6850
|
+
const degraded = circuitOpen || latencyBypass || diskPruning || diskLowSpace;
|
|
6851
|
+
const healthy = this.opts.failReadinessOnDegraded ? !degraded : true;
|
|
6852
|
+
const reasons = [];
|
|
6853
|
+
if (circuitOpen) reasons.push("redis_circuit_breaker_open");
|
|
6854
|
+
if (latencyBypass) reasons.push(`disk_latency_bypass_stage_${watchdogTel.bypassStage}`);
|
|
6855
|
+
if (diskPruning) reasons.push("disk_quota_watermark_pruning_active");
|
|
6856
|
+
if (diskLowSpace) reasons.push("disk_host_volume_low_space");
|
|
6857
|
+
return {
|
|
6858
|
+
healthy,
|
|
6859
|
+
degraded,
|
|
6860
|
+
reasons,
|
|
6861
|
+
details: {
|
|
6862
|
+
redisConnected: !circuitOpen && !this._redisDisabled,
|
|
6863
|
+
circuitBreakerState: this.cb.currentState,
|
|
6864
|
+
diskPruningActive: diskPruning,
|
|
6865
|
+
diskHostVolumeLowSpace: diskLowSpace,
|
|
6866
|
+
watchdog: watchdogTel
|
|
6867
|
+
}
|
|
6868
|
+
};
|
|
6869
|
+
}
|
|
6870
|
+
/**
|
|
6871
|
+
* Direct access to the internal tier latency watchdog instance.
|
|
6872
|
+
* Used for diagnostics, canary probes, and control-loop tuning.
|
|
6873
|
+
*/
|
|
6874
|
+
getLatencyWatchdog() {
|
|
6875
|
+
return this.watchdog;
|
|
6876
|
+
}
|
|
4670
6877
|
/**
|
|
4671
6878
|
* Export all live L1 entries to Redis via a single pipeline.
|
|
4672
6879
|
* Useful for warming a new Redis instance or for zero-downtime failover.
|
|
4673
6880
|
* Returns the number of keys written.
|
|
4674
6881
|
*/
|
|
4675
6882
|
async drainToL2() {
|
|
6883
|
+
this._assertActive("drainToL2");
|
|
4676
6884
|
if (this._redisDisabled) return 0;
|
|
4677
6885
|
try {
|
|
4678
6886
|
const client = await this.getRedis();
|
|
@@ -4716,6 +6924,7 @@ var CacheService = class _CacheService {
|
|
|
4716
6924
|
* if (!claimed) return res.status(409).json({ error: 'duplicate request' });
|
|
4717
6925
|
*/
|
|
4718
6926
|
async setIfAbsent(cacheKey, value, ttlSeconds = 300, priority) {
|
|
6927
|
+
this._assertActive("setIfAbsent");
|
|
4719
6928
|
const k = this.nk(cacheKey);
|
|
4720
6929
|
if (this.l1.has(k)) return false;
|
|
4721
6930
|
if (!this._redisDisabled) {
|
|
@@ -4734,6 +6943,8 @@ var CacheService = class _CacheService {
|
|
|
4734
6943
|
}
|
|
4735
6944
|
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
4736
6945
|
const p = priority ?? inferPriority(cacheKey);
|
|
6946
|
+
this._bumpKeyMutation(k);
|
|
6947
|
+
this._pendingDiskDeletes.delete(k);
|
|
4737
6948
|
this.l1.set(k, value, ttlMs, p);
|
|
4738
6949
|
this.counters.sets++;
|
|
4739
6950
|
return true;
|
|
@@ -4752,6 +6963,7 @@ var CacheService = class _CacheService {
|
|
|
4752
6963
|
* @param options TTL, acquire timeout, and retry polling intervals.
|
|
4753
6964
|
*/
|
|
4754
6965
|
async lock(resourceKey, fn, options) {
|
|
6966
|
+
this._assertActive("lock");
|
|
4755
6967
|
const ttlSeconds = Math.max(1, options?.ttl ?? 30);
|
|
4756
6968
|
const acquireTimeout = Math.max(0, options?.acquireTimeout ?? 5e3);
|
|
4757
6969
|
const retryInterval = Math.max(10, options?.retryInterval ?? 100);
|
|
@@ -4778,6 +6990,10 @@ var CacheService = class _CacheService {
|
|
|
4778
6990
|
}
|
|
4779
6991
|
} catch (err) {
|
|
4780
6992
|
if (err.message.startsWith("Failed to acquire lock")) throw err;
|
|
6993
|
+
const failClosed = options?.failClosedOnRedisError ?? this.opts.lockFailClosed;
|
|
6994
|
+
if (failClosed) {
|
|
6995
|
+
throw new Error(`Distributed lock acquisition failed for resource "${resourceKey}" due to Redis error: ${err.message}`);
|
|
6996
|
+
}
|
|
4781
6997
|
this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
|
|
4782
6998
|
resourceKey,
|
|
4783
6999
|
error: err.message
|
|
@@ -4914,7 +7130,7 @@ var CacheService = class _CacheService {
|
|
|
4914
7130
|
if (visited.has(dep)) continue;
|
|
4915
7131
|
this.l1.delete(dep);
|
|
4916
7132
|
if (!this._diskDisabled) this.disk.delete(dep);
|
|
4917
|
-
void this.publishInvalidation("del", dep);
|
|
7133
|
+
void this.publishInvalidation("del", dep, void 0, false, true);
|
|
4918
7134
|
this.logger.debug("Dependency cascade: invalidated dependent key", {
|
|
4919
7135
|
trigger: deletedKey.slice(0, 60),
|
|
4920
7136
|
dependent: dep.slice(0, 60)
|
|
@@ -4979,12 +7195,36 @@ var CacheService = class _CacheService {
|
|
|
4979
7195
|
evictions: c.oomEvictions,
|
|
4980
7196
|
lastTriggeredAt: c.oomLastAt
|
|
4981
7197
|
},
|
|
7198
|
+
...this.opts.remoteSnapshot && {
|
|
7199
|
+
remoteSnapshot: {
|
|
7200
|
+
enabled: true,
|
|
7201
|
+
uploads: c.remoteSnapshotUploads,
|
|
7202
|
+
downloads: c.remoteSnapshotDownloads,
|
|
7203
|
+
errors: c.remoteSnapshotErrors,
|
|
7204
|
+
lastUploadedAt: c.remoteSnapshotLastUploadedAt,
|
|
7205
|
+
lastDownloadedAt: c.remoteSnapshotLastDownloadedAt
|
|
7206
|
+
}
|
|
7207
|
+
},
|
|
7208
|
+
...this.opts.crossRegion && {
|
|
7209
|
+
crossRegion: {
|
|
7210
|
+
enabled: true,
|
|
7211
|
+
currentRegion: this.opts.crossRegion.currentRegion,
|
|
7212
|
+
sent: c.crossRegionSent,
|
|
7213
|
+
received: c.crossRegionReceived,
|
|
7214
|
+
deduplicated: c.crossRegionDeduplicated,
|
|
7215
|
+
errors: c.crossRegionErrors
|
|
7216
|
+
}
|
|
7217
|
+
},
|
|
4982
7218
|
l1: {
|
|
4983
7219
|
entries: l1s.entries,
|
|
4984
7220
|
sizeBytes: this.l1.memoryUsage,
|
|
4985
7221
|
maxBytes: this.opts.l1MaxBytes
|
|
4986
7222
|
},
|
|
4987
|
-
disk: {
|
|
7223
|
+
disk: {
|
|
7224
|
+
...this.disk.stats,
|
|
7225
|
+
disabled: this._diskDisabled,
|
|
7226
|
+
latencyWatchdog: this.watchdog.getTelemetry()
|
|
7227
|
+
},
|
|
4988
7228
|
...this.latencyTracker && {
|
|
4989
7229
|
adaptiveTtl: {
|
|
4990
7230
|
enabled: true,
|
|
@@ -4997,9 +7237,16 @@ var CacheService = class _CacheService {
|
|
|
4997
7237
|
this.opts.adaptiveTtlMaxMs
|
|
4998
7238
|
)
|
|
4999
7239
|
}
|
|
7240
|
+
},
|
|
7241
|
+
...this.pipeliner && {
|
|
7242
|
+
pipelining: this.pipeliner.stats
|
|
5000
7243
|
}
|
|
5001
7244
|
};
|
|
5002
7245
|
}
|
|
7246
|
+
/** Return auto-pipelining metrics, or null if pipelining is disabled. */
|
|
7247
|
+
getPipelinerStats() {
|
|
7248
|
+
return this.pipeliner ? this.pipeliner.stats : null;
|
|
7249
|
+
}
|
|
5003
7250
|
/**
|
|
5004
7251
|
* Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
|
|
5005
7252
|
* Paste the result into your `/metrics` endpoint.
|
|
@@ -5039,6 +7286,18 @@ var CacheService = class _CacheService {
|
|
|
5039
7286
|
gauge("l1_entries", m.l1.entries, "Current L1 entry count");
|
|
5040
7287
|
gauge("l1_size_bytes", m.l1.sizeBytes, "Current L1 used bytes");
|
|
5041
7288
|
gauge("disk_files", m.disk.files, "Current L1.5 disk file count");
|
|
7289
|
+
if (m.disk.latencyWatchdog) {
|
|
7290
|
+
gauge("disk_latency_bypass_stage", m.disk.latencyWatchdog.bypassStage, "Disk latency watchdog bypass stage (0: normal, 1: 25%, 2: 75%, 3: 100%)");
|
|
7291
|
+
gauge("disk_p95_ms", m.disk.latencyWatchdog.diskP95Ms, "Disk read p95 latency in ms");
|
|
7292
|
+
gauge("redis_p95_ms", m.disk.latencyWatchdog.redisP95Ms, "Redis read p95 latency in ms");
|
|
7293
|
+
counter("disk_bypassed_events", m.disk.latencyWatchdog.bypassedTotal, "Total disk bypass activation events");
|
|
7294
|
+
}
|
|
7295
|
+
if (m.disk.pruning) {
|
|
7296
|
+
counter("disk_spills_shed", m.disk.pruning.spillsShedTotal, "Total disk spills shed due to pruning or low disk space");
|
|
7297
|
+
counter("disk_prune_rounds", m.disk.pruning.pruneRounds, "Total high-watermark disk prune rounds");
|
|
7298
|
+
counter("disk_entries_pruned", m.disk.pruning.entriesPruned, "Total entries removed by watermark pruning");
|
|
7299
|
+
counter("disk_low_space_pauses", m.disk.pruning.hostVolumeLowSpacePauses, "Total times spills paused due to <10% host volume space");
|
|
7300
|
+
}
|
|
5042
7301
|
gauge(
|
|
5043
7302
|
"bloom_false_positive_rate",
|
|
5044
7303
|
m.bloom.falsePositiveRate,
|
|
@@ -5060,6 +7319,17 @@ var CacheService = class _CacheService {
|
|
|
5060
7319
|
"Emergency L1 eviction rounds triggered by heap pressure"
|
|
5061
7320
|
);
|
|
5062
7321
|
}
|
|
7322
|
+
if (m.remoteSnapshot?.enabled) {
|
|
7323
|
+
counter("remote_snapshot_uploads", m.remoteSnapshot.uploads, "Total remote snapshot uploads");
|
|
7324
|
+
counter("remote_snapshot_downloads", m.remoteSnapshot.downloads, "Total remote snapshot downloads");
|
|
7325
|
+
counter("remote_snapshot_errors", m.remoteSnapshot.errors, "Total remote snapshot errors");
|
|
7326
|
+
}
|
|
7327
|
+
if (m.crossRegion?.enabled) {
|
|
7328
|
+
counter("cross_region_sent", m.crossRegion.sent, "Total cross-region invalidations broadcast");
|
|
7329
|
+
counter("cross_region_received", m.crossRegion.received, "Total cross-region invalidations received");
|
|
7330
|
+
counter("cross_region_deduplicated", m.crossRegion.deduplicated, "Total cross-region invalidations deduplicated or self-filtered");
|
|
7331
|
+
counter("cross_region_errors", m.crossRegion.errors, "Total cross-region relay errors");
|
|
7332
|
+
}
|
|
5063
7333
|
return lines.join("\n");
|
|
5064
7334
|
}
|
|
5065
7335
|
// ── Lifecycle ────────────────────────────────────────────────────────────
|
|
@@ -5069,6 +7339,7 @@ var CacheService = class _CacheService {
|
|
|
5069
7339
|
* the previous key for seamless fallback decryption of existing cache entries.
|
|
5070
7340
|
*/
|
|
5071
7341
|
async rotateEncryptionKey(newKeyBase64, newMode) {
|
|
7342
|
+
this._assertActive("rotateEncryptionKey");
|
|
5072
7343
|
this.enc.rotateKey(newKeyBase64, newMode);
|
|
5073
7344
|
if (this._workerPool) {
|
|
5074
7345
|
await this._workerPool.drainAndReinit(this.enc.toWorkerInit());
|
|
@@ -5078,23 +7349,33 @@ var CacheService = class _CacheService {
|
|
|
5078
7349
|
/** Close Redis connections and stop all background timers. */
|
|
5079
7350
|
async destroy() {
|
|
5080
7351
|
this._destroyed = true;
|
|
7352
|
+
this._pendingDiskDeletes.clear();
|
|
7353
|
+
this._keyMutationEpochs.clear();
|
|
7354
|
+
const g = globalThis;
|
|
7355
|
+
const key = _CacheService.globalKey(this.opts);
|
|
7356
|
+
if (g[key] === this) {
|
|
7357
|
+
delete g[key];
|
|
7358
|
+
}
|
|
5081
7359
|
if (this.cleanupInterval) clearInterval(this.cleanupInterval);
|
|
5082
7360
|
if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
|
|
5083
7361
|
if (this.oomInterval) clearInterval(this.oomInterval);
|
|
5084
7362
|
if (this.metricsInterval) clearInterval(this.metricsInterval);
|
|
5085
|
-
if (this.
|
|
5086
|
-
|
|
5087
|
-
|
|
5088
|
-
this._shutdownHandler = null;
|
|
7363
|
+
if (this.remoteSnapshotInterval) {
|
|
7364
|
+
clearInterval(this.remoteSnapshotInterval);
|
|
7365
|
+
this.remoteSnapshotInterval = null;
|
|
5089
7366
|
}
|
|
7367
|
+
ProcessTerminationBus.unregister(this);
|
|
7368
|
+
this._shutdownHandler = null;
|
|
5090
7369
|
if (this._workerPool) {
|
|
5091
7370
|
await this._workerPool.destroy();
|
|
5092
7371
|
this._workerPool = null;
|
|
5093
7372
|
}
|
|
5094
7373
|
if (this.subClient) {
|
|
5095
|
-
|
|
5096
|
-
|
|
5097
|
-
|
|
7374
|
+
if (!this.opts.redisSubClient) {
|
|
7375
|
+
try {
|
|
7376
|
+
this.subClient.disconnect();
|
|
7377
|
+
} catch {
|
|
7378
|
+
}
|
|
5098
7379
|
}
|
|
5099
7380
|
this.subClient = null;
|
|
5100
7381
|
}
|
|
@@ -5106,14 +7387,33 @@ var CacheService = class _CacheService {
|
|
|
5106
7387
|
this.streamClient = null;
|
|
5107
7388
|
}
|
|
5108
7389
|
if (this.redis) {
|
|
5109
|
-
|
|
5110
|
-
|
|
5111
|
-
|
|
7390
|
+
if (!this.opts.redisClient) {
|
|
7391
|
+
try {
|
|
7392
|
+
await this.redis.disconnect();
|
|
7393
|
+
} catch {
|
|
7394
|
+
}
|
|
5112
7395
|
}
|
|
5113
7396
|
this.redis = null;
|
|
5114
7397
|
}
|
|
7398
|
+
if (this._ipcServer) {
|
|
7399
|
+
await this._ipcServer.close();
|
|
7400
|
+
this._ipcServer = void 0;
|
|
7401
|
+
}
|
|
5115
7402
|
if (!this._diskDisabled) this.disk.close();
|
|
5116
7403
|
}
|
|
7404
|
+
/**
|
|
7405
|
+
* Return the active IPC telemetry server instance, if enabled.
|
|
7406
|
+
*/
|
|
7407
|
+
getIpcServer() {
|
|
7408
|
+
return this._ipcServer;
|
|
7409
|
+
}
|
|
7410
|
+
/**
|
|
7411
|
+
* Return real-time telemetry and metrics for the Window TinyLFU admission policy.
|
|
7412
|
+
* Returns `undefined` if W-TinyLFU admission is not active.
|
|
7413
|
+
*/
|
|
7414
|
+
getWTinyLfuStats() {
|
|
7415
|
+
return this.l1.getWTinyLfuStats();
|
|
7416
|
+
}
|
|
5117
7417
|
};
|
|
5118
7418
|
|
|
5119
7419
|
// src/nestjs/tricache.store.ts
|