tricache 0.1.0 → 0.3.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.
package/dist/index.d.ts CHANGED
@@ -10,6 +10,25 @@ interface ILogger {
10
10
  }
11
11
  /** Default no-op logger — swap out via CacheService options */
12
12
  declare const consoleLogger: ILogger;
13
+ /**
14
+ * Reason passed to the `onEviction` callback.
15
+ * - `'capacity'` — L1 over-capacity; evicted during a `set()` call
16
+ * - `'category'` — Per-category limit exceeded
17
+ * - `'rebalance'` — `cache.rebalance()` was called
18
+ * - `'oom'` — OOM guard emergency eviction
19
+ * - `'ttl'` — Entry expired during periodic cleanup
20
+ * - `'manual'` — Explicit `cache.delete()` call
21
+ */
22
+ type EvictionReason = 'capacity' | 'category' | 'rebalance' | 'oom' | 'ttl' | 'manual';
23
+ /** Per-tier latency returned by `cache.ping()`. */
24
+ interface CachePingResult {
25
+ /** L1 RAM check latency in milliseconds */
26
+ l1: number;
27
+ /** L1.5 disk stats access in milliseconds */
28
+ disk: number;
29
+ /** L2 Redis PING round-trip in milliseconds, or `null` when Redis is disabled */
30
+ l2: number | null;
31
+ }
13
32
  /** Priority levels for L1 eviction — higher = less likely to be evicted */
14
33
  declare enum CachePriority {
15
34
  LOW = 1,// Easily regenerated (analytics, reports)
@@ -19,8 +38,14 @@ declare enum CachePriority {
19
38
  }
20
39
  /** Internal representation of a single cache entry in the L1 Map */
21
40
  interface SmartCacheEntry {
22
- /** msgpackr-packed binary payload */
41
+ /** msgpackr-packed binary payload — used for disk spill and snapshot serialization */
23
42
  data: Buffer;
43
+ /**
44
+ * Deserialized JS value, cached at write time so hot reads skip the unpack step entirely.
45
+ * Undefined for entries restored from disk/snapshot (populated lazily on first access).
46
+ * NOTE: returned by reference — callers should treat the value as immutable.
47
+ */
48
+ value?: unknown;
24
49
  /** always true for entries written by the current code;
25
50
  * may be false in legacy snapshots/disk files — handled transparently on import */
26
51
  isCompressed: boolean;
@@ -209,6 +234,16 @@ interface CacheOptions {
209
234
  * Default: `'aes-256-gcm'`
210
235
  */
211
236
  encryptionMode?: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
237
+ /**
238
+ * Fallback encryption key for zero-downtime key rotation.
239
+ * On every read, tricache tries the current `encryptionKey` first.
240
+ * If decryption fails (wrong key), it retries with `previousEncryptionKey`.
241
+ * All writes always use the current `encryptionKey`.
242
+ * Remove this field once you are confident all data has been re-encrypted.
243
+ */
244
+ previousEncryptionKey?: string;
245
+ /** Encryption mode that was used with `previousEncryptionKey`. Defaults to `encryptionMode`. */
246
+ previousEncryptionMode?: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
212
247
  /**
213
248
  * Path where the cold-start snapshot is written on SIGTERM/SIGINT and loaded
214
249
  * on startup. Default: os.tmpdir()/tricache-snapshot.msgpack
@@ -239,6 +274,35 @@ interface CacheOptions {
239
274
  * Default: `''` (no prefix)
240
275
  */
241
276
  namespace?: string;
277
+ /**
278
+ * Seconds to extend a stale SWR entry's life when background revalidation fails.
279
+ * Without this, a failed revalidation leaves the entry stale until its hard TTL
280
+ * expires, after which the next caller blocks. With `staleIfError`, tricache bumps
281
+ * the expiry by this many seconds on every failed revalidation, keeping the stale
282
+ * value available while the underlying service is degraded.
283
+ * Default: `0` (disabled — entry expires normally on revalidation failure).
284
+ */
285
+ staleIfError?: number;
286
+ /**
287
+ * Called after every L1 eviction. Receives the raw (namespaced) key and the reason.
288
+ * Useful for diagnosing cache pressure and tuning `categoryLimits`.
289
+ */
290
+ onEviction?: (key: string, reason: EvictionReason) => void;
291
+ /**
292
+ * Human-readable name for this CacheService instance. Added as an `instance` label
293
+ * to all Prometheus metrics emitted by `CacheService.toPrometheusText()`.
294
+ * Required when multiple CacheService instances share a process — without it,
295
+ * metric names from different instances collide.
296
+ * Default: `''` (no label).
297
+ */
298
+ instanceName?: string;
299
+ /**
300
+ * Controls whether writes are propagated to L2 (Redis).
301
+ * - `'read-write'` (default): read from and write to L2.
302
+ * - `'read-only'`: read from L2 but never write, delete, or expire keys in Redis.
303
+ * Use for shared read replicas or external Redis clusters you do not own.
304
+ */
305
+ l2WriteMode?: 'read-write' | 'read-only';
242
306
  /**
243
307
  * Enable Redis Pub/Sub invalidation backplane so every running instance
244
308
  * evicts a key from its L1 when any peer calls `set()` or `delete()`.
@@ -310,6 +374,9 @@ declare class CacheService {
310
374
  private readonly _redisDisabled;
311
375
  private readonly inflight;
312
376
  private readonly revalidating;
377
+ private readonly _l1Counters;
378
+ /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
379
+ private readonly tagIndex;
313
380
  private redis;
314
381
  private redisConnecting;
315
382
  private snapshotLoaded;
@@ -332,6 +399,14 @@ declare class CacheService {
332
399
  * with different namespaces return independent instances.
333
400
  */
334
401
  static create(options?: CacheOptions): CacheService;
402
+ /**
403
+ * Async factory — accepts a Promise that resolves to CacheOptions.
404
+ * Useful when config is fetched from a secret store at startup.
405
+ *
406
+ * @example
407
+ * const cache = await CacheService.createAsync(fetchSecrets());
408
+ */
409
+ static createAsync(options: Promise<CacheOptions> | CacheOptions): Promise<CacheService>;
335
410
  /** Replace the singleton (useful in tests). */
336
411
  static reset(options?: CacheOptions): CacheService;
337
412
  /** Derive the globalThis key for a given set of options. */
@@ -345,9 +420,11 @@ declare class CacheService {
345
420
  */
346
421
  private nk;
347
422
  private initBackplane;
423
+ /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
424
+ _handleBackplaneMessage(message: string): void;
348
425
  private publishInvalidation;
349
426
  private getRedis;
350
- writeSnapshot(): void;
427
+ writeSnapshot(altPath?: string): void;
351
428
  loadSnapshot(): void;
352
429
  /**
353
430
  * Get a value from cache, or fetch and cache it.
@@ -366,7 +443,9 @@ declare class CacheService {
366
443
  }): Promise<T>;
367
444
  private _revalidate;
368
445
  /** Explicitly write a value into L1 (+ L2 in production). */
369
- set<T>(cacheKey: string, data: T, ttlSeconds?: number, priority?: CachePriority): Promise<void>;
446
+ set<T>(cacheKey: string, data: T, ttlSeconds?: number, priority?: CachePriority, opts?: {
447
+ tags?: string[];
448
+ }): Promise<void>;
370
449
  /**
371
450
  * Delete one key or a glob pattern (supports `*` wildcard).
372
451
  *
@@ -380,11 +459,111 @@ declare class CacheService {
380
459
  * Returns 0 if Redis is disabled (safe fallback — rate limiting won't block in dev).
381
460
  */
382
461
  increment(cacheKey: string, ttlSeconds?: number): Promise<number>;
462
+ /**
463
+ * Flush all cached entries, or only those whose key starts with `prefix`.
464
+ *
465
+ * @example
466
+ * await cache.clear(); // flush everything
467
+ * await cache.clear('user:abc'); // flush all keys for one user
468
+ */
469
+ clear(prefix?: string): Promise<void>;
470
+ /**
471
+ * Evict L1 entries that violate the current category or global capacity limits.
472
+ * Useful after a write burst or after adding stricter `categoryLimits`.
473
+ * Returns the number of entries evicted.
474
+ */
475
+ rebalance(): number;
476
+ /**
477
+ * Return the remaining TTL in seconds for a key currently in L1.
478
+ * Returns null if the key is absent from L1 or has already expired.
479
+ * Only reflects L1 state — does not query Redis or disk.
480
+ */
481
+ ttl(cacheKey: string): number | null;
482
+ /**
483
+ * Return true if the key exists in L1 and has not expired.
484
+ * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
485
+ */
486
+ has(cacheKey: string): boolean;
487
+ /**
488
+ * Lazily yield every non-expired L1 key, stripped of its namespace prefix.
489
+ *
490
+ * @example
491
+ * for (const key of cache.keys()) console.log(key);
492
+ */
493
+ keys(): Generator<string>;
494
+ /**
495
+ * Lazily yield every non-expired L1 value.
496
+ * Each value is the cached (pre-deserialized) JS object — no unpack overhead.
497
+ *
498
+ * @example
499
+ * for (const val of cache.values<User>()) console.log(val.id);
500
+ */
501
+ values<T = unknown>(): Generator<T>;
502
+ /**
503
+ * Lazily yield every non-expired L1 [key, value] pair.
504
+ * Keys are stripped of their namespace prefix.
505
+ *
506
+ * @example
507
+ * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
508
+ */
509
+ entries<T = unknown>(): Generator<[string, T]>;
510
+ /**
511
+ * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
512
+ * Returns `false` if the key is absent or already expired.
513
+ *
514
+ * @param newTtlSeconds - The new TTL from now, in seconds.
515
+ */
516
+ touch(cacheKey: string, newTtlSeconds: number): Promise<boolean>;
517
+ /**
518
+ * Return the cached value from L1 **only if it is fresh** (not in the SWR grace window).
519
+ * Returns `null` when the key is absent, expired, or stale — without triggering a fetch.
520
+ *
521
+ * @example
522
+ * const fresh = cache.getIfFresh('user:123');
523
+ * if (fresh !== null) return fresh; // serve from L1, no network hop
524
+ */
525
+ getIfFresh<T = unknown>(cacheKey: string): T | null;
526
+ /**
527
+ * Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
528
+ * Preserves input ordering. Uses inflight coalescing per key.
529
+ *
530
+ * @param keys - Array of cache keys.
531
+ * @param fetchFn - Called with only the keys that missed L1.
532
+ * @param ttl - TTL in seconds for newly fetched values.
533
+ */
534
+ mget<T>(keys: string[], fetchFn: (missKeys: string[]) => Promise<Record<string, T>>, ttl?: number, priority?: CachePriority): Promise<(T | undefined)[]>;
535
+ /**
536
+ * Invalidate all keys associated with a tag.
537
+ * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
538
+ *
539
+ * @example
540
+ * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
541
+ * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
542
+ */
543
+ invalidateTag(tag: string): Promise<void>;
544
+ /**
545
+ * Measure L1 / disk / Redis latency.
546
+ * Useful for health checks and dashboards.
547
+ *
548
+ * @returns `{ l1, disk, l2 }` latencies in milliseconds.
549
+ * `l2` is `null` when Redis is disabled.
550
+ */
551
+ ping(): Promise<CachePingResult>;
552
+ /**
553
+ * Export all live L1 entries to Redis via a single pipeline.
554
+ * Useful for warming a new Redis instance or for zero-downtime failover.
555
+ * Returns the number of keys written.
556
+ */
557
+ drainToL2(): Promise<number>;
383
558
  stats(): {
384
559
  l1: {
385
560
  entries: number;
561
+ sizeBytes: number;
386
562
  sizeKB: number;
387
- categories: Record<string, number>;
563
+ categories: Record<string, {
564
+ entries: number;
565
+ hits: number;
566
+ }>;
388
567
  bloom: {
389
568
  checks: number;
390
569
  falsePositives: number;
@@ -410,7 +589,7 @@ declare class CacheService {
410
589
  * @param m - Snapshot returned by `cache.metrics()`
411
590
  * @param prefix - Metric name prefix. Default: `"tricache"`
412
591
  */
413
- static toPrometheusText(m: CacheMetrics, prefix?: string): string;
592
+ static toPrometheusText(m: CacheMetrics, prefix?: string, instanceName?: string): string;
414
593
  /** Close Redis connections and stop all background timers. */
415
594
  destroy(): Promise<void>;
416
595
  }
@@ -455,6 +634,8 @@ type EncryptionMode = 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
455
634
  declare class CacheEncryption {
456
635
  private _key;
457
636
  private readonly _mode;
637
+ private _prevKey;
638
+ private _prevMode;
458
639
  private readonly _ivPool;
459
640
  private _ivOffset;
460
641
  /** Return the next unique 12-byte IV slice from the pre-allocated GCM pool. */
@@ -475,7 +656,7 @@ declare class CacheEncryption {
475
656
  * WARNING: XOR is NOT cryptographic. It provides obfuscation only.
476
657
  */
477
658
  private _xorBuffer;
478
- constructor(keyBase64: string | undefined, logger: ILogger, mode?: EncryptionMode);
659
+ constructor(keyBase64: string | undefined, logger: ILogger, mode?: EncryptionMode, previousKeyBase64?: string, previousMode?: EncryptionMode);
479
660
  get isEnabled(): boolean;
480
661
  /**
481
662
  * Encrypt a string for Redis storage.
@@ -486,15 +667,19 @@ declare class CacheEncryption {
486
667
  /**
487
668
  * Decrypt a Redis value.
488
669
  * Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
670
+ * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
489
671
  */
490
672
  decrypt(value: string): string;
673
+ private _decryptWithKey;
491
674
  /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
492
675
  encryptBuffer(data: Buffer): Buffer;
493
676
  /**
494
677
  * Decrypt a raw Buffer from disk/snapshot.
495
678
  * Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
679
+ * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
496
680
  */
497
681
  decryptBuffer(data: Buffer): Buffer;
682
+ private _decryptBufferWithKey;
498
683
  }
499
684
 
500
685
  /**
@@ -516,6 +701,7 @@ interface SmartMemoryCacheOptions {
516
701
  maxEntries: number;
517
702
  categories: Record<string, CategoryLimit>;
518
703
  diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
704
+ onEviction?: (key: string, reason: EvictionReason) => void;
519
705
  logger: ILogger;
520
706
  }
521
707
  declare class SmartMemoryCache {
@@ -524,6 +710,8 @@ declare class SmartMemoryCache {
524
710
  private bloom;
525
711
  /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
526
712
  private readonly categoryPrefixes;
713
+ /** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
714
+ private readonly sketch;
527
715
  private totalSize;
528
716
  private categoryCount;
529
717
  private categorySize;
@@ -532,6 +720,7 @@ declare class SmartMemoryCache {
532
720
  private bloomChecks;
533
721
  private bloomFalsePos;
534
722
  private compressions;
723
+ private categoryHits;
535
724
  /** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
536
725
  private _bloomDirtyCount;
537
726
  constructor(opts: SmartMemoryCacheOptions, existing?: Map<string, SmartCacheEntry>);
@@ -561,6 +750,18 @@ declare class SmartMemoryCache {
561
750
  delete(key: string): boolean;
562
751
  private keysMatchingPattern;
563
752
  deletePattern(pattern: string): number;
753
+ /** Flush all entries, or only those whose key starts with `prefix`. */
754
+ clear(prefix?: string): number;
755
+ /**
756
+ * Evict entries that violate current category or global limits.
757
+ * Returns the number of entries evicted.
758
+ */
759
+ rebalance(): number;
760
+ /**
761
+ * Return remaining TTL in seconds for a key in L1, or null if absent/expired.
762
+ * Only reflects L1 state — does not query Redis or disk.
763
+ */
764
+ ttl(key: string): number | null;
564
765
  /**
565
766
  * Forcibly evict the coldest `pct` fraction of non-CRITICAL L1 entries,
566
767
  * spilling each to L1.5 disk. Called by the OOM guard when heap pressure
@@ -579,12 +780,34 @@ declare class SmartMemoryCache {
579
780
  key: string;
580
781
  entry: SmartCacheEntry;
581
782
  }>, forbiddenPrefixes: readonly string[]): number;
783
+ /**
784
+ * Lazily yields every [key, entry] pair whose TTL has not yet expired.
785
+ * Expired entries that are still in the Map (awaiting background cleanup)
786
+ * are silently skipped.
787
+ */
788
+ liveEntries(): Generator<[string, SmartCacheEntry]>;
789
+ /**
790
+ * Yields only the keys of live entries — no intermediate tuple allocation.
791
+ * Use this instead of liveEntries() when you only need keys.
792
+ */
793
+ liveKeys(): Generator<string>;
794
+ /**
795
+ * Yields only the resolved values of live entries.
796
+ * Iterates Map.values() so the key is never loaded into the yielded path.
797
+ * Returns the cached deserialized object when available (entry.value), otherwise
798
+ * the raw msgpackr Buffer — identical semantics to get() but without bloom/hit tracking.
799
+ */
800
+ liveValues(): Generator<unknown>;
582
801
  get size(): number;
583
802
  get memoryUsage(): number;
584
803
  getStats(): {
585
804
  entries: number;
805
+ sizeBytes: number;
586
806
  sizeKB: number;
587
- categories: Record<string, number>;
807
+ categories: Record<string, {
808
+ entries: number;
809
+ hits: number;
810
+ }>;
588
811
  bloom: {
589
812
  checks: number;
590
813
  falsePositives: number;
@@ -595,6 +818,26 @@ declare class SmartMemoryCache {
595
818
  bytesSaved: number;
596
819
  };
597
820
  };
821
+ /**
822
+ * Return the raw cache entry for a key, or `undefined` if absent/expired.
823
+ * Does NOT count as a hit or perform SWR logic.
824
+ */
825
+ getEntry(key: string): SmartCacheEntry | undefined;
826
+ /**
827
+ * Return true if the key exists in L1 and has not expired.
828
+ * Uses the bloom filter as a fast negative check.
829
+ */
830
+ has(key: string): boolean;
831
+ /**
832
+ * Extend the TTL of an existing key. Returns `false` if the key is absent or expired.
833
+ * @param newTtlMs - New TTL from now, in milliseconds.
834
+ */
835
+ touch(key: string, newTtlMs: number): boolean;
836
+ /**
837
+ * Add additional milliseconds to a key's existing expiry (for stale-if-error).
838
+ * Returns `false` if the key is absent or already expired.
839
+ */
840
+ bumpExpiry(key: string, additionalMs: number): boolean;
598
841
  bloomMightContain(key: string): boolean;
599
842
  bloomStats(): {
600
843
  bitsSet: number;
@@ -679,6 +922,8 @@ declare class DiskTier {
679
922
  delete(key: string): void;
680
923
  /** Purge all expired entries. Returns number deleted. */
681
924
  purgeExpired(): number;
925
+ /** Delete every file in the disk cache. Returns the count deleted. */
926
+ clear(): number;
682
927
  get stats(): {
683
928
  files: number;
684
929
  sizeKB: number;
@@ -715,4 +960,4 @@ declare class WasmBloomFilter {
715
960
  get maxCapacity(): number;
716
961
  }
717
962
 
718
- export { CacheEncryption, type CacheHit, type CacheMetrics, type CacheOptions, CachePriority, CacheService, type CategoryLimit, type DiskCacheEntry, DiskTier, type EncryptionMode, type ILogger, type SmartCacheEntry, SmartMemoryCache, WasmBloomFilter, consoleLogger };
963
+ 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 };