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,29 @@
1
+ export declare class WasmBloomFilter {
2
+ private readonly exports;
3
+ private readonly mem;
4
+ private readonly encoder;
5
+ private readonly numBits;
6
+ /** Pre-computed — k and numBits are fixed constants; no need to recalculate on every probe. */
7
+ private readonly _maxCapacity;
8
+ /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
9
+ private _insertionCount;
10
+ constructor();
11
+ private writeKey;
12
+ add(key: string): void;
13
+ mightContain(key: string): boolean;
14
+ reset(): void;
15
+ rebuild(keys: Iterable<string>): void;
16
+ get stats(): {
17
+ bitsSet: number;
18
+ fillFactor: number;
19
+ };
20
+ /** Number of add() calls since last reset/rebuild. */
21
+ get insertions(): number;
22
+ /**
23
+ * Maximum safe insertions before false-positive rate exceeds ~1 %.
24
+ * Exact formula for k=7 hash rounds, m=100 000 bits:
25
+ * n_max = -m * ln(1 - p^(1/k)) / k ≈ 18 169
26
+ */
27
+ get maxCapacity(): number;
28
+ }
29
+ //# sourceMappingURL=bloom-filter-wasm.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bloom-filter-wasm.d.ts","sourceRoot":"","sources":["../../src/wasm/bloom-filter-wasm.ts"],"names":[],"mappings":"AA0CA,qBAAa,eAAe;IAC1B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAmB;IAC3C,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAa;IACjC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAqB;IAC7C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAW;IACnC,+FAA+F;IAC/F,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAS;IACtC,uFAAuF;IACvF,OAAO,CAAC,eAAe,CAAK;;IAU5B,OAAO,CAAC,QAAQ;IAMhB,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IAOtB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO;IAMlC,KAAK,IAAI,IAAI;IAEb,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,MAAM,CAAC,GAAG,IAAI;IAKrC,IAAI,KAAK,IAAI;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,CAGnD;IAED,sDAAsD;IACtD,IAAI,UAAU,IAAI,MAAM,CAAiC;IAEzD;;;;OAIG;IACH,IAAI,WAAW,IAAI,MAAM,CAA8B;CACxD"}
@@ -0,0 +1,83 @@
1
+ /// <reference lib="dom" />
2
+ /**
3
+ * WasmBloomFilter — WASM-powered Bloom filter using FNV-1a/djb2 double-hashing.
4
+ *
5
+ * The 562-byte WASM binary is inlined as Base64 to avoid any runtime file-system
6
+ * dependency. It implements a 100,000-bit filter with k=7 hash probes giving a
7
+ * ~0.01% false-positive rate at 2,000 entries.
8
+ *
9
+ * Memory layout (1 WASM page = 64 KB):
10
+ * [0 .. 12499] = 100,000-bit bit-array
11
+ * [20000 .. 20511] = 512-byte key staging area (JS → WASM string transfer)
12
+ *
13
+ * Used by SmartMemoryCache as the first-level miss detector.
14
+ * Falls back to the pure-JS BloomFilter if WASM fails to instantiate.
15
+ */
16
+ const BLOOM_WASM_BASE64 = 'AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUG' +
17
+ 'BQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVz' +
18
+ 'ZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAA' +
19
+ 'cyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJB' +
20
+ 'BXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAA' +
21
+ 'CxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEh' +
22
+ 'A0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEh' +
23
+ 'A0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJA' +
24
+ 'A0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAA' +
25
+ 'LQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==';
26
+ const KEY_STAGING_OFFSET = 20_000;
27
+ const MAX_KEY_BYTES = 512;
28
+ const BLOOM_WASM_MODULE = new WebAssembly.Module(Buffer.from(BLOOM_WASM_BASE64, 'base64'));
29
+ export class WasmBloomFilter {
30
+ exports;
31
+ mem;
32
+ encoder = new TextEncoder();
33
+ numBits = 100_000;
34
+ /** Pre-computed — k and numBits are fixed constants; no need to recalculate on every probe. */
35
+ _maxCapacity;
36
+ /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
37
+ _insertionCount = 0;
38
+ constructor() {
39
+ const instance = new WebAssembly.Instance(BLOOM_WASM_MODULE, {});
40
+ this.exports = instance.exports;
41
+ this.mem = new Uint8Array(this.exports.memory.buffer);
42
+ const k = 7, p = 0.01;
43
+ this._maxCapacity = Math.floor(-this.numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
44
+ }
45
+ writeKey(key) {
46
+ if (key.length === 0)
47
+ return 0;
48
+ const target = this.mem.subarray(KEY_STAGING_OFFSET, KEY_STAGING_OFFSET + MAX_KEY_BYTES);
49
+ return this.encoder.encodeInto(key, target).written;
50
+ }
51
+ add(key) {
52
+ const len = this.writeKey(key);
53
+ if (len === 0)
54
+ return;
55
+ this.exports.add(KEY_STAGING_OFFSET, len);
56
+ this._insertionCount++;
57
+ }
58
+ mightContain(key) {
59
+ const len = this.writeKey(key);
60
+ if (len === 0)
61
+ return true;
62
+ return this.exports.mightContain(KEY_STAGING_OFFSET, len) === 1;
63
+ }
64
+ reset() { this.exports.reset(); this._insertionCount = 0; }
65
+ rebuild(keys) {
66
+ this.reset();
67
+ for (const key of keys)
68
+ this.add(key);
69
+ }
70
+ get stats() {
71
+ const bitsSet = this.exports.countBits();
72
+ return { bitsSet, fillFactor: bitsSet / this.numBits };
73
+ }
74
+ /** Number of add() calls since last reset/rebuild. */
75
+ get insertions() { return this._insertionCount; }
76
+ /**
77
+ * Maximum safe insertions before false-positive rate exceeds ~1 %.
78
+ * Exact formula for k=7 hash rounds, m=100 000 bits:
79
+ * n_max = -m * ln(1 - p^(1/k)) / k ≈ 18 169
80
+ */
81
+ get maxCapacity() { return this._maxCapacity; }
82
+ }
83
+ //# sourceMappingURL=bloom-filter-wasm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bloom-filter-wasm.js","sourceRoot":"","sources":["../../src/wasm/bloom-filter-wasm.ts"],"names":[],"mappings":"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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tricache",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "Three-tier Node.js cache: L1 smart RAM (adaptive LFU/LRU + Count-Min Sketch) → L1.5 NVMe disk spill → L2 Redis/Valkey. Includes AES-256-GCM at-rest encryption, WASM Bloom filter, Stale-While-Revalidate, and thundering-herd prevention.",
5
5
  "keywords": [
6
6
  "cache",
@@ -42,7 +42,7 @@
42
42
  "typecheck": "tsc --noEmit",
43
43
  "test": "vitest run",
44
44
  "test:watch": "vitest",
45
- "bench": "node --import tsx/esm bench/benchmark.ts"
45
+ "bench": "node --expose-gc --import tsx/esm bench/benchmark.ts"
46
46
  },
47
47
  "dependencies": {
48
48
  "ioredis": "^5.3.2",
@@ -20,6 +20,7 @@ import { Redis as RedisClient } from 'ioredis';
20
20
  import { pack, unpack } from 'msgpackr';
21
21
  import crypto from 'crypto';
22
22
  import os from 'os';
23
+ import v8 from 'node:v8';
23
24
  import fs from 'fs';
24
25
  import path from 'path';
25
26
 
@@ -124,6 +125,125 @@ function deepFreeze<T>(obj: T): T {
124
125
  return obj;
125
126
  }
126
127
 
128
+ // ─── Adaptive TTL latency tracker ────────────────────────────────────────────
129
+
130
+ /**
131
+ * Lightweight per-key fetch-latency ring buffer.
132
+ *
133
+ * Each key gets a `Float64Array` of `samples` slots written in round-robin
134
+ * order. A separate `{ head, count }` object tracks the write pointer and
135
+ * how many slots have been filled so far. Once a key has ≥ 5 samples the
136
+ * p95 percentile can be read back with `.p95(key)`.
137
+ *
138
+ * Total memory per key: 8 × samples bytes (Float64Array) + one small object.
139
+ * With defaults (32 samples, 5 000 keys): ~1.3 MB worst-case.
140
+ *
141
+ * Key eviction: the internal Map preserves insertion order. When `maxKeys`
142
+ * is reached the oldest-inserted key is removed before the new one is added —
143
+ * no extra LRU bookkeeping required.
144
+ */
145
+ /** Per-key metadata stored alongside each ring buffer. */
146
+ interface LatencyMeta {
147
+ head: number; // ring-buffer write pointer
148
+ count: number; // filled slots (≤ samples)
149
+ p95: number; // cached p95 value (valid when !dirty && count ≥ 5)
150
+ dirty: boolean; // true when a new sample was written since last p95 computation
151
+ }
152
+
153
+ class LatencyTracker {
154
+ private readonly samples: number;
155
+ private readonly maxKeys: number;
156
+ private readonly bufs = new Map<string, Float64Array>();
157
+ private readonly meta = new Map<string, LatencyMeta>();
158
+ /** Shared sort buffer — safe to reuse because JS is single-threaded. */
159
+ private readonly scratch: Float64Array;
160
+
161
+ constructor(samples: number, maxKeys: number) {
162
+ this.samples = samples;
163
+ this.maxKeys = maxKeys;
164
+ this.scratch = new Float64Array(samples);
165
+ }
166
+
167
+ record(key: string, deltaMs: number): void {
168
+ let buf = this.bufs.get(key);
169
+ let m = this.meta.get(key);
170
+ if (buf === undefined) {
171
+ if (this.bufs.size >= this.maxKeys) {
172
+ // Evict oldest key (Map insertion order)
173
+ const oldest = this.bufs.keys().next().value as string;
174
+ this.bufs.delete(oldest);
175
+ this.meta.delete(oldest);
176
+ }
177
+ buf = new Float64Array(this.samples);
178
+ m = { head: 0, count: 0, p95: 0, dirty: false };
179
+ this.bufs.set(key, buf);
180
+ this.meta.set(key, m);
181
+ }
182
+ buf[m!.head] = deltaMs;
183
+ m!.head = (m!.head + 1) % this.samples;
184
+ if (m!.count < this.samples) m!.count++;
185
+ m!.dirty = true; // new sample → cached p95 is stale
186
+ }
187
+
188
+ /**
189
+ * Recomputes the p95 for the given key into `m.p95` and clears `m.dirty`.
190
+ * Uses the shared scratch buffer — no heap allocation.
191
+ */
192
+ private _computeP95(buf: Float64Array, m: LatencyMeta): void {
193
+ const n = m.count;
194
+ this.scratch.set(buf.subarray(0, n));
195
+ const view = this.scratch.subarray(0, n);
196
+ view.sort(); // TypedArray numeric sort — no comparator needed
197
+ m.p95 = view[Math.ceil(n * 0.95) - 1];
198
+ m.dirty = false;
199
+ }
200
+
201
+ /**
202
+ * Returns the p95 fetch latency for `key` in milliseconds, or `null` when
203
+ * fewer than 5 samples have been collected (not enough data yet).
204
+ * Uses a dirty-flag cache — sort only runs when a new sample was recorded.
205
+ */
206
+ p95(key: string): number | null {
207
+ const buf = this.bufs.get(key);
208
+ const m = this.meta.get(key);
209
+ if (!buf || !m || m.count < 5) return null;
210
+ if (m.dirty) this._computeP95(buf, m);
211
+ return m.p95;
212
+ }
213
+
214
+ get trackedKeys(): number { return this.bufs.size; }
215
+
216
+ /**
217
+ * Top-20 slowest keys by p95, sorted descending.
218
+ * Keys with < 5 samples are excluded (not enough data for a reliable p95).
219
+ *
220
+ * Only dirty keys (those with new samples since the last call) pay the sort
221
+ * cost. Keys whose p95 is already cached are O(1) reads — so repeated
222
+ * metrics() calls with no intervening fetches are essentially free.
223
+ */
224
+ snapshot(
225
+ prefixLen: number,
226
+ multiplierSec: number,
227
+ minMs: number,
228
+ maxMs: number,
229
+ ): Array<{ key: string; p95Ms: number; adaptedTtlSec: number }> {
230
+ const out: Array<{ key: string; p95Ms: number; adaptedTtlSec: number }> = [];
231
+ for (const [key, buf] of this.bufs) {
232
+ const m = this.meta.get(key)!;
233
+ if (m.count < 5) continue;
234
+ if (m.dirty) this._computeP95(buf, m); // sort only when new sample arrived
235
+ const p95 = m.p95;
236
+ const adaptedMs = Math.max(minMs, Math.min(maxMs, Math.round(p95 * multiplierSec * 1_000)));
237
+ out.push({
238
+ key: prefixLen > 0 ? key.slice(prefixLen) : key,
239
+ p95Ms: Math.round(p95),
240
+ adaptedTtlSec: Math.round(adaptedMs / 1_000),
241
+ });
242
+ }
243
+ return out.sort((a, b) => b.p95Ms - a.p95Ms).slice(0, 20);
244
+ }
245
+ }
246
+
127
247
  function inferPriority(cacheKey: string): CachePriority {
128
248
  if (cacheKey.includes('auth:') || cacheKey.includes('session:')) return CachePriority.CRITICAL;
129
249
  if (cacheKey.includes('user:') || cacheKey.includes('org:') || cacheKey.includes('profile:')) return CachePriority.HIGH;
@@ -159,6 +279,7 @@ export class CacheService {
159
279
  staleIfError: number;
160
280
  l2WriteMode: 'read-write' | 'read-only';
161
281
  instanceName: string;
282
+ l1EvictionWatermark: number;
162
283
  ttlJitterFactor: number;
163
284
  tracer: ICacheTracer | undefined;
164
285
  notFoundTtl: number;
@@ -166,6 +287,10 @@ export class CacheService {
166
287
  onHit: ((key: string, tier: 'l1' | 'disk' | 'l2') => void) | undefined;
167
288
  onMiss: ((key: string) => void) | undefined;
168
289
  frozen: boolean;
290
+ adaptiveTtl: boolean;
291
+ adaptiveTtlMinMs: number;
292
+ adaptiveTtlMaxMs: number;
293
+ adaptiveTtlMultiplier: number;
169
294
  };
170
295
  /** Pre-computed once — opts.namespace never changes after construction. */
171
296
  private readonly _namespace: string;
@@ -191,6 +316,7 @@ export class CacheService {
191
316
  private oomInterval: ReturnType<typeof setInterval> | null = null;
192
317
  private metricsInterval: ReturnType<typeof setInterval> | null = null;
193
318
  private _shutdownHandler: (() => void) | null = null;
319
+ private latencyTracker: LatencyTracker | null = null;
194
320
  private readonly instanceId: string;
195
321
  private readonly backplaneChannel: string;
196
322
  private subClient: RedisClient | null = null;
@@ -270,6 +396,7 @@ export class CacheService {
270
396
  staleIfError: options.staleIfError ?? 0,
271
397
  l2WriteMode: options.l2WriteMode ?? 'read-write',
272
398
  instanceName: options.instanceName ?? '',
399
+ l1EvictionWatermark: Math.min(Math.max(options.l1EvictionWatermark ?? 0.9, 0), 1),
273
400
  ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
274
401
  tracer: options.tracer,
275
402
  notFoundTtl: options.notFoundTtl ?? 0,
@@ -277,6 +404,10 @@ export class CacheService {
277
404
  onHit: options.onHit,
278
405
  onMiss: options.onMiss,
279
406
  frozen: options.frozen ?? false,
407
+ adaptiveTtl: options.adaptiveTtl ?? false,
408
+ adaptiveTtlMinMs: (options.adaptiveTtlMin ?? 10) * 1_000,
409
+ adaptiveTtlMaxMs: (options.adaptiveTtlMax ?? 86_400) * 1_000,
410
+ adaptiveTtlMultiplier: options.adaptiveTtlMultiplier ?? 20,
280
411
  };
281
412
 
282
413
  // Circuit breaker for L2 Redis
@@ -284,6 +415,13 @@ export class CacheService {
284
415
  const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 30_000;
285
416
  this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
286
417
 
418
+ // Adaptive TTL latency tracker (only allocated when the feature is enabled)
419
+ if (this.opts.adaptiveTtl) {
420
+ const samples = options.adaptiveTtlSamples ?? 32;
421
+ const maxKeys = options.adaptiveTtlMaxKeys ?? 5_000;
422
+ this.latencyTracker = new LatencyTracker(samples, maxKeys);
423
+ }
424
+
287
425
  // L1.5 disk tier
288
426
  this.disk = new DiskTier({
289
427
  dir: this.opts.diskCacheDir,
@@ -302,6 +440,7 @@ export class CacheService {
302
440
  maxBytes: this.opts.l1MaxBytes,
303
441
  maxEntries: this.opts.l1MaxEntries,
304
442
  categories: this.opts.categoryLimits,
443
+ evictionWatermark: this.opts.l1EvictionWatermark,
305
444
  diskSpill: (key: string, entry: SmartCacheEntry) => {
306
445
  // Defer disk.save() entirely to the next event-loop tick so the synchronous
307
446
  // preamble inside save() (SHA-256 keyToPath + msgpackr pack) does not block
@@ -345,8 +484,8 @@ export class CacheService {
345
484
  // OOM protection: evict coldest L1 entries when heap pressure rises
346
485
  if (this.opts.oomProtection) {
347
486
  this.oomInterval = setInterval(() => {
348
- const mem = process.memoryUsage();
349
- const used = mem.heapUsed / mem.heapTotal;
487
+ const heap = v8.getHeapStatistics();
488
+ const used = heap.used_heap_size / heap.heap_size_limit;
350
489
  if (used >= this.opts.oomHeapThreshold) {
351
490
  const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
352
491
  this.counters.oomEvictions++;
@@ -700,13 +839,25 @@ export class CacheService {
700
839
  const k = this.nk(cacheKey); // namespaced key used for all storage
701
840
  this.counters.gets++;
702
841
 
842
+ // Normalize all opts fields to plain locals once. Every opts.XXX read
843
+ // elsewhere in this function would hit a polymorphic IC when callers pass
844
+ // different option shapes: {}, { swr }, { refreshAhead }, { tags }, etc.
845
+ // Reading everything here collapses all downstream accesses to fast
846
+ // monomorphic local-variable reads regardless of call-site variety.
847
+ const optSwr = opts.swr ?? 0;
848
+ const optPriority = opts.priority;
849
+ const optRefreshAhead = opts.refreshAhead;
850
+ const optXfetchBeta = opts.xfetchBeta;
851
+ const optNotFoundTtl = opts.notFoundTtl;
852
+ const optTags = opts.tags;
853
+
703
854
  // L1: in-memory (fastest path)
704
855
  const l1Hit = this.l1.get(k);
705
856
  if (l1Hit !== null) {
706
857
  if (l1Hit.isStale) {
707
- const swrGraceMs = (opts.swr ?? 0) * 1_000;
858
+ const swrGraceMs = optSwr * 1_000;
708
859
  if (swrGraceMs > 0 && !this.revalidating.has(k)) {
709
- const priority = opts.priority ?? inferPriority(cacheKey);
860
+ const priority = optPriority ?? inferPriority(cacheKey);
710
861
  this.revalidating.add(k);
711
862
  void this._revalidate(k, fetchFn, ttlSeconds * 1_000, swrGraceMs, priority);
712
863
  this.counters.swrRevalidations++;
@@ -719,20 +870,21 @@ export class CacheService {
719
870
  // Refresh-ahead and XFetch: proactively recompute a fresh entry before it expires.
720
871
  // l1Hit already carries expiresAt/ttlMs/delta — no second Map lookup needed.
721
872
  // Check opts first — pointless work when neither feature is configured.
722
- if (opts.refreshAhead || opts.xfetchBeta) {
873
+ // Local aliases for the opts fields already normalised at function entry.
874
+ const ra = optRefreshAhead;
875
+ const xb = optXfetchBeta;
876
+ if (ra || xb) {
723
877
  // Reuse the timestamp already captured by l1.get() — avoids a second Date.now() syscall.
724
878
  const now = l1Hit.fetchedAt ?? Date.now();
725
879
  const remaining = l1Hit.expiresAt - now;
726
880
  const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1_000;
727
881
 
728
- const shouldRefreshAhead = !!opts.refreshAhead
729
- ? remaining <= entryTtl * (1 - opts.refreshAhead)
730
- : false;
882
+ const shouldRefreshAhead = ra ? remaining <= entryTtl * (1 - ra) : false;
731
883
 
732
884
  // XFetch: fire with probability proportional to recompute cost (delta) vs. remaining TTL
733
885
  // Formula: fire when remaining <= delta * beta * -ln(U), U ~ uniform(0,1)
734
- const shouldXFetch = !!opts.xfetchBeta && l1Hit.delta != null
735
- ? remaining <= l1Hit.delta * opts.xfetchBeta * -Math.log(Math.random())
886
+ const shouldXFetch = xb && l1Hit.delta != null
887
+ ? remaining <= l1Hit.delta * xb * -Math.log(Math.random())
736
888
  : false;
737
889
 
738
890
  // Set.has() deferred to here — the common case (fresh key, threshold not crossed)
@@ -740,9 +892,9 @@ export class CacheService {
740
892
  if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
741
893
  // Defer inferPriority until we actually need it — avoids 3× string.includes()
742
894
  // scans on every warm hit when the threshold check is false (the common case).
743
- const priority = opts.priority ?? inferPriority(cacheKey);
895
+ const priority = optPriority ?? inferPriority(cacheKey);
744
896
  this.revalidating.add(k);
745
- void this._revalidate(k, fetchFn, entryTtl, (opts.swr ?? 0) * 1_000, priority);
897
+ void this._revalidate(k, fetchFn, entryTtl, optSwr * 1_000, priority);
746
898
  this.counters.swrRevalidations++;
747
899
  this.logger.debug(
748
900
  shouldXFetch ? 'XFetch: proactive background recompute' : 'Refresh-ahead: proactive background recompute',
@@ -759,8 +911,8 @@ export class CacheService {
759
911
  }
760
912
 
761
913
  const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
762
- const swrGraceMs = (opts.swr ?? 0) * 1_000;
763
- const priority = opts.priority ?? inferPriority(cacheKey);
914
+ const swrGraceMs = optSwr * 1_000;
915
+ const priority = optPriority ?? inferPriority(cacheKey);
764
916
 
765
917
  // L2: Redis (distributed, production-only by default)
766
918
  if (!this._redisDisabled) {
@@ -823,14 +975,29 @@ export class CacheService {
823
975
  const delta = Date.now() - fetchStart;
824
976
 
825
977
  // Negative caching: null/undefined results get their own (shorter) TTL
826
- const notFoundTtlMs = (opts.notFoundTtl ?? this.opts.notFoundTtl) * 1_000;
827
- const effectiveTtl = (data == null && notFoundTtlMs > 0) ? notFoundTtlMs : ttlMs;
978
+ const notFoundTtlMs = (optNotFoundTtl ?? this.opts.notFoundTtl) * 1_000;
979
+ let effectiveTtl = (data == null && notFoundTtlMs > 0) ? notFoundTtlMs : ttlMs;
980
+
981
+ // Adaptive TTL: record this fetch duration and override the caller-supplied
982
+ // TTL once ≥ 5 samples are available for the key.
983
+ // Skipped for negative-cache (null/undefined) results — those use notFoundTtl.
984
+ if (this.latencyTracker && data != null) {
985
+ this.latencyTracker.record(k, delta);
986
+ const p95 = this.latencyTracker.p95(k);
987
+ if (p95 !== null) {
988
+ const adaptedMs = Math.round(p95 * this.opts.adaptiveTtlMultiplier * 1_000);
989
+ effectiveTtl = Math.max(
990
+ this.opts.adaptiveTtlMinMs,
991
+ Math.min(this.opts.adaptiveTtlMaxMs, adaptedMs),
992
+ );
993
+ }
994
+ }
828
995
 
829
996
  const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : undefined;
830
997
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
831
998
 
832
999
  this.l1.set(k, data, storeTtl, priority, staleAt, delta);
833
- if (opts.tags?.length) await this._registerTags(k, opts.tags, Math.ceil(effectiveTtl / 1_000));
1000
+ if (optTags?.length) await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1_000));
834
1001
 
835
1002
  if (!this._redisDisabled) {
836
1003
  try {
@@ -871,6 +1038,10 @@ export class CacheService {
871
1038
  const data = await fetchFn();
872
1039
  const delta = Date.now() - fetchStart;
873
1040
  const staleAt = Date.now() + ttlMs;
1041
+
1042
+ // Keep the latency tracker current during SWR background revalidations too
1043
+ if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
1044
+
874
1045
  this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta);
875
1046
 
876
1047
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
@@ -1717,6 +1888,18 @@ export class CacheService {
1717
1888
  maxBytes: this.opts.l1MaxBytes,
1718
1889
  },
1719
1890
  disk: this.disk.stats,
1891
+ ...(this.latencyTracker && {
1892
+ adaptiveTtl: {
1893
+ enabled: true as const,
1894
+ trackedKeys: this.latencyTracker.trackedKeys,
1895
+ slowestKeys: this.latencyTracker.snapshot(
1896
+ this._namespace ? this._namespace.length + 1 : 0, // strip "namespace:" prefix
1897
+ this.opts.adaptiveTtlMultiplier,
1898
+ this.opts.adaptiveTtlMinMs,
1899
+ this.opts.adaptiveTtlMaxMs,
1900
+ ),
1901
+ },
1902
+ }),
1720
1903
  };
1721
1904
  }
1722
1905
 
@@ -1802,6 +1985,7 @@ export class CacheService {
1802
1985
  try { await this.redis.disconnect(); } catch { /* ok */ }
1803
1986
  this.redis = null;
1804
1987
  }
1988
+ this.disk.close();
1805
1989
  }
1806
1990
 
1807
1991
  }