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.
@@ -33,6 +33,8 @@ import {
33
33
  CacheMetrics,
34
34
  CachePingResult,
35
35
  ILogger,
36
+ ICacheTracer,
37
+ ICacheSpan,
36
38
  consoleLogger,
37
39
  } from './types';
38
40
  import { CacheEncryption } from './encryption';
@@ -55,6 +57,57 @@ const DEFAULT_CATEGORY_LIMITS: Record<string, CategoryLimit> = {
55
57
 
56
58
  const DEFAULT_FORBIDDEN_PREFIXES = ['auth:', 'session:', 'mfa:', 'rate_limit:'] as const;
57
59
 
60
+ // ─────────────────────────────────────────────────────────────────────────────
61
+ // Circuit breaker — three-state (CLOSED → OPEN → HALF_OPEN) for L2 Redis
62
+ // ─────────────────────────────────────────────────────────────────────────────
63
+
64
+ const enum CBState { CLOSED, OPEN, HALF_OPEN }
65
+
66
+ class L2CircuitBreaker {
67
+ private state = CBState.CLOSED;
68
+ private failures = 0;
69
+ private openedAt = 0;
70
+ constructor(
71
+ private readonly threshold: number,
72
+ private readonly cooldownMs: number,
73
+ ) {}
74
+
75
+ /** Call before each Redis attempt. Returns false when the circuit is open. */
76
+ isAllowed(): boolean {
77
+ if (this.state === CBState.CLOSED) return true;
78
+ if (this.state === CBState.HALF_OPEN) return true; // one probe allowed
79
+ // OPEN: check if cooldown elapsed
80
+ if (Date.now() - this.openedAt >= this.cooldownMs) {
81
+ this.state = CBState.HALF_OPEN;
82
+ return true; // probe
83
+ }
84
+ return false;
85
+ }
86
+
87
+ /** Call on Redis success. */
88
+ onSuccess(): void {
89
+ this.failures = 0;
90
+ this.state = CBState.CLOSED;
91
+ }
92
+
93
+ /** Call on Redis failure. */
94
+ onFailure(): void {
95
+ this.failures++;
96
+ if (this.state === CBState.HALF_OPEN || this.failures >= this.threshold) {
97
+ this.state = CBState.OPEN;
98
+ this.openedAt = Date.now();
99
+ this.failures = 0;
100
+ }
101
+ }
102
+
103
+ get isOpen(): boolean { return this.state === CBState.OPEN; }
104
+ get currentState(): 'closed' | 'open' | 'half_open' {
105
+ return this.state === CBState.CLOSED ? 'closed'
106
+ : this.state === CBState.OPEN ? 'open'
107
+ : 'half_open';
108
+ }
109
+ }
110
+
58
111
  // ─────────────────────────────────────────────────────────────────────────────
59
112
  // Priority inference — override by passing priority explicitly to get()
60
113
  // ─────────────────────────────────────────────────────────────────────────────
@@ -94,6 +147,9 @@ export class CacheService {
94
147
  staleIfError: number;
95
148
  l2WriteMode: 'read-write' | 'read-only';
96
149
  instanceName: string;
150
+ ttlJitterFactor: number;
151
+ tracer: ICacheTracer | undefined;
152
+ notFoundTtl: number;
97
153
  };
98
154
  /** Pre-computed once — opts.namespace never changes after construction. */
99
155
  private readonly _namespace: string;
@@ -104,8 +160,14 @@ export class CacheService {
104
160
  private readonly _l1Counters = new Map<string, { value: number; expiresAt: number }>();
105
161
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
106
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>>();
107
168
  private redis: RedisClient | null = null;
108
169
  private redisConnecting: Promise<RedisClient> | null = null;
170
+ private readonly cb: L2CircuitBreaker;
109
171
  private snapshotLoaded = false;
110
172
  private cleanupInterval: ReturnType<typeof setInterval> | null = null;
111
173
  private oomInterval: ReturnType<typeof setInterval> | null = null;
@@ -190,8 +252,16 @@ export class CacheService {
190
252
  staleIfError: options.staleIfError ?? 0,
191
253
  l2WriteMode: options.l2WriteMode ?? 'read-write',
192
254
  instanceName: options.instanceName ?? '',
255
+ ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
256
+ tracer: options.tracer,
257
+ notFoundTtl: options.notFoundTtl ?? 0,
193
258
  };
194
259
 
260
+ // Circuit breaker for L2 Redis
261
+ const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
262
+ const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 30_000;
263
+ this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
264
+
195
265
  // L1.5 disk tier
196
266
  this.disk = new DiskTier({
197
267
  dir: this.opts.diskCacheDir,
@@ -328,6 +398,19 @@ export class CacheService {
328
398
  return this._namespace ? `${this._namespace}:${key}` : key;
329
399
  }
330
400
 
401
+ /** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
402
+ private _jitterTtl(ttlMs: number): number {
403
+ const j = this.opts.ttlJitterFactor;
404
+ if (j === 0) return ttlMs;
405
+ return Math.round(ttlMs * (1 + (Math.random() * 2 - 1) * j));
406
+ }
407
+
408
+ /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
409
+ private _startSpan(name: string): ICacheSpan {
410
+ if (this.opts.tracer) return this.opts.tracer.startSpan(name);
411
+ return { setAttribute() { return this; }, setStatus() { return this; }, end() {} };
412
+ }
413
+
331
414
  private initBackplane(): void {
332
415
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
333
416
  if (this.subClient) return;
@@ -401,7 +484,7 @@ export class CacheService {
401
484
  }
402
485
 
403
486
  private async getRedis(): Promise<RedisClient> {
404
- if (this.redis?.status === 'ready') return this.redis as RedisClient;
487
+ if (!this.cb.isAllowed()) throw new Error('tricache: L2 circuit breaker is open');
405
488
  if (this.redisConnecting) return this.redisConnecting;
406
489
 
407
490
  this.redisConnecting = (async () => {
@@ -429,10 +512,12 @@ export class CacheService {
429
512
  setTimeout(() => reject(new Error('Redis connection timeout')), 15_000);
430
513
  });
431
514
 
515
+ this.cb.onSuccess();
432
516
  this.redis = client;
433
517
  this.redisConnecting = null;
434
518
  return client;
435
519
  } catch (err) {
520
+ this.cb.onFailure();
436
521
  this.redisConnecting = null; // allow retry on next call — fixes the cached-rejection bug
437
522
  throw err;
438
523
  }
@@ -524,25 +609,37 @@ export class CacheService {
524
609
  * @param cacheKey - Unique key identifying this value
525
610
  * @param fetchFn - Called on a cache miss; its return value is cached and returned
526
611
  * @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
527
- * @param opts.priority - Override the auto-inferred eviction priority
528
- * @param opts.swr - Stale-While-Revalidate grace seconds. When > 0 the entry stays
529
- * alive for this many extra seconds after TTL; callers get stale data
530
- * 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.
531
624
  */
532
625
  async get<T>(
533
626
  cacheKey: string,
534
627
  fetchFn: () => Promise<T>,
535
628
  ttlSeconds: number = 300,
536
629
  opts: {
537
- priority?: CachePriority;
538
- 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
539
635
  } = {},
540
636
  ): Promise<T> {
637
+ const span = this._startSpan('tricache.get');
638
+ span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
541
639
  const k = this.nk(cacheKey); // namespaced key used for all storage
542
640
  this.counters.gets++;
543
641
 
544
- // L1: in-memory (fastest path — defer inferPriority / ttlMs until we confirm a miss;
545
- // inferPriority runs 3 regex tests that are wasted work on every warm hit)
642
+ // L1: in-memory (fastest path)
546
643
  const l1Hit = this.l1.get(k);
547
644
  if (l1Hit !== null) {
548
645
  if (l1Hit.isStale) {
@@ -558,29 +655,61 @@ export class CacheService {
558
655
  }
559
656
  } else {
560
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
+ }
561
686
  }
562
687
  this.counters.l1Hits++;
688
+ span.setAttribute('cache.hit', 'l1').end();
563
689
  return l1Hit.value as T;
564
690
  }
565
691
 
566
- const ttlMs = ttlSeconds * 1_000;
692
+ const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
567
693
  const swrGraceMs = (opts.swr ?? 0) * 1_000;
568
- const priority = opts.priority ?? inferPriority(cacheKey); // original key for correct prefix inference
694
+ const priority = opts.priority ?? inferPriority(cacheKey);
569
695
 
570
696
  // L2: Redis (distributed, production-only by default)
571
697
  if (!this._redisDisabled) {
572
698
  try {
573
699
  const client = await this.getRedis();
574
700
  const raw = await client.get(k);
701
+ this.cb.onSuccess();
575
702
  if (raw) {
576
703
  const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
577
704
  const parsed = JSON.parse(decrypted) as T;
578
705
  this.l1.set(k, parsed, ttlMs, priority);
579
706
  this.counters.l2Hits++;
580
707
  this.logger.debug('L2 hit (Redis)', { cacheKey });
708
+ span.setAttribute('cache.hit', 'l2').end();
581
709
  return parsed;
582
710
  }
583
711
  } catch (err) {
712
+ this.cb.onFailure();
584
713
  this.logger.debug('Redis unavailable, continuing to fetch', { cacheKey, error: (err as Error).message });
585
714
  }
586
715
  }
@@ -597,36 +726,49 @@ export class CacheService {
597
726
  if (l1Check !== null) {
598
727
  this.counters.diskHits++;
599
728
  this.logger.debug('L1.5 hit (disk → L1)', { cacheKey });
729
+ span.setAttribute('cache.hit', 'disk').end();
600
730
  return l1Check.value as T;
601
731
  }
602
732
  }
603
733
  }
604
734
 
735
+ span.setAttribute('cache.hit', 'miss');
736
+
605
737
  // Cache MISS: thundering-herd prevention
606
738
  const existing = this.inflight.get(k);
607
739
  if (existing) {
608
740
  this.counters.stampedes++;
609
741
  this.logger.debug('Stampede prevented — coalescing onto inflight fetch', { cacheKey });
742
+ span.end();
610
743
  return existing as Promise<T>;
611
744
  }
612
745
 
613
746
  const fetchPromise: Promise<T> = (async () => {
614
747
  try {
615
748
  this.counters.fetches++;
616
- const data = await fetchFn();
617
- const staleAt = swrGraceMs > 0 ? Date.now() + ttlMs : undefined;
618
- const storeTtl = swrGraceMs > 0 ? ttlMs + swrGraceMs : ttlMs;
749
+ const fetchStart = Date.now();
750
+ const data = await fetchFn();
751
+ const delta = Date.now() - fetchStart;
752
+
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;
619
756
 
620
- this.l1.set(k, data, storeTtl, priority, staleAt);
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);
621
761
 
622
762
  if (!this._redisDisabled) {
623
763
  try {
624
764
  const client = await this.getRedis();
625
765
  const serialized = JSON.stringify(data);
626
766
  const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
627
- await client.setex(k, ttlSeconds, toStore);
767
+ await client.setex(k, Math.ceil(effectiveTtl / 1_000), toStore);
768
+ this.cb.onSuccess();
628
769
  this.logger.debug('Cached L1+L2', { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
629
770
  } catch {
771
+ this.cb.onFailure();
630
772
  this.logger.debug('Cached L1 only (Redis unavailable)', { cacheKey });
631
773
  }
632
774
  } else {
@@ -636,6 +778,7 @@ export class CacheService {
636
778
  return data;
637
779
  } finally {
638
780
  this.inflight.delete(k);
781
+ span.end();
639
782
  }
640
783
  })();
641
784
 
@@ -651,9 +794,11 @@ export class CacheService {
651
794
  priority: CachePriority,
652
795
  ): Promise<void> {
653
796
  try {
654
- const data = await fetchFn();
655
- const staleAt = Date.now() + ttlMs;
656
- 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);
657
802
 
658
803
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
659
804
  try {
@@ -682,8 +827,10 @@ export class CacheService {
682
827
  // ── Explicit set / delete ─────────────────────────────────────────────────
683
828
 
684
829
  /** Explicitly write a value into L1 (+ L2 in production). */
685
- async set<T>(cacheKey: string, data: T, ttlSeconds = 300, priority?: CachePriority, opts?: { tags?: string[] }): Promise<void> {
686
- const ttlMs = ttlSeconds * 1_000;
830
+ async set<T>(cacheKey: string, data: T, ttlSeconds = 300, priority?: CachePriority, opts?: { tags?: string[]; dependsOn?: string[] }): Promise<void> {
831
+ const span = this._startSpan('tricache.set');
832
+ span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
833
+ const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
687
834
  const p = priority ?? inferPriority(cacheKey);
688
835
  const k = this.nk(cacheKey);
689
836
  this.counters.sets++;
@@ -704,10 +851,22 @@ export class CacheService {
704
851
  for (const tag of opts.tags) {
705
852
  const tagKey = this.nk(`_tag_:${tag}`);
706
853
  pl.sadd(tagKey, k);
707
- pl.expire(tagKey, ttlSeconds + 3_600); // keep tag set alive longer than entries
854
+ pl.expire(tagKey, ttlSeconds + 3_600);
708
855
  }
709
856
  await pl.exec();
710
- } catch { /* tags are best-effort */ }
857
+ this.cb.onSuccess();
858
+ } catch { this.cb.onFailure(); /* tags are best-effort */ }
859
+ }
860
+ }
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);
711
870
  }
712
871
  }
713
872
 
@@ -716,13 +875,16 @@ export class CacheService {
716
875
  const client = await this.getRedis();
717
876
  const s = JSON.stringify(data);
718
877
  const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
719
- await client.setex(k, ttlSeconds, stored);
878
+ await client.setex(k, Math.ceil(ttlMs / 1_000), stored);
879
+ this.cb.onSuccess();
720
880
  } catch (err) {
881
+ this.cb.onFailure();
721
882
  this.logger.debug('set: Redis unavailable', { cacheKey, error: (err as Error).message });
722
883
  }
723
884
  }
724
885
 
725
886
  void this.publishInvalidation('del', k);
887
+ span.end();
726
888
  }
727
889
 
728
890
  /**
@@ -733,8 +895,10 @@ export class CacheService {
733
895
  * await cache.delete('user:abc:*'); // all keys for user abc
734
896
  */
735
897
  async delete(cacheKey: string): Promise<void> {
898
+ const span = this._startSpan('tricache.delete');
899
+ span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
736
900
  const isPattern = cacheKey.includes('*');
737
- const k = this.nk(cacheKey); // namespace-scoped key / pattern
901
+ const k = this.nk(cacheKey);
738
902
  this.counters.deletes++;
739
903
 
740
904
  if (isPattern) {
@@ -742,6 +906,10 @@ export class CacheService {
742
906
  } else {
743
907
  this.l1.delete(k);
744
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);
745
913
  }
746
914
 
747
915
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
@@ -759,12 +927,15 @@ export class CacheService {
759
927
  } else {
760
928
  await client.del(k);
761
929
  }
930
+ this.cb.onSuccess();
762
931
  } catch (err) {
932
+ this.cb.onFailure();
763
933
  this.logger.debug('delete: Redis unavailable', { cacheKey, error: (err as Error).message });
764
934
  }
765
935
  }
766
936
 
767
937
  void this.publishInvalidation(isPattern ? 'del-glob' : 'del', k);
938
+ span.end();
768
939
  }
769
940
 
770
941
  // ── Counter (distributed rate limiting) ──────────────────────────────────
@@ -993,6 +1164,104 @@ export class CacheService {
993
1164
  return result;
994
1165
  }
995
1166
 
1167
+ /**
1168
+ * Batch write — set multiple entries in a single call.
1169
+ * TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
1170
+ *
1171
+ * @example
1172
+ * await cache.mset({
1173
+ * 'user:1': { value: { name: 'Alice' }, ttl: 300 },
1174
+ * 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
1175
+ * });
1176
+ */
1177
+ async mset<T = unknown>(
1178
+ entries: Record<string, { value: T; ttl?: number; priority?: CachePriority; tags?: string[]; dependsOn?: string[] }>,
1179
+ ): Promise<void> {
1180
+ const keys = Object.keys(entries);
1181
+ await Promise.all(keys.map(key => {
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);
1185
+ }));
1186
+ }
1187
+
1188
+ /**
1189
+ * Batch delete — delete multiple exact keys in a single call.
1190
+ * Glob patterns are not supported; use `delete('prefix:*')` for patterns.
1191
+ *
1192
+ * @example
1193
+ * await cache.mdel(['user:1', 'user:2', 'user:3']);
1194
+ */
1195
+ async mdel(keys: string[]): Promise<void> {
1196
+ await Promise.all(keys.map(k => this.delete(k)));
1197
+ }
1198
+
1199
+ /**
1200
+ * Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
1201
+ * pulling them into L1. Useful on startup to eliminate cold-start penalty when
1202
+ * the local snapshot is unavailable or too stale.
1203
+ *
1204
+ * Returns the number of keys loaded into L1.
1205
+ *
1206
+ * @example
1207
+ * // In your startup hook (e.g. ECS task, k8s readiness probe):
1208
+ * const loaded = await cache.warmFromL2('org:*');
1209
+ * console.log(`Warmed ${loaded} keys from Redis`);
1210
+ */
1211
+ async warmFromL2(pattern: string): Promise<number> {
1212
+ if (this._redisDisabled) return 0;
1213
+ try {
1214
+ const client = await this.getRedis();
1215
+ const nsPattern = this.nk(pattern);
1216
+
1217
+ // Collect all matching keys via SCAN
1218
+ const matchedKeys: string[] = [];
1219
+ const stream = client.scanStream({ match: nsPattern, count: 100 });
1220
+ await new Promise<void>((resolve, reject) => {
1221
+ stream.on('data', (chunk: string[]) => matchedKeys.push(...chunk));
1222
+ stream.on('end', resolve);
1223
+ stream.on('error', reject);
1224
+ });
1225
+
1226
+ if (matchedKeys.length === 0) {
1227
+ this.cb.onSuccess();
1228
+ return 0;
1229
+ }
1230
+
1231
+ // Fetch values in a pipeline and load into L1
1232
+ const pl = client.pipeline();
1233
+ for (const k of matchedKeys) pl.get(k);
1234
+ const results = await pl.exec() as Array<[Error | null, string | null]>;
1235
+ this.cb.onSuccess();
1236
+
1237
+ let loaded = 0;
1238
+ const now = Date.now();
1239
+ for (let i = 0; i < matchedKeys.length; i++) {
1240
+ const [err, raw] = results[i];
1241
+ if (err || raw == null) continue;
1242
+ try {
1243
+ const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
1244
+ const parsed = JSON.parse(decrypted) as unknown;
1245
+ // Use a 10-minute TTL as a reasonable default; the real TTL is not
1246
+ // returned by GET (use PTTL to be precise, but that doubles round-trips).
1247
+ const remainingMs = 10 * 60 * 1_000;
1248
+ this.l1.set(matchedKeys[i], parsed, remainingMs, inferPriority(matchedKeys[i]));
1249
+ loaded++;
1250
+ } catch { /* skip malformed entries */ }
1251
+ }
1252
+ void now; // suppress unused warning
1253
+
1254
+ this.logger.info('warmFromL2 complete', {
1255
+ pattern, matched: matchedKeys.length, loaded,
1256
+ });
1257
+ return loaded;
1258
+ } catch (err) {
1259
+ this.cb.onFailure();
1260
+ this.logger.debug('warmFromL2: Redis unavailable', { error: (err as Error).message });
1261
+ return 0;
1262
+ }
1263
+ }
1264
+
996
1265
  /**
997
1266
  * Invalidate all keys associated with a tag.
998
1267
  * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
@@ -1099,6 +1368,107 @@ export class CacheService {
1099
1368
  };
1100
1369
  }
1101
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
+
1102
1472
  // ── Observability ──────────────────────────────────────────────────────────────────
1103
1473
 
1104
1474
  /** Return a full metrics snapshot. */
@@ -1147,6 +1517,10 @@ export class CacheService {
1147
1517
  skipped: c.invSkipped,
1148
1518
  },
1149
1519
 
1520
+ l2CircuitBreaker: {
1521
+ state: this.cb.currentState,
1522
+ },
1523
+
1150
1524
  oom: {
1151
1525
  enabled: this.opts.oomProtection,
1152
1526
  evictions: c.oomEvictions,
package/src/index.ts CHANGED
@@ -35,4 +35,6 @@ export {
35
35
  type CacheHit,
36
36
  type EvictionReason,
37
37
  type CachePingResult,
38
+ type ICacheTracer,
39
+ type ICacheSpan,
38
40
  } from './types';