tricache 0.5.1 → 0.6.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 +14 -0
- package/dist/cache-service.d.ts +419 -0
- package/dist/cache-service.d.ts.map +1 -0
- package/dist/cache-service.js +1788 -0
- package/dist/cache-service.js.map +1 -0
- package/dist/disk-tier.d.ts +150 -0
- package/dist/disk-tier.d.ts.map +1 -0
- package/dist/disk-tier.js +808 -0
- package/dist/disk-tier.js.map +1 -0
- package/dist/encryption.d.ts +90 -0
- package/dist/encryption.d.ts.map +1 -0
- package/dist/encryption.js +393 -0
- package/dist/encryption.js.map +1 -0
- package/dist/index.cjs +463 -72
- package/dist/index.d.cts +123 -6
- package/dist/index.d.ts +18 -1310
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +25 -3131
- package/dist/index.js.map +1 -0
- package/dist/smart-memory-cache.d.ts +208 -0
- package/dist/smart-memory-cache.d.ts.map +1 -0
- package/dist/smart-memory-cache.js +933 -0
- package/dist/smart-memory-cache.js.map +1 -0
- package/dist/types.d.ts +537 -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 +83 -0
- package/dist/wasm/bloom-filter-wasm.js.map +1 -0
- package/package.json +2 -2
- package/src/cache-service.ts +201 -17
- package/src/disk-tier.ts +244 -28
- package/src/encryption.ts +47 -22
- package/src/smart-memory-cache.ts +63 -30
- package/src/types.ts +80 -0
|
@@ -24,6 +24,10 @@ import { WasmBloomFilter } from './wasm/bloom-filter-wasm';
|
|
|
24
24
|
|
|
25
25
|
/** Fraction of candidates evicted in one pass when a limit is exceeded */
|
|
26
26
|
const EVICTION_BATCH_PERCENT = 0.2;
|
|
27
|
+
/** Reservoir sample window for smartEvict() — Redis-style. */
|
|
28
|
+
const EVICTION_SAMPLE = 16;
|
|
29
|
+
/** Number of lowest-scored candidates evicted per smartEvict() call. */
|
|
30
|
+
const EVICT_COUNT = Math.max(1, Math.ceil(EVICTION_SAMPLE * EVICTION_BATCH_PERCENT)); // 4
|
|
27
31
|
|
|
28
32
|
// ─── Pure-JS Bloom filter fallback ───────────────────────────────────────────
|
|
29
33
|
|
|
@@ -242,12 +246,14 @@ function globMatch(pattern: string, key: string): boolean {
|
|
|
242
246
|
// ─── SmartMemoryCache ─────────────────────────────────────────────────────────
|
|
243
247
|
|
|
244
248
|
export interface SmartMemoryCacheOptions {
|
|
245
|
-
maxBytes:
|
|
246
|
-
maxEntries:
|
|
247
|
-
categories:
|
|
248
|
-
diskSpill?:
|
|
249
|
-
onEviction?:
|
|
250
|
-
logger:
|
|
249
|
+
maxBytes: number;
|
|
250
|
+
maxEntries: number;
|
|
251
|
+
categories: Record<string, CategoryLimit>;
|
|
252
|
+
diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
|
|
253
|
+
onEviction?: (key: string, reason: EvictionReason) => void;
|
|
254
|
+
logger: ILogger;
|
|
255
|
+
/** Fraction of maxEntries / maxBytes at which proactive eviction fires (default 0.9). */
|
|
256
|
+
evictionWatermark?: number;
|
|
251
257
|
}
|
|
252
258
|
|
|
253
259
|
export class SmartMemoryCache {
|
|
@@ -271,6 +277,18 @@ export class SmartMemoryCache {
|
|
|
271
277
|
/** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
|
|
272
278
|
private _bloomDirtyCount = 0;
|
|
273
279
|
|
|
280
|
+
/**
|
|
281
|
+
* Pre-allocated eviction candidate pools — reused across every smartEvict() call to
|
|
282
|
+
* eliminate per-call heap pressure. Each slot holds a mutable {key, score} record
|
|
283
|
+
* that is overwritten in-place rather than replaced with a new object literal.
|
|
284
|
+
* Safe because JS is single-threaded: smartEvict() completes synchronously before
|
|
285
|
+
* any other code can observe the pool state.
|
|
286
|
+
*/
|
|
287
|
+
private readonly _evictPool: Array<{ key: string; score: number }> =
|
|
288
|
+
Array.from({ length: EVICTION_SAMPLE }, () => ({ key: '', score: 0 }));
|
|
289
|
+
private readonly _evictGPool: Array<{ key: string; score: number }> =
|
|
290
|
+
Array.from({ length: EVICTION_SAMPLE }, () => ({ key: '', score: 0 }));
|
|
291
|
+
|
|
274
292
|
constructor(opts: SmartMemoryCacheOptions, existing?: Map<string, SmartCacheEntry>) {
|
|
275
293
|
this.opts = opts;
|
|
276
294
|
this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
|
|
@@ -342,8 +360,9 @@ export class SmartMemoryCache {
|
|
|
342
360
|
// capacity become uncommon. Both dimensions are guarded so that
|
|
343
361
|
// large-payload workloads (where maxBytes is the binding constraint)
|
|
344
362
|
// benefit equally alongside entry-count-bound workloads.
|
|
345
|
-
const
|
|
346
|
-
const
|
|
363
|
+
const wm = this.opts.evictionWatermark ?? 0.9;
|
|
364
|
+
const entryWatermark = this.cache.size >= Math.floor(this.opts.maxEntries * wm);
|
|
365
|
+
const byteWatermark = this.totalSize + neededSize >= Math.floor(this.opts.maxBytes * wm);
|
|
347
366
|
if (entryWatermark || byteWatermark) {
|
|
348
367
|
this.smartEvict(category, false);
|
|
349
368
|
}
|
|
@@ -396,16 +415,15 @@ export class SmartMemoryCache {
|
|
|
396
415
|
|
|
397
416
|
private smartEvict(targetCat: string, catOvf: boolean): void {
|
|
398
417
|
const now = Date.now();
|
|
399
|
-
const
|
|
400
|
-
const
|
|
401
|
-
|
|
402
|
-
const pool: Array<{ key: string; score: number }> = [];
|
|
418
|
+
const pool = this._evictPool;
|
|
419
|
+
const gPool = this._evictGPool;
|
|
420
|
+
let poolLen = 0;
|
|
403
421
|
|
|
404
422
|
if (catOvf) {
|
|
405
423
|
// Phase 1 — O(catSize) category-local reservoir sample.
|
|
406
424
|
// Uses the categoryKeys index to iterate only the overflowing category's keys,
|
|
407
425
|
// avoiding an O(N) scan of the entire cache. Guarantees at least
|
|
408
|
-
// min(catSize,
|
|
426
|
+
// min(catSize, EVICT_COUNT) entries from the overflowing category in the pool so
|
|
409
427
|
// the priority score ordering is always deterministic in practice.
|
|
410
428
|
const catKeySet = this.categoryKeys.get(targetCat);
|
|
411
429
|
if (catKeySet) {
|
|
@@ -415,44 +433,59 @@ export class SmartMemoryCache {
|
|
|
415
433
|
if (!entry || (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now)) continue;
|
|
416
434
|
catSeen++;
|
|
417
435
|
const s = this.score(entry, 100, now, key);
|
|
418
|
-
if (
|
|
419
|
-
pool.
|
|
436
|
+
if (poolLen < EVICT_COUNT) {
|
|
437
|
+
pool[poolLen].key = key; pool[poolLen].score = s; poolLen++;
|
|
420
438
|
} else {
|
|
421
439
|
const j = Math.floor(Math.random() * catSeen);
|
|
422
|
-
if (j <
|
|
440
|
+
if (j < EVICT_COUNT) { pool[j].key = key; pool[j].score = s; }
|
|
423
441
|
}
|
|
424
442
|
}
|
|
425
443
|
}
|
|
426
444
|
}
|
|
427
445
|
|
|
428
|
-
// Phase 2 — global reservoir sample fills remaining
|
|
429
|
-
// Skipped entirely when Phase 1 already collected a full
|
|
430
|
-
// (the common catOvf case — overflowing categories always have ≥
|
|
446
|
+
// Phase 2 — global reservoir sample fills remaining EVICTION_SAMPLE-poolLen slots.
|
|
447
|
+
// Skipped entirely when Phase 1 already collected a full EVICT_COUNT-sized pool
|
|
448
|
+
// (the common catOvf case — overflowing categories always have ≥ EVICT_COUNT entries).
|
|
431
449
|
// Also the sole phase when !catOvf (global over-capacity, no preferred category).
|
|
432
|
-
if (
|
|
433
|
-
const remaining =
|
|
450
|
+
if (poolLen < EVICT_COUNT) {
|
|
451
|
+
const remaining = EVICTION_SAMPLE - poolLen;
|
|
434
452
|
let globalSeen = 0;
|
|
435
|
-
|
|
453
|
+
let gLen = 0;
|
|
436
454
|
for (const [key, entry] of this.cache) {
|
|
437
455
|
if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now) continue;
|
|
438
456
|
if (catOvf && this.getCategory(key) === targetCat) continue; // already sampled above
|
|
439
457
|
globalSeen++;
|
|
440
458
|
const s = this.score(entry, 0, now, key);
|
|
441
|
-
if (
|
|
442
|
-
|
|
459
|
+
if (gLen < remaining) {
|
|
460
|
+
gPool[gLen].key = key; gPool[gLen].score = s; gLen++;
|
|
443
461
|
} else {
|
|
444
462
|
const j = Math.floor(Math.random() * globalSeen);
|
|
445
|
-
if (j < remaining)
|
|
463
|
+
if (j < remaining) { gPool[j].key = key; gPool[j].score = s; }
|
|
446
464
|
}
|
|
447
465
|
}
|
|
448
|
-
|
|
466
|
+
// Manual merge — no spread, no new array
|
|
467
|
+
for (let i = 0; i < gLen; i++) {
|
|
468
|
+
pool[poolLen].key = gPool[i].key; pool[poolLen].score = gPool[i].score; poolLen++;
|
|
469
|
+
}
|
|
449
470
|
}
|
|
450
471
|
|
|
451
|
-
if (
|
|
472
|
+
if (poolLen === 0) return;
|
|
473
|
+
|
|
474
|
+
// Insertion sort — O(poolLen²) but poolLen ≤ EVICTION_SAMPLE=16 (max 256 comparisons).
|
|
475
|
+
// Faster than Array.sort() at this scale: no comparator closure call overhead,
|
|
476
|
+
// no timsort startup, no allocation. Sorts in-place within the pre-allocated pool.
|
|
477
|
+
for (let i = 1; i < poolLen; i++) {
|
|
478
|
+
const sk = pool[i].key, ss = pool[i].score;
|
|
479
|
+
let j = i - 1;
|
|
480
|
+
while (j >= 0 && pool[j].score > ss) {
|
|
481
|
+
pool[j + 1].key = pool[j].key; pool[j + 1].score = pool[j].score; j--;
|
|
482
|
+
}
|
|
483
|
+
pool[j + 1].key = sk; pool[j + 1].score = ss;
|
|
484
|
+
}
|
|
452
485
|
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
486
|
+
const toEvict = Math.min(EVICT_COUNT, poolLen);
|
|
487
|
+
for (let i = 0; i < toEvict; i++) {
|
|
488
|
+
const key = pool[i].key;
|
|
456
489
|
const entry = this.cache.get(key);
|
|
457
490
|
if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry); // L1.5 spill
|
|
458
491
|
this._delete(key, 'capacity');
|
package/src/types.ts
CHANGED
|
@@ -222,6 +222,19 @@ export interface CacheMetrics {
|
|
|
222
222
|
|
|
223
223
|
l1: { entries: number; sizeBytes: number; maxBytes: number };
|
|
224
224
|
disk: { files: number; sizeKB: number; maxKB: number };
|
|
225
|
+
|
|
226
|
+
/** Adaptive TTL statistics — present only when `adaptiveTtl` is enabled */
|
|
227
|
+
adaptiveTtl?: {
|
|
228
|
+
enabled: true;
|
|
229
|
+
/** Number of unique keys currently tracked in the latency ring buffers */
|
|
230
|
+
trackedKeys: number;
|
|
231
|
+
/**
|
|
232
|
+
* Top-20 slowest keys by p95 fetch latency, sorted descending.
|
|
233
|
+
* Keys are shown without the instance namespace prefix.
|
|
234
|
+
* Only keys with ≥ 5 recorded samples appear here.
|
|
235
|
+
*/
|
|
236
|
+
slowestKeys: Array<{ key: string; p95Ms: number; adaptedTtlSec: number }>;
|
|
237
|
+
};
|
|
225
238
|
}
|
|
226
239
|
|
|
227
240
|
// ─── Configuration ───────────────────────────────────────────────────────────
|
|
@@ -249,6 +262,12 @@ export interface CacheOptions {
|
|
|
249
262
|
l1MaxBytes?: number;
|
|
250
263
|
/** Max total entries in L1. Default: 2000 */
|
|
251
264
|
l1MaxEntries?: number;
|
|
265
|
+
/**
|
|
266
|
+
* Fraction of `l1MaxEntries` / `l1MaxBytes` at which proactive eviction fires
|
|
267
|
+
* before the hard limit is reached. Range: 0–1. Default: 0.9.
|
|
268
|
+
* Lower (e.g. 0.8) reduces GC pressure at the cost of slightly more eviction work.
|
|
269
|
+
*/
|
|
270
|
+
l1EvictionWatermark?: number;
|
|
252
271
|
/**
|
|
253
272
|
* Per-category limits keyed by the key prefix (e.g. `'org:'`).
|
|
254
273
|
* Merged over the built-in defaults.
|
|
@@ -515,4 +534,65 @@ export interface CacheOptions {
|
|
|
515
534
|
* frozen: process.env.NODE_ENV !== 'production'
|
|
516
535
|
*/
|
|
517
536
|
frozen?: boolean;
|
|
537
|
+
|
|
538
|
+
// ── Adaptive TTL ──────────────────────────────────────────────────────────
|
|
539
|
+
|
|
540
|
+
/**
|
|
541
|
+
* When `true`, tricache tracks per-key fetch latency in a rolling ring buffer
|
|
542
|
+
* and automatically derives an optimal TTL from the p95 fetch duration:
|
|
543
|
+
*
|
|
544
|
+
* ```
|
|
545
|
+
* adaptedTtl = clamp(p95LatencyMs × adaptiveTtlMultiplier, adaptiveTtlMin, adaptiveTtlMax)
|
|
546
|
+
* ```
|
|
547
|
+
*
|
|
548
|
+
* The caller-supplied `ttlSeconds` is used until at least 5 samples are collected
|
|
549
|
+
* for a key, then the library takes over TTL management autonomously.
|
|
550
|
+
*
|
|
551
|
+
* Expensive keys (slow DB queries) get cached longer; cheap keys stay close to
|
|
552
|
+
* their base TTL. Callers no longer need to reason about individual TTL values.
|
|
553
|
+
*
|
|
554
|
+
* Default: `false`.
|
|
555
|
+
*/
|
|
556
|
+
adaptiveTtl?: boolean;
|
|
557
|
+
|
|
558
|
+
/**
|
|
559
|
+
* Minimum TTL (seconds) the adaptive tuner will ever assign.
|
|
560
|
+
* Guards against extremely fast fetches producing near-zero TTLs.
|
|
561
|
+
* Default: `10`.
|
|
562
|
+
*/
|
|
563
|
+
adaptiveTtlMin?: number;
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* Maximum TTL (seconds) the adaptive tuner will ever assign.
|
|
567
|
+
* Guards against pathologically slow fetches producing indefinite caching.
|
|
568
|
+
* Default: `86400` (24 hours).
|
|
569
|
+
*/
|
|
570
|
+
adaptiveTtlMax?: number;
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* `p95FetchLatencyMs × adaptiveTtlMultiplier = adaptedTtlSeconds`.
|
|
574
|
+
*
|
|
575
|
+
* Intuition: a 200 ms p95 fetch with the default multiplier of 20 yields a
|
|
576
|
+
* 4-second TTL. A 2 000 ms fetch yields 40 seconds. Increase the multiplier
|
|
577
|
+
* if you want the cache to absorb more upstream pressure.
|
|
578
|
+
*
|
|
579
|
+
* Default: `20`.
|
|
580
|
+
*/
|
|
581
|
+
adaptiveTtlMultiplier?: number;
|
|
582
|
+
|
|
583
|
+
/**
|
|
584
|
+
* Number of fetch duration samples kept per key in the ring buffer.
|
|
585
|
+
* Larger values smooth out latency spikes but use slightly more memory
|
|
586
|
+
* (~8 bytes × samples per tracked key).
|
|
587
|
+
* Default: `32`.
|
|
588
|
+
*/
|
|
589
|
+
adaptiveTtlSamples?: number;
|
|
590
|
+
|
|
591
|
+
/**
|
|
592
|
+
* Maximum number of distinct keys tracked by the adaptive TTL system.
|
|
593
|
+
* When the cap is reached, the oldest-tracked key is evicted from the
|
|
594
|
+
* ring-buffer store to make room for the new key.
|
|
595
|
+
* Default: `5000`.
|
|
596
|
+
*/
|
|
597
|
+
adaptiveTtlMaxKeys?: number;
|
|
518
598
|
}
|