tricache 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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.3.1",
3
+ "version": "0.5.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",
@@ -18,7 +18,6 @@
18
18
  "nodejs"
19
19
  ],
20
20
  "license": "MIT",
21
- "packageManager": "pnpm@11.0.9",
22
21
  "type": "module",
23
22
  "main": "./dist/index.js",
24
23
  "module": "./dist/index.js",
@@ -36,14 +35,6 @@
36
35
  "README.md",
37
36
  "LICENSE"
38
37
  ],
39
- "scripts": {
40
- "build": "tsup src/index.ts --format esm,cjs --dts --clean",
41
- "dev": "tsup src/index.ts --format esm,cjs --dts --watch",
42
- "typecheck": "tsc --noEmit",
43
- "test": "vitest run",
44
- "test:watch": "vitest",
45
- "bench": "node --import tsx/esm bench/benchmark.ts"
46
- },
47
38
  "dependencies": {
48
39
  "ioredis": "^5.3.2",
49
40
  "msgpackr": "^2.0.1"
@@ -62,5 +53,13 @@
62
53
  "repository": {
63
54
  "type": "git",
64
55
  "url": "git+https://github.com/Kareem411/TriCache.git"
56
+ },
57
+ "scripts": {
58
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean",
59
+ "dev": "tsup src/index.ts --format esm,cjs --dts --watch",
60
+ "typecheck": "tsc --noEmit",
61
+ "test": "vitest run",
62
+ "test:watch": "vitest",
63
+ "bench": "node --import tsx/esm bench/benchmark.ts"
65
64
  }
66
- }
65
+ }
@@ -149,6 +149,8 @@ export class CacheService {
149
149
  instanceName: string;
150
150
  ttlJitterFactor: number;
151
151
  tracer: ICacheTracer | undefined;
152
+ notFoundTtl: number;
153
+ warmKeys: string | undefined;
152
154
  };
153
155
  /** Pre-computed once — opts.namespace never changes after construction. */
154
156
  private readonly _namespace: string;
@@ -159,10 +161,16 @@ export class CacheService {
159
161
  private readonly _l1Counters = new Map<string, { value: number; expiresAt: number }>();
160
162
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
161
163
  private readonly tagIndex = new Map<string, Set<string>>();
164
+ /**
165
+ * Dependency index: source glob pattern → Set of namespaced dependent keys.
166
+ * When an exact-key delete matches a registered pattern, all dependents are cascaded.
167
+ */
168
+ private readonly dependencyIndex = new Map<string, Set<string>>();
162
169
  private redis: RedisClient | null = null;
163
170
  private redisConnecting: Promise<RedisClient> | null = null;
164
171
  private readonly cb: L2CircuitBreaker;
165
172
  private snapshotLoaded = false;
173
+ private _readyPromise: Promise<void> = Promise.resolve();
166
174
  private cleanupInterval: ReturnType<typeof setInterval> | null = null;
167
175
  private oomInterval: ReturnType<typeof setInterval> | null = null;
168
176
  private metricsInterval: ReturnType<typeof setInterval> | null = null;
@@ -248,6 +256,8 @@ export class CacheService {
248
256
  instanceName: options.instanceName ?? '',
249
257
  ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
250
258
  tracer: options.tracer,
259
+ notFoundTtl: options.notFoundTtl ?? 0,
260
+ warmKeys: options.warmKeys,
251
261
  };
252
262
 
253
263
  // Circuit breaker for L2 Redis
@@ -330,6 +340,11 @@ export class CacheService {
330
340
  this.instanceId = crypto.randomBytes(8).toString('hex');
331
341
  this.backplaneChannel = `tricache:inv${ns ? ':' + ns : ''}`;
332
342
  this.initBackplane();
343
+
344
+ // Auto-warm from L2 if warmKeys is configured; ready() waits for completion.
345
+ if (this.opts.warmKeys) {
346
+ this._readyPromise = this.warmFromL2(this.opts.warmKeys).then(() => undefined);
347
+ }
333
348
  }
334
349
 
335
350
  // ── Singleton factory ─────────────────────────────────────────────────────
@@ -453,6 +468,11 @@ export class CacheService {
453
468
  // message returns immediately without blocking hot get() calls.
454
469
  this.l1.delete(msg.key);
455
470
  setImmediate(() => this.disk.delete(msg.key));
471
+ // Cascade: evict dependents registered on this instance for the
472
+ // deleted key — same logic the local delete() path runs, now also
473
+ // applied to peer-originated invalidations so fleet-wide deletes
474
+ // propagate dependency cascades to every node.
475
+ this._cascadeDependencies(msg.key);
456
476
  } else if (msg.op === 'del-glob') {
457
477
  // Glob patterns clean L1 only — disk entries expire naturally via
458
478
  // the background purge timer or are bypassed on the next L1 miss.
@@ -602,18 +622,29 @@ export class CacheService {
602
622
  * @param cacheKey - Unique key identifying this value
603
623
  * @param fetchFn - Called on a cache miss; its return value is cached and returned
604
624
  * @param ttlSeconds - How long to cache the value (default: 300 s = 5 min)
605
- * @param opts.priority - Override the auto-inferred eviction priority
606
- * @param opts.swr - Stale-While-Revalidate grace seconds. When > 0 the entry stays
607
- * alive for this many extra seconds after TTL; callers get stale data
608
- * instantly while a background refresh runs. Default: 0 (disabled).
625
+ * @param opts.priority - Override the auto-inferred eviction priority
626
+ * @param opts.swr - Stale-While-Revalidate grace seconds.
627
+ * @param opts.refreshAhead - 0–1 fraction of TTL elapsed at which a background recompute
628
+ * is triggered proactively while the caller still receives the
629
+ * cached value. E.g. `0.8` starts refreshing at 80 % of TTL.
630
+ * Requires `fetchFn` to be stable across calls.
631
+ * @param opts.xfetchBeta - Enable XFetch (probabilistic early expiration). Higher values
632
+ * recompute more aggressively before expiry. Typical range: 0.5–2.
633
+ * Complementary to refreshAhead — uses recompute cost (delta) to
634
+ * decide probabilistically rather than at a fixed threshold.
635
+ * @param opts.notFoundTtl - Override TTL in seconds for `null`/`undefined` fetch results.
636
+ * Caches negative lookups to avoid repeated DB hits for missing keys.
609
637
  */
610
638
  async get<T>(
611
639
  cacheKey: string,
612
640
  fetchFn: () => Promise<T>,
613
641
  ttlSeconds: number = 300,
614
642
  opts: {
615
- priority?: CachePriority;
616
- swr?: number; // Stale-While-Revalidate grace period in seconds
643
+ priority?: CachePriority;
644
+ swr?: number;
645
+ refreshAhead?: number; // 0–1: trigger background recompute at this fraction of TTL elapsed
646
+ xfetchBeta?: number; // > 0: XFetch probabilistic early expiration (uses stored delta)
647
+ notFoundTtl?: number; // seconds; cache null/undefined results with this TTL instead
617
648
  } = {},
618
649
  ): Promise<T> {
619
650
  const span = this._startSpan('tricache.get');
@@ -637,6 +668,36 @@ export class CacheService {
637
668
  }
638
669
  } else {
639
670
  this.logger.debug('L1 hit');
671
+ // Refresh-ahead and XFetch: proactively recompute a fresh entry before it expires.
672
+ // l1Hit already carries expiresAt/ttlMs/delta — no second Map lookup needed.
673
+ if (!this.revalidating.has(k) && (opts.refreshAhead || opts.xfetchBeta)) {
674
+ const now = Date.now();
675
+ const remaining = l1Hit.expiresAt - now;
676
+ const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1_000;
677
+
678
+ const shouldRefreshAhead = opts.refreshAhead != null && opts.refreshAhead > 0
679
+ ? remaining <= entryTtl * (1 - opts.refreshAhead)
680
+ : false;
681
+
682
+ // XFetch: fire with probability proportional to recompute cost (delta) vs. remaining TTL
683
+ // Formula: fire when remaining <= delta * beta * -ln(U), U ~ uniform(0,1)
684
+ const shouldXFetch = opts.xfetchBeta != null && opts.xfetchBeta > 0 && l1Hit.delta != null
685
+ ? remaining <= l1Hit.delta * opts.xfetchBeta * -Math.log(Math.random())
686
+ : false;
687
+
688
+ if (shouldRefreshAhead || shouldXFetch) {
689
+ // Defer inferPriority until we actually need it — avoids 3× string.includes()
690
+ // scans on every warm hit when the threshold check is false (the common case).
691
+ const priority = opts.priority ?? inferPriority(cacheKey);
692
+ this.revalidating.add(k);
693
+ void this._revalidate(k, fetchFn, entryTtl, (opts.swr ?? 0) * 1_000, priority);
694
+ this.counters.swrRevalidations++;
695
+ this.logger.debug(
696
+ shouldXFetch ? 'XFetch: proactive background recompute' : 'Refresh-ahead: proactive background recompute',
697
+ { cacheKey, remainingMs: remaining, ttlMs: entryTtl },
698
+ );
699
+ }
700
+ }
640
701
  }
641
702
  this.counters.l1Hits++;
642
703
  span.setAttribute('cache.hit', 'l1').end();
@@ -700,18 +761,25 @@ export class CacheService {
700
761
  const fetchPromise: Promise<T> = (async () => {
701
762
  try {
702
763
  this.counters.fetches++;
703
- const data = await fetchFn();
704
- const staleAt = swrGraceMs > 0 ? Date.now() + ttlMs : undefined;
705
- const storeTtl = swrGraceMs > 0 ? ttlMs + swrGraceMs : ttlMs;
764
+ const fetchStart = Date.now();
765
+ const data = await fetchFn();
766
+ const delta = Date.now() - fetchStart;
767
+
768
+ // Negative caching: null/undefined results get their own (shorter) TTL
769
+ const notFoundTtlMs = (opts.notFoundTtl ?? this.opts.notFoundTtl) * 1_000;
770
+ const effectiveTtl = (data == null && notFoundTtlMs > 0) ? notFoundTtlMs : ttlMs;
771
+
772
+ const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : undefined;
773
+ const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
706
774
 
707
- this.l1.set(k, data, storeTtl, priority, staleAt);
775
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta);
708
776
 
709
777
  if (!this._redisDisabled) {
710
778
  try {
711
779
  const client = await this.getRedis();
712
780
  const serialized = JSON.stringify(data);
713
781
  const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
714
- await client.setex(k, Math.ceil(ttlMs / 1_000), toStore);
782
+ await client.setex(k, Math.ceil(effectiveTtl / 1_000), toStore);
715
783
  this.cb.onSuccess();
716
784
  this.logger.debug('Cached L1+L2', { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
717
785
  } catch {
@@ -741,9 +809,11 @@ export class CacheService {
741
809
  priority: CachePriority,
742
810
  ): Promise<void> {
743
811
  try {
744
- const data = await fetchFn();
745
- const staleAt = Date.now() + ttlMs;
746
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt);
812
+ const fetchStart = Date.now();
813
+ const data = await fetchFn();
814
+ const delta = Date.now() - fetchStart;
815
+ const staleAt = Date.now() + ttlMs;
816
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta);
747
817
 
748
818
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
749
819
  try {
@@ -772,7 +842,7 @@ export class CacheService {
772
842
  // ── Explicit set / delete ─────────────────────────────────────────────────
773
843
 
774
844
  /** Explicitly write a value into L1 (+ L2 in production). */
775
- async set<T>(cacheKey: string, data: T, ttlSeconds = 300, priority?: CachePriority, opts?: { tags?: string[] }): Promise<void> {
845
+ async set<T>(cacheKey: string, data: T, ttlSeconds = 300, priority?: CachePriority, opts?: { tags?: string[]; dependsOn?: string[] }): Promise<void> {
776
846
  const span = this._startSpan('tricache.set');
777
847
  span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
778
848
  const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
@@ -804,6 +874,17 @@ export class CacheService {
804
874
  }
805
875
  }
806
876
 
877
+ // Register dependency patterns: when any key matching a pattern is deleted,
878
+ // this key (k) is automatically cascaded.
879
+ if (opts?.dependsOn?.length) {
880
+ for (const pattern of opts.dependsOn) {
881
+ const nsPattern = this.nk(pattern);
882
+ let deps = this.dependencyIndex.get(nsPattern);
883
+ if (!deps) { deps = new Set(); this.dependencyIndex.set(nsPattern, deps); }
884
+ deps.add(k);
885
+ }
886
+ }
887
+
807
888
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
808
889
  try {
809
890
  const client = await this.getRedis();
@@ -840,6 +921,10 @@ export class CacheService {
840
921
  } else {
841
922
  this.l1.delete(k);
842
923
  this.disk.delete(k);
924
+ // Cascade: invalidate any key that declared it depends on this exact key's pattern
925
+ this._cascadeDependencies(k);
926
+ // Clean up: remove k from all dependency registrations (it is gone)
927
+ for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
843
928
  }
844
929
 
845
930
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
@@ -1057,12 +1142,13 @@ export class CacheService {
1057
1142
  *
1058
1143
  * @param keys - Array of cache keys.
1059
1144
  * @param fetchFn - Called with only the keys that missed L1.
1060
- * @param ttl - TTL in seconds for newly fetched values.
1145
+ * @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
1146
+ * `(key) => number` so heterogeneous TTLs can be batched in one call.
1061
1147
  */
1062
1148
  async mget<T>(
1063
1149
  keys: string[],
1064
1150
  fetchFn: (missKeys: string[]) => Promise<Record<string, T>>,
1065
- ttl = 300,
1151
+ ttl: number | ((key: string) => number) = 300,
1066
1152
  priority?: CachePriority,
1067
1153
  ): Promise<(T | undefined)[]> {
1068
1154
  const result: (T | undefined)[] = new Array(keys.length);
@@ -1086,7 +1172,8 @@ export class CacheService {
1086
1172
  const v = fetched[missKeys[j]];
1087
1173
  result[missIndexes[j]] = v;
1088
1174
  if (v !== undefined) {
1089
- await this.set(missKeys[j], v, ttl, priority);
1175
+ const resolvedTtl = typeof ttl === 'function' ? ttl(missKeys[j]) : ttl;
1176
+ await this.set(missKeys[j], v, resolvedTtl, priority);
1090
1177
  }
1091
1178
  }
1092
1179
  }
@@ -1094,6 +1181,21 @@ export class CacheService {
1094
1181
  return result;
1095
1182
  }
1096
1183
 
1184
+ /**
1185
+ * Returns a Promise that resolves once the cache is fully initialised and any
1186
+ * startup warming configured via `warmKeys` has completed.
1187
+ *
1188
+ * Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once
1189
+ * `warmFromL2(warmKeys)` finishes — ideal for k8s readiness probes.
1190
+ *
1191
+ * @example
1192
+ * const cache = CacheService.create({ warmKeys: 'user:*' });
1193
+ * await cache.ready(); // gate traffic until warm
1194
+ */
1195
+ ready(): Promise<void> {
1196
+ return this._readyPromise;
1197
+ }
1198
+
1097
1199
  /**
1098
1200
  * Batch write — set multiple entries in a single call.
1099
1201
  * TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
@@ -1105,12 +1207,13 @@ export class CacheService {
1105
1207
  * });
1106
1208
  */
1107
1209
  async mset<T = unknown>(
1108
- entries: Record<string, { value: T; ttl?: number; priority?: CachePriority; tags?: string[] }>,
1210
+ entries: Record<string, { value: T; ttl?: number; priority?: CachePriority; tags?: string[]; dependsOn?: string[] }>,
1109
1211
  ): Promise<void> {
1110
1212
  const keys = Object.keys(entries);
1111
1213
  await Promise.all(keys.map(key => {
1112
- const { value, ttl = 300, priority, tags } = entries[key];
1113
- return this.set(key, value, ttl, priority, tags ? { tags } : undefined);
1214
+ const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
1215
+ const hasOpts = tags?.length || dependsOn?.length;
1216
+ return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : undefined);
1114
1217
  }));
1115
1218
  }
1116
1219
 
@@ -1297,6 +1400,107 @@ export class CacheService {
1297
1400
  };
1298
1401
  }
1299
1402
 
1403
+ // ── Conditional write ─────────────────────────────────────────────────
1404
+
1405
+ /**
1406
+ * Write `value` only if the key is not already cached.
1407
+ * Returns `true` if the write happened, `false` if the key already existed.
1408
+ *
1409
+ * When Redis is available, atomicity is guaranteed via `SET NX EX` so this
1410
+ * is safe to use for idempotency keys and "first writer wins" patterns across
1411
+ * multiple instances. L1 is populated on success.
1412
+ *
1413
+ * @example
1414
+ * const claimed = await cache.setIfAbsent('idempotency:req_abc', payload, 300);
1415
+ * if (!claimed) return res.status(409).json({ error: 'duplicate request' });
1416
+ */
1417
+ async setIfAbsent<T>(cacheKey: string, value: T, ttlSeconds = 300, priority?: CachePriority): Promise<boolean> {
1418
+ const k = this.nk(cacheKey);
1419
+
1420
+ // Fast path: L1 check (process-local, no network hop)
1421
+ if (this.l1.has(k)) return false;
1422
+
1423
+ if (!this._redisDisabled) {
1424
+ try {
1425
+ const client = await this.getRedis();
1426
+ const serialized = JSON.stringify(value);
1427
+ const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
1428
+ // SET key value EX ttl NX — atomic; returns 'OK' on success, null if key exists
1429
+ const result = await client.set(k, toStore, 'EX', ttlSeconds, 'NX');
1430
+ this.cb.onSuccess();
1431
+ if (result === null) return false; // already exists in Redis
1432
+ } catch (err) {
1433
+ this.cb.onFailure();
1434
+ this.logger.debug('setIfAbsent: Redis unavailable, falling back to L1 check', { cacheKey, error: (err as Error).message });
1435
+ // Re-check L1 after Redis failure — another thread may have won the race
1436
+ if (this.l1.has(k)) return false;
1437
+ }
1438
+ }
1439
+
1440
+ const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
1441
+ const p = priority ?? inferPriority(cacheKey);
1442
+ this.l1.set(k, value, ttlMs, p);
1443
+ this.counters.sets++;
1444
+ return true;
1445
+ }
1446
+
1447
+ // ── Hot key introspection ─────────────────────────────────────────────
1448
+
1449
+ /**
1450
+ * Return the top-N live L1 keys by historical access frequency.
1451
+ * Powered by the Count-Min Sketch — includes evicted-then-re-admitted keys
1452
+ * whose historical frequency exceeds their current in-memory hit count.
1453
+ *
1454
+ * Useful for diagnosing what is driving L1 pressure without any extra data
1455
+ * collection overhead.
1456
+ *
1457
+ * @param n - Maximum number of keys to return. Default: 10.
1458
+ *
1459
+ * @example
1460
+ * cache.hotKeys(5).forEach(({ key, hits, sizeBytes }) =>
1461
+ * console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
1462
+ */
1463
+ hotKeys(n = 10): Array<{ key: string; hits: number; sizeBytes: number }> {
1464
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
1465
+ return this.l1.hotKeys(n).map(({ key, hits, sizeBytes }) => ({
1466
+ key: prefixLen > 0 ? key.slice(prefixLen) : key,
1467
+ hits,
1468
+ sizeBytes,
1469
+ }));
1470
+ }
1471
+
1472
+ // ── Dependency cascade helpers ────────────────────────────────────────
1473
+
1474
+ /**
1475
+ * Test whether `key` (a concrete namespaced key) matches `pattern` (a glob
1476
+ * pattern that may contain `*` wildcards).
1477
+ */
1478
+ private _matchesGlob(key: string, pattern: string): boolean {
1479
+ if (!pattern.includes('*')) return key === pattern;
1480
+ const re = new RegExp('^' + pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*') + '$');
1481
+ return re.test(key);
1482
+ }
1483
+
1484
+ /**
1485
+ * When an exact key `deletedKey` is removed, cascade to every dependent key
1486
+ * that was registered via `dependsOn` and whose source pattern matches.
1487
+ */
1488
+ private _cascadeDependencies(deletedKey: string): void {
1489
+ for (const [pattern, dependents] of this.dependencyIndex) {
1490
+ if (!this._matchesGlob(deletedKey, pattern)) continue;
1491
+ for (const dep of dependents) {
1492
+ if (dep === deletedKey) continue; // no self-cascade
1493
+ this.l1.delete(dep);
1494
+ this.disk.delete(dep);
1495
+ void this.publishInvalidation('del', dep);
1496
+ this.logger.debug('Dependency cascade: invalidated dependent key', {
1497
+ trigger: deletedKey.slice(0, 60), dependent: dep.slice(0, 60),
1498
+ });
1499
+ }
1500
+ }
1501
+ }
1502
+
1503
+
1300
1504
  // ── Observability ──────────────────────────────────────────────────────────────────
1301
1505
 
1302
1506
  /** Return a full metrics snapshot. */
@@ -14,6 +14,10 @@
14
14
 
15
15
  import { pack, unpack } from 'msgpackr';
16
16
  import type { CacheHit, CachePriority, CategoryLimit, SmartCacheEntry, ILogger, EvictionReason } from './types';
17
+
18
+ // Reusable return object for get() — eliminates one heap allocation per hot read.
19
+ // Safe because JS is single-threaded: callers consume all fields before the next get().
20
+ const _hit: CacheHit = { value: undefined, isStale: false, expiresAt: 0, ttlMs: undefined, delta: undefined };
17
21
  import { WasmBloomFilter } from './wasm/bloom-filter-wasm';
18
22
 
19
23
 
@@ -133,36 +137,38 @@ class CountMinSketch {
133
137
  return h;
134
138
  }
135
139
 
136
- /** Four independent bit-mixes from one FNV-1a seed. */
137
- private hashes(key: string): [number, number, number, number] {
138
- const h = this.fnv32(key);
139
- const h1 = (h ^ (h >>> 16)) >>> 0;
140
- const h2 = (Math.imul(h1, 0x45d9f3b) ^ (h1 >>> 16)) >>> 0;
141
- const h3 = (Math.imul(h2, 0x7fb9b7a1) ^ (h2 >>> 16)) >>> 0;
142
- const h4 = (Math.imul(h3, 0x1b873593) ^ (h3 >>> 16)) >>> 0;
143
- return [h1, h2, h3, h4];
144
- }
145
-
146
140
  /** Record one access. Decays all counters when the insertion threshold is crossed. */
147
141
  increment(key: string): void {
148
- const [h1, h2, h3, h4] = this.hashes(key);
149
- const t = this.table;
150
- t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] = Math.min(0xffff, (t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] + 1));
151
- t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] = Math.min(0xffff, (t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] + 1));
152
- t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] = Math.min(0xffff, (t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] + 1));
153
- t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] = Math.min(0xffff, (t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] + 1));
142
+ const h = this.fnv32(key);
143
+ const h1 = (h ^ (h >>> 16)) >>> 0;
144
+ const h2 = (Math.imul(h1, 0x45d9f3b) ^ (h1 >>> 16)) >>> 0;
145
+ const h3 = (Math.imul(h2, 0x7fb9b7a1) ^ (h2 >>> 16)) >>> 0;
146
+ const h4 = (Math.imul(h3, 0x1b873593) ^ (h3 >>> 16)) >>> 0;
147
+ const t = this.table;
148
+ const i0 = h1 & SKETCH_MASK;
149
+ const i1 = SKETCH_WIDTH + (h2 & SKETCH_MASK);
150
+ const i2 = 2 * SKETCH_WIDTH + (h3 & SKETCH_MASK);
151
+ const i3 = 3 * SKETCH_WIDTH + (h4 & SKETCH_MASK);
152
+ if (t[i0] < 0xffff) t[i0]++;
153
+ if (t[i1] < 0xffff) t[i1]++;
154
+ if (t[i2] < 0xffff) t[i2]++;
155
+ if (t[i3] < 0xffff) t[i3]++;
154
156
  if (++this.inserts >= SKETCH_DECAY_THRESHOLD) this.decay();
155
157
  }
156
158
 
157
159
  /** Minimum-across-rows frequency estimate. */
158
160
  estimate(key: string): number {
159
- const [h1, h2, h3, h4] = this.hashes(key);
160
- const t = this.table;
161
+ const h = this.fnv32(key);
162
+ const h1 = (h ^ (h >>> 16)) >>> 0;
163
+ const h2 = (Math.imul(h1, 0x45d9f3b) ^ (h1 >>> 16)) >>> 0;
164
+ const h3 = (Math.imul(h2, 0x7fb9b7a1) ^ (h2 >>> 16)) >>> 0;
165
+ const h4 = (Math.imul(h3, 0x1b873593) ^ (h3 >>> 16)) >>> 0;
166
+ const t = this.table;
161
167
  return Math.min(
162
- t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)],
163
- t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)],
164
- t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)],
165
- t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)],
168
+ t[h1 & SKETCH_MASK],
169
+ t[SKETCH_WIDTH + (h2 & SKETCH_MASK)],
170
+ t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)],
171
+ t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)],
166
172
  );
167
173
  }
168
174
 
@@ -384,14 +390,17 @@ export class SmartMemoryCache {
384
390
  if (entry.expiresAt < now) { this._delete(key, 'ttl'); return null; }
385
391
  entry.hits++;
386
392
  entry.lastAccess = now;
387
- this.sketch.increment(key);
388
- const cat = this.getCategory(key);
389
- this.categoryHits.set(cat, (this.categoryHits.get(cat) ?? 0) + 1);
393
+ // Sample sketch at 25 % — eviction scoring only needs relative frequency, not exact counts.
394
+ if ((entry.hits & 3) === 0) this.sketch.increment(key);
390
395
  // value is cached at write time — hot reads return the live object directly,
391
396
  // skipping unpack. Falls back to decode for entries restored from disk/snapshot.
392
397
  const value = entry.value !== undefined ? entry.value : unpack(entry.data as Buffer);
393
- const isStale = entry.staleAt !== undefined && now > entry.staleAt;
394
- return { value, isStale };
398
+ _hit.value = value;
399
+ _hit.isStale = entry.staleAt !== undefined && now > entry.staleAt;
400
+ _hit.expiresAt = entry.expiresAt;
401
+ _hit.ttlMs = entry.ttlMs;
402
+ _hit.delta = entry.delta;
403
+ return _hit;
395
404
  }
396
405
 
397
406
  set(
@@ -400,6 +409,7 @@ export class SmartMemoryCache {
400
409
  ttlMs: number,
401
410
  priority: CachePriority = 2 /* NORMAL */,
402
411
  staleAt?: number,
412
+ delta?: number,
403
413
  ): void {
404
414
  // Single serialization pass — always msgpackr. Eliminates the prior JSON.stringify
405
415
  // "size probe" that was discarded for large payloads (the double-pass).
@@ -427,7 +437,7 @@ export class SmartMemoryCache {
427
437
  this.ensureCapacity(cat, size);
428
438
 
429
439
  const now = Date.now();
430
- this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority });
440
+ this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta });
431
441
  this.bloom.add(key);
432
442
  this.maybeRebuildBloom();
433
443
  this.totalSize += size;
@@ -729,4 +739,22 @@ export class SmartMemoryCache {
729
739
 
730
740
  bloomMightContain(key: string): boolean { return this.bloom.mightContain(key); }
731
741
  bloomStats() { return this.bloom.stats; }
742
+
743
+ /**
744
+ * Return the top-N live L1 keys by historical access frequency (Count-Min Sketch estimate).
745
+ * Includes evicted-then-readmitted keys whose sketch frequency exceeds their current hit count.
746
+ * Useful for diagnosing which keys are driving cache pressure.
747
+ *
748
+ * @param n - Maximum number of entries to return. Default: 10.
749
+ */
750
+ hotKeys(n: number): Array<{ key: string; hits: number; sizeBytes: number }> {
751
+ const now = Date.now();
752
+ const out: Array<{ key: string; hits: number; sizeBytes: number }> = [];
753
+ for (const [key, entry] of this.cache) {
754
+ if (entry.expiresAt <= now) continue;
755
+ out.push({ key, hits: this.sketch.estimate(key), sizeBytes: entry.size });
756
+ }
757
+ out.sort((a, b) => b.hits - a.hits);
758
+ return out.slice(0, n);
759
+ }
732
760
  }
package/src/types.ts CHANGED
@@ -101,6 +101,10 @@ export interface SmartCacheEntry {
101
101
  lastAccess: number;
102
102
  /** Eviction priority */
103
103
  priority: CachePriority;
104
+ /** Original TTL in ms at write time — used by refresh-ahead to compute the proactive refresh threshold. */
105
+ ttlMs?: number;
106
+ /** Milliseconds taken to fetch/compute this value — used by XFetch probabilistic early expiration. */
107
+ delta?: number;
104
108
  }
105
109
 
106
110
  /** Returned by SmartMemoryCache.get() — distinguishes "cached null" from a real miss */
@@ -108,6 +112,13 @@ export interface CacheHit {
108
112
  value: unknown;
109
113
  /** true = past soft TTL (staleAt) but within hard expiry → SWR path */
110
114
  isStale: boolean;
115
+ /** Hard expiry timestamp — lets CacheService.get() do refresh-ahead / XFetch math
116
+ * without a second Map lookup (eliminates the duplicate l1.getEntry() call). */
117
+ expiresAt: number;
118
+ /** Original TTL in ms stored at write time — for refresh-ahead fraction calculation */
119
+ ttlMs?: number;
120
+ /** Fetch duration in ms stored at write time — for XFetch probabilistic threshold */
121
+ delta?: number;
111
122
  }
112
123
 
113
124
  // ─── Disk tier ───────────────────────────────────────────────────────────────
@@ -441,6 +452,14 @@ export interface CacheOptions {
441
452
  ttlJitterFactor?: number;
442
453
 
443
454
  // ── L2 circuit breaker ─────────────────────────────────────────────────────
455
+ /**
456
+ * Default TTL in seconds for `null` or `undefined` results from `fetchFn`.
457
+ * Caches negative results so a non-existent key (deleted user, bad ID) does not
458
+ * hit the DB on every request. Can be overridden per-call via `get(..., { notFoundTtl }).
459
+ * Default: `0` (disabled — null/undefined uses the normal TTL).
460
+ */
461
+ notFoundTtl?: number;
462
+
444
463
  /**
445
464
  * Number of consecutive Redis errors before the circuit opens (stops
446
465
  * attempting Redis until the cooldown elapses).
@@ -453,4 +472,10 @@ export interface CacheOptions {
453
472
  * Default: `30 000` ms (30 s).
454
473
  */
455
474
  l2CircuitBreakerCooldownMs?: number;
475
+ /**
476
+ * Redis key pattern to automatically warm L1 from at startup (e.g. `'user:*'`).
477
+ * `cache.ready()` returns a Promise that resolves once this warm-up completes.
478
+ * No-op when Redis is disabled or unreachable — safe to set unconditionally.
479
+ */
480
+ warmKeys?: string;
456
481
  }