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.cjs CHANGED
@@ -769,9 +769,9 @@ var SmartMemoryCache = class {
769
769
  this.categoryHits.set(cat, (this.categoryHits.get(cat) ?? 0) + 1);
770
770
  const value = entry.value !== void 0 ? entry.value : (0, import_msgpackr.unpack)(entry.data);
771
771
  const isStale = entry.staleAt !== void 0 && now > entry.staleAt;
772
- return { value, isStale };
772
+ return { value, isStale, expiresAt: entry.expiresAt, ttlMs: entry.ttlMs, delta: entry.delta };
773
773
  }
774
- set(key, data, ttlMs, priority = 2, staleAt) {
774
+ set(key, data, ttlMs, priority = 2, staleAt, delta) {
775
775
  const packed = (0, import_msgpackr.pack)(data);
776
776
  const size = packed.byteLength;
777
777
  this.compressions++;
@@ -791,7 +791,7 @@ var SmartMemoryCache = class {
791
791
  }
792
792
  this.ensureCapacity(cat, size);
793
793
  const now = Date.now();
794
- this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority });
794
+ this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta });
795
795
  this.bloom.add(key);
796
796
  this.maybeRebuildBloom();
797
797
  this.totalSize += size;
@@ -1079,6 +1079,23 @@ var SmartMemoryCache = class {
1079
1079
  bloomStats() {
1080
1080
  return this.bloom.stats;
1081
1081
  }
1082
+ /**
1083
+ * Return the top-N live L1 keys by historical access frequency (Count-Min Sketch estimate).
1084
+ * Includes evicted-then-readmitted keys whose sketch frequency exceeds their current hit count.
1085
+ * Useful for diagnosing which keys are driving cache pressure.
1086
+ *
1087
+ * @param n - Maximum number of entries to return. Default: 10.
1088
+ */
1089
+ hotKeys(n) {
1090
+ const now = Date.now();
1091
+ const out = [];
1092
+ for (const [key, entry] of this.cache) {
1093
+ if (entry.expiresAt <= now) continue;
1094
+ out.push({ key, hits: this.sketch.estimate(key), sizeBytes: entry.size });
1095
+ }
1096
+ out.sort((a, b) => b.hits - a.hits);
1097
+ return out.slice(0, n);
1098
+ }
1082
1099
  };
1083
1100
 
1084
1101
  // src/disk-tier.ts
@@ -1366,6 +1383,47 @@ var DEFAULT_CATEGORY_LIMITS = {
1366
1383
  "default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
1367
1384
  };
1368
1385
  var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
1386
+ var L2CircuitBreaker = class {
1387
+ constructor(threshold, cooldownMs) {
1388
+ this.threshold = threshold;
1389
+ this.cooldownMs = cooldownMs;
1390
+ }
1391
+ threshold;
1392
+ cooldownMs;
1393
+ state = 0 /* CLOSED */;
1394
+ failures = 0;
1395
+ openedAt = 0;
1396
+ /** Call before each Redis attempt. Returns false when the circuit is open. */
1397
+ isAllowed() {
1398
+ if (this.state === 0 /* CLOSED */) return true;
1399
+ if (this.state === 2 /* HALF_OPEN */) return true;
1400
+ if (Date.now() - this.openedAt >= this.cooldownMs) {
1401
+ this.state = 2 /* HALF_OPEN */;
1402
+ return true;
1403
+ }
1404
+ return false;
1405
+ }
1406
+ /** Call on Redis success. */
1407
+ onSuccess() {
1408
+ this.failures = 0;
1409
+ this.state = 0 /* CLOSED */;
1410
+ }
1411
+ /** Call on Redis failure. */
1412
+ onFailure() {
1413
+ this.failures++;
1414
+ if (this.state === 2 /* HALF_OPEN */ || this.failures >= this.threshold) {
1415
+ this.state = 1 /* OPEN */;
1416
+ this.openedAt = Date.now();
1417
+ this.failures = 0;
1418
+ }
1419
+ }
1420
+ get isOpen() {
1421
+ return this.state === 1 /* OPEN */;
1422
+ }
1423
+ get currentState() {
1424
+ return this.state === 0 /* CLOSED */ ? "closed" : this.state === 1 /* OPEN */ ? "open" : "half_open";
1425
+ }
1426
+ };
1369
1427
  function inferPriority(cacheKey) {
1370
1428
  if (cacheKey.includes("auth:") || cacheKey.includes("session:")) return 4 /* CRITICAL */;
1371
1429
  if (cacheKey.includes("user:") || cacheKey.includes("org:") || cacheKey.includes("profile:")) return 3 /* HIGH */;
@@ -1388,8 +1446,14 @@ var CacheService = class _CacheService {
1388
1446
  _l1Counters = /* @__PURE__ */ new Map();
1389
1447
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
1390
1448
  tagIndex = /* @__PURE__ */ new Map();
1449
+ /**
1450
+ * Dependency index: source glob pattern → Set of namespaced dependent keys.
1451
+ * When an exact-key delete matches a registered pattern, all dependents are cascaded.
1452
+ */
1453
+ dependencyIndex = /* @__PURE__ */ new Map();
1391
1454
  redis = null;
1392
1455
  redisConnecting = null;
1456
+ cb;
1393
1457
  snapshotLoaded = false;
1394
1458
  cleanupInterval = null;
1395
1459
  oomInterval = null;
@@ -1464,8 +1528,14 @@ var CacheService = class _CacheService {
1464
1528
  metricsIntervalMs: options.metricsIntervalMs ?? 6e4,
1465
1529
  staleIfError: options.staleIfError ?? 0,
1466
1530
  l2WriteMode: options.l2WriteMode ?? "read-write",
1467
- instanceName: options.instanceName ?? ""
1531
+ instanceName: options.instanceName ?? "",
1532
+ ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
1533
+ tracer: options.tracer,
1534
+ notFoundTtl: options.notFoundTtl ?? 0
1468
1535
  };
1536
+ const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
1537
+ const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
1538
+ this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
1469
1539
  this.disk = new DiskTier({
1470
1540
  dir: this.opts.diskCacheDir,
1471
1541
  maxBytes: this.opts.diskMaxBytes,
@@ -1586,6 +1656,22 @@ var CacheService = class _CacheService {
1586
1656
  nk(key) {
1587
1657
  return this._namespace ? `${this._namespace}:${key}` : key;
1588
1658
  }
1659
+ /** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
1660
+ _jitterTtl(ttlMs) {
1661
+ const j = this.opts.ttlJitterFactor;
1662
+ if (j === 0) return ttlMs;
1663
+ return Math.round(ttlMs * (1 + (Math.random() * 2 - 1) * j));
1664
+ }
1665
+ /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
1666
+ _startSpan(name) {
1667
+ if (this.opts.tracer) return this.opts.tracer.startSpan(name);
1668
+ return { setAttribute() {
1669
+ return this;
1670
+ }, setStatus() {
1671
+ return this;
1672
+ }, end() {
1673
+ } };
1674
+ }
1589
1675
  initBackplane() {
1590
1676
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
1591
1677
  if (this.subClient) return;
@@ -1647,7 +1733,7 @@ var CacheService = class _CacheService {
1647
1733
  }
1648
1734
  }
1649
1735
  async getRedis() {
1650
- if (this.redis?.status === "ready") return this.redis;
1736
+ if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
1651
1737
  if (this.redisConnecting) return this.redisConnecting;
1652
1738
  this.redisConnecting = (async () => {
1653
1739
  try {
@@ -1671,10 +1757,12 @@ var CacheService = class _CacheService {
1671
1757
  client.once("error", reject);
1672
1758
  setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
1673
1759
  });
1760
+ this.cb.onSuccess();
1674
1761
  this.redis = client;
1675
1762
  this.redisConnecting = null;
1676
1763
  return client;
1677
1764
  } catch (err) {
1765
+ this.cb.onFailure();
1678
1766
  this.redisConnecting = null;
1679
1767
  throw err;
1680
1768
  }
@@ -1755,12 +1843,22 @@ var CacheService = class _CacheService {
1755
1843
  * @param cacheKey - Unique key identifying this value
1756
1844
  * @param fetchFn - Called on a cache miss; its return value is cached and returned
1757
1845
  * @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
1758
- * @param opts.priority - Override the auto-inferred eviction priority
1759
- * @param opts.swr - Stale-While-Revalidate grace seconds. When > 0 the entry stays
1760
- * alive for this many extra seconds after TTL; callers get stale data
1761
- * instantly while a background refresh runs. Default: 0 (disabled).
1846
+ * @param opts.priority - Override the auto-inferred eviction priority
1847
+ * @param opts.swr - Stale-While-Revalidate grace seconds.
1848
+ * @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
1849
+ * is triggered proactively while the caller still receives the
1850
+ * cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
1851
+ * Requires `fetchFn` to be stable across calls.
1852
+ * @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
1853
+ * recompute more aggressively before expiry. Typical range: 0.5–2.
1854
+ * Complementary to refreshAhead — uses recompute cost (delta) to
1855
+ * decide probabilistically rather than at a fixed threshold.
1856
+ * @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
1857
+ * Caches negative lookups to avoid repeated DB hits for missing keys.
1762
1858
  */
1763
1859
  async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
1860
+ const span = this._startSpan("tricache.get");
1861
+ span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
1764
1862
  const k = this.nk(cacheKey);
1765
1863
  this.counters.gets++;
1766
1864
  const l1Hit = this.l1.get(k);
@@ -1778,26 +1876,47 @@ var CacheService = class _CacheService {
1778
1876
  }
1779
1877
  } else {
1780
1878
  this.logger.debug("L1 hit");
1879
+ if (!this.revalidating.has(k) && (opts.refreshAhead || opts.xfetchBeta)) {
1880
+ const now = Date.now();
1881
+ const remaining = l1Hit.expiresAt - now;
1882
+ const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1e3;
1883
+ const priority2 = opts.priority ?? inferPriority(cacheKey);
1884
+ const shouldRefreshAhead = opts.refreshAhead != null && opts.refreshAhead > 0 ? remaining <= entryTtl * (1 - opts.refreshAhead) : false;
1885
+ const shouldXFetch = opts.xfetchBeta != null && opts.xfetchBeta > 0 && l1Hit.delta != null ? remaining <= l1Hit.delta * opts.xfetchBeta * -Math.log(Math.random()) : false;
1886
+ if (shouldRefreshAhead || shouldXFetch) {
1887
+ this.revalidating.add(k);
1888
+ void this._revalidate(k, fetchFn, entryTtl, (opts.swr ?? 0) * 1e3, priority2);
1889
+ this.counters.swrRevalidations++;
1890
+ this.logger.debug(
1891
+ shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
1892
+ { cacheKey, remainingMs: remaining, ttlMs: entryTtl }
1893
+ );
1894
+ }
1895
+ }
1781
1896
  }
1782
1897
  this.counters.l1Hits++;
1898
+ span.setAttribute("cache.hit", "l1").end();
1783
1899
  return l1Hit.value;
1784
1900
  }
1785
- const ttlMs = ttlSeconds * 1e3;
1901
+ const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
1786
1902
  const swrGraceMs = (opts.swr ?? 0) * 1e3;
1787
1903
  const priority = opts.priority ?? inferPriority(cacheKey);
1788
1904
  if (!this._redisDisabled) {
1789
1905
  try {
1790
1906
  const client = await this.getRedis();
1791
1907
  const raw = await client.get(k);
1908
+ this.cb.onSuccess();
1792
1909
  if (raw) {
1793
1910
  const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
1794
1911
  const parsed = JSON.parse(decrypted);
1795
1912
  this.l1.set(k, parsed, ttlMs, priority);
1796
1913
  this.counters.l2Hits++;
1797
1914
  this.logger.debug("L2 hit (Redis)", { cacheKey });
1915
+ span.setAttribute("cache.hit", "l2").end();
1798
1916
  return parsed;
1799
1917
  }
1800
1918
  } catch (err) {
1919
+ this.cb.onFailure();
1801
1920
  this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
1802
1921
  }
1803
1922
  }
@@ -1812,31 +1931,40 @@ var CacheService = class _CacheService {
1812
1931
  if (l1Check !== null) {
1813
1932
  this.counters.diskHits++;
1814
1933
  this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
1934
+ span.setAttribute("cache.hit", "disk").end();
1815
1935
  return l1Check.value;
1816
1936
  }
1817
1937
  }
1818
1938
  }
1939
+ span.setAttribute("cache.hit", "miss");
1819
1940
  const existing = this.inflight.get(k);
1820
1941
  if (existing) {
1821
1942
  this.counters.stampedes++;
1822
1943
  this.logger.debug("Stampede prevented \u2014 coalescing onto inflight fetch", { cacheKey });
1944
+ span.end();
1823
1945
  return existing;
1824
1946
  }
1825
1947
  const fetchPromise = (async () => {
1826
1948
  try {
1827
1949
  this.counters.fetches++;
1950
+ const fetchStart = Date.now();
1828
1951
  const data = await fetchFn();
1829
- const staleAt = swrGraceMs > 0 ? Date.now() + ttlMs : void 0;
1830
- const storeTtl = swrGraceMs > 0 ? ttlMs + swrGraceMs : ttlMs;
1831
- this.l1.set(k, data, storeTtl, priority, staleAt);
1952
+ const delta = Date.now() - fetchStart;
1953
+ const notFoundTtlMs = (opts.notFoundTtl ?? this.opts.notFoundTtl) * 1e3;
1954
+ const effectiveTtl = data == null && notFoundTtlMs > 0 ? notFoundTtlMs : ttlMs;
1955
+ const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
1956
+ const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
1957
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta);
1832
1958
  if (!this._redisDisabled) {
1833
1959
  try {
1834
1960
  const client = await this.getRedis();
1835
1961
  const serialized = JSON.stringify(data);
1836
1962
  const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
1837
- await client.setex(k, ttlSeconds, toStore);
1963
+ await client.setex(k, Math.ceil(effectiveTtl / 1e3), toStore);
1964
+ this.cb.onSuccess();
1838
1965
  this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
1839
1966
  } catch {
1967
+ this.cb.onFailure();
1840
1968
  this.logger.debug("Cached L1 only (Redis unavailable)", { cacheKey });
1841
1969
  }
1842
1970
  } else {
@@ -1845,6 +1973,7 @@ var CacheService = class _CacheService {
1845
1973
  return data;
1846
1974
  } finally {
1847
1975
  this.inflight.delete(k);
1976
+ span.end();
1848
1977
  }
1849
1978
  })();
1850
1979
  this.inflight.set(k, fetchPromise);
@@ -1852,9 +1981,11 @@ var CacheService = class _CacheService {
1852
1981
  }
1853
1982
  async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
1854
1983
  try {
1984
+ const fetchStart = Date.now();
1855
1985
  const data = await fetchFn();
1986
+ const delta = Date.now() - fetchStart;
1856
1987
  const staleAt = Date.now() + ttlMs;
1857
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt);
1988
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta);
1858
1989
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
1859
1990
  try {
1860
1991
  const client = await this.getRedis();
@@ -1883,7 +2014,9 @@ var CacheService = class _CacheService {
1883
2014
  // ── Explicit set / delete ─────────────────────────────────────────────────
1884
2015
  /** Explicitly write a value into L1 (+ L2 in production). */
1885
2016
  async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
1886
- const ttlMs = ttlSeconds * 1e3;
2017
+ const span = this._startSpan("tricache.set");
2018
+ span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2019
+ const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
1887
2020
  const p = priority ?? inferPriority(cacheKey);
1888
2021
  const k = this.nk(cacheKey);
1889
2022
  this.counters.sets++;
@@ -1908,21 +2041,37 @@ var CacheService = class _CacheService {
1908
2041
  pl.expire(tagKey, ttlSeconds + 3600);
1909
2042
  }
1910
2043
  await pl.exec();
2044
+ this.cb.onSuccess();
1911
2045
  } catch {
2046
+ this.cb.onFailure();
1912
2047
  }
1913
2048
  }
1914
2049
  }
2050
+ if (opts?.dependsOn?.length) {
2051
+ for (const pattern of opts.dependsOn) {
2052
+ const nsPattern = this.nk(pattern);
2053
+ let deps = this.dependencyIndex.get(nsPattern);
2054
+ if (!deps) {
2055
+ deps = /* @__PURE__ */ new Set();
2056
+ this.dependencyIndex.set(nsPattern, deps);
2057
+ }
2058
+ deps.add(k);
2059
+ }
2060
+ }
1915
2061
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
1916
2062
  try {
1917
2063
  const client = await this.getRedis();
1918
2064
  const s = JSON.stringify(data);
1919
2065
  const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
1920
- await client.setex(k, ttlSeconds, stored);
2066
+ await client.setex(k, Math.ceil(ttlMs / 1e3), stored);
2067
+ this.cb.onSuccess();
1921
2068
  } catch (err) {
2069
+ this.cb.onFailure();
1922
2070
  this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
1923
2071
  }
1924
2072
  }
1925
2073
  void this.publishInvalidation("del", k);
2074
+ span.end();
1926
2075
  }
1927
2076
  /**
1928
2077
  * Delete one key or a glob pattern (supports `*` wildcard).
@@ -1932,6 +2081,8 @@ var CacheService = class _CacheService {
1932
2081
  * await cache.delete('user:abc:*'); // all keys for user abc
1933
2082
  */
1934
2083
  async delete(cacheKey) {
2084
+ const span = this._startSpan("tricache.delete");
2085
+ span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
1935
2086
  const isPattern = cacheKey.includes("*");
1936
2087
  const k = this.nk(cacheKey);
1937
2088
  this.counters.deletes++;
@@ -1940,6 +2091,8 @@ var CacheService = class _CacheService {
1940
2091
  } else {
1941
2092
  this.l1.delete(k);
1942
2093
  this.disk.delete(k);
2094
+ this._cascadeDependencies(k);
2095
+ for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
1943
2096
  }
1944
2097
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
1945
2098
  try {
@@ -1956,11 +2109,14 @@ var CacheService = class _CacheService {
1956
2109
  } else {
1957
2110
  await client.del(k);
1958
2111
  }
2112
+ this.cb.onSuccess();
1959
2113
  } catch (err) {
2114
+ this.cb.onFailure();
1960
2115
  this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
1961
2116
  }
1962
2117
  }
1963
2118
  void this.publishInvalidation(isPattern ? "del-glob" : "del", k);
2119
+ span.end();
1964
2120
  }
1965
2121
  // ── Counter (distributed rate limiting) ──────────────────────────────────
1966
2122
  /**
@@ -2159,6 +2315,93 @@ var CacheService = class _CacheService {
2159
2315
  }
2160
2316
  return result;
2161
2317
  }
2318
+ /**
2319
+ * Batch write — set multiple entries in a single call.
2320
+ * TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
2321
+ *
2322
+ * @example
2323
+ * await cache.mset({
2324
+ * 'user:1': { value: { name: 'Alice' }, ttl: 300 },
2325
+ * 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
2326
+ * });
2327
+ */
2328
+ async mset(entries) {
2329
+ const keys = Object.keys(entries);
2330
+ await Promise.all(keys.map((key) => {
2331
+ const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
2332
+ const hasOpts = tags?.length || dependsOn?.length;
2333
+ return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
2334
+ }));
2335
+ }
2336
+ /**
2337
+ * Batch delete — delete multiple exact keys in a single call.
2338
+ * Glob patterns are not supported; use `delete('prefix:*')` for patterns.
2339
+ *
2340
+ * @example
2341
+ * await cache.mdel(['user:1', 'user:2', 'user:3']);
2342
+ */
2343
+ async mdel(keys) {
2344
+ await Promise.all(keys.map((k) => this.delete(k)));
2345
+ }
2346
+ /**
2347
+ * Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
2348
+ * pulling them into L1. Useful on startup to eliminate cold-start penalty when
2349
+ * the local snapshot is unavailable or too stale.
2350
+ *
2351
+ * Returns the number of keys loaded into L1.
2352
+ *
2353
+ * @example
2354
+ * // In your startup hook (e.g. ECS task, k8s readiness probe):
2355
+ * const loaded = await cache.warmFromL2('org:*');
2356
+ * console.log(`Warmed ${loaded} keys from Redis`);
2357
+ */
2358
+ async warmFromL2(pattern) {
2359
+ if (this._redisDisabled) return 0;
2360
+ try {
2361
+ const client = await this.getRedis();
2362
+ const nsPattern = this.nk(pattern);
2363
+ const matchedKeys = [];
2364
+ const stream = client.scanStream({ match: nsPattern, count: 100 });
2365
+ await new Promise((resolve, reject) => {
2366
+ stream.on("data", (chunk) => matchedKeys.push(...chunk));
2367
+ stream.on("end", resolve);
2368
+ stream.on("error", reject);
2369
+ });
2370
+ if (matchedKeys.length === 0) {
2371
+ this.cb.onSuccess();
2372
+ return 0;
2373
+ }
2374
+ const pl = client.pipeline();
2375
+ for (const k of matchedKeys) pl.get(k);
2376
+ const results = await pl.exec();
2377
+ this.cb.onSuccess();
2378
+ let loaded = 0;
2379
+ const now = Date.now();
2380
+ for (let i = 0; i < matchedKeys.length; i++) {
2381
+ const [err, raw] = results[i];
2382
+ if (err || raw == null) continue;
2383
+ try {
2384
+ const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
2385
+ const parsed = JSON.parse(decrypted);
2386
+ const remainingMs = 10 * 60 * 1e3;
2387
+ this.l1.set(matchedKeys[i], parsed, remainingMs, inferPriority(matchedKeys[i]));
2388
+ loaded++;
2389
+ } catch {
2390
+ }
2391
+ }
2392
+ void now;
2393
+ this.logger.info("warmFromL2 complete", {
2394
+ pattern,
2395
+ matched: matchedKeys.length,
2396
+ loaded
2397
+ });
2398
+ return loaded;
2399
+ } catch (err) {
2400
+ this.cb.onFailure();
2401
+ this.logger.debug("warmFromL2: Redis unavailable", { error: err.message });
2402
+ return 0;
2403
+ }
2404
+ }
2162
2405
  /**
2163
2406
  * Invalidate all keys associated with a tag.
2164
2407
  * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
@@ -2252,6 +2495,94 @@ var CacheService = class _CacheService {
2252
2495
  disk: this.disk.stats
2253
2496
  };
2254
2497
  }
2498
+ // ── Conditional write ─────────────────────────────────────────────────
2499
+ /**
2500
+ * Write `value` only if the key is not already cached.
2501
+ * Returns `true` if the write happened, `false` if the key already existed.
2502
+ *
2503
+ * When Redis is available, atomicity is guaranteed via `SET NX EX` so this
2504
+ * is safe to use for idempotency keys and "first writer wins" patterns across
2505
+ * multiple instances. L1 is populated on success.
2506
+ *
2507
+ * @example
2508
+ * const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
2509
+ * if (!claimed) return res.status(409).json({ error: 'duplicate request' });
2510
+ */
2511
+ async setIfAbsent(cacheKey, value, ttlSeconds = 300, priority) {
2512
+ const k = this.nk(cacheKey);
2513
+ if (this.l1.has(k)) return false;
2514
+ if (!this._redisDisabled) {
2515
+ try {
2516
+ const client = await this.getRedis();
2517
+ const serialized = JSON.stringify(value);
2518
+ const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
2519
+ const result = await client.set(k, toStore, "EX", ttlSeconds, "NX");
2520
+ this.cb.onSuccess();
2521
+ if (result === null) return false;
2522
+ } catch (err) {
2523
+ this.cb.onFailure();
2524
+ this.logger.debug("setIfAbsent: Redis unavailable, falling back to L1 check", { cacheKey, error: err.message });
2525
+ if (this.l1.has(k)) return false;
2526
+ }
2527
+ }
2528
+ const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
2529
+ const p = priority ?? inferPriority(cacheKey);
2530
+ this.l1.set(k, value, ttlMs, p);
2531
+ this.counters.sets++;
2532
+ return true;
2533
+ }
2534
+ // ── Hot key introspection ─────────────────────────────────────────────
2535
+ /**
2536
+ * Return the top-N live L1 keys by historical access frequency.
2537
+ * Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
2538
+ * whose historical frequency exceeds their current in-memory hit count.
2539
+ *
2540
+ * Useful for diagnosing what is driving L1 pressure without any extra data
2541
+ * collection overhead.
2542
+ *
2543
+ * @param n - Maximum number of keys to return. Default: 10.
2544
+ *
2545
+ * @example
2546
+ * cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
2547
+ * console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
2548
+ */
2549
+ hotKeys(n = 10) {
2550
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
2551
+ return this.l1.hotKeys(n).map(({ key, hits, sizeBytes }) => ({
2552
+ key: prefixLen > 0 ? key.slice(prefixLen) : key,
2553
+ hits,
2554
+ sizeBytes
2555
+ }));
2556
+ }
2557
+ // ── Dependency cascade helpers ────────────────────────────────────────
2558
+ /**
2559
+ * Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
2560
+ * pattern that may contain `*` wildcards).
2561
+ */
2562
+ _matchesGlob(key, pattern) {
2563
+ if (!pattern.includes("*")) return key === pattern;
2564
+ const re = new RegExp("^" + pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$");
2565
+ return re.test(key);
2566
+ }
2567
+ /**
2568
+ * When an exact key `deletedKey` is removed, cascade to every dependent key
2569
+ * that was registered via `dependsOn` and whose source pattern matches.
2570
+ */
2571
+ _cascadeDependencies(deletedKey) {
2572
+ for (const [pattern, dependents] of this.dependencyIndex) {
2573
+ if (!this._matchesGlob(deletedKey, pattern)) continue;
2574
+ for (const dep of dependents) {
2575
+ if (dep === deletedKey) continue;
2576
+ this.l1.delete(dep);
2577
+ this.disk.delete(dep);
2578
+ void this.publishInvalidation("del", dep);
2579
+ this.logger.debug("Dependency cascade: invalidated dependent key", {
2580
+ trigger: deletedKey.slice(0, 60),
2581
+ dependent: dep.slice(0, 60)
2582
+ });
2583
+ }
2584
+ }
2585
+ }
2255
2586
  // ── Observability ──────────────────────────────────────────────────────────────────
2256
2587
  /** Return a full metrics snapshot. */
2257
2588
  metrics() {
@@ -2292,6 +2623,9 @@ var CacheService = class _CacheService {
2292
2623
  received: c.invReceived,
2293
2624
  skipped: c.invSkipped
2294
2625
  },
2626
+ l2CircuitBreaker: {
2627
+ state: this.cb.currentState
2628
+ },
2295
2629
  oom: {
2296
2630
  enabled: this.opts.oomProtection,
2297
2631
  evictions: c.oomEvictions,