tricache 0.3.1 → 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.d.ts 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).
@@ -435,6 +453,11 @@ declare class CacheService {
435
453
  private readonly _l1Counters;
436
454
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
437
455
  private readonly tagIndex;
456
+ /**
457
+ * Dependency index: source glob pattern → Set of namespaced dependent keys.
458
+ * When an exact-key delete matches a registered pattern, all dependents are cascaded.
459
+ */
460
+ private readonly dependencyIndex;
438
461
  private redis;
439
462
  private redisConnecting;
440
463
  private readonly cb;
@@ -495,19 +518,31 @@ declare class CacheService {
495
518
  * @param cacheKey - Unique key identifying this value
496
519
  * @param fetchFn - Called on a cache miss; its return value is cached and returned
497
520
  * @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).
521
+ * @param opts.priority - Override the auto-inferred eviction priority
522
+ * @param opts.swr - Stale-While-Revalidate grace seconds.
523
+ * @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
524
+ * is triggered proactively while the caller still receives the
525
+ * cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
526
+ * Requires `fetchFn` to be stable across calls.
527
+ * @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
528
+ * recompute more aggressively before expiry. Typical range: 0.5–2.
529
+ * Complementary to refreshAhead — uses recompute cost (delta) to
530
+ * decide probabilistically rather than at a fixed threshold.
531
+ * @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
532
+ * Caches negative lookups to avoid repeated DB hits for missing keys.
502
533
  */
503
534
  get<T>(cacheKey: string, fetchFn: () => Promise<T>, ttlSeconds?: number, opts?: {
504
535
  priority?: CachePriority;
505
536
  swr?: number;
537
+ refreshAhead?: number;
538
+ xfetchBeta?: number;
539
+ notFoundTtl?: number;
506
540
  }): Promise<T>;
507
541
  private _revalidate;
508
542
  /** Explicitly write a value into L1 (+ L2 in production). */
509
543
  set<T>(cacheKey: string, data: T, ttlSeconds?: number, priority?: CachePriority, opts?: {
510
544
  tags?: string[];
545
+ dependsOn?: string[];
511
546
  }): Promise<void>;
512
547
  /**
513
548
  * Delete one key or a glob pattern (supports `*` wildcard).
@@ -610,6 +645,7 @@ declare class CacheService {
610
645
  ttl?: number;
611
646
  priority?: CachePriority;
612
647
  tags?: string[];
648
+ dependsOn?: string[];
613
649
  }>): Promise<void>;
614
650
  /**
615
651
  * Batch delete — delete multiple exact keys in a single call.
@@ -680,6 +716,48 @@ declare class CacheService {
680
716
  maxKB: number;
681
717
  };
682
718
  };
719
+ /**
720
+ * Write `value` only if the key is not already cached.
721
+ * Returns `true` if the write happened, `false` if the key already existed.
722
+ *
723
+ * When Redis is available, atomicity is guaranteed via `SET NX EX` so this
724
+ * is safe to use for idempotency keys and "first writer wins" patterns across
725
+ * multiple instances. L1 is populated on success.
726
+ *
727
+ * @example
728
+ * const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
729
+ * if (!claimed) return res.status(409).json({ error: 'duplicate request' });
730
+ */
731
+ setIfAbsent<T>(cacheKey: string, value: T, ttlSeconds?: number, priority?: CachePriority): Promise<boolean>;
732
+ /**
733
+ * Return the top-N live L1 keys by historical access frequency.
734
+ * Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
735
+ * whose historical frequency exceeds their current in-memory hit count.
736
+ *
737
+ * Useful for diagnosing what is driving L1 pressure without any extra data
738
+ * collection overhead.
739
+ *
740
+ * @param n - Maximum number of keys to return. Default: 10.
741
+ *
742
+ * @example
743
+ * cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
744
+ * console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
745
+ */
746
+ hotKeys(n?: number): Array<{
747
+ key: string;
748
+ hits: number;
749
+ sizeBytes: number;
750
+ }>;
751
+ /**
752
+ * Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
753
+ * pattern that may contain `*` wildcards).
754
+ */
755
+ private _matchesGlob;
756
+ /**
757
+ * When an exact key `deletedKey` is removed, cascade to every dependent key
758
+ * that was registered via `dependsOn` and whose source pattern matches.
759
+ */
760
+ private _cascadeDependencies;
683
761
  /** Return a full metrics snapshot. */
684
762
  metrics(): CacheMetrics;
685
763
  /**
@@ -846,7 +924,7 @@ declare class SmartMemoryCache {
846
924
  private maybeRebuildBloom;
847
925
  private smartEvict;
848
926
  get(key: string): CacheHit | null;
849
- set(key: string, data: unknown, ttlMs: number, priority?: CachePriority, staleAt?: number): void;
927
+ set(key: string, data: unknown, ttlMs: number, priority?: CachePriority, staleAt?: number, delta?: number): void;
850
928
  delete(key: string): boolean;
851
929
  private keysMatchingPattern;
852
930
  deletePattern(pattern: string): number;
@@ -946,6 +1024,18 @@ declare class SmartMemoryCache {
946
1024
  bitsSet: number;
947
1025
  fillFactor: number;
948
1026
  };
1027
+ /**
1028
+ * Return the top-N live L1 keys by historical access frequency (Count-Min Sketch estimate).
1029
+ * Includes evicted-then-readmitted keys whose sketch frequency exceeds their current hit count.
1030
+ * Useful for diagnosing which keys are driving cache pressure.
1031
+ *
1032
+ * @param n - Maximum number of entries to return. Default: 10.
1033
+ */
1034
+ hotKeys(n: number): Array<{
1035
+ key: string;
1036
+ hits: number;
1037
+ sizeBytes: number;
1038
+ }>;
949
1039
  }
950
1040
 
951
1041
  /**
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
@@ -1387,6 +1404,11 @@ var CacheService = class _CacheService {
1387
1404
  _l1Counters = /* @__PURE__ */ new Map();
1388
1405
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
1389
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();
1390
1412
  redis = null;
1391
1413
  redisConnecting = null;
1392
1414
  cb;
@@ -1466,7 +1488,8 @@ var CacheService = class _CacheService {
1466
1488
  l2WriteMode: options.l2WriteMode ?? "read-write",
1467
1489
  instanceName: options.instanceName ?? "",
1468
1490
  ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
1469
- tracer: options.tracer
1491
+ tracer: options.tracer,
1492
+ notFoundTtl: options.notFoundTtl ?? 0
1470
1493
  };
1471
1494
  const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
1472
1495
  const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
@@ -1778,10 +1801,18 @@ var CacheService = class _CacheService {
1778
1801
  * @param cacheKey - Unique key identifying this value
1779
1802
  * @param fetchFn - Called on a cache miss; its return value is cached and returned
1780
1803
  * @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
1781
- * @param opts.priority - Override the auto-inferred eviction priority
1782
- * @param opts.swr - Stale-While-Revalidate grace seconds. When > 0 the entry stays
1783
- * alive for this many extra seconds after TTL; callers get stale data
1784
- * 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.
1785
1816
  */
1786
1817
  async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
1787
1818
  const span = this._startSpan("tricache.get");
@@ -1803,6 +1834,23 @@ var CacheService = class _CacheService {
1803
1834
  }
1804
1835
  } else {
1805
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
+ }
1806
1854
  }
1807
1855
  this.counters.l1Hits++;
1808
1856
  span.setAttribute("cache.hit", "l1").end();
@@ -1857,16 +1905,20 @@ var CacheService = class _CacheService {
1857
1905
  const fetchPromise = (async () => {
1858
1906
  try {
1859
1907
  this.counters.fetches++;
1908
+ const fetchStart = Date.now();
1860
1909
  const data = await fetchFn();
1861
- const staleAt = swrGraceMs > 0 ? Date.now() + ttlMs : void 0;
1862
- const storeTtl = swrGraceMs > 0 ? ttlMs + swrGraceMs : ttlMs;
1863
- 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);
1864
1916
  if (!this._redisDisabled) {
1865
1917
  try {
1866
1918
  const client = await this.getRedis();
1867
1919
  const serialized = JSON.stringify(data);
1868
1920
  const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
1869
- await client.setex(k, Math.ceil(ttlMs / 1e3), toStore);
1921
+ await client.setex(k, Math.ceil(effectiveTtl / 1e3), toStore);
1870
1922
  this.cb.onSuccess();
1871
1923
  this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
1872
1924
  } catch {
@@ -1887,9 +1939,11 @@ var CacheService = class _CacheService {
1887
1939
  }
1888
1940
  async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
1889
1941
  try {
1942
+ const fetchStart = Date.now();
1890
1943
  const data = await fetchFn();
1944
+ const delta = Date.now() - fetchStart;
1891
1945
  const staleAt = Date.now() + ttlMs;
1892
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt);
1946
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta);
1893
1947
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
1894
1948
  try {
1895
1949
  const client = await this.getRedis();
@@ -1951,6 +2005,17 @@ var CacheService = class _CacheService {
1951
2005
  }
1952
2006
  }
1953
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
+ }
1954
2019
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
1955
2020
  try {
1956
2021
  const client = await this.getRedis();
@@ -1984,6 +2049,8 @@ var CacheService = class _CacheService {
1984
2049
  } else {
1985
2050
  this.l1.delete(k);
1986
2051
  this.disk.delete(k);
2052
+ this._cascadeDependencies(k);
2053
+ for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
1987
2054
  }
1988
2055
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
1989
2056
  try {
@@ -2219,8 +2286,9 @@ var CacheService = class _CacheService {
2219
2286
  async mset(entries) {
2220
2287
  const keys = Object.keys(entries);
2221
2288
  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);
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);
2224
2292
  }));
2225
2293
  }
2226
2294
  /**
@@ -2385,6 +2453,94 @@ var CacheService = class _CacheService {
2385
2453
  disk: this.disk.stats
2386
2454
  };
2387
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
+ }
2388
2544
  // ── Observability ──────────────────────────────────────────────────────────────────
2389
2545
  /** Return a full metrics snapshot. */
2390
2546
  metrics() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tricache",
3
- "version": "0.3.1",
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",