tricache 0.2.0 → 0.3.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.
- package/README.md +117 -15
- package/dist/index.cjs +341 -31
- package/dist/index.d.cts +146 -1
- package/dist/index.d.ts +146 -1
- package/dist/index.js +341 -31
- package/package.json +3 -2
- package/src/cache-service.ts +282 -28
- package/src/index.ts +2 -0
- package/src/smart-memory-cache.ts +125 -6
- package/src/types.ts +65 -0
|
@@ -100,6 +100,79 @@ function createBloomFilter(logger: ILogger): AnyBloomFilter {
|
|
|
100
100
|
}
|
|
101
101
|
}
|
|
102
102
|
|
|
103
|
+
// ─── Count-Min Sketch ─────────────────────────────────────────────────────────
|
|
104
|
+
//
|
|
105
|
+
// Estimates historical access frequency across eviction boundaries — a per-entry
|
|
106
|
+
// `hits` counter resets to 1 whenever a key is re-admitted after eviction, but
|
|
107
|
+
// the sketch remembers the key's frequency in a fixed-size typed array that
|
|
108
|
+
// survives evictions. This closes the same-priority burst-flood gap: a key that
|
|
109
|
+
// has been accessed 80 times over the last hour but was evicted 5 minutes ago
|
|
110
|
+
// will score far above a brand-new burst key whose hits = 1.
|
|
111
|
+
//
|
|
112
|
+
// Dimensions: 4 rows × 512 counters (Uint16Array) — 4 KB total, fits in L1d.
|
|
113
|
+
// Hash: four independent Murmur3-fragment mixes of the key's FNV-1a digest.
|
|
114
|
+
// Decay: all counters halved when total insertions cross SKETCH_DECAY_THRESHOLD
|
|
115
|
+
// (frequency-ageing prevents indefinitely growing hot-key counts).
|
|
116
|
+
|
|
117
|
+
const SKETCH_ROWS = 4;
|
|
118
|
+
const SKETCH_WIDTH = 512; // must be power of two
|
|
119
|
+
const SKETCH_MASK = SKETCH_WIDTH - 1;
|
|
120
|
+
const SKETCH_DECAY_THRESHOLD = 100_000;
|
|
121
|
+
|
|
122
|
+
class CountMinSketch {
|
|
123
|
+
private readonly table = new Uint16Array(SKETCH_ROWS * SKETCH_WIDTH);
|
|
124
|
+
private inserts = 0;
|
|
125
|
+
|
|
126
|
+
/** Inline FNV-1a for a string key → 32-bit unsigned integer. */
|
|
127
|
+
private fnv32(key: string): number {
|
|
128
|
+
let h = 0x811c9dc5;
|
|
129
|
+
for (let i = 0; i < key.length; i++) {
|
|
130
|
+
h ^= key.charCodeAt(i);
|
|
131
|
+
h = (Math.imul(h, 0x01000193) >>> 0);
|
|
132
|
+
}
|
|
133
|
+
return h;
|
|
134
|
+
}
|
|
135
|
+
|
|
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
|
+
/** Record one access. Decays all counters when the insertion threshold is crossed. */
|
|
147
|
+
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));
|
|
154
|
+
if (++this.inserts >= SKETCH_DECAY_THRESHOLD) this.decay();
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Minimum-across-rows frequency estimate. */
|
|
158
|
+
estimate(key: string): number {
|
|
159
|
+
const [h1, h2, h3, h4] = this.hashes(key);
|
|
160
|
+
const t = this.table;
|
|
161
|
+
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)],
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Halve all counters — ages out old frequency so bursts don't hold indefinitely. */
|
|
170
|
+
private decay(): void {
|
|
171
|
+
for (let i = 0; i < this.table.length; i++) this.table[i] >>>= 1;
|
|
172
|
+
this.inserts = 0;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
103
176
|
// ─── SmartMemoryCache ─────────────────────────────────────────────────────────
|
|
104
177
|
|
|
105
178
|
export interface SmartMemoryCacheOptions {
|
|
@@ -117,6 +190,8 @@ export class SmartMemoryCache {
|
|
|
117
190
|
private bloom: AnyBloomFilter;
|
|
118
191
|
/** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
|
|
119
192
|
private readonly categoryPrefixes: string[];
|
|
193
|
+
/** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
|
|
194
|
+
private readonly sketch = new CountMinSketch();
|
|
120
195
|
private totalSize = 0;
|
|
121
196
|
private categoryCount = new Map<string, number>();
|
|
122
197
|
private categorySize = new Map<string, number>();
|
|
@@ -197,10 +272,13 @@ export class SmartMemoryCache {
|
|
|
197
272
|
this.smartEvict(category, catOvf);
|
|
198
273
|
}
|
|
199
274
|
|
|
200
|
-
private score(entry: SmartCacheEntry, catBonus: number, now: number): number {
|
|
275
|
+
private score(entry: SmartCacheEntry, catBonus: number, now: number, key: string): number {
|
|
201
276
|
const age = now - entry.lastAccess;
|
|
202
277
|
const ttl = Math.max(0, entry.expiresAt - now);
|
|
203
|
-
|
|
278
|
+
// Use the sketch's cross-eviction frequency estimate when it exceeds the
|
|
279
|
+
// entry's current-tenure hit count — protects long-resident keys that were
|
|
280
|
+
// recently re-admitted (hits reset to 1) from same-priority burst floods.
|
|
281
|
+
const freq = Math.min(Math.max(entry.hits, this.sketch.estimate(key)), 100);
|
|
204
282
|
return entry.priority * 1000 + freq * 10 + ttl / 60000 - age / 60000 - catBonus;
|
|
205
283
|
}
|
|
206
284
|
|
|
@@ -250,7 +328,7 @@ export class SmartMemoryCache {
|
|
|
250
328
|
const entry = this.cache.get(key);
|
|
251
329
|
if (!entry || (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now)) continue;
|
|
252
330
|
catSeen++;
|
|
253
|
-
const s = this.score(entry, 100, now);
|
|
331
|
+
const s = this.score(entry, 100, now, key);
|
|
254
332
|
if (pool.length < EVICT) {
|
|
255
333
|
pool.push({ key, score: s });
|
|
256
334
|
} else {
|
|
@@ -273,7 +351,7 @@ export class SmartMemoryCache {
|
|
|
273
351
|
if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now) continue;
|
|
274
352
|
if (catOvf && this.getCategory(key) === targetCat) continue; // already sampled above
|
|
275
353
|
globalSeen++;
|
|
276
|
-
const s = this.score(entry, 0, now);
|
|
354
|
+
const s = this.score(entry, 0, now, key);
|
|
277
355
|
if (globalPool.length < remaining) {
|
|
278
356
|
globalPool.push({ key, score: s });
|
|
279
357
|
} else {
|
|
@@ -306,6 +384,7 @@ export class SmartMemoryCache {
|
|
|
306
384
|
if (entry.expiresAt < now) { this._delete(key, 'ttl'); return null; }
|
|
307
385
|
entry.hits++;
|
|
308
386
|
entry.lastAccess = now;
|
|
387
|
+
this.sketch.increment(key);
|
|
309
388
|
const cat = this.getCategory(key);
|
|
310
389
|
this.categoryHits.set(cat, (this.categoryHits.get(cat) ?? 0) + 1);
|
|
311
390
|
// value is cached at write time — hot reads return the live object directly,
|
|
@@ -327,6 +406,7 @@ export class SmartMemoryCache {
|
|
|
327
406
|
const packed = pack(data);
|
|
328
407
|
const size = packed.byteLength;
|
|
329
408
|
this.compressions++;
|
|
409
|
+
this.sketch.increment(key);
|
|
330
410
|
|
|
331
411
|
const cat = this.getCategory(key);
|
|
332
412
|
const lim = this.getCategoryLimit(cat);
|
|
@@ -418,7 +498,7 @@ export class SmartMemoryCache {
|
|
|
418
498
|
const entry = this.cache.get(key);
|
|
419
499
|
if (!entry) continue;
|
|
420
500
|
if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now) continue;
|
|
421
|
-
candidates.push({ key, score: this.score(entry, 0, now) });
|
|
501
|
+
candidates.push({ key, score: this.score(entry, 0, now, key) });
|
|
422
502
|
}
|
|
423
503
|
candidates.sort((a, b) => a.score - b.score);
|
|
424
504
|
|
|
@@ -470,7 +550,7 @@ export class SmartMemoryCache {
|
|
|
470
550
|
const candidates: Array<{ key: string; score: number }> = [];
|
|
471
551
|
for (const [key, entry] of this.cache) {
|
|
472
552
|
if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now) continue;
|
|
473
|
-
candidates.push({ key, score: this.score(entry, 0, now) });
|
|
553
|
+
candidates.push({ key, score: this.score(entry, 0, now, key) });
|
|
474
554
|
}
|
|
475
555
|
candidates.sort((a, b) => a.score - b.score);
|
|
476
556
|
const count = Math.max(1, Math.ceil(candidates.length * pct));
|
|
@@ -530,6 +610,45 @@ export class SmartMemoryCache {
|
|
|
530
610
|
return loaded;
|
|
531
611
|
}
|
|
532
612
|
|
|
613
|
+
// ── Iterators ─────────────────────────────────────────────────────────────
|
|
614
|
+
|
|
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(): Generator<[string, SmartCacheEntry]> {
|
|
621
|
+
const now = Date.now();
|
|
622
|
+
for (const [key, entry] of this.cache) {
|
|
623
|
+
if (entry.expiresAt > now) yield [key, entry];
|
|
624
|
+
}
|
|
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(): Generator<string> {
|
|
632
|
+
const now = Date.now();
|
|
633
|
+
for (const [key, entry] of this.cache) {
|
|
634
|
+
if (entry.expiresAt > now) yield key;
|
|
635
|
+
}
|
|
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(): Generator<unknown> {
|
|
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
|
+
|
|
533
652
|
// ── Stats ─────────────────────────────────────────────────────────────────
|
|
534
653
|
|
|
535
654
|
get size(): number { return this.cache.size; }
|
package/src/types.ts
CHANGED
|
@@ -4,6 +4,25 @@
|
|
|
4
4
|
|
|
5
5
|
// ─── Logger ─────────────────────────────────────────────────────────────────
|
|
6
6
|
|
|
7
|
+
// ─── OpenTelemetry tracer interface ──────────────────────────────────────────
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Minimal span interface — structurally compatible with `@opentelemetry/api` Span.
|
|
11
|
+
* Pass your existing OTEL tracer; no extra package required.
|
|
12
|
+
*/
|
|
13
|
+
export interface ICacheSpan {
|
|
14
|
+
setAttribute(key: string, value: string | number | boolean): this;
|
|
15
|
+
setStatus(status: { code: 0 | 1 | 2; message?: string }): this;
|
|
16
|
+
end(): void;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Minimal tracer interface — structurally compatible with `@opentelemetry/api` Tracer.
|
|
21
|
+
*/
|
|
22
|
+
export interface ICacheTracer {
|
|
23
|
+
startSpan(name: string): ICacheSpan;
|
|
24
|
+
}
|
|
25
|
+
|
|
7
26
|
/** Minimal logger interface — plug in any logger (pino, winston, console, etc.) */
|
|
8
27
|
export interface ILogger {
|
|
9
28
|
debug(msg: string, meta?: Record<string, unknown>): void;
|
|
@@ -172,6 +191,12 @@ export interface CacheMetrics {
|
|
|
172
191
|
skipped: number;
|
|
173
192
|
};
|
|
174
193
|
|
|
194
|
+
/** L2 Redis circuit breaker state */
|
|
195
|
+
l2CircuitBreaker: {
|
|
196
|
+
/** `'closed'` = normal; `'open'` = Redis paused; `'half_open'` = probing recovery */
|
|
197
|
+
state: 'closed' | 'open' | 'half_open';
|
|
198
|
+
};
|
|
199
|
+
|
|
175
200
|
/** OOM guard statistics */
|
|
176
201
|
oom: {
|
|
177
202
|
enabled: boolean;
|
|
@@ -388,4 +413,44 @@ export interface CacheOptions {
|
|
|
388
413
|
onMetrics?: (metrics: CacheMetrics) => void;
|
|
389
414
|
/** How often the `onMetrics` callback fires (ms). Default: 60 000 ms */
|
|
390
415
|
metricsIntervalMs?: number;
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* OpenTelemetry-compatible tracer. When provided, `get()`, `set()`, and
|
|
419
|
+
* `delete()` are each wrapped in a span with attributes:
|
|
420
|
+
* - `cache.hit` — `'l1' | 'disk' | 'l2' | 'miss'`
|
|
421
|
+
* - `cache.key_prefix` — first path segment of the key (e.g. `'user'`)
|
|
422
|
+
*
|
|
423
|
+
* Pass your existing `@opentelemetry/api` Tracer directly — no extra
|
|
424
|
+
* dependency required; the interface is structurally compatible.
|
|
425
|
+
*
|
|
426
|
+
* @example
|
|
427
|
+
* import { trace } from '@opentelemetry/api';
|
|
428
|
+
* tracer: trace.getTracer('tricache')
|
|
429
|
+
*/
|
|
430
|
+
tracer?: ICacheTracer;
|
|
431
|
+
|
|
432
|
+
// ── TTL jitter ─────────────────────────────────────────────────────────────
|
|
433
|
+
/**
|
|
434
|
+
* Randomise every stored TTL by ± `ttlJitterFactor × ttl` seconds.
|
|
435
|
+
* Prevents thundering-herd cache stampedes when thousands of entries share
|
|
436
|
+
* the same TTL and expire simultaneously.
|
|
437
|
+
*
|
|
438
|
+
* A factor of `0.15` spreads a 300 s TTL uniformly over [255 s, 345 s].
|
|
439
|
+
* Default: `0` (disabled — TTLs are stored exactly as given).
|
|
440
|
+
*/
|
|
441
|
+
ttlJitterFactor?: number;
|
|
442
|
+
|
|
443
|
+
// ── L2 circuit breaker ─────────────────────────────────────────────────────
|
|
444
|
+
/**
|
|
445
|
+
* Number of consecutive Redis errors before the circuit opens (stops
|
|
446
|
+
* attempting Redis until the cooldown elapses).
|
|
447
|
+
* Default: `5`.
|
|
448
|
+
*/
|
|
449
|
+
l2CircuitBreakerThreshold?: number;
|
|
450
|
+
/**
|
|
451
|
+
* Milliseconds the circuit stays open before transitioning to half-open
|
|
452
|
+
* (allows a single probe request to test recovery).
|
|
453
|
+
* Default: `30 000` ms (30 s).
|
|
454
|
+
*/
|
|
455
|
+
l2CircuitBreakerCooldownMs?: number;
|
|
391
456
|
}
|