tricache 0.4.0 → 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.
@@ -0,0 +1,1494 @@
1
+ /**
2
+ * CacheService — three-tier cache with stampede prevention and SWR.
3
+ *
4
+ * Architecture:
5
+ * L1 → SmartMemoryCache (in-process RAM, always active, adaptive eviction)
6
+ * L1.5→ DiskTier (NVMe overflow, evicted L1 entries, 2–100 µs)
7
+ * L2 → Redis / Valkey (distributed, production-only by default, survives restarts)
8
+ * DB → your fetchFunction (cache miss path)
9
+ *
10
+ * Key features:
11
+ * - Thundering-herd / cache-stampede prevention (inflight Promise registry)
12
+ * - Stale-While-Revalidate (serve stale instantly + revalidate in background)
13
+ * - AES-256-GCM encryption for L2 and disk data at rest
14
+ * - Cold-start snapshot: L1 is persisted to disk on SIGTERM and restored on startup
15
+ * - Process-level singleton (globalThis) survives hot reloads in frameworks like Next.js
16
+ * - Periodic cleanup of expired entries every 5 minutes
17
+ */
18
+ import { Redis as RedisClient } from 'ioredis';
19
+ import { pack, unpack } from 'msgpackr';
20
+ import crypto from 'crypto';
21
+ import os from 'os';
22
+ import fs from 'fs';
23
+ import path from 'path';
24
+ import { CachePriority, consoleLogger, } from './types';
25
+ import { CacheEncryption } from './encryption';
26
+ import { SmartMemoryCache } from './smart-memory-cache';
27
+ import { DiskTier } from './disk-tier';
28
+ // ─── Snapshot constants ───────────────────────────────────────────────────────
29
+ const SNAPSHOT_VERSION = 1;
30
+ const DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1000; // 2 hours
31
+ const SNAPSHOT_MAX_FILE_BYTES = 220 * 1024 * 1024; // 220 MB guard
32
+ // ─── Default category limits ──────────────────────────────────────────────────
33
+ const DEFAULT_CATEGORY_LIMITS = {
34
+ 'default': { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 },
35
+ };
36
+ // ─── Default forbidden prefixes ───────────────────────────────────────────────
37
+ const DEFAULT_FORBIDDEN_PREFIXES = ['auth:', 'session:', 'mfa:', 'rate_limit:'];
38
+ class L2CircuitBreaker {
39
+ threshold;
40
+ cooldownMs;
41
+ state = 0 /* CBState.CLOSED */;
42
+ failures = 0;
43
+ openedAt = 0;
44
+ constructor(threshold, cooldownMs) {
45
+ this.threshold = threshold;
46
+ this.cooldownMs = cooldownMs;
47
+ }
48
+ /** Call before each Redis attempt. Returns false when the circuit is open. */
49
+ isAllowed() {
50
+ if (this.state === 0 /* CBState.CLOSED */)
51
+ return true;
52
+ if (this.state === 2 /* CBState.HALF_OPEN */)
53
+ return true; // one probe allowed
54
+ // OPEN: check if cooldown elapsed
55
+ if (Date.now() - this.openedAt >= this.cooldownMs) {
56
+ this.state = 2 /* CBState.HALF_OPEN */;
57
+ return true; // probe
58
+ }
59
+ return false;
60
+ }
61
+ /** Call on Redis success. */
62
+ onSuccess() {
63
+ this.failures = 0;
64
+ this.state = 0 /* CBState.CLOSED */;
65
+ }
66
+ /** Call on Redis failure. */
67
+ onFailure() {
68
+ this.failures++;
69
+ if (this.state === 2 /* CBState.HALF_OPEN */ || this.failures >= this.threshold) {
70
+ this.state = 1 /* CBState.OPEN */;
71
+ this.openedAt = Date.now();
72
+ this.failures = 0;
73
+ }
74
+ }
75
+ get isOpen() { return this.state === 1 /* CBState.OPEN */; }
76
+ get currentState() {
77
+ return this.state === 0 /* CBState.CLOSED */ ? 'closed'
78
+ : this.state === 1 /* CBState.OPEN */ ? 'open'
79
+ : 'half_open';
80
+ }
81
+ }
82
+ // ─────────────────────────────────────────────────────────────────────────────
83
+ // Priority inference — override by passing priority explicitly to get()
84
+ // ─────────────────────────────────────────────────────────────────────────────
85
+ function inferPriority(cacheKey) {
86
+ if (cacheKey.includes('auth:') || cacheKey.includes('session:'))
87
+ return CachePriority.CRITICAL;
88
+ if (cacheKey.includes('user:') || cacheKey.includes('org:') || cacheKey.includes('profile:'))
89
+ return CachePriority.HIGH;
90
+ if (cacheKey.includes('analytics:') || cacheKey.includes('report:') || cacheKey.includes('stats:'))
91
+ return CachePriority.LOW;
92
+ return CachePriority.NORMAL;
93
+ }
94
+ // ─────────────────────────────────────────────────────────────────────────────
95
+ // CacheService
96
+ // ─────────────────────────────────────────────────────────────────────────────
97
+ // globalThis key — allows reuse across hot reloads (Next.js, ts-node watch, etc.)
98
+ const GLOBAL_KEY = '__tricache_instance__';
99
+ export class CacheService {
100
+ logger;
101
+ enc;
102
+ l1;
103
+ disk;
104
+ opts;
105
+ /** Pre-computed once — opts.namespace never changes after construction. */
106
+ _namespace;
107
+ /** Pre-computed once — disableRedis and redisHost never change after construction. */
108
+ _redisDisabled;
109
+ inflight = new Map();
110
+ revalidating = new Set();
111
+ _l1Counters = new Map();
112
+ /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
113
+ tagIndex = new Map();
114
+ /**
115
+ * Dependency index: source glob pattern → Set of namespaced dependent keys.
116
+ * When an exact-key delete matches a registered pattern, all dependents are cascaded.
117
+ */
118
+ dependencyIndex = new Map();
119
+ redis = null;
120
+ redisConnecting = null;
121
+ cb;
122
+ snapshotLoaded = false;
123
+ _readyPromise = Promise.resolve();
124
+ cleanupInterval = null;
125
+ oomInterval = null;
126
+ metricsInterval = null;
127
+ _shutdownHandler = null;
128
+ instanceId;
129
+ backplaneChannel;
130
+ subClient = null;
131
+ counters = {
132
+ gets: 0,
133
+ l1Hits: 0,
134
+ diskHits: 0,
135
+ l2Hits: 0,
136
+ fetches: 0,
137
+ stampedes: 0,
138
+ sets: 0,
139
+ deletes: 0,
140
+ swrRevalidations: 0,
141
+ invSent: 0,
142
+ invReceived: 0,
143
+ invSkipped: 0,
144
+ oomEvictions: 0,
145
+ oomLastAt: null,
146
+ startedAt: Date.now(),
147
+ };
148
+ // ── Constructor (use CacheService.create() for the recommended singleton) ──
149
+ constructor(options = {}) {
150
+ const logger = options.logger ?? consoleLogger;
151
+ this.logger = logger;
152
+ // Resolve namespace: trim whitespace, default to empty string
153
+ const ns = options.namespace?.trim() ?? '';
154
+ // Resolve encryption key: option > env var
155
+ const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
156
+ this.enc = new CacheEncryption(encKeyRaw, logger, options.encryptionMode, options.previousEncryptionKey, options.previousEncryptionMode);
157
+ // When a namespace is active, scope the forbidden prefixes so that
158
+ // auth/session keys like `org_abc:auth:token` are still protected.
159
+ const rawForbidden = options.forbiddenSnapshotPrefixes ?? [...DEFAULT_FORBIDDEN_PREFIXES];
160
+ const forbiddenPrefixes = ns
161
+ ? rawForbidden.map(p => `${ns}:${p}`)
162
+ : rawForbidden;
163
+ // Normalised options with defaults
164
+ this.opts = {
165
+ namespace: ns,
166
+ logger,
167
+ l1MaxBytes: options.l1MaxBytes ?? 200 * 1024 * 1024,
168
+ l1MaxEntries: options.l1MaxEntries ?? 2_000,
169
+ categoryLimits: { ...DEFAULT_CATEGORY_LIMITS, ...(options.categoryLimits ?? {}) },
170
+ forbiddenSnapshotPrefixes: forbiddenPrefixes,
171
+ // Namespace-isolated defaults: separate dir / snapshot per namespace so
172
+ // two instances with different namespaces never share cache files.
173
+ diskCacheDir: options.diskCacheDir ?? path.join(os.tmpdir(), ns ? `tricache-disk-${ns}` : 'tricache-disk'),
174
+ diskMaxBytes: options.diskMaxBytes ?? 500 * 1024 * 1024,
175
+ diskEntryMaxBytes: options.diskEntryMaxBytes ?? 10 * 1024 * 1024,
176
+ redisHost: options.redisHost ?? process.env.REDIS_HOST ?? '',
177
+ redisPort: options.redisPort ?? 6379,
178
+ redisTls: options.redisTls ?? (process.env.NODE_ENV === 'production'),
179
+ disableRedis: options.disableRedis ?? (process.env.NODE_ENV !== 'production'),
180
+ encryptionKey: encKeyRaw,
181
+ snapshotPath: options.snapshotPath ?? path.join(os.tmpdir(), ns ? `tricache-snapshot-${ns}.msgpack` : 'tricache-snapshot.msgpack'),
182
+ snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
183
+ invalidationBackplane: options.invalidationBackplane ?? true,
184
+ oomProtection: options.oomProtection ?? true,
185
+ oomHeapThreshold: options.oomHeapThreshold ?? 0.85,
186
+ oomCheckIntervalMs: options.oomCheckIntervalMs ?? 10_000,
187
+ oomEvictPercent: options.oomEvictPercent ?? 0.20,
188
+ onMetrics: options.onMetrics,
189
+ metricsIntervalMs: options.metricsIntervalMs ?? 60_000,
190
+ staleIfError: options.staleIfError ?? 0,
191
+ l2WriteMode: options.l2WriteMode ?? 'read-write',
192
+ instanceName: options.instanceName ?? '',
193
+ ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
194
+ tracer: options.tracer,
195
+ notFoundTtl: options.notFoundTtl ?? 0,
196
+ warmKeys: options.warmKeys,
197
+ };
198
+ // Circuit breaker for L2 Redis
199
+ const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
200
+ const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 30_000;
201
+ this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
202
+ // L1.5 disk tier
203
+ this.disk = new DiskTier({
204
+ dir: this.opts.diskCacheDir,
205
+ maxBytes: this.opts.diskMaxBytes,
206
+ entryMaxBytes: this.opts.diskEntryMaxBytes,
207
+ forbiddenPrefixes: forbiddenPrefixes,
208
+ encryptionKey: this.enc.isEnabled ? this.enc['_key'] : null,
209
+ logger,
210
+ });
211
+ this._namespace = ns;
212
+ this._redisDisabled = (this.opts.disableRedis || !this.opts.redisHost);
213
+ // L1 in-memory cache
214
+ this.l1 = new SmartMemoryCache({
215
+ maxBytes: this.opts.l1MaxBytes,
216
+ maxEntries: this.opts.l1MaxEntries,
217
+ categories: this.opts.categoryLimits,
218
+ diskSpill: (key, entry) => { void this.disk.save(key, entry); },
219
+ onEviction: options.onEviction,
220
+ logger,
221
+ });
222
+ // Load snapshot once per process
223
+ if (!this.snapshotLoaded) {
224
+ this.snapshotLoaded = true;
225
+ this.loadSnapshot();
226
+ }
227
+ // Graceful shutdown: persist L1 to disk
228
+ this._shutdownHandler = () => { this.writeSnapshot(); process.exit(0); };
229
+ process.once('SIGTERM', this._shutdownHandler);
230
+ process.once('SIGINT', this._shutdownHandler);
231
+ // Periodic cleanup (5 min)
232
+ this.cleanupInterval = setInterval(() => {
233
+ const cleaned = this.l1.cleanup();
234
+ const diskPurged = this.disk.purgeExpired();
235
+ if (cleaned > 0 || diskPurged > 0) {
236
+ this.logger.debug('Periodic cache cleanup', { cleaned, diskPurged });
237
+ }
238
+ }, 5 * 60 * 1000);
239
+ if (this.cleanupInterval.unref)
240
+ this.cleanupInterval.unref(); // don't block process exit
241
+ // OOM protection: evict coldest L1 entries when heap pressure rises
242
+ if (this.opts.oomProtection) {
243
+ this.oomInterval = setInterval(() => {
244
+ const mem = process.memoryUsage();
245
+ const used = mem.heapUsed / mem.heapTotal;
246
+ if (used >= this.opts.oomHeapThreshold) {
247
+ const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
248
+ this.counters.oomEvictions++;
249
+ this.counters.oomLastAt = Date.now();
250
+ this.logger.warn('tricache OOM guard: emergency L1 eviction', {
251
+ heapUsedPct: Math.round(used * 100),
252
+ threshold: Math.round(this.opts.oomHeapThreshold * 100),
253
+ evicted,
254
+ });
255
+ }
256
+ }, this.opts.oomCheckIntervalMs);
257
+ if (this.oomInterval.unref)
258
+ this.oomInterval.unref();
259
+ }
260
+ // Metrics callback
261
+ if (this.opts.onMetrics && this.opts.metricsIntervalMs > 0) {
262
+ this.metricsInterval = setInterval(() => {
263
+ try {
264
+ this.opts.onMetrics(this.metrics());
265
+ }
266
+ catch { /* never crash process */ }
267
+ }, this.opts.metricsIntervalMs);
268
+ if (this.metricsInterval.unref)
269
+ this.metricsInterval.unref();
270
+ }
271
+ // Backplane: assign instance ID + channel, then subscribe
272
+ this.instanceId = crypto.randomBytes(8).toString('hex');
273
+ this.backplaneChannel = `tricache:inv${ns ? ':' + ns : ''}`;
274
+ this.initBackplane();
275
+ // Auto-warm from L2 if warmKeys is configured; ready() waits for completion.
276
+ if (this.opts.warmKeys) {
277
+ this._readyPromise = this.warmFromL2(this.opts.warmKeys).then(() => undefined);
278
+ }
279
+ }
280
+ // ── Singleton factory ─────────────────────────────────────────────────────
281
+ /**
282
+ * Get (or create) the process-level singleton CacheService instance.
283
+ *
284
+ * Options are only applied on first call — subsequent calls return the
285
+ * existing instance regardless of options passed.
286
+ *
287
+ * When `namespace` is set the singleton is keyed by namespace, so two calls
288
+ * with different namespaces return independent instances.
289
+ */
290
+ static create(options) {
291
+ const g = globalThis;
292
+ const key = CacheService.globalKey(options);
293
+ if (!g[key])
294
+ g[key] = new CacheService(options);
295
+ return g[key];
296
+ }
297
+ /**
298
+ * Async factory — accepts a Promise that resolves to CacheOptions.
299
+ * Useful when config is fetched from a secret store at startup.
300
+ *
301
+ * @example
302
+ * const cache = await CacheService.createAsync(fetchSecrets());
303
+ */
304
+ static async createAsync(options) {
305
+ const resolved = await options;
306
+ return CacheService.create(resolved);
307
+ }
308
+ /** Replace the singleton (useful in tests). */
309
+ static reset(options) {
310
+ const g = globalThis;
311
+ const key = CacheService.globalKey(options);
312
+ const existing = g[key];
313
+ if (existing)
314
+ existing.destroy();
315
+ g[key] = new CacheService(options);
316
+ return g[key];
317
+ }
318
+ /** Derive the globalThis key for a given set of options. */
319
+ static globalKey(options) {
320
+ const ns = options?.namespace?.trim() ?? '';
321
+ return ns ? `__tricache_${ns}__` : GLOBAL_KEY;
322
+ }
323
+ // ── Redis connection ──────────────────────────────────────────────────────
324
+ /**
325
+ * Prepend the configured namespace to a raw cache key.
326
+ * Returns the key unchanged when namespace is empty.
327
+ *
328
+ * This is the only place the namespace prefix is applied — callers always
329
+ * receive and provide un-prefixed keys in the public API.
330
+ */
331
+ nk(key) {
332
+ return this._namespace ? `${this._namespace}:${key}` : key;
333
+ }
334
+ /** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
335
+ _jitterTtl(ttlMs) {
336
+ const j = this.opts.ttlJitterFactor;
337
+ if (j === 0)
338
+ return ttlMs;
339
+ return Math.round(ttlMs * (1 + (Math.random() * 2 - 1) * j));
340
+ }
341
+ /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
342
+ _startSpan(name) {
343
+ if (this.opts.tracer)
344
+ return this.opts.tracer.startSpan(name);
345
+ return { setAttribute() { return this; }, setStatus() { return this; }, end() { } };
346
+ }
347
+ initBackplane() {
348
+ if (!this.opts.invalidationBackplane || this._redisDisabled)
349
+ return;
350
+ if (this.subClient)
351
+ return;
352
+ const sub = new RedisClient({
353
+ host: this.opts.redisHost,
354
+ port: this.opts.redisPort,
355
+ tls: this.opts.redisTls ? {} : undefined,
356
+ connectTimeout: 10_000,
357
+ lazyConnect: true,
358
+ maxRetriesPerRequest: null,
359
+ enableAutoPipelining: false,
360
+ family: 4,
361
+ retryStrategy: (times) => Math.min(times * 50, 2_000),
362
+ });
363
+ sub.on('error', (e) => this.logger.debug('Backplane subscriber error', { error: e.message }));
364
+ sub.on('message', (_channel, message) => {
365
+ this._handleBackplaneMessage(message);
366
+ });
367
+ sub.subscribe(this.backplaneChannel)
368
+ .then(() => this.logger.info('Backplane: subscribed', {
369
+ channel: this.backplaneChannel, instanceId: this.instanceId,
370
+ }))
371
+ .catch((err) => this.logger.warn('Backplane: subscribe failed', {
372
+ error: err.message,
373
+ }));
374
+ this.subClient = sub;
375
+ }
376
+ /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
377
+ _handleBackplaneMessage(message) {
378
+ try {
379
+ const msg = JSON.parse(message);
380
+ if (msg.src === this.instanceId) {
381
+ this.counters.invSkipped++;
382
+ return; // own message — our L1 is already current
383
+ }
384
+ this.counters.invReceived++;
385
+ if (msg.op === 'del') {
386
+ // L1 eviction is synchronous and O(1); disk delete is deferred via
387
+ // setImmediate so the event-loop tick that processes this pub/sub
388
+ // message returns immediately without blocking hot get() calls.
389
+ this.l1.delete(msg.key);
390
+ setImmediate(() => this.disk.delete(msg.key));
391
+ // Cascade: evict dependents registered on this instance for the
392
+ // deleted key — same logic the local delete() path runs, now also
393
+ // applied to peer-originated invalidations so fleet-wide deletes
394
+ // propagate dependency cascades to every node.
395
+ this._cascadeDependencies(msg.key);
396
+ }
397
+ else if (msg.op === 'del-glob') {
398
+ // Glob patterns clean L1 only — disk entries expire naturally via
399
+ // the background purge timer or are bypassed on the next L1 miss.
400
+ this.l1.deletePattern(msg.key);
401
+ }
402
+ this.logger.debug('Backplane: peer invalidation applied', {
403
+ op: msg.op, key: msg.key.slice(0, 60),
404
+ });
405
+ }
406
+ catch { /* malformed message — ignore */ }
407
+ }
408
+ async publishInvalidation(op, key) {
409
+ if (!this.opts.invalidationBackplane || this._redisDisabled)
410
+ return;
411
+ try {
412
+ const client = await this.getRedis();
413
+ await client.publish(this.backplaneChannel, JSON.stringify({ op, key, src: this.instanceId }));
414
+ this.counters.invSent++;
415
+ }
416
+ catch { /* non-critical — never block the caller */ }
417
+ }
418
+ async getRedis() {
419
+ if (!this.cb.isAllowed())
420
+ throw new Error('tricache: L2 circuit breaker is open');
421
+ if (this.redisConnecting)
422
+ return this.redisConnecting;
423
+ this.redisConnecting = (async () => {
424
+ try {
425
+ const client = new RedisClient({
426
+ host: this.opts.redisHost,
427
+ port: this.opts.redisPort,
428
+ tls: this.opts.redisTls ? {} : undefined,
429
+ connectTimeout: 10_000,
430
+ lazyConnect: false,
431
+ maxRetriesPerRequest: 3,
432
+ enableAutoPipelining: true,
433
+ keepAlive: 30_000,
434
+ family: 4,
435
+ retryStrategy: (times) => Math.min(times * 50, 2_000),
436
+ });
437
+ client.on('connect', () => this.logger.info('Redis connected', { host: this.opts.redisHost }));
438
+ client.on('error', (e) => this.logger.error('Redis error', { host: this.opts.redisHost }, e));
439
+ client.on('reconnecting', () => this.logger.debug('Redis reconnecting'));
440
+ await new Promise((resolve, reject) => {
441
+ client.once('ready', resolve);
442
+ client.once('error', reject);
443
+ setTimeout(() => reject(new Error('Redis connection timeout')), 15_000);
444
+ });
445
+ this.cb.onSuccess();
446
+ this.redis = client;
447
+ this.redisConnecting = null;
448
+ return client;
449
+ }
450
+ catch (err) {
451
+ this.cb.onFailure();
452
+ this.redisConnecting = null; // allow retry on next call — fixes the cached-rejection bug
453
+ throw err;
454
+ }
455
+ })();
456
+ return this.redisConnecting;
457
+ }
458
+ // ── Snapshot (cold-start persistence) ────────────────────────────────────
459
+ writeSnapshot(altPath) {
460
+ try {
461
+ const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
462
+ if (entries.length === 0)
463
+ return;
464
+ const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
465
+ const packed = pack(payload);
466
+ const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
467
+ const dest = altPath ?? this.opts.snapshotPath;
468
+ fs.writeFileSync(dest, final, { mode: 0o600 });
469
+ this.logger.info('Cache snapshot written', {
470
+ path: dest, entries: entries.length,
471
+ sizeKB: Math.round(final.length / 1024), encrypted: this.enc.isEnabled,
472
+ });
473
+ }
474
+ catch (err) {
475
+ this.logger.warn('Cache snapshot write failed', { error: err.message });
476
+ }
477
+ }
478
+ loadSnapshot() {
479
+ const snapshotPath = this.opts.snapshotPath;
480
+ try {
481
+ if (!fs.existsSync(snapshotPath))
482
+ return;
483
+ const stat = fs.statSync(snapshotPath);
484
+ if (stat.size > SNAPSHOT_MAX_FILE_BYTES) {
485
+ this.logger.warn('Snapshot rejected: exceeds size limit', { sizeBytes: stat.size });
486
+ fs.unlinkSync(snapshotPath);
487
+ return;
488
+ }
489
+ const raw = fs.readFileSync(snapshotPath);
490
+ fs.unlinkSync(snapshotPath); // delete immediately — don't leave cache data on disk
491
+ let buf;
492
+ try {
493
+ buf = this.enc.decryptBuffer(raw);
494
+ }
495
+ catch (e) {
496
+ this.logger.warn('Snapshot rejected: decryption failed', { error: e.message });
497
+ return;
498
+ }
499
+ const snapshot = unpack(buf);
500
+ if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
501
+ this.logger.warn('Snapshot rejected: version mismatch', { got: snapshot?.version });
502
+ return;
503
+ }
504
+ const ageMs = Date.now() - (snapshot.writtenAt ?? 0);
505
+ if (ageMs > this.opts.snapshotMaxAgeMs || ageMs < 0) {
506
+ this.logger.warn('Snapshot rejected: too old', { ageMinutes: Math.round(ageMs / 60000) });
507
+ return;
508
+ }
509
+ if (!Array.isArray(snapshot.entries)) {
510
+ this.logger.warn('Snapshot rejected: entries is not an array');
511
+ return;
512
+ }
513
+ const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
514
+ this.logger.info('Cache snapshot loaded (L1 is warm)', {
515
+ loaded, total: snapshot.entries.length,
516
+ sizeKB: this.l1.getStats().sizeKB,
517
+ });
518
+ }
519
+ catch (err) {
520
+ this.logger.warn('Snapshot load failed — starting cold', { error: err.message });
521
+ try {
522
+ fs.unlinkSync(snapshotPath);
523
+ }
524
+ catch { /* ok */ }
525
+ }
526
+ }
527
+ // ── Core get (L1 → L1.5 → L2 → fetch) ───────────────────────────────────
528
+ /**
529
+ * Get a value from cache, or fetch and cache it.
530
+ *
531
+ * @param cacheKey - Unique key identifying this value
532
+ * @param fetchFn - Called on a cache miss; its return value is cached and returned
533
+ * @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
534
+ * @param opts.priority - Override the auto-inferred eviction priority
535
+ * @param opts.swr - Stale-While-Revalidate grace seconds.
536
+ * @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
537
+ * is triggered proactively while the caller still receives the
538
+ * cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
539
+ * Requires `fetchFn` to be stable across calls.
540
+ * @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
541
+ * recompute more aggressively before expiry. Typical range: 0.5–2.
542
+ * Complementary to refreshAhead — uses recompute cost (delta) to
543
+ * decide probabilistically rather than at a fixed threshold.
544
+ * @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
545
+ * Caches negative lookups to avoid repeated DB hits for missing keys.
546
+ */
547
+ async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
548
+ const span = this._startSpan('tricache.get');
549
+ span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
550
+ const k = this.nk(cacheKey); // namespaced key used for all storage
551
+ this.counters.gets++;
552
+ // L1: in-memory (fastest path)
553
+ const l1Hit = this.l1.get(k);
554
+ if (l1Hit !== null) {
555
+ if (l1Hit.isStale) {
556
+ const swrGraceMs = (opts.swr ?? 0) * 1_000;
557
+ if (swrGraceMs > 0 && !this.revalidating.has(k)) {
558
+ const priority = opts.priority ?? inferPriority(cacheKey);
559
+ this.revalidating.add(k);
560
+ void this._revalidate(k, fetchFn, ttlSeconds * 1_000, swrGraceMs, priority);
561
+ this.counters.swrRevalidations++;
562
+ this.logger.debug('SWR: serving stale, revalidating', { cacheKey });
563
+ }
564
+ else {
565
+ this.logger.debug('L1 hit');
566
+ }
567
+ }
568
+ else {
569
+ this.logger.debug('L1 hit');
570
+ // Refresh-ahead and XFetch: proactively recompute a fresh entry before it expires.
571
+ // l1Hit already carries expiresAt/ttlMs/delta — no second Map lookup needed.
572
+ if (!this.revalidating.has(k) && (opts.refreshAhead || opts.xfetchBeta)) {
573
+ const now = Date.now();
574
+ const remaining = l1Hit.expiresAt - now;
575
+ const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1_000;
576
+ const shouldRefreshAhead = opts.refreshAhead != null && opts.refreshAhead > 0
577
+ ? remaining <= entryTtl * (1 - opts.refreshAhead)
578
+ : false;
579
+ // XFetch: fire with probability proportional to recompute cost (delta) vs. remaining TTL
580
+ // Formula: fire when remaining <= delta * beta * -ln(U), U ~ uniform(0,1)
581
+ const shouldXFetch = opts.xfetchBeta != null && opts.xfetchBeta > 0 && l1Hit.delta != null
582
+ ? remaining <= l1Hit.delta * opts.xfetchBeta * -Math.log(Math.random())
583
+ : false;
584
+ if (shouldRefreshAhead || shouldXFetch) {
585
+ // Defer inferPriority until we actually need it — avoids 3× string.includes()
586
+ // scans on every warm hit when the threshold check is false (the common case).
587
+ const priority = opts.priority ?? inferPriority(cacheKey);
588
+ this.revalidating.add(k);
589
+ void this._revalidate(k, fetchFn, entryTtl, (opts.swr ?? 0) * 1_000, priority);
590
+ this.counters.swrRevalidations++;
591
+ this.logger.debug(shouldXFetch ? 'XFetch: proactive background recompute' : 'Refresh-ahead: proactive background recompute', { cacheKey, remainingMs: remaining, ttlMs: entryTtl });
592
+ }
593
+ }
594
+ }
595
+ this.counters.l1Hits++;
596
+ span.setAttribute('cache.hit', 'l1').end();
597
+ return l1Hit.value;
598
+ }
599
+ const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
600
+ const swrGraceMs = (opts.swr ?? 0) * 1_000;
601
+ const priority = opts.priority ?? inferPriority(cacheKey);
602
+ // L2: Redis (distributed, production-only by default)
603
+ if (!this._redisDisabled) {
604
+ try {
605
+ const client = await this.getRedis();
606
+ const raw = await client.get(k);
607
+ this.cb.onSuccess();
608
+ if (raw) {
609
+ const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
610
+ const parsed = JSON.parse(decrypted);
611
+ this.l1.set(k, parsed, ttlMs, priority);
612
+ this.counters.l2Hits++;
613
+ this.logger.debug('L2 hit (Redis)', { cacheKey });
614
+ span.setAttribute('cache.hit', 'l2').end();
615
+ return parsed;
616
+ }
617
+ }
618
+ catch (err) {
619
+ this.cb.onFailure();
620
+ this.logger.debug('Redis unavailable, continuing to fetch', { cacheKey, error: err.message });
621
+ }
622
+ }
623
+ // L1.5: disk tier (evicted L1 entries)
624
+ const diskHit = this.disk.load(k);
625
+ if (diskHit !== null) {
626
+ const promoted = this.l1.importEntries([{ key: k, entry: diskHit }], this.opts.forbiddenSnapshotPrefixes);
627
+ if (promoted > 0) {
628
+ const l1Check = this.l1.get(k);
629
+ if (l1Check !== null) {
630
+ this.counters.diskHits++;
631
+ this.logger.debug('L1.5 hit (disk → L1)', { cacheKey });
632
+ span.setAttribute('cache.hit', 'disk').end();
633
+ return l1Check.value;
634
+ }
635
+ }
636
+ }
637
+ span.setAttribute('cache.hit', 'miss');
638
+ // Cache MISS: thundering-herd prevention
639
+ const existing = this.inflight.get(k);
640
+ if (existing) {
641
+ this.counters.stampedes++;
642
+ this.logger.debug('Stampede prevented — coalescing onto inflight fetch', { cacheKey });
643
+ span.end();
644
+ return existing;
645
+ }
646
+ const fetchPromise = (async () => {
647
+ try {
648
+ this.counters.fetches++;
649
+ const fetchStart = Date.now();
650
+ const data = await fetchFn();
651
+ const delta = Date.now() - fetchStart;
652
+ // Negative caching: null/undefined results get their own (shorter) TTL
653
+ const notFoundTtlMs = (opts.notFoundTtl ?? this.opts.notFoundTtl) * 1_000;
654
+ const effectiveTtl = (data == null && notFoundTtlMs > 0) ? notFoundTtlMs : ttlMs;
655
+ const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : undefined;
656
+ const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
657
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta);
658
+ if (!this._redisDisabled) {
659
+ try {
660
+ const client = await this.getRedis();
661
+ const serialized = JSON.stringify(data);
662
+ const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
663
+ await client.setex(k, Math.ceil(effectiveTtl / 1_000), toStore);
664
+ this.cb.onSuccess();
665
+ this.logger.debug('Cached L1+L2', { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
666
+ }
667
+ catch {
668
+ this.cb.onFailure();
669
+ this.logger.debug('Cached L1 only (Redis unavailable)', { cacheKey });
670
+ }
671
+ }
672
+ else {
673
+ this.logger.debug('Cached L1', { cacheKey });
674
+ }
675
+ return data;
676
+ }
677
+ finally {
678
+ this.inflight.delete(k);
679
+ span.end();
680
+ }
681
+ })();
682
+ this.inflight.set(k, fetchPromise);
683
+ return fetchPromise;
684
+ }
685
+ async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
686
+ try {
687
+ const fetchStart = Date.now();
688
+ const data = await fetchFn();
689
+ const delta = Date.now() - fetchStart;
690
+ const staleAt = Date.now() + ttlMs;
691
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta);
692
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
693
+ try {
694
+ const client = await this.getRedis();
695
+ const s = JSON.stringify(data);
696
+ const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
697
+ await client.setex(cacheKey, Math.ceil(ttlMs / 1_000), stored);
698
+ }
699
+ catch { /* ok */ }
700
+ }
701
+ this.logger.debug('SWR: revalidation complete', { cacheKey });
702
+ }
703
+ catch (err) {
704
+ if (this.opts.staleIfError > 0) {
705
+ const additionalMs = this.opts.staleIfError * 1_000;
706
+ this.l1.bumpExpiry(cacheKey, additionalMs);
707
+ this.logger.debug('SWR: revalidation failed, stale-if-error extending expiry', {
708
+ cacheKey, staleIfErrorSecs: this.opts.staleIfError,
709
+ });
710
+ }
711
+ else {
712
+ this.logger.debug('SWR: revalidation failed', { cacheKey, error: err.message });
713
+ }
714
+ }
715
+ finally {
716
+ this.revalidating.delete(cacheKey);
717
+ }
718
+ }
719
+ // ── Explicit set / delete ─────────────────────────────────────────────────
720
+ /** Explicitly write a value into L1 (+ L2 in production). */
721
+ async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
722
+ const span = this._startSpan('tricache.set');
723
+ span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
724
+ const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
725
+ const p = priority ?? inferPriority(cacheKey);
726
+ const k = this.nk(cacheKey);
727
+ this.counters.sets++;
728
+ this.l1.set(k, data, ttlMs, p);
729
+ // Register tags in the in-process index (+ Redis SADD)
730
+ if (opts?.tags?.length) {
731
+ for (const tag of opts.tags) {
732
+ const tagKey = this.nk(`_tag_:${tag}`);
733
+ let members = this.tagIndex.get(tagKey);
734
+ if (!members) {
735
+ members = new Set();
736
+ this.tagIndex.set(tagKey, members);
737
+ }
738
+ members.add(k);
739
+ }
740
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
741
+ try {
742
+ const client = await this.getRedis();
743
+ const pl = client.pipeline();
744
+ for (const tag of opts.tags) {
745
+ const tagKey = this.nk(`_tag_:${tag}`);
746
+ pl.sadd(tagKey, k);
747
+ pl.expire(tagKey, ttlSeconds + 3_600);
748
+ }
749
+ await pl.exec();
750
+ this.cb.onSuccess();
751
+ }
752
+ catch {
753
+ this.cb.onFailure(); /* tags are best-effort */
754
+ }
755
+ }
756
+ }
757
+ // Register dependency patterns: when any key matching a pattern is deleted,
758
+ // this key (k) is automatically cascaded.
759
+ if (opts?.dependsOn?.length) {
760
+ for (const pattern of opts.dependsOn) {
761
+ const nsPattern = this.nk(pattern);
762
+ let deps = this.dependencyIndex.get(nsPattern);
763
+ if (!deps) {
764
+ deps = new Set();
765
+ this.dependencyIndex.set(nsPattern, deps);
766
+ }
767
+ deps.add(k);
768
+ }
769
+ }
770
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
771
+ try {
772
+ const client = await this.getRedis();
773
+ const s = JSON.stringify(data);
774
+ const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
775
+ await client.setex(k, Math.ceil(ttlMs / 1_000), stored);
776
+ this.cb.onSuccess();
777
+ }
778
+ catch (err) {
779
+ this.cb.onFailure();
780
+ this.logger.debug('set: Redis unavailable', { cacheKey, error: err.message });
781
+ }
782
+ }
783
+ void this.publishInvalidation('del', k);
784
+ span.end();
785
+ }
786
+ /**
787
+ * Delete one key or a glob pattern (supports `*` wildcard).
788
+ *
789
+ * @example
790
+ * await cache.delete('user:abc:profile'); // exact key
791
+ * await cache.delete('user:abc:*'); // all keys for user abc
792
+ */
793
+ async delete(cacheKey) {
794
+ const span = this._startSpan('tricache.delete');
795
+ span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
796
+ const isPattern = cacheKey.includes('*');
797
+ const k = this.nk(cacheKey);
798
+ this.counters.deletes++;
799
+ if (isPattern) {
800
+ this.l1.deletePattern(k);
801
+ }
802
+ else {
803
+ this.l1.delete(k);
804
+ this.disk.delete(k);
805
+ // Cascade: invalidate any key that declared it depends on this exact key's pattern
806
+ this._cascadeDependencies(k);
807
+ // Clean up: remove k from all dependency registrations (it is gone)
808
+ for (const [, dependents] of this.dependencyIndex)
809
+ dependents.delete(k);
810
+ }
811
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
812
+ try {
813
+ const client = await this.getRedis();
814
+ if (isPattern) {
815
+ const stream = client.scanStream({ match: k, count: 100 });
816
+ const keys = [];
817
+ await new Promise((resolve, reject) => {
818
+ stream.on('data', (chunk) => keys.push(...chunk));
819
+ stream.on('end', resolve);
820
+ stream.on('error', reject);
821
+ });
822
+ if (keys.length > 0)
823
+ await client.del(...keys);
824
+ }
825
+ else {
826
+ await client.del(k);
827
+ }
828
+ this.cb.onSuccess();
829
+ }
830
+ catch (err) {
831
+ this.cb.onFailure();
832
+ this.logger.debug('delete: Redis unavailable', { cacheKey, error: err.message });
833
+ }
834
+ }
835
+ void this.publishInvalidation(isPattern ? 'del-glob' : 'del', k);
836
+ span.end();
837
+ }
838
+ // ── Counter (distributed rate limiting) ──────────────────────────────────
839
+ /**
840
+ * Atomically increment a counter in Redis. Returns the new value.
841
+ * Returns 0 if Redis is disabled (safe fallback — rate limiting won't block in dev).
842
+ */
843
+ async increment(cacheKey, ttlSeconds) {
844
+ const k = this.nk(cacheKey);
845
+ if (this._redisDisabled) {
846
+ const now = Date.now();
847
+ const ttlMs = (ttlSeconds ?? 60) * 1_000;
848
+ const entry = this._l1Counters.get(k);
849
+ if (entry && entry.expiresAt > now) {
850
+ entry.value++;
851
+ return entry.value;
852
+ }
853
+ this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
854
+ return 1;
855
+ }
856
+ try {
857
+ const client = await this.getRedis();
858
+ const count = await client.incr(k);
859
+ if (count === 1 && ttlSeconds)
860
+ await client.expire(k, ttlSeconds);
861
+ return count;
862
+ }
863
+ catch (err) {
864
+ this.logger.error('increment: Redis error', { cacheKey }, err);
865
+ return 0;
866
+ }
867
+ }
868
+ // ── Clear / Rebalance / TTL ────────────────────────────────────────────────
869
+ /**
870
+ * Flush all cached entries, or only those whose key starts with `prefix`.
871
+ *
872
+ * @example
873
+ * await cache.clear(); // flush everything
874
+ * await cache.clear('user:abc'); // flush all keys for one user
875
+ */
876
+ async clear(prefix) {
877
+ this.counters.deletes++;
878
+ const k = prefix
879
+ ? this.nk(prefix.includes('*') ? prefix : `${prefix}*`)
880
+ : undefined;
881
+ if (k) {
882
+ this.l1.deletePattern(k);
883
+ // Disk-tier pattern delete is not supported (files are keyed by SHA-256 hash);
884
+ // prefix-scoped clears only evict from L1, matching existing delete('glob*') semantics.
885
+ }
886
+ else {
887
+ this.l1.clear();
888
+ this.disk.clear();
889
+ this._l1Counters.clear();
890
+ this.tagIndex.clear();
891
+ }
892
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
893
+ try {
894
+ const client = await this.getRedis();
895
+ const pattern = k ?? (this._namespace ? `${this._namespace}:*` : '*');
896
+ const stream = client.scanStream({ match: pattern, count: 100 });
897
+ const keys = [];
898
+ await new Promise((resolve, reject) => {
899
+ stream.on('data', (chunk) => keys.push(...chunk));
900
+ stream.on('end', resolve);
901
+ stream.on('error', reject);
902
+ });
903
+ if (keys.length > 0)
904
+ await client.del(...keys);
905
+ }
906
+ catch (err) {
907
+ this.logger.debug('clear: Redis unavailable', { error: err.message });
908
+ }
909
+ }
910
+ void this.publishInvalidation('del-glob', k ?? (this._namespace ? `${this._namespace}:*` : '*'));
911
+ }
912
+ /**
913
+ * Evict L1 entries that violate the current category or global capacity limits.
914
+ * Useful after a write burst or after adding stricter `categoryLimits`.
915
+ * Returns the number of entries evicted.
916
+ */
917
+ rebalance() {
918
+ return this.l1.rebalance();
919
+ }
920
+ /**
921
+ * Return the remaining TTL in seconds for a key currently in L1.
922
+ * Returns null if the key is absent from L1 or has already expired.
923
+ * Only reflects L1 state — does not query Redis or disk.
924
+ */
925
+ ttl(cacheKey) {
926
+ return this.l1.ttl(this.nk(cacheKey));
927
+ }
928
+ /**
929
+ * Return true if the key exists in L1 and has not expired.
930
+ * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
931
+ */
932
+ has(cacheKey) {
933
+ return this.l1.has(this.nk(cacheKey));
934
+ }
935
+ // ── Iteration ─────────────────────────────────────────────────────────────
936
+ /**
937
+ * Lazily yield every non-expired L1 key, stripped of its namespace prefix.
938
+ *
939
+ * @example
940
+ * for (const key of cache.keys()) console.log(key);
941
+ */
942
+ *keys() {
943
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
944
+ for (const key of this.l1.liveKeys()) {
945
+ yield prefixLen > 0 ? key.slice(prefixLen) : key;
946
+ }
947
+ }
948
+ /**
949
+ * Lazily yield every non-expired L1 value.
950
+ * Each value is the cached (pre-deserialized) JS object — no unpack overhead.
951
+ *
952
+ * @example
953
+ * for (const val of cache.values<User>()) console.log(val.id);
954
+ */
955
+ *values() {
956
+ // yield* delegates directly into liveValues(), collapsing one generator frame.
957
+ yield* this.l1.liveValues();
958
+ }
959
+ /**
960
+ * Lazily yield every non-expired L1 [key, value] pair.
961
+ * Keys are stripped of their namespace prefix.
962
+ *
963
+ * @example
964
+ * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
965
+ */
966
+ *entries() {
967
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
968
+ for (const [key, entry] of this.l1.liveEntries()) {
969
+ const k = prefixLen > 0 ? key.slice(prefixLen) : key;
970
+ yield [k, (entry.value !== undefined ? entry.value : entry.data)];
971
+ }
972
+ }
973
+ /**
974
+ * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
975
+ * Returns `false` if the key is absent or already expired.
976
+ *
977
+ * @param newTtlSeconds - The new TTL from now, in seconds.
978
+ */
979
+ async touch(cacheKey, newTtlSeconds) {
980
+ const k = this.nk(cacheKey);
981
+ const hit = this.l1.touch(k, newTtlSeconds * 1_000);
982
+ if (hit && !this._redisDisabled) {
983
+ try {
984
+ const client = await this.getRedis();
985
+ void client.expire(k, newTtlSeconds); // fire-and-forget
986
+ }
987
+ catch { /* ok */ }
988
+ }
989
+ return hit;
990
+ }
991
+ /**
992
+ * Return the cached value from L1 **only if it is fresh** (not in the SWR grace window).
993
+ * Returns `null` when the key is absent, expired, or stale — without triggering a fetch.
994
+ *
995
+ * @example
996
+ * const fresh = cache.getIfFresh('user:123');
997
+ * if (fresh !== null) return fresh; // serve from L1, no network hop
998
+ */
999
+ getIfFresh(cacheKey) {
1000
+ const k = this.nk(cacheKey);
1001
+ const entry = this.l1.getEntry(k);
1002
+ if (!entry)
1003
+ return null;
1004
+ const now = Date.now();
1005
+ if (entry.expiresAt <= now)
1006
+ return null; // expired
1007
+ if (entry.staleAt !== undefined && entry.staleAt < now)
1008
+ return null; // in SWR grace
1009
+ return (entry.value !== undefined ? entry.value : unpack(entry.data));
1010
+ }
1011
+ /**
1012
+ * Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
1013
+ * Preserves input ordering. Uses inflight coalescing per key.
1014
+ *
1015
+ * @param keys - Array of cache keys.
1016
+ * @param fetchFn - Called with only the keys that missed L1.
1017
+ * @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
1018
+ * `(key) => number` so heterogeneous TTLs can be batched in one call.
1019
+ */
1020
+ async mget(keys, fetchFn, ttl = 300, priority) {
1021
+ const result = new Array(keys.length);
1022
+ const missIndexes = [];
1023
+ const missKeys = [];
1024
+ for (let i = 0; i < keys.length; i++) {
1025
+ const entry = this.l1.getEntry(this.nk(keys[i]));
1026
+ if (entry && entry.expiresAt > Date.now()) {
1027
+ result[i] = (entry.value !== undefined ? entry.value : unpack(entry.data));
1028
+ this.counters.l1Hits++;
1029
+ }
1030
+ else {
1031
+ missIndexes.push(i);
1032
+ missKeys.push(keys[i]);
1033
+ }
1034
+ }
1035
+ if (missKeys.length > 0) {
1036
+ const fetched = await fetchFn(missKeys);
1037
+ for (let j = 0; j < missKeys.length; j++) {
1038
+ const v = fetched[missKeys[j]];
1039
+ result[missIndexes[j]] = v;
1040
+ if (v !== undefined) {
1041
+ const resolvedTtl = typeof ttl === 'function' ? ttl(missKeys[j]) : ttl;
1042
+ await this.set(missKeys[j], v, resolvedTtl, priority);
1043
+ }
1044
+ }
1045
+ }
1046
+ return result;
1047
+ }
1048
+ /**
1049
+ * Returns a Promise that resolves once the cache is fully initialised and any
1050
+ * startup warming configured via `warmKeys` has completed.
1051
+ *
1052
+ * Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once
1053
+ * `warmFromL2(warmKeys)` finishes — ideal for k8s readiness probes.
1054
+ *
1055
+ * @example
1056
+ * const cache = CacheService.create({ warmKeys: 'user:*' });
1057
+ * await cache.ready(); // gate traffic until warm
1058
+ */
1059
+ ready() {
1060
+ return this._readyPromise;
1061
+ }
1062
+ /**
1063
+ * Batch write — set multiple entries in a single call.
1064
+ * TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
1065
+ *
1066
+ * @example
1067
+ * await cache.mset({
1068
+ * 'user:1': { value: { name: 'Alice' }, ttl: 300 },
1069
+ * 'user:2': { value: { name: 'Bob' }, ttl: 300, priority: CachePriority.HIGH },
1070
+ * });
1071
+ */
1072
+ async mset(entries) {
1073
+ const keys = Object.keys(entries);
1074
+ await Promise.all(keys.map(key => {
1075
+ const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
1076
+ const hasOpts = tags?.length || dependsOn?.length;
1077
+ return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : undefined);
1078
+ }));
1079
+ }
1080
+ /**
1081
+ * Batch delete — delete multiple exact keys in a single call.
1082
+ * Glob patterns are not supported; use `delete('prefix:*')` for patterns.
1083
+ *
1084
+ * @example
1085
+ * await cache.mdel(['user:1', 'user:2', 'user:3']);
1086
+ */
1087
+ async mdel(keys) {
1088
+ await Promise.all(keys.map(k => this.delete(k)));
1089
+ }
1090
+ /**
1091
+ * Warm L1 from L2 (Redis) by scanning for keys matching a glob pattern and
1092
+ * pulling them into L1. Useful on startup to eliminate cold-start penalty when
1093
+ * the local snapshot is unavailable or too stale.
1094
+ *
1095
+ * Returns the number of keys loaded into L1.
1096
+ *
1097
+ * @example
1098
+ * // In your startup hook (e.g. ECS task, k8s readiness probe):
1099
+ * const loaded = await cache.warmFromL2('org:*');
1100
+ * console.log(`Warmed ${loaded} keys from Redis`);
1101
+ */
1102
+ async warmFromL2(pattern) {
1103
+ if (this._redisDisabled)
1104
+ return 0;
1105
+ try {
1106
+ const client = await this.getRedis();
1107
+ const nsPattern = this.nk(pattern);
1108
+ // Collect all matching keys via SCAN
1109
+ const matchedKeys = [];
1110
+ const stream = client.scanStream({ match: nsPattern, count: 100 });
1111
+ await new Promise((resolve, reject) => {
1112
+ stream.on('data', (chunk) => matchedKeys.push(...chunk));
1113
+ stream.on('end', resolve);
1114
+ stream.on('error', reject);
1115
+ });
1116
+ if (matchedKeys.length === 0) {
1117
+ this.cb.onSuccess();
1118
+ return 0;
1119
+ }
1120
+ // Fetch values in a pipeline and load into L1
1121
+ const pl = client.pipeline();
1122
+ for (const k of matchedKeys)
1123
+ pl.get(k);
1124
+ const results = await pl.exec();
1125
+ this.cb.onSuccess();
1126
+ let loaded = 0;
1127
+ const now = Date.now();
1128
+ for (let i = 0; i < matchedKeys.length; i++) {
1129
+ const [err, raw] = results[i];
1130
+ if (err || raw == null)
1131
+ continue;
1132
+ try {
1133
+ const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
1134
+ const parsed = JSON.parse(decrypted);
1135
+ // Use a 10-minute TTL as a reasonable default; the real TTL is not
1136
+ // returned by GET (use PTTL to be precise, but that doubles round-trips).
1137
+ const remainingMs = 10 * 60 * 1_000;
1138
+ this.l1.set(matchedKeys[i], parsed, remainingMs, inferPriority(matchedKeys[i]));
1139
+ loaded++;
1140
+ }
1141
+ catch { /* skip malformed entries */ }
1142
+ }
1143
+ void now; // suppress unused warning
1144
+ this.logger.info('warmFromL2 complete', {
1145
+ pattern, matched: matchedKeys.length, loaded,
1146
+ });
1147
+ return loaded;
1148
+ }
1149
+ catch (err) {
1150
+ this.cb.onFailure();
1151
+ this.logger.debug('warmFromL2: Redis unavailable', { error: err.message });
1152
+ return 0;
1153
+ }
1154
+ }
1155
+ /**
1156
+ * Invalidate all keys associated with a tag.
1157
+ * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
1158
+ *
1159
+ * @example
1160
+ * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
1161
+ * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
1162
+ */
1163
+ async invalidateTag(tag) {
1164
+ const tagKey = this.nk(`_tag_:${tag}`);
1165
+ const members = this.tagIndex.get(tagKey) ?? new Set();
1166
+ // Remove from L1 + disk
1167
+ for (const k of members) {
1168
+ this.l1.delete(k);
1169
+ this.disk.delete(k);
1170
+ }
1171
+ this.tagIndex.delete(tagKey);
1172
+ if (!this._redisDisabled) {
1173
+ try {
1174
+ const client = await this.getRedis();
1175
+ const redisMembers = await client.smembers(tagKey);
1176
+ const toDelete = [...new Set([...members, ...redisMembers])];
1177
+ if (toDelete.length > 0) {
1178
+ await client.del(...toDelete, tagKey);
1179
+ }
1180
+ else {
1181
+ await client.del(tagKey);
1182
+ }
1183
+ }
1184
+ catch (err) {
1185
+ this.logger.debug('invalidateTag: Redis unavailable', { tag, error: err.message });
1186
+ }
1187
+ }
1188
+ }
1189
+ /**
1190
+ * Measure L1 / disk / Redis latency.
1191
+ * Useful for health checks and dashboards.
1192
+ *
1193
+ * @returns `{ l1, disk, l2 }` latencies in milliseconds.
1194
+ * `l2` is `null` when Redis is disabled.
1195
+ */
1196
+ async ping() {
1197
+ // L1: measure a has() call
1198
+ const t0 = Date.now();
1199
+ this.l1.has('__ping__');
1200
+ const l1 = Date.now() - t0;
1201
+ // Disk: measure a stats access
1202
+ const t1 = Date.now();
1203
+ void this.disk.stats;
1204
+ const disk = Date.now() - t1;
1205
+ // L2: PING command
1206
+ let l2 = null;
1207
+ if (!this._redisDisabled) {
1208
+ try {
1209
+ const client = await this.getRedis();
1210
+ const t2 = Date.now();
1211
+ await client.ping();
1212
+ l2 = Date.now() - t2;
1213
+ }
1214
+ catch {
1215
+ l2 = null;
1216
+ }
1217
+ }
1218
+ return { l1, disk, l2 };
1219
+ }
1220
+ /**
1221
+ * Export all live L1 entries to Redis via a single pipeline.
1222
+ * Useful for warming a new Redis instance or for zero-downtime failover.
1223
+ * Returns the number of keys written.
1224
+ */
1225
+ async drainToL2() {
1226
+ if (this._redisDisabled)
1227
+ return 0;
1228
+ try {
1229
+ const client = await this.getRedis();
1230
+ const entries = this.l1.exportEntries([]);
1231
+ const now = Date.now();
1232
+ if (entries.length === 0)
1233
+ return 0;
1234
+ const pl = client.pipeline();
1235
+ for (const { key, entry } of entries) {
1236
+ const remainingMs = entry.expiresAt - now;
1237
+ if (remainingMs <= 0)
1238
+ continue;
1239
+ const ttlSecs = Math.max(1, Math.ceil(remainingMs / 1_000));
1240
+ const s = JSON.stringify(entry.value);
1241
+ const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
1242
+ pl.setex(key, ttlSecs, stored);
1243
+ }
1244
+ await pl.exec();
1245
+ return entries.length;
1246
+ }
1247
+ catch (err) {
1248
+ this.logger.debug('drainToL2: Redis unavailable', { error: err.message });
1249
+ return 0;
1250
+ }
1251
+ }
1252
+ // ── Stats ─────────────────────────────────────────────────────────────
1253
+ stats() {
1254
+ return {
1255
+ l1: this.l1.getStats(),
1256
+ disk: this.disk.stats,
1257
+ };
1258
+ }
1259
+ // ── Conditional write ─────────────────────────────────────────────────
1260
+ /**
1261
+ * Write `value` only if the key is not already cached.
1262
+ * Returns `true` if the write happened, `false` if the key already existed.
1263
+ *
1264
+ * When Redis is available, atomicity is guaranteed via `SET NX EX` so this
1265
+ * is safe to use for idempotency keys and "first writer wins" patterns across
1266
+ * multiple instances. L1 is populated on success.
1267
+ *
1268
+ * @example
1269
+ * const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
1270
+ * if (!claimed) return res.status(409).json({ error: 'duplicate request' });
1271
+ */
1272
+ async setIfAbsent(cacheKey, value, ttlSeconds = 300, priority) {
1273
+ const k = this.nk(cacheKey);
1274
+ // Fast path: L1 check (process-local, no network hop)
1275
+ if (this.l1.has(k))
1276
+ return false;
1277
+ if (!this._redisDisabled) {
1278
+ try {
1279
+ const client = await this.getRedis();
1280
+ const serialized = JSON.stringify(value);
1281
+ const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
1282
+ // SET key value EX ttl NX — atomic; returns 'OK' on success, null if key exists
1283
+ const result = await client.set(k, toStore, 'EX', ttlSeconds, 'NX');
1284
+ this.cb.onSuccess();
1285
+ if (result === null)
1286
+ return false; // already exists in Redis
1287
+ }
1288
+ catch (err) {
1289
+ this.cb.onFailure();
1290
+ this.logger.debug('setIfAbsent: Redis unavailable, falling back to L1 check', { cacheKey, error: err.message });
1291
+ // Re-check L1 after Redis failure — another thread may have won the race
1292
+ if (this.l1.has(k))
1293
+ return false;
1294
+ }
1295
+ }
1296
+ const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
1297
+ const p = priority ?? inferPriority(cacheKey);
1298
+ this.l1.set(k, value, ttlMs, p);
1299
+ this.counters.sets++;
1300
+ return true;
1301
+ }
1302
+ // ── Hot key introspection ─────────────────────────────────────────────
1303
+ /**
1304
+ * Return the top-N live L1 keys by historical access frequency.
1305
+ * Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
1306
+ * whose historical frequency exceeds their current in-memory hit count.
1307
+ *
1308
+ * Useful for diagnosing what is driving L1 pressure without any extra data
1309
+ * collection overhead.
1310
+ *
1311
+ * @param n - Maximum number of keys to return. Default: 10.
1312
+ *
1313
+ * @example
1314
+ * cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
1315
+ * console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
1316
+ */
1317
+ hotKeys(n = 10) {
1318
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
1319
+ return this.l1.hotKeys(n).map(({ key, hits, sizeBytes }) => ({
1320
+ key: prefixLen > 0 ? key.slice(prefixLen) : key,
1321
+ hits,
1322
+ sizeBytes,
1323
+ }));
1324
+ }
1325
+ // ── Dependency cascade helpers ────────────────────────────────────────
1326
+ /**
1327
+ * Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
1328
+ * pattern that may contain `*` wildcards).
1329
+ */
1330
+ _matchesGlob(key, pattern) {
1331
+ if (!pattern.includes('*'))
1332
+ return key === pattern;
1333
+ const re = new RegExp('^' + pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*') + '$');
1334
+ return re.test(key);
1335
+ }
1336
+ /**
1337
+ * When an exact key `deletedKey` is removed, cascade to every dependent key
1338
+ * that was registered via `dependsOn` and whose source pattern matches.
1339
+ */
1340
+ _cascadeDependencies(deletedKey) {
1341
+ for (const [pattern, dependents] of this.dependencyIndex) {
1342
+ if (!this._matchesGlob(deletedKey, pattern))
1343
+ continue;
1344
+ for (const dep of dependents) {
1345
+ if (dep === deletedKey)
1346
+ continue; // no self-cascade
1347
+ this.l1.delete(dep);
1348
+ this.disk.delete(dep);
1349
+ void this.publishInvalidation('del', dep);
1350
+ this.logger.debug('Dependency cascade: invalidated dependent key', {
1351
+ trigger: deletedKey.slice(0, 60), dependent: dep.slice(0, 60),
1352
+ });
1353
+ }
1354
+ }
1355
+ }
1356
+ // ── Observability ──────────────────────────────────────────────────────────────────
1357
+ /** Return a full metrics snapshot. */
1358
+ metrics() {
1359
+ const c = this.counters;
1360
+ const l1s = this.l1.getStats();
1361
+ const div = (n, d) => (d > 0 ? n / d : 0);
1362
+ return {
1363
+ namespace: this.opts.namespace,
1364
+ uptimeMs: Date.now() - c.startedAt,
1365
+ gets: {
1366
+ total: c.gets,
1367
+ l1Hits: c.l1Hits,
1368
+ l1HitRate: div(c.l1Hits, c.gets),
1369
+ diskHits: c.diskHits,
1370
+ diskHitRate: div(c.diskHits, c.gets),
1371
+ l2Hits: c.l2Hits,
1372
+ l2HitRate: div(c.l2Hits, c.gets),
1373
+ fetches: c.fetches,
1374
+ fetchRate: div(c.fetches, c.gets),
1375
+ stampedePrevented: c.stampedes,
1376
+ },
1377
+ sets: { total: c.sets },
1378
+ deletes: { total: c.deletes },
1379
+ revalidations: { total: c.swrRevalidations },
1380
+ bloom: {
1381
+ checksTotal: l1s.bloom.checks,
1382
+ falsePositives: l1s.bloom.falsePositives,
1383
+ falsePositiveRate: div(l1s.bloom.falsePositives, l1s.bloom.checks),
1384
+ },
1385
+ compression: {
1386
+ entriesCompressed: l1s.compression.compressed,
1387
+ entriesUncompressed: l1s.compression.uncompressed,
1388
+ bytesSaved: l1s.compression.bytesSaved,
1389
+ },
1390
+ backplane: {
1391
+ enabled: this.opts.invalidationBackplane && !this._redisDisabled,
1392
+ sent: c.invSent,
1393
+ received: c.invReceived,
1394
+ skipped: c.invSkipped,
1395
+ },
1396
+ l2CircuitBreaker: {
1397
+ state: this.cb.currentState,
1398
+ },
1399
+ oom: {
1400
+ enabled: this.opts.oomProtection,
1401
+ evictions: c.oomEvictions,
1402
+ lastTriggeredAt: c.oomLastAt,
1403
+ },
1404
+ l1: {
1405
+ entries: l1s.entries,
1406
+ sizeBytes: this.l1.memoryUsage,
1407
+ maxBytes: this.opts.l1MaxBytes,
1408
+ },
1409
+ disk: this.disk.stats,
1410
+ };
1411
+ }
1412
+ /**
1413
+ * Convert a `CacheMetrics` snapshot to Prometheus text exposition format.
1414
+ * Paste the result into your `/metrics` endpoint.
1415
+ *
1416
+ * @param m - Snapshot returned by `cache.metrics()`
1417
+ * @param prefix - Metric name prefix. Default: `"tricache"`
1418
+ */
1419
+ static toPrometheusText(m, prefix = 'tricache', instanceName) {
1420
+ const parts = [];
1421
+ if (m.namespace)
1422
+ parts.push(`namespace="${m.namespace}"`);
1423
+ if (instanceName)
1424
+ parts.push(`instance="${instanceName}"`);
1425
+ const lbl = parts.length ? `{${parts.join(',')}}` : '';
1426
+ const lines = [];
1427
+ const counter = (name, val, help) => {
1428
+ lines.push(`# HELP ${prefix}_${name}_total ${help}`);
1429
+ lines.push(`# TYPE ${prefix}_${name}_total counter`);
1430
+ lines.push(`${prefix}_${name}_total${lbl} ${val}`);
1431
+ };
1432
+ const gauge = (name, val, help) => {
1433
+ lines.push(`# HELP ${prefix}_${name} ${help}`);
1434
+ lines.push(`# TYPE ${prefix}_${name} gauge`);
1435
+ lines.push(`${prefix}_${name}${lbl} ${val}`);
1436
+ };
1437
+ counter('gets', m.gets.total, 'Total get() calls');
1438
+ counter('l1_hits', m.gets.l1Hits, 'L1 RAM cache hits');
1439
+ counter('disk_hits', m.gets.diskHits, 'L1.5 disk tier hits');
1440
+ counter('l2_hits', m.gets.l2Hits, 'L2 Redis hits');
1441
+ counter('fetches', m.gets.fetches, 'fetchFn calls (cache misses)');
1442
+ counter('stampedes_prevented', m.gets.stampedePrevented, 'Coalesced duplicate inflight requests');
1443
+ counter('sets', m.sets.total, 'Total set() calls');
1444
+ counter('deletes', m.deletes.total, 'Total delete() calls');
1445
+ counter('swr_revalidations', m.revalidations.total, 'Stale-While-Revalidate background refreshes');
1446
+ gauge('l1_hit_rate', m.gets.l1HitRate, 'Fraction of gets served from L1 RAM (0-1)');
1447
+ gauge('disk_hit_rate', m.gets.diskHitRate, 'Fraction of gets served from disk (0-1)');
1448
+ gauge('l2_hit_rate', m.gets.l2HitRate, 'Fraction of gets served from Redis (0-1)');
1449
+ gauge('fetch_rate', m.gets.fetchRate, 'Fraction of gets calling fetchFn (0-1)');
1450
+ gauge('l1_entries', m.l1.entries, 'Current L1 entry count');
1451
+ gauge('l1_size_bytes', m.l1.sizeBytes, 'Current L1 used bytes');
1452
+ gauge('disk_files', m.disk.files, 'Current L1.5 disk file count');
1453
+ gauge('bloom_false_positive_rate', m.bloom.falsePositiveRate, 'Bloom filter false-positive rate; increase capacity if > 0.01');
1454
+ gauge('compression_bytes_saved', m.compression.bytesSaved, 'Approximate bytes saved by msgpackr compression');
1455
+ if (m.backplane.enabled) {
1456
+ counter('backplane_sent', m.backplane.sent, 'Invalidation messages sent via Pub/Sub');
1457
+ counter('backplane_received', m.backplane.received, 'Invalidation messages received from peers');
1458
+ }
1459
+ if (m.oom.enabled) {
1460
+ counter('oom_evictions', m.oom.evictions, 'Emergency L1 eviction rounds triggered by heap pressure');
1461
+ }
1462
+ return lines.join('\n');
1463
+ }
1464
+ // ── Lifecycle ────────────────────────────────────────────────────────────
1465
+ /** Close Redis connections and stop all background timers. */
1466
+ async destroy() {
1467
+ if (this.cleanupInterval)
1468
+ clearInterval(this.cleanupInterval);
1469
+ if (this.oomInterval)
1470
+ clearInterval(this.oomInterval);
1471
+ if (this.metricsInterval)
1472
+ clearInterval(this.metricsInterval);
1473
+ if (this._shutdownHandler) {
1474
+ process.off('SIGTERM', this._shutdownHandler);
1475
+ process.off('SIGINT', this._shutdownHandler);
1476
+ this._shutdownHandler = null;
1477
+ }
1478
+ if (this.subClient) {
1479
+ try {
1480
+ await this.subClient.quit();
1481
+ }
1482
+ catch { /* ok */ }
1483
+ this.subClient = null;
1484
+ }
1485
+ if (this.redis) {
1486
+ try {
1487
+ await this.redis.disconnect();
1488
+ }
1489
+ catch { /* ok */ }
1490
+ this.redis = null;
1491
+ }
1492
+ }
1493
+ }
1494
+ //# sourceMappingURL=cache-service.js.map