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