tricache 0.3.0 → 0.3.1

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,8 @@ 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;
97
152
  };
98
153
  /** Pre-computed once — opts.namespace never changes after construction. */
99
154
  private readonly _namespace: string;
@@ -106,6 +161,7 @@ export class CacheService {
106
161
  private readonly tagIndex = new Map<string, Set<string>>();
107
162
  private redis: RedisClient | null = null;
108
163
  private redisConnecting: Promise<RedisClient> | null = null;
164
+ private readonly cb: L2CircuitBreaker;
109
165
  private snapshotLoaded = false;
110
166
  private cleanupInterval: ReturnType<typeof setInterval> | null = null;
111
167
  private oomInterval: ReturnType<typeof setInterval> | null = null;
@@ -190,8 +246,15 @@ export class CacheService {
190
246
  staleIfError: options.staleIfError ?? 0,
191
247
  l2WriteMode: options.l2WriteMode ?? 'read-write',
192
248
  instanceName: options.instanceName ?? '',
249
+ ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
250
+ tracer: options.tracer,
193
251
  };
194
252
 
253
+ // Circuit breaker for L2 Redis
254
+ const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
255
+ const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 30_000;
256
+ this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
257
+
195
258
  // L1.5 disk tier
196
259
  this.disk = new DiskTier({
197
260
  dir: this.opts.diskCacheDir,
@@ -328,6 +391,19 @@ export class CacheService {
328
391
  return this._namespace ? `${this._namespace}:${key}` : key;
329
392
  }
330
393
 
394
+ /** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
395
+ private _jitterTtl(ttlMs: number): number {
396
+ const j = this.opts.ttlJitterFactor;
397
+ if (j === 0) return ttlMs;
398
+ return Math.round(ttlMs * (1 + (Math.random() * 2 - 1) * j));
399
+ }
400
+
401
+ /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
402
+ private _startSpan(name: string): ICacheSpan {
403
+ if (this.opts.tracer) return this.opts.tracer.startSpan(name);
404
+ return { setAttribute() { return this; }, setStatus() { return this; }, end() {} };
405
+ }
406
+
331
407
  private initBackplane(): void {
332
408
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
333
409
  if (this.subClient) return;
@@ -401,7 +477,7 @@ export class CacheService {
401
477
  }
402
478
 
403
479
  private async getRedis(): Promise<RedisClient> {
404
- if (this.redis?.status === 'ready') return this.redis as RedisClient;
480
+ if (!this.cb.isAllowed()) throw new Error('tricache: L2 circuit breaker is open');
405
481
  if (this.redisConnecting) return this.redisConnecting;
406
482
 
407
483
  this.redisConnecting = (async () => {
@@ -429,10 +505,12 @@ export class CacheService {
429
505
  setTimeout(() => reject(new Error('Redis connection timeout')), 15_000);
430
506
  });
431
507
 
508
+ this.cb.onSuccess();
432
509
  this.redis = client;
433
510
  this.redisConnecting = null;
434
511
  return client;
435
512
  } catch (err) {
513
+ this.cb.onFailure();
436
514
  this.redisConnecting = null; // allow retry on next call — fixes the cached-rejection bug
437
515
  throw err;
438
516
  }
@@ -538,11 +616,12 @@ export class CacheService {
538
616
  swr?: number; // Stale-While-Revalidate grace period in seconds
539
617
  } = {},
540
618
  ): Promise<T> {
619
+ const span = this._startSpan('tricache.get');
620
+ span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
541
621
  const k = this.nk(cacheKey); // namespaced key used for all storage
542
622
  this.counters.gets++;
543
623
 
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)
624
+ // L1: in-memory (fastest path)
546
625
  const l1Hit = this.l1.get(k);
547
626
  if (l1Hit !== null) {
548
627
  if (l1Hit.isStale) {
@@ -560,27 +639,31 @@ export class CacheService {
560
639
  this.logger.debug('L1 hit');
561
640
  }
562
641
  this.counters.l1Hits++;
642
+ span.setAttribute('cache.hit', 'l1').end();
563
643
  return l1Hit.value as T;
564
644
  }
565
645
 
566
- const ttlMs = ttlSeconds * 1_000;
646
+ const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
567
647
  const swrGraceMs = (opts.swr ?? 0) * 1_000;
568
- const priority = opts.priority ?? inferPriority(cacheKey); // original key for correct prefix inference
648
+ const priority = opts.priority ?? inferPriority(cacheKey);
569
649
 
570
650
  // L2: Redis (distributed, production-only by default)
571
651
  if (!this._redisDisabled) {
572
652
  try {
573
653
  const client = await this.getRedis();
574
654
  const raw = await client.get(k);
655
+ this.cb.onSuccess();
575
656
  if (raw) {
576
657
  const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
577
658
  const parsed = JSON.parse(decrypted) as T;
578
659
  this.l1.set(k, parsed, ttlMs, priority);
579
660
  this.counters.l2Hits++;
580
661
  this.logger.debug('L2 hit (Redis)', { cacheKey });
662
+ span.setAttribute('cache.hit', 'l2').end();
581
663
  return parsed;
582
664
  }
583
665
  } catch (err) {
666
+ this.cb.onFailure();
584
667
  this.logger.debug('Redis unavailable, continuing to fetch', { cacheKey, error: (err as Error).message });
585
668
  }
586
669
  }
@@ -597,16 +680,20 @@ export class CacheService {
597
680
  if (l1Check !== null) {
598
681
  this.counters.diskHits++;
599
682
  this.logger.debug('L1.5 hit (disk → L1)', { cacheKey });
683
+ span.setAttribute('cache.hit', 'disk').end();
600
684
  return l1Check.value as T;
601
685
  }
602
686
  }
603
687
  }
604
688
 
689
+ span.setAttribute('cache.hit', 'miss');
690
+
605
691
  // Cache MISS: thundering-herd prevention
606
692
  const existing = this.inflight.get(k);
607
693
  if (existing) {
608
694
  this.counters.stampedes++;
609
695
  this.logger.debug('Stampede prevented — coalescing onto inflight fetch', { cacheKey });
696
+ span.end();
610
697
  return existing as Promise<T>;
611
698
  }
612
699
 
@@ -624,9 +711,11 @@ export class CacheService {
624
711
  const client = await this.getRedis();
625
712
  const serialized = JSON.stringify(data);
626
713
  const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
627
- await client.setex(k, ttlSeconds, toStore);
714
+ await client.setex(k, Math.ceil(ttlMs / 1_000), toStore);
715
+ this.cb.onSuccess();
628
716
  this.logger.debug('Cached L1+L2', { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
629
717
  } catch {
718
+ this.cb.onFailure();
630
719
  this.logger.debug('Cached L1 only (Redis unavailable)', { cacheKey });
631
720
  }
632
721
  } else {
@@ -636,6 +725,7 @@ export class CacheService {
636
725
  return data;
637
726
  } finally {
638
727
  this.inflight.delete(k);
728
+ span.end();
639
729
  }
640
730
  })();
641
731
 
@@ -683,7 +773,9 @@ export class CacheService {
683
773
 
684
774
  /** Explicitly write a value into L1 (+ L2 in production). */
685
775
  async set<T>(cacheKey: string, data: T, ttlSeconds = 300, priority?: CachePriority, opts?: { tags?: string[] }): Promise<void> {
686
- const ttlMs = ttlSeconds * 1_000;
776
+ const span = this._startSpan('tricache.set');
777
+ span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
778
+ const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
687
779
  const p = priority ?? inferPriority(cacheKey);
688
780
  const k = this.nk(cacheKey);
689
781
  this.counters.sets++;
@@ -704,10 +796,11 @@ export class CacheService {
704
796
  for (const tag of opts.tags) {
705
797
  const tagKey = this.nk(`_tag_:${tag}`);
706
798
  pl.sadd(tagKey, k);
707
- pl.expire(tagKey, ttlSeconds + 3_600); // keep tag set alive longer than entries
799
+ pl.expire(tagKey, ttlSeconds + 3_600);
708
800
  }
709
801
  await pl.exec();
710
- } catch { /* tags are best-effort */ }
802
+ this.cb.onSuccess();
803
+ } catch { this.cb.onFailure(); /* tags are best-effort */ }
711
804
  }
712
805
  }
713
806
 
@@ -716,13 +809,16 @@ export class CacheService {
716
809
  const client = await this.getRedis();
717
810
  const s = JSON.stringify(data);
718
811
  const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
719
- await client.setex(k, ttlSeconds, stored);
812
+ await client.setex(k, Math.ceil(ttlMs / 1_000), stored);
813
+ this.cb.onSuccess();
720
814
  } catch (err) {
815
+ this.cb.onFailure();
721
816
  this.logger.debug('set: Redis unavailable', { cacheKey, error: (err as Error).message });
722
817
  }
723
818
  }
724
819
 
725
820
  void this.publishInvalidation('del', k);
821
+ span.end();
726
822
  }
727
823
 
728
824
  /**
@@ -733,8 +829,10 @@ export class CacheService {
733
829
  * await cache.delete('user:abc:*'); // all keys for user abc
734
830
  */
735
831
  async delete(cacheKey: string): Promise<void> {
832
+ const span = this._startSpan('tricache.delete');
833
+ span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
736
834
  const isPattern = cacheKey.includes('*');
737
- const k = this.nk(cacheKey); // namespace-scoped key / pattern
835
+ const k = this.nk(cacheKey);
738
836
  this.counters.deletes++;
739
837
 
740
838
  if (isPattern) {
@@ -759,12 +857,15 @@ export class CacheService {
759
857
  } else {
760
858
  await client.del(k);
761
859
  }
860
+ this.cb.onSuccess();
762
861
  } catch (err) {
862
+ this.cb.onFailure();
763
863
  this.logger.debug('delete: Redis unavailable', { cacheKey, error: (err as Error).message });
764
864
  }
765
865
  }
766
866
 
767
867
  void this.publishInvalidation(isPattern ? 'del-glob' : 'del', k);
868
+ span.end();
768
869
  }
769
870
 
770
871
  // ── Counter (distributed rate limiting) ──────────────────────────────────
@@ -993,6 +1094,103 @@ export class CacheService {
993
1094
  return result;
994
1095
  }
995
1096
 
1097
+ /**
1098
+ * Batch write — set multiple entries in a single call.
1099
+ * TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
1100
+ *
1101
+ * @example
1102
+ * await cache.mset({
1103
+ * 'user:1': { value: { name: 'Alice' }, ttl: 300 },
1104
+ * 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
1105
+ * });
1106
+ */
1107
+ async mset<T = unknown>(
1108
+ entries: Record<string, { value: T; ttl?: number; priority?: CachePriority; tags?: string[] }>,
1109
+ ): Promise<void> {
1110
+ const keys = Object.keys(entries);
1111
+ 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);
1114
+ }));
1115
+ }
1116
+
1117
+ /**
1118
+ * Batch delete — delete multiple exact keys in a single call.
1119
+ * Glob patterns are not supported; use `delete('prefix:*')` for patterns.
1120
+ *
1121
+ * @example
1122
+ * await cache.mdel(['user:1', 'user:2', 'user:3']);
1123
+ */
1124
+ async mdel(keys: string[]): Promise<void> {
1125
+ await Promise.all(keys.map(k => this.delete(k)));
1126
+ }
1127
+
1128
+ /**
1129
+ * Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
1130
+ * pulling them into L1. Useful on startup to eliminate cold-start penalty when
1131
+ * the local snapshot is unavailable or too stale.
1132
+ *
1133
+ * Returns the number of keys loaded into L1.
1134
+ *
1135
+ * @example
1136
+ * // In your startup hook (e.g. ECS task, k8s readiness probe):
1137
+ * const loaded = await cache.warmFromL2('org:*');
1138
+ * console.log(`Warmed ${loaded} keys from Redis`);
1139
+ */
1140
+ async warmFromL2(pattern: string): Promise<number> {
1141
+ if (this._redisDisabled) return 0;
1142
+ try {
1143
+ const client = await this.getRedis();
1144
+ const nsPattern = this.nk(pattern);
1145
+
1146
+ // Collect all matching keys via SCAN
1147
+ const matchedKeys: string[] = [];
1148
+ const stream = client.scanStream({ match: nsPattern, count: 100 });
1149
+ await new Promise<void>((resolve, reject) => {
1150
+ stream.on('data', (chunk: string[]) => matchedKeys.push(...chunk));
1151
+ stream.on('end', resolve);
1152
+ stream.on('error', reject);
1153
+ });
1154
+
1155
+ if (matchedKeys.length === 0) {
1156
+ this.cb.onSuccess();
1157
+ return 0;
1158
+ }
1159
+
1160
+ // Fetch values in a pipeline and load into L1
1161
+ const pl = client.pipeline();
1162
+ for (const k of matchedKeys) pl.get(k);
1163
+ const results = await pl.exec() as Array<[Error | null, string | null]>;
1164
+ this.cb.onSuccess();
1165
+
1166
+ let loaded = 0;
1167
+ const now = Date.now();
1168
+ for (let i = 0; i < matchedKeys.length; i++) {
1169
+ const [err, raw] = results[i];
1170
+ if (err || raw == null) continue;
1171
+ try {
1172
+ const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
1173
+ const parsed = JSON.parse(decrypted) as unknown;
1174
+ // Use a 10-minute TTL as a reasonable default; the real TTL is not
1175
+ // returned by GET (use PTTL to be precise, but that doubles round-trips).
1176
+ const remainingMs = 10 * 60 * 1_000;
1177
+ this.l1.set(matchedKeys[i], parsed, remainingMs, inferPriority(matchedKeys[i]));
1178
+ loaded++;
1179
+ } catch { /* skip malformed entries */ }
1180
+ }
1181
+ void now; // suppress unused warning
1182
+
1183
+ this.logger.info('warmFromL2 complete', {
1184
+ pattern, matched: matchedKeys.length, loaded,
1185
+ });
1186
+ return loaded;
1187
+ } catch (err) {
1188
+ this.cb.onFailure();
1189
+ this.logger.debug('warmFromL2: Redis unavailable', { error: (err as Error).message });
1190
+ return 0;
1191
+ }
1192
+ }
1193
+
996
1194
  /**
997
1195
  * Invalidate all keys associated with a tag.
998
1196
  * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
@@ -1147,6 +1345,10 @@ export class CacheService {
1147
1345
  skipped: c.invSkipped,
1148
1346
  },
1149
1347
 
1348
+ l2CircuitBreaker: {
1349
+ state: this.cb.currentState,
1350
+ },
1351
+
1150
1352
  oom: {
1151
1353
  enabled: this.opts.oomProtection,
1152
1354
  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';
package/src/types.ts CHANGED
@@ -4,6 +4,25 @@
4
4
 
5
5
  // ─── Logger ─────────────────────────────────────────────────────────────────
6
6
 
7
+ // ─── OpenTelemetry tracer interface ──────────────────────────────────────────
8
+
9
+ /**
10
+ * Minimal span interface — structurally compatible with `@opentelemetry/api` Span.
11
+ * Pass your existing OTEL tracer; no extra package required.
12
+ */
13
+ export interface ICacheSpan {
14
+ setAttribute(key: string, value: string | number | boolean): this;
15
+ setStatus(status: { code: 0 | 1 | 2; message?: string }): this;
16
+ end(): void;
17
+ }
18
+
19
+ /**
20
+ * Minimal tracer interface — structurally compatible with `@opentelemetry/api` Tracer.
21
+ */
22
+ export interface ICacheTracer {
23
+ startSpan(name: string): ICacheSpan;
24
+ }
25
+
7
26
  /** Minimal logger interface — plug in any logger (pino, winston, console, etc.) */
8
27
  export interface ILogger {
9
28
  debug(msg: string, meta?: Record<string, unknown>): void;
@@ -172,6 +191,12 @@ export interface CacheMetrics {
172
191
  skipped: number;
173
192
  };
174
193
 
194
+ /** L2 Redis circuit breaker state */
195
+ l2CircuitBreaker: {
196
+ /** `'closed'` = normal; `'open'` = Redis paused; `'half_open'` = probing recovery */
197
+ state: 'closed' | 'open' | 'half_open';
198
+ };
199
+
175
200
  /** OOM guard statistics */
176
201
  oom: {
177
202
  enabled: boolean;
@@ -388,4 +413,44 @@ export interface CacheOptions {
388
413
  onMetrics?: (metrics: CacheMetrics) => void;
389
414
  /** How often the `onMetrics` callback fires (ms). Default: 60 000 ms */
390
415
  metricsIntervalMs?: number;
416
+
417
+ /**
418
+ * OpenTelemetry-compatible tracer. When provided, `get()`, `set()`, and
419
+ * `delete()` are each wrapped in a span with attributes:
420
+ * - `cache.hit` — `'l1' | 'disk' | 'l2' | 'miss'`
421
+ * - `cache.key_prefix` — first path segment of the key (e.g. `'user'`)
422
+ *
423
+ * Pass your existing `@opentelemetry/api` Tracer directly — no extra
424
+ * dependency required; the interface is structurally compatible.
425
+ *
426
+ * @example
427
+ * import { trace } from '@opentelemetry/api';
428
+ * tracer: trace.getTracer('tricache')
429
+ */
430
+ tracer?: ICacheTracer;
431
+
432
+ // ── TTL jitter ─────────────────────────────────────────────────────────────
433
+ /**
434
+ * Randomise every stored TTL by ± `ttlJitterFactor × ttl` seconds.
435
+ * Prevents thundering-herd cache stampedes when thousands of entries share
436
+ * the same TTL and expire simultaneously.
437
+ *
438
+ * A factor of `0.15` spreads a 300 s TTL uniformly over [255 s, 345 s].
439
+ * Default: `0` (disabled — TTLs are stored exactly as given).
440
+ */
441
+ ttlJitterFactor?: number;
442
+
443
+ // ── L2 circuit breaker ─────────────────────────────────────────────────────
444
+ /**
445
+ * Number of consecutive Redis errors before the circuit opens (stops
446
+ * attempting Redis until the cooldown elapses).
447
+ * Default: `5`.
448
+ */
449
+ l2CircuitBreakerThreshold?: number;
450
+ /**
451
+ * Milliseconds the circuit stays open before transitioning to half-open
452
+ * (allows a single probe request to test recovery).
453
+ * Default: `30 000` ms (30 s).
454
+ */
455
+ l2CircuitBreakerCooldownMs?: number;
391
456
  }