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