tricache 0.1.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,472 @@
1
+ /**
2
+ * SmartMemoryCache — L1 in-process cache with adaptive LFU/LRU hybrid eviction.
3
+ *
4
+ * Features:
5
+ * - WASM Bloom filter for O(k) guaranteed-miss detection (pure-JS fallback)
6
+ * - msgpackr compression for entries ≥ 512 bytes
7
+ * - Category-aware capacity limits (prevents any single key prefix from monopolising RAM)
8
+ * - Priority-weighted adaptive eviction (LFU × LRU × priority score)
9
+ * - Stale-While-Revalidate soft-expiry support (isStale flag on get())
10
+ * - L1.5 disk-spill on eviction — evicted entries are sent to DiskTier before deletion
11
+ * - Periodic cleanup of hard-expired entries + bloom filter rebuild
12
+ * - Process-level singleton via globalThis (survives Next.js hot reloads)
13
+ */
14
+
15
+ import { pack, unpack } from 'msgpackr';
16
+ import type { CacheHit, CachePriority, CategoryLimit, SmartCacheEntry, ILogger } from './types';
17
+ import { WasmBloomFilter } from './wasm/bloom-filter-wasm';
18
+
19
+
20
+
21
+ /** Fraction of candidates evicted in one pass when a limit is exceeded */
22
+ const EVICTION_BATCH_PERCENT = 0.2;
23
+
24
+ // ─── Pure-JS Bloom filter fallback ───────────────────────────────────────────
25
+
26
+ class JsBloomFilter {
27
+ private bits: Buffer;
28
+ private readonly numBits: number;
29
+ private readonly k: number;
30
+ /** Pre-computed — numBits and k are constant, no need to recalculate on every probe. */
31
+ private readonly _maxCapacity: number;
32
+ /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
33
+ private _insertionCount = 0;
34
+
35
+ constructor(numBits = 100_000, k = 7) {
36
+ this.numBits = numBits;
37
+ this.k = k;
38
+ this.bits = Buffer.alloc(Math.ceil(numBits / 8), 0);
39
+ const p = 0.01;
40
+ this._maxCapacity = Math.floor(-numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
41
+ }
42
+
43
+ private fnv1a32(s: string): number {
44
+ let h = 0x811c9dc5;
45
+ for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0; }
46
+ return h >>> 0;
47
+ }
48
+
49
+ private djb2(s: string): number {
50
+ let h = 5381;
51
+ for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) >>> 0;
52
+ return h >>> 0;
53
+ }
54
+
55
+ private setBit(i: number) { this.bits[i >>> 3] |= 1 << (i & 7); }
56
+ private getBit(i: number): boolean { return (this.bits[i >>> 3] & (1 << (i & 7))) !== 0; }
57
+
58
+ add(key: string): void {
59
+ const h1 = this.fnv1a32(key), h2 = this.djb2(key);
60
+ for (let i = 0; i < this.k; i++) this.setBit(((h1 + i * h2) >>> 0) % this.numBits);
61
+ this._insertionCount++;
62
+ }
63
+
64
+ mightContain(key: string): boolean {
65
+ const h1 = this.fnv1a32(key), h2 = this.djb2(key);
66
+ for (let i = 0; i < this.k; i++) if (!this.getBit(((h1 + i * h2) >>> 0) % this.numBits)) return false;
67
+ return true;
68
+ }
69
+
70
+ reset() { this.bits.fill(0); this._insertionCount = 0; }
71
+ rebuild(keys: Iterable<string>) { this.bits.fill(0); this._insertionCount = 0; for (const k of keys) this.add(k); }
72
+
73
+ /** Number of add() calls since last reset/rebuild. */
74
+ get insertions(): number { return this._insertionCount; }
75
+
76
+ /**
77
+ * Maximum safe insertions before false-positive rate exceeds ~1 %.
78
+ * Exact formula for the configured k and target p=1 %:
79
+ * n_max = -m * ln(1 - p^(1/k)) / k
80
+ */
81
+ get maxCapacity(): number { return this._maxCapacity; }
82
+
83
+ get stats(): { bitsSet: number; fillFactor: number } {
84
+ let bitsSet = 0;
85
+ for (const byte of this.bits) { let b = byte; while (b) { bitsSet++; b &= b - 1; } }
86
+ return { bitsSet, fillFactor: bitsSet / this.numBits };
87
+ }
88
+ }
89
+
90
+ type AnyBloomFilter = JsBloomFilter | WasmBloomFilter;
91
+
92
+ function createBloomFilter(logger: ILogger): AnyBloomFilter {
93
+ try {
94
+ const wasm = new WasmBloomFilter();
95
+ logger.debug('SmartMemoryCache: WASM BloomFilter active');
96
+ return wasm;
97
+ } catch (err) {
98
+ logger.debug('SmartMemoryCache: WASM unavailable — using pure-JS BloomFilter', { reason: (err as Error).message });
99
+ return new JsBloomFilter();
100
+ }
101
+ }
102
+
103
+ // ─── SmartMemoryCache ─────────────────────────────────────────────────────────
104
+
105
+ export interface SmartMemoryCacheOptions {
106
+ maxBytes: number;
107
+ maxEntries: number;
108
+ categories: Record<string, CategoryLimit>;
109
+ diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
110
+ logger: ILogger;
111
+ }
112
+
113
+ export class SmartMemoryCache {
114
+ private readonly cache = new Map<string, SmartCacheEntry>();
115
+ private readonly opts: SmartMemoryCacheOptions;
116
+ private bloom: AnyBloomFilter;
117
+ /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
118
+ private readonly categoryPrefixes: string[];
119
+ private totalSize = 0;
120
+ private categoryCount = new Map<string, number>();
121
+ private categorySize = new Map<string, number>();
122
+ /** Per-category key sets — enables O(catSize) Phase-1 reservoir sampling without an O(N) scan. */
123
+ private categoryKeys = new Map<string, Set<string>>();
124
+
125
+ // ── Observability counters ──────────────────────────────────────────────────────
126
+ private bloomChecks = 0;
127
+ private bloomFalsePos = 0;
128
+ private compressions = 0;
129
+
130
+ /** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
131
+ private _bloomDirtyCount = 0;
132
+
133
+ constructor(opts: SmartMemoryCacheOptions, existing?: Map<string, SmartCacheEntry>) {
134
+ this.opts = opts;
135
+ this.bloom = createBloomFilter(opts.logger);
136
+ this.categoryPrefixes = Object.keys(opts.categories).filter(k => k !== 'default');
137
+
138
+ if (existing) {
139
+ for (const [k, v] of existing) this.cache.set(k, v);
140
+ this.recalculateStats();
141
+ for (const key of this.cache.keys()) this.bloom.add(key);
142
+ }
143
+ }
144
+
145
+ // ── Internal helpers ──────────────────────────────────────────────────────
146
+
147
+ private recalculateStats(): void {
148
+ this.totalSize = 0;
149
+ this.categoryCount.clear();
150
+ this.categorySize.clear();
151
+ this.categoryKeys.clear();
152
+ for (const [key, entry] of this.cache) {
153
+ this.totalSize += entry.size;
154
+ const cat = this.getCategory(key);
155
+ this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
156
+ this.categorySize.set(cat, (this.categorySize.get(cat) ?? 0) + entry.size);
157
+ let ks = this.categoryKeys.get(cat);
158
+ if (!ks) { ks = new Set(); this.categoryKeys.set(cat, ks); }
159
+ ks.add(key);
160
+ }
161
+ }
162
+
163
+ private getCategory(key: string): string {
164
+ for (const prefix of this.categoryPrefixes) {
165
+ if (key.startsWith(prefix)) return prefix;
166
+ }
167
+ return 'default';
168
+ }
169
+
170
+ private getCategoryLimit(cat: string): CategoryLimit {
171
+ return this.opts.categories[cat] ?? this.opts.categories['default'] ?? { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 };
172
+ }
173
+
174
+ private _delete(key: string): boolean {
175
+ const entry = this.cache.get(key);
176
+ if (!entry) return false;
177
+ const cat = this.getCategory(key);
178
+ this.totalSize -= entry.size;
179
+ this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
180
+ this.categorySize.set(cat, (this.categorySize.get(cat) ?? entry.size) - entry.size);
181
+ this.categoryKeys.get(cat)?.delete(key);
182
+ this._bloomDirtyCount++;
183
+ return this.cache.delete(key);
184
+ }
185
+
186
+ private ensureCapacity(category: string, neededSize: number): void {
187
+ const lim = this.getCategoryLimit(category);
188
+ const catCnt = this.categoryCount.get(category) ?? 0;
189
+ const catSz = this.categorySize.get(category) ?? 0;
190
+ const catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
191
+ const glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
192
+ if (!catOvf && !glbOvf) return;
193
+ this.smartEvict(category, catOvf);
194
+ }
195
+
196
+ private score(entry: SmartCacheEntry, catBonus: number, now: number): number {
197
+ const age = now - entry.lastAccess;
198
+ const ttl = Math.max(0, entry.expiresAt - now);
199
+ const freq = Math.min(entry.hits, 100);
200
+ return entry.priority * 1000 + freq * 10 + ttl / 60000 - age / 60000 - catBonus;
201
+ }
202
+
203
+ /**
204
+ * Rebuild the bloom filter when phantom bits from deleted/expired keys have
205
+ * saturated the filter past its ~1 % FP capacity.
206
+ *
207
+ * Trigger: (insertions − live entries) > maxCapacity
208
+ *
209
+ * Using the phantom count (insertions − cache.size) instead of raw insertions
210
+ * prevents an O(cache.size) rebuild from re-firing on every set() when the
211
+ * cache holds more entries than the filter's rated capacity — which would
212
+ * stall the write path entirely.
213
+ *
214
+ * After rebuild: insertions = cache.size → phantoms = 0 → no immediate re-trigger.
215
+ */
216
+ private maybeRebuildBloom(): void {
217
+ // Two independent triggers — whichever fires first:
218
+ // 1. Phantom count (insertions of dead keys since last rebuild)
219
+ // 2. Deletion count (ANY _delete() call — expiry, eviction, or explicit)
220
+ // Trigger 2 uses maxCapacity>>>2 (~4500) so eviction/expiry cycling doesn't
221
+ // accumulate stale bits for thousands of ops before trigger 1 fires.
222
+ if (this._bloomDirtyCount > (this.bloom.maxCapacity >>> 2) ||
223
+ this.bloom.insertions - this.cache.size > this.bloom.maxCapacity) {
224
+ this.bloom.rebuild(this.cache.keys());
225
+ this._bloomDirtyCount = 0;
226
+ }
227
+ }
228
+
229
+ private smartEvict(targetCat: string, catOvf: boolean): void {
230
+ const now = Date.now();
231
+ const SAMPLE = 16; // Redis-style sample window
232
+ const EVICT = Math.max(1, Math.ceil(SAMPLE * EVICTION_BATCH_PERCENT)); // ~4
233
+
234
+ const pool: Array<{ key: string; score: number }> = [];
235
+
236
+ if (catOvf) {
237
+ // Phase 1 — O(catSize) category-local reservoir sample.
238
+ // Uses the categoryKeys index to iterate only the overflowing category's keys,
239
+ // avoiding an O(N) scan of the entire cache. Guarantees at least
240
+ // min(catSize, EVICT) entries from the overflowing category in the pool so
241
+ // the priority score ordering is always deterministic in practice.
242
+ const catKeySet = this.categoryKeys.get(targetCat);
243
+ if (catKeySet) {
244
+ let catSeen = 0;
245
+ for (const key of catKeySet) {
246
+ const entry = this.cache.get(key);
247
+ if (!entry || (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now)) continue;
248
+ catSeen++;
249
+ const s = this.score(entry, 100, now);
250
+ if (pool.length < EVICT) {
251
+ pool.push({ key, score: s });
252
+ } else {
253
+ const j = Math.floor(Math.random() * catSeen);
254
+ if (j < EVICT) pool[j] = { key, score: s };
255
+ }
256
+ }
257
+ }
258
+ }
259
+
260
+ // Phase 2 — global reservoir sample fills remaining SAMPLE-pool.length slots.
261
+ // Skipped entirely when Phase 1 already collected a full EVICT-sized pool
262
+ // (the common catOvf case — overflowing categories always have ≥ EVICT entries).
263
+ // Also the sole phase when !catOvf (global over-capacity, no preferred category).
264
+ if (pool.length < EVICT) {
265
+ const remaining = SAMPLE - pool.length;
266
+ let globalSeen = 0;
267
+ const globalPool: Array<{ key: string; score: number }> = [];
268
+ for (const [key, entry] of this.cache) {
269
+ if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now) continue;
270
+ if (catOvf && this.getCategory(key) === targetCat) continue; // already sampled above
271
+ globalSeen++;
272
+ const s = this.score(entry, 0, now);
273
+ if (globalPool.length < remaining) {
274
+ globalPool.push({ key, score: s });
275
+ } else {
276
+ const j = Math.floor(Math.random() * globalSeen);
277
+ if (j < remaining) globalPool[j] = { key, score: s };
278
+ }
279
+ }
280
+ pool.push(...globalPool);
281
+ }
282
+
283
+ if (pool.length === 0) return;
284
+
285
+ // Sort only the tiny merged pool (O(SAMPLE * log(SAMPLE)) ≈ 64 comparisons)
286
+ pool.sort((a, b) => a.score - b.score);
287
+ for (const { key } of pool.slice(0, EVICT)) {
288
+ const entry = this.cache.get(key);
289
+ if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry); // L1.5 spill
290
+ this._delete(key);
291
+ }
292
+ }
293
+
294
+ // ── Public API ────────────────────────────────────────────────────────────
295
+
296
+ get(key: string): CacheHit | null {
297
+ this.bloomChecks++;
298
+ if (!this.bloom.mightContain(key)) return null;
299
+ const entry = this.cache.get(key);
300
+ if (!entry) { this.bloomFalsePos++; return null; }
301
+ const now = Date.now();
302
+ if (entry.expiresAt < now) { this._delete(key); return null; }
303
+ entry.hits++;
304
+ entry.lastAccess = now;
305
+ const value = unpack(entry.data as Buffer);
306
+ const isStale = entry.staleAt !== undefined && now > entry.staleAt;
307
+ return { value, isStale };
308
+ }
309
+
310
+ set(
311
+ key: string,
312
+ data: unknown,
313
+ ttlMs: number,
314
+ priority: CachePriority = 2 /* NORMAL */,
315
+ staleAt?: number,
316
+ ): void {
317
+ // Single serialization pass — always msgpackr. Eliminates the prior JSON.stringify
318
+ // "size probe" that was discarded for large payloads (the double-pass).
319
+ const packed = pack(data);
320
+ const size = packed.byteLength;
321
+ this.compressions++;
322
+
323
+ const cat = this.getCategory(key);
324
+ const lim = this.getCategoryLimit(cat);
325
+
326
+ if (size > lim.maxSizeBytes * 0.5) {
327
+ this.opts.logger.debug('SmartMemoryCache: entry too large, skipping', { key, sizeBytes: size });
328
+ return;
329
+ }
330
+
331
+ // Single Map.get replaces Map.has + _delete's Map.get (saves one lookup on overwrite).
332
+ const existingEntry = this.cache.get(key);
333
+ if (existingEntry) {
334
+ this.totalSize -= existingEntry.size;
335
+ this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
336
+ this.categorySize.set(cat, (this.categorySize.get(cat) ?? existingEntry.size) - existingEntry.size);
337
+ this.cache.delete(key);
338
+ }
339
+ this.ensureCapacity(cat, size);
340
+
341
+ const now = Date.now();
342
+ this.cache.set(key, { data: packed, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority });
343
+ this.bloom.add(key);
344
+ this.maybeRebuildBloom();
345
+ this.totalSize += size;
346
+ this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
347
+ this.categorySize.set(cat, (this.categorySize.get(cat) ?? 0) + size);
348
+ let ks = this.categoryKeys.get(cat);
349
+ if (!ks) { ks = new Set(); this.categoryKeys.set(cat, ks); }
350
+ ks.add(key);
351
+ }
352
+
353
+ delete(key: string): boolean {
354
+ const deleted = this._delete(key);
355
+ if (deleted) this.maybeRebuildBloom();
356
+ return deleted;
357
+ }
358
+
359
+ private keysMatchingPattern(pattern: string): string[] {
360
+ if (!pattern.includes('*')) return this.cache.has(pattern) ? [pattern] : [];
361
+ const re = new RegExp('^' + pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*') + '$');
362
+ const out: string[] = [];
363
+ for (const k of this.cache.keys()) if (re.test(k)) out.push(k);
364
+ return out;
365
+ }
366
+
367
+ deletePattern(pattern: string): number {
368
+ let n = 0;
369
+ for (const key of this.keysMatchingPattern(pattern)) if (this._delete(key)) n++;
370
+ if (n > 0) this.maybeRebuildBloom();
371
+ return n;
372
+ }
373
+
374
+ /**
375
+ * Forcibly evict the coldest `pct` fraction of non-CRITICAL L1 entries,
376
+ * spilling each to L1.5 disk. Called by the OOM guard when heap pressure
377
+ * exceeds the configured threshold.
378
+ *
379
+ * @param pct - Fraction to evict (0–1), e.g. 0.2 = 20 %
380
+ * @returns Number of entries evicted
381
+ */
382
+ evictPercentage(pct: number): number {
383
+ if (pct <= 0 || this.cache.size === 0) return 0;
384
+ const now = Date.now();
385
+ const candidates: Array<{ key: string; score: number }> = [];
386
+ for (const [key, entry] of this.cache) {
387
+ if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now) continue;
388
+ candidates.push({ key, score: this.score(entry, 0, now) });
389
+ }
390
+ candidates.sort((a, b) => a.score - b.score);
391
+ const count = Math.max(1, Math.ceil(candidates.length * pct));
392
+ let evicted = 0;
393
+ for (const { key } of candidates.slice(0, count)) {
394
+ const entry = this.cache.get(key);
395
+ if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
396
+ this._delete(key);
397
+ evicted++;
398
+ }
399
+ return evicted;
400
+ }
401
+
402
+ cleanup(): number {
403
+ const now = Date.now();
404
+ let cleaned = 0;
405
+ for (const [key, entry] of this.cache) if (entry.expiresAt < now) { this._delete(key); cleaned++; }
406
+ if (cleaned > 0) { this.bloom.rebuild(this.cache.keys()); this._bloomDirtyCount = 0; }
407
+ return cleaned;
408
+ }
409
+
410
+ // ── Snapshot import/export ────────────────────────────────────────────────
411
+
412
+ exportEntries(forbiddenPrefixes: readonly string[]): Array<{ key: string; entry: SmartCacheEntry }> {
413
+ const now = Date.now();
414
+ const out: Array<{ key: string; entry: SmartCacheEntry }> = [];
415
+ for (const [key, entry] of this.cache) {
416
+ if (entry.expiresAt <= now) continue;
417
+ if (entry.priority === 4 /* CRITICAL */) continue;
418
+ if (forbiddenPrefixes.some(p => key.startsWith(p))) continue;
419
+ out.push({ key, entry: { ...entry } });
420
+ }
421
+ return out;
422
+ }
423
+
424
+ importEntries(entries: Array<{ key: string; entry: SmartCacheEntry }>, forbiddenPrefixes: readonly string[]): number {
425
+ const now = Date.now();
426
+ let loaded = 0;
427
+ for (const { key, entry } of entries) {
428
+ if (entry.expiresAt <= now) continue;
429
+ if (forbiddenPrefixes.some(p => key.startsWith(p))) continue;
430
+ if (this.cache.has(key)) continue;
431
+ const rawData = entry.data;
432
+ // Handle both legacy (isCompressed=false, data=JSON string) and current (data=Buffer) formats.
433
+ const data: Buffer = !entry.isCompressed
434
+ ? pack(JSON.parse(rawData as unknown as string)) // legacy: re-encode JSON → msgpackr
435
+ : rawData instanceof Uint8Array
436
+ ? Buffer.from(rawData) // msgpackr Uint8Array → Buffer
437
+ : rawData as Buffer; // already a Buffer
438
+ this.cache.set(key, { ...entry, data, isCompressed: true });
439
+ this.bloom.add(key);
440
+ loaded++;
441
+ }
442
+ this.recalculateStats();
443
+ return loaded;
444
+ }
445
+
446
+ // ── Stats ─────────────────────────────────────────────────────────────────
447
+
448
+ get size(): number { return this.cache.size; }
449
+ get memoryUsage(): number { return this.totalSize; }
450
+
451
+ getStats() {
452
+ const categories: Record<string, number> = {};
453
+ for (const [cat, cnt] of this.categoryCount) categories[cat] = cnt;
454
+ return {
455
+ entries: this.cache.size,
456
+ sizeKB: Math.round(this.totalSize / 1024),
457
+ categories,
458
+ bloom: {
459
+ checks: this.bloomChecks,
460
+ falsePositives: this.bloomFalsePos,
461
+ },
462
+ compression: {
463
+ compressed: this.compressions,
464
+ uncompressed: 0, // all entries are now msgpackr-packed
465
+ bytesSaved: 0, // no longer tracked (unified format removes the split path)
466
+ },
467
+ };
468
+ }
469
+
470
+ bloomMightContain(key: string): boolean { return this.bloom.mightContain(key); }
471
+ bloomStats() { return this.bloom.stats; }
472
+ }