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