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