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/dist/index.js CHANGED
@@ -495,12 +495,66 @@ function createBloomFilter(logger) {
495
495
  return new JsBloomFilter();
496
496
  }
497
497
  }
498
+ var SKETCH_ROWS = 4;
499
+ var SKETCH_WIDTH = 512;
500
+ var SKETCH_MASK = SKETCH_WIDTH - 1;
501
+ var SKETCH_DECAY_THRESHOLD = 1e5;
502
+ var CountMinSketch = class {
503
+ table = new Uint16Array(SKETCH_ROWS * SKETCH_WIDTH);
504
+ inserts = 0;
505
+ /** Inline FNV-1a for a string key → 32-bit unsigned integer. */
506
+ fnv32(key) {
507
+ let h = 2166136261;
508
+ for (let i = 0; i < key.length; i++) {
509
+ h ^= key.charCodeAt(i);
510
+ h = Math.imul(h, 16777619) >>> 0;
511
+ }
512
+ return h;
513
+ }
514
+ /** Four independent bit-mixes from one FNV-1a seed. */
515
+ hashes(key) {
516
+ const h = this.fnv32(key);
517
+ const h1 = (h ^ h >>> 16) >>> 0;
518
+ const h2 = (Math.imul(h1, 73244475) ^ h1 >>> 16) >>> 0;
519
+ const h3 = (Math.imul(h2, 2142877601) ^ h2 >>> 16) >>> 0;
520
+ const h4 = (Math.imul(h3, 461845907) ^ h3 >>> 16) >>> 0;
521
+ return [h1, h2, h3, h4];
522
+ }
523
+ /** Record one access. Decays all counters when the insertion threshold is crossed. */
524
+ increment(key) {
525
+ const [h1, h2, h3, h4] = this.hashes(key);
526
+ const t = this.table;
527
+ t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] = Math.min(65535, t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] + 1);
528
+ t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] = Math.min(65535, t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] + 1);
529
+ t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] = Math.min(65535, t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] + 1);
530
+ t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] = Math.min(65535, t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] + 1);
531
+ if (++this.inserts >= SKETCH_DECAY_THRESHOLD) this.decay();
532
+ }
533
+ /** Minimum-across-rows frequency estimate. */
534
+ estimate(key) {
535
+ const [h1, h2, h3, h4] = this.hashes(key);
536
+ const t = this.table;
537
+ return Math.min(
538
+ t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)],
539
+ t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)],
540
+ t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)],
541
+ t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)]
542
+ );
543
+ }
544
+ /** Halve all counters — ages out old frequency so bursts don't hold indefinitely. */
545
+ decay() {
546
+ for (let i = 0; i < this.table.length; i++) this.table[i] >>>= 1;
547
+ this.inserts = 0;
548
+ }
549
+ };
498
550
  var SmartMemoryCache = class {
499
551
  cache = /* @__PURE__ */ new Map();
500
552
  opts;
501
553
  bloom;
502
554
  /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
503
555
  categoryPrefixes;
556
+ /** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
557
+ sketch = new CountMinSketch();
504
558
  totalSize = 0;
505
559
  categoryCount = /* @__PURE__ */ new Map();
506
560
  categorySize = /* @__PURE__ */ new Map();
@@ -578,10 +632,10 @@ var SmartMemoryCache = class {
578
632
  if (!catOvf && !glbOvf) return;
579
633
  this.smartEvict(category, catOvf);
580
634
  }
581
- score(entry, catBonus, now) {
635
+ score(entry, catBonus, now, key) {
582
636
  const age = now - entry.lastAccess;
583
637
  const ttl = Math.max(0, entry.expiresAt - now);
584
- const freq = Math.min(entry.hits, 100);
638
+ const freq = Math.min(Math.max(entry.hits, this.sketch.estimate(key)), 100);
585
639
  return entry.priority * 1e3 + freq * 10 + ttl / 6e4 - age / 6e4 - catBonus;
586
640
  }
587
641
  /**
@@ -616,7 +670,7 @@ var SmartMemoryCache = class {
616
670
  const entry = this.cache.get(key);
617
671
  if (!entry || entry.priority === 4 && entry.expiresAt > now) continue;
618
672
  catSeen++;
619
- const s = this.score(entry, 100, now);
673
+ const s = this.score(entry, 100, now, key);
620
674
  if (pool.length < EVICT) {
621
675
  pool.push({ key, score: s });
622
676
  } else {
@@ -634,7 +688,7 @@ var SmartMemoryCache = class {
634
688
  if (entry.priority === 4 && entry.expiresAt > now) continue;
635
689
  if (catOvf && this.getCategory(key) === targetCat) continue;
636
690
  globalSeen++;
637
- const s = this.score(entry, 0, now);
691
+ const s = this.score(entry, 0, now, key);
638
692
  if (globalPool.length < remaining) {
639
693
  globalPool.push({ key, score: s });
640
694
  } else {
@@ -668,6 +722,7 @@ var SmartMemoryCache = class {
668
722
  }
669
723
  entry.hits++;
670
724
  entry.lastAccess = now;
725
+ this.sketch.increment(key);
671
726
  const cat = this.getCategory(key);
672
727
  this.categoryHits.set(cat, (this.categoryHits.get(cat) ?? 0) + 1);
673
728
  const value = entry.value !== void 0 ? entry.value : unpack(entry.data);
@@ -678,6 +733,7 @@ var SmartMemoryCache = class {
678
733
  const packed = pack(data);
679
734
  const size = packed.byteLength;
680
735
  this.compressions++;
736
+ this.sketch.increment(key);
681
737
  const cat = this.getCategory(key);
682
738
  const lim = this.getCategoryLimit(cat);
683
739
  if (size > lim.maxSizeBytes * 0.5) {
@@ -759,7 +815,7 @@ var SmartMemoryCache = class {
759
815
  const entry = this.cache.get(key);
760
816
  if (!entry) continue;
761
817
  if (entry.priority === 4 && entry.expiresAt > now) continue;
762
- candidates.push({ key, score: this.score(entry, 0, now) });
818
+ candidates.push({ key, score: this.score(entry, 0, now, key) });
763
819
  }
764
820
  candidates.sort((a, b) => a.score - b.score);
765
821
  for (const { key } of candidates) {
@@ -805,7 +861,7 @@ var SmartMemoryCache = class {
805
861
  const candidates = [];
806
862
  for (const [key, entry] of this.cache) {
807
863
  if (entry.priority === 4 && entry.expiresAt > now) continue;
808
- candidates.push({ key, score: this.score(entry, 0, now) });
864
+ candidates.push({ key, score: this.score(entry, 0, now, key) });
809
865
  }
810
866
  candidates.sort((a, b) => a.score - b.score);
811
867
  const count = Math.max(1, Math.ceil(candidates.length * pct));
@@ -860,6 +916,41 @@ var SmartMemoryCache = class {
860
916
  this.recalculateStats();
861
917
  return loaded;
862
918
  }
919
+ // ── Iterators ─────────────────────────────────────────────────────────────
920
+ /**
921
+ * Lazily yields every [key, entry] pair whose TTL has not yet expired.
922
+ * Expired entries that are still in the Map (awaiting background cleanup)
923
+ * are silently skipped.
924
+ */
925
+ *liveEntries() {
926
+ const now = Date.now();
927
+ for (const [key, entry] of this.cache) {
928
+ if (entry.expiresAt > now) yield [key, entry];
929
+ }
930
+ }
931
+ /**
932
+ * Yields only the keys of live entries — no intermediate tuple allocation.
933
+ * Use this instead of liveEntries() when you only need keys.
934
+ */
935
+ *liveKeys() {
936
+ const now = Date.now();
937
+ for (const [key, entry] of this.cache) {
938
+ if (entry.expiresAt > now) yield key;
939
+ }
940
+ }
941
+ /**
942
+ * Yields only the resolved values of live entries.
943
+ * Iterates Map.values() so the key is never loaded into the yielded path.
944
+ * Returns the cached deserialized object when available (entry.value), otherwise
945
+ * the raw msgpackr Buffer — identical semantics to get() but without bloom/hit tracking.
946
+ */
947
+ *liveValues() {
948
+ const now = Date.now();
949
+ for (const entry of this.cache.values()) {
950
+ if (entry.expiresAt > now)
951
+ yield entry.value !== void 0 ? entry.value : entry.data;
952
+ }
953
+ }
863
954
  // ── Stats ─────────────────────────────────────────────────────────────────
864
955
  get size() {
865
956
  return this.cache.size;
@@ -1233,6 +1324,47 @@ var DEFAULT_CATEGORY_LIMITS = {
1233
1324
  "default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
1234
1325
  };
1235
1326
  var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
1327
+ var L2CircuitBreaker = class {
1328
+ constructor(threshold, cooldownMs) {
1329
+ this.threshold = threshold;
1330
+ this.cooldownMs = cooldownMs;
1331
+ }
1332
+ threshold;
1333
+ cooldownMs;
1334
+ state = 0 /* CLOSED */;
1335
+ failures = 0;
1336
+ openedAt = 0;
1337
+ /** Call before each Redis attempt. Returns false when the circuit is open. */
1338
+ isAllowed() {
1339
+ if (this.state === 0 /* CLOSED */) return true;
1340
+ if (this.state === 2 /* HALF_OPEN */) return true;
1341
+ if (Date.now() - this.openedAt >= this.cooldownMs) {
1342
+ this.state = 2 /* HALF_OPEN */;
1343
+ return true;
1344
+ }
1345
+ return false;
1346
+ }
1347
+ /** Call on Redis success. */
1348
+ onSuccess() {
1349
+ this.failures = 0;
1350
+ this.state = 0 /* CLOSED */;
1351
+ }
1352
+ /** Call on Redis failure. */
1353
+ onFailure() {
1354
+ this.failures++;
1355
+ if (this.state === 2 /* HALF_OPEN */ || this.failures >= this.threshold) {
1356
+ this.state = 1 /* OPEN */;
1357
+ this.openedAt = Date.now();
1358
+ this.failures = 0;
1359
+ }
1360
+ }
1361
+ get isOpen() {
1362
+ return this.state === 1 /* OPEN */;
1363
+ }
1364
+ get currentState() {
1365
+ return this.state === 0 /* CLOSED */ ? "closed" : this.state === 1 /* OPEN */ ? "open" : "half_open";
1366
+ }
1367
+ };
1236
1368
  function inferPriority(cacheKey) {
1237
1369
  if (cacheKey.includes("auth:") || cacheKey.includes("session:")) return 4 /* CRITICAL */;
1238
1370
  if (cacheKey.includes("user:") || cacheKey.includes("org:") || cacheKey.includes("profile:")) return 3 /* HIGH */;
@@ -1257,6 +1389,7 @@ var CacheService = class _CacheService {
1257
1389
  tagIndex = /* @__PURE__ */ new Map();
1258
1390
  redis = null;
1259
1391
  redisConnecting = null;
1392
+ cb;
1260
1393
  snapshotLoaded = false;
1261
1394
  cleanupInterval = null;
1262
1395
  oomInterval = null;
@@ -1331,8 +1464,13 @@ var CacheService = class _CacheService {
1331
1464
  metricsIntervalMs: options.metricsIntervalMs ?? 6e4,
1332
1465
  staleIfError: options.staleIfError ?? 0,
1333
1466
  l2WriteMode: options.l2WriteMode ?? "read-write",
1334
- instanceName: options.instanceName ?? ""
1467
+ instanceName: options.instanceName ?? "",
1468
+ ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
1469
+ tracer: options.tracer
1335
1470
  };
1471
+ const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
1472
+ const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
1473
+ this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
1336
1474
  this.disk = new DiskTier({
1337
1475
  dir: this.opts.diskCacheDir,
1338
1476
  maxBytes: this.opts.diskMaxBytes,
@@ -1453,6 +1591,22 @@ var CacheService = class _CacheService {
1453
1591
  nk(key) {
1454
1592
  return this._namespace ? `${this._namespace}:${key}` : key;
1455
1593
  }
1594
+ /** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
1595
+ _jitterTtl(ttlMs) {
1596
+ const j = this.opts.ttlJitterFactor;
1597
+ if (j === 0) return ttlMs;
1598
+ return Math.round(ttlMs * (1 + (Math.random() * 2 - 1) * j));
1599
+ }
1600
+ /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
1601
+ _startSpan(name) {
1602
+ if (this.opts.tracer) return this.opts.tracer.startSpan(name);
1603
+ return { setAttribute() {
1604
+ return this;
1605
+ }, setStatus() {
1606
+ return this;
1607
+ }, end() {
1608
+ } };
1609
+ }
1456
1610
  initBackplane() {
1457
1611
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
1458
1612
  if (this.subClient) return;
@@ -1469,25 +1623,7 @@ var CacheService = class _CacheService {
1469
1623
  });
1470
1624
  sub.on("error", (e) => this.logger.debug("Backplane subscriber error", { error: e.message }));
1471
1625
  sub.on("message", (_channel, message) => {
1472
- try {
1473
- const msg = JSON.parse(message);
1474
- if (msg.src === this.instanceId) {
1475
- this.counters.invSkipped++;
1476
- return;
1477
- }
1478
- this.counters.invReceived++;
1479
- if (msg.op === "del") {
1480
- this.l1.delete(msg.key);
1481
- this.disk.delete(msg.key);
1482
- } else if (msg.op === "del-glob") {
1483
- this.l1.deletePattern(msg.key);
1484
- }
1485
- this.logger.debug("Backplane: peer invalidation applied", {
1486
- op: msg.op,
1487
- key: msg.key.slice(0, 60)
1488
- });
1489
- } catch {
1490
- }
1626
+ this._handleBackplaneMessage(message);
1491
1627
  });
1492
1628
  sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
1493
1629
  channel: this.backplaneChannel,
@@ -1497,6 +1633,28 @@ var CacheService = class _CacheService {
1497
1633
  }));
1498
1634
  this.subClient = sub;
1499
1635
  }
1636
+ /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
1637
+ _handleBackplaneMessage(message) {
1638
+ try {
1639
+ const msg = JSON.parse(message);
1640
+ if (msg.src === this.instanceId) {
1641
+ this.counters.invSkipped++;
1642
+ return;
1643
+ }
1644
+ this.counters.invReceived++;
1645
+ if (msg.op === "del") {
1646
+ this.l1.delete(msg.key);
1647
+ setImmediate(() => this.disk.delete(msg.key));
1648
+ } else if (msg.op === "del-glob") {
1649
+ this.l1.deletePattern(msg.key);
1650
+ }
1651
+ this.logger.debug("Backplane: peer invalidation applied", {
1652
+ op: msg.op,
1653
+ key: msg.key.slice(0, 60)
1654
+ });
1655
+ } catch {
1656
+ }
1657
+ }
1500
1658
  async publishInvalidation(op, key) {
1501
1659
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
1502
1660
  try {
@@ -1510,7 +1668,7 @@ var CacheService = class _CacheService {
1510
1668
  }
1511
1669
  }
1512
1670
  async getRedis() {
1513
- if (this.redis?.status === "ready") return this.redis;
1671
+ if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
1514
1672
  if (this.redisConnecting) return this.redisConnecting;
1515
1673
  this.redisConnecting = (async () => {
1516
1674
  try {
@@ -1534,10 +1692,12 @@ var CacheService = class _CacheService {
1534
1692
  client.once("error", reject);
1535
1693
  setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
1536
1694
  });
1695
+ this.cb.onSuccess();
1537
1696
  this.redis = client;
1538
1697
  this.redisConnecting = null;
1539
1698
  return client;
1540
1699
  } catch (err) {
1700
+ this.cb.onFailure();
1541
1701
  this.redisConnecting = null;
1542
1702
  throw err;
1543
1703
  }
@@ -1624,6 +1784,8 @@ var CacheService = class _CacheService {
1624
1784
  * instantly while a background refresh runs. Default: 0 (disabled).
1625
1785
  */
1626
1786
  async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
1787
+ const span = this._startSpan("tricache.get");
1788
+ span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
1627
1789
  const k = this.nk(cacheKey);
1628
1790
  this.counters.gets++;
1629
1791
  const l1Hit = this.l1.get(k);
@@ -1643,24 +1805,28 @@ var CacheService = class _CacheService {
1643
1805
  this.logger.debug("L1 hit");
1644
1806
  }
1645
1807
  this.counters.l1Hits++;
1808
+ span.setAttribute("cache.hit", "l1").end();
1646
1809
  return l1Hit.value;
1647
1810
  }
1648
- const ttlMs = ttlSeconds * 1e3;
1811
+ const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
1649
1812
  const swrGraceMs = (opts.swr ?? 0) * 1e3;
1650
1813
  const priority = opts.priority ?? inferPriority(cacheKey);
1651
1814
  if (!this._redisDisabled) {
1652
1815
  try {
1653
1816
  const client = await this.getRedis();
1654
1817
  const raw = await client.get(k);
1818
+ this.cb.onSuccess();
1655
1819
  if (raw) {
1656
1820
  const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
1657
1821
  const parsed = JSON.parse(decrypted);
1658
1822
  this.l1.set(k, parsed, ttlMs, priority);
1659
1823
  this.counters.l2Hits++;
1660
1824
  this.logger.debug("L2 hit (Redis)", { cacheKey });
1825
+ span.setAttribute("cache.hit", "l2").end();
1661
1826
  return parsed;
1662
1827
  }
1663
1828
  } catch (err) {
1829
+ this.cb.onFailure();
1664
1830
  this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
1665
1831
  }
1666
1832
  }
@@ -1675,14 +1841,17 @@ var CacheService = class _CacheService {
1675
1841
  if (l1Check !== null) {
1676
1842
  this.counters.diskHits++;
1677
1843
  this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
1844
+ span.setAttribute("cache.hit", "disk").end();
1678
1845
  return l1Check.value;
1679
1846
  }
1680
1847
  }
1681
1848
  }
1849
+ span.setAttribute("cache.hit", "miss");
1682
1850
  const existing = this.inflight.get(k);
1683
1851
  if (existing) {
1684
1852
  this.counters.stampedes++;
1685
1853
  this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch", { cacheKey });
1854
+ span.end();
1686
1855
  return existing;
1687
1856
  }
1688
1857
  const fetchPromise = (async () => {
@@ -1697,9 +1866,11 @@ var CacheService = class _CacheService {
1697
1866
  const client = await this.getRedis();
1698
1867
  const serialized = JSON.stringify(data);
1699
1868
  const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
1700
- await client.setex(k, ttlSeconds, toStore);
1869
+ await client.setex(k, Math.ceil(ttlMs / 1e3), toStore);
1870
+ this.cb.onSuccess();
1701
1871
  this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
1702
1872
  } catch {
1873
+ this.cb.onFailure();
1703
1874
  this.logger.debug("Cached L1 only (Redis unavailable)", { cacheKey });
1704
1875
  }
1705
1876
  } else {
@@ -1708,6 +1879,7 @@ var CacheService = class _CacheService {
1708
1879
  return data;
1709
1880
  } finally {
1710
1881
  this.inflight.delete(k);
1882
+ span.end();
1711
1883
  }
1712
1884
  })();
1713
1885
  this.inflight.set(k, fetchPromise);
@@ -1746,7 +1918,9 @@ var CacheService = class _CacheService {
1746
1918
  // ── Explicit set / delete ─────────────────────────────────────────────────
1747
1919
  /** Explicitly write a value into L1 (+ L2 in production). */
1748
1920
  async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
1749
- const ttlMs = ttlSeconds * 1e3;
1921
+ const span = this._startSpan("tricache.set");
1922
+ span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
1923
+ const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
1750
1924
  const p = priority ?? inferPriority(cacheKey);
1751
1925
  const k = this.nk(cacheKey);
1752
1926
  this.counters.sets++;
@@ -1771,7 +1945,9 @@ var CacheService = class _CacheService {
1771
1945
  pl.expire(tagKey, ttlSeconds + 3600);
1772
1946
  }
1773
1947
  await pl.exec();
1948
+ this.cb.onSuccess();
1774
1949
  } catch {
1950
+ this.cb.onFailure();
1775
1951
  }
1776
1952
  }
1777
1953
  }
@@ -1780,12 +1956,15 @@ var CacheService = class _CacheService {
1780
1956
  const client = await this.getRedis();
1781
1957
  const s = JSON.stringify(data);
1782
1958
  const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
1783
- await client.setex(k, ttlSeconds, stored);
1959
+ await client.setex(k, Math.ceil(ttlMs / 1e3), stored);
1960
+ this.cb.onSuccess();
1784
1961
  } catch (err) {
1962
+ this.cb.onFailure();
1785
1963
  this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
1786
1964
  }
1787
1965
  }
1788
1966
  void this.publishInvalidation("del", k);
1967
+ span.end();
1789
1968
  }
1790
1969
  /**
1791
1970
  * Delete one key or a glob pattern (supports `*` wildcard).
@@ -1795,6 +1974,8 @@ var CacheService = class _CacheService {
1795
1974
  * await cache.delete('user:abc:*'); // all keys for user abc
1796
1975
  */
1797
1976
  async delete(cacheKey) {
1977
+ const span = this._startSpan("tricache.delete");
1978
+ span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
1798
1979
  const isPattern = cacheKey.includes("*");
1799
1980
  const k = this.nk(cacheKey);
1800
1981
  this.counters.deletes++;
@@ -1819,11 +2000,14 @@ var CacheService = class _CacheService {
1819
2000
  } else {
1820
2001
  await client.del(k);
1821
2002
  }
2003
+ this.cb.onSuccess();
1822
2004
  } catch (err) {
2005
+ this.cb.onFailure();
1823
2006
  this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
1824
2007
  }
1825
2008
  }
1826
2009
  void this.publishInvalidation(isPattern ? "del-glob" : "del", k);
2010
+ span.end();
1827
2011
  }
1828
2012
  // ── Counter (distributed rate limiting) ──────────────────────────────────
1829
2013
  /**
@@ -1916,6 +2100,43 @@ var CacheService = class _CacheService {
1916
2100
  has(cacheKey) {
1917
2101
  return this.l1.has(this.nk(cacheKey));
1918
2102
  }
2103
+ // ── Iteration ─────────────────────────────────────────────────────────────
2104
+ /**
2105
+ * Lazily yield every non-expired L1 key, stripped of its namespace prefix.
2106
+ *
2107
+ * @example
2108
+ * for (const key of cache.keys()) console.log(key);
2109
+ */
2110
+ *keys() {
2111
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
2112
+ for (const key of this.l1.liveKeys()) {
2113
+ yield prefixLen > 0 ? key.slice(prefixLen) : key;
2114
+ }
2115
+ }
2116
+ /**
2117
+ * Lazily yield every non-expired L1 value.
2118
+ * Each value is the cached (pre-deserialized) JS object — no unpack overhead.
2119
+ *
2120
+ * @example
2121
+ * for (const val of cache.values<User>()) console.log(val.id);
2122
+ */
2123
+ *values() {
2124
+ yield* this.l1.liveValues();
2125
+ }
2126
+ /**
2127
+ * Lazily yield every non-expired L1 [key, value] pair.
2128
+ * Keys are stripped of their namespace prefix.
2129
+ *
2130
+ * @example
2131
+ * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
2132
+ */
2133
+ *entries() {
2134
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
2135
+ for (const [key, entry] of this.l1.liveEntries()) {
2136
+ const k = prefixLen > 0 ? key.slice(prefixLen) : key;
2137
+ yield [k, entry.value !== void 0 ? entry.value : entry.data];
2138
+ }
2139
+ }
1919
2140
  /**
1920
2141
  * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
1921
2142
  * Returns `false` if the key is absent or already expired.
@@ -1985,6 +2206,92 @@ var CacheService = class _CacheService {
1985
2206
  }
1986
2207
  return result;
1987
2208
  }
2209
+ /**
2210
+ * Batch write — set multiple entries in a single call.
2211
+ * TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
2212
+ *
2213
+ * @example
2214
+ * await cache.mset({
2215
+ * 'user:1': { value: { name: 'Alice' }, ttl: 300 },
2216
+ * 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
2217
+ * });
2218
+ */
2219
+ async mset(entries) {
2220
+ const keys = Object.keys(entries);
2221
+ await Promise.all(keys.map((key) => {
2222
+ const { value, ttl = 300, priority, tags } = entries[key];
2223
+ return this.set(key, value, ttl, priority, tags ? { tags } : void 0);
2224
+ }));
2225
+ }
2226
+ /**
2227
+ * Batch delete — delete multiple exact keys in a single call.
2228
+ * Glob patterns are not supported; use `delete('prefix:*')` for patterns.
2229
+ *
2230
+ * @example
2231
+ * await cache.mdel(['user:1', 'user:2', 'user:3']);
2232
+ */
2233
+ async mdel(keys) {
2234
+ await Promise.all(keys.map((k) => this.delete(k)));
2235
+ }
2236
+ /**
2237
+ * Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
2238
+ * pulling them into L1. Useful on startup to eliminate cold-start penalty when
2239
+ * the local snapshot is unavailable or too stale.
2240
+ *
2241
+ * Returns the number of keys loaded into L1.
2242
+ *
2243
+ * @example
2244
+ * // In your startup hook (e.g. ECS task, k8s readiness probe):
2245
+ * const loaded = await cache.warmFromL2('org:*');
2246
+ * console.log(`Warmed ${loaded} keys from Redis`);
2247
+ */
2248
+ async warmFromL2(pattern) {
2249
+ if (this._redisDisabled) return 0;
2250
+ try {
2251
+ const client = await this.getRedis();
2252
+ const nsPattern = this.nk(pattern);
2253
+ const matchedKeys = [];
2254
+ const stream = client.scanStream({ match: nsPattern, count: 100 });
2255
+ await new Promise((resolve, reject) => {
2256
+ stream.on("data", (chunk) => matchedKeys.push(...chunk));
2257
+ stream.on("end", resolve);
2258
+ stream.on("error", reject);
2259
+ });
2260
+ if (matchedKeys.length === 0) {
2261
+ this.cb.onSuccess();
2262
+ return 0;
2263
+ }
2264
+ const pl = client.pipeline();
2265
+ for (const k of matchedKeys) pl.get(k);
2266
+ const results = await pl.exec();
2267
+ this.cb.onSuccess();
2268
+ let loaded = 0;
2269
+ const now = Date.now();
2270
+ for (let i = 0; i < matchedKeys.length; i++) {
2271
+ const [err, raw] = results[i];
2272
+ if (err || raw == null) continue;
2273
+ try {
2274
+ const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
2275
+ const parsed = JSON.parse(decrypted);
2276
+ const remainingMs = 10 * 60 * 1e3;
2277
+ this.l1.set(matchedKeys[i], parsed, remainingMs, inferPriority(matchedKeys[i]));
2278
+ loaded++;
2279
+ } catch {
2280
+ }
2281
+ }
2282
+ void now;
2283
+ this.logger.info("warmFromL2 complete", {
2284
+ pattern,
2285
+ matched: matchedKeys.length,
2286
+ loaded
2287
+ });
2288
+ return loaded;
2289
+ } catch (err) {
2290
+ this.cb.onFailure();
2291
+ this.logger.debug("warmFromL2: Redis unavailable", { error: err.message });
2292
+ return 0;
2293
+ }
2294
+ }
1988
2295
  /**
1989
2296
  * Invalidate all keys associated with a tag.
1990
2297
  * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
@@ -2118,6 +2425,9 @@ var CacheService = class _CacheService {
2118
2425
  received: c.invReceived,
2119
2426
  skipped: c.invSkipped
2120
2427
  },
2428
+ l2CircuitBreaker: {
2429
+ state: this.cb.currentState
2430
+ },
2121
2431
  oom: {
2122
2432
  enabled: this.opts.oomProtection,
2123
2433
  evictions: c.oomEvictions,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tricache",
3
- "version": "0.2.0",
4
- "description": "Three-tier Node.js cache: L1 smart RAM (adaptive LFU/LRU) → L1.5 NVMe disk spill → L2 Redis/Valkey. Includes AES-256-GCM at-rest encryption, WASM Bloom filter, Stale-While-Revalidate, and thundering-herd prevention.",
3
+ "version": "0.3.1",
4
+ "description": "Three-tier Node.js cache: L1 smart RAM (adaptive LFU/LRU + Count-Min Sketch) → L1.5 NVMe disk spill → L2 Redis/Valkey. Includes AES-256-GCM at-rest encryption, WASM Bloom filter, Stale-While-Revalidate, and thundering-herd prevention.",
5
5
  "keywords": [
6
6
  "cache",
7
7
  "redis",
@@ -9,6 +9,7 @@
9
9
  "lru",
10
10
  "lfu",
11
11
  "bloom-filter",
12
+ "count-min-sketch",
12
13
  "swr",
13
14
  "stale-while-revalidate",
14
15
  "msgpack",