tricache 0.1.0 → 0.2.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. */
@@ -347,7 +422,7 @@ declare class CacheService {
347
422
  private initBackplane;
348
423
  private publishInvalidation;
349
424
  private getRedis;
350
- writeSnapshot(): void;
425
+ writeSnapshot(altPath?: string): void;
351
426
  loadSnapshot(): void;
352
427
  /**
353
428
  * Get a value from cache, or fetch and cache it.
@@ -366,7 +441,9 @@ declare class CacheService {
366
441
  }): Promise<T>;
367
442
  private _revalidate;
368
443
  /** Explicitly write a value into L1 (+ L2 in production). */
369
- set<T>(cacheKey: string, data: T, ttlSeconds?: number, priority?: CachePriority): Promise<void>;
444
+ set<T>(cacheKey: string, data: T, ttlSeconds?: number, priority?: CachePriority, opts?: {
445
+ tags?: string[];
446
+ }): Promise<void>;
370
447
  /**
371
448
  * Delete one key or a glob pattern (supports `*` wildcard).
372
449
  *
@@ -380,11 +457,88 @@ declare class CacheService {
380
457
  * Returns 0 if Redis is disabled (safe fallback — rate limiting won't block in dev).
381
458
  */
382
459
  increment(cacheKey: string, ttlSeconds?: number): Promise<number>;
460
+ /**
461
+ * Flush all cached entries, or only those whose key starts with `prefix`.
462
+ *
463
+ * @example
464
+ * await cache.clear(); // flush everything
465
+ * await cache.clear('user:abc'); // flush all keys for one user
466
+ */
467
+ clear(prefix?: string): Promise<void>;
468
+ /**
469
+ * Evict L1 entries that violate the current category or global capacity limits.
470
+ * Useful after a write burst or after adding stricter `categoryLimits`.
471
+ * Returns the number of entries evicted.
472
+ */
473
+ rebalance(): number;
474
+ /**
475
+ * Return the remaining TTL in seconds for a key currently in L1.
476
+ * Returns null if the key is absent from L1 or has already expired.
477
+ * Only reflects L1 state — does not query Redis or disk.
478
+ */
479
+ ttl(cacheKey: string): number | null;
480
+ /**
481
+ * Return true if the key exists in L1 and has not expired.
482
+ * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
483
+ */
484
+ has(cacheKey: string): boolean;
485
+ /**
486
+ * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
487
+ * Returns `false` if the key is absent or already expired.
488
+ *
489
+ * @param newTtlSeconds - The new TTL from now, in seconds.
490
+ */
491
+ touch(cacheKey: string, newTtlSeconds: number): Promise<boolean>;
492
+ /**
493
+ * Return the cached value from L1 **only if it is fresh** (not in the SWR grace window).
494
+ * Returns `null` when the key is absent, expired, or stale — without triggering a fetch.
495
+ *
496
+ * @example
497
+ * const fresh = cache.getIfFresh('user:123');
498
+ * if (fresh !== null) return fresh; // serve from L1, no network hop
499
+ */
500
+ getIfFresh<T = unknown>(cacheKey: string): T | null;
501
+ /**
502
+ * Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
503
+ * Preserves input ordering. Uses inflight coalescing per key.
504
+ *
505
+ * @param keys - Array of cache keys.
506
+ * @param fetchFn - Called with only the keys that missed L1.
507
+ * @param ttl - TTL in seconds for newly fetched values.
508
+ */
509
+ mget<T>(keys: string[], fetchFn: (missKeys: string[]) => Promise<Record<string, T>>, ttl?: number, priority?: CachePriority): Promise<(T | undefined)[]>;
510
+ /**
511
+ * Invalidate all keys associated with a tag.
512
+ * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
513
+ *
514
+ * @example
515
+ * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
516
+ * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
517
+ */
518
+ invalidateTag(tag: string): Promise<void>;
519
+ /**
520
+ * Measure L1 / disk / Redis latency.
521
+ * Useful for health checks and dashboards.
522
+ *
523
+ * @returns `{ l1, disk, l2 }` latencies in milliseconds.
524
+ * `l2` is `null` when Redis is disabled.
525
+ */
526
+ ping(): Promise<CachePingResult>;
527
+ /**
528
+ * Export all live L1 entries to Redis via a single pipeline.
529
+ * Useful for warming a new Redis instance or for zero-downtime failover.
530
+ * Returns the number of keys written.
531
+ */
532
+ drainToL2(): Promise<number>;
383
533
  stats(): {
384
534
  l1: {
385
535
  entries: number;
536
+ sizeBytes: number;
386
537
  sizeKB: number;
387
- categories: Record<string, number>;
538
+ categories: Record<string, {
539
+ entries: number;
540
+ hits: number;
541
+ }>;
388
542
  bloom: {
389
543
  checks: number;
390
544
  falsePositives: number;
@@ -410,7 +564,7 @@ declare class CacheService {
410
564
  * @param m - Snapshot returned by `cache.metrics()`
411
565
  * @param prefix - Metric name prefix. Default: `"tricache"`
412
566
  */
413
- static toPrometheusText(m: CacheMetrics, prefix?: string): string;
567
+ static toPrometheusText(m: CacheMetrics, prefix?: string, instanceName?: string): string;
414
568
  /** Close Redis connections and stop all background timers. */
415
569
  destroy(): Promise<void>;
416
570
  }
@@ -455,6 +609,8 @@ type EncryptionMode = 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
455
609
  declare class CacheEncryption {
456
610
  private _key;
457
611
  private readonly _mode;
612
+ private _prevKey;
613
+ private _prevMode;
458
614
  private readonly _ivPool;
459
615
  private _ivOffset;
460
616
  /** Return the next unique 12-byte IV slice from the pre-allocated GCM pool. */
@@ -475,7 +631,7 @@ declare class CacheEncryption {
475
631
  * WARNING: XOR is NOT cryptographic. It provides obfuscation only.
476
632
  */
477
633
  private _xorBuffer;
478
- constructor(keyBase64: string | undefined, logger: ILogger, mode?: EncryptionMode);
634
+ constructor(keyBase64: string | undefined, logger: ILogger, mode?: EncryptionMode, previousKeyBase64?: string, previousMode?: EncryptionMode);
479
635
  get isEnabled(): boolean;
480
636
  /**
481
637
  * Encrypt a string for Redis storage.
@@ -486,15 +642,19 @@ declare class CacheEncryption {
486
642
  /**
487
643
  * Decrypt a Redis value.
488
644
  * Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
645
+ * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
489
646
  */
490
647
  decrypt(value: string): string;
648
+ private _decryptWithKey;
491
649
  /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
492
650
  encryptBuffer(data: Buffer): Buffer;
493
651
  /**
494
652
  * Decrypt a raw Buffer from disk/snapshot.
495
653
  * Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
654
+ * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
496
655
  */
497
656
  decryptBuffer(data: Buffer): Buffer;
657
+ private _decryptBufferWithKey;
498
658
  }
499
659
 
500
660
  /**
@@ -516,6 +676,7 @@ interface SmartMemoryCacheOptions {
516
676
  maxEntries: number;
517
677
  categories: Record<string, CategoryLimit>;
518
678
  diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
679
+ onEviction?: (key: string, reason: EvictionReason) => void;
519
680
  logger: ILogger;
520
681
  }
521
682
  declare class SmartMemoryCache {
@@ -532,6 +693,7 @@ declare class SmartMemoryCache {
532
693
  private bloomChecks;
533
694
  private bloomFalsePos;
534
695
  private compressions;
696
+ private categoryHits;
535
697
  /** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
536
698
  private _bloomDirtyCount;
537
699
  constructor(opts: SmartMemoryCacheOptions, existing?: Map<string, SmartCacheEntry>);
@@ -561,6 +723,18 @@ declare class SmartMemoryCache {
561
723
  delete(key: string): boolean;
562
724
  private keysMatchingPattern;
563
725
  deletePattern(pattern: string): number;
726
+ /** Flush all entries, or only those whose key starts with `prefix`. */
727
+ clear(prefix?: string): number;
728
+ /**
729
+ * Evict entries that violate current category or global limits.
730
+ * Returns the number of entries evicted.
731
+ */
732
+ rebalance(): number;
733
+ /**
734
+ * Return remaining TTL in seconds for a key in L1, or null if absent/expired.
735
+ * Only reflects L1 state — does not query Redis or disk.
736
+ */
737
+ ttl(key: string): number | null;
564
738
  /**
565
739
  * Forcibly evict the coldest `pct` fraction of non-CRITICAL L1 entries,
566
740
  * spilling each to L1.5 disk. Called by the OOM guard when heap pressure
@@ -583,8 +757,12 @@ declare class SmartMemoryCache {
583
757
  get memoryUsage(): number;
584
758
  getStats(): {
585
759
  entries: number;
760
+ sizeBytes: number;
586
761
  sizeKB: number;
587
- categories: Record<string, number>;
762
+ categories: Record<string, {
763
+ entries: number;
764
+ hits: number;
765
+ }>;
588
766
  bloom: {
589
767
  checks: number;
590
768
  falsePositives: number;
@@ -595,6 +773,26 @@ declare class SmartMemoryCache {
595
773
  bytesSaved: number;
596
774
  };
597
775
  };
776
+ /**
777
+ * Return the raw cache entry for a key, or `undefined` if absent/expired.
778
+ * Does NOT count as a hit or perform SWR logic.
779
+ */
780
+ getEntry(key: string): SmartCacheEntry | undefined;
781
+ /**
782
+ * Return true if the key exists in L1 and has not expired.
783
+ * Uses the bloom filter as a fast negative check.
784
+ */
785
+ has(key: string): boolean;
786
+ /**
787
+ * Extend the TTL of an existing key. Returns `false` if the key is absent or expired.
788
+ * @param newTtlMs - New TTL from now, in milliseconds.
789
+ */
790
+ touch(key: string, newTtlMs: number): boolean;
791
+ /**
792
+ * Add additional milliseconds to a key's existing expiry (for stale-if-error).
793
+ * Returns `false` if the key is absent or already expired.
794
+ */
795
+ bumpExpiry(key: string, additionalMs: number): boolean;
598
796
  bloomMightContain(key: string): boolean;
599
797
  bloomStats(): {
600
798
  bitsSet: number;
@@ -679,6 +877,8 @@ declare class DiskTier {
679
877
  delete(key: string): void;
680
878
  /** Purge all expired entries. Returns number deleted. */
681
879
  purgeExpired(): number;
880
+ /** Delete every file in the disk cache. Returns the count deleted. */
881
+ clear(): number;
682
882
  get stats(): {
683
883
  files: number;
684
884
  sizeKB: number;
@@ -715,4 +915,4 @@ declare class WasmBloomFilter {
715
915
  get maxCapacity(): number;
716
916
  }
717
917
 
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 };
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 };