tricache 0.2.0 → 0.3.1
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/README.md +117 -15
- package/dist/index.cjs +341 -31
- package/dist/index.d.cts +146 -1
- package/dist/index.d.ts +146 -1
- package/dist/index.js +341 -31
- package/package.json +3 -2
- package/src/cache-service.ts +282 -28
- package/src/index.ts +2 -0
- package/src/smart-memory-cache.ts +125 -6
- package/src/types.ts +65 -0
package/dist/index.cjs
CHANGED
|
@@ -537,12 +537,66 @@ function createBloomFilter(logger) {
|
|
|
537
537
|
return new JsBloomFilter();
|
|
538
538
|
}
|
|
539
539
|
}
|
|
540
|
+
var SKETCH_ROWS = 4;
|
|
541
|
+
var SKETCH_WIDTH = 512;
|
|
542
|
+
var SKETCH_MASK = SKETCH_WIDTH - 1;
|
|
543
|
+
var SKETCH_DECAY_THRESHOLD = 1e5;
|
|
544
|
+
var CountMinSketch = class {
|
|
545
|
+
table = new Uint16Array(SKETCH_ROWS * SKETCH_WIDTH);
|
|
546
|
+
inserts = 0;
|
|
547
|
+
/** Inline FNV-1a for a string key → 32-bit unsigned integer. */
|
|
548
|
+
fnv32(key) {
|
|
549
|
+
let h = 2166136261;
|
|
550
|
+
for (let i = 0; i < key.length; i++) {
|
|
551
|
+
h ^= key.charCodeAt(i);
|
|
552
|
+
h = Math.imul(h, 16777619) >>> 0;
|
|
553
|
+
}
|
|
554
|
+
return h;
|
|
555
|
+
}
|
|
556
|
+
/** Four independent bit-mixes from one FNV-1a seed. */
|
|
557
|
+
hashes(key) {
|
|
558
|
+
const h = this.fnv32(key);
|
|
559
|
+
const h1 = (h ^ h >>> 16) >>> 0;
|
|
560
|
+
const h2 = (Math.imul(h1, 73244475) ^ h1 >>> 16) >>> 0;
|
|
561
|
+
const h3 = (Math.imul(h2, 2142877601) ^ h2 >>> 16) >>> 0;
|
|
562
|
+
const h4 = (Math.imul(h3, 461845907) ^ h3 >>> 16) >>> 0;
|
|
563
|
+
return [h1, h2, h3, h4];
|
|
564
|
+
}
|
|
565
|
+
/** Record one access. Decays all counters when the insertion threshold is crossed. */
|
|
566
|
+
increment(key) {
|
|
567
|
+
const [h1, h2, h3, h4] = this.hashes(key);
|
|
568
|
+
const t = this.table;
|
|
569
|
+
t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] = Math.min(65535, t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] + 1);
|
|
570
|
+
t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] = Math.min(65535, t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] + 1);
|
|
571
|
+
t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] = Math.min(65535, t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] + 1);
|
|
572
|
+
t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] = Math.min(65535, t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] + 1);
|
|
573
|
+
if (++this.inserts >= SKETCH_DECAY_THRESHOLD) this.decay();
|
|
574
|
+
}
|
|
575
|
+
/** Minimum-across-rows frequency estimate. */
|
|
576
|
+
estimate(key) {
|
|
577
|
+
const [h1, h2, h3, h4] = this.hashes(key);
|
|
578
|
+
const t = this.table;
|
|
579
|
+
return Math.min(
|
|
580
|
+
t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)],
|
|
581
|
+
t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)],
|
|
582
|
+
t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)],
|
|
583
|
+
t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)]
|
|
584
|
+
);
|
|
585
|
+
}
|
|
586
|
+
/** Halve all counters — ages out old frequency so bursts don't hold indefinitely. */
|
|
587
|
+
decay() {
|
|
588
|
+
for (let i = 0; i < this.table.length; i++) this.table[i] >>>= 1;
|
|
589
|
+
this.inserts = 0;
|
|
590
|
+
}
|
|
591
|
+
};
|
|
540
592
|
var SmartMemoryCache = class {
|
|
541
593
|
cache = /* @__PURE__ */ new Map();
|
|
542
594
|
opts;
|
|
543
595
|
bloom;
|
|
544
596
|
/** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
|
|
545
597
|
categoryPrefixes;
|
|
598
|
+
/** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
|
|
599
|
+
sketch = new CountMinSketch();
|
|
546
600
|
totalSize = 0;
|
|
547
601
|
categoryCount = /* @__PURE__ */ new Map();
|
|
548
602
|
categorySize = /* @__PURE__ */ new Map();
|
|
@@ -620,10 +674,10 @@ var SmartMemoryCache = class {
|
|
|
620
674
|
if (!catOvf && !glbOvf) return;
|
|
621
675
|
this.smartEvict(category, catOvf);
|
|
622
676
|
}
|
|
623
|
-
score(entry, catBonus, now) {
|
|
677
|
+
score(entry, catBonus, now, key) {
|
|
624
678
|
const age = now - entry.lastAccess;
|
|
625
679
|
const ttl = Math.max(0, entry.expiresAt - now);
|
|
626
|
-
const freq = Math.min(entry.hits, 100);
|
|
680
|
+
const freq = Math.min(Math.max(entry.hits, this.sketch.estimate(key)), 100);
|
|
627
681
|
return entry.priority * 1e3 + freq * 10 + ttl / 6e4 - age / 6e4 - catBonus;
|
|
628
682
|
}
|
|
629
683
|
/**
|
|
@@ -658,7 +712,7 @@ var SmartMemoryCache = class {
|
|
|
658
712
|
const entry = this.cache.get(key);
|
|
659
713
|
if (!entry || entry.priority === 4 && entry.expiresAt > now) continue;
|
|
660
714
|
catSeen++;
|
|
661
|
-
const s = this.score(entry, 100, now);
|
|
715
|
+
const s = this.score(entry, 100, now, key);
|
|
662
716
|
if (pool.length < EVICT) {
|
|
663
717
|
pool.push({ key, score: s });
|
|
664
718
|
} else {
|
|
@@ -676,7 +730,7 @@ var SmartMemoryCache = class {
|
|
|
676
730
|
if (entry.priority === 4 && entry.expiresAt > now) continue;
|
|
677
731
|
if (catOvf && this.getCategory(key) === targetCat) continue;
|
|
678
732
|
globalSeen++;
|
|
679
|
-
const s = this.score(entry, 0, now);
|
|
733
|
+
const s = this.score(entry, 0, now, key);
|
|
680
734
|
if (globalPool.length < remaining) {
|
|
681
735
|
globalPool.push({ key, score: s });
|
|
682
736
|
} else {
|
|
@@ -710,6 +764,7 @@ var SmartMemoryCache = class {
|
|
|
710
764
|
}
|
|
711
765
|
entry.hits++;
|
|
712
766
|
entry.lastAccess = now;
|
|
767
|
+
this.sketch.increment(key);
|
|
713
768
|
const cat = this.getCategory(key);
|
|
714
769
|
this.categoryHits.set(cat, (this.categoryHits.get(cat) ?? 0) + 1);
|
|
715
770
|
const value = entry.value !== void 0 ? entry.value : (0, import_msgpackr.unpack)(entry.data);
|
|
@@ -720,6 +775,7 @@ var SmartMemoryCache = class {
|
|
|
720
775
|
const packed = (0, import_msgpackr.pack)(data);
|
|
721
776
|
const size = packed.byteLength;
|
|
722
777
|
this.compressions++;
|
|
778
|
+
this.sketch.increment(key);
|
|
723
779
|
const cat = this.getCategory(key);
|
|
724
780
|
const lim = this.getCategoryLimit(cat);
|
|
725
781
|
if (size > lim.maxSizeBytes * 0.5) {
|
|
@@ -801,7 +857,7 @@ var SmartMemoryCache = class {
|
|
|
801
857
|
const entry = this.cache.get(key);
|
|
802
858
|
if (!entry) continue;
|
|
803
859
|
if (entry.priority === 4 && entry.expiresAt > now) continue;
|
|
804
|
-
candidates.push({ key, score: this.score(entry, 0, now) });
|
|
860
|
+
candidates.push({ key, score: this.score(entry, 0, now, key) });
|
|
805
861
|
}
|
|
806
862
|
candidates.sort((a, b) => a.score - b.score);
|
|
807
863
|
for (const { key } of candidates) {
|
|
@@ -847,7 +903,7 @@ var SmartMemoryCache = class {
|
|
|
847
903
|
const candidates = [];
|
|
848
904
|
for (const [key, entry] of this.cache) {
|
|
849
905
|
if (entry.priority === 4 && entry.expiresAt > now) continue;
|
|
850
|
-
candidates.push({ key, score: this.score(entry, 0, now) });
|
|
906
|
+
candidates.push({ key, score: this.score(entry, 0, now, key) });
|
|
851
907
|
}
|
|
852
908
|
candidates.sort((a, b) => a.score - b.score);
|
|
853
909
|
const count = Math.max(1, Math.ceil(candidates.length * pct));
|
|
@@ -902,6 +958,41 @@ var SmartMemoryCache = class {
|
|
|
902
958
|
this.recalculateStats();
|
|
903
959
|
return loaded;
|
|
904
960
|
}
|
|
961
|
+
// ── Iterators ─────────────────────────────────────────────────────────────
|
|
962
|
+
/**
|
|
963
|
+
* Lazily yields every [key, entry] pair whose TTL has not yet expired.
|
|
964
|
+
* Expired entries that are still in the Map (awaiting background cleanup)
|
|
965
|
+
* are silently skipped.
|
|
966
|
+
*/
|
|
967
|
+
*liveEntries() {
|
|
968
|
+
const now = Date.now();
|
|
969
|
+
for (const [key, entry] of this.cache) {
|
|
970
|
+
if (entry.expiresAt > now) yield [key, entry];
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
/**
|
|
974
|
+
* Yields only the keys of live entries — no intermediate tuple allocation.
|
|
975
|
+
* Use this instead of liveEntries() when you only need keys.
|
|
976
|
+
*/
|
|
977
|
+
*liveKeys() {
|
|
978
|
+
const now = Date.now();
|
|
979
|
+
for (const [key, entry] of this.cache) {
|
|
980
|
+
if (entry.expiresAt > now) yield key;
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
/**
|
|
984
|
+
* Yields only the resolved values of live entries.
|
|
985
|
+
* Iterates Map.values() so the key is never loaded into the yielded path.
|
|
986
|
+
* Returns the cached deserialized object when available (entry.value), otherwise
|
|
987
|
+
* the raw msgpackr Buffer — identical semantics to get() but without bloom/hit tracking.
|
|
988
|
+
*/
|
|
989
|
+
*liveValues() {
|
|
990
|
+
const now = Date.now();
|
|
991
|
+
for (const entry of this.cache.values()) {
|
|
992
|
+
if (entry.expiresAt > now)
|
|
993
|
+
yield entry.value !== void 0 ? entry.value : entry.data;
|
|
994
|
+
}
|
|
995
|
+
}
|
|
905
996
|
// ── Stats ─────────────────────────────────────────────────────────────────
|
|
906
997
|
get size() {
|
|
907
998
|
return this.cache.size;
|
|
@@ -1275,6 +1366,47 @@ var DEFAULT_CATEGORY_LIMITS = {
|
|
|
1275
1366
|
"default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
|
|
1276
1367
|
};
|
|
1277
1368
|
var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
|
|
1369
|
+
var L2CircuitBreaker = class {
|
|
1370
|
+
constructor(threshold, cooldownMs) {
|
|
1371
|
+
this.threshold = threshold;
|
|
1372
|
+
this.cooldownMs = cooldownMs;
|
|
1373
|
+
}
|
|
1374
|
+
threshold;
|
|
1375
|
+
cooldownMs;
|
|
1376
|
+
state = 0 /* CLOSED */;
|
|
1377
|
+
failures = 0;
|
|
1378
|
+
openedAt = 0;
|
|
1379
|
+
/** Call before each Redis attempt. Returns false when the circuit is open. */
|
|
1380
|
+
isAllowed() {
|
|
1381
|
+
if (this.state === 0 /* CLOSED */) return true;
|
|
1382
|
+
if (this.state === 2 /* HALF_OPEN */) return true;
|
|
1383
|
+
if (Date.now() - this.openedAt >= this.cooldownMs) {
|
|
1384
|
+
this.state = 2 /* HALF_OPEN */;
|
|
1385
|
+
return true;
|
|
1386
|
+
}
|
|
1387
|
+
return false;
|
|
1388
|
+
}
|
|
1389
|
+
/** Call on Redis success. */
|
|
1390
|
+
onSuccess() {
|
|
1391
|
+
this.failures = 0;
|
|
1392
|
+
this.state = 0 /* CLOSED */;
|
|
1393
|
+
}
|
|
1394
|
+
/** Call on Redis failure. */
|
|
1395
|
+
onFailure() {
|
|
1396
|
+
this.failures++;
|
|
1397
|
+
if (this.state === 2 /* HALF_OPEN */ || this.failures >= this.threshold) {
|
|
1398
|
+
this.state = 1 /* OPEN */;
|
|
1399
|
+
this.openedAt = Date.now();
|
|
1400
|
+
this.failures = 0;
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
get isOpen() {
|
|
1404
|
+
return this.state === 1 /* OPEN */;
|
|
1405
|
+
}
|
|
1406
|
+
get currentState() {
|
|
1407
|
+
return this.state === 0 /* CLOSED */ ? "closed" : this.state === 1 /* OPEN */ ? "open" : "half_open";
|
|
1408
|
+
}
|
|
1409
|
+
};
|
|
1278
1410
|
function inferPriority(cacheKey) {
|
|
1279
1411
|
if (cacheKey.includes("auth:") || cacheKey.includes("session:")) return 4 /* CRITICAL */;
|
|
1280
1412
|
if (cacheKey.includes("user:") || cacheKey.includes("org:") || cacheKey.includes("profile:")) return 3 /* HIGH */;
|
|
@@ -1299,6 +1431,7 @@ var CacheService = class _CacheService {
|
|
|
1299
1431
|
tagIndex = /* @__PURE__ */ new Map();
|
|
1300
1432
|
redis = null;
|
|
1301
1433
|
redisConnecting = null;
|
|
1434
|
+
cb;
|
|
1302
1435
|
snapshotLoaded = false;
|
|
1303
1436
|
cleanupInterval = null;
|
|
1304
1437
|
oomInterval = null;
|
|
@@ -1373,8 +1506,13 @@ var CacheService = class _CacheService {
|
|
|
1373
1506
|
metricsIntervalMs: options.metricsIntervalMs ?? 6e4,
|
|
1374
1507
|
staleIfError: options.staleIfError ?? 0,
|
|
1375
1508
|
l2WriteMode: options.l2WriteMode ?? "read-write",
|
|
1376
|
-
instanceName: options.instanceName ?? ""
|
|
1509
|
+
instanceName: options.instanceName ?? "",
|
|
1510
|
+
ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
|
|
1511
|
+
tracer: options.tracer
|
|
1377
1512
|
};
|
|
1513
|
+
const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
|
|
1514
|
+
const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
|
|
1515
|
+
this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
|
|
1378
1516
|
this.disk = new DiskTier({
|
|
1379
1517
|
dir: this.opts.diskCacheDir,
|
|
1380
1518
|
maxBytes: this.opts.diskMaxBytes,
|
|
@@ -1495,6 +1633,22 @@ var CacheService = class _CacheService {
|
|
|
1495
1633
|
nk(key) {
|
|
1496
1634
|
return this._namespace ? `${this._namespace}:${key}` : key;
|
|
1497
1635
|
}
|
|
1636
|
+
/** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
|
|
1637
|
+
_jitterTtl(ttlMs) {
|
|
1638
|
+
const j = this.opts.ttlJitterFactor;
|
|
1639
|
+
if (j === 0) return ttlMs;
|
|
1640
|
+
return Math.round(ttlMs * (1 + (Math.random() * 2 - 1) * j));
|
|
1641
|
+
}
|
|
1642
|
+
/** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
|
|
1643
|
+
_startSpan(name) {
|
|
1644
|
+
if (this.opts.tracer) return this.opts.tracer.startSpan(name);
|
|
1645
|
+
return { setAttribute() {
|
|
1646
|
+
return this;
|
|
1647
|
+
}, setStatus() {
|
|
1648
|
+
return this;
|
|
1649
|
+
}, end() {
|
|
1650
|
+
} };
|
|
1651
|
+
}
|
|
1498
1652
|
initBackplane() {
|
|
1499
1653
|
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
1500
1654
|
if (this.subClient) return;
|
|
@@ -1511,25 +1665,7 @@ var CacheService = class _CacheService {
|
|
|
1511
1665
|
});
|
|
1512
1666
|
sub.on("error", (e) => this.logger.debug("Backplane subscriber error", { error: e.message }));
|
|
1513
1667
|
sub.on("message", (_channel, message) => {
|
|
1514
|
-
|
|
1515
|
-
const msg = JSON.parse(message);
|
|
1516
|
-
if (msg.src === this.instanceId) {
|
|
1517
|
-
this.counters.invSkipped++;
|
|
1518
|
-
return;
|
|
1519
|
-
}
|
|
1520
|
-
this.counters.invReceived++;
|
|
1521
|
-
if (msg.op === "del") {
|
|
1522
|
-
this.l1.delete(msg.key);
|
|
1523
|
-
this.disk.delete(msg.key);
|
|
1524
|
-
} else if (msg.op === "del-glob") {
|
|
1525
|
-
this.l1.deletePattern(msg.key);
|
|
1526
|
-
}
|
|
1527
|
-
this.logger.debug("Backplane: peer invalidation applied", {
|
|
1528
|
-
op: msg.op,
|
|
1529
|
-
key: msg.key.slice(0, 60)
|
|
1530
|
-
});
|
|
1531
|
-
} catch {
|
|
1532
|
-
}
|
|
1668
|
+
this._handleBackplaneMessage(message);
|
|
1533
1669
|
});
|
|
1534
1670
|
sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
|
|
1535
1671
|
channel: this.backplaneChannel,
|
|
@@ -1539,6 +1675,28 @@ var CacheService = class _CacheService {
|
|
|
1539
1675
|
}));
|
|
1540
1676
|
this.subClient = sub;
|
|
1541
1677
|
}
|
|
1678
|
+
/** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
|
|
1679
|
+
_handleBackplaneMessage(message) {
|
|
1680
|
+
try {
|
|
1681
|
+
const msg = JSON.parse(message);
|
|
1682
|
+
if (msg.src === this.instanceId) {
|
|
1683
|
+
this.counters.invSkipped++;
|
|
1684
|
+
return;
|
|
1685
|
+
}
|
|
1686
|
+
this.counters.invReceived++;
|
|
1687
|
+
if (msg.op === "del") {
|
|
1688
|
+
this.l1.delete(msg.key);
|
|
1689
|
+
setImmediate(() => this.disk.delete(msg.key));
|
|
1690
|
+
} else if (msg.op === "del-glob") {
|
|
1691
|
+
this.l1.deletePattern(msg.key);
|
|
1692
|
+
}
|
|
1693
|
+
this.logger.debug("Backplane: peer invalidation applied", {
|
|
1694
|
+
op: msg.op,
|
|
1695
|
+
key: msg.key.slice(0, 60)
|
|
1696
|
+
});
|
|
1697
|
+
} catch {
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1542
1700
|
async publishInvalidation(op, key) {
|
|
1543
1701
|
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
1544
1702
|
try {
|
|
@@ -1552,7 +1710,7 @@ var CacheService = class _CacheService {
|
|
|
1552
1710
|
}
|
|
1553
1711
|
}
|
|
1554
1712
|
async getRedis() {
|
|
1555
|
-
if (this.
|
|
1713
|
+
if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
|
|
1556
1714
|
if (this.redisConnecting) return this.redisConnecting;
|
|
1557
1715
|
this.redisConnecting = (async () => {
|
|
1558
1716
|
try {
|
|
@@ -1576,10 +1734,12 @@ var CacheService = class _CacheService {
|
|
|
1576
1734
|
client.once("error", reject);
|
|
1577
1735
|
setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
|
|
1578
1736
|
});
|
|
1737
|
+
this.cb.onSuccess();
|
|
1579
1738
|
this.redis = client;
|
|
1580
1739
|
this.redisConnecting = null;
|
|
1581
1740
|
return client;
|
|
1582
1741
|
} catch (err) {
|
|
1742
|
+
this.cb.onFailure();
|
|
1583
1743
|
this.redisConnecting = null;
|
|
1584
1744
|
throw err;
|
|
1585
1745
|
}
|
|
@@ -1666,6 +1826,8 @@ var CacheService = class _CacheService {
|
|
|
1666
1826
|
* instantly while a background refresh runs. Default: 0 (disabled).
|
|
1667
1827
|
*/
|
|
1668
1828
|
async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
|
|
1829
|
+
const span = this._startSpan("tricache.get");
|
|
1830
|
+
span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
1669
1831
|
const k = this.nk(cacheKey);
|
|
1670
1832
|
this.counters.gets++;
|
|
1671
1833
|
const l1Hit = this.l1.get(k);
|
|
@@ -1685,24 +1847,28 @@ var CacheService = class _CacheService {
|
|
|
1685
1847
|
this.logger.debug("L1 hit");
|
|
1686
1848
|
}
|
|
1687
1849
|
this.counters.l1Hits++;
|
|
1850
|
+
span.setAttribute("cache.hit", "l1").end();
|
|
1688
1851
|
return l1Hit.value;
|
|
1689
1852
|
}
|
|
1690
|
-
const ttlMs = ttlSeconds * 1e3;
|
|
1853
|
+
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
1691
1854
|
const swrGraceMs = (opts.swr ?? 0) * 1e3;
|
|
1692
1855
|
const priority = opts.priority ?? inferPriority(cacheKey);
|
|
1693
1856
|
if (!this._redisDisabled) {
|
|
1694
1857
|
try {
|
|
1695
1858
|
const client = await this.getRedis();
|
|
1696
1859
|
const raw = await client.get(k);
|
|
1860
|
+
this.cb.onSuccess();
|
|
1697
1861
|
if (raw) {
|
|
1698
1862
|
const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
|
|
1699
1863
|
const parsed = JSON.parse(decrypted);
|
|
1700
1864
|
this.l1.set(k, parsed, ttlMs, priority);
|
|
1701
1865
|
this.counters.l2Hits++;
|
|
1702
1866
|
this.logger.debug("L2 hit (Redis)", { cacheKey });
|
|
1867
|
+
span.setAttribute("cache.hit", "l2").end();
|
|
1703
1868
|
return parsed;
|
|
1704
1869
|
}
|
|
1705
1870
|
} catch (err) {
|
|
1871
|
+
this.cb.onFailure();
|
|
1706
1872
|
this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
|
|
1707
1873
|
}
|
|
1708
1874
|
}
|
|
@@ -1717,14 +1883,17 @@ var CacheService = class _CacheService {
|
|
|
1717
1883
|
if (l1Check !== null) {
|
|
1718
1884
|
this.counters.diskHits++;
|
|
1719
1885
|
this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
|
|
1886
|
+
span.setAttribute("cache.hit", "disk").end();
|
|
1720
1887
|
return l1Check.value;
|
|
1721
1888
|
}
|
|
1722
1889
|
}
|
|
1723
1890
|
}
|
|
1891
|
+
span.setAttribute("cache.hit", "miss");
|
|
1724
1892
|
const existing = this.inflight.get(k);
|
|
1725
1893
|
if (existing) {
|
|
1726
1894
|
this.counters.stampedes++;
|
|
1727
1895
|
this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch", { cacheKey });
|
|
1896
|
+
span.end();
|
|
1728
1897
|
return existing;
|
|
1729
1898
|
}
|
|
1730
1899
|
const fetchPromise = (async () => {
|
|
@@ -1739,9 +1908,11 @@ var CacheService = class _CacheService {
|
|
|
1739
1908
|
const client = await this.getRedis();
|
|
1740
1909
|
const serialized = JSON.stringify(data);
|
|
1741
1910
|
const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
|
|
1742
|
-
await client.setex(k,
|
|
1911
|
+
await client.setex(k, Math.ceil(ttlMs / 1e3), toStore);
|
|
1912
|
+
this.cb.onSuccess();
|
|
1743
1913
|
this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
|
|
1744
1914
|
} catch {
|
|
1915
|
+
this.cb.onFailure();
|
|
1745
1916
|
this.logger.debug("Cached L1 only (Redis unavailable)", { cacheKey });
|
|
1746
1917
|
}
|
|
1747
1918
|
} else {
|
|
@@ -1750,6 +1921,7 @@ var CacheService = class _CacheService {
|
|
|
1750
1921
|
return data;
|
|
1751
1922
|
} finally {
|
|
1752
1923
|
this.inflight.delete(k);
|
|
1924
|
+
span.end();
|
|
1753
1925
|
}
|
|
1754
1926
|
})();
|
|
1755
1927
|
this.inflight.set(k, fetchPromise);
|
|
@@ -1788,7 +1960,9 @@ var CacheService = class _CacheService {
|
|
|
1788
1960
|
// ── Explicit set / delete ─────────────────────────────────────────────────
|
|
1789
1961
|
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
1790
1962
|
async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
|
|
1791
|
-
const
|
|
1963
|
+
const span = this._startSpan("tricache.set");
|
|
1964
|
+
span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
1965
|
+
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
1792
1966
|
const p = priority ?? inferPriority(cacheKey);
|
|
1793
1967
|
const k = this.nk(cacheKey);
|
|
1794
1968
|
this.counters.sets++;
|
|
@@ -1813,7 +1987,9 @@ var CacheService = class _CacheService {
|
|
|
1813
1987
|
pl.expire(tagKey, ttlSeconds + 3600);
|
|
1814
1988
|
}
|
|
1815
1989
|
await pl.exec();
|
|
1990
|
+
this.cb.onSuccess();
|
|
1816
1991
|
} catch {
|
|
1992
|
+
this.cb.onFailure();
|
|
1817
1993
|
}
|
|
1818
1994
|
}
|
|
1819
1995
|
}
|
|
@@ -1822,12 +1998,15 @@ var CacheService = class _CacheService {
|
|
|
1822
1998
|
const client = await this.getRedis();
|
|
1823
1999
|
const s = JSON.stringify(data);
|
|
1824
2000
|
const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
|
|
1825
|
-
await client.setex(k,
|
|
2001
|
+
await client.setex(k, Math.ceil(ttlMs / 1e3), stored);
|
|
2002
|
+
this.cb.onSuccess();
|
|
1826
2003
|
} catch (err) {
|
|
2004
|
+
this.cb.onFailure();
|
|
1827
2005
|
this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
|
|
1828
2006
|
}
|
|
1829
2007
|
}
|
|
1830
2008
|
void this.publishInvalidation("del", k);
|
|
2009
|
+
span.end();
|
|
1831
2010
|
}
|
|
1832
2011
|
/**
|
|
1833
2012
|
* Delete one key or a glob pattern (supports `*` wildcard).
|
|
@@ -1837,6 +2016,8 @@ var CacheService = class _CacheService {
|
|
|
1837
2016
|
* await cache.delete('user:abc:*'); // all keys for user abc
|
|
1838
2017
|
*/
|
|
1839
2018
|
async delete(cacheKey) {
|
|
2019
|
+
const span = this._startSpan("tricache.delete");
|
|
2020
|
+
span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
1840
2021
|
const isPattern = cacheKey.includes("*");
|
|
1841
2022
|
const k = this.nk(cacheKey);
|
|
1842
2023
|
this.counters.deletes++;
|
|
@@ -1861,11 +2042,14 @@ var CacheService = class _CacheService {
|
|
|
1861
2042
|
} else {
|
|
1862
2043
|
await client.del(k);
|
|
1863
2044
|
}
|
|
2045
|
+
this.cb.onSuccess();
|
|
1864
2046
|
} catch (err) {
|
|
2047
|
+
this.cb.onFailure();
|
|
1865
2048
|
this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
|
|
1866
2049
|
}
|
|
1867
2050
|
}
|
|
1868
2051
|
void this.publishInvalidation(isPattern ? "del-glob" : "del", k);
|
|
2052
|
+
span.end();
|
|
1869
2053
|
}
|
|
1870
2054
|
// ── Counter (distributed rate limiting) ──────────────────────────────────
|
|
1871
2055
|
/**
|
|
@@ -1958,6 +2142,43 @@ var CacheService = class _CacheService {
|
|
|
1958
2142
|
has(cacheKey) {
|
|
1959
2143
|
return this.l1.has(this.nk(cacheKey));
|
|
1960
2144
|
}
|
|
2145
|
+
// ── Iteration ─────────────────────────────────────────────────────────────
|
|
2146
|
+
/**
|
|
2147
|
+
* Lazily yield every non-expired L1 key, stripped of its namespace prefix.
|
|
2148
|
+
*
|
|
2149
|
+
* @example
|
|
2150
|
+
* for (const key of cache.keys()) console.log(key);
|
|
2151
|
+
*/
|
|
2152
|
+
*keys() {
|
|
2153
|
+
const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
|
|
2154
|
+
for (const key of this.l1.liveKeys()) {
|
|
2155
|
+
yield prefixLen > 0 ? key.slice(prefixLen) : key;
|
|
2156
|
+
}
|
|
2157
|
+
}
|
|
2158
|
+
/**
|
|
2159
|
+
* Lazily yield every non-expired L1 value.
|
|
2160
|
+
* Each value is the cached (pre-deserialized) JS object — no unpack overhead.
|
|
2161
|
+
*
|
|
2162
|
+
* @example
|
|
2163
|
+
* for (const val of cache.values<User>()) console.log(val.id);
|
|
2164
|
+
*/
|
|
2165
|
+
*values() {
|
|
2166
|
+
yield* this.l1.liveValues();
|
|
2167
|
+
}
|
|
2168
|
+
/**
|
|
2169
|
+
* Lazily yield every non-expired L1 [key, value] pair.
|
|
2170
|
+
* Keys are stripped of their namespace prefix.
|
|
2171
|
+
*
|
|
2172
|
+
* @example
|
|
2173
|
+
* for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
|
|
2174
|
+
*/
|
|
2175
|
+
*entries() {
|
|
2176
|
+
const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
|
|
2177
|
+
for (const [key, entry] of this.l1.liveEntries()) {
|
|
2178
|
+
const k = prefixLen > 0 ? key.slice(prefixLen) : key;
|
|
2179
|
+
yield [k, entry.value !== void 0 ? entry.value : entry.data];
|
|
2180
|
+
}
|
|
2181
|
+
}
|
|
1961
2182
|
/**
|
|
1962
2183
|
* Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
|
|
1963
2184
|
* Returns `false` if the key is absent or already expired.
|
|
@@ -2027,6 +2248,92 @@ var CacheService = class _CacheService {
|
|
|
2027
2248
|
}
|
|
2028
2249
|
return result;
|
|
2029
2250
|
}
|
|
2251
|
+
/**
|
|
2252
|
+
* Batch write — set multiple entries in a single call.
|
|
2253
|
+
* TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
|
|
2254
|
+
*
|
|
2255
|
+
* @example
|
|
2256
|
+
* await cache.mset({
|
|
2257
|
+
* 'user:1': { value: { name: 'Alice' }, ttl: 300 },
|
|
2258
|
+
* 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
|
|
2259
|
+
* });
|
|
2260
|
+
*/
|
|
2261
|
+
async mset(entries) {
|
|
2262
|
+
const keys = Object.keys(entries);
|
|
2263
|
+
await Promise.all(keys.map((key) => {
|
|
2264
|
+
const { value, ttl = 300, priority, tags } = entries[key];
|
|
2265
|
+
return this.set(key, value, ttl, priority, tags ? { tags } : void 0);
|
|
2266
|
+
}));
|
|
2267
|
+
}
|
|
2268
|
+
/**
|
|
2269
|
+
* Batch delete — delete multiple exact keys in a single call.
|
|
2270
|
+
* Glob patterns are not supported; use `delete('prefix:*')` for patterns.
|
|
2271
|
+
*
|
|
2272
|
+
* @example
|
|
2273
|
+
* await cache.mdel(['user:1', 'user:2', 'user:3']);
|
|
2274
|
+
*/
|
|
2275
|
+
async mdel(keys) {
|
|
2276
|
+
await Promise.all(keys.map((k) => this.delete(k)));
|
|
2277
|
+
}
|
|
2278
|
+
/**
|
|
2279
|
+
* Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
|
|
2280
|
+
* pulling them into L1. Useful on startup to eliminate cold-start penalty when
|
|
2281
|
+
* the local snapshot is unavailable or too stale.
|
|
2282
|
+
*
|
|
2283
|
+
* Returns the number of keys loaded into L1.
|
|
2284
|
+
*
|
|
2285
|
+
* @example
|
|
2286
|
+
* // In your startup hook (e.g. ECS task, k8s readiness probe):
|
|
2287
|
+
* const loaded = await cache.warmFromL2('org:*');
|
|
2288
|
+
* console.log(`Warmed ${loaded} keys from Redis`);
|
|
2289
|
+
*/
|
|
2290
|
+
async warmFromL2(pattern) {
|
|
2291
|
+
if (this._redisDisabled) return 0;
|
|
2292
|
+
try {
|
|
2293
|
+
const client = await this.getRedis();
|
|
2294
|
+
const nsPattern = this.nk(pattern);
|
|
2295
|
+
const matchedKeys = [];
|
|
2296
|
+
const stream = client.scanStream({ match: nsPattern, count: 100 });
|
|
2297
|
+
await new Promise((resolve, reject) => {
|
|
2298
|
+
stream.on("data", (chunk) => matchedKeys.push(...chunk));
|
|
2299
|
+
stream.on("end", resolve);
|
|
2300
|
+
stream.on("error", reject);
|
|
2301
|
+
});
|
|
2302
|
+
if (matchedKeys.length === 0) {
|
|
2303
|
+
this.cb.onSuccess();
|
|
2304
|
+
return 0;
|
|
2305
|
+
}
|
|
2306
|
+
const pl = client.pipeline();
|
|
2307
|
+
for (const k of matchedKeys) pl.get(k);
|
|
2308
|
+
const results = await pl.exec();
|
|
2309
|
+
this.cb.onSuccess();
|
|
2310
|
+
let loaded = 0;
|
|
2311
|
+
const now = Date.now();
|
|
2312
|
+
for (let i = 0; i < matchedKeys.length; i++) {
|
|
2313
|
+
const [err, raw] = results[i];
|
|
2314
|
+
if (err || raw == null) continue;
|
|
2315
|
+
try {
|
|
2316
|
+
const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
|
|
2317
|
+
const parsed = JSON.parse(decrypted);
|
|
2318
|
+
const remainingMs = 10 * 60 * 1e3;
|
|
2319
|
+
this.l1.set(matchedKeys[i], parsed, remainingMs, inferPriority(matchedKeys[i]));
|
|
2320
|
+
loaded++;
|
|
2321
|
+
} catch {
|
|
2322
|
+
}
|
|
2323
|
+
}
|
|
2324
|
+
void now;
|
|
2325
|
+
this.logger.info("warmFromL2 complete", {
|
|
2326
|
+
pattern,
|
|
2327
|
+
matched: matchedKeys.length,
|
|
2328
|
+
loaded
|
|
2329
|
+
});
|
|
2330
|
+
return loaded;
|
|
2331
|
+
} catch (err) {
|
|
2332
|
+
this.cb.onFailure();
|
|
2333
|
+
this.logger.debug("warmFromL2: Redis unavailable", { error: err.message });
|
|
2334
|
+
return 0;
|
|
2335
|
+
}
|
|
2336
|
+
}
|
|
2030
2337
|
/**
|
|
2031
2338
|
* Invalidate all keys associated with a tag.
|
|
2032
2339
|
* Deletes from L1, disk, and Redis (both the keyed values and the tag set).
|
|
@@ -2160,6 +2467,9 @@ var CacheService = class _CacheService {
|
|
|
2160
2467
|
received: c.invReceived,
|
|
2161
2468
|
skipped: c.invSkipped
|
|
2162
2469
|
},
|
|
2470
|
+
l2CircuitBreaker: {
|
|
2471
|
+
state: this.cb.currentState
|
|
2472
|
+
},
|
|
2163
2473
|
oom: {
|
|
2164
2474
|
enabled: this.opts.oomProtection,
|
|
2165
2475
|
evictions: c.oomEvictions,
|