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.
package/dist/index.d.cts CHANGED
@@ -1,6 +1,24 @@
1
1
  /**
2
2
  * tricache — shared types and interfaces
3
3
  */
4
+ /**
5
+ * Minimal span interface — structurally compatible with `@opentelemetry/api` Span.
6
+ * Pass your existing OTEL tracer; no extra package required.
7
+ */
8
+ interface ICacheSpan {
9
+ setAttribute(key: string, value: string | number | boolean): this;
10
+ setStatus(status: {
11
+ code: 0 | 1 | 2;
12
+ message?: string;
13
+ }): this;
14
+ end(): void;
15
+ }
16
+ /**
17
+ * Minimal tracer interface — structurally compatible with `@opentelemetry/api` Tracer.
18
+ */
19
+ interface ICacheTracer {
20
+ startSpan(name: string): ICacheSpan;
21
+ }
4
22
  /** Minimal logger interface — plug in any logger (pino, winston, console, etc.) */
5
23
  interface ILogger {
6
24
  debug(msg: string, meta?: Record<string, unknown>): void;
@@ -144,6 +162,11 @@ interface CacheMetrics {
144
162
  /** Own messages silently skipped (prevents double-eviction) */
145
163
  skipped: number;
146
164
  };
165
+ /** L2 Redis circuit breaker state */
166
+ l2CircuitBreaker: {
167
+ /** `'closed'` = normal; `'open'` = Redis paused; `'half_open'` = probing recovery */
168
+ state: 'closed' | 'open' | 'half_open';
169
+ };
147
170
  /** OOM guard statistics */
148
171
  oom: {
149
172
  enabled: boolean;
@@ -342,6 +365,41 @@ interface CacheOptions {
342
365
  onMetrics?: (metrics: CacheMetrics) => void;
343
366
  /** How often the `onMetrics` callback fires (ms). Default: 60 000 ms */
344
367
  metricsIntervalMs?: number;
368
+ /**
369
+ * OpenTelemetry-compatible tracer. When provided, `get()`, `set()`, and
370
+ * `delete()` are each wrapped in a span with attributes:
371
+ * - `cache.hit` — `'l1' | 'disk' | 'l2' | 'miss'`
372
+ * - `cache.key_prefix` — first path segment of the key (e.g. `'user'`)
373
+ *
374
+ * Pass your existing `@opentelemetry/api` Tracer directly — no extra
375
+ * dependency required; the interface is structurally compatible.
376
+ *
377
+ * @example
378
+ * import { trace } from '@opentelemetry/api';
379
+ * tracer: trace.getTracer('tricache')
380
+ */
381
+ tracer?: ICacheTracer;
382
+ /**
383
+ * Randomise every stored TTL by ± `ttlJitterFactor × ttl` seconds.
384
+ * Prevents thundering-herd cache stampedes when thousands of entries share
385
+ * the same TTL and expire simultaneously.
386
+ *
387
+ * A factor of `0.15` spreads a 300 s TTL uniformly over [255 s, 345 s].
388
+ * Default: `0` (disabled — TTLs are stored exactly as given).
389
+ */
390
+ ttlJitterFactor?: number;
391
+ /**
392
+ * Number of consecutive Redis errors before the circuit opens (stops
393
+ * attempting Redis until the cooldown elapses).
394
+ * Default: `5`.
395
+ */
396
+ l2CircuitBreakerThreshold?: number;
397
+ /**
398
+ * Milliseconds the circuit stays open before transitioning to half-open
399
+ * (allows a single probe request to test recovery).
400
+ * Default: `30 000` ms (30 s).
401
+ */
402
+ l2CircuitBreakerCooldownMs?: number;
345
403
  }
346
404
 
347
405
  /**
@@ -379,6 +437,7 @@ declare class CacheService {
379
437
  private readonly tagIndex;
380
438
  private redis;
381
439
  private redisConnecting;
440
+ private readonly cb;
382
441
  private snapshotLoaded;
383
442
  private cleanupInterval;
384
443
  private oomInterval;
@@ -419,7 +478,13 @@ declare class CacheService {
419
478
  * receive and provide un-prefixed keys in the public API.
420
479
  */
421
480
  private nk;
481
+ /** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
482
+ private _jitterTtl;
483
+ /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
484
+ private _startSpan;
422
485
  private initBackplane;
486
+ /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
487
+ _handleBackplaneMessage(message: string): void;
423
488
  private publishInvalidation;
424
489
  private getRedis;
425
490
  writeSnapshot(altPath?: string): void;
@@ -482,6 +547,29 @@ declare class CacheService {
482
547
  * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
483
548
  */
484
549
  has(cacheKey: string): boolean;
550
+ /**
551
+ * Lazily yield every non-expired L1 key, stripped of its namespace prefix.
552
+ *
553
+ * @example
554
+ * for (const key of cache.keys()) console.log(key);
555
+ */
556
+ keys(): Generator<string>;
557
+ /**
558
+ * Lazily yield every non-expired L1 value.
559
+ * Each value is the cached (pre-deserialized) JS object — no unpack overhead.
560
+ *
561
+ * @example
562
+ * for (const val of cache.values<User>()) console.log(val.id);
563
+ */
564
+ values<T = unknown>(): Generator<T>;
565
+ /**
566
+ * Lazily yield every non-expired L1 [key, value] pair.
567
+ * Keys are stripped of their namespace prefix.
568
+ *
569
+ * @example
570
+ * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
571
+ */
572
+ entries<T = unknown>(): Generator<[string, T]>;
485
573
  /**
486
574
  * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
487
575
  * Returns `false` if the key is absent or already expired.
@@ -507,6 +595,43 @@ declare class CacheService {
507
595
  * @param ttl - TTL in seconds for newly fetched values.
508
596
  */
509
597
  mget<T>(keys: string[], fetchFn: (missKeys: string[]) => Promise<Record<string, T>>, ttl?: number, priority?: CachePriority): Promise<(T | undefined)[]>;
598
+ /**
599
+ * Batch write — set multiple entries in a single call.
600
+ * TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
601
+ *
602
+ * @example
603
+ * await cache.mset({
604
+ * 'user:1': { value: { name: 'Alice' }, ttl: 300 },
605
+ * 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
606
+ * });
607
+ */
608
+ mset<T = unknown>(entries: Record<string, {
609
+ value: T;
610
+ ttl?: number;
611
+ priority?: CachePriority;
612
+ tags?: string[];
613
+ }>): Promise<void>;
614
+ /**
615
+ * Batch delete — delete multiple exact keys in a single call.
616
+ * Glob patterns are not supported; use `delete('prefix:*')` for patterns.
617
+ *
618
+ * @example
619
+ * await cache.mdel(['user:1', 'user:2', 'user:3']);
620
+ */
621
+ mdel(keys: string[]): Promise<void>;
622
+ /**
623
+ * Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
624
+ * pulling them into L1. Useful on startup to eliminate cold-start penalty when
625
+ * the local snapshot is unavailable or too stale.
626
+ *
627
+ * Returns the number of keys loaded into L1.
628
+ *
629
+ * @example
630
+ * // In your startup hook (e.g. ECS task, k8s readiness probe):
631
+ * const loaded = await cache.warmFromL2('org:*');
632
+ * console.log(`Warmed ${loaded} keys from Redis`);
633
+ */
634
+ warmFromL2(pattern: string): Promise<number>;
510
635
  /**
511
636
  * Invalidate all keys associated with a tag.
512
637
  * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
@@ -685,6 +810,8 @@ declare class SmartMemoryCache {
685
810
  private bloom;
686
811
  /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
687
812
  private readonly categoryPrefixes;
813
+ /** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
814
+ private readonly sketch;
688
815
  private totalSize;
689
816
  private categoryCount;
690
817
  private categorySize;
@@ -753,6 +880,24 @@ declare class SmartMemoryCache {
753
880
  key: string;
754
881
  entry: SmartCacheEntry;
755
882
  }>, forbiddenPrefixes: readonly string[]): number;
883
+ /**
884
+ * Lazily yields every [key, entry] pair whose TTL has not yet expired.
885
+ * Expired entries that are still in the Map (awaiting background cleanup)
886
+ * are silently skipped.
887
+ */
888
+ liveEntries(): Generator<[string, SmartCacheEntry]>;
889
+ /**
890
+ * Yields only the keys of live entries — no intermediate tuple allocation.
891
+ * Use this instead of liveEntries() when you only need keys.
892
+ */
893
+ liveKeys(): Generator<string>;
894
+ /**
895
+ * Yields only the resolved values of live entries.
896
+ * Iterates Map.values() so the key is never loaded into the yielded path.
897
+ * Returns the cached deserialized object when available (entry.value), otherwise
898
+ * the raw msgpackr Buffer — identical semantics to get() but without bloom/hit tracking.
899
+ */
900
+ liveValues(): Generator<unknown>;
756
901
  get size(): number;
757
902
  get memoryUsage(): number;
758
903
  getStats(): {
@@ -915,4 +1060,4 @@ declare class WasmBloomFilter {
915
1060
  get maxCapacity(): number;
916
1061
  }
917
1062
 
918
- export { CacheEncryption, type CacheHit, type CacheMetrics, type CacheOptions, type CachePingResult, CachePriority, CacheService, type CategoryLimit, type DiskCacheEntry, DiskTier, type EncryptionMode, type EvictionReason, type ILogger, type SmartCacheEntry, SmartMemoryCache, WasmBloomFilter, consoleLogger };
1063
+ export { CacheEncryption, type CacheHit, type CacheMetrics, type CacheOptions, type CachePingResult, CachePriority, CacheService, type CategoryLimit, type DiskCacheEntry, DiskTier, type EncryptionMode, type EvictionReason, type ICacheSpan, type ICacheTracer, type ILogger, type SmartCacheEntry, SmartMemoryCache, WasmBloomFilter, consoleLogger };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,24 @@
1
1
  /**
2
2
  * tricache — shared types and interfaces
3
3
  */
4
+ /**
5
+ * Minimal span interface — structurally compatible with `@opentelemetry/api` Span.
6
+ * Pass your existing OTEL tracer; no extra package required.
7
+ */
8
+ interface ICacheSpan {
9
+ setAttribute(key: string, value: string | number | boolean): this;
10
+ setStatus(status: {
11
+ code: 0 | 1 | 2;
12
+ message?: string;
13
+ }): this;
14
+ end(): void;
15
+ }
16
+ /**
17
+ * Minimal tracer interface — structurally compatible with `@opentelemetry/api` Tracer.
18
+ */
19
+ interface ICacheTracer {
20
+ startSpan(name: string): ICacheSpan;
21
+ }
4
22
  /** Minimal logger interface — plug in any logger (pino, winston, console, etc.) */
5
23
  interface ILogger {
6
24
  debug(msg: string, meta?: Record<string, unknown>): void;
@@ -144,6 +162,11 @@ interface CacheMetrics {
144
162
  /** Own messages silently skipped (prevents double-eviction) */
145
163
  skipped: number;
146
164
  };
165
+ /** L2 Redis circuit breaker state */
166
+ l2CircuitBreaker: {
167
+ /** `'closed'` = normal; `'open'` = Redis paused; `'half_open'` = probing recovery */
168
+ state: 'closed' | 'open' | 'half_open';
169
+ };
147
170
  /** OOM guard statistics */
148
171
  oom: {
149
172
  enabled: boolean;
@@ -342,6 +365,41 @@ interface CacheOptions {
342
365
  onMetrics?: (metrics: CacheMetrics) => void;
343
366
  /** How often the `onMetrics` callback fires (ms). Default: 60 000 ms */
344
367
  metricsIntervalMs?: number;
368
+ /**
369
+ * OpenTelemetry-compatible tracer. When provided, `get()`, `set()`, and
370
+ * `delete()` are each wrapped in a span with attributes:
371
+ * - `cache.hit` — `'l1' | 'disk' | 'l2' | 'miss'`
372
+ * - `cache.key_prefix` — first path segment of the key (e.g. `'user'`)
373
+ *
374
+ * Pass your existing `@opentelemetry/api` Tracer directly — no extra
375
+ * dependency required; the interface is structurally compatible.
376
+ *
377
+ * @example
378
+ * import { trace } from '@opentelemetry/api';
379
+ * tracer: trace.getTracer('tricache')
380
+ */
381
+ tracer?: ICacheTracer;
382
+ /**
383
+ * Randomise every stored TTL by ± `ttlJitterFactor × ttl` seconds.
384
+ * Prevents thundering-herd cache stampedes when thousands of entries share
385
+ * the same TTL and expire simultaneously.
386
+ *
387
+ * A factor of `0.15` spreads a 300 s TTL uniformly over [255 s, 345 s].
388
+ * Default: `0` (disabled — TTLs are stored exactly as given).
389
+ */
390
+ ttlJitterFactor?: number;
391
+ /**
392
+ * Number of consecutive Redis errors before the circuit opens (stops
393
+ * attempting Redis until the cooldown elapses).
394
+ * Default: `5`.
395
+ */
396
+ l2CircuitBreakerThreshold?: number;
397
+ /**
398
+ * Milliseconds the circuit stays open before transitioning to half-open
399
+ * (allows a single probe request to test recovery).
400
+ * Default: `30 000` ms (30 s).
401
+ */
402
+ l2CircuitBreakerCooldownMs?: number;
345
403
  }
346
404
 
347
405
  /**
@@ -379,6 +437,7 @@ declare class CacheService {
379
437
  private readonly tagIndex;
380
438
  private redis;
381
439
  private redisConnecting;
440
+ private readonly cb;
382
441
  private snapshotLoaded;
383
442
  private cleanupInterval;
384
443
  private oomInterval;
@@ -419,7 +478,13 @@ declare class CacheService {
419
478
  * receive and provide un-prefixed keys in the public API.
420
479
  */
421
480
  private nk;
481
+ /** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
482
+ private _jitterTtl;
483
+ /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
484
+ private _startSpan;
422
485
  private initBackplane;
486
+ /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
487
+ _handleBackplaneMessage(message: string): void;
423
488
  private publishInvalidation;
424
489
  private getRedis;
425
490
  writeSnapshot(altPath?: string): void;
@@ -482,6 +547,29 @@ declare class CacheService {
482
547
  * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
483
548
  */
484
549
  has(cacheKey: string): boolean;
550
+ /**
551
+ * Lazily yield every non-expired L1 key, stripped of its namespace prefix.
552
+ *
553
+ * @example
554
+ * for (const key of cache.keys()) console.log(key);
555
+ */
556
+ keys(): Generator<string>;
557
+ /**
558
+ * Lazily yield every non-expired L1 value.
559
+ * Each value is the cached (pre-deserialized) JS object — no unpack overhead.
560
+ *
561
+ * @example
562
+ * for (const val of cache.values<User>()) console.log(val.id);
563
+ */
564
+ values<T = unknown>(): Generator<T>;
565
+ /**
566
+ * Lazily yield every non-expired L1 [key, value] pair.
567
+ * Keys are stripped of their namespace prefix.
568
+ *
569
+ * @example
570
+ * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
571
+ */
572
+ entries<T = unknown>(): Generator<[string, T]>;
485
573
  /**
486
574
  * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
487
575
  * Returns `false` if the key is absent or already expired.
@@ -507,6 +595,43 @@ declare class CacheService {
507
595
  * @param ttl - TTL in seconds for newly fetched values.
508
596
  */
509
597
  mget<T>(keys: string[], fetchFn: (missKeys: string[]) => Promise<Record<string, T>>, ttl?: number, priority?: CachePriority): Promise<(T | undefined)[]>;
598
+ /**
599
+ * Batch write — set multiple entries in a single call.
600
+ * TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
601
+ *
602
+ * @example
603
+ * await cache.mset({
604
+ * 'user:1': { value: { name: 'Alice' }, ttl: 300 },
605
+ * 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
606
+ * });
607
+ */
608
+ mset<T = unknown>(entries: Record<string, {
609
+ value: T;
610
+ ttl?: number;
611
+ priority?: CachePriority;
612
+ tags?: string[];
613
+ }>): Promise<void>;
614
+ /**
615
+ * Batch delete — delete multiple exact keys in a single call.
616
+ * Glob patterns are not supported; use `delete('prefix:*')` for patterns.
617
+ *
618
+ * @example
619
+ * await cache.mdel(['user:1', 'user:2', 'user:3']);
620
+ */
621
+ mdel(keys: string[]): Promise<void>;
622
+ /**
623
+ * Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
624
+ * pulling them into L1. Useful on startup to eliminate cold-start penalty when
625
+ * the local snapshot is unavailable or too stale.
626
+ *
627
+ * Returns the number of keys loaded into L1.
628
+ *
629
+ * @example
630
+ * // In your startup hook (e.g. ECS task, k8s readiness probe):
631
+ * const loaded = await cache.warmFromL2('org:*');
632
+ * console.log(`Warmed ${loaded} keys from Redis`);
633
+ */
634
+ warmFromL2(pattern: string): Promise<number>;
510
635
  /**
511
636
  * Invalidate all keys associated with a tag.
512
637
  * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
@@ -685,6 +810,8 @@ declare class SmartMemoryCache {
685
810
  private bloom;
686
811
  /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
687
812
  private readonly categoryPrefixes;
813
+ /** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
814
+ private readonly sketch;
688
815
  private totalSize;
689
816
  private categoryCount;
690
817
  private categorySize;
@@ -753,6 +880,24 @@ declare class SmartMemoryCache {
753
880
  key: string;
754
881
  entry: SmartCacheEntry;
755
882
  }>, forbiddenPrefixes: readonly string[]): number;
883
+ /**
884
+ * Lazily yields every [key, entry] pair whose TTL has not yet expired.
885
+ * Expired entries that are still in the Map (awaiting background cleanup)
886
+ * are silently skipped.
887
+ */
888
+ liveEntries(): Generator<[string, SmartCacheEntry]>;
889
+ /**
890
+ * Yields only the keys of live entries — no intermediate tuple allocation.
891
+ * Use this instead of liveEntries() when you only need keys.
892
+ */
893
+ liveKeys(): Generator<string>;
894
+ /**
895
+ * Yields only the resolved values of live entries.
896
+ * Iterates Map.values() so the key is never loaded into the yielded path.
897
+ * Returns the cached deserialized object when available (entry.value), otherwise
898
+ * the raw msgpackr Buffer — identical semantics to get() but without bloom/hit tracking.
899
+ */
900
+ liveValues(): Generator<unknown>;
756
901
  get size(): number;
757
902
  get memoryUsage(): number;
758
903
  getStats(): {
@@ -915,4 +1060,4 @@ declare class WasmBloomFilter {
915
1060
  get maxCapacity(): number;
916
1061
  }
917
1062
 
918
- export { CacheEncryption, type CacheHit, type CacheMetrics, type CacheOptions, type CachePingResult, CachePriority, CacheService, type CategoryLimit, type DiskCacheEntry, DiskTier, type EncryptionMode, type EvictionReason, type ILogger, type SmartCacheEntry, SmartMemoryCache, WasmBloomFilter, consoleLogger };
1063
+ export { CacheEncryption, type CacheHit, type CacheMetrics, type CacheOptions, type CachePingResult, CachePriority, CacheService, type CategoryLimit, type DiskCacheEntry, DiskTier, type EncryptionMode, type EvictionReason, type ICacheSpan, type ICacheTracer, type ILogger, type SmartCacheEntry, SmartMemoryCache, WasmBloomFilter, consoleLogger };