tricache 0.4.0 → 0.5.1

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.
@@ -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, fetchedAt: 0 };
17
21
  import { WasmBloomFilter } from './wasm/bloom-filter-wasm';
18
22
 
19
23
 
@@ -89,15 +93,35 @@ class JsBloomFilter {
89
93
 
90
94
  type AnyBloomFilter = JsBloomFilter | WasmBloomFilter;
91
95
 
92
- function createBloomFilter(logger: ILogger): AnyBloomFilter {
96
+ /**
97
+ * Return a bloom filter sized for `maxEntries` at a ~1 % false-positive target.
98
+ *
99
+ * The WASM filter is hardcoded at 100 K bits (k = 7), which holds ≈ 10 400 entries
100
+ * at 1 % FP. For larger caches the filter saturates quickly, producing high FP rates
101
+ * that force wasted Map.get() calls on every definite miss. When `maxEntries` exceeds
102
+ * the WASM filter's rated capacity, we instantiate a JS filter sized via the optimal
103
+ * formula: m = ⌈–n · ln p / (ln 2)²⌉ with k = round(ln 2 · m / n) clamped to [4, 10].
104
+ */
105
+ function createBloomFilter(logger: ILogger, maxEntries: number): AnyBloomFilter {
106
+ // Compute optimal bit-count for p = 1 % and the requested entry ceiling.
107
+ const LN2_SQ = Math.LN2 * Math.LN2; // (ln 2)² ≈ 0.4804
108
+ const optimalBits = Math.ceil(-maxEntries * Math.log(0.01) / LN2_SQ);
109
+ const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / maxEntries)));
110
+
93
111
  try {
94
112
  const wasm = new WasmBloomFilter();
95
- logger.debug('SmartMemoryCache: WASM BloomFilter active');
96
- return wasm;
113
+ if (wasm.maxCapacity >= maxEntries) {
114
+ logger.debug('SmartMemoryCache: WASM BloomFilter active');
115
+ return wasm;
116
+ }
117
+ // WASM filter is undersized for this cache — fall through to right-sized JS filter.
118
+ logger.debug('SmartMemoryCache: WASM BloomFilter capacity too small, using sized JS BloomFilter', {
119
+ wasmCapacity: wasm.maxCapacity, maxEntries, optimalBits,
120
+ });
97
121
  } catch (err) {
98
122
  logger.debug('SmartMemoryCache: WASM unavailable — using pure-JS BloomFilter', { reason: (err as Error).message });
99
- return new JsBloomFilter();
100
123
  }
124
+ return new JsBloomFilter(optimalBits, optimalK);
101
125
  }
102
126
 
103
127
  // ─── Count-Min Sketch ─────────────────────────────────────────────────────────
@@ -133,36 +157,38 @@ class CountMinSketch {
133
157
  return h;
134
158
  }
135
159
 
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
160
  /** Record one access. Decays all counters when the insertion threshold is crossed. */
147
161
  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));
162
+ const h = this.fnv32(key);
163
+ const h1 = (h ^ (h >>> 16)) >>> 0;
164
+ const h2 = (Math.imul(h1, 0x45d9f3b) ^ (h1 >>> 16)) >>> 0;
165
+ const h3 = (Math.imul(h2, 0x7fb9b7a1) ^ (h2 >>> 16)) >>> 0;
166
+ const h4 = (Math.imul(h3, 0x1b873593) ^ (h3 >>> 16)) >>> 0;
167
+ const t = this.table;
168
+ const i0 = h1 & SKETCH_MASK;
169
+ const i1 = SKETCH_WIDTH + (h2 & SKETCH_MASK);
170
+ const i2 = 2 * SKETCH_WIDTH + (h3 & SKETCH_MASK);
171
+ const i3 = 3 * SKETCH_WIDTH + (h4 & SKETCH_MASK);
172
+ if (t[i0] < 0xffff) t[i0]++;
173
+ if (t[i1] < 0xffff) t[i1]++;
174
+ if (t[i2] < 0xffff) t[i2]++;
175
+ if (t[i3] < 0xffff) t[i3]++;
154
176
  if (++this.inserts >= SKETCH_DECAY_THRESHOLD) this.decay();
155
177
  }
156
178
 
157
179
  /** Minimum-across-rows frequency estimate. */
158
180
  estimate(key: string): number {
159
- const [h1, h2, h3, h4] = this.hashes(key);
160
- const t = this.table;
181
+ const h = this.fnv32(key);
182
+ const h1 = (h ^ (h >>> 16)) >>> 0;
183
+ const h2 = (Math.imul(h1, 0x45d9f3b) ^ (h1 >>> 16)) >>> 0;
184
+ const h3 = (Math.imul(h2, 0x7fb9b7a1) ^ (h2 >>> 16)) >>> 0;
185
+ const h4 = (Math.imul(h3, 0x1b873593) ^ (h3 >>> 16)) >>> 0;
186
+ const t = this.table;
161
187
  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)],
188
+ t[h1 & SKETCH_MASK],
189
+ t[SKETCH_WIDTH + (h2 & SKETCH_MASK)],
190
+ t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)],
191
+ t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)],
166
192
  );
167
193
  }
168
194
 
@@ -173,6 +199,46 @@ class CountMinSketch {
173
199
  }
174
200
  }
175
201
 
202
+ // ─── Glob matcher ───────────────────────────────────────────────────────────────
203
+
204
+ /**
205
+ * Pure-string glob matcher — replaces RegExp on the deletePattern hot path.
206
+ * Supports only '*' wildcards (any sequence, including empty).
207
+ * No NFA/DFA state machine, no backtracking.
208
+ *
209
+ * Two-layer design to avoid per-key allocation in the inner loop:
210
+ * globMatch() — public entry point; splits the pattern once.
211
+ * globMatchParts() — hot inner loop; receives the pre-split segments.
212
+ *
213
+ * Algorithm:
214
+ * 1. First segment anchors the prefix (startsWith, O(|first|)).
215
+ * 2. Last segment anchors the suffix (endsWith, O(|last|)).
216
+ * 3. Middle segments are located left-to-right with indexOf (O(N) total, no re-scan).
217
+ */
218
+ function globMatchParts(parts: string[], first: string, last: string, key: string): boolean {
219
+ if (first.length > 0 && !key.startsWith(first)) return false;
220
+ if (last.length > 0 && !key.endsWith(last)) return false;
221
+ if (first.length + last.length > key.length) return false; // anchors overlap
222
+
223
+ // Walk any middle segments left-to-right — indexOf never backtracks.
224
+ let pos = first.length;
225
+ const end = key.length - last.length;
226
+ for (let i = 1; i < parts.length - 1; i++) {
227
+ const seg = parts[i];
228
+ if (seg.length === 0) continue; // consecutive '*' — skip
229
+ const idx = key.indexOf(seg, pos);
230
+ if (idx === -1 || idx + seg.length > end) return false;
231
+ pos = idx + seg.length;
232
+ }
233
+ return true;
234
+ }
235
+
236
+ function globMatch(pattern: string, key: string): boolean {
237
+ const parts = pattern.split('*');
238
+ if (parts.length === 1) return pattern === key; // no wildcard — exact match
239
+ return globMatchParts(parts, parts[0], parts[parts.length - 1], key);
240
+ }
241
+
176
242
  // ─── SmartMemoryCache ─────────────────────────────────────────────────────────
177
243
 
178
244
  export interface SmartMemoryCacheOptions {
@@ -207,7 +273,7 @@ export class SmartMemoryCache {
207
273
 
208
274
  constructor(opts: SmartMemoryCacheOptions, existing?: Map<string, SmartCacheEntry>) {
209
275
  this.opts = opts;
210
- this.bloom = createBloomFilter(opts.logger);
276
+ this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
211
277
  this.categoryPrefixes = Object.keys(opts.categories).filter(k => k !== 'default');
212
278
 
213
279
  if (existing) {
@@ -268,7 +334,21 @@ export class SmartMemoryCache {
268
334
  const catSz = this.categorySize.get(category) ?? 0;
269
335
  const catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
270
336
  const glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
271
- if (!catOvf && !glbOvf) return;
337
+ if (!catOvf && !glbOvf) {
338
+ // Proactive watermark: when either the global entry count OR total byte
339
+ // usage crosses 90 % of its configured ceiling while there is still
340
+ // headroom, run one eviction pass now — during the cheap headroom path —
341
+ // so the hard cliffs at 100 % are rarely reached and writes at full
342
+ // capacity become uncommon. Both dimensions are guarded so that
343
+ // large-payload workloads (where maxBytes is the binding constraint)
344
+ // benefit equally alongside entry-count-bound workloads.
345
+ const entryWatermark = this.cache.size >= Math.floor(this.opts.maxEntries * 0.9);
346
+ const byteWatermark = this.totalSize + neededSize >= Math.floor(this.opts.maxBytes * 0.9);
347
+ if (entryWatermark || byteWatermark) {
348
+ this.smartEvict(category, false);
349
+ }
350
+ return;
351
+ }
272
352
  this.smartEvict(category, catOvf);
273
353
  }
274
354
 
@@ -299,9 +379,15 @@ export class SmartMemoryCache {
299
379
  // Two independent triggers — whichever fires first:
300
380
  // 1. Phantom count (insertions of dead keys since last rebuild)
301
381
  // 2. Deletion count (ANY _delete() call — expiry, eviction, or explicit)
302
- // Trigger 2 uses maxCapacity>>>2 (~4500) so eviction/expiry cycling doesn't
303
- // accumulate stale bits for thousands of ops before trigger 1 fires.
304
- if (this._bloomDirtyCount > (this.bloom.maxCapacity >>> 2) ||
382
+ //
383
+ // Dirty-count cap: bloom.maxCapacity grows proportionally with filter size, but
384
+ // we want rebuild frequency to stay proportional to cache ENTRY count, not bit
385
+ // count. Without the cap a JS filter sized for 50 K entries allows ~12 500 ghost
386
+ // entries before a rebuild — 5× longer than the old WASM filter, which let phantom
387
+ // bits accumulate and raised the measured FP rate. The cap restores the original
388
+ // rebuild cadence: rebuild after ~5 % of maxEntries are deleted, with a 256 floor.
389
+ const dirtyThreshold = Math.max(256, Math.min(this.bloom.maxCapacity >>> 2, Math.ceil(this.opts.maxEntries * 0.05)));
390
+ if (this._bloomDirtyCount > dirtyThreshold ||
305
391
  this.bloom.insertions - this.cache.size > this.bloom.maxCapacity) {
306
392
  this.bloom.rebuild(this.cache.keys());
307
393
  this._bloomDirtyCount = 0;
@@ -384,14 +470,18 @@ export class SmartMemoryCache {
384
470
  if (entry.expiresAt < now) { this._delete(key, 'ttl'); return null; }
385
471
  entry.hits++;
386
472
  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);
473
+ // Sample sketch at 25 % — eviction scoring only needs relative frequency, not exact counts.
474
+ if ((entry.hits & 3) === 0) this.sketch.increment(key);
390
475
  // value is cached at write time — hot reads return the live object directly,
391
476
  // skipping unpack. Falls back to decode for entries restored from disk/snapshot.
392
477
  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, expiresAt: entry.expiresAt, ttlMs: entry.ttlMs, delta: entry.delta };
478
+ _hit.value = value;
479
+ _hit.isStale = entry.staleAt !== undefined && now > entry.staleAt;
480
+ _hit.expiresAt = entry.expiresAt;
481
+ _hit.ttlMs = entry.ttlMs;
482
+ _hit.delta = entry.delta;
483
+ _hit.fetchedAt = now;
484
+ return _hit;
395
485
  }
396
486
 
397
487
  set(
@@ -429,7 +519,9 @@ export class SmartMemoryCache {
429
519
 
430
520
  const now = Date.now();
431
521
  this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta });
432
- this.bloom.add(key);
522
+ // Only add new keys to the bloom — overwrites already have their bits set.
523
+ // Re-adding inflates the insertions counter, delaying trigger-2 phantom detection.
524
+ if (!existingEntry) this.bloom.add(key);
433
525
  this.maybeRebuildBloom();
434
526
  this.totalSize += size;
435
527
  this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
@@ -447,9 +539,40 @@ export class SmartMemoryCache {
447
539
 
448
540
  private keysMatchingPattern(pattern: string): string[] {
449
541
  if (!pattern.includes('*')) return this.cache.has(pattern) ? [pattern] : [];
450
- const re = new RegExp('^' + pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*') + '$');
542
+
543
+ // Fast path: trailing-only wildcard whose prefix exactly matches a configured
544
+ // category (e.g. deletePattern('user:*') when 'user:' is a category).
545
+ // categoryKeys already indexes all live keys per category prefix in O(1),
546
+ // so we skip the O(N) Map scan and regex evaluation entirely.
547
+ // We snapshot via Array.from() before returning so _delete() mutations to
548
+ // the Set during the subsequent iteration are safe.
549
+ if (pattern.endsWith('*') && pattern.indexOf('*') === pattern.length - 1) {
550
+ const prefix = pattern.slice(0, -1);
551
+ const catKeys = this.categoryKeys.get(prefix);
552
+ if (catKeys !== undefined) return Array.from(catKeys);
553
+ }
554
+
555
+ // Fast path: exactly one '*' that is NOT at the end (e.g. "user:*:profile").
556
+ // AOT detection lets us avoid globMatchParts dispatch and its empty middle-
557
+ // segment loop — keys only need startsWith + endsWith + length checks inline.
558
+ const firstStar = pattern.indexOf('*');
559
+ if (firstStar === pattern.lastIndexOf('*')) {
560
+ const prefix = pattern.slice(0, firstStar);
561
+ const suffix = pattern.slice(firstStar + 1); // empty when star is last char
562
+ const minLen = prefix.length + suffix.length;
563
+ const out: string[] = [];
564
+ for (const k of this.cache.keys()) {
565
+ if (k.length >= minLen && k.startsWith(prefix) && k.endsWith(suffix)) out.push(k);
566
+ }
567
+ return out;
568
+ }
569
+
570
+ // General case: multiple '*' wildcards — split once, then scan.
571
+ const parts = pattern.split('*');
572
+ const first = parts[0];
573
+ const last = parts[parts.length - 1];
451
574
  const out: string[] = [];
452
- for (const k of this.cache.keys()) if (re.test(k)) out.push(k);
575
+ for (const k of this.cache.keys()) if (globMatchParts(parts, first, last, k)) out.push(k);
453
576
  return out;
454
577
  }
455
578
 
@@ -625,6 +748,31 @@ export class SmartMemoryCache {
625
748
  }
626
749
  }
627
750
 
751
+ /**
752
+ * Non-generator bulk scan over all live entries.
753
+ *
754
+ * Faster than the generator-based iterators for bulk operations because:
755
+ * - No generator state-machine overhead (no yield/resume suspend points).
756
+ * - No per-entry tuple allocation (compare `liveEntries()` which yields `[key, entry]`).
757
+ * - The same Map call-site is used by a single plain `for` loop instead of being
758
+ * shared across three competing generator functions, giving V8's IC a cleaner
759
+ * monomorphic profile for this path.
760
+ *
761
+ * The callback receives the raw (namespaced) key and a `prefixLen` offset so the
762
+ * caller can call `key.slice(prefixLen)` only when it actually needs the stripped
763
+ * key, avoiding the allocation entirely for callers that don't.
764
+ *
765
+ * @param fn Called once per live entry.
766
+ * @param prefixLen Number of bytes to skip to reach the un-namespaced portion of the key.
767
+ * Pass 0 when no namespace is configured.
768
+ */
769
+ scan(fn: (key: string, entry: SmartCacheEntry, prefixLen: number) => void, prefixLen: number): void {
770
+ const now = Date.now();
771
+ for (const [key, entry] of this.cache) {
772
+ if (entry.expiresAt > now) fn(key, entry, prefixLen);
773
+ }
774
+ }
775
+
628
776
  /**
629
777
  * Yields only the keys of live entries — no intermediate tuple allocation.
630
778
  * Use this instead of liveEntries() when you only need keys.
package/src/types.ts CHANGED
@@ -119,6 +119,9 @@ export interface CacheHit {
119
119
  ttlMs?: number;
120
120
  /** Fetch duration in ms stored at write time — for XFetch probabilistic threshold */
121
121
  delta?: number;
122
+ /** Timestamp (Date.now()) recorded inside SmartMemoryCache.get() — lets CacheService
123
+ * reuse this value for refresh-ahead/XFetch math instead of making a second syscall. */
124
+ fetchedAt?: number;
122
125
  }
123
126
 
124
127
  // ─── Disk tier ───────────────────────────────────────────────────────────────
@@ -472,4 +475,44 @@ export interface CacheOptions {
472
475
  * Default: `30 000` ms (30 s).
473
476
  */
474
477
  l2CircuitBreakerCooldownMs?: number;
478
+ /**
479
+ * Redis key pattern to automatically warm L1 from at startup (e.g. `'user:*'`).
480
+ * `cache.ready()` returns a Promise that resolves once this warm-up completes.
481
+ * No-op when Redis is disabled or unreachable — safe to set unconditionally.
482
+ */
483
+ warmKeys?: string;
484
+
485
+ /**
486
+ * Called on every L1, disk, or L2 cache hit. Receives the caller-facing key (no
487
+ * namespace prefix) and the tier that served it. Useful for per-route hit-rate
488
+ * metrics without waiting for the `onMetrics` interval.
489
+ *
490
+ * @example
491
+ * onHit: (key, tier) => cloudwatch.putMetricData({ key, tier })
492
+ */
493
+ onHit?: (key: string, tier: 'l1' | 'disk' | 'l2') => void;
494
+
495
+ /**
496
+ * Called on every cache miss (after L1, disk, and L2 are all exhausted).
497
+ * Receives the caller-facing key (no namespace prefix).
498
+ *
499
+ * @example
500
+ * onMiss: (key) => cloudwatch.putMetricData({ key })
501
+ */
502
+ onMiss?: (key: string) => void;
503
+
504
+ /**
505
+ * When `true`, every value returned from an L1 cache hit is recursively
506
+ * frozen with `Object.freeze()` before being handed to the caller.
507
+ * Any attempt to mutate the returned object throws a `TypeError` immediately,
508
+ * catching reference-semantic corruption bugs that would otherwise silently
509
+ * corrupt the cached entry.
510
+ *
511
+ * **Do not enable in production** — use `process.env.NODE_ENV !== 'production'`.
512
+ * Deep-freezing large objects has measurable overhead per hit.
513
+ *
514
+ * @example
515
+ * frozen: process.env.NODE_ENV !== 'production'
516
+ */
517
+ frozen?: boolean;
475
518
  }
@@ -38,11 +38,7 @@ interface BloomWasmExports {
38
38
  countBits(): number;
39
39
  }
40
40
 
41
- function instantiateSync(): WebAssembly.Instance {
42
- const wasmBytes = Buffer.from(BLOOM_WASM_BASE64, 'base64');
43
- const compiled = new WebAssembly.Module(wasmBytes);
44
- return new WebAssembly.Instance(compiled, {});
45
- }
41
+ const BLOOM_WASM_MODULE = new WebAssembly.Module(Buffer.from(BLOOM_WASM_BASE64, 'base64'));
46
42
 
47
43
  export class WasmBloomFilter {
48
44
  private readonly exports: BloomWasmExports;
@@ -55,7 +51,7 @@ export class WasmBloomFilter {
55
51
  private _insertionCount = 0;
56
52
 
57
53
  constructor() {
58
- const instance = instantiateSync();
54
+ const instance = new WebAssembly.Instance(BLOOM_WASM_MODULE, {});
59
55
  this.exports = instance.exports as unknown as BloomWasmExports;
60
56
  this.mem = new Uint8Array(this.exports.memory.buffer);
61
57
  const k = 7, p = 0.01;
@@ -63,21 +59,9 @@ export class WasmBloomFilter {
63
59
  }
64
60
 
65
61
  private writeKey(key: string): number {
66
- const max = Math.min(key.length, MAX_KEY_BYTES);
67
- if (max === 0) return 0;
68
- // Fast path: write ASCII bytes directly, skipping TextEncoder heap allocation.
69
- // On the first non-ASCII char, fall back to TextEncoder for correct multi-byte encoding.
70
- for (let i = 0; i < max; i++) {
71
- const c = key.charCodeAt(i);
72
- if (c > 127) {
73
- const encoded = this.encoder.encode(key);
74
- const len = Math.min(encoded.length, MAX_KEY_BYTES);
75
- this.mem.set(encoded.subarray(0, len), KEY_STAGING_OFFSET);
76
- return len;
77
- }
78
- this.mem[KEY_STAGING_OFFSET + i] = c;
79
- }
80
- return max;
62
+ if (key.length === 0) return 0;
63
+ const target = this.mem.subarray(KEY_STAGING_OFFSET, KEY_STAGING_OFFSET + MAX_KEY_BYTES);
64
+ return this.encoder.encodeInto(key, target).written;
81
65
  }
82
66
 
83
67
  add(key: string): void {