tricache 0.2.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;
@@ -348,23 +424,7 @@ export class CacheService {
348
424
  this.logger.debug('Backplane subscriber error', { error: e.message }));
349
425
 
350
426
  sub.on('message', (_channel: string, message: string) => {
351
- try {
352
- const msg = JSON.parse(message) as { op: 'del' | 'del-glob'; key: string; src: string };
353
- if (msg.src === this.instanceId) {
354
- this.counters.invSkipped++;
355
- return; // own message — our L1 is already current
356
- }
357
- this.counters.invReceived++;
358
- if (msg.op === 'del') {
359
- this.l1.delete(msg.key);
360
- this.disk.delete(msg.key);
361
- } else if (msg.op === 'del-glob') {
362
- this.l1.deletePattern(msg.key);
363
- }
364
- this.logger.debug('Backplane: peer invalidation applied', {
365
- op: msg.op, key: msg.key.slice(0, 60),
366
- });
367
- } catch { /* malformed message — ignore */ }
427
+ this._handleBackplaneMessage(message);
368
428
  });
369
429
 
370
430
  sub.subscribe(this.backplaneChannel)
@@ -378,6 +438,32 @@ export class CacheService {
378
438
  this.subClient = sub;
379
439
  }
380
440
 
441
+ /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
442
+ _handleBackplaneMessage(message: string): void {
443
+ try {
444
+ const msg = JSON.parse(message) as { op: 'del' | 'del-glob'; key: string; src: string };
445
+ if (msg.src === this.instanceId) {
446
+ this.counters.invSkipped++;
447
+ return; // own message — our L1 is already current
448
+ }
449
+ this.counters.invReceived++;
450
+ if (msg.op === 'del') {
451
+ // L1 eviction is synchronous and O(1); disk delete is deferred via
452
+ // setImmediate so the event-loop tick that processes this pub/sub
453
+ // message returns immediately without blocking hot get() calls.
454
+ this.l1.delete(msg.key);
455
+ setImmediate(() => this.disk.delete(msg.key));
456
+ } else if (msg.op === 'del-glob') {
457
+ // Glob patterns clean L1 only — disk entries expire naturally via
458
+ // the background purge timer or are bypassed on the next L1 miss.
459
+ this.l1.deletePattern(msg.key);
460
+ }
461
+ this.logger.debug('Backplane: peer invalidation applied', {
462
+ op: msg.op, key: msg.key.slice(0, 60),
463
+ });
464
+ } catch { /* malformed message — ignore */ }
465
+ }
466
+
381
467
  private async publishInvalidation(op: 'del' | 'del-glob', key: string): Promise<void> {
382
468
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
383
469
  try {
@@ -391,7 +477,7 @@ export class CacheService {
391
477
  }
392
478
 
393
479
  private async getRedis(): Promise<RedisClient> {
394
- if (this.redis?.status === 'ready') return this.redis as RedisClient;
480
+ if (!this.cb.isAllowed()) throw new Error('tricache: L2 circuit breaker is open');
395
481
  if (this.redisConnecting) return this.redisConnecting;
396
482
 
397
483
  this.redisConnecting = (async () => {
@@ -419,10 +505,12 @@ export class CacheService {
419
505
  setTimeout(() => reject(new Error('Redis connection timeout')), 15_000);
420
506
  });
421
507
 
508
+ this.cb.onSuccess();
422
509
  this.redis = client;
423
510
  this.redisConnecting = null;
424
511
  return client;
425
512
  } catch (err) {
513
+ this.cb.onFailure();
426
514
  this.redisConnecting = null; // allow retry on next call — fixes the cached-rejection bug
427
515
  throw err;
428
516
  }
@@ -528,11 +616,12 @@ export class CacheService {
528
616
  swr?: number; // Stale-While-Revalidate grace period in seconds
529
617
  } = {},
530
618
  ): Promise<T> {
619
+ const span = this._startSpan('tricache.get');
620
+ span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
531
621
  const k = this.nk(cacheKey); // namespaced key used for all storage
532
622
  this.counters.gets++;
533
623
 
534
- // L1: in-memory (fastest path — defer inferPriority / ttlMs until we confirm a miss;
535
- // inferPriority runs 3 regex tests that are wasted work on every warm hit)
624
+ // L1: in-memory (fastest path)
536
625
  const l1Hit = this.l1.get(k);
537
626
  if (l1Hit !== null) {
538
627
  if (l1Hit.isStale) {
@@ -550,27 +639,31 @@ export class CacheService {
550
639
  this.logger.debug('L1 hit');
551
640
  }
552
641
  this.counters.l1Hits++;
642
+ span.setAttribute('cache.hit', 'l1').end();
553
643
  return l1Hit.value as T;
554
644
  }
555
645
 
556
- const ttlMs = ttlSeconds * 1_000;
646
+ const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
557
647
  const swrGraceMs = (opts.swr ?? 0) * 1_000;
558
- const priority = opts.priority ?? inferPriority(cacheKey); // original key for correct prefix inference
648
+ const priority = opts.priority ?? inferPriority(cacheKey);
559
649
 
560
650
  // L2: Redis (distributed, production-only by default)
561
651
  if (!this._redisDisabled) {
562
652
  try {
563
653
  const client = await this.getRedis();
564
654
  const raw = await client.get(k);
655
+ this.cb.onSuccess();
565
656
  if (raw) {
566
657
  const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
567
658
  const parsed = JSON.parse(decrypted) as T;
568
659
  this.l1.set(k, parsed, ttlMs, priority);
569
660
  this.counters.l2Hits++;
570
661
  this.logger.debug('L2 hit (Redis)', { cacheKey });
662
+ span.setAttribute('cache.hit', 'l2').end();
571
663
  return parsed;
572
664
  }
573
665
  } catch (err) {
666
+ this.cb.onFailure();
574
667
  this.logger.debug('Redis unavailable, continuing to fetch', { cacheKey, error: (err as Error).message });
575
668
  }
576
669
  }
@@ -587,16 +680,20 @@ export class CacheService {
587
680
  if (l1Check !== null) {
588
681
  this.counters.diskHits++;
589
682
  this.logger.debug('L1.5 hit (disk → L1)', { cacheKey });
683
+ span.setAttribute('cache.hit', 'disk').end();
590
684
  return l1Check.value as T;
591
685
  }
592
686
  }
593
687
  }
594
688
 
689
+ span.setAttribute('cache.hit', 'miss');
690
+
595
691
  // Cache MISS: thundering-herd prevention
596
692
  const existing = this.inflight.get(k);
597
693
  if (existing) {
598
694
  this.counters.stampedes++;
599
695
  this.logger.debug('Stampede prevented — coalescing onto inflight fetch', { cacheKey });
696
+ span.end();
600
697
  return existing as Promise<T>;
601
698
  }
602
699
 
@@ -614,9 +711,11 @@ export class CacheService {
614
711
  const client = await this.getRedis();
615
712
  const serialized = JSON.stringify(data);
616
713
  const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
617
- await client.setex(k, ttlSeconds, toStore);
714
+ await client.setex(k, Math.ceil(ttlMs / 1_000), toStore);
715
+ this.cb.onSuccess();
618
716
  this.logger.debug('Cached L1+L2', { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
619
717
  } catch {
718
+ this.cb.onFailure();
620
719
  this.logger.debug('Cached L1 only (Redis unavailable)', { cacheKey });
621
720
  }
622
721
  } else {
@@ -626,6 +725,7 @@ export class CacheService {
626
725
  return data;
627
726
  } finally {
628
727
  this.inflight.delete(k);
728
+ span.end();
629
729
  }
630
730
  })();
631
731
 
@@ -673,7 +773,9 @@ export class CacheService {
673
773
 
674
774
  /** Explicitly write a value into L1 (+ L2 in production). */
675
775
  async set<T>(cacheKey: string, data: T, ttlSeconds = 300, priority?: CachePriority, opts?: { tags?: string[] }): Promise<void> {
676
- 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);
677
779
  const p = priority ?? inferPriority(cacheKey);
678
780
  const k = this.nk(cacheKey);
679
781
  this.counters.sets++;
@@ -694,10 +796,11 @@ export class CacheService {
694
796
  for (const tag of opts.tags) {
695
797
  const tagKey = this.nk(`_tag_:${tag}`);
696
798
  pl.sadd(tagKey, k);
697
- pl.expire(tagKey, ttlSeconds + 3_600); // keep tag set alive longer than entries
799
+ pl.expire(tagKey, ttlSeconds + 3_600);
698
800
  }
699
801
  await pl.exec();
700
- } catch { /* tags are best-effort */ }
802
+ this.cb.onSuccess();
803
+ } catch { this.cb.onFailure(); /* tags are best-effort */ }
701
804
  }
702
805
  }
703
806
 
@@ -706,13 +809,16 @@ export class CacheService {
706
809
  const client = await this.getRedis();
707
810
  const s = JSON.stringify(data);
708
811
  const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
709
- await client.setex(k, ttlSeconds, stored);
812
+ await client.setex(k, Math.ceil(ttlMs / 1_000), stored);
813
+ this.cb.onSuccess();
710
814
  } catch (err) {
815
+ this.cb.onFailure();
711
816
  this.logger.debug('set: Redis unavailable', { cacheKey, error: (err as Error).message });
712
817
  }
713
818
  }
714
819
 
715
820
  void this.publishInvalidation('del', k);
821
+ span.end();
716
822
  }
717
823
 
718
824
  /**
@@ -723,8 +829,10 @@ export class CacheService {
723
829
  * await cache.delete('user:abc:*'); // all keys for user abc
724
830
  */
725
831
  async delete(cacheKey: string): Promise<void> {
832
+ const span = this._startSpan('tricache.delete');
833
+ span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
726
834
  const isPattern = cacheKey.includes('*');
727
- const k = this.nk(cacheKey); // namespace-scoped key / pattern
835
+ const k = this.nk(cacheKey);
728
836
  this.counters.deletes++;
729
837
 
730
838
  if (isPattern) {
@@ -749,12 +857,15 @@ export class CacheService {
749
857
  } else {
750
858
  await client.del(k);
751
859
  }
860
+ this.cb.onSuccess();
752
861
  } catch (err) {
862
+ this.cb.onFailure();
753
863
  this.logger.debug('delete: Redis unavailable', { cacheKey, error: (err as Error).message });
754
864
  }
755
865
  }
756
866
 
757
867
  void this.publishInvalidation(isPattern ? 'del-glob' : 'del', k);
868
+ span.end();
758
869
  }
759
870
 
760
871
  // ── Counter (distributed rate limiting) ──────────────────────────────────
@@ -862,6 +973,48 @@ export class CacheService {
862
973
  return this.l1.has(this.nk(cacheKey));
863
974
  }
864
975
 
976
+ // ── Iteration ─────────────────────────────────────────────────────────────
977
+
978
+ /**
979
+ * Lazily yield every non-expired L1 key, stripped of its namespace prefix.
980
+ *
981
+ * @example
982
+ * for (const key of cache.keys()) console.log(key);
983
+ */
984
+ *keys(): Generator<string> {
985
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
986
+ for (const key of this.l1.liveKeys()) {
987
+ yield prefixLen > 0 ? key.slice(prefixLen) : key;
988
+ }
989
+ }
990
+
991
+ /**
992
+ * Lazily yield every non-expired L1 value.
993
+ * Each value is the cached (pre-deserialized) JS object — no unpack overhead.
994
+ *
995
+ * @example
996
+ * for (const val of cache.values<User>()) console.log(val.id);
997
+ */
998
+ *values<T = unknown>(): Generator<T> {
999
+ // yield* delegates directly into liveValues(), collapsing one generator frame.
1000
+ yield* this.l1.liveValues() as Generator<T>;
1001
+ }
1002
+
1003
+ /**
1004
+ * Lazily yield every non-expired L1 [key, value] pair.
1005
+ * Keys are stripped of their namespace prefix.
1006
+ *
1007
+ * @example
1008
+ * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
1009
+ */
1010
+ *entries<T = unknown>(): Generator<[string, T]> {
1011
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
1012
+ for (const [key, entry] of this.l1.liveEntries()) {
1013
+ const k = prefixLen > 0 ? key.slice(prefixLen) : key;
1014
+ yield [k, (entry.value !== undefined ? entry.value : entry.data) as T];
1015
+ }
1016
+ }
1017
+
865
1018
  /**
866
1019
  * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
867
1020
  * Returns `false` if the key is absent or already expired.
@@ -941,6 +1094,103 @@ export class CacheService {
941
1094
  return result;
942
1095
  }
943
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
+
944
1194
  /**
945
1195
  * Invalidate all keys associated with a tag.
946
1196
  * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
@@ -1095,6 +1345,10 @@ export class CacheService {
1095
1345
  skipped: c.invSkipped,
1096
1346
  },
1097
1347
 
1348
+ l2CircuitBreaker: {
1349
+ state: this.cb.currentState,
1350
+ },
1351
+
1098
1352
  oom: {
1099
1353
  enabled: this.opts.oomProtection,
1100
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';