tricache 0.4.0 → 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.
- package/README.md +63 -27
- package/dist/cache-service.d.ts +366 -0
- package/dist/cache-service.d.ts.map +1 -0
- package/dist/cache-service.js +1494 -0
- package/dist/cache-service.js.map +1 -0
- package/dist/disk-tier.d.ts +83 -0
- package/dist/disk-tier.d.ts.map +1 -0
- package/dist/disk-tier.js +324 -0
- package/dist/disk-tier.js.map +1 -0
- package/dist/encryption.d.ts +88 -0
- package/dist/encryption.d.ts.map +1 -0
- package/dist/encryption.js +371 -0
- package/dist/encryption.js.map +1 -0
- package/dist/index.cjs +51 -23
- package/dist/index.d.cts +22 -2
- package/dist/index.d.ts +18 -1146
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +25 -2697
- package/dist/index.js.map +1 -0
- package/dist/smart-memory-cache.d.ts +178 -0
- package/dist/smart-memory-cache.d.ts.map +1 -0
- package/dist/smart-memory-cache.js +753 -0
- package/dist/smart-memory-cache.js.map +1 -0
- package/dist/types.d.ts +428 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +20 -0
- package/dist/types.js.map +1 -0
- package/dist/wasm/bloom-filter-wasm.d.ts +29 -0
- package/dist/wasm/bloom-filter-wasm.d.ts.map +1 -0
- package/dist/wasm/bloom-filter-wasm.js +99 -0
- package/dist/wasm/bloom-filter-wasm.js.map +1 -0
- package/package.json +10 -11
- package/src/cache-service.ts +36 -4
- package/src/smart-memory-cache.ts +36 -27
- package/src/types.ts +6 -0
|
@@ -0,0 +1,753 @@
|
|
|
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
|
+
import { pack, unpack } from 'msgpackr';
|
|
15
|
+
// Reusable return object for get() — eliminates one heap allocation per hot read.
|
|
16
|
+
// Safe because JS is single-threaded: callers consume all fields before the next get().
|
|
17
|
+
const _hit = { value: undefined, isStale: false, expiresAt: 0, ttlMs: undefined, delta: undefined };
|
|
18
|
+
import { WasmBloomFilter } from './wasm/bloom-filter-wasm';
|
|
19
|
+
/** Fraction of candidates evicted in one pass when a limit is exceeded */
|
|
20
|
+
const EVICTION_BATCH_PERCENT = 0.2;
|
|
21
|
+
// ─── Pure-JS Bloom filter fallback ───────────────────────────────────────────
|
|
22
|
+
class JsBloomFilter {
|
|
23
|
+
bits;
|
|
24
|
+
numBits;
|
|
25
|
+
k;
|
|
26
|
+
/** Pre-computed — numBits and k are constant, no need to recalculate on every probe. */
|
|
27
|
+
_maxCapacity;
|
|
28
|
+
/** Tracks total add() calls so we know when phantom bits have saturated the filter. */
|
|
29
|
+
_insertionCount = 0;
|
|
30
|
+
constructor(numBits = 100_000, k = 7) {
|
|
31
|
+
this.numBits = numBits;
|
|
32
|
+
this.k = k;
|
|
33
|
+
this.bits = Buffer.alloc(Math.ceil(numBits / 8), 0);
|
|
34
|
+
const p = 0.01;
|
|
35
|
+
this._maxCapacity = Math.floor(-numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
|
|
36
|
+
}
|
|
37
|
+
fnv1a32(s) {
|
|
38
|
+
let h = 0x811c9dc5;
|
|
39
|
+
for (let i = 0; i < s.length; i++) {
|
|
40
|
+
h ^= s.charCodeAt(i);
|
|
41
|
+
h = Math.imul(h, 0x01000193) >>> 0;
|
|
42
|
+
}
|
|
43
|
+
return h >>> 0;
|
|
44
|
+
}
|
|
45
|
+
djb2(s) {
|
|
46
|
+
let h = 5381;
|
|
47
|
+
for (let i = 0; i < s.length; i++)
|
|
48
|
+
h = ((h << 5) + h + s.charCodeAt(i)) >>> 0;
|
|
49
|
+
return h >>> 0;
|
|
50
|
+
}
|
|
51
|
+
setBit(i) { this.bits[i >>> 3] |= 1 << (i & 7); }
|
|
52
|
+
getBit(i) { return (this.bits[i >>> 3] & (1 << (i & 7))) !== 0; }
|
|
53
|
+
add(key) {
|
|
54
|
+
const h1 = this.fnv1a32(key), h2 = this.djb2(key);
|
|
55
|
+
for (let i = 0; i < this.k; i++)
|
|
56
|
+
this.setBit(((h1 + i * h2) >>> 0) % this.numBits);
|
|
57
|
+
this._insertionCount++;
|
|
58
|
+
}
|
|
59
|
+
mightContain(key) {
|
|
60
|
+
const h1 = this.fnv1a32(key), h2 = this.djb2(key);
|
|
61
|
+
for (let i = 0; i < this.k; i++)
|
|
62
|
+
if (!this.getBit(((h1 + i * h2) >>> 0) % this.numBits))
|
|
63
|
+
return false;
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
reset() { this.bits.fill(0); this._insertionCount = 0; }
|
|
67
|
+
rebuild(keys) { this.bits.fill(0); this._insertionCount = 0; for (const k of keys)
|
|
68
|
+
this.add(k); }
|
|
69
|
+
/** Number of add() calls since last reset/rebuild. */
|
|
70
|
+
get insertions() { return this._insertionCount; }
|
|
71
|
+
/**
|
|
72
|
+
* Maximum safe insertions before false-positive rate exceeds ~1 %.
|
|
73
|
+
* Exact formula for the configured k and target p=1 %:
|
|
74
|
+
* n_max = -m * ln(1 - p^(1/k)) / k
|
|
75
|
+
*/
|
|
76
|
+
get maxCapacity() { return this._maxCapacity; }
|
|
77
|
+
get stats() {
|
|
78
|
+
let bitsSet = 0;
|
|
79
|
+
for (const byte of this.bits) {
|
|
80
|
+
let b = byte;
|
|
81
|
+
while (b) {
|
|
82
|
+
bitsSet++;
|
|
83
|
+
b &= b - 1;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return { bitsSet, fillFactor: bitsSet / this.numBits };
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function createBloomFilter(logger) {
|
|
90
|
+
try {
|
|
91
|
+
const wasm = new WasmBloomFilter();
|
|
92
|
+
logger.debug('SmartMemoryCache: WASM BloomFilter active');
|
|
93
|
+
return wasm;
|
|
94
|
+
}
|
|
95
|
+
catch (err) {
|
|
96
|
+
logger.debug('SmartMemoryCache: WASM unavailable — using pure-JS BloomFilter', { reason: err.message });
|
|
97
|
+
return new JsBloomFilter();
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
// ─── Count-Min Sketch ─────────────────────────────────────────────────────────
|
|
101
|
+
//
|
|
102
|
+
// Estimates historical access frequency across eviction boundaries — a per-entry
|
|
103
|
+
// `hits` counter resets to 1 whenever a key is re-admitted after eviction, but
|
|
104
|
+
// the sketch remembers the key's frequency in a fixed-size typed array that
|
|
105
|
+
// survives evictions. This closes the same-priority burst-flood gap: a key that
|
|
106
|
+
// has been accessed 80 times over the last hour but was evicted 5 minutes ago
|
|
107
|
+
// will score far above a brand-new burst key whose hits = 1.
|
|
108
|
+
//
|
|
109
|
+
// Dimensions: 4 rows × 512 counters (Uint16Array) — 4 KB total, fits in L1d.
|
|
110
|
+
// Hash: four independent Murmur3-fragment mixes of the key's FNV-1a digest.
|
|
111
|
+
// Decay: all counters halved when total insertions cross SKETCH_DECAY_THRESHOLD
|
|
112
|
+
// (frequency-ageing prevents indefinitely growing hot-key counts).
|
|
113
|
+
const SKETCH_ROWS = 4;
|
|
114
|
+
const SKETCH_WIDTH = 512; // must be power of two
|
|
115
|
+
const SKETCH_MASK = SKETCH_WIDTH - 1;
|
|
116
|
+
const SKETCH_DECAY_THRESHOLD = 100_000;
|
|
117
|
+
class CountMinSketch {
|
|
118
|
+
table = new Uint16Array(SKETCH_ROWS * SKETCH_WIDTH);
|
|
119
|
+
inserts = 0;
|
|
120
|
+
/** Inline FNV-1a for a string key → 32-bit unsigned integer. */
|
|
121
|
+
fnv32(key) {
|
|
122
|
+
let h = 0x811c9dc5;
|
|
123
|
+
for (let i = 0; i < key.length; i++) {
|
|
124
|
+
h ^= key.charCodeAt(i);
|
|
125
|
+
h = (Math.imul(h, 0x01000193) >>> 0);
|
|
126
|
+
}
|
|
127
|
+
return h;
|
|
128
|
+
}
|
|
129
|
+
/** Record one access. Decays all counters when the insertion threshold is crossed. */
|
|
130
|
+
increment(key) {
|
|
131
|
+
const h = this.fnv32(key);
|
|
132
|
+
const h1 = (h ^ (h >>> 16)) >>> 0;
|
|
133
|
+
const h2 = (Math.imul(h1, 0x45d9f3b) ^ (h1 >>> 16)) >>> 0;
|
|
134
|
+
const h3 = (Math.imul(h2, 0x7fb9b7a1) ^ (h2 >>> 16)) >>> 0;
|
|
135
|
+
const h4 = (Math.imul(h3, 0x1b873593) ^ (h3 >>> 16)) >>> 0;
|
|
136
|
+
const t = this.table;
|
|
137
|
+
const i0 = h1 & SKETCH_MASK;
|
|
138
|
+
const i1 = SKETCH_WIDTH + (h2 & SKETCH_MASK);
|
|
139
|
+
const i2 = 2 * SKETCH_WIDTH + (h3 & SKETCH_MASK);
|
|
140
|
+
const i3 = 3 * SKETCH_WIDTH + (h4 & SKETCH_MASK);
|
|
141
|
+
if (t[i0] < 0xffff)
|
|
142
|
+
t[i0]++;
|
|
143
|
+
if (t[i1] < 0xffff)
|
|
144
|
+
t[i1]++;
|
|
145
|
+
if (t[i2] < 0xffff)
|
|
146
|
+
t[i2]++;
|
|
147
|
+
if (t[i3] < 0xffff)
|
|
148
|
+
t[i3]++;
|
|
149
|
+
if (++this.inserts >= SKETCH_DECAY_THRESHOLD)
|
|
150
|
+
this.decay();
|
|
151
|
+
}
|
|
152
|
+
/** Minimum-across-rows frequency estimate. */
|
|
153
|
+
estimate(key) {
|
|
154
|
+
const h = this.fnv32(key);
|
|
155
|
+
const h1 = (h ^ (h >>> 16)) >>> 0;
|
|
156
|
+
const h2 = (Math.imul(h1, 0x45d9f3b) ^ (h1 >>> 16)) >>> 0;
|
|
157
|
+
const h3 = (Math.imul(h2, 0x7fb9b7a1) ^ (h2 >>> 16)) >>> 0;
|
|
158
|
+
const h4 = (Math.imul(h3, 0x1b873593) ^ (h3 >>> 16)) >>> 0;
|
|
159
|
+
const t = this.table;
|
|
160
|
+
return Math.min(t[h1 & SKETCH_MASK], t[SKETCH_WIDTH + (h2 & SKETCH_MASK)], t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)], t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)]);
|
|
161
|
+
}
|
|
162
|
+
/** Halve all counters — ages out old frequency so bursts don't hold indefinitely. */
|
|
163
|
+
decay() {
|
|
164
|
+
for (let i = 0; i < this.table.length; i++)
|
|
165
|
+
this.table[i] >>>= 1;
|
|
166
|
+
this.inserts = 0;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
export class SmartMemoryCache {
|
|
170
|
+
cache = new Map();
|
|
171
|
+
opts;
|
|
172
|
+
bloom;
|
|
173
|
+
/** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
|
|
174
|
+
categoryPrefixes;
|
|
175
|
+
/** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
|
|
176
|
+
sketch = new CountMinSketch();
|
|
177
|
+
totalSize = 0;
|
|
178
|
+
categoryCount = new Map();
|
|
179
|
+
categorySize = new Map();
|
|
180
|
+
/** Per-category key sets — enables O(catSize) Phase-1 reservoir sampling without an O(N) scan. */
|
|
181
|
+
categoryKeys = new Map();
|
|
182
|
+
// ── Observability counters ──────────────────────────────────────────────────────
|
|
183
|
+
bloomChecks = 0;
|
|
184
|
+
bloomFalsePos = 0;
|
|
185
|
+
compressions = 0;
|
|
186
|
+
categoryHits = new Map();
|
|
187
|
+
/** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
|
|
188
|
+
_bloomDirtyCount = 0;
|
|
189
|
+
constructor(opts, existing) {
|
|
190
|
+
this.opts = opts;
|
|
191
|
+
this.bloom = createBloomFilter(opts.logger);
|
|
192
|
+
this.categoryPrefixes = Object.keys(opts.categories).filter(k => k !== 'default');
|
|
193
|
+
if (existing) {
|
|
194
|
+
for (const [k, v] of existing)
|
|
195
|
+
this.cache.set(k, v);
|
|
196
|
+
this.recalculateStats();
|
|
197
|
+
for (const key of this.cache.keys())
|
|
198
|
+
this.bloom.add(key);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
// ── Internal helpers ──────────────────────────────────────────────────────
|
|
202
|
+
recalculateStats() {
|
|
203
|
+
this.totalSize = 0;
|
|
204
|
+
this.categoryCount.clear();
|
|
205
|
+
this.categorySize.clear();
|
|
206
|
+
this.categoryKeys.clear();
|
|
207
|
+
for (const [key, entry] of this.cache) {
|
|
208
|
+
this.totalSize += entry.size;
|
|
209
|
+
const cat = this.getCategory(key);
|
|
210
|
+
this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
|
|
211
|
+
this.categorySize.set(cat, (this.categorySize.get(cat) ?? 0) + entry.size);
|
|
212
|
+
let ks = this.categoryKeys.get(cat);
|
|
213
|
+
if (!ks) {
|
|
214
|
+
ks = new Set();
|
|
215
|
+
this.categoryKeys.set(cat, ks);
|
|
216
|
+
}
|
|
217
|
+
ks.add(key);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
getCategory(key) {
|
|
221
|
+
for (const prefix of this.categoryPrefixes) {
|
|
222
|
+
if (key.startsWith(prefix))
|
|
223
|
+
return prefix;
|
|
224
|
+
}
|
|
225
|
+
return 'default';
|
|
226
|
+
}
|
|
227
|
+
getCategoryLimit(cat) {
|
|
228
|
+
return this.opts.categories[cat] ?? this.opts.categories['default'] ?? { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 };
|
|
229
|
+
}
|
|
230
|
+
_delete(key, reason = 'manual') {
|
|
231
|
+
const entry = this.cache.get(key);
|
|
232
|
+
if (!entry)
|
|
233
|
+
return false;
|
|
234
|
+
const cat = this.getCategory(key);
|
|
235
|
+
this.totalSize -= entry.size;
|
|
236
|
+
this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
|
|
237
|
+
this.categorySize.set(cat, (this.categorySize.get(cat) ?? entry.size) - entry.size);
|
|
238
|
+
this.categoryKeys.get(cat)?.delete(key);
|
|
239
|
+
this._bloomDirtyCount++;
|
|
240
|
+
const deleted = this.cache.delete(key);
|
|
241
|
+
if (deleted && this.opts.onEviction) {
|
|
242
|
+
try {
|
|
243
|
+
this.opts.onEviction(key, reason);
|
|
244
|
+
}
|
|
245
|
+
catch { /* never crash cache */ }
|
|
246
|
+
}
|
|
247
|
+
return deleted;
|
|
248
|
+
}
|
|
249
|
+
ensureCapacity(category, neededSize) {
|
|
250
|
+
const lim = this.getCategoryLimit(category);
|
|
251
|
+
const catCnt = this.categoryCount.get(category) ?? 0;
|
|
252
|
+
const catSz = this.categorySize.get(category) ?? 0;
|
|
253
|
+
const catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
|
|
254
|
+
const glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
|
|
255
|
+
if (!catOvf && !glbOvf)
|
|
256
|
+
return;
|
|
257
|
+
this.smartEvict(category, catOvf);
|
|
258
|
+
}
|
|
259
|
+
score(entry, catBonus, now, key) {
|
|
260
|
+
const age = now - entry.lastAccess;
|
|
261
|
+
const ttl = Math.max(0, entry.expiresAt - now);
|
|
262
|
+
// Use the sketch's cross-eviction frequency estimate when it exceeds the
|
|
263
|
+
// entry's current-tenure hit count — protects long-resident keys that were
|
|
264
|
+
// recently re-admitted (hits reset to 1) from same-priority burst floods.
|
|
265
|
+
const freq = Math.min(Math.max(entry.hits, this.sketch.estimate(key)), 100);
|
|
266
|
+
return entry.priority * 1000 + freq * 10 + ttl / 60000 - age / 60000 - catBonus;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Rebuild the bloom filter when phantom bits from deleted/expired keys have
|
|
270
|
+
* saturated the filter past its ~1 % FP capacity.
|
|
271
|
+
*
|
|
272
|
+
* Trigger: (insertions − live entries) > maxCapacity
|
|
273
|
+
*
|
|
274
|
+
* Using the phantom count (insertions − cache.size) instead of raw insertions
|
|
275
|
+
* prevents an O(cache.size) rebuild from re-firing on every set() when the
|
|
276
|
+
* cache holds more entries than the filter's rated capacity — which would
|
|
277
|
+
* stall the write path entirely.
|
|
278
|
+
*
|
|
279
|
+
* After rebuild: insertions = cache.size → phantoms = 0 → no immediate re-trigger.
|
|
280
|
+
*/
|
|
281
|
+
maybeRebuildBloom() {
|
|
282
|
+
// Two independent triggers — whichever fires first:
|
|
283
|
+
// 1. Phantom count (insertions of dead keys since last rebuild)
|
|
284
|
+
// 2. Deletion count (ANY _delete() call — expiry, eviction, or explicit)
|
|
285
|
+
// Trigger 2 uses maxCapacity>>>2 (~4500) so eviction/expiry cycling doesn't
|
|
286
|
+
// accumulate stale bits for thousands of ops before trigger 1 fires.
|
|
287
|
+
if (this._bloomDirtyCount > (this.bloom.maxCapacity >>> 2) ||
|
|
288
|
+
this.bloom.insertions - this.cache.size > this.bloom.maxCapacity) {
|
|
289
|
+
this.bloom.rebuild(this.cache.keys());
|
|
290
|
+
this._bloomDirtyCount = 0;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
smartEvict(targetCat, catOvf) {
|
|
294
|
+
const now = Date.now();
|
|
295
|
+
const SAMPLE = 16; // Redis-style sample window
|
|
296
|
+
const EVICT = Math.max(1, Math.ceil(SAMPLE * EVICTION_BATCH_PERCENT)); // ~4
|
|
297
|
+
const pool = [];
|
|
298
|
+
if (catOvf) {
|
|
299
|
+
// Phase 1 — O(catSize) category-local reservoir sample.
|
|
300
|
+
// Uses the categoryKeys index to iterate only the overflowing category's keys,
|
|
301
|
+
// avoiding an O(N) scan of the entire cache. Guarantees at least
|
|
302
|
+
// min(catSize, EVICT) entries from the overflowing category in the pool so
|
|
303
|
+
// the priority score ordering is always deterministic in practice.
|
|
304
|
+
const catKeySet = this.categoryKeys.get(targetCat);
|
|
305
|
+
if (catKeySet) {
|
|
306
|
+
let catSeen = 0;
|
|
307
|
+
for (const key of catKeySet) {
|
|
308
|
+
const entry = this.cache.get(key);
|
|
309
|
+
if (!entry || (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now))
|
|
310
|
+
continue;
|
|
311
|
+
catSeen++;
|
|
312
|
+
const s = this.score(entry, 100, now, key);
|
|
313
|
+
if (pool.length < EVICT) {
|
|
314
|
+
pool.push({ key, score: s });
|
|
315
|
+
}
|
|
316
|
+
else {
|
|
317
|
+
const j = Math.floor(Math.random() * catSeen);
|
|
318
|
+
if (j < EVICT)
|
|
319
|
+
pool[j] = { key, score: s };
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
// Phase 2 — global reservoir sample fills remaining SAMPLE-pool.length slots.
|
|
325
|
+
// Skipped entirely when Phase 1 already collected a full EVICT-sized pool
|
|
326
|
+
// (the common catOvf case — overflowing categories always have ≥ EVICT entries).
|
|
327
|
+
// Also the sole phase when !catOvf (global over-capacity, no preferred category).
|
|
328
|
+
if (pool.length < EVICT) {
|
|
329
|
+
const remaining = SAMPLE - pool.length;
|
|
330
|
+
let globalSeen = 0;
|
|
331
|
+
const globalPool = [];
|
|
332
|
+
for (const [key, entry] of this.cache) {
|
|
333
|
+
if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now)
|
|
334
|
+
continue;
|
|
335
|
+
if (catOvf && this.getCategory(key) === targetCat)
|
|
336
|
+
continue; // already sampled above
|
|
337
|
+
globalSeen++;
|
|
338
|
+
const s = this.score(entry, 0, now, key);
|
|
339
|
+
if (globalPool.length < remaining) {
|
|
340
|
+
globalPool.push({ key, score: s });
|
|
341
|
+
}
|
|
342
|
+
else {
|
|
343
|
+
const j = Math.floor(Math.random() * globalSeen);
|
|
344
|
+
if (j < remaining)
|
|
345
|
+
globalPool[j] = { key, score: s };
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
pool.push(...globalPool);
|
|
349
|
+
}
|
|
350
|
+
if (pool.length === 0)
|
|
351
|
+
return;
|
|
352
|
+
// Sort only the tiny merged pool (O(SAMPLE * log(SAMPLE)) ≈ 64 comparisons)
|
|
353
|
+
pool.sort((a, b) => a.score - b.score);
|
|
354
|
+
for (const { key } of pool.slice(0, EVICT)) {
|
|
355
|
+
const entry = this.cache.get(key);
|
|
356
|
+
if (entry && this.opts.diskSpill)
|
|
357
|
+
this.opts.diskSpill(key, entry); // L1.5 spill
|
|
358
|
+
this._delete(key, 'capacity');
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
// ── Public API ────────────────────────────────────────────────────────────
|
|
362
|
+
get(key) {
|
|
363
|
+
this.bloomChecks++;
|
|
364
|
+
if (!this.bloom.mightContain(key))
|
|
365
|
+
return null;
|
|
366
|
+
const entry = this.cache.get(key);
|
|
367
|
+
if (!entry) {
|
|
368
|
+
this.bloomFalsePos++;
|
|
369
|
+
return null;
|
|
370
|
+
}
|
|
371
|
+
const now = Date.now();
|
|
372
|
+
if (entry.expiresAt < now) {
|
|
373
|
+
this._delete(key, 'ttl');
|
|
374
|
+
return null;
|
|
375
|
+
}
|
|
376
|
+
entry.hits++;
|
|
377
|
+
entry.lastAccess = now;
|
|
378
|
+
// Sample sketch at 25 % — eviction scoring only needs relative frequency, not exact counts.
|
|
379
|
+
if ((entry.hits & 3) === 0)
|
|
380
|
+
this.sketch.increment(key);
|
|
381
|
+
// value is cached at write time — hot reads return the live object directly,
|
|
382
|
+
// skipping unpack. Falls back to decode for entries restored from disk/snapshot.
|
|
383
|
+
const value = entry.value !== undefined ? entry.value : unpack(entry.data);
|
|
384
|
+
_hit.value = value;
|
|
385
|
+
_hit.isStale = entry.staleAt !== undefined && now > entry.staleAt;
|
|
386
|
+
_hit.expiresAt = entry.expiresAt;
|
|
387
|
+
_hit.ttlMs = entry.ttlMs;
|
|
388
|
+
_hit.delta = entry.delta;
|
|
389
|
+
return _hit;
|
|
390
|
+
}
|
|
391
|
+
set(key, data, ttlMs, priority = 2 /* NORMAL */, staleAt, delta) {
|
|
392
|
+
// Single serialization pass — always msgpackr. Eliminates the prior JSON.stringify
|
|
393
|
+
// "size probe" that was discarded for large payloads (the double-pass).
|
|
394
|
+
const packed = pack(data);
|
|
395
|
+
const size = packed.byteLength;
|
|
396
|
+
this.compressions++;
|
|
397
|
+
this.sketch.increment(key);
|
|
398
|
+
const cat = this.getCategory(key);
|
|
399
|
+
const lim = this.getCategoryLimit(cat);
|
|
400
|
+
if (size > lim.maxSizeBytes * 0.5) {
|
|
401
|
+
this.opts.logger.debug('SmartMemoryCache: entry too large, skipping', { key, sizeBytes: size });
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
// Single Map.get replaces Map.has + _delete's Map.get (saves one lookup on overwrite).
|
|
405
|
+
const existingEntry = this.cache.get(key);
|
|
406
|
+
if (existingEntry) {
|
|
407
|
+
this.totalSize -= existingEntry.size;
|
|
408
|
+
this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
|
|
409
|
+
this.categorySize.set(cat, (this.categorySize.get(cat) ?? existingEntry.size) - existingEntry.size);
|
|
410
|
+
this.cache.delete(key);
|
|
411
|
+
}
|
|
412
|
+
this.ensureCapacity(cat, size);
|
|
413
|
+
const now = Date.now();
|
|
414
|
+
this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta });
|
|
415
|
+
this.bloom.add(key);
|
|
416
|
+
this.maybeRebuildBloom();
|
|
417
|
+
this.totalSize += size;
|
|
418
|
+
this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
|
|
419
|
+
this.categorySize.set(cat, (this.categorySize.get(cat) ?? 0) + size);
|
|
420
|
+
let ks = this.categoryKeys.get(cat);
|
|
421
|
+
if (!ks) {
|
|
422
|
+
ks = new Set();
|
|
423
|
+
this.categoryKeys.set(cat, ks);
|
|
424
|
+
}
|
|
425
|
+
ks.add(key);
|
|
426
|
+
}
|
|
427
|
+
delete(key) {
|
|
428
|
+
const deleted = this._delete(key, 'manual');
|
|
429
|
+
if (deleted)
|
|
430
|
+
this.maybeRebuildBloom();
|
|
431
|
+
return deleted;
|
|
432
|
+
}
|
|
433
|
+
keysMatchingPattern(pattern) {
|
|
434
|
+
if (!pattern.includes('*'))
|
|
435
|
+
return this.cache.has(pattern) ? [pattern] : [];
|
|
436
|
+
const re = new RegExp('^' + pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*') + '$');
|
|
437
|
+
const out = [];
|
|
438
|
+
for (const k of this.cache.keys())
|
|
439
|
+
if (re.test(k))
|
|
440
|
+
out.push(k);
|
|
441
|
+
return out;
|
|
442
|
+
}
|
|
443
|
+
deletePattern(pattern) {
|
|
444
|
+
let n = 0;
|
|
445
|
+
for (const key of this.keysMatchingPattern(pattern))
|
|
446
|
+
if (this._delete(key, 'manual'))
|
|
447
|
+
n++;
|
|
448
|
+
if (n > 0)
|
|
449
|
+
this.maybeRebuildBloom();
|
|
450
|
+
return n;
|
|
451
|
+
}
|
|
452
|
+
/** Flush all entries, or only those whose key starts with `prefix`. */
|
|
453
|
+
clear(prefix) {
|
|
454
|
+
if (prefix) {
|
|
455
|
+
const pattern = prefix.includes('*') ? prefix : `${prefix}*`;
|
|
456
|
+
return this.deletePattern(pattern);
|
|
457
|
+
}
|
|
458
|
+
const count = this.cache.size;
|
|
459
|
+
this.cache.clear();
|
|
460
|
+
this.totalSize = 0;
|
|
461
|
+
this.categoryCount.clear();
|
|
462
|
+
this.categorySize.clear();
|
|
463
|
+
this.categoryKeys.clear();
|
|
464
|
+
this.categoryHits.clear();
|
|
465
|
+
this.bloom.reset();
|
|
466
|
+
this._bloomDirtyCount = 0;
|
|
467
|
+
return count;
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* Evict entries that violate current category or global limits.
|
|
471
|
+
* Returns the number of entries evicted.
|
|
472
|
+
*/
|
|
473
|
+
rebalance() {
|
|
474
|
+
const now = Date.now();
|
|
475
|
+
let evicted = 0;
|
|
476
|
+
for (const [cat, limit] of Object.entries(this.opts.categories)) {
|
|
477
|
+
const catKeys = this.categoryKeys.get(cat);
|
|
478
|
+
if (!catKeys || catKeys.size === 0)
|
|
479
|
+
continue;
|
|
480
|
+
let catCnt = this.categoryCount.get(cat) ?? 0;
|
|
481
|
+
let catSz = this.categorySize.get(cat) ?? 0;
|
|
482
|
+
if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes)
|
|
483
|
+
continue;
|
|
484
|
+
const candidates = [];
|
|
485
|
+
for (const key of catKeys) {
|
|
486
|
+
const entry = this.cache.get(key);
|
|
487
|
+
if (!entry)
|
|
488
|
+
continue;
|
|
489
|
+
if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now)
|
|
490
|
+
continue;
|
|
491
|
+
candidates.push({ key, score: this.score(entry, 0, now, key) });
|
|
492
|
+
}
|
|
493
|
+
candidates.sort((a, b) => a.score - b.score);
|
|
494
|
+
for (const { key } of candidates) {
|
|
495
|
+
catCnt = this.categoryCount.get(cat) ?? 0;
|
|
496
|
+
catSz = this.categorySize.get(cat) ?? 0;
|
|
497
|
+
if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes)
|
|
498
|
+
break;
|
|
499
|
+
const entry = this.cache.get(key);
|
|
500
|
+
if (entry && this.opts.diskSpill)
|
|
501
|
+
this.opts.diskSpill(key, entry);
|
|
502
|
+
this._delete(key, 'rebalance');
|
|
503
|
+
evicted++;
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
// Global limits
|
|
507
|
+
while (this.cache.size > this.opts.maxEntries || this.totalSize > this.opts.maxBytes) {
|
|
508
|
+
const before = this.cache.size;
|
|
509
|
+
this.smartEvict('default', false);
|
|
510
|
+
if (this.cache.size >= before)
|
|
511
|
+
break; // only CRITICAL entries remain
|
|
512
|
+
evicted += before - this.cache.size;
|
|
513
|
+
}
|
|
514
|
+
if (evicted > 0)
|
|
515
|
+
this.maybeRebuildBloom();
|
|
516
|
+
return evicted;
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* Return remaining TTL in seconds for a key in L1, or null if absent/expired.
|
|
520
|
+
* Only reflects L1 state — does not query Redis or disk.
|
|
521
|
+
*/
|
|
522
|
+
ttl(key) {
|
|
523
|
+
const entry = this.cache.get(key);
|
|
524
|
+
if (!entry)
|
|
525
|
+
return null;
|
|
526
|
+
const remaining = entry.expiresAt - Date.now();
|
|
527
|
+
return remaining > 0 ? Math.ceil(remaining / 1000) : null;
|
|
528
|
+
}
|
|
529
|
+
/**
|
|
530
|
+
* Forcibly evict the coldest `pct` fraction of non-CRITICAL L1 entries,
|
|
531
|
+
* spilling each to L1.5 disk. Called by the OOM guard when heap pressure
|
|
532
|
+
* exceeds the configured threshold.
|
|
533
|
+
*
|
|
534
|
+
* @param pct - Fraction to evict (0–1), e.g. 0.2 = 20 %
|
|
535
|
+
* @returns Number of entries evicted
|
|
536
|
+
*/
|
|
537
|
+
evictPercentage(pct) {
|
|
538
|
+
if (pct <= 0 || this.cache.size === 0)
|
|
539
|
+
return 0;
|
|
540
|
+
const now = Date.now();
|
|
541
|
+
const candidates = [];
|
|
542
|
+
for (const [key, entry] of this.cache) {
|
|
543
|
+
if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now)
|
|
544
|
+
continue;
|
|
545
|
+
candidates.push({ key, score: this.score(entry, 0, now, key) });
|
|
546
|
+
}
|
|
547
|
+
candidates.sort((a, b) => a.score - b.score);
|
|
548
|
+
const count = Math.max(1, Math.ceil(candidates.length * pct));
|
|
549
|
+
let evicted = 0;
|
|
550
|
+
for (const { key } of candidates.slice(0, count)) {
|
|
551
|
+
const entry = this.cache.get(key);
|
|
552
|
+
if (entry && this.opts.diskSpill)
|
|
553
|
+
this.opts.diskSpill(key, entry);
|
|
554
|
+
this._delete(key, 'oom');
|
|
555
|
+
evicted++;
|
|
556
|
+
}
|
|
557
|
+
return evicted;
|
|
558
|
+
}
|
|
559
|
+
cleanup() {
|
|
560
|
+
const now = Date.now();
|
|
561
|
+
let cleaned = 0;
|
|
562
|
+
for (const [key, entry] of this.cache)
|
|
563
|
+
if (entry.expiresAt < now) {
|
|
564
|
+
this._delete(key, 'ttl');
|
|
565
|
+
cleaned++;
|
|
566
|
+
}
|
|
567
|
+
if (cleaned > 0) {
|
|
568
|
+
this.bloom.rebuild(this.cache.keys());
|
|
569
|
+
this._bloomDirtyCount = 0;
|
|
570
|
+
}
|
|
571
|
+
return cleaned;
|
|
572
|
+
}
|
|
573
|
+
// ── Snapshot import/export ────────────────────────────────────────────────
|
|
574
|
+
exportEntries(forbiddenPrefixes) {
|
|
575
|
+
const now = Date.now();
|
|
576
|
+
const out = [];
|
|
577
|
+
for (const [key, entry] of this.cache) {
|
|
578
|
+
if (entry.expiresAt <= now)
|
|
579
|
+
continue;
|
|
580
|
+
if (entry.priority === 4 /* CRITICAL */)
|
|
581
|
+
continue;
|
|
582
|
+
if (forbiddenPrefixes.some(p => key.startsWith(p)))
|
|
583
|
+
continue;
|
|
584
|
+
out.push({ key, entry: { ...entry } });
|
|
585
|
+
}
|
|
586
|
+
return out;
|
|
587
|
+
}
|
|
588
|
+
importEntries(entries, forbiddenPrefixes) {
|
|
589
|
+
const now = Date.now();
|
|
590
|
+
let loaded = 0;
|
|
591
|
+
for (const { key, entry } of entries) {
|
|
592
|
+
if (entry.expiresAt <= now)
|
|
593
|
+
continue;
|
|
594
|
+
if (forbiddenPrefixes.some(p => key.startsWith(p)))
|
|
595
|
+
continue;
|
|
596
|
+
if (this.cache.has(key))
|
|
597
|
+
continue;
|
|
598
|
+
const rawData = entry.data;
|
|
599
|
+
// Handle both legacy (isCompressed=false, data=JSON string) and current (data=Buffer) formats.
|
|
600
|
+
const data = !entry.isCompressed
|
|
601
|
+
? pack(JSON.parse(rawData)) // legacy: re-encode JSON → msgpackr
|
|
602
|
+
: rawData instanceof Uint8Array
|
|
603
|
+
? Buffer.from(rawData) // msgpackr Uint8Array → Buffer
|
|
604
|
+
: rawData; // already a Buffer
|
|
605
|
+
// Decode once on import so subsequent gets return the live object without unpacking.
|
|
606
|
+
const value = unpack(data);
|
|
607
|
+
this.cache.set(key, { ...entry, data, value, isCompressed: true });
|
|
608
|
+
this.bloom.add(key);
|
|
609
|
+
loaded++;
|
|
610
|
+
}
|
|
611
|
+
this.recalculateStats();
|
|
612
|
+
return loaded;
|
|
613
|
+
}
|
|
614
|
+
// ── Iterators ─────────────────────────────────────────────────────────────
|
|
615
|
+
/**
|
|
616
|
+
* Lazily yields every [key, entry] pair whose TTL has not yet expired.
|
|
617
|
+
* Expired entries that are still in the Map (awaiting background cleanup)
|
|
618
|
+
* are silently skipped.
|
|
619
|
+
*/
|
|
620
|
+
*liveEntries() {
|
|
621
|
+
const now = Date.now();
|
|
622
|
+
for (const [key, entry] of this.cache) {
|
|
623
|
+
if (entry.expiresAt > now)
|
|
624
|
+
yield [key, entry];
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
/**
|
|
628
|
+
* Yields only the keys of live entries — no intermediate tuple allocation.
|
|
629
|
+
* Use this instead of liveEntries() when you only need keys.
|
|
630
|
+
*/
|
|
631
|
+
*liveKeys() {
|
|
632
|
+
const now = Date.now();
|
|
633
|
+
for (const [key, entry] of this.cache) {
|
|
634
|
+
if (entry.expiresAt > now)
|
|
635
|
+
yield key;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
/**
|
|
639
|
+
* Yields only the resolved values of live entries.
|
|
640
|
+
* Iterates Map.values() so the key is never loaded into the yielded path.
|
|
641
|
+
* Returns the cached deserialized object when available (entry.value), otherwise
|
|
642
|
+
* the raw msgpackr Buffer — identical semantics to get() but without bloom/hit tracking.
|
|
643
|
+
*/
|
|
644
|
+
*liveValues() {
|
|
645
|
+
const now = Date.now();
|
|
646
|
+
for (const entry of this.cache.values()) {
|
|
647
|
+
if (entry.expiresAt > now)
|
|
648
|
+
yield entry.value !== undefined ? entry.value : entry.data;
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
// ── Stats ─────────────────────────────────────────────────────────────────
|
|
652
|
+
get size() { return this.cache.size; }
|
|
653
|
+
get memoryUsage() { return this.totalSize; }
|
|
654
|
+
getStats() {
|
|
655
|
+
const categories = {};
|
|
656
|
+
for (const [cat, cnt] of this.categoryCount) {
|
|
657
|
+
categories[cat] = { entries: cnt, hits: this.categoryHits.get(cat) ?? 0 };
|
|
658
|
+
}
|
|
659
|
+
return {
|
|
660
|
+
entries: this.cache.size,
|
|
661
|
+
sizeBytes: this.totalSize,
|
|
662
|
+
sizeKB: Math.round(this.totalSize / 1024),
|
|
663
|
+
categories,
|
|
664
|
+
bloom: {
|
|
665
|
+
checks: this.bloomChecks,
|
|
666
|
+
falsePositives: this.bloomFalsePos,
|
|
667
|
+
},
|
|
668
|
+
compression: {
|
|
669
|
+
compressed: this.compressions,
|
|
670
|
+
uncompressed: 0, // all entries are now msgpackr-packed
|
|
671
|
+
bytesSaved: 0, // no longer tracked (unified format removes the split path)
|
|
672
|
+
},
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
/**
|
|
676
|
+
* Return the raw cache entry for a key, or `undefined` if absent/expired.
|
|
677
|
+
* Does NOT count as a hit or perform SWR logic.
|
|
678
|
+
*/
|
|
679
|
+
getEntry(key) {
|
|
680
|
+
const entry = this.cache.get(key);
|
|
681
|
+
if (!entry)
|
|
682
|
+
return undefined;
|
|
683
|
+
if (entry.expiresAt <= Date.now())
|
|
684
|
+
return undefined;
|
|
685
|
+
return entry;
|
|
686
|
+
}
|
|
687
|
+
/**
|
|
688
|
+
* Return true if the key exists in L1 and has not expired.
|
|
689
|
+
* Uses the bloom filter as a fast negative check.
|
|
690
|
+
*/
|
|
691
|
+
has(key) {
|
|
692
|
+
if (!this.bloom.mightContain(key))
|
|
693
|
+
return false;
|
|
694
|
+
const entry = this.cache.get(key);
|
|
695
|
+
if (!entry)
|
|
696
|
+
return false;
|
|
697
|
+
if (entry.expiresAt <= Date.now()) {
|
|
698
|
+
this._delete(key, 'ttl');
|
|
699
|
+
return false;
|
|
700
|
+
}
|
|
701
|
+
return true;
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* Extend the TTL of an existing key. Returns `false` if the key is absent or expired.
|
|
705
|
+
* @param newTtlMs - New TTL from now, in milliseconds.
|
|
706
|
+
*/
|
|
707
|
+
touch(key, newTtlMs) {
|
|
708
|
+
const entry = this.cache.get(key);
|
|
709
|
+
if (!entry)
|
|
710
|
+
return false;
|
|
711
|
+
const now = Date.now();
|
|
712
|
+
if (entry.expiresAt <= now) {
|
|
713
|
+
this._delete(key, 'ttl');
|
|
714
|
+
return false;
|
|
715
|
+
}
|
|
716
|
+
entry.expiresAt = now + newTtlMs;
|
|
717
|
+
return true;
|
|
718
|
+
}
|
|
719
|
+
/**
|
|
720
|
+
* Add additional milliseconds to a key's existing expiry (for stale-if-error).
|
|
721
|
+
* Returns `false` if the key is absent or already expired.
|
|
722
|
+
*/
|
|
723
|
+
bumpExpiry(key, additionalMs) {
|
|
724
|
+
const entry = this.cache.get(key);
|
|
725
|
+
if (!entry)
|
|
726
|
+
return false;
|
|
727
|
+
if (entry.expiresAt <= Date.now())
|
|
728
|
+
return false;
|
|
729
|
+
entry.expiresAt += additionalMs;
|
|
730
|
+
return true;
|
|
731
|
+
}
|
|
732
|
+
bloomMightContain(key) { return this.bloom.mightContain(key); }
|
|
733
|
+
bloomStats() { return this.bloom.stats; }
|
|
734
|
+
/**
|
|
735
|
+
* Return the top-N live L1 keys by historical access frequency (Count-Min Sketch estimate).
|
|
736
|
+
* Includes evicted-then-readmitted keys whose sketch frequency exceeds their current hit count.
|
|
737
|
+
* Useful for diagnosing which keys are driving cache pressure.
|
|
738
|
+
*
|
|
739
|
+
* @param n - Maximum number of entries to return. Default: 10.
|
|
740
|
+
*/
|
|
741
|
+
hotKeys(n) {
|
|
742
|
+
const now = Date.now();
|
|
743
|
+
const out = [];
|
|
744
|
+
for (const [key, entry] of this.cache) {
|
|
745
|
+
if (entry.expiresAt <= now)
|
|
746
|
+
continue;
|
|
747
|
+
out.push({ key, hits: this.sketch.estimate(key), sizeBytes: entry.size });
|
|
748
|
+
}
|
|
749
|
+
out.sort((a, b) => b.hits - a.hits);
|
|
750
|
+
return out.slice(0, n);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
//# sourceMappingURL=smart-memory-cache.js.map
|