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