tricache 0.3.1 → 0.5.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
@@ -1,1063 +1,25 @@
1
1
  /**
2
- * tricache — shared types and interfaces
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
- }
22
- /** Minimal logger interface — plug in any logger (pino, winston, console, etc.) */
23
- interface ILogger {
24
- debug(msg: string, meta?: Record<string, unknown>): void;
25
- info(msg: string, meta?: Record<string, unknown>): void;
26
- warn(msg: string, meta?: Record<string, unknown>): void;
27
- error(msg: string, meta?: Record<string, unknown>, err?: Error): void;
28
- }
29
- /** Default no-op logger — swap out via CacheService options */
30
- declare const consoleLogger: ILogger;
31
- /**
32
- * Reason passed to the `onEviction` callback.
33
- * - `'capacity'` — L1 over-capacity; evicted during a `set()` call
34
- * - `'category'` — Per-category limit exceeded
35
- * - `'rebalance'` — `cache.rebalance()` was called
36
- * - `'oom'` — OOM guard emergency eviction
37
- * - `'ttl'` — Entry expired during periodic cleanup
38
- * - `'manual'` — Explicit `cache.delete()` call
39
- */
40
- type EvictionReason = 'capacity' | 'category' | 'rebalance' | 'oom' | 'ttl' | 'manual';
41
- /** Per-tier latency returned by `cache.ping()`. */
42
- interface CachePingResult {
43
- /** L1 RAM check latency in milliseconds */
44
- l1: number;
45
- /** L1.5 disk stats access in milliseconds */
46
- disk: number;
47
- /** L2 Redis PING round-trip in milliseconds, or `null` when Redis is disabled */
48
- l2: number | null;
49
- }
50
- /** Priority levels for L1 eviction — higher = less likely to be evicted */
51
- declare enum CachePriority {
52
- LOW = 1,// Easily regenerated (analytics, reports)
53
- NORMAL = 2,// General data
54
- HIGH = 3,// Frequently accessed (profiles, config)
55
- CRITICAL = 4
56
- }
57
- /** Internal representation of a single cache entry in the L1 Map */
58
- interface SmartCacheEntry {
59
- /** msgpackr-packed binary payload — used for disk spill and snapshot serialization */
60
- data: Buffer;
61
- /**
62
- * Deserialized JS value, cached at write time so hot reads skip the unpack step entirely.
63
- * Undefined for entries restored from disk/snapshot (populated lazily on first access).
64
- * NOTE: returned by reference — callers should treat the value as immutable.
65
- */
66
- value?: unknown;
67
- /** always true for entries written by the current code;
68
- * may be false in legacy snapshots/disk files — handled transparently on import */
69
- isCompressed: boolean;
70
- /** Hard expiry — entry is deleted after this timestamp */
71
- expiresAt: number;
72
- /** SWR soft expiry — serve stale + revalidate in background when past this */
73
- staleAt?: number;
74
- /** Exact byte size of the stored value */
75
- size: number;
76
- /** Access count (LFU numerator) */
77
- hits: number;
78
- /** Last access timestamp (LRU comparator) */
79
- lastAccess: number;
80
- /** Eviction priority */
81
- priority: CachePriority;
82
- }
83
- /** Returned by SmartMemoryCache.get() — distinguishes "cached null" from a real miss */
84
- interface CacheHit {
85
- value: unknown;
86
- /** true = past soft TTL (staleAt) but within hard expiry → SWR path */
87
- isStale: boolean;
88
- }
89
- /** On-disk entry shape (mirrors SmartCacheEntry — Uint8Array accepted for msgpack round-trips;
90
- * legacy disk files written by older versions may have a JSON string in data) */
91
- interface DiskCacheEntry {
92
- data: string | Buffer | Uint8Array;
93
- isCompressed: boolean;
94
- expiresAt: number;
95
- staleAt?: number;
96
- size: number;
97
- hits: number;
98
- lastAccess: number;
99
- priority: number;
100
- }
101
- /**
102
- * Snapshot of runtime metrics for a CacheService instance.
103
- * Returned by `CacheService.metrics()` and passed to the `onMetrics` callback.
104
- * Convert to Prometheus text with `CacheService.toPrometheusText(metrics)`.
105
- */
106
- interface CacheMetrics {
107
- /** Configured namespace (empty string = no namespace) */
108
- namespace: string;
109
- /** Milliseconds since the CacheService instance was constructed */
110
- uptimeMs: number;
111
- gets: {
112
- total: number;
113
- l1Hits: number;
114
- /** Fraction of gets served from L1 RAM cache (0–1) */
115
- l1HitRate: number;
116
- diskHits: number;
117
- /** Fraction of gets served from L1.5 disk tier (0–1) */
118
- diskHitRate: number;
119
- l2Hits: number;
120
- /** Fraction of gets served from L2 Redis (0–1) */
121
- l2HitRate: number;
122
- /** fetchFn calls (cache misses that fell through to the DB) */
123
- fetches: number;
124
- /** Fraction of gets that called fetchFn (0–1) */
125
- fetchRate: number;
126
- /** Concurrent get() calls deduplicated by the stampede guard */
127
- stampedePrevented: number;
128
- };
129
- sets: {
130
- total: number;
131
- };
132
- deletes: {
133
- total: number;
134
- };
135
- revalidations: {
136
- total: number;
137
- };
138
- bloom: {
139
- /** Total bloom-filter checks (get() calls that passed prefix filter) */
140
- checksTotal: number;
141
- /**
142
- * Times the filter said "might contain" but the key was absent in L1.
143
- * A high rate suggests the bloom filter capacity needs increasing.
144
- */
145
- falsePositives: number;
146
- /** falsePositives / checksTotal (0–1; ideal < 0.01) */
147
- falsePositiveRate: number;
148
- };
149
- compression: {
150
- entriesCompressed: number;
151
- entriesUncompressed: number;
152
- /** Approximate bytes saved by msgpackr vs raw JSON */
153
- bytesSaved: number;
154
- };
155
- /** Pub/Sub invalidation backplane statistics */
156
- backplane: {
157
- enabled: boolean;
158
- /** Invalidation messages published to other instances */
159
- sent: number;
160
- /** Invalidation messages received from other instances */
161
- received: number;
162
- /** Own messages silently skipped (prevents double-eviction) */
163
- skipped: number;
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
- };
170
- /** OOM guard statistics */
171
- oom: {
172
- enabled: boolean;
173
- /** Number of emergency L1 eviction rounds triggered */
174
- evictions: number;
175
- /** Timestamp of the most recent OOM eviction, or null */
176
- lastTriggeredAt: number | null;
177
- };
178
- l1: {
179
- entries: number;
180
- sizeBytes: number;
181
- maxBytes: number;
182
- };
183
- disk: {
184
- files: number;
185
- sizeKB: number;
186
- maxKB: number;
187
- };
188
- }
189
- /** Per-category memory limits for L1 */
190
- interface CategoryLimit {
191
- maxEntries: number;
192
- maxSizeBytes: number;
193
- }
194
- /**
195
- * Options accepted by CacheService.create()
196
- *
197
- * All fields are optional — sensible defaults are used when omitted.
198
- */
199
- interface CacheOptions {
200
- /**
201
- * Plug in your own logger (pino, winston, bunyan, …).
202
- * Defaults to a minimal console logger that only prints warn/error.
203
- */
204
- logger?: ILogger;
205
- /** Max total bytes held in L1 RAM cache. Default: 200 MB */
206
- l1MaxBytes?: number;
207
- /** Max total entries in L1. Default: 2000 */
208
- l1MaxEntries?: number;
209
- /**
210
- * Per-category limits keyed by the key prefix (e.g. `'org:'`).
211
- * Merged over the built-in defaults.
212
- */
213
- categoryLimits?: Record<string, CategoryLimit>;
214
- /**
215
- * Key prefixes that are never written to disk snapshots or the disk tier.
216
- * Default: ['auth:', 'session:', 'mfa:', 'rate_limit:']
217
- */
218
- forbiddenSnapshotPrefixes?: string[];
219
- /** Directory used for L1.5 disk-spill files. Default: os.tmpdir()/tricache-disk */
220
- diskCacheDir?: string;
221
- /** Max total bytes for the disk tier. Default: 500 MB */
222
- diskMaxBytes?: number;
223
- /** Max bytes for a single disk entry. Default: 10 MB */
224
- diskEntryMaxBytes?: number;
225
- /**
226
- * Redis/Valkey hostname (no `redis://` prefix).
227
- * Falls back to the `REDIS_HOST` environment variable.
228
- * When neither is provided, L2 is disabled.
229
- */
230
- redisHost?: string;
231
- /** Redis port. Default: 6379 */
232
- redisPort?: number;
233
- /**
234
- * Whether to enable TLS for the Redis connection. Default: true in production,
235
- * false otherwise.
236
- */
237
- redisTls?: boolean;
238
- /**
239
- * Set to `true` to disable L2 Redis entirely (e.g. when running single-process
240
- * services that don't need distributed caching). Default: false in production,
241
- * true in development.
242
- */
243
- disableRedis?: boolean;
244
- /**
245
- * Base64-encoded 32-byte AES-256-GCM key for encrypting L2 (Redis) values and
246
- * disk-tier files at rest. Falls back to `CACHE_ENCRYPTION_KEY` env var.
247
- * If not provided in production, a warning is logged and data is stored plaintext.
248
- */
249
- encryptionKey?: string;
250
- /**
251
- * Encryption algorithm used for L2 (Redis) values and disk-tier files.
252
- * - `'aes-256-gcm'` — default. 32-byte key. Authenticated encryption (AEAD).
253
- * - `'aes-128-gcm'` — 16-byte key. ~10% faster on non-AES-NI hardware. AEAD.
254
- * - `'xor'` — XOR obfuscation ONLY. NOT cryptographic security.
255
- * Any key length (minimum 16 bytes recommended).
256
- * Use for dev environments or non-sensitive data only.
257
- * Default: `'aes-256-gcm'`
258
- */
259
- encryptionMode?: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
260
- /**
261
- * Fallback encryption key for zero-downtime key rotation.
262
- * On every read, tricache tries the current `encryptionKey` first.
263
- * If decryption fails (wrong key), it retries with `previousEncryptionKey`.
264
- * All writes always use the current `encryptionKey`.
265
- * Remove this field once you are confident all data has been re-encrypted.
266
- */
267
- previousEncryptionKey?: string;
268
- /** Encryption mode that was used with `previousEncryptionKey`. Defaults to `encryptionMode`. */
269
- previousEncryptionMode?: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
270
- /**
271
- * Path where the cold-start snapshot is written on SIGTERM/SIGINT and loaded
272
- * on startup. Default: os.tmpdir()/tricache-snapshot.msgpack
273
- */
274
- snapshotPath?: string;
275
- /**
276
- * Max age (ms) of a snapshot file before it is rejected. Default: 2 hours
277
- */
278
- snapshotMaxAgeMs?: number;
279
- /**
280
- * Optional namespace prefix for all cache keys.
281
- *
282
- * When set, every key is transparently stored as `${namespace}:${key}` in
283
- * L1, L1.5 (disk), and L2 (Redis). This enables:
284
- * - **Multi-tenant isolation**: `CacheService.create({ namespace: 'org_abc' })`
285
- * — tenants sharing the same Redis instance or disk dir are fully isolated.
286
- * - **Environment separation**: `CacheService.create({ namespace: 'staging' })`
287
- * - **Service-level scoping**: microservices sharing one Redis without key collisions.
288
- *
289
- * Consumers never see the prefix — `get('user:1')` behaves identically
290
- * whether namespaced or not. Glob deletes (`delete('user:*')`) automatically
291
- * scope to the namespace.
292
- *
293
- * The process-level singleton, disk cache directory, and cold-start snapshot
294
- * path are all scoped per namespace, so two `CacheService.create()` calls
295
- * with different namespaces return completely independent instances.
296
- *
297
- * Default: `''` (no prefix)
298
- */
299
- namespace?: string;
300
- /**
301
- * Seconds to extend a stale SWR entry's life when background revalidation fails.
302
- * Without this, a failed revalidation leaves the entry stale until its hard TTL
303
- * expires, after which the next caller blocks. With `staleIfError`, tricache bumps
304
- * the expiry by this many seconds on every failed revalidation, keeping the stale
305
- * value available while the underlying service is degraded.
306
- * Default: `0` (disabled — entry expires normally on revalidation failure).
307
- */
308
- staleIfError?: number;
309
- /**
310
- * Called after every L1 eviction. Receives the raw (namespaced) key and the reason.
311
- * Useful for diagnosing cache pressure and tuning `categoryLimits`.
312
- */
313
- onEviction?: (key: string, reason: EvictionReason) => void;
314
- /**
315
- * Human-readable name for this CacheService instance. Added as an `instance` label
316
- * to all Prometheus metrics emitted by `CacheService.toPrometheusText()`.
317
- * Required when multiple CacheService instances share a process — without it,
318
- * metric names from different instances collide.
319
- * Default: `''` (no label).
320
- */
321
- instanceName?: string;
322
- /**
323
- * Controls whether writes are propagated to L2 (Redis).
324
- * - `'read-write'` (default): read from and write to L2.
325
- * - `'read-only'`: read from L2 but never write, delete, or expire keys in Redis.
326
- * Use for shared read replicas or external Redis clusters you do not own.
327
- */
328
- l2WriteMode?: 'read-write' | 'read-only';
329
- /**
330
- * Enable Redis Pub/Sub invalidation backplane so every running instance
331
- * evicts a key from its L1 when any peer calls `set()` or `delete()`.
332
- *
333
- * Gives you sub-microsecond in-process cache speed with cluster-wide
334
- * consistency across all your app servers.
335
- *
336
- * Default: `true` (auto-activates when Redis is available).
337
- * Set to `false` for single-process services or eventual-consistency scenarios.
338
- */
339
- invalidationBackplane?: boolean;
340
- /**
341
- * Enable the GC-aware OOM guard. When heap utilisation crosses
342
- * `oomHeapThreshold`, a fraction of the coldest L1 entries are
343
- * emergency-evicted to L1.5 disk, preventing Node.js OOM crashes inside
344
- * Docker/Kubernetes containers with tight memory limits.
345
- *
346
- * Default: `true`
347
- */
348
- oomProtection?: boolean;
349
- /**
350
- * Heap-used / heap-total ratio that triggers emergency eviction.
351
- * Default: `0.85` (85 %)
352
- */
353
- oomHeapThreshold?: number;
354
- /** Milliseconds between heap-pressure checks. Default: 10 000 ms (10 s) */
355
- oomCheckIntervalMs?: number;
356
- /** Fraction of L1 entries to evict per OOM round. Default: `0.20` (20 %) */
357
- oomEvictPercent?: number;
358
- /**
359
- * Callback invoked periodically with a `CacheMetrics` snapshot.
360
- * Wire up to OpenTelemetry, Prometheus push gateway, Datadog, etc.
361
- *
362
- * @example
363
- * onMetrics: (m) => statsd.gauge('cache.l1_hit_rate', m.gets.l1HitRate)
364
- */
365
- onMetrics?: (metrics: CacheMetrics) => void;
366
- /** How often the `onMetrics` callback fires (ms). Default: 60 000 ms */
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;
403
- }
404
-
405
- /**
406
- * CacheService — three-tier cache with stampede prevention and SWR.
2
+ * tricache — three-tier cache for Node.js
407
3
  *
408
- * Architecture:
409
- * L1 → SmartMemoryCache (in-process RAM, always active, adaptive eviction)
410
- * L1.5→ DiskTier (NVMe overflow, evicted L1 entries, 2–100 µs)
411
- * L2 → Redis / Valkey (distributed, production-only by default, survives restarts)
412
- * DB → your fetchFunction (cache miss path)
4
+ * L1 (RAM) → L1.5 (disk) → L2 (Redis/Valkey) → your fetch function
413
5
  *
414
- * Key features:
415
- * - Thundering-herd / cache-stampede prevention (inflight Promise registry)
416
- * - Stale-While-Revalidate (serve stale instantly + revalidate in background)
417
- * - AES-256-GCM encryption for L2 and disk data at rest
418
- * - Cold-start snapshot: L1 is persisted to disk on SIGTERM and restored on startup
419
- * - Process-level singleton (globalThis) survives hot reloads in frameworks like Next.js
420
- * - Periodic cleanup of expired entries every 5 minutes
421
- */
422
-
423
- declare class CacheService {
424
- private readonly logger;
425
- private readonly enc;
426
- private readonly l1;
427
- private readonly disk;
428
- private readonly opts;
429
- /** Pre-computed once — opts.namespace never changes after construction. */
430
- private readonly _namespace;
431
- /** Pre-computed once — disableRedis and redisHost never change after construction. */
432
- private readonly _redisDisabled;
433
- private readonly inflight;
434
- private readonly revalidating;
435
- private readonly _l1Counters;
436
- /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
437
- private readonly tagIndex;
438
- private redis;
439
- private redisConnecting;
440
- private readonly cb;
441
- private snapshotLoaded;
442
- private cleanupInterval;
443
- private oomInterval;
444
- private metricsInterval;
445
- private _shutdownHandler;
446
- private readonly instanceId;
447
- private readonly backplaneChannel;
448
- private subClient;
449
- private readonly counters;
450
- constructor(options?: CacheOptions);
451
- /**
452
- * Get (or create) the process-level singleton CacheService instance.
453
- *
454
- * Options are only applied on first call — subsequent calls return the
455
- * existing instance regardless of options passed.
456
- *
457
- * When `namespace` is set the singleton is keyed by namespace, so two calls
458
- * with different namespaces return independent instances.
459
- */
460
- static create(options?: CacheOptions): CacheService;
461
- /**
462
- * Async factory — accepts a Promise that resolves to CacheOptions.
463
- * Useful when config is fetched from a secret store at startup.
464
- *
465
- * @example
466
- * const cache = await CacheService.createAsync(fetchSecrets());
467
- */
468
- static createAsync(options: Promise<CacheOptions> | CacheOptions): Promise<CacheService>;
469
- /** Replace the singleton (useful in tests). */
470
- static reset(options?: CacheOptions): CacheService;
471
- /** Derive the globalThis key for a given set of options. */
472
- private static globalKey;
473
- /**
474
- * Prepend the configured namespace to a raw cache key.
475
- * Returns the key unchanged when namespace is empty.
476
- *
477
- * This is the only place the namespace prefix is applied — callers always
478
- * receive and provide un-prefixed keys in the public API.
479
- */
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;
485
- private initBackplane;
486
- /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
487
- _handleBackplaneMessage(message: string): void;
488
- private publishInvalidation;
489
- private getRedis;
490
- writeSnapshot(altPath?: string): void;
491
- loadSnapshot(): void;
492
- /**
493
- * Get a value from cache, or fetch and cache it.
494
- *
495
- * @param cacheKey - Unique key identifying this value
496
- * @param fetchFn - Called on a cache miss; its return value is cached and returned
497
- * @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
498
- * @param opts.priority - Override the auto-inferred eviction priority
499
- * @param opts.swr - Stale-While-Revalidate grace seconds. When > 0 the entry stays
500
- * alive for this many extra seconds after TTL; callers get stale data
501
- * instantly while a background refresh runs. Default: 0 (disabled).
502
- */
503
- get<T>(cacheKey: string, fetchFn: () => Promise<T>, ttlSeconds?: number, opts?: {
504
- priority?: CachePriority;
505
- swr?: number;
506
- }): Promise<T>;
507
- private _revalidate;
508
- /** Explicitly write a value into L1 (+ L2 in production). */
509
- set<T>(cacheKey: string, data: T, ttlSeconds?: number, priority?: CachePriority, opts?: {
510
- tags?: string[];
511
- }): Promise<void>;
512
- /**
513
- * Delete one key or a glob pattern (supports `*` wildcard).
514
- *
515
- * @example
516
- * await cache.delete('user:abc:profile'); // exact key
517
- * await cache.delete('user:abc:*'); // all keys for user abc
518
- */
519
- delete(cacheKey: string): Promise<void>;
520
- /**
521
- * Atomically increment a counter in Redis. Returns the new value.
522
- * Returns 0 if Redis is disabled (safe fallback — rate limiting won't block in dev).
523
- */
524
- increment(cacheKey: string, ttlSeconds?: number): Promise<number>;
525
- /**
526
- * Flush all cached entries, or only those whose key starts with `prefix`.
527
- *
528
- * @example
529
- * await cache.clear(); // flush everything
530
- * await cache.clear('user:abc'); // flush all keys for one user
531
- */
532
- clear(prefix?: string): Promise<void>;
533
- /**
534
- * Evict L1 entries that violate the current category or global capacity limits.
535
- * Useful after a write burst or after adding stricter `categoryLimits`.
536
- * Returns the number of entries evicted.
537
- */
538
- rebalance(): number;
539
- /**
540
- * Return the remaining TTL in seconds for a key currently in L1.
541
- * Returns null if the key is absent from L1 or has already expired.
542
- * Only reflects L1 state — does not query Redis or disk.
543
- */
544
- ttl(cacheKey: string): number | null;
545
- /**
546
- * Return true if the key exists in L1 and has not expired.
547
- * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
548
- */
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]>;
573
- /**
574
- * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
575
- * Returns `false` if the key is absent or already expired.
576
- *
577
- * @param newTtlSeconds - The new TTL from now, in seconds.
578
- */
579
- touch(cacheKey: string, newTtlSeconds: number): Promise<boolean>;
580
- /**
581
- * Return the cached value from L1 **only if it is fresh** (not in the SWR grace window).
582
- * Returns `null` when the key is absent, expired, or stale — without triggering a fetch.
583
- *
584
- * @example
585
- * const fresh = cache.getIfFresh('user:123');
586
- * if (fresh !== null) return fresh; // serve from L1, no network hop
587
- */
588
- getIfFresh<T = unknown>(cacheKey: string): T | null;
589
- /**
590
- * Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
591
- * Preserves input ordering. Uses inflight coalescing per key.
592
- *
593
- * @param keys - Array of cache keys.
594
- * @param fetchFn - Called with only the keys that missed L1.
595
- * @param ttl - TTL in seconds for newly fetched values.
596
- */
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>;
635
- /**
636
- * Invalidate all keys associated with a tag.
637
- * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
638
- *
639
- * @example
640
- * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
641
- * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
642
- */
643
- invalidateTag(tag: string): Promise<void>;
644
- /**
645
- * Measure L1 / disk / Redis latency.
646
- * Useful for health checks and dashboards.
647
- *
648
- * @returns `{ l1, disk, l2 }` latencies in milliseconds.
649
- * `l2` is `null` when Redis is disabled.
650
- */
651
- ping(): Promise<CachePingResult>;
652
- /**
653
- * Export all live L1 entries to Redis via a single pipeline.
654
- * Useful for warming a new Redis instance or for zero-downtime failover.
655
- * Returns the number of keys written.
656
- */
657
- drainToL2(): Promise<number>;
658
- stats(): {
659
- l1: {
660
- entries: number;
661
- sizeBytes: number;
662
- sizeKB: number;
663
- categories: Record<string, {
664
- entries: number;
665
- hits: number;
666
- }>;
667
- bloom: {
668
- checks: number;
669
- falsePositives: number;
670
- };
671
- compression: {
672
- compressed: number;
673
- uncompressed: number;
674
- bytesSaved: number;
675
- };
676
- };
677
- disk: {
678
- files: number;
679
- sizeKB: number;
680
- maxKB: number;
681
- };
682
- };
683
- /** Return a full metrics snapshot. */
684
- metrics(): CacheMetrics;
685
- /**
686
- * Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
687
- * Paste the result into your `/metrics` endpoint.
688
- *
689
- * @param m - Snapshot returned by `cache.metrics()`
690
- * @param prefix - Metric name prefix. Default: `"tricache"`
691
- */
692
- static toPrometheusText(m: CacheMetrics, prefix?: string, instanceName?: string): string;
693
- /** Close Redis connections and stop all background timers. */
694
- destroy(): Promise<void>;
695
- }
696
-
697
- /**
698
- * Encryption / obfuscation for L2 (Redis) values and disk snapshots at rest.
699
- *
700
- * Four modes are supported via the `encryptionMode` CacheOption:
701
- *
702
- * ┌──────────────┬────────────┬──────────────────────────────────────────────────────────────┐
703
- * │ Mode │ Key bytes │ Notes │
704
- * ├──────────────┼────────────┼──────────────────────────────────────────────────────────────┤
705
- * │ aes-256-gcm │ 32 │ Default. Authenticated encryption (AEAD). │
706
- * │ aes-128-gcm │ 16 │ ~15% faster than AES-256. AEAD. │
707
- * │ aes-128-ctr │ 16 │ Fastest cipher. AES-NI keystream, no auth tag. │
708
- * │ │ │ Use when integrity is guaranteed elsewhere (TLS, HMAC, etc.). │
709
- * │ xor │ any (≥ 1) │ XOR obfuscation ONLY — NOT cryptographic. │
710
- * │ │ │ Use only for dev or non-sensitive data. │
711
- * └──────────────┴────────────┴──────────────────────────────────────────────────────────────┘
712
- *
713
- * Key generation:
714
- * AES-256 (32 B): node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
715
- * AES-128 (16 B): node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
716
- * CTR (16 B): node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
717
- * XOR (any len): node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
718
- *
719
- * Redis envelope formats:
720
- * enc:v1:<base64(IV[12]|Tag[16]|CT)> ← AES-256-GCM
721
- * a128:v1:<base64(IV[12]|Tag[16]|CT)> ← AES-128-GCM
722
- * ctr:v1:<base64(IV[16]|CT)> ← AES-128-CTR (no auth tag)
723
- * xor:v1:<base64(key⊕data)> ← XOR (self-inverse)
724
- *
725
- * Disk envelope formats:
726
- * TRIC1ENC | IV[12] | Tag[16] | CT[N] ← AES-256-GCM
727
- * TRIC1128 | IV[12] | Tag[16] | CT[N] ← AES-128-GCM
728
- * TRIC1CTR | IV[16] | CT[N] ← AES-128-CTR (no auth tag)
729
- * TRIC1XOR | key⊕data[N] ← XOR
730
- */
731
-
732
- /** Encryption algorithm used for L2 (Redis) values and disk-tier files. */
733
- type EncryptionMode = 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
734
- declare class CacheEncryption {
735
- private _key;
736
- private readonly _mode;
737
- private _prevKey;
738
- private _prevMode;
739
- private readonly _ivPool;
740
- private _ivOffset;
741
- /** Return the next unique 12-byte IV slice from the pre-allocated GCM pool. */
742
- private _nextIV;
743
- private readonly _ctrIvPool;
744
- private _ctrIvOffset;
745
- /** Return the next unique 16-byte IV slice from the pre-allocated CTR pool. */
746
- private _nextCtrIV;
747
- /**
748
- * XOR `data` with the key, cycling through key bytes.
749
- * Self-inverse: _xorBuffer(_xorBuffer(x)) === x.
750
- *
751
- * Fast path: Uint32Array views over the existing Buffer memory — zero copy,
752
- * no method-call overhead. V8 JITs `out32[i] = data32[i] ^ key32[...]`
753
- * to a single `XOR r32, r32` instruction. Requires 4-byte-aligned byteOffsets,
754
- * which Node.js guarantees (pool rounds up to 8 bytes; direct allocs to page).
755
- *
756
- * WARNING: XOR is NOT cryptographic. It provides obfuscation only.
757
- */
758
- private _xorBuffer;
759
- constructor(keyBase64: string | undefined, logger: ILogger, mode?: EncryptionMode, previousKeyBase64?: string, previousMode?: EncryptionMode);
760
- get isEnabled(): boolean;
761
- /**
762
- * Encrypt a string for Redis storage.
763
- * Returns a mode-prefixed base64 string when a key is configured;
764
- * otherwise returns the original string unchanged (backward-compatible).
765
- */
766
- encrypt(plaintext: string): string;
767
- /**
768
- * Decrypt a Redis value.
769
- * Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
770
- * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
771
- */
772
- decrypt(value: string): string;
773
- private _decryptWithKey;
774
- /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
775
- encryptBuffer(data: Buffer): Buffer;
776
- /**
777
- * Decrypt a raw Buffer from disk/snapshot.
778
- * Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
779
- * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
780
- */
781
- decryptBuffer(data: Buffer): Buffer;
782
- private _decryptBufferWithKey;
783
- }
784
-
785
- /**
786
- * SmartMemoryCache — L1 in-process cache with adaptive LFU/LRU hybrid eviction.
787
- *
788
- * Features:
789
- * - WASM Bloom filter for O(k) guaranteed-miss detection (pure-JS fallback)
790
- * - msgpackr compression for entries ≥ 512 bytes
791
- * - Category-aware capacity limits (prevents any single key prefix from monopolising RAM)
792
- * - Priority-weighted adaptive eviction (LFU × LRU × priority score)
793
- * - Stale-While-Revalidate soft-expiry support (isStale flag on get())
794
- * - L1.5 disk-spill on eviction — evicted entries are sent to DiskTier before deletion
795
- * - Periodic cleanup of hard-expired entries + bloom filter rebuild
796
- * - Process-level singleton via globalThis (survives Next.js hot reloads)
797
- */
798
-
799
- interface SmartMemoryCacheOptions {
800
- maxBytes: number;
801
- maxEntries: number;
802
- categories: Record<string, CategoryLimit>;
803
- diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
804
- onEviction?: (key: string, reason: EvictionReason) => void;
805
- logger: ILogger;
806
- }
807
- declare class SmartMemoryCache {
808
- private readonly cache;
809
- private readonly opts;
810
- private bloom;
811
- /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
812
- private readonly categoryPrefixes;
813
- /** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
814
- private readonly sketch;
815
- private totalSize;
816
- private categoryCount;
817
- private categorySize;
818
- /** Per-category key sets — enables O(catSize) Phase-1 reservoir sampling without an O(N) scan. */
819
- private categoryKeys;
820
- private bloomChecks;
821
- private bloomFalsePos;
822
- private compressions;
823
- private categoryHits;
824
- /** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
825
- private _bloomDirtyCount;
826
- constructor(opts: SmartMemoryCacheOptions, existing?: Map<string, SmartCacheEntry>);
827
- private recalculateStats;
828
- private getCategory;
829
- private getCategoryLimit;
830
- private _delete;
831
- private ensureCapacity;
832
- private score;
833
- /**
834
- * Rebuild the bloom filter when phantom bits from deleted/expired keys have
835
- * saturated the filter past its ~1 % FP capacity.
836
- *
837
- * Trigger: (insertions − live entries) > maxCapacity
838
- *
839
- * Using the phantom count (insertions − cache.size) instead of raw insertions
840
- * prevents an O(cache.size) rebuild from re-firing on every set() when the
841
- * cache holds more entries than the filter's rated capacity — which would
842
- * stall the write path entirely.
843
- *
844
- * After rebuild: insertions = cache.size → phantoms = 0 → no immediate re-trigger.
845
- */
846
- private maybeRebuildBloom;
847
- private smartEvict;
848
- get(key: string): CacheHit | null;
849
- set(key: string, data: unknown, ttlMs: number, priority?: CachePriority, staleAt?: number): void;
850
- delete(key: string): boolean;
851
- private keysMatchingPattern;
852
- deletePattern(pattern: string): number;
853
- /** Flush all entries, or only those whose key starts with `prefix`. */
854
- clear(prefix?: string): number;
855
- /**
856
- * Evict entries that violate current category or global limits.
857
- * Returns the number of entries evicted.
858
- */
859
- rebalance(): number;
860
- /**
861
- * Return remaining TTL in seconds for a key in L1, or null if absent/expired.
862
- * Only reflects L1 state — does not query Redis or disk.
863
- */
864
- ttl(key: string): number | null;
865
- /**
866
- * Forcibly evict the coldest `pct` fraction of non-CRITICAL L1 entries,
867
- * spilling each to L1.5 disk. Called by the OOM guard when heap pressure
868
- * exceeds the configured threshold.
869
- *
870
- * @param pct - Fraction to evict (0–1), e.g. 0.2 = 20 %
871
- * @returns Number of entries evicted
872
- */
873
- evictPercentage(pct: number): number;
874
- cleanup(): number;
875
- exportEntries(forbiddenPrefixes: readonly string[]): Array<{
876
- key: string;
877
- entry: SmartCacheEntry;
878
- }>;
879
- importEntries(entries: Array<{
880
- key: string;
881
- entry: SmartCacheEntry;
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>;
901
- get size(): number;
902
- get memoryUsage(): number;
903
- getStats(): {
904
- entries: number;
905
- sizeBytes: number;
906
- sizeKB: number;
907
- categories: Record<string, {
908
- entries: number;
909
- hits: number;
910
- }>;
911
- bloom: {
912
- checks: number;
913
- falsePositives: number;
914
- };
915
- compression: {
916
- compressed: number;
917
- uncompressed: number;
918
- bytesSaved: number;
919
- };
920
- };
921
- /**
922
- * Return the raw cache entry for a key, or `undefined` if absent/expired.
923
- * Does NOT count as a hit or perform SWR logic.
924
- */
925
- getEntry(key: string): SmartCacheEntry | undefined;
926
- /**
927
- * Return true if the key exists in L1 and has not expired.
928
- * Uses the bloom filter as a fast negative check.
929
- */
930
- has(key: string): boolean;
931
- /**
932
- * Extend the TTL of an existing key. Returns `false` if the key is absent or expired.
933
- * @param newTtlMs - New TTL from now, in milliseconds.
934
- */
935
- touch(key: string, newTtlMs: number): boolean;
936
- /**
937
- * Add additional milliseconds to a key's existing expiry (for stale-if-error).
938
- * Returns `false` if the key is absent or already expired.
939
- */
940
- bumpExpiry(key: string, additionalMs: number): boolean;
941
- bloomMightContain(key: string): boolean;
942
- bloomStats(): {
943
- bitsSet: number;
944
- fillFactor: number;
945
- } | {
946
- bitsSet: number;
947
- fillFactor: number;
948
- };
949
- }
950
-
951
- /**
952
- * DiskTier — L1.5 NVMe-fast overflow cache between L1 RAM and L2 Redis/DB.
6
+ * Quick start:
7
+ * import { CacheService, CachePriority } from 'tricache';
953
8
  *
954
- * When L1 evicts an entry it is spilled here instead of being discarded.
955
- * On a subsequent L1 miss the entry is promoted back (2–100 µs disk read
956
- * vs 10–100 ms DB round-trip).
9
+ * const cache = CacheService.create({ redisHost: 'localhost' });
957
10
  *
958
- * Storage:
959
- * - Directory: configurable (default os.tmpdir()/tricache-disk)
960
- * - Filename: SHA-256(key) hex — bounded, URL-safe, no key injection
961
- * - Format: msgpack({ version, key, entry, writtenAt })
962
- * - Mode: 0o600 — owner read/write only
11
+ * const user = await cache.get(
12
+ * `user:${userId}`,
13
+ * () => db.users.findById(userId),
14
+ * 300, // 5-minute TTL
15
+ * );
963
16
  *
964
- * Encryption: same AES-256-GCM as L2 when CacheEncryption is configured.
17
+ * await cache.delete(`user:${userId}`);
965
18
  */
966
-
967
- interface DiskTierOptions {
968
- dir: string;
969
- maxBytes: number;
970
- entryMaxBytes: number;
971
- forbiddenPrefixes: readonly string[];
972
- encryptionKey?: Buffer | null;
973
- logger: ILogger;
974
- }
975
- declare class DiskTier {
976
- private readonly opts;
977
- private dirReady;
978
- private diskUsageBytes;
979
- private usageCounted;
980
- private fileCount;
981
- constructor(opts: DiskTierOptions);
982
- private ensureDir;
983
- private ensureUsageCounted;
984
- /**
985
- * Map a cache key to its on-disk path.
986
- *
987
- * Files are sharded into two-character hex prefix subdirectories to avoid
988
- * putting thousands of flat files into a single directory node — which
989
- * degrades EXT4/NTFS performance at scale.
990
- *
991
- * key → SHA-256 hex e3b0c442...
992
- * path → {dir}/e3/e3b0c442...
993
- */
994
- private keyToPath;
995
- /**
996
- * Recursively list all cache file paths across the 2-level sharded subdirs.
997
- * Top-level entries that are not directories are skipped (e.g. stale flat
998
- * files written by older versions).
999
- */
1000
- private walkCacheFiles;
1001
- private isForbidden;
1002
- private encrypt;
1003
- private decrypt;
1004
- /**
1005
- * Spill an evicted L1 entry to disk.
1006
- *
1007
- * Returns a Promise that resolves when the file is durably written. Callers
1008
- * that treat the spill as fire-and-forget should do:
1009
- * `void disk.save(key, entry)`
1010
- *
1011
- * Implementation notes:
1012
- * - pack() + AES-256-GCM encrypt run synchronously — both are pure CPU,
1013
- * sub-millisecond for entries up to diskEntryMaxBytes, and do not block
1014
- * on any external resource.
1015
- * - The actual write syscall (mkdir + writeFile) is async via fs.promises,
1016
- * so the Node.js event loop is never stalled waiting for disk I/O.
1017
- */
1018
- save(key: string, entry: DiskCacheEntry): Promise<void>;
1019
- /** Load a key from disk, or return null on miss/expiry/corruption. */
1020
- load(key: string): DiskCacheEntry | null;
1021
- /** Explicitly delete a key from disk (cache invalidation). */
1022
- delete(key: string): void;
1023
- /** Purge all expired entries. Returns number deleted. */
1024
- purgeExpired(): number;
1025
- /** Delete every file in the disk cache. Returns the count deleted. */
1026
- clear(): number;
1027
- get stats(): {
1028
- files: number;
1029
- sizeKB: number;
1030
- maxKB: number;
1031
- };
1032
- }
1033
-
1034
- declare class WasmBloomFilter {
1035
- private readonly exports;
1036
- private readonly mem;
1037
- private readonly encoder;
1038
- private readonly numBits;
1039
- /** Pre-computed — k and numBits are fixed constants; no need to recalculate on every probe. */
1040
- private readonly _maxCapacity;
1041
- /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
1042
- private _insertionCount;
1043
- constructor();
1044
- private writeKey;
1045
- add(key: string): void;
1046
- mightContain(key: string): boolean;
1047
- reset(): void;
1048
- rebuild(keys: Iterable<string>): void;
1049
- get stats(): {
1050
- bitsSet: number;
1051
- fillFactor: number;
1052
- };
1053
- /** Number of add() calls since last reset/rebuild. */
1054
- get insertions(): number;
1055
- /**
1056
- * Maximum safe insertions before false-positive rate exceeds ~1 %.
1057
- * Exact formula for k=7 hash rounds, m=100 000 bits:
1058
- * n_max = -m * ln(1 - p^(1/k)) / k ≈ 18 169
1059
- */
1060
- get maxCapacity(): number;
1061
- }
1062
-
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 };
19
+ export { CacheService } from './cache-service';
20
+ export { CacheEncryption, type EncryptionMode } from './encryption';
21
+ export { SmartMemoryCache } from './smart-memory-cache';
22
+ export { DiskTier } from './disk-tier';
23
+ export { WasmBloomFilter } from './wasm/bloom-filter-wasm';
24
+ export { CachePriority, consoleLogger, type ILogger, type CacheOptions, type CacheMetrics, type CategoryLimit, type SmartCacheEntry, type DiskCacheEntry, type CacheHit, type EvictionReason, type CachePingResult, type ICacheTracer, type ICacheSpan, } from './types';
25
+ //# sourceMappingURL=index.d.ts.map