tricache 0.3.1 → 0.5.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
@@ -449,6 +449,7 @@ var WasmBloomFilter = class {
449
449
  };
450
450
 
451
451
  // src/smart-memory-cache.ts
452
+ var _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0 };
452
453
  var EVICTION_BATCH_PERCENT = 0.2;
453
454
  var JsBloomFilter = class {
454
455
  bits;
@@ -553,32 +554,35 @@ var CountMinSketch = class {
553
554
  }
554
555
  return h;
555
556
  }
556
- /** Four independent bit-mixes from one FNV-1a seed. */
557
- hashes(key) {
557
+ /** Record one access. Decays all counters when the insertion threshold is crossed. */
558
+ increment(key) {
558
559
  const h = this.fnv32(key);
559
560
  const h1 = (h ^ h >>> 16) >>> 0;
560
561
  const h2 = (Math.imul(h1, 73244475) ^ h1 >>> 16) >>> 0;
561
562
  const h3 = (Math.imul(h2, 2142877601) ^ h2 >>> 16) >>> 0;
562
563
  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
564
  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);
565
+ const i0 = h1 & SKETCH_MASK;
566
+ const i1 = SKETCH_WIDTH + (h2 & SKETCH_MASK);
567
+ const i2 = 2 * SKETCH_WIDTH + (h3 & SKETCH_MASK);
568
+ const i3 = 3 * SKETCH_WIDTH + (h4 & SKETCH_MASK);
569
+ if (t[i0] < 65535) t[i0]++;
570
+ if (t[i1] < 65535) t[i1]++;
571
+ if (t[i2] < 65535) t[i2]++;
572
+ if (t[i3] < 65535) t[i3]++;
573
573
  if (++this.inserts >= SKETCH_DECAY_THRESHOLD) this.decay();
574
574
  }
575
575
  /** Minimum-across-rows frequency estimate. */
576
576
  estimate(key) {
577
- const [h1, h2, h3, h4] = this.hashes(key);
577
+ const h = this.fnv32(key);
578
+ const h1 = (h ^ h >>> 16) >>> 0;
579
+ const h2 = (Math.imul(h1, 73244475) ^ h1 >>> 16) >>> 0;
580
+ const h3 = (Math.imul(h2, 2142877601) ^ h2 >>> 16) >>> 0;
581
+ const h4 = (Math.imul(h3, 461845907) ^ h3 >>> 16) >>> 0;
578
582
  const t = this.table;
579
583
  return Math.min(
580
- t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)],
581
- t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)],
584
+ t[h1 & SKETCH_MASK],
585
+ t[SKETCH_WIDTH + (h2 & SKETCH_MASK)],
582
586
  t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)],
583
587
  t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)]
584
588
  );
@@ -764,14 +768,16 @@ var SmartMemoryCache = class {
764
768
  }
765
769
  entry.hits++;
766
770
  entry.lastAccess = now;
767
- this.sketch.increment(key);
768
- const cat = this.getCategory(key);
769
- this.categoryHits.set(cat, (this.categoryHits.get(cat) ?? 0) + 1);
771
+ if ((entry.hits & 3) === 0) this.sketch.increment(key);
770
772
  const value = entry.value !== void 0 ? entry.value : (0, import_msgpackr.unpack)(entry.data);
771
- const isStale = entry.staleAt !== void 0 && now > entry.staleAt;
772
- return { value, isStale };
773
- }
774
- set(key, data, ttlMs, priority = 2, staleAt) {
773
+ _hit.value = value;
774
+ _hit.isStale = entry.staleAt !== void 0 && now > entry.staleAt;
775
+ _hit.expiresAt = entry.expiresAt;
776
+ _hit.ttlMs = entry.ttlMs;
777
+ _hit.delta = entry.delta;
778
+ return _hit;
779
+ }
780
+ set(key, data, ttlMs, priority = 2, staleAt, delta) {
775
781
  const packed = (0, import_msgpackr.pack)(data);
776
782
  const size = packed.byteLength;
777
783
  this.compressions++;
@@ -791,7 +797,7 @@ var SmartMemoryCache = class {
791
797
  }
792
798
  this.ensureCapacity(cat, size);
793
799
  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 });
800
+ this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta });
795
801
  this.bloom.add(key);
796
802
  this.maybeRebuildBloom();
797
803
  this.totalSize += size;
@@ -1079,6 +1085,23 @@ var SmartMemoryCache = class {
1079
1085
  bloomStats() {
1080
1086
  return this.bloom.stats;
1081
1087
  }
1088
+ /**
1089
+ * Return the top-N live L1 keys by historical access frequency (Count-Min Sketch estimate).
1090
+ * Includes evicted-then-readmitted keys whose sketch frequency exceeds their current hit count.
1091
+ * Useful for diagnosing which keys are driving cache pressure.
1092
+ *
1093
+ * @param n - Maximum number of entries to return. Default: 10.
1094
+ */
1095
+ hotKeys(n) {
1096
+ const now = Date.now();
1097
+ const out = [];
1098
+ for (const [key, entry] of this.cache) {
1099
+ if (entry.expiresAt <= now) continue;
1100
+ out.push({ key, hits: this.sketch.estimate(key), sizeBytes: entry.size });
1101
+ }
1102
+ out.sort((a, b) => b.hits - a.hits);
1103
+ return out.slice(0, n);
1104
+ }
1082
1105
  };
1083
1106
 
1084
1107
  // src/disk-tier.ts
@@ -1429,10 +1452,16 @@ var CacheService = class _CacheService {
1429
1452
  _l1Counters = /* @__PURE__ */ new Map();
1430
1453
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
1431
1454
  tagIndex = /* @__PURE__ */ new Map();
1455
+ /**
1456
+ * Dependency index: source glob pattern → Set of namespaced dependent keys.
1457
+ * When an exact-key delete matches a registered pattern, all dependents are cascaded.
1458
+ */
1459
+ dependencyIndex = /* @__PURE__ */ new Map();
1432
1460
  redis = null;
1433
1461
  redisConnecting = null;
1434
1462
  cb;
1435
1463
  snapshotLoaded = false;
1464
+ _readyPromise = Promise.resolve();
1436
1465
  cleanupInterval = null;
1437
1466
  oomInterval = null;
1438
1467
  metricsInterval = null;
@@ -1508,7 +1537,9 @@ var CacheService = class _CacheService {
1508
1537
  l2WriteMode: options.l2WriteMode ?? "read-write",
1509
1538
  instanceName: options.instanceName ?? "",
1510
1539
  ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
1511
- tracer: options.tracer
1540
+ tracer: options.tracer,
1541
+ notFoundTtl: options.notFoundTtl ?? 0,
1542
+ warmKeys: options.warmKeys
1512
1543
  };
1513
1544
  const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
1514
1545
  const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
@@ -1580,6 +1611,9 @@ var CacheService = class _CacheService {
1580
1611
  this.instanceId = import_crypto3.default.randomBytes(8).toString("hex");
1581
1612
  this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
1582
1613
  this.initBackplane();
1614
+ if (this.opts.warmKeys) {
1615
+ this._readyPromise = this.warmFromL2(this.opts.warmKeys).then(() => void 0);
1616
+ }
1583
1617
  }
1584
1618
  // ── Singleton factory ─────────────────────────────────────────────────────
1585
1619
  /**
@@ -1687,6 +1721,7 @@ var CacheService = class _CacheService {
1687
1721
  if (msg.op === "del") {
1688
1722
  this.l1.delete(msg.key);
1689
1723
  setImmediate(() => this.disk.delete(msg.key));
1724
+ this._cascadeDependencies(msg.key);
1690
1725
  } else if (msg.op === "del-glob") {
1691
1726
  this.l1.deletePattern(msg.key);
1692
1727
  }
@@ -1820,10 +1855,18 @@ var CacheService = class _CacheService {
1820
1855
  * @param cacheKey - Unique key identifying this value
1821
1856
  * @param fetchFn - Called on a cache miss; its return value is cached and returned
1822
1857
  * @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
1823
- * @param opts.priority - Override the auto-inferred eviction priority
1824
- * @param opts.swr - Stale-While-Revalidate grace seconds. When > 0 the entry stays
1825
- * alive for this many extra seconds after TTL; callers get stale data
1826
- * instantly while a background refresh runs. Default: 0 (disabled).
1858
+ * @param opts.priority - Override the auto-inferred eviction priority
1859
+ * @param opts.swr - Stale-While-Revalidate grace seconds.
1860
+ * @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
1861
+ * is triggered proactively while the caller still receives the
1862
+ * cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
1863
+ * Requires `fetchFn` to be stable across calls.
1864
+ * @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
1865
+ * recompute more aggressively before expiry. Typical range: 0.5–2.
1866
+ * Complementary to refreshAhead — uses recompute cost (delta) to
1867
+ * decide probabilistically rather than at a fixed threshold.
1868
+ * @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
1869
+ * Caches negative lookups to avoid repeated DB hits for missing keys.
1827
1870
  */
1828
1871
  async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
1829
1872
  const span = this._startSpan("tricache.get");
@@ -1845,6 +1888,23 @@ var CacheService = class _CacheService {
1845
1888
  }
1846
1889
  } else {
1847
1890
  this.logger.debug("L1 hit");
1891
+ if (!this.revalidating.has(k) && (opts.refreshAhead || opts.xfetchBeta)) {
1892
+ const now = Date.now();
1893
+ const remaining = l1Hit.expiresAt - now;
1894
+ const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1e3;
1895
+ const shouldRefreshAhead = opts.refreshAhead != null && opts.refreshAhead > 0 ? remaining <= entryTtl * (1 - opts.refreshAhead) : false;
1896
+ const shouldXFetch = opts.xfetchBeta != null && opts.xfetchBeta > 0 && l1Hit.delta != null ? remaining <= l1Hit.delta * opts.xfetchBeta * -Math.log(Math.random()) : false;
1897
+ if (shouldRefreshAhead || shouldXFetch) {
1898
+ const priority2 = opts.priority ?? inferPriority(cacheKey);
1899
+ this.revalidating.add(k);
1900
+ void this._revalidate(k, fetchFn, entryTtl, (opts.swr ?? 0) * 1e3, priority2);
1901
+ this.counters.swrRevalidations++;
1902
+ this.logger.debug(
1903
+ shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
1904
+ { cacheKey, remainingMs: remaining, ttlMs: entryTtl }
1905
+ );
1906
+ }
1907
+ }
1848
1908
  }
1849
1909
  this.counters.l1Hits++;
1850
1910
  span.setAttribute("cache.hit", "l1").end();
@@ -1899,16 +1959,20 @@ var CacheService = class _CacheService {
1899
1959
  const fetchPromise = (async () => {
1900
1960
  try {
1901
1961
  this.counters.fetches++;
1962
+ const fetchStart = Date.now();
1902
1963
  const data = await fetchFn();
1903
- const staleAt = swrGraceMs > 0 ? Date.now() + ttlMs : void 0;
1904
- const storeTtl = swrGraceMs > 0 ? ttlMs + swrGraceMs : ttlMs;
1905
- this.l1.set(k, data, storeTtl, priority, staleAt);
1964
+ const delta = Date.now() - fetchStart;
1965
+ const notFoundTtlMs = (opts.notFoundTtl ?? this.opts.notFoundTtl) * 1e3;
1966
+ const effectiveTtl = data == null && notFoundTtlMs > 0 ? notFoundTtlMs : ttlMs;
1967
+ const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
1968
+ const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
1969
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta);
1906
1970
  if (!this._redisDisabled) {
1907
1971
  try {
1908
1972
  const client = await this.getRedis();
1909
1973
  const serialized = JSON.stringify(data);
1910
1974
  const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
1911
- await client.setex(k, Math.ceil(ttlMs / 1e3), toStore);
1975
+ await client.setex(k, Math.ceil(effectiveTtl / 1e3), toStore);
1912
1976
  this.cb.onSuccess();
1913
1977
  this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
1914
1978
  } catch {
@@ -1929,9 +1993,11 @@ var CacheService = class _CacheService {
1929
1993
  }
1930
1994
  async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
1931
1995
  try {
1996
+ const fetchStart = Date.now();
1932
1997
  const data = await fetchFn();
1998
+ const delta = Date.now() - fetchStart;
1933
1999
  const staleAt = Date.now() + ttlMs;
1934
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt);
2000
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta);
1935
2001
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
1936
2002
  try {
1937
2003
  const client = await this.getRedis();
@@ -1993,6 +2059,17 @@ var CacheService = class _CacheService {
1993
2059
  }
1994
2060
  }
1995
2061
  }
2062
+ if (opts?.dependsOn?.length) {
2063
+ for (const pattern of opts.dependsOn) {
2064
+ const nsPattern = this.nk(pattern);
2065
+ let deps = this.dependencyIndex.get(nsPattern);
2066
+ if (!deps) {
2067
+ deps = /* @__PURE__ */ new Set();
2068
+ this.dependencyIndex.set(nsPattern, deps);
2069
+ }
2070
+ deps.add(k);
2071
+ }
2072
+ }
1996
2073
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
1997
2074
  try {
1998
2075
  const client = await this.getRedis();
@@ -2026,6 +2103,8 @@ var CacheService = class _CacheService {
2026
2103
  } else {
2027
2104
  this.l1.delete(k);
2028
2105
  this.disk.delete(k);
2106
+ this._cascadeDependencies(k);
2107
+ for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
2029
2108
  }
2030
2109
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
2031
2110
  try {
@@ -2220,7 +2299,8 @@ var CacheService = class _CacheService {
2220
2299
  *
2221
2300
  * @param keys - Array of cache keys.
2222
2301
  * @param fetchFn - Called with only the keys that missed L1.
2223
- * @param ttl - TTL in seconds for newly fetched values.
2302
+ * @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
2303
+ * `(key) => number` so heterogeneous TTLs can be batched in one call.
2224
2304
  */
2225
2305
  async mget(keys, fetchFn, ttl = 300, priority) {
2226
2306
  const result = new Array(keys.length);
@@ -2242,12 +2322,27 @@ var CacheService = class _CacheService {
2242
2322
  const v = fetched[missKeys[j]];
2243
2323
  result[missIndexes[j]] = v;
2244
2324
  if (v !== void 0) {
2245
- await this.set(missKeys[j], v, ttl, priority);
2325
+ const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
2326
+ await this.set(missKeys[j], v, resolvedTtl, priority);
2246
2327
  }
2247
2328
  }
2248
2329
  }
2249
2330
  return result;
2250
2331
  }
2332
+ /**
2333
+ * Returns a Promise that resolves once the cache is fully initialised and any
2334
+ * startup warming configured via `warmKeys` has completed.
2335
+ *
2336
+ * Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once
2337
+ * `warmFromL2(warmKeys)` finishes — ideal for k8s readiness probes.
2338
+ *
2339
+ * @example
2340
+ * const cache = CacheService.create({ warmKeys: 'user:*' });
2341
+ * await cache.ready(); // gate traffic until warm
2342
+ */
2343
+ ready() {
2344
+ return this._readyPromise;
2345
+ }
2251
2346
  /**
2252
2347
  * Batch write — set multiple entries in a single call.
2253
2348
  * TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
@@ -2261,8 +2356,9 @@ var CacheService = class _CacheService {
2261
2356
  async mset(entries) {
2262
2357
  const keys = Object.keys(entries);
2263
2358
  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);
2359
+ const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
2360
+ const hasOpts = tags?.length || dependsOn?.length;
2361
+ return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : void 0);
2266
2362
  }));
2267
2363
  }
2268
2364
  /**
@@ -2427,6 +2523,94 @@ var CacheService = class _CacheService {
2427
2523
  disk: this.disk.stats
2428
2524
  };
2429
2525
  }
2526
+ // ── Conditional write ─────────────────────────────────────────────────
2527
+ /**
2528
+ * Write `value` only if the key is not already cached.
2529
+ * Returns `true` if the write happened, `false` if the key already existed.
2530
+ *
2531
+ * When Redis is available, atomicity is guaranteed via `SET NX EX` so this
2532
+ * is safe to use for idempotency keys and "first writer wins" patterns across
2533
+ * multiple instances. L1 is populated on success.
2534
+ *
2535
+ * @example
2536
+ * const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
2537
+ * if (!claimed) return res.status(409).json({ error: 'duplicate request' });
2538
+ */
2539
+ async setIfAbsent(cacheKey, value, ttlSeconds = 300, priority) {
2540
+ const k = this.nk(cacheKey);
2541
+ if (this.l1.has(k)) return false;
2542
+ if (!this._redisDisabled) {
2543
+ try {
2544
+ const client = await this.getRedis();
2545
+ const serialized = JSON.stringify(value);
2546
+ const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
2547
+ const result = await client.set(k, toStore, "EX", ttlSeconds, "NX");
2548
+ this.cb.onSuccess();
2549
+ if (result === null) return false;
2550
+ } catch (err) {
2551
+ this.cb.onFailure();
2552
+ this.logger.debug("setIfAbsent: Redis unavailable, falling back to L1 check", { cacheKey, error: err.message });
2553
+ if (this.l1.has(k)) return false;
2554
+ }
2555
+ }
2556
+ const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
2557
+ const p = priority ?? inferPriority(cacheKey);
2558
+ this.l1.set(k, value, ttlMs, p);
2559
+ this.counters.sets++;
2560
+ return true;
2561
+ }
2562
+ // ── Hot key introspection ─────────────────────────────────────────────
2563
+ /**
2564
+ * Return the top-N live L1 keys by historical access frequency.
2565
+ * Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
2566
+ * whose historical frequency exceeds their current in-memory hit count.
2567
+ *
2568
+ * Useful for diagnosing what is driving L1 pressure without any extra data
2569
+ * collection overhead.
2570
+ *
2571
+ * @param n - Maximum number of keys to return. Default: 10.
2572
+ *
2573
+ * @example
2574
+ * cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
2575
+ * console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
2576
+ */
2577
+ hotKeys(n = 10) {
2578
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
2579
+ return this.l1.hotKeys(n).map(({ key, hits, sizeBytes }) => ({
2580
+ key: prefixLen > 0 ? key.slice(prefixLen) : key,
2581
+ hits,
2582
+ sizeBytes
2583
+ }));
2584
+ }
2585
+ // ── Dependency cascade helpers ────────────────────────────────────────
2586
+ /**
2587
+ * Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
2588
+ * pattern that may contain `*` wildcards).
2589
+ */
2590
+ _matchesGlob(key, pattern) {
2591
+ if (!pattern.includes("*")) return key === pattern;
2592
+ const re = new RegExp("^" + pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$");
2593
+ return re.test(key);
2594
+ }
2595
+ /**
2596
+ * When an exact key `deletedKey` is removed, cascade to every dependent key
2597
+ * that was registered via `dependsOn` and whose source pattern matches.
2598
+ */
2599
+ _cascadeDependencies(deletedKey) {
2600
+ for (const [pattern, dependents] of this.dependencyIndex) {
2601
+ if (!this._matchesGlob(deletedKey, pattern)) continue;
2602
+ for (const dep of dependents) {
2603
+ if (dep === deletedKey) continue;
2604
+ this.l1.delete(dep);
2605
+ this.disk.delete(dep);
2606
+ void this.publishInvalidation("del", dep);
2607
+ this.logger.debug("Dependency cascade: invalidated dependent key", {
2608
+ trigger: deletedKey.slice(0, 60),
2609
+ dependent: dep.slice(0, 60)
2610
+ });
2611
+ }
2612
+ }
2613
+ }
2430
2614
  // ── Observability ──────────────────────────────────────────────────────────────────
2431
2615
  /** Return a full metrics snapshot. */
2432
2616
  metrics() {
package/dist/index.d.cts CHANGED
@@ -79,12 +79,23 @@ interface SmartCacheEntry {
79
79
  lastAccess: number;
80
80
  /** Eviction priority */
81
81
  priority: CachePriority;
82
+ /** Original TTL in ms at write time — used by refresh-ahead to compute the proactive refresh threshold. */
83
+ ttlMs?: number;
84
+ /** Milliseconds taken to fetch/compute this value — used by XFetch probabilistic early expiration. */
85
+ delta?: number;
82
86
  }
83
87
  /** Returned by SmartMemoryCache.get() — distinguishes "cached null" from a real miss */
84
88
  interface CacheHit {
85
89
  value: unknown;
86
90
  /** true = past soft TTL (staleAt) but within hard expiry → SWR path */
87
91
  isStale: boolean;
92
+ /** Hard expiry timestamp — lets CacheService.get() do refresh-ahead / XFetch math
93
+ * without a second Map lookup (eliminates the duplicate l1.getEntry() call). */
94
+ expiresAt: number;
95
+ /** Original TTL in ms stored at write time — for refresh-ahead fraction calculation */
96
+ ttlMs?: number;
97
+ /** Fetch duration in ms stored at write time — for XFetch probabilistic threshold */
98
+ delta?: number;
88
99
  }
89
100
  /** On-disk entry shape (mirrors SmartCacheEntry — Uint8Array accepted for msgpack round-trips;
90
101
  * legacy disk files written by older versions may have a JSON string in data) */
@@ -388,6 +399,13 @@ interface CacheOptions {
388
399
  * Default: `0` (disabled — TTLs are stored exactly as given).
389
400
  */
390
401
  ttlJitterFactor?: number;
402
+ /**
403
+ * Default TTL in seconds for `null` or `undefined` results from `fetchFn`.
404
+ * Caches negative results so a non-existent key (deleted user, bad ID) does not
405
+ * hit the DB on every request. Can be overridden per-call via `get(..., { notFoundTtl }).
406
+ * Default: `0` (disabled — null/undefined uses the normal TTL).
407
+ */
408
+ notFoundTtl?: number;
391
409
  /**
392
410
  * Number of consecutive Redis errors before the circuit opens (stops
393
411
  * attempting Redis until the cooldown elapses).
@@ -400,6 +418,12 @@ interface CacheOptions {
400
418
  * Default: `30 000` ms (30 s).
401
419
  */
402
420
  l2CircuitBreakerCooldownMs?: number;
421
+ /**
422
+ * Redis key pattern to automatically warm L1 from at startup (e.g. `'user:*'`).
423
+ * `cache.ready()` returns a Promise that resolves once this warm-up completes.
424
+ * No-op when Redis is disabled or unreachable — safe to set unconditionally.
425
+ */
426
+ warmKeys?: string;
403
427
  }
404
428
 
405
429
  /**
@@ -435,10 +459,16 @@ declare class CacheService {
435
459
  private readonly _l1Counters;
436
460
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
437
461
  private readonly tagIndex;
462
+ /**
463
+ * Dependency index: source glob pattern → Set of namespaced dependent keys.
464
+ * When an exact-key delete matches a registered pattern, all dependents are cascaded.
465
+ */
466
+ private readonly dependencyIndex;
438
467
  private redis;
439
468
  private redisConnecting;
440
469
  private readonly cb;
441
470
  private snapshotLoaded;
471
+ private _readyPromise;
442
472
  private cleanupInterval;
443
473
  private oomInterval;
444
474
  private metricsInterval;
@@ -495,19 +525,31 @@ declare class CacheService {
495
525
  * @param cacheKey - Unique key identifying this value
496
526
  * @param fetchFn - Called on a cache miss; its return value is cached and returned
497
527
  * @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
498
- * @param opts.priority - Override the auto-inferred eviction priority
499
- * @param opts.swr - Stale-While-Revalidate grace seconds. When > 0 the entry stays
500
- * alive for this many extra seconds after TTL; callers get stale data
501
- * instantly while a background refresh runs. Default: 0 (disabled).
528
+ * @param opts.priority - Override the auto-inferred eviction priority
529
+ * @param opts.swr - Stale-While-Revalidate grace seconds.
530
+ * @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
531
+ * is triggered proactively while the caller still receives the
532
+ * cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
533
+ * Requires `fetchFn` to be stable across calls.
534
+ * @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
535
+ * recompute more aggressively before expiry. Typical range: 0.5–2.
536
+ * Complementary to refreshAhead — uses recompute cost (delta) to
537
+ * decide probabilistically rather than at a fixed threshold.
538
+ * @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
539
+ * Caches negative lookups to avoid repeated DB hits for missing keys.
502
540
  */
503
541
  get<T>(cacheKey: string, fetchFn: () => Promise<T>, ttlSeconds?: number, opts?: {
504
542
  priority?: CachePriority;
505
543
  swr?: number;
544
+ refreshAhead?: number;
545
+ xfetchBeta?: number;
546
+ notFoundTtl?: number;
506
547
  }): Promise<T>;
507
548
  private _revalidate;
508
549
  /** Explicitly write a value into L1 (+ L2 in production). */
509
550
  set<T>(cacheKey: string, data: T, ttlSeconds?: number, priority?: CachePriority, opts?: {
510
551
  tags?: string[];
552
+ dependsOn?: string[];
511
553
  }): Promise<void>;
512
554
  /**
513
555
  * Delete one key or a glob pattern (supports `*` wildcard).
@@ -592,9 +634,22 @@ declare class CacheService {
592
634
  *
593
635
  * @param keys - Array of cache keys.
594
636
  * @param fetchFn - Called with only the keys that missed L1.
595
- * @param ttl - TTL in seconds for newly fetched values.
637
+ * @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
638
+ * `(key) => number` so heterogeneous TTLs can be batched in one call.
639
+ */
640
+ mget<T>(keys: string[], fetchFn: (missKeys: string[]) => Promise<Record<string, T>>, ttl?: number | ((key: string) => number), priority?: CachePriority): Promise<(T | undefined)[]>;
641
+ /**
642
+ * Returns a Promise that resolves once the cache is fully initialised and any
643
+ * startup warming configured via `warmKeys` has completed.
644
+ *
645
+ * Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once
646
+ * `warmFromL2(warmKeys)` finishes — ideal for k8s readiness probes.
647
+ *
648
+ * @example
649
+ * const cache = CacheService.create({ warmKeys: 'user:*' });
650
+ * await cache.ready(); // gate traffic until warm
596
651
  */
597
- mget<T>(keys: string[], fetchFn: (missKeys: string[]) => Promise<Record<string, T>>, ttl?: number, priority?: CachePriority): Promise<(T | undefined)[]>;
652
+ ready(): Promise<void>;
598
653
  /**
599
654
  * Batch write — set multiple entries in a single call.
600
655
  * TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
@@ -610,6 +665,7 @@ declare class CacheService {
610
665
  ttl?: number;
611
666
  priority?: CachePriority;
612
667
  tags?: string[];
668
+ dependsOn?: string[];
613
669
  }>): Promise<void>;
614
670
  /**
615
671
  * Batch delete — delete multiple exact keys in a single call.
@@ -680,6 +736,48 @@ declare class CacheService {
680
736
  maxKB: number;
681
737
  };
682
738
  };
739
+ /**
740
+ * Write `value` only if the key is not already cached.
741
+ * Returns `true` if the write happened, `false` if the key already existed.
742
+ *
743
+ * When Redis is available, atomicity is guaranteed via `SET NX EX` so this
744
+ * is safe to use for idempotency keys and "first writer wins" patterns across
745
+ * multiple instances. L1 is populated on success.
746
+ *
747
+ * @example
748
+ * const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
749
+ * if (!claimed) return res.status(409).json({ error: 'duplicate request' });
750
+ */
751
+ setIfAbsent<T>(cacheKey: string, value: T, ttlSeconds?: number, priority?: CachePriority): Promise<boolean>;
752
+ /**
753
+ * Return the top-N live L1 keys by historical access frequency.
754
+ * Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
755
+ * whose historical frequency exceeds their current in-memory hit count.
756
+ *
757
+ * Useful for diagnosing what is driving L1 pressure without any extra data
758
+ * collection overhead.
759
+ *
760
+ * @param n - Maximum number of keys to return. Default: 10.
761
+ *
762
+ * @example
763
+ * cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
764
+ * console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
765
+ */
766
+ hotKeys(n?: number): Array<{
767
+ key: string;
768
+ hits: number;
769
+ sizeBytes: number;
770
+ }>;
771
+ /**
772
+ * Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
773
+ * pattern that may contain `*` wildcards).
774
+ */
775
+ private _matchesGlob;
776
+ /**
777
+ * When an exact key `deletedKey` is removed, cascade to every dependent key
778
+ * that was registered via `dependsOn` and whose source pattern matches.
779
+ */
780
+ private _cascadeDependencies;
683
781
  /** Return a full metrics snapshot. */
684
782
  metrics(): CacheMetrics;
685
783
  /**
@@ -846,7 +944,7 @@ declare class SmartMemoryCache {
846
944
  private maybeRebuildBloom;
847
945
  private smartEvict;
848
946
  get(key: string): CacheHit | null;
849
- set(key: string, data: unknown, ttlMs: number, priority?: CachePriority, staleAt?: number): void;
947
+ set(key: string, data: unknown, ttlMs: number, priority?: CachePriority, staleAt?: number, delta?: number): void;
850
948
  delete(key: string): boolean;
851
949
  private keysMatchingPattern;
852
950
  deletePattern(pattern: string): number;
@@ -946,6 +1044,18 @@ declare class SmartMemoryCache {
946
1044
  bitsSet: number;
947
1045
  fillFactor: number;
948
1046
  };
1047
+ /**
1048
+ * Return the top-N live L1 keys by historical access frequency (Count-Min Sketch estimate).
1049
+ * Includes evicted-then-readmitted keys whose sketch frequency exceeds their current hit count.
1050
+ * Useful for diagnosing which keys are driving cache pressure.
1051
+ *
1052
+ * @param n - Maximum number of entries to return. Default: 10.
1053
+ */
1054
+ hotKeys(n: number): Array<{
1055
+ key: string;
1056
+ hits: number;
1057
+ sizeBytes: number;
1058
+ }>;
949
1059
  }
950
1060
 
951
1061
  /**