tricache 0.5.1 → 0.6.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,1317 +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
- /** Original TTL in ms at write time — used by refresh-ahead to compute the proactive refresh threshold. */
83
- ttlMs?: number;
84
- /** Milliseconds taken to fetch/compute this value — used by XFetch probabilistic early expiration. */
85
- delta?: number;
86
- }
87
- /** Returned by SmartMemoryCache.get() — distinguishes "cached null" from a real miss */
88
- interface CacheHit {
89
- value: unknown;
90
- /** true = past soft TTL (staleAt) but within hard expiry → SWR path */
91
- isStale: boolean;
92
- /** Hard expiry timestamp — lets CacheService.get() do refresh-ahead / XFetch math
93
- * without a second Map lookup (eliminates the duplicate l1.getEntry() call). */
94
- expiresAt: number;
95
- /** Original TTL in ms stored at write time — for refresh-ahead fraction calculation */
96
- ttlMs?: number;
97
- /** Fetch duration in ms stored at write time — for XFetch probabilistic threshold */
98
- delta?: number;
99
- /** Timestamp (Date.now()) recorded inside SmartMemoryCache.get() — lets CacheService
100
- * reuse this value for refresh-ahead/XFetch math instead of making a second syscall. */
101
- fetchedAt?: number;
102
- }
103
- /** On-disk entry shape (mirrors SmartCacheEntry — Uint8Array accepted for msgpack round-trips;
104
- * legacy disk files written by older versions may have a JSON string in data) */
105
- interface DiskCacheEntry {
106
- data: string | Buffer | Uint8Array;
107
- isCompressed: boolean;
108
- expiresAt: number;
109
- staleAt?: number;
110
- size: number;
111
- hits: number;
112
- lastAccess: number;
113
- priority: number;
114
- }
115
- /**
116
- * Snapshot of runtime metrics for a CacheService instance.
117
- * Returned by `CacheService.metrics()` and passed to the `onMetrics` callback.
118
- * Convert to Prometheus text with `CacheService.toPrometheusText(metrics)`.
119
- */
120
- interface CacheMetrics {
121
- /** Configured namespace (empty string = no namespace) */
122
- namespace: string;
123
- /** Milliseconds since the CacheService instance was constructed */
124
- uptimeMs: number;
125
- gets: {
126
- total: number;
127
- l1Hits: number;
128
- /** Fraction of gets served from L1 RAM cache (0–1) */
129
- l1HitRate: number;
130
- diskHits: number;
131
- /** Fraction of gets served from L1.5 disk tier (0–1) */
132
- diskHitRate: number;
133
- l2Hits: number;
134
- /** Fraction of gets served from L2 Redis (0–1) */
135
- l2HitRate: number;
136
- /** fetchFn calls (cache misses that fell through to the DB) */
137
- fetches: number;
138
- /** Fraction of gets that called fetchFn (0–1) */
139
- fetchRate: number;
140
- /** Concurrent get() calls deduplicated by the stampede guard */
141
- stampedePrevented: number;
142
- };
143
- sets: {
144
- total: number;
145
- };
146
- deletes: {
147
- total: number;
148
- };
149
- revalidations: {
150
- total: number;
151
- };
152
- bloom: {
153
- /** Total bloom-filter checks (get() calls that passed prefix filter) */
154
- checksTotal: number;
155
- /**
156
- * Times the filter said "might contain" but the key was absent in L1.
157
- * A high rate suggests the bloom filter capacity needs increasing.
158
- */
159
- falsePositives: number;
160
- /** falsePositives / checksTotal (0–1; ideal < 0.01) */
161
- falsePositiveRate: number;
162
- };
163
- compression: {
164
- entriesCompressed: number;
165
- entriesUncompressed: number;
166
- /** Approximate bytes saved by msgpackr vs raw JSON */
167
- bytesSaved: number;
168
- };
169
- /** Pub/Sub invalidation backplane statistics */
170
- backplane: {
171
- enabled: boolean;
172
- /** Invalidation messages published to other instances */
173
- sent: number;
174
- /** Invalidation messages received from other instances */
175
- received: number;
176
- /** Own messages silently skipped (prevents double-eviction) */
177
- skipped: number;
178
- };
179
- /** L2 Redis circuit breaker state */
180
- l2CircuitBreaker: {
181
- /** `'closed'` = normal; `'open'` = Redis paused; `'half_open'` = probing recovery */
182
- state: 'closed' | 'open' | 'half_open';
183
- };
184
- /** OOM guard statistics */
185
- oom: {
186
- enabled: boolean;
187
- /** Number of emergency L1 eviction rounds triggered */
188
- evictions: number;
189
- /** Timestamp of the most recent OOM eviction, or null */
190
- lastTriggeredAt: number | null;
191
- };
192
- l1: {
193
- entries: number;
194
- sizeBytes: number;
195
- maxBytes: number;
196
- };
197
- disk: {
198
- files: number;
199
- sizeKB: number;
200
- maxKB: number;
201
- };
202
- }
203
- /** Per-category memory limits for L1 */
204
- interface CategoryLimit {
205
- maxEntries: number;
206
- maxSizeBytes: number;
207
- }
208
- /**
209
- * Options accepted by CacheService.create()
210
- *
211
- * All fields are optional — sensible defaults are used when omitted.
212
- */
213
- interface CacheOptions {
214
- /**
215
- * Plug in your own logger (pino, winston, bunyan, …).
216
- * Defaults to a minimal console logger that only prints warn/error.
217
- */
218
- logger?: ILogger;
219
- /** Max total bytes held in L1 RAM cache. Default: 200 MB */
220
- l1MaxBytes?: number;
221
- /** Max total entries in L1. Default: 2000 */
222
- l1MaxEntries?: number;
223
- /**
224
- * Per-category limits keyed by the key prefix (e.g. `'org:'`).
225
- * Merged over the built-in defaults.
226
- */
227
- categoryLimits?: Record<string, CategoryLimit>;
228
- /**
229
- * Key prefixes that are never written to disk snapshots or the disk tier.
230
- * Default: ['auth:', 'session:', 'mfa:', 'rate_limit:']
231
- */
232
- forbiddenSnapshotPrefixes?: string[];
233
- /** Directory used for L1.5 disk-spill files. Default: os.tmpdir()/tricache-disk */
234
- diskCacheDir?: string;
235
- /** Max total bytes for the disk tier. Default: 500 MB */
236
- diskMaxBytes?: number;
237
- /** Max bytes for a single disk entry. Default: 10 MB */
238
- diskEntryMaxBytes?: number;
239
- /**
240
- * Redis/Valkey hostname (no `redis://` prefix).
241
- * Falls back to the `REDIS_HOST` environment variable.
242
- * When neither is provided, L2 is disabled.
243
- */
244
- redisHost?: string;
245
- /** Redis port. Default: 6379 */
246
- redisPort?: number;
247
- /**
248
- * Whether to enable TLS for the Redis connection. Default: true in production,
249
- * false otherwise.
250
- */
251
- redisTls?: boolean;
252
- /**
253
- * Set to `true` to disable L2 Redis entirely (e.g. when running single-process
254
- * services that don't need distributed caching). Default: false in production,
255
- * true in development.
256
- */
257
- disableRedis?: boolean;
258
- /**
259
- * Base64-encoded 32-byte AES-256-GCM key for encrypting L2 (Redis) values and
260
- * disk-tier files at rest. Falls back to `CACHE_ENCRYPTION_KEY` env var.
261
- * If not provided in production, a warning is logged and data is stored plaintext.
262
- */
263
- encryptionKey?: string;
264
- /**
265
- * Encryption algorithm used for L2 (Redis) values and disk-tier files.
266
- * - `'aes-256-gcm'` — default. 32-byte key. Authenticated encryption (AEAD).
267
- * - `'aes-128-gcm'` — 16-byte key. ~10% faster on non-AES-NI hardware. AEAD.
268
- * - `'xor'` — XOR obfuscation ONLY. NOT cryptographic security.
269
- * Any key length (minimum 16 bytes recommended).
270
- * Use for dev environments or non-sensitive data only.
271
- * Default: `'aes-256-gcm'`
272
- */
273
- encryptionMode?: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
274
- /**
275
- * Fallback encryption key for zero-downtime key rotation.
276
- * On every read, tricache tries the current `encryptionKey` first.
277
- * If decryption fails (wrong key), it retries with `previousEncryptionKey`.
278
- * All writes always use the current `encryptionKey`.
279
- * Remove this field once you are confident all data has been re-encrypted.
280
- */
281
- previousEncryptionKey?: string;
282
- /** Encryption mode that was used with `previousEncryptionKey`. Defaults to `encryptionMode`. */
283
- previousEncryptionMode?: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
284
- /**
285
- * Path where the cold-start snapshot is written on SIGTERM/SIGINT and loaded
286
- * on startup. Default: os.tmpdir()/tricache-snapshot.msgpack
287
- */
288
- snapshotPath?: string;
289
- /**
290
- * Max age (ms) of a snapshot file before it is rejected. Default: 2 hours
291
- */
292
- snapshotMaxAgeMs?: number;
293
- /**
294
- * Optional namespace prefix for all cache keys.
295
- *
296
- * When set, every key is transparently stored as `${namespace}:${key}` in
297
- * L1, L1.5 (disk), and L2 (Redis). This enables:
298
- * - **Multi-tenant isolation**: `CacheService.create({ namespace: 'org_abc' })`
299
- * — tenants sharing the same Redis instance or disk dir are fully isolated.
300
- * - **Environment separation**: `CacheService.create({ namespace: 'staging' })`
301
- * - **Service-level scoping**: microservices sharing one Redis without key collisions.
302
- *
303
- * Consumers never see the prefix — `get('user:1')` behaves identically
304
- * whether namespaced or not. Glob deletes (`delete('user:*')`) automatically
305
- * scope to the namespace.
306
- *
307
- * The process-level singleton, disk cache directory, and cold-start snapshot
308
- * path are all scoped per namespace, so two `CacheService.create()` calls
309
- * with different namespaces return completely independent instances.
310
- *
311
- * Default: `''` (no prefix)
312
- */
313
- namespace?: string;
314
- /**
315
- * Seconds to extend a stale SWR entry's life when background revalidation fails.
316
- * Without this, a failed revalidation leaves the entry stale until its hard TTL
317
- * expires, after which the next caller blocks. With `staleIfError`, tricache bumps
318
- * the expiry by this many seconds on every failed revalidation, keeping the stale
319
- * value available while the underlying service is degraded.
320
- * Default: `0` (disabled — entry expires normally on revalidation failure).
321
- */
322
- staleIfError?: number;
323
- /**
324
- * Called after every L1 eviction. Receives the raw (namespaced) key and the reason.
325
- * Useful for diagnosing cache pressure and tuning `categoryLimits`.
326
- */
327
- onEviction?: (key: string, reason: EvictionReason) => void;
328
- /**
329
- * Human-readable name for this CacheService instance. Added as an `instance` label
330
- * to all Prometheus metrics emitted by `CacheService.toPrometheusText()`.
331
- * Required when multiple CacheService instances share a process — without it,
332
- * metric names from different instances collide.
333
- * Default: `''` (no label).
334
- */
335
- instanceName?: string;
336
- /**
337
- * Controls whether writes are propagated to L2 (Redis).
338
- * - `'read-write'` (default): read from and write to L2.
339
- * - `'read-only'`: read from L2 but never write, delete, or expire keys in Redis.
340
- * Use for shared read replicas or external Redis clusters you do not own.
341
- */
342
- l2WriteMode?: 'read-write' | 'read-only';
343
- /**
344
- * Enable Redis Pub/Sub invalidation backplane so every running instance
345
- * evicts a key from its L1 when any peer calls `set()` or `delete()`.
346
- *
347
- * Gives you sub-microsecond in-process cache speed with cluster-wide
348
- * consistency across all your app servers.
349
- *
350
- * Default: `true` (auto-activates when Redis is available).
351
- * Set to `false` for single-process services or eventual-consistency scenarios.
352
- */
353
- invalidationBackplane?: boolean;
354
- /**
355
- * Enable the GC-aware OOM guard. When heap utilisation crosses
356
- * `oomHeapThreshold`, a fraction of the coldest L1 entries are
357
- * emergency-evicted to L1.5 disk, preventing Node.js OOM crashes inside
358
- * Docker/Kubernetes containers with tight memory limits.
359
- *
360
- * Default: `true`
361
- */
362
- oomProtection?: boolean;
363
- /**
364
- * Heap-used / heap-total ratio that triggers emergency eviction.
365
- * Default: `0.85` (85 %)
366
- */
367
- oomHeapThreshold?: number;
368
- /** Milliseconds between heap-pressure checks. Default: 10 000 ms (10 s) */
369
- oomCheckIntervalMs?: number;
370
- /** Fraction of L1 entries to evict per OOM round. Default: `0.20` (20 %) */
371
- oomEvictPercent?: number;
372
- /**
373
- * Callback invoked periodically with a `CacheMetrics` snapshot.
374
- * Wire up to OpenTelemetry, Prometheus push gateway, Datadog, etc.
375
- *
376
- * @example
377
- * onMetrics: (m) => statsd.gauge('cache.l1_hit_rate', m.gets.l1HitRate)
378
- */
379
- onMetrics?: (metrics: CacheMetrics) => void;
380
- /** How often the `onMetrics` callback fires (ms). Default: 60 000 ms */
381
- metricsIntervalMs?: number;
382
- /**
383
- * OpenTelemetry-compatible tracer. When provided, `get()`, `set()`, and
384
- * `delete()` are each wrapped in a span with attributes:
385
- * - `cache.hit` — `'l1' | 'disk' | 'l2' | 'miss'`
386
- * - `cache.key_prefix` — first path segment of the key (e.g. `'user'`)
387
- *
388
- * Pass your existing `@opentelemetry/api` Tracer directly — no extra
389
- * dependency required; the interface is structurally compatible.
390
- *
391
- * @example
392
- * import { trace } from '@opentelemetry/api';
393
- * tracer: trace.getTracer('tricache')
394
- */
395
- tracer?: ICacheTracer;
396
- /**
397
- * Randomise every stored TTL by ± `ttlJitterFactor × ttl` seconds.
398
- * Prevents thundering-herd cache stampedes when thousands of entries share
399
- * the same TTL and expire simultaneously.
400
- *
401
- * A factor of `0.15` spreads a 300 s TTL uniformly over [255 s, 345 s].
402
- * Default: `0` (disabled — TTLs are stored exactly as given).
403
- */
404
- ttlJitterFactor?: number;
405
- /**
406
- * Default TTL in seconds for `null` or `undefined` results from `fetchFn`.
407
- * Caches negative results so a non-existent key (deleted user, bad ID) does not
408
- * hit the DB on every request. Can be overridden per-call via `get(..., { notFoundTtl }).
409
- * Default: `0` (disabled — null/undefined uses the normal TTL).
410
- */
411
- notFoundTtl?: number;
412
- /**
413
- * Number of consecutive Redis errors before the circuit opens (stops
414
- * attempting Redis until the cooldown elapses).
415
- * Default: `5`.
416
- */
417
- l2CircuitBreakerThreshold?: number;
418
- /**
419
- * Milliseconds the circuit stays open before transitioning to half-open
420
- * (allows a single probe request to test recovery).
421
- * Default: `30 000` ms (30 s).
422
- */
423
- l2CircuitBreakerCooldownMs?: number;
424
- /**
425
- * Redis key pattern to automatically warm L1 from at startup (e.g. `'user:*'`).
426
- * `cache.ready()` returns a Promise that resolves once this warm-up completes.
427
- * No-op when Redis is disabled or unreachable — safe to set unconditionally.
428
- */
429
- warmKeys?: string;
430
- /**
431
- * Called on every L1, disk, or L2 cache hit. Receives the caller-facing key (no
432
- * namespace prefix) and the tier that served it. Useful for per-route hit-rate
433
- * metrics without waiting for the `onMetrics` interval.
434
- *
435
- * @example
436
- * onHit: (key, tier) => cloudwatch.putMetricData({ key, tier })
437
- */
438
- onHit?: (key: string, tier: 'l1' | 'disk' | 'l2') => void;
439
- /**
440
- * Called on every cache miss (after L1, disk, and L2 are all exhausted).
441
- * Receives the caller-facing key (no namespace prefix).
442
- *
443
- * @example
444
- * onMiss: (key) => cloudwatch.putMetricData({ key })
445
- */
446
- onMiss?: (key: string) => void;
447
- /**
448
- * When `true`, every value returned from an L1 cache hit is recursively
449
- * frozen with `Object.freeze()` before being handed to the caller.
450
- * Any attempt to mutate the returned object throws a `TypeError` immediately,
451
- * catching reference-semantic corruption bugs that would otherwise silently
452
- * corrupt the cached entry.
453
- *
454
- * **Do not enable in production** — use `process.env.NODE_ENV !== 'production'`.
455
- * Deep-freezing large objects has measurable overhead per hit.
456
- *
457
- * @example
458
- * frozen: process.env.NODE_ENV !== 'production'
459
- */
460
- frozen?: boolean;
461
- }
462
-
463
- /**
464
- * CacheService — three-tier cache with stampede prevention and SWR.
2
+ * tricache — three-tier cache for Node.js
465
3
  *
466
- * Architecture:
467
- * L1 → SmartMemoryCache (in-process RAM, always active, adaptive eviction)
468
- * L1.5→ DiskTier (NVMe overflow, evicted L1 entries, 2–100 µs)
469
- * L2 → Redis / Valkey (distributed, production-only by default, survives restarts)
470
- * DB → your fetchFunction (cache miss path)
4
+ * L1 (RAM) → L1.5 (disk) → L2 (Redis/Valkey) → your fetch function
471
5
  *
472
- * Key features:
473
- * - Thundering-herd / cache-stampede prevention (inflight Promise registry)
474
- * - Stale-While-Revalidate (serve stale instantly + revalidate in background)
475
- * - AES-256-GCM encryption for L2 and disk data at rest
476
- * - Cold-start snapshot: L1 is persisted to disk on SIGTERM and restored on startup
477
- * - Process-level singleton (globalThis) survives hot reloads in frameworks like Next.js
478
- * - Periodic cleanup of expired entries every 5 minutes
479
- */
480
-
481
- declare class CacheService {
482
- private readonly logger;
483
- private readonly enc;
484
- private readonly l1;
485
- private readonly disk;
486
- private readonly opts;
487
- /** Pre-computed once — opts.namespace never changes after construction. */
488
- private readonly _namespace;
489
- /** Pre-computed once — disableRedis and redisHost never change after construction. */
490
- private readonly _redisDisabled;
491
- private readonly inflight;
492
- private readonly revalidating;
493
- private readonly _l1Counters;
494
- /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
495
- private readonly tagIndex;
496
- /**
497
- * Dependency index: source glob pattern → Set of namespaced dependent keys.
498
- * When an exact-key delete matches a registered pattern, all dependents are cascaded.
499
- */
500
- private readonly dependencyIndex;
501
- private redis;
502
- private redisConnecting;
503
- private readonly cb;
504
- private snapshotLoaded;
505
- private _readyPromise;
506
- private cleanupInterval;
507
- private diskJanitorInterval;
508
- private oomInterval;
509
- private metricsInterval;
510
- private _shutdownHandler;
511
- private readonly instanceId;
512
- private readonly backplaneChannel;
513
- private subClient;
514
- private readonly counters;
515
- constructor(options?: CacheOptions);
516
- /**
517
- * Get (or create) the process-level singleton CacheService instance.
518
- *
519
- * Options are only applied on first call — subsequent calls return the
520
- * existing instance regardless of options passed.
521
- *
522
- * When `namespace` is set the singleton is keyed by namespace, so two calls
523
- * with different namespaces return independent instances.
524
- */
525
- static create(options?: CacheOptions): CacheService;
526
- /**
527
- * Async factory — accepts a Promise that resolves to CacheOptions.
528
- * Useful when config is fetched from a secret store at startup.
529
- *
530
- * @example
531
- * const cache = await CacheService.createAsync(fetchSecrets());
532
- */
533
- static createAsync(options: Promise<CacheOptions> | CacheOptions): Promise<CacheService>;
534
- /** Replace the singleton (useful in tests). */
535
- static reset(options?: CacheOptions): CacheService;
536
- /** Derive the globalThis key for a given set of options. */
537
- private static globalKey;
538
- /**
539
- * Prepend the configured namespace to a raw cache key.
540
- * Returns the key unchanged when namespace is empty.
541
- *
542
- * This is the only place the namespace prefix is applied — callers always
543
- * receive and provide un-prefixed keys in the public API.
544
- */
545
- private nk;
546
- /** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
547
- private _jitterTtl;
548
- /** Shared no-op span for the common case where no tracer is configured.
549
- * Using a singleton avoids allocating a fresh object literal on every get/set/delete call. */
550
- private static readonly _nullSpan;
551
- /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
552
- private _startSpan;
553
- private initBackplane;
554
- /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
555
- _handleBackplaneMessage(message: string): void;
556
- private publishInvalidation;
557
- private getRedis;
558
- writeSnapshot(altPath?: string): void;
559
- loadSnapshot(): void;
560
- /**
561
- * Get a value from cache, or fetch and cache it.
562
- *
563
- * @param cacheKey - Unique key identifying this value
564
- * @param fetchFn - Called on a cache miss; its return value is cached and returned
565
- * @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
566
- * @param opts.priority - Override the auto-inferred eviction priority
567
- * @param opts.swr - Stale-While-Revalidate grace seconds.
568
- * @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
569
- * is triggered proactively while the caller still receives the
570
- * cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
571
- * Requires `fetchFn` to be stable across calls.
572
- * @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
573
- * recompute more aggressively before expiry. Typical range: 0.5–2.
574
- * Complementary to refreshAhead — uses recompute cost (delta) to
575
- * decide probabilistically rather than at a fixed threshold.
576
- * @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
577
- * Caches negative lookups to avoid repeated DB hits for missing keys.
578
- */
579
- get<T>(cacheKey: string, fetchFn: () => Promise<T>, ttlSeconds?: number, opts?: {
580
- priority?: CachePriority;
581
- swr?: number;
582
- refreshAhead?: number;
583
- xfetchBeta?: number;
584
- notFoundTtl?: number;
585
- /**
586
- * Tags to associate with this cache entry when fetchFn populates it on a miss.
587
- * Tags are registered in the in-process `tagIndex` and (if Redis is enabled) mirrored
588
- * via `SADD` so that `invalidateTag()` covers disk-spill and multi-instance nodes.
589
- * On an L1/L2 hit the tags are already registered — this field is a no-op for hits.
590
- */
591
- tags?: string[];
592
- }): Promise<T>;
593
- private _revalidate;
594
- /** Explicitly write a value into L1 (+ L2 in production). */
595
- set<T>(cacheKey: string, data: T, ttlSeconds?: number, priority?: CachePriority, opts?: {
596
- tags?: string[];
597
- dependsOn?: string[];
598
- }): Promise<void>;
599
- /**
600
- * Register tags for a cache key in the in-process index and (if Redis is enabled) in
601
- * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
602
- */
603
- private _registerTags;
604
- /**
605
- * Delete one key or a glob pattern (supports `*` wildcard).
606
- *
607
- * @example
608
- * await cache.delete('user:abc:profile'); // exact key
609
- * await cache.delete('user:abc:*'); // all keys for user abc
610
- */
611
- delete(cacheKey: string): Promise<void>;
612
- /**
613
- * Atomically increment a counter in Redis. Returns the new value.
614
- * Returns 0 if Redis is disabled (safe fallback — rate limiting won't block in dev).
615
- */
616
- increment(cacheKey: string, ttlSeconds?: number): Promise<number>;
617
- /**
618
- * Flush all cached entries, or only those whose key starts with `prefix`.
619
- *
620
- * @example
621
- * await cache.clear(); // flush everything
622
- * await cache.clear('user:abc'); // flush all keys for one user
623
- */
624
- clear(prefix?: string): Promise<void>;
625
- /**
626
- * Evict L1 entries that violate the current category or global capacity limits.
627
- * Useful after a write burst or after adding stricter `categoryLimits`.
628
- * Returns the number of entries evicted.
629
- */
630
- rebalance(): number;
631
- /**
632
- * Return the remaining TTL in seconds for a key currently in L1.
633
- * Returns null if the key is absent from L1 or has already expired.
634
- * Only reflects L1 state — does not query Redis or disk.
635
- */
636
- ttl(cacheKey: string): number | null;
637
- /**
638
- * Return true if the key exists in L1 and has not expired.
639
- * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
640
- */
641
- has(cacheKey: string): boolean;
642
- /**
643
- * Lazily yield every non-expired L1 key, stripped of its namespace prefix.
644
- *
645
- * @example
646
- * for (const key of cache.keys()) console.log(key);
647
- */
648
- keys(): Generator<string>;
649
- /**
650
- * Lazily yield every non-expired L1 value.
651
- * Each value is the cached (pre-deserialized) JS object — no unpack overhead.
652
- *
653
- * @example
654
- * for (const val of cache.values<User>()) console.log(val.id);
655
- */
656
- values<T = unknown>(): Generator<T>;
657
- /**
658
- * Lazily yield every non-expired L1 [key, value] pair.
659
- * Keys are stripped of their namespace prefix.
660
- *
661
- * @example
662
- * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
663
- */
664
- entries<T = unknown>(): Generator<[string, T]>;
665
- /**
666
- * High-throughput bulk scan over all live L1 entries.
667
- *
668
- * Compared with `entries()` this avoids generator frame overhead, per-entry
669
- * `[key, value]` tuple allocation, and the `key.slice()` allocation when the
670
- * caller uses the `offset` parameter instead of pre-slicing.
671
- *
672
- * ```typescript
673
- * // Zero extra string allocations — use rawKey + offset directly:
674
- * cache.scan((rawKey, value, offset) => {
675
- * const key = rawKey.slice(offset); // allocate only if needed
676
- * sync(key, value as User);
677
- * });
678
- * ```
679
- *
680
- * @param fn Called once per live L1 entry.
681
- * `rawKey` — key with namespace prefix still attached.
682
- * `value` — deserialized cached value.
683
- * `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
684
- */
685
- scan<T = unknown>(fn: (rawKey: string, value: T, offset: number) => void): void;
686
- /**
687
- * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
688
- * Returns `false` if the key is absent or already expired.
689
- *
690
- * @param newTtlSeconds - The new TTL from now, in seconds.
691
- */
692
- touch(cacheKey: string, newTtlSeconds: number): Promise<boolean>;
693
- /**
694
- * Return the cached value from L1 **only if it is fresh** (not in the SWR grace window).
695
- * Returns `null` when the key is absent, expired, or stale — without triggering a fetch.
696
- *
697
- * @example
698
- * const fresh = cache.getIfFresh('user:123');
699
- * if (fresh !== null) return fresh; // serve from L1, no network hop
700
- */
701
- getIfFresh<T = unknown>(cacheKey: string): T | null;
702
- /**
703
- * Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
704
- * Preserves input ordering. Uses inflight coalescing per key.
705
- *
706
- * @param keys - Array of cache keys.
707
- * @param fetchFn - Called with only the keys that missed L1.
708
- * @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
709
- * `(key) => number` so heterogeneous TTLs can be batched in one call.
710
- */
711
- mget<T>(keys: string[], fetchFn: (missKeys: string[]) => Promise<Record<string, T>>, ttl?: number | ((key: string) => number), priority?: CachePriority): Promise<(T | undefined)[]>;
712
- /**
713
- * Returns a Promise that resolves once the cache is fully initialised and any
714
- * startup warming configured via `warmKeys` has completed.
715
- *
716
- * Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once
717
- * `warmFromL2(warmKeys)` finishes — ideal for k8s readiness probes.
718
- *
719
- * @example
720
- * const cache = CacheService.create({ warmKeys: 'user:*' });
721
- * await cache.ready(); // gate traffic until warm
722
- */
723
- ready(): Promise<void>;
724
- /**
725
- * Batch write — set multiple entries in a single call.
726
- * TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
727
- *
728
- * @example
729
- * await cache.mset({
730
- * 'user:1': { value: { name: 'Alice' }, ttl: 300 },
731
- * 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
732
- * });
733
- */
734
- mset<T = unknown>(entries: Record<string, {
735
- value: T;
736
- ttl?: number;
737
- priority?: CachePriority;
738
- tags?: string[];
739
- dependsOn?: string[];
740
- }>): Promise<void>;
741
- /**
742
- * Batch delete — delete multiple exact keys in a single call.
743
- * Glob patterns are not supported; use `delete('prefix:*')` for patterns.
744
- *
745
- * @example
746
- * await cache.mdel(['user:1', 'user:2', 'user:3']);
747
- */
748
- mdel(keys: string[]): Promise<void>;
749
- /**
750
- * Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
751
- * pulling them into L1. Useful on startup to eliminate cold-start penalty when
752
- * the local snapshot is unavailable or too stale.
753
- *
754
- * Returns the number of keys loaded into L1.
755
- *
756
- * @example
757
- * // In your startup hook (e.g. ECS task, k8s readiness probe):
758
- * const loaded = await cache.warmFromL2('org:*');
759
- * console.log(`Warmed ${loaded} keys from Redis`);
760
- */
761
- warmFromL2(pattern: string, opts?: {
762
- priority?: CachePriority;
763
- }): Promise<number>;
764
- /**
765
- * Invalidate all keys associated with a tag.
766
- * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
767
- *
768
- * @example
769
- * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
770
- * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
771
- */
772
- invalidateTag(tag: string): Promise<void>;
773
- /**
774
- * Invalidate all keys associated with any of the given tags in a single operation.
775
- * Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
776
- * reducing latency when invalidating several related tags together.
777
- *
778
- * Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
779
- * synchronously before the Redis round-trip.
780
- *
781
- * @example
782
- * // Instead of three serial round-trips:
783
- * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
784
- */
785
- invalidateTags(tags: string[]): Promise<void>;
786
- /**
787
- * Measure L1 / disk / Redis latency.
788
- * Useful for health checks and dashboards.
789
- *
790
- * @returns `{ l1, disk, l2 }` latencies in milliseconds.
791
- * `l2` is `null` when Redis is disabled.
792
- */
793
- ping(): Promise<CachePingResult>;
794
- /**
795
- * Export all live L1 entries to Redis via a single pipeline.
796
- * Useful for warming a new Redis instance or for zero-downtime failover.
797
- * Returns the number of keys written.
798
- */
799
- drainToL2(): Promise<number>;
800
- stats(): {
801
- l1: {
802
- entries: number;
803
- sizeBytes: number;
804
- sizeKB: number;
805
- categories: Record<string, {
806
- entries: number;
807
- hits: number;
808
- }>;
809
- bloom: {
810
- checks: number;
811
- falsePositives: number;
812
- };
813
- compression: {
814
- compressed: number;
815
- uncompressed: number;
816
- bytesSaved: number;
817
- };
818
- };
819
- disk: {
820
- files: number;
821
- sizeKB: number;
822
- maxKB: number;
823
- };
824
- };
825
- /**
826
- * Write `value` only if the key is not already cached.
827
- * Returns `true` if the write happened, `false` if the key already existed.
828
- *
829
- * When Redis is available, atomicity is guaranteed via `SET NX EX` so this
830
- * is safe to use for idempotency keys and "first writer wins" patterns across
831
- * multiple instances. L1 is populated on success.
832
- *
833
- * @example
834
- * const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
835
- * if (!claimed) return res.status(409).json({ error: 'duplicate request' });
836
- */
837
- setIfAbsent<T>(cacheKey: string, value: T, ttlSeconds?: number, priority?: CachePriority): Promise<boolean>;
838
- /**
839
- * Return the top-N live L1 keys by historical access frequency.
840
- * Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
841
- * whose historical frequency exceeds their current in-memory hit count.
842
- *
843
- * Useful for diagnosing what is driving L1 pressure without any extra data
844
- * collection overhead.
845
- *
846
- * @param n - Maximum number of keys to return. Default: 10.
847
- *
848
- * @example
849
- * cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
850
- * console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
851
- */
852
- hotKeys(n?: number): Array<{
853
- key: string;
854
- hits: number;
855
- sizeBytes: number;
856
- }>;
857
- /**
858
- * Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
859
- * pattern that may contain `*` wildcards).
860
- */
861
- private _matchesGlob;
862
- /**
863
- * When an exact key `deletedKey` is removed, cascade to every dependent key
864
- * that was registered via `dependsOn` and whose source pattern matches.
865
- */
866
- private _cascadeDependencies;
867
- /** Return a full metrics snapshot. */
868
- metrics(): CacheMetrics;
869
- /**
870
- * Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
871
- * Paste the result into your `/metrics` endpoint.
872
- *
873
- * @param m - Snapshot returned by `cache.metrics()`
874
- * @param prefix - Metric name prefix. Default: `"tricache"`
875
- */
876
- static toPrometheusText(m: CacheMetrics, prefix?: string, instanceName?: string): string;
877
- /** Close Redis connections and stop all background timers. */
878
- destroy(): Promise<void>;
879
- }
880
-
881
- /**
882
- * Encryption / obfuscation for L2 (Redis) values and disk snapshots at rest.
883
- *
884
- * Four modes are supported via the `encryptionMode` CacheOption:
885
- *
886
- * ┌──────────────┬────────────┬──────────────────────────────────────────────────────────────┐
887
- * │ Mode │ Key bytes │ Notes │
888
- * ├──────────────┼────────────┼──────────────────────────────────────────────────────────────┤
889
- * │ aes-256-gcm │ 32 │ Default. Authenticated encryption (AEAD). │
890
- * │ aes-128-gcm │ 16 │ ~15% faster than AES-256. AEAD. │
891
- * │ aes-128-ctr │ 16 │ Fastest cipher. AES-NI keystream, no auth tag. │
892
- * │ │ │ Use when integrity is guaranteed elsewhere (TLS, HMAC, etc.). │
893
- * │ xor │ any (≥ 1) │ XOR obfuscation ONLY — NOT cryptographic. │
894
- * │ │ │ Use only for dev or non-sensitive data. │
895
- * └──────────────┴────────────┴──────────────────────────────────────────────────────────────┘
896
- *
897
- * Key generation:
898
- * AES-256 (32 B): node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
899
- * AES-128 (16 B): node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
900
- * CTR (16 B): node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
901
- * XOR (any len): node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
902
- *
903
- * Redis envelope formats:
904
- * enc:v1:<base64(IV[12]|Tag[16]|CT)> ← AES-256-GCM
905
- * a128:v1:<base64(IV[12]|Tag[16]|CT)> ← AES-128-GCM
906
- * ctr:v1:<base64(IV[16]|CT)> ← AES-128-CTR (no auth tag)
907
- * xor:v1:<base64(key⊕data)> ← XOR (self-inverse)
908
- *
909
- * Disk envelope formats:
910
- * TRIC1ENC | IV[12] | Tag[16] | CT[N] ← AES-256-GCM
911
- * TRIC1128 | IV[12] | Tag[16] | CT[N] ← AES-128-GCM
912
- * TRIC1CTR | IV[16] | CT[N] ← AES-128-CTR (no auth tag)
913
- * TRIC1XOR | key⊕data[N] ← XOR
914
- */
915
-
916
- /** Encryption algorithm used for L2 (Redis) values and disk-tier files. */
917
- type EncryptionMode = 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
918
- declare class CacheEncryption {
919
- private _key;
920
- private readonly _mode;
921
- private _prevKey;
922
- private _prevMode;
923
- private readonly _ivPool;
924
- private _ivOffset;
925
- /** Return the next unique 12-byte IV slice from the pre-allocated GCM pool. */
926
- private _nextIV;
927
- private readonly _ctrIvPool;
928
- private _ctrIvOffset;
929
- /** Return the next unique 16-byte IV slice from the pre-allocated CTR pool. */
930
- private _nextCtrIV;
931
- /**
932
- * XOR `data` with the key, cycling through key bytes.
933
- * Self-inverse: _xorBuffer(_xorBuffer(x)) === x.
934
- *
935
- * Fast path: Uint32Array views over the existing Buffer memory — zero copy,
936
- * no method-call overhead. V8 JITs `out32[i] = data32[i] ^ key32[...]`
937
- * to a single `XOR r32, r32` instruction. Requires 4-byte-aligned byteOffsets,
938
- * which Node.js guarantees (pool rounds up to 8 bytes; direct allocs to page).
939
- *
940
- * WARNING: XOR is NOT cryptographic. It provides obfuscation only.
941
- */
942
- private _xorBuffer;
943
- constructor(keyBase64: string | undefined, logger: ILogger, mode?: EncryptionMode, previousKeyBase64?: string, previousMode?: EncryptionMode);
944
- get isEnabled(): boolean;
945
- /**
946
- * Encrypt a string for Redis storage.
947
- * Returns a mode-prefixed base64 string when a key is configured;
948
- * otherwise returns the original string unchanged (backward-compatible).
949
- */
950
- encrypt(plaintext: string): string;
951
- /**
952
- * Decrypt a Redis value.
953
- * Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
954
- * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
955
- */
956
- decrypt(value: string): string;
957
- private _decryptWithKey;
958
- /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
959
- encryptBuffer(data: Buffer): Buffer;
960
- /**
961
- * Decrypt a raw Buffer from disk/snapshot.
962
- * Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
963
- * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
964
- */
965
- decryptBuffer(data: Buffer): Buffer;
966
- private _decryptBufferWithKey;
967
- }
968
-
969
- /**
970
- * SmartMemoryCache — L1 in-process cache with adaptive LFU/LRU hybrid eviction.
971
- *
972
- * Features:
973
- * - WASM Bloom filter for O(k) guaranteed-miss detection (pure-JS fallback)
974
- * - msgpackr compression for entries ≥ 512 bytes
975
- * - Category-aware capacity limits (prevents any single key prefix from monopolising RAM)
976
- * - Priority-weighted adaptive eviction (LFU × LRU × priority score)
977
- * - Stale-While-Revalidate soft-expiry support (isStale flag on get())
978
- * - L1.5 disk-spill on eviction — evicted entries are sent to DiskTier before deletion
979
- * - Periodic cleanup of hard-expired entries + bloom filter rebuild
980
- * - Process-level singleton via globalThis (survives Next.js hot reloads)
981
- */
982
-
983
- interface SmartMemoryCacheOptions {
984
- maxBytes: number;
985
- maxEntries: number;
986
- categories: Record<string, CategoryLimit>;
987
- diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
988
- onEviction?: (key: string, reason: EvictionReason) => void;
989
- logger: ILogger;
990
- }
991
- declare class SmartMemoryCache {
992
- private readonly cache;
993
- private readonly opts;
994
- private bloom;
995
- /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
996
- private readonly categoryPrefixes;
997
- /** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
998
- private readonly sketch;
999
- private totalSize;
1000
- private categoryCount;
1001
- private categorySize;
1002
- /** Per-category key sets — enables O(catSize) Phase-1 reservoir sampling without an O(N) scan. */
1003
- private categoryKeys;
1004
- private bloomChecks;
1005
- private bloomFalsePos;
1006
- private compressions;
1007
- private categoryHits;
1008
- /** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
1009
- private _bloomDirtyCount;
1010
- constructor(opts: SmartMemoryCacheOptions, existing?: Map<string, SmartCacheEntry>);
1011
- private recalculateStats;
1012
- private getCategory;
1013
- private getCategoryLimit;
1014
- private _delete;
1015
- private ensureCapacity;
1016
- private score;
1017
- /**
1018
- * Rebuild the bloom filter when phantom bits from deleted/expired keys have
1019
- * saturated the filter past its ~1 % FP capacity.
1020
- *
1021
- * Trigger: (insertions − live entries) > maxCapacity
1022
- *
1023
- * Using the phantom count (insertions − cache.size) instead of raw insertions
1024
- * prevents an O(cache.size) rebuild from re-firing on every set() when the
1025
- * cache holds more entries than the filter's rated capacity — which would
1026
- * stall the write path entirely.
1027
- *
1028
- * After rebuild: insertions = cache.size → phantoms = 0 → no immediate re-trigger.
1029
- */
1030
- private maybeRebuildBloom;
1031
- private smartEvict;
1032
- get(key: string): CacheHit | null;
1033
- set(key: string, data: unknown, ttlMs: number, priority?: CachePriority, staleAt?: number, delta?: number): void;
1034
- delete(key: string): boolean;
1035
- private keysMatchingPattern;
1036
- deletePattern(pattern: string): number;
1037
- /** Flush all entries, or only those whose key starts with `prefix`. */
1038
- clear(prefix?: string): number;
1039
- /**
1040
- * Evict entries that violate current category or global limits.
1041
- * Returns the number of entries evicted.
1042
- */
1043
- rebalance(): number;
1044
- /**
1045
- * Return remaining TTL in seconds for a key in L1, or null if absent/expired.
1046
- * Only reflects L1 state — does not query Redis or disk.
1047
- */
1048
- ttl(key: string): number | null;
1049
- /**
1050
- * Forcibly evict the coldest `pct` fraction of non-CRITICAL L1 entries,
1051
- * spilling each to L1.5 disk. Called by the OOM guard when heap pressure
1052
- * exceeds the configured threshold.
1053
- *
1054
- * @param pct - Fraction to evict (0–1), e.g. 0.2 = 20 %
1055
- * @returns Number of entries evicted
1056
- */
1057
- evictPercentage(pct: number): number;
1058
- cleanup(): number;
1059
- exportEntries(forbiddenPrefixes: readonly string[]): Array<{
1060
- key: string;
1061
- entry: SmartCacheEntry;
1062
- }>;
1063
- importEntries(entries: Array<{
1064
- key: string;
1065
- entry: SmartCacheEntry;
1066
- }>, forbiddenPrefixes: readonly string[]): number;
1067
- /**
1068
- * Lazily yields every [key, entry] pair whose TTL has not yet expired.
1069
- * Expired entries that are still in the Map (awaiting background cleanup)
1070
- * are silently skipped.
1071
- */
1072
- liveEntries(): Generator<[string, SmartCacheEntry]>;
1073
- /**
1074
- * Non-generator bulk scan over all live entries.
1075
- *
1076
- * Faster than the generator-based iterators for bulk operations because:
1077
- * - No generator state-machine overhead (no yield/resume suspend points).
1078
- * - No per-entry tuple allocation (compare `liveEntries()` which yields `[key, entry]`).
1079
- * - The same Map call-site is used by a single plain `for` loop instead of being
1080
- * shared across three competing generator functions, giving V8's IC a cleaner
1081
- * monomorphic profile for this path.
1082
- *
1083
- * The callback receives the raw (namespaced) key and a `prefixLen` offset so the
1084
- * caller can call `key.slice(prefixLen)` only when it actually needs the stripped
1085
- * key, avoiding the allocation entirely for callers that don't.
1086
- *
1087
- * @param fn Called once per live entry.
1088
- * @param prefixLen Number of bytes to skip to reach the un-namespaced portion of the key.
1089
- * Pass 0 when no namespace is configured.
1090
- */
1091
- scan(fn: (key: string, entry: SmartCacheEntry, prefixLen: number) => void, prefixLen: number): void;
1092
- /**
1093
- * Yields only the keys of live entries — no intermediate tuple allocation.
1094
- * Use this instead of liveEntries() when you only need keys.
1095
- */
1096
- liveKeys(): Generator<string>;
1097
- /**
1098
- * Yields only the resolved values of live entries.
1099
- * Iterates Map.values() so the key is never loaded into the yielded path.
1100
- * Returns the cached deserialized object when available (entry.value), otherwise
1101
- * the raw msgpackr Buffer — identical semantics to get() but without bloom/hit tracking.
1102
- */
1103
- liveValues(): Generator<unknown>;
1104
- get size(): number;
1105
- get memoryUsage(): number;
1106
- getStats(): {
1107
- entries: number;
1108
- sizeBytes: number;
1109
- sizeKB: number;
1110
- categories: Record<string, {
1111
- entries: number;
1112
- hits: number;
1113
- }>;
1114
- bloom: {
1115
- checks: number;
1116
- falsePositives: number;
1117
- };
1118
- compression: {
1119
- compressed: number;
1120
- uncompressed: number;
1121
- bytesSaved: number;
1122
- };
1123
- };
1124
- /**
1125
- * Return the raw cache entry for a key, or `undefined` if absent/expired.
1126
- * Does NOT count as a hit or perform SWR logic.
1127
- */
1128
- getEntry(key: string): SmartCacheEntry | undefined;
1129
- /**
1130
- * Return true if the key exists in L1 and has not expired.
1131
- * Uses the bloom filter as a fast negative check.
1132
- */
1133
- has(key: string): boolean;
1134
- /**
1135
- * Extend the TTL of an existing key. Returns `false` if the key is absent or expired.
1136
- * @param newTtlMs - New TTL from now, in milliseconds.
1137
- */
1138
- touch(key: string, newTtlMs: number): boolean;
1139
- /**
1140
- * Add additional milliseconds to a key's existing expiry (for stale-if-error).
1141
- * Returns `false` if the key is absent or already expired.
1142
- */
1143
- bumpExpiry(key: string, additionalMs: number): boolean;
1144
- bloomMightContain(key: string): boolean;
1145
- bloomStats(): {
1146
- bitsSet: number;
1147
- fillFactor: number;
1148
- } | {
1149
- bitsSet: number;
1150
- fillFactor: number;
1151
- };
1152
- /**
1153
- * Return the top-N live L1 keys by historical access frequency (Count-Min Sketch estimate).
1154
- * Includes evicted-then-readmitted keys whose sketch frequency exceeds their current hit count.
1155
- * Useful for diagnosing which keys are driving cache pressure.
1156
- *
1157
- * @param n - Maximum number of entries to return. Default: 10.
1158
- */
1159
- hotKeys(n: number): Array<{
1160
- key: string;
1161
- hits: number;
1162
- sizeBytes: number;
1163
- }>;
1164
- }
1165
-
1166
- /**
1167
- * DiskTier — L1.5 NVMe-fast overflow cache between L1 RAM and L2 Redis/DB.
6
+ * Quick start:
7
+ * import { CacheService, CachePriority } from 'tricache';
1168
8
  *
1169
- * When L1 evicts an entry it is spilled here instead of being discarded.
1170
- * On a subsequent L1 miss the entry is promoted back (2–100 µs disk read
1171
- * vs 10–100 ms DB round-trip).
9
+ * const cache = CacheService.create({ redisHost: 'localhost' });
1172
10
  *
1173
- * Storage:
1174
- * - Directory: configurable (default os.tmpdir()/tricache-disk)
1175
- * - Filename: SHA-256(key) hex — bounded, URL-safe, no key injection
1176
- * - Format: msgpack({ version, key, entry, writtenAt })
1177
- * - 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
+ * );
1178
16
  *
1179
- * Encryption: same AES-256-GCM as L2 when CacheEncryption is configured.
17
+ * await cache.delete(`user:${userId}`);
1180
18
  */
1181
-
1182
- interface DiskTierOptions {
1183
- dir: string;
1184
- maxBytes: number;
1185
- entryMaxBytes: number;
1186
- forbiddenPrefixes: readonly string[];
1187
- encryptionKey?: Buffer | null;
1188
- logger: ILogger;
1189
- }
1190
- declare class DiskTier {
1191
- private readonly opts;
1192
- private dirReady;
1193
- private diskUsageBytes;
1194
- private usageCounted;
1195
- private fileCount;
1196
- /** Next bucket index (0–255) for the staggered janitor wheel. */
1197
- private _nextJanitorBucket;
1198
- constructor(opts: DiskTierOptions);
1199
- private ensureDir;
1200
- private ensureUsageCounted;
1201
- /**
1202
- * SHA-256 hex digest of a key (pure CPU, no I/O).
1203
- * Kept separate from path construction so callers can find files by prefix
1204
- * without knowing which filename generation was used when the file was written.
1205
- */
1206
- private keyToHash;
1207
- /**
1208
- * Build the write path for a NEW file (V3 generation).
1209
- * Encoding expiresAt in the filename lets purgeNextBucket() skip live entries
1210
- * with zero file I/O — after readdirSync() it only needs a string parse.
1211
- *
1212
- * {dir}/{hash[0..1]}/{hash}_{expiresAt-hex-12}
1213
- * e.g. {dir}/e3/e3b0c442…abcd_018f7c3b5a00
1214
- *
1215
- * 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
1216
- */
1217
- private hashToWritePath;
1218
- /**
1219
- * Find the on-disk file for a key hash, handling all filename generations:
1220
- * V3 (current): "{hash}_{expiresHex12}" — 77 chars
1221
- * V1/V2 (older): "{hash}" — 64 chars, no suffix
1222
- * Returns null when the bucket dir does not exist or the key is absent.
1223
- */
1224
- private findFilePath;
1225
- /**
1226
- * Recursively list all cache file paths across the 2-level sharded subdirs.
1227
- * Top-level entries that are not directories are skipped (e.g. stale flat
1228
- * files written by older versions).
1229
- */
1230
- private walkCacheFiles;
1231
- private isForbidden;
1232
- private encrypt;
1233
- private decrypt;
1234
- /**
1235
- * V2 encryption — returns IV+TAG+ciphertext (no magic prefix; magic lives in
1236
- * the outer 16-byte header alongside the plaintext expiresAt).
1237
- * Returns the buffer unchanged when no encryption key is configured.
1238
- */
1239
- private encryptV2;
1240
- /**
1241
- * V2 decryption — inner payload after stripping the 16-byte header.
1242
- * When a key is configured the format is IV(12)+TAG(16)+ciphertext;
1243
- * without a key the payload is raw msgpack.
1244
- */
1245
- private decryptV2;
1246
- /**
1247
- * Spill an evicted L1 entry to disk.
1248
- *
1249
- * Returns a Promise that resolves when the file is durably written. Callers
1250
- * that treat the spill as fire-and-forget should do:
1251
- * `void disk.save(key, entry)`
1252
- *
1253
- * Implementation notes:
1254
- * - pack() + AES-256-GCM encrypt run synchronously — both are pure CPU,
1255
- * sub-millisecond for entries up to diskEntryMaxBytes, and do not block
1256
- * on any external resource.
1257
- * - The actual write syscall (mkdir + writeFile) is async via fs.promises,
1258
- * so the Node.js event loop is never stalled waiting for disk I/O.
1259
- */
1260
- save(key: string, entry: DiskCacheEntry): Promise<void>;
1261
- /** Load a key from disk, or return null on miss/expiry/corruption. */
1262
- load(key: string): DiskCacheEntry | null;
1263
- /** Explicitly delete a key from disk (cache invalidation). */
1264
- delete(key: string): void;
1265
- /** Purge all expired entries. Returns number deleted. */
1266
- purgeExpired(): number;
1267
- /**
1268
- * Purge expired entries from exactly one of the 256 subdirectory buckets, then
1269
- * advance the wheel pointer. Call on a short recurring interval (e.g. 30 s) so
1270
- * the O(fileCount) work of a full purgeExpired() is spread over 256 ticks instead
1271
- * of landing as one large synchronous burst every 5 minutes.
1272
- *
1273
- * V3 files: expiresAt is encoded in the filename — live entries skip with zero
1274
- * file I/O (just readdirSync + string parse). Expired entries: statSync + unlinkSync.
1275
- *
1276
- * Returns the number of entries deleted in this tick.
1277
- */
1278
- purgeNextBucket(): number;
1279
- /** Delete every file in the disk cache. Returns the count deleted. */
1280
- clear(): number;
1281
- get stats(): {
1282
- files: number;
1283
- sizeKB: number;
1284
- maxKB: number;
1285
- };
1286
- }
1287
-
1288
- declare class WasmBloomFilter {
1289
- private readonly exports;
1290
- private readonly mem;
1291
- private readonly encoder;
1292
- private readonly numBits;
1293
- /** Pre-computed — k and numBits are fixed constants; no need to recalculate on every probe. */
1294
- private readonly _maxCapacity;
1295
- /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
1296
- private _insertionCount;
1297
- constructor();
1298
- private writeKey;
1299
- add(key: string): void;
1300
- mightContain(key: string): boolean;
1301
- reset(): void;
1302
- rebuild(keys: Iterable<string>): void;
1303
- get stats(): {
1304
- bitsSet: number;
1305
- fillFactor: number;
1306
- };
1307
- /** Number of add() calls since last reset/rebuild. */
1308
- get insertions(): number;
1309
- /**
1310
- * Maximum safe insertions before false-positive rate exceeds ~1 %.
1311
- * Exact formula for k=7 hash rounds, m=100 000 bits:
1312
- * n_max = -m * ln(1 - p^(1/k)) / k ≈ 18 169
1313
- */
1314
- get maxCapacity(): number;
1315
- }
1316
-
1317
- 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