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.
@@ -149,6 +149,7 @@ export class CacheService {
149
149
  instanceName: string;
150
150
  ttlJitterFactor: number;
151
151
  tracer: ICacheTracer | undefined;
152
+ notFoundTtl: number;
152
153
  };
153
154
  /** Pre-computed once — opts.namespace never changes after construction. */
154
155
  private readonly _namespace: string;
@@ -159,6 +160,11 @@ export class CacheService {
159
160
  private readonly _l1Counters = new Map<string, { value: number; expiresAt: number }>();
160
161
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
161
162
  private readonly tagIndex = new Map<string, Set<string>>();
163
+ /**
164
+ * Dependency index: source glob pattern → Set of namespaced dependent keys.
165
+ * When an exact-key delete matches a registered pattern, all dependents are cascaded.
166
+ */
167
+ private readonly dependencyIndex = new Map<string, Set<string>>();
162
168
  private redis: RedisClient | null = null;
163
169
  private redisConnecting: Promise<RedisClient> | null = null;
164
170
  private readonly cb: L2CircuitBreaker;
@@ -248,6 +254,7 @@ export class CacheService {
248
254
  instanceName: options.instanceName ?? '',
249
255
  ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
250
256
  tracer: options.tracer,
257
+ notFoundTtl: options.notFoundTtl ?? 0,
251
258
  };
252
259
 
253
260
  // Circuit breaker for L2 Redis
@@ -602,18 +609,29 @@ export class CacheService {
602
609
  * @param cacheKey - Unique key identifying this value
603
610
  * @param fetchFn - Called on a cache miss; its return value is cached and returned
604
611
  * @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
605
- * @param opts.priority - Override the auto-inferred eviction priority
606
- * @param opts.swr - Stale-While-Revalidate grace seconds. When > 0 the entry stays
607
- * alive for this many extra seconds after TTL; callers get stale data
608
- * instantly while a background refresh runs. Default: 0 (disabled).
612
+ * @param opts.priority - Override the auto-inferred eviction priority
613
+ * @param opts.swr - Stale-While-Revalidate grace seconds.
614
+ * @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
615
+ * is triggered proactively while the caller still receives the
616
+ * cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
617
+ * Requires `fetchFn` to be stable across calls.
618
+ * @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
619
+ * recompute more aggressively before expiry. Typical range: 0.5–2.
620
+ * Complementary to refreshAhead — uses recompute cost (delta) to
621
+ * decide probabilistically rather than at a fixed threshold.
622
+ * @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
623
+ * Caches negative lookups to avoid repeated DB hits for missing keys.
609
624
  */
610
625
  async get<T>(
611
626
  cacheKey: string,
612
627
  fetchFn: () => Promise<T>,
613
628
  ttlSeconds: number = 300,
614
629
  opts: {
615
- priority?: CachePriority;
616
- swr?: number; // Stale-While-Revalidate grace period in seconds
630
+ priority?: CachePriority;
631
+ swr?: number;
632
+ refreshAhead?: number; // 0–1: trigger background recompute at this fraction of TTL elapsed
633
+ xfetchBeta?: number; // > 0: XFetch probabilistic early expiration (uses stored delta)
634
+ notFoundTtl?: number; // seconds; cache null/undefined results with this TTL instead
617
635
  } = {},
618
636
  ): Promise<T> {
619
637
  const span = this._startSpan('tricache.get');
@@ -637,6 +655,34 @@ export class CacheService {
637
655
  }
638
656
  } else {
639
657
  this.logger.debug('L1 hit');
658
+ // Refresh-ahead and XFetch: proactively recompute a fresh entry before it expires.
659
+ // l1Hit already carries expiresAt/ttlMs/delta — no second Map lookup needed.
660
+ if (!this.revalidating.has(k) && (opts.refreshAhead || opts.xfetchBeta)) {
661
+ const now = Date.now();
662
+ const remaining = l1Hit.expiresAt - now;
663
+ const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1_000;
664
+ const priority = opts.priority ?? inferPriority(cacheKey);
665
+
666
+ const shouldRefreshAhead = opts.refreshAhead != null && opts.refreshAhead > 0
667
+ ? remaining <= entryTtl * (1 - opts.refreshAhead)
668
+ : false;
669
+
670
+ // XFetch: fire with probability proportional to recompute cost (delta) vs. remaining TTL
671
+ // Formula: fire when remaining <= delta * beta * -ln(U), U ~ uniform(0,1)
672
+ const shouldXFetch = opts.xfetchBeta != null && opts.xfetchBeta > 0 && l1Hit.delta != null
673
+ ? remaining <= l1Hit.delta * opts.xfetchBeta * -Math.log(Math.random())
674
+ : false;
675
+
676
+ if (shouldRefreshAhead || shouldXFetch) {
677
+ this.revalidating.add(k);
678
+ void this._revalidate(k, fetchFn, entryTtl, (opts.swr ?? 0) * 1_000, priority);
679
+ this.counters.swrRevalidations++;
680
+ this.logger.debug(
681
+ shouldXFetch ? 'XFetch: proactive background recompute' : 'Refresh-ahead: proactive background recompute',
682
+ { cacheKey, remainingMs: remaining, ttlMs: entryTtl },
683
+ );
684
+ }
685
+ }
640
686
  }
641
687
  this.counters.l1Hits++;
642
688
  span.setAttribute('cache.hit', 'l1').end();
@@ -700,18 +746,25 @@ export class CacheService {
700
746
  const fetchPromise: Promise<T> = (async () => {
701
747
  try {
702
748
  this.counters.fetches++;
703
- const data = await fetchFn();
704
- const staleAt = swrGraceMs > 0 ? Date.now() + ttlMs : undefined;
705
- const storeTtl = swrGraceMs > 0 ? ttlMs + swrGraceMs : ttlMs;
749
+ const fetchStart = Date.now();
750
+ const data = await fetchFn();
751
+ const delta = Date.now() - fetchStart;
706
752
 
707
- this.l1.set(k, data, storeTtl, priority, staleAt);
753
+ // Negative caching: null/undefined results get their own (shorter) TTL
754
+ const notFoundTtlMs = (opts.notFoundTtl ?? this.opts.notFoundTtl) * 1_000;
755
+ const effectiveTtl = (data == null && notFoundTtlMs > 0) ? notFoundTtlMs : ttlMs;
756
+
757
+ const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : undefined;
758
+ const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
759
+
760
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta);
708
761
 
709
762
  if (!this._redisDisabled) {
710
763
  try {
711
764
  const client = await this.getRedis();
712
765
  const serialized = JSON.stringify(data);
713
766
  const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
714
- await client.setex(k, Math.ceil(ttlMs / 1_000), toStore);
767
+ await client.setex(k, Math.ceil(effectiveTtl / 1_000), toStore);
715
768
  this.cb.onSuccess();
716
769
  this.logger.debug('Cached L1+L2', { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
717
770
  } catch {
@@ -741,9 +794,11 @@ export class CacheService {
741
794
  priority: CachePriority,
742
795
  ): Promise<void> {
743
796
  try {
744
- const data = await fetchFn();
745
- const staleAt = Date.now() + ttlMs;
746
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt);
797
+ const fetchStart = Date.now();
798
+ const data = await fetchFn();
799
+ const delta = Date.now() - fetchStart;
800
+ const staleAt = Date.now() + ttlMs;
801
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta);
747
802
 
748
803
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
749
804
  try {
@@ -772,7 +827,7 @@ export class CacheService {
772
827
  // ── Explicit set / delete ─────────────────────────────────────────────────
773
828
 
774
829
  /** Explicitly write a value into L1 (+ L2 in production). */
775
- async set<T>(cacheKey: string, data: T, ttlSeconds = 300, priority?: CachePriority, opts?: { tags?: string[] }): Promise<void> {
830
+ async set<T>(cacheKey: string, data: T, ttlSeconds = 300, priority?: CachePriority, opts?: { tags?: string[]; dependsOn?: string[] }): Promise<void> {
776
831
  const span = this._startSpan('tricache.set');
777
832
  span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
778
833
  const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
@@ -804,6 +859,17 @@ export class CacheService {
804
859
  }
805
860
  }
806
861
 
862
+ // Register dependency patterns: when any key matching a pattern is deleted,
863
+ // this key (k) is automatically cascaded.
864
+ if (opts?.dependsOn?.length) {
865
+ for (const pattern of opts.dependsOn) {
866
+ const nsPattern = this.nk(pattern);
867
+ let deps = this.dependencyIndex.get(nsPattern);
868
+ if (!deps) { deps = new Set(); this.dependencyIndex.set(nsPattern, deps); }
869
+ deps.add(k);
870
+ }
871
+ }
872
+
807
873
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
808
874
  try {
809
875
  const client = await this.getRedis();
@@ -840,6 +906,10 @@ export class CacheService {
840
906
  } else {
841
907
  this.l1.delete(k);
842
908
  this.disk.delete(k);
909
+ // Cascade: invalidate any key that declared it depends on this exact key's pattern
910
+ this._cascadeDependencies(k);
911
+ // Clean up: remove k from all dependency registrations (it is gone)
912
+ for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
843
913
  }
844
914
 
845
915
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
@@ -1105,12 +1175,13 @@ export class CacheService {
1105
1175
  * });
1106
1176
  */
1107
1177
  async mset<T = unknown>(
1108
- entries: Record<string, { value: T; ttl?: number; priority?: CachePriority; tags?: string[] }>,
1178
+ entries: Record<string, { value: T; ttl?: number; priority?: CachePriority; tags?: string[]; dependsOn?: string[] }>,
1109
1179
  ): Promise<void> {
1110
1180
  const keys = Object.keys(entries);
1111
1181
  await Promise.all(keys.map(key => {
1112
- const { value, ttl = 300, priority, tags } = entries[key];
1113
- return this.set(key, value, ttl, priority, tags ? { tags } : undefined);
1182
+ const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
1183
+ const hasOpts = tags?.length || dependsOn?.length;
1184
+ return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : undefined);
1114
1185
  }));
1115
1186
  }
1116
1187
 
@@ -1297,6 +1368,107 @@ export class CacheService {
1297
1368
  };
1298
1369
  }
1299
1370
 
1371
+ // ── Conditional write ─────────────────────────────────────────────────
1372
+
1373
+ /**
1374
+ * Write `value` only if the key is not already cached.
1375
+ * Returns `true` if the write happened, `false` if the key already existed.
1376
+ *
1377
+ * When Redis is available, atomicity is guaranteed via `SET NX EX` so this
1378
+ * is safe to use for idempotency keys and "first writer wins" patterns across
1379
+ * multiple instances. L1 is populated on success.
1380
+ *
1381
+ * @example
1382
+ * const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
1383
+ * if (!claimed) return res.status(409).json({ error: 'duplicate request' });
1384
+ */
1385
+ async setIfAbsent<T>(cacheKey: string, value: T, ttlSeconds = 300, priority?: CachePriority): Promise<boolean> {
1386
+ const k = this.nk(cacheKey);
1387
+
1388
+ // Fast path: L1 check (process-local, no network hop)
1389
+ if (this.l1.has(k)) return false;
1390
+
1391
+ if (!this._redisDisabled) {
1392
+ try {
1393
+ const client = await this.getRedis();
1394
+ const serialized = JSON.stringify(value);
1395
+ const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
1396
+ // SET key value EX ttl NX — atomic; returns 'OK' on success, null if key exists
1397
+ const result = await client.set(k, toStore, 'EX', ttlSeconds, 'NX');
1398
+ this.cb.onSuccess();
1399
+ if (result === null) return false; // already exists in Redis
1400
+ } catch (err) {
1401
+ this.cb.onFailure();
1402
+ this.logger.debug('setIfAbsent: Redis unavailable, falling back to L1 check', { cacheKey, error: (err as Error).message });
1403
+ // Re-check L1 after Redis failure — another thread may have won the race
1404
+ if (this.l1.has(k)) return false;
1405
+ }
1406
+ }
1407
+
1408
+ const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
1409
+ const p = priority ?? inferPriority(cacheKey);
1410
+ this.l1.set(k, value, ttlMs, p);
1411
+ this.counters.sets++;
1412
+ return true;
1413
+ }
1414
+
1415
+ // ── Hot key introspection ─────────────────────────────────────────────
1416
+
1417
+ /**
1418
+ * Return the top-N live L1 keys by historical access frequency.
1419
+ * Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
1420
+ * whose historical frequency exceeds their current in-memory hit count.
1421
+ *
1422
+ * Useful for diagnosing what is driving L1 pressure without any extra data
1423
+ * collection overhead.
1424
+ *
1425
+ * @param n - Maximum number of keys to return. Default: 10.
1426
+ *
1427
+ * @example
1428
+ * cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
1429
+ * console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
1430
+ */
1431
+ hotKeys(n = 10): Array<{ key: string; hits: number; sizeBytes: number }> {
1432
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
1433
+ return this.l1.hotKeys(n).map(({ key, hits, sizeBytes }) => ({
1434
+ key: prefixLen > 0 ? key.slice(prefixLen) : key,
1435
+ hits,
1436
+ sizeBytes,
1437
+ }));
1438
+ }
1439
+
1440
+ // ── Dependency cascade helpers ────────────────────────────────────────
1441
+
1442
+ /**
1443
+ * Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
1444
+ * pattern that may contain `*` wildcards).
1445
+ */
1446
+ private _matchesGlob(key: string, pattern: string): boolean {
1447
+ if (!pattern.includes('*')) return key === pattern;
1448
+ const re = new RegExp('^' + pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*') + '$');
1449
+ return re.test(key);
1450
+ }
1451
+
1452
+ /**
1453
+ * When an exact key `deletedKey` is removed, cascade to every dependent key
1454
+ * that was registered via `dependsOn` and whose source pattern matches.
1455
+ */
1456
+ private _cascadeDependencies(deletedKey: string): void {
1457
+ for (const [pattern, dependents] of this.dependencyIndex) {
1458
+ if (!this._matchesGlob(deletedKey, pattern)) continue;
1459
+ for (const dep of dependents) {
1460
+ if (dep === deletedKey) continue; // no self-cascade
1461
+ this.l1.delete(dep);
1462
+ this.disk.delete(dep);
1463
+ void this.publishInvalidation('del', dep);
1464
+ this.logger.debug('Dependency cascade: invalidated dependent key', {
1465
+ trigger: deletedKey.slice(0, 60), dependent: dep.slice(0, 60),
1466
+ });
1467
+ }
1468
+ }
1469
+ }
1470
+
1471
+
1300
1472
  // ── Observability ──────────────────────────────────────────────────────────────────
1301
1473
 
1302
1474
  /** Return a full metrics snapshot. */
@@ -391,7 +391,7 @@ export class SmartMemoryCache {
391
391
  // skipping unpack. Falls back to decode for entries restored from disk/snapshot.
392
392
  const value = entry.value !== undefined ? entry.value : unpack(entry.data as Buffer);
393
393
  const isStale = entry.staleAt !== undefined && now > entry.staleAt;
394
- return { value, isStale };
394
+ return { value, isStale, expiresAt: entry.expiresAt, ttlMs: entry.ttlMs, delta: entry.delta };
395
395
  }
396
396
 
397
397
  set(
@@ -400,6 +400,7 @@ export class SmartMemoryCache {
400
400
  ttlMs: number,
401
401
  priority: CachePriority = 2 /* NORMAL */,
402
402
  staleAt?: number,
403
+ delta?: number,
403
404
  ): void {
404
405
  // Single serialization pass — always msgpackr. Eliminates the prior JSON.stringify
405
406
  // "size probe" that was discarded for large payloads (the double-pass).
@@ -427,7 +428,7 @@ export class SmartMemoryCache {
427
428
  this.ensureCapacity(cat, size);
428
429
 
429
430
  const now = Date.now();
430
- this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority });
431
+ this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta });
431
432
  this.bloom.add(key);
432
433
  this.maybeRebuildBloom();
433
434
  this.totalSize += size;
@@ -729,4 +730,22 @@ export class SmartMemoryCache {
729
730
 
730
731
  bloomMightContain(key: string): boolean { return this.bloom.mightContain(key); }
731
732
  bloomStats() { return this.bloom.stats; }
733
+
734
+ /**
735
+ * Return the top-N live L1 keys by historical access frequency (Count-Min Sketch estimate).
736
+ * Includes evicted-then-readmitted keys whose sketch frequency exceeds their current hit count.
737
+ * Useful for diagnosing which keys are driving cache pressure.
738
+ *
739
+ * @param n - Maximum number of entries to return. Default: 10.
740
+ */
741
+ hotKeys(n: number): Array<{ key: string; hits: number; sizeBytes: number }> {
742
+ const now = Date.now();
743
+ const out: Array<{ key: string; hits: number; sizeBytes: number }> = [];
744
+ for (const [key, entry] of this.cache) {
745
+ if (entry.expiresAt <= now) continue;
746
+ out.push({ key, hits: this.sketch.estimate(key), sizeBytes: entry.size });
747
+ }
748
+ out.sort((a, b) => b.hits - a.hits);
749
+ return out.slice(0, n);
750
+ }
732
751
  }
package/src/types.ts CHANGED
@@ -101,6 +101,10 @@ export interface SmartCacheEntry {
101
101
  lastAccess: number;
102
102
  /** Eviction priority */
103
103
  priority: CachePriority;
104
+ /** Original TTL in ms at write time — used by refresh-ahead to compute the proactive refresh threshold. */
105
+ ttlMs?: number;
106
+ /** Milliseconds taken to fetch/compute this value — used by XFetch probabilistic early expiration. */
107
+ delta?: number;
104
108
  }
105
109
 
106
110
  /** Returned by SmartMemoryCache.get() — distinguishes "cached null" from a real miss */
@@ -108,6 +112,13 @@ export interface CacheHit {
108
112
  value: unknown;
109
113
  /** true = past soft TTL (staleAt) but within hard expiry → SWR path */
110
114
  isStale: boolean;
115
+ /** Hard expiry timestamp — lets CacheService.get() do refresh-ahead / XFetch math
116
+ * without a second Map lookup (eliminates the duplicate l1.getEntry() call). */
117
+ expiresAt: number;
118
+ /** Original TTL in ms stored at write time — for refresh-ahead fraction calculation */
119
+ ttlMs?: number;
120
+ /** Fetch duration in ms stored at write time — for XFetch probabilistic threshold */
121
+ delta?: number;
111
122
  }
112
123
 
113
124
  // ─── Disk tier ───────────────────────────────────────────────────────────────
@@ -441,6 +452,14 @@ export interface CacheOptions {
441
452
  ttlJitterFactor?: number;
442
453
 
443
454
  // ── L2 circuit breaker ─────────────────────────────────────────────────────
455
+ /**
456
+ * Default TTL in seconds for `null` or `undefined` results from `fetchFn`.
457
+ * Caches negative results so a non-existent key (deleted user, bad ID) does not
458
+ * hit the DB on every request. Can be overridden per-call via `get(..., { notFoundTtl }).
459
+ * Default: `0` (disabled — null/undefined uses the normal TTL).
460
+ */
461
+ notFoundTtl?: number;
462
+
444
463
  /**
445
464
  * Number of consecutive Redis errors before the circuit opens (stops
446
465
  * attempting Redis until the cooldown elapses).