tricache 0.3.0 → 0.4.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/dist/index.js CHANGED
@@ -727,9 +727,9 @@ var SmartMemoryCache = class {
727
727
  this.categoryHits.set(cat, (this.categoryHits.get(cat) ?? 0) + 1);
728
728
  const value = entry.value !== void 0 ? entry.value : unpack(entry.data);
729
729
  const isStale = entry.staleAt !== void 0 && now > entry.staleAt;
730
- return { value, isStale };
730
+ return { value, isStale, expiresAt: entry.expiresAt, ttlMs: entry.ttlMs, delta: entry.delta };
731
731
  }
732
- set(key, data, ttlMs, priority = 2, staleAt) {
732
+ set(key, data, ttlMs, priority = 2, staleAt, delta) {
733
733
  const packed = pack(data);
734
734
  const size = packed.byteLength;
735
735
  this.compressions++;
@@ -749,7 +749,7 @@ var SmartMemoryCache = class {
749
749
  }
750
750
  this.ensureCapacity(cat, size);
751
751
  const now = Date.now();
752
- this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority });
752
+ this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta });
753
753
  this.bloom.add(key);
754
754
  this.maybeRebuildBloom();
755
755
  this.totalSize += size;
@@ -1037,6 +1037,23 @@ var SmartMemoryCache = class {
1037
1037
  bloomStats() {
1038
1038
  return this.bloom.stats;
1039
1039
  }
1040
+ /**
1041
+ * Return the top-N live L1 keys by historical access frequency (Count-Min Sketch estimate).
1042
+ * Includes evicted-then-readmitted keys whose sketch frequency exceeds their current hit count.
1043
+ * Useful for diagnosing which keys are driving cache pressure.
1044
+ *
1045
+ * @param n - Maximum number of entries to return. Default: 10.
1046
+ */
1047
+ hotKeys(n) {
1048
+ const now = Date.now();
1049
+ const out = [];
1050
+ for (const [key, entry] of this.cache) {
1051
+ if (entry.expiresAt <= now) continue;
1052
+ out.push({ key, hits: this.sketch.estimate(key), sizeBytes: entry.size });
1053
+ }
1054
+ out.sort((a, b) => b.hits - a.hits);
1055
+ return out.slice(0, n);
1056
+ }
1040
1057
  };
1041
1058
 
1042
1059
  // src/disk-tier.ts
@@ -1324,6 +1341,47 @@ var DEFAULT_CATEGORY_LIMITS = {
1324
1341
  "default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
1325
1342
  };
1326
1343
  var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
1344
+ var L2CircuitBreaker = class {
1345
+ constructor(threshold, cooldownMs) {
1346
+ this.threshold = threshold;
1347
+ this.cooldownMs = cooldownMs;
1348
+ }
1349
+ threshold;
1350
+ cooldownMs;
1351
+ state = 0 /* CLOSED */;
1352
+ failures = 0;
1353
+ openedAt = 0;
1354
+ /** Call before each Redis attempt. Returns false when the circuit is open. */
1355
+ isAllowed() {
1356
+ if (this.state === 0 /* CLOSED */) return true;
1357
+ if (this.state === 2 /* HALF_OPEN */) return true;
1358
+ if (Date.now() - this.openedAt >= this.cooldownMs) {
1359
+ this.state = 2 /* HALF_OPEN */;
1360
+ return true;
1361
+ }
1362
+ return false;
1363
+ }
1364
+ /** Call on Redis success. */
1365
+ onSuccess() {
1366
+ this.failures = 0;
1367
+ this.state = 0 /* CLOSED */;
1368
+ }
1369
+ /** Call on Redis failure. */
1370
+ onFailure() {
1371
+ this.failures++;
1372
+ if (this.state === 2 /* HALF_OPEN */ || this.failures >= this.threshold) {
1373
+ this.state = 1 /* OPEN */;
1374
+ this.openedAt = Date.now();
1375
+ this.failures = 0;
1376
+ }
1377
+ }
1378
+ get isOpen() {
1379
+ return this.state === 1 /* OPEN */;
1380
+ }
1381
+ get currentState() {
1382
+ return this.state === 0 /* CLOSED */ ? "closed" : this.state === 1 /* OPEN */ ? "open" : "half_open";
1383
+ }
1384
+ };
1327
1385
  function inferPriority(cacheKey) {
1328
1386
  if (cacheKey.includes("auth:") || cacheKey.includes("session:")) return 4 /* CRITICAL */;
1329
1387
  if (cacheKey.includes("user:") || cacheKey.includes("org:") || cacheKey.includes("profile:")) return 3 /* HIGH */;
@@ -1346,8 +1404,14 @@ var CacheService = class _CacheService {
1346
1404
  _l1Counters = /* @__PURE__ */ new Map();
1347
1405
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
1348
1406
  tagIndex = /* @__PURE__ */ new Map();
1407
+ /**
1408
+ * Dependency index: source glob pattern → Set of namespaced dependent keys.
1409
+ * When an exact-key delete matches a registered pattern, all dependents are cascaded.
1410
+ */
1411
+ dependencyIndex = /* @__PURE__ */ new Map();
1349
1412
  redis = null;
1350
1413
  redisConnecting = null;
1414
+ cb;
1351
1415
  snapshotLoaded = false;
1352
1416
  cleanupInterval = null;
1353
1417
  oomInterval = null;
@@ -1422,8 +1486,14 @@ var CacheService = class _CacheService {
1422
1486
  metricsIntervalMs: options.metricsIntervalMs ?? 6e4,
1423
1487
  staleIfError: options.staleIfError ?? 0,
1424
1488
  l2WriteMode: options.l2WriteMode ?? "read-write",
1425
- instanceName: options.instanceName ?? ""
1489
+ instanceName: options.instanceName ?? "",
1490
+ ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
1491
+ tracer: options.tracer,
1492
+ notFoundTtl: options.notFoundTtl ?? 0
1426
1493
  };
1494
+ const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
1495
+ const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
1496
+ this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
1427
1497
  this.disk = new DiskTier({
1428
1498
  dir: this.opts.diskCacheDir,
1429
1499
  maxBytes: this.opts.diskMaxBytes,
@@ -1544,6 +1614,22 @@ var CacheService = class _CacheService {
1544
1614
  nk(key) {
1545
1615
  return this._namespace ? `${this._namespace}:${key}` : key;
1546
1616
  }
1617
+ /** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
1618
+ _jitterTtl(ttlMs) {
1619
+ const j = this.opts.ttlJitterFactor;
1620
+ if (j === 0) return ttlMs;
1621
+ return Math.round(ttlMs * (1 + (Math.random() * 2 - 1) * j));
1622
+ }
1623
+ /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
1624
+ _startSpan(name) {
1625
+ if (this.opts.tracer) return this.opts.tracer.startSpan(name);
1626
+ return { setAttribute() {
1627
+ return this;
1628
+ }, setStatus() {
1629
+ return this;
1630
+ }, end() {
1631
+ } };
1632
+ }
1547
1633
  initBackplane() {
1548
1634
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
1549
1635
  if (this.subClient) return;
@@ -1605,7 +1691,7 @@ var CacheService = class _CacheService {
1605
1691
  }
1606
1692
  }
1607
1693
  async getRedis() {
1608
- if (this.redis?.status === "ready") return this.redis;
1694
+ if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
1609
1695
  if (this.redisConnecting) return this.redisConnecting;
1610
1696
  this.redisConnecting = (async () => {
1611
1697
  try {
@@ -1629,10 +1715,12 @@ var CacheService = class _CacheService {
1629
1715
  client.once("error", reject);
1630
1716
  setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
1631
1717
  });
1718
+ this.cb.onSuccess();
1632
1719
  this.redis = client;
1633
1720
  this.redisConnecting = null;
1634
1721
  return client;
1635
1722
  } catch (err) {
1723
+ this.cb.onFailure();
1636
1724
  this.redisConnecting = null;
1637
1725
  throw err;
1638
1726
  }
@@ -1713,12 +1801,22 @@ var CacheService = class _CacheService {
1713
1801
  * @param cacheKey - Unique key identifying this value
1714
1802
  * @param fetchFn - Called on a cache miss; its return value is cached and returned
1715
1803
  * @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
1716
- * @param opts.priority - Override the auto-inferred eviction priority
1717
- * @param opts.swr - Stale-While-Revalidate grace seconds. When > 0 the entry stays
1718
- * alive for this many extra seconds after TTL; callers get stale data
1719
- * instantly while a background refresh runs. Default: 0 (disabled).
1804
+ * @param opts.priority - Override the auto-inferred eviction priority
1805
+ * @param opts.swr - Stale-While-Revalidate grace seconds.
1806
+ * @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
1807
+ * is triggered proactively while the caller still receives the
1808
+ * cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
1809
+ * Requires `fetchFn` to be stable across calls.
1810
+ * @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
1811
+ * recompute more aggressively before expiry. Typical range: 0.5–2.
1812
+ * Complementary to refreshAhead — uses recompute cost (delta) to
1813
+ * decide probabilistically rather than at a fixed threshold.
1814
+ * @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
1815
+ * Caches negative lookups to avoid repeated DB hits for missing keys.
1720
1816
  */
1721
1817
  async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
1818
+ const span = this._startSpan("tricache.get");
1819
+ span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
1722
1820
  const k = this.nk(cacheKey);
1723
1821
  this.counters.gets++;
1724
1822
  const l1Hit = this.l1.get(k);
@@ -1736,26 +1834,47 @@ var CacheService = class _CacheService {
1736
1834
  }
1737
1835
  } else {
1738
1836
  this.logger.debug("L1 hit");
1837
+ if (!this.revalidating.has(k) && (opts.refreshAhead || opts.xfetchBeta)) {
1838
+ const now = Date.now();
1839
+ const remaining = l1Hit.expiresAt - now;
1840
+ const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1e3;
1841
+ const priority2 = opts.priority ?? inferPriority(cacheKey);
1842
+ const shouldRefreshAhead = opts.refreshAhead != null && opts.refreshAhead > 0 ? remaining <= entryTtl * (1 - opts.refreshAhead) : false;
1843
+ const shouldXFetch = opts.xfetchBeta != null && opts.xfetchBeta > 0 && l1Hit.delta != null ? remaining <= l1Hit.delta * opts.xfetchBeta * -Math.log(Math.random()) : false;
1844
+ if (shouldRefreshAhead || shouldXFetch) {
1845
+ this.revalidating.add(k);
1846
+ void this._revalidate(k, fetchFn, entryTtl, (opts.swr ?? 0) * 1e3, priority2);
1847
+ this.counters.swrRevalidations++;
1848
+ this.logger.debug(
1849
+ shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
1850
+ { cacheKey, remainingMs: remaining, ttlMs: entryTtl }
1851
+ );
1852
+ }
1853
+ }
1739
1854
  }
1740
1855
  this.counters.l1Hits++;
1856
+ span.setAttribute("cache.hit", "l1").end();
1741
1857
  return l1Hit.value;
1742
1858
  }
1743
- const ttlMs = ttlSeconds * 1e3;
1859
+ const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
1744
1860
  const swrGraceMs = (opts.swr ?? 0) * 1e3;
1745
1861
  const priority = opts.priority ?? inferPriority(cacheKey);
1746
1862
  if (!this._redisDisabled) {
1747
1863
  try {
1748
1864
  const client = await this.getRedis();
1749
1865
  const raw = await client.get(k);
1866
+ this.cb.onSuccess();
1750
1867
  if (raw) {
1751
1868
  const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
1752
1869
  const parsed = JSON.parse(decrypted);
1753
1870
  this.l1.set(k, parsed, ttlMs, priority);
1754
1871
  this.counters.l2Hits++;
1755
1872
  this.logger.debug("L2 hit (Redis)", { cacheKey });
1873
+ span.setAttribute("cache.hit", "l2").end();
1756
1874
  return parsed;
1757
1875
  }
1758
1876
  } catch (err) {
1877
+ this.cb.onFailure();
1759
1878
  this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
1760
1879
  }
1761
1880
  }
@@ -1770,31 +1889,40 @@ var CacheService = class _CacheService {
1770
1889
  if (l1Check !== null) {
1771
1890
  this.counters.diskHits++;
1772
1891
  this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
1892
+ span.setAttribute("cache.hit", "disk").end();
1773
1893
  return l1Check.value;
1774
1894
  }
1775
1895
  }
1776
1896
  }
1897
+ span.setAttribute("cache.hit", "miss");
1777
1898
  const existing = this.inflight.get(k);
1778
1899
  if (existing) {
1779
1900
  this.counters.stampedes++;
1780
1901
  this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch", { cacheKey });
1902
+ span.end();
1781
1903
  return existing;
1782
1904
  }
1783
1905
  const fetchPromise = (async () => {
1784
1906
  try {
1785
1907
  this.counters.fetches++;
1908
+ const fetchStart = Date.now();
1786
1909
  const data = await fetchFn();
1787
- const staleAt = swrGraceMs > 0 ? Date.now() + ttlMs : void 0;
1788
- const storeTtl = swrGraceMs > 0 ? ttlMs + swrGraceMs : ttlMs;
1789
- this.l1.set(k, data, storeTtl, priority, staleAt);
1910
+ const delta = Date.now() - fetchStart;
1911
+ const notFoundTtlMs = (opts.notFoundTtl ?? this.opts.notFoundTtl) * 1e3;
1912
+ const effectiveTtl = data == null && notFoundTtlMs > 0 ? notFoundTtlMs : ttlMs;
1913
+ const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
1914
+ const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
1915
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta);
1790
1916
  if (!this._redisDisabled) {
1791
1917
  try {
1792
1918
  const client = await this.getRedis();
1793
1919
  const serialized = JSON.stringify(data);
1794
1920
  const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
1795
- await client.setex(k, ttlSeconds, toStore);
1921
+ await client.setex(k, Math.ceil(effectiveTtl / 1e3), toStore);
1922
+ this.cb.onSuccess();
1796
1923
  this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
1797
1924
  } catch {
1925
+ this.cb.onFailure();
1798
1926
  this.logger.debug("Cached L1 only (Redis unavailable)", { cacheKey });
1799
1927
  }
1800
1928
  } else {
@@ -1803,6 +1931,7 @@ var CacheService = class _CacheService {
1803
1931
  return data;
1804
1932
  } finally {
1805
1933
  this.inflight.delete(k);
1934
+ span.end();
1806
1935
  }
1807
1936
  })();
1808
1937
  this.inflight.set(k, fetchPromise);
@@ -1810,9 +1939,11 @@ var CacheService = class _CacheService {
1810
1939
  }
1811
1940
  async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
1812
1941
  try {
1942
+ const fetchStart = Date.now();
1813
1943
  const data = await fetchFn();
1944
+ const delta = Date.now() - fetchStart;
1814
1945
  const staleAt = Date.now() + ttlMs;
1815
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt);
1946
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta);
1816
1947
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
1817
1948
  try {
1818
1949
  const client = await this.getRedis();
@@ -1841,7 +1972,9 @@ var CacheService = class _CacheService {
1841
1972
  // ── Explicit set / delete ─────────────────────────────────────────────────
1842
1973
  /** Explicitly write a value into L1 (+ L2 in production). */
1843
1974
  async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
1844
- const ttlMs = ttlSeconds * 1e3;
1975
+ const span = this._startSpan("tricache.set");
1976
+ span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
1977
+ const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
1845
1978
  const p = priority ?? inferPriority(cacheKey);
1846
1979
  const k = this.nk(cacheKey);
1847
1980
  this.counters.sets++;
@@ -1866,21 +1999,37 @@ var CacheService = class _CacheService {
1866
1999
  pl.expire(tagKey, ttlSeconds + 3600);
1867
2000
  }
1868
2001
  await pl.exec();
2002
+ this.cb.onSuccess();
1869
2003
  } catch {
2004
+ this.cb.onFailure();
1870
2005
  }
1871
2006
  }
1872
2007
  }
2008
+ if (opts?.dependsOn?.length) {
2009
+ for (const pattern of opts.dependsOn) {
2010
+ const nsPattern = this.nk(pattern);
2011
+ let deps = this.dependencyIndex.get(nsPattern);
2012
+ if (!deps) {
2013
+ deps = /* @__PURE__ */ new Set();
2014
+ this.dependencyIndex.set(nsPattern, deps);
2015
+ }
2016
+ deps.add(k);
2017
+ }
2018
+ }
1873
2019
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
1874
2020
  try {
1875
2021
  const client = await this.getRedis();
1876
2022
  const s = JSON.stringify(data);
1877
2023
  const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
1878
- await client.setex(k, ttlSeconds, stored);
2024
+ await client.setex(k, Math.ceil(ttlMs / 1e3), stored);
2025
+ this.cb.onSuccess();
1879
2026
  } catch (err) {
2027
+ this.cb.onFailure();
1880
2028
  this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
1881
2029
  }
1882
2030
  }
1883
2031
  void this.publishInvalidation("del", k);
2032
+ span.end();
1884
2033
  }
1885
2034
  /**
1886
2035
  * Delete one key or a glob pattern (supports `*` wildcard).
@@ -1890,6 +2039,8 @@ var CacheService = class _CacheService {
1890
2039
  * await cache.delete('user:abc:*'); // all keys for user abc
1891
2040
  */
1892
2041
  async delete(cacheKey) {
2042
+ const span = this._startSpan("tricache.delete");
2043
+ span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
1893
2044
  const isPattern = cacheKey.includes("*");
1894
2045
  const k = this.nk(cacheKey);
1895
2046
  this.counters.deletes++;
@@ -1898,6 +2049,8 @@ var CacheService = class _CacheService {
1898
2049
  } else {
1899
2050
  this.l1.delete(k);
1900
2051
  this.disk.delete(k);
2052
+ this._cascadeDependencies(k);
2053
+ for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
1901
2054
  }
1902
2055
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
1903
2056
  try {
@@ -1914,11 +2067,14 @@ var CacheService = class _CacheService {
1914
2067
  } else {
1915
2068
  await client.del(k);
1916
2069
  }
2070
+ this.cb.onSuccess();
1917
2071
  } catch (err) {
2072
+ this.cb.onFailure();
1918
2073
  this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
1919
2074
  }
1920
2075
  }
1921
2076
  void this.publishInvalidation(isPattern ? "del-glob" : "del", k);
2077
+ span.end();
1922
2078
  }
1923
2079
  // ── Counter (distributed rate limiting) ──────────────────────────────────
1924
2080
  /**
@@ -2117,6 +2273,93 @@ var CacheService = class _CacheService {
2117
2273
  }
2118
2274
  return result;
2119
2275
  }
2276
+ /**
2277
+ * Batch write — set multiple entries in a single call.
2278
+ * TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
2279
+ *
2280
+ * @example
2281
+ * await cache.mset({
2282
+ * 'user:1': { value: { name: 'Alice' }, ttl: 300 },
2283
+ * 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
2284
+ * });
2285
+ */
2286
+ async mset(entries) {
2287
+ const keys = Object.keys(entries);
2288
+ await Promise.all(keys.map((key) => {
2289
+ const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
2290
+ const hasOpts = tags?.length || dependsOn?.length;
2291
+ return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
2292
+ }));
2293
+ }
2294
+ /**
2295
+ * Batch delete — delete multiple exact keys in a single call.
2296
+ * Glob patterns are not supported; use `delete('prefix:*')` for patterns.
2297
+ *
2298
+ * @example
2299
+ * await cache.mdel(['user:1', 'user:2', 'user:3']);
2300
+ */
2301
+ async mdel(keys) {
2302
+ await Promise.all(keys.map((k) => this.delete(k)));
2303
+ }
2304
+ /**
2305
+ * Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
2306
+ * pulling them into L1. Useful on startup to eliminate cold-start penalty when
2307
+ * the local snapshot is unavailable or too stale.
2308
+ *
2309
+ * Returns the number of keys loaded into L1.
2310
+ *
2311
+ * @example
2312
+ * // In your startup hook (e.g. ECS task, k8s readiness probe):
2313
+ * const loaded = await cache.warmFromL2('org:*');
2314
+ * console.log(`Warmed ${loaded} keys from Redis`);
2315
+ */
2316
+ async warmFromL2(pattern) {
2317
+ if (this._redisDisabled) return 0;
2318
+ try {
2319
+ const client = await this.getRedis();
2320
+ const nsPattern = this.nk(pattern);
2321
+ const matchedKeys = [];
2322
+ const stream = client.scanStream({ match: nsPattern, count: 100 });
2323
+ await new Promise((resolve, reject) => {
2324
+ stream.on("data", (chunk) => matchedKeys.push(...chunk));
2325
+ stream.on("end", resolve);
2326
+ stream.on("error", reject);
2327
+ });
2328
+ if (matchedKeys.length === 0) {
2329
+ this.cb.onSuccess();
2330
+ return 0;
2331
+ }
2332
+ const pl = client.pipeline();
2333
+ for (const k of matchedKeys) pl.get(k);
2334
+ const results = await pl.exec();
2335
+ this.cb.onSuccess();
2336
+ let loaded = 0;
2337
+ const now = Date.now();
2338
+ for (let i = 0; i < matchedKeys.length; i++) {
2339
+ const [err, raw] = results[i];
2340
+ if (err || raw == null) continue;
2341
+ try {
2342
+ const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
2343
+ const parsed = JSON.parse(decrypted);
2344
+ const remainingMs = 10 * 60 * 1e3;
2345
+ this.l1.set(matchedKeys[i], parsed, remainingMs, inferPriority(matchedKeys[i]));
2346
+ loaded++;
2347
+ } catch {
2348
+ }
2349
+ }
2350
+ void now;
2351
+ this.logger.info("warmFromL2 complete", {
2352
+ pattern,
2353
+ matched: matchedKeys.length,
2354
+ loaded
2355
+ });
2356
+ return loaded;
2357
+ } catch (err) {
2358
+ this.cb.onFailure();
2359
+ this.logger.debug("warmFromL2: Redis unavailable", { error: err.message });
2360
+ return 0;
2361
+ }
2362
+ }
2120
2363
  /**
2121
2364
  * Invalidate all keys associated with a tag.
2122
2365
  * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
@@ -2210,6 +2453,94 @@ var CacheService = class _CacheService {
2210
2453
  disk: this.disk.stats
2211
2454
  };
2212
2455
  }
2456
+ // ── Conditional write ─────────────────────────────────────────────────
2457
+ /**
2458
+ * Write `value` only if the key is not already cached.
2459
+ * Returns `true` if the write happened, `false` if the key already existed.
2460
+ *
2461
+ * When Redis is available, atomicity is guaranteed via `SET NX EX` so this
2462
+ * is safe to use for idempotency keys and "first writer wins" patterns across
2463
+ * multiple instances. L1 is populated on success.
2464
+ *
2465
+ * @example
2466
+ * const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
2467
+ * if (!claimed) return res.status(409).json({ error: 'duplicate request' });
2468
+ */
2469
+ async setIfAbsent(cacheKey, value, ttlSeconds = 300, priority) {
2470
+ const k = this.nk(cacheKey);
2471
+ if (this.l1.has(k)) return false;
2472
+ if (!this._redisDisabled) {
2473
+ try {
2474
+ const client = await this.getRedis();
2475
+ const serialized = JSON.stringify(value);
2476
+ const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
2477
+ const result = await client.set(k, toStore, "EX", ttlSeconds, "NX");
2478
+ this.cb.onSuccess();
2479
+ if (result === null) return false;
2480
+ } catch (err) {
2481
+ this.cb.onFailure();
2482
+ this.logger.debug("setIfAbsent: Redis unavailable, falling back to L1 check", { cacheKey, error: err.message });
2483
+ if (this.l1.has(k)) return false;
2484
+ }
2485
+ }
2486
+ const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
2487
+ const p = priority ?? inferPriority(cacheKey);
2488
+ this.l1.set(k, value, ttlMs, p);
2489
+ this.counters.sets++;
2490
+ return true;
2491
+ }
2492
+ // ── Hot key introspection ─────────────────────────────────────────────
2493
+ /**
2494
+ * Return the top-N live L1 keys by historical access frequency.
2495
+ * Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
2496
+ * whose historical frequency exceeds their current in-memory hit count.
2497
+ *
2498
+ * Useful for diagnosing what is driving L1 pressure without any extra data
2499
+ * collection overhead.
2500
+ *
2501
+ * @param n - Maximum number of keys to return. Default: 10.
2502
+ *
2503
+ * @example
2504
+ * cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
2505
+ * console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
2506
+ */
2507
+ hotKeys(n = 10) {
2508
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
2509
+ return this.l1.hotKeys(n).map(({ key, hits, sizeBytes }) => ({
2510
+ key: prefixLen > 0 ? key.slice(prefixLen) : key,
2511
+ hits,
2512
+ sizeBytes
2513
+ }));
2514
+ }
2515
+ // ── Dependency cascade helpers ────────────────────────────────────────
2516
+ /**
2517
+ * Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
2518
+ * pattern that may contain `*` wildcards).
2519
+ */
2520
+ _matchesGlob(key, pattern) {
2521
+ if (!pattern.includes("*")) return key === pattern;
2522
+ const re = new RegExp("^" + pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$");
2523
+ return re.test(key);
2524
+ }
2525
+ /**
2526
+ * When an exact key `deletedKey` is removed, cascade to every dependent key
2527
+ * that was registered via `dependsOn` and whose source pattern matches.
2528
+ */
2529
+ _cascadeDependencies(deletedKey) {
2530
+ for (const [pattern, dependents] of this.dependencyIndex) {
2531
+ if (!this._matchesGlob(deletedKey, pattern)) continue;
2532
+ for (const dep of dependents) {
2533
+ if (dep === deletedKey) continue;
2534
+ this.l1.delete(dep);
2535
+ this.disk.delete(dep);
2536
+ void this.publishInvalidation("del", dep);
2537
+ this.logger.debug("Dependency cascade: invalidated dependent key", {
2538
+ trigger: deletedKey.slice(0, 60),
2539
+ dependent: dep.slice(0, 60)
2540
+ });
2541
+ }
2542
+ }
2543
+ }
2213
2544
  // ── Observability ──────────────────────────────────────────────────────────────────
2214
2545
  /** Return a full metrics snapshot. */
2215
2546
  metrics() {
@@ -2250,6 +2581,9 @@ var CacheService = class _CacheService {
2250
2581
  received: c.invReceived,
2251
2582
  skipped: c.invSkipped
2252
2583
  },
2584
+ l2CircuitBreaker: {
2585
+ state: this.cb.currentState
2586
+ },
2253
2587
  oom: {
2254
2588
  enabled: this.opts.oomProtection,
2255
2589
  evictions: c.oomEvictions,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tricache",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
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",
@@ -18,6 +18,7 @@
18
18
  "nodejs"
19
19
  ],
20
20
  "license": "MIT",
21
+ "packageManager": "pnpm@11.0.9",
21
22
  "type": "module",
22
23
  "main": "./dist/index.js",
23
24
  "module": "./dist/index.js",
@@ -35,6 +36,14 @@
35
36
  "README.md",
36
37
  "LICENSE"
37
38
  ],
39
+ "scripts": {
40
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean",
41
+ "dev": "tsup src/index.ts --format esm,cjs --dts --watch",
42
+ "typecheck": "tsc --noEmit",
43
+ "test": "vitest run",
44
+ "test:watch": "vitest",
45
+ "bench": "node --import tsx/esm bench/benchmark.ts"
46
+ },
38
47
  "dependencies": {
39
48
  "ioredis": "^5.3.2",
40
49
  "msgpackr": "^2.0.1"
@@ -53,13 +62,5 @@
53
62
  "repository": {
54
63
  "type": "git",
55
64
  "url": "git+https://github.com/Kareem411/TriCache.git"
56
- },
57
- "scripts": {
58
- "build": "tsup src/index.ts --format esm,cjs --dts --clean",
59
- "dev": "tsup src/index.ts --format esm,cjs --dts --watch",
60
- "typecheck": "tsc --noEmit",
61
- "test": "vitest run",
62
- "test:watch": "vitest",
63
- "bench": "node --import tsx/esm bench/benchmark.ts"
64
65
  }
65
- }
66
+ }