tricache 1.0.1 → 2.0.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 +89 -93
- package/dashboards/tricache-alerts.yaml +80 -4
- package/dashboards/tricache-grafana.json +54 -1
- package/dashboards/tricache-inventory.rules.yml +21 -0
- package/dist/cache-service-BV5T8-20.d.cts +1064 -0
- package/dist/cache-service-UZXOQGEY.js +14 -0
- package/dist/{cache-service-CREOp7MM.d.ts → cache-service-tpyrXvlH.d.ts} +157 -24
- package/dist/{chunk-UBWLPKTI.js → chunk-EJXG7WO6.js} +152 -32
- package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
- package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
- package/dist/{chunk-2AJKEQMZ.js → chunk-KV7KISK2.js} +54 -5
- package/dist/{chunk-JYQFQJNJ.js → chunk-MB3DMVWN.js} +3424 -1022
- package/dist/chunk-RBJRTGFK.js +94 -0
- package/dist/chunk-S5N65I45.js +17 -0
- package/dist/cli.cjs +3694 -1070
- package/dist/cli.d.cts +12 -0
- package/dist/cli.js +210 -14
- package/dist/dashboard/index.cjs +111 -29
- package/dist/dashboard/index.d.cts +185 -0
- package/dist/dashboard/index.d.ts +5 -3
- package/dist/dashboard/index.js +1 -1
- package/dist/drizzle/index.cjs +3578 -1068
- package/dist/drizzle/index.d.cts +46 -0
- package/dist/drizzle/index.d.ts +2 -2
- package/dist/drizzle/index.js +6 -2
- package/dist/edge/index.cjs +368 -162
- package/dist/edge/index.d.cts +134 -0
- package/dist/edge/index.d.ts +11 -4
- package/dist/edge/index.js +314 -155
- package/dist/hono/index.cjs +3614 -1087
- package/dist/hono/index.d.cts +93 -0
- package/dist/hono/index.d.ts +7 -5
- package/dist/hono/index.js +16 -9
- package/dist/hono-CMv2VdQ6.d.cts +404 -0
- package/dist/{hono-DSV2ve66.d.ts → hono-Dvq04kX9.d.ts} +33 -7
- package/dist/http/index.cjs +3712 -1124
- package/dist/http/index.d.cts +103 -0
- package/dist/http/index.d.ts +13 -5
- package/dist/http/index.js +92 -43
- package/dist/index.cjs +4067 -1252
- package/dist/index.d.cts +1071 -0
- package/dist/index.d.ts +123 -27
- package/dist/index.js +878 -21
- package/dist/{murmur3-CMGw9PbV.d.ts → murmur3-DF8BFRnu.d.cts} +1 -0
- package/dist/murmur3-DF8BFRnu.d.ts +99 -0
- package/dist/nestjs/index.cjs +3635 -1112
- package/dist/nestjs/index.d.cts +299 -0
- package/dist/nestjs/index.d.ts +120 -33
- package/dist/nestjs/index.js +132 -43
- package/dist/next/index.cjs +3704 -1175
- package/dist/next/index.d.cts +238 -0
- package/dist/next/index.d.ts +39 -11
- package/dist/next/index.js +202 -102
- package/dist/prisma/index.cjs +29 -18
- package/dist/prisma/index.d.cts +62 -0
- package/dist/prisma/index.d.ts +2 -2
- package/dist/prisma/index.js +17 -18
- package/dist/serialize-worker.cjs +162 -39
- package/dist/serialize-worker.d.cts +2 -0
- package/dist/serialize-worker.js +9 -7
- package/dist/{types-Dyip5wAl.d.ts → types-F8vRWMrE.d.cts} +186 -54
- package/dist/types-F8vRWMrE.d.ts +1636 -0
- package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
- package/dist/utils-Bvzn-rKS.d.ts +29 -0
- package/package.json +116 -37
- package/src/adapters/auto-pipeliner.ts +150 -26
- package/src/adapters/node-redis.ts +106 -27
- package/src/cache-service.ts +2215 -793
- package/src/cli.ts +25 -14
- package/src/codec.ts +3 -3
- package/src/compression.ts +39 -16
- package/src/cross-region.ts +22 -4
- package/src/dashboard/handler.ts +26 -6
- package/src/dashboard/html.ts +35 -10
- package/src/dashboard/index.ts +35 -13
- package/src/dashboard/types.ts +3 -1
- package/src/disk-tier.ts +448 -102
- package/src/drizzle/index.ts +2 -1
- package/src/edge/adapters/cloudflare-do.ts +25 -10
- package/src/edge/adapters/cloudflare-kv.ts +12 -9
- package/src/edge/adapters/upstash.ts +27 -11
- package/src/edge/cache.ts +200 -110
- package/src/edge/hono.ts +23 -6
- package/src/edge/types.ts +17 -5
- package/src/encryption.ts +50 -18
- package/src/env.d.ts +1 -1
- package/src/errors.ts +12 -0
- package/src/hono/index.ts +19 -9
- package/src/http/express.ts +62 -17
- package/src/http/fastify.ts +35 -21
- package/src/http/utils.ts +60 -20
- package/src/index.ts +6 -0
- package/src/ipc-telemetry.ts +35 -9
- package/src/latency-watchdog.ts +5 -1
- package/src/nestjs/decorators.ts +11 -6
- package/src/nestjs/index.ts +2 -0
- package/src/nestjs/keyv-adapter.ts +68 -0
- package/src/nestjs/tricache.module.ts +15 -12
- package/src/nestjs/tricache.store.ts +69 -26
- package/src/nestjs/types.ts +30 -16
- package/src/next/cache-handler.ts +151 -53
- package/src/next/index.ts +1 -0
- package/src/next/types.ts +25 -0
- package/src/origin-capacity.ts +134 -0
- package/src/prisma/index.ts +17 -24
- package/src/remote-snapshot.ts +37 -27
- package/src/serialize-worker.ts +8 -5
- package/src/sigv4-snapshot-adapter.ts +37 -27
- package/src/smart-memory-cache.ts +121 -44
- package/src/types.ts +117 -37
- package/src/utils/cgroup.ts +12 -0
- package/src/utils/config-comparison.ts +29 -0
- package/src/utils/deadline.ts +14 -0
- package/src/utils/diagnostics.ts +27 -0
- package/src/utils/lz4-size.ts +74 -0
- package/src/utils/namespace-key.ts +48 -0
- package/src/utils/query-key.ts +13 -0
- package/src/utils/redis-slot.ts +13 -0
- package/src/utils/snapshot-transfer.ts +83 -0
- package/src/utils/work-limits.ts +73 -0
- package/src/utils/write-revision.ts +4 -0
- package/src/wasm/bloom-filter-wasm.ts +25 -5
- package/src/worker-pool.ts +44 -15
- package/src/wtiny-lfu.ts +82 -20
- package/dist/cache-service-MG7PN6MX.js +0 -12
- package/dist/chunk-3I5L7K6I.js +0 -704
- package/dist/chunk-BQRURGGD.js +0 -60
|
@@ -13,8 +13,10 @@
|
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
15
|
import { CacheCodec, defaultCodec } from './codec.js';
|
|
16
|
+
import { randomUUID } from 'node:crypto';
|
|
16
17
|
import type { CacheHit, CachePriority, CategoryLimit, SmartCacheEntry, ILogger, EvictionReason, WTinyLfuStats } from './types';
|
|
17
18
|
import { WTinyLfuPolicy } from './wtiny-lfu.js';
|
|
19
|
+
import { isWriteRevision } from './utils/write-revision.js';
|
|
18
20
|
|
|
19
21
|
/**
|
|
20
22
|
* Packed-byte threshold above which the live JS object is NOT stored alongside the
|
|
@@ -119,8 +121,9 @@ type AnyBloomFilter = JsBloomFilter | WasmBloomFilter;
|
|
|
119
121
|
function createBloomFilter(logger: ILogger, maxEntries: number): AnyBloomFilter {
|
|
120
122
|
// Compute optimal bit-count for p = 1 % and the requested entry ceiling.
|
|
121
123
|
const LN2_SQ = Math.LN2 * Math.LN2; // (ln 2)² ≈ 0.4804
|
|
122
|
-
const
|
|
123
|
-
const
|
|
124
|
+
const capacity = Math.max(1, maxEntries);
|
|
125
|
+
const optimalBits = Math.ceil(-capacity * Math.log(0.01) / LN2_SQ);
|
|
126
|
+
const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / capacity)));
|
|
124
127
|
|
|
125
128
|
try {
|
|
126
129
|
const wasm = new WasmBloomFilter();
|
|
@@ -253,6 +256,8 @@ export interface SmartMemoryCacheOptions {
|
|
|
253
256
|
maxBytes: number;
|
|
254
257
|
maxEntries: number;
|
|
255
258
|
categories: Record<string, CategoryLimit>;
|
|
259
|
+
/** Storage-key prefix to skip when matching logical category prefixes. */
|
|
260
|
+
keyPrefixLength?: number;
|
|
256
261
|
diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
|
|
257
262
|
onEviction?: (key: string, reason: EvictionReason) => void;
|
|
258
263
|
logger: ILogger;
|
|
@@ -288,6 +293,7 @@ export class SmartMemoryCache {
|
|
|
288
293
|
// ── Observability counters ──────────────────────────────────────────────────────
|
|
289
294
|
private bloomChecks = 0;
|
|
290
295
|
private bloomFalsePos = 0;
|
|
296
|
+
private bloomAbsentChecks = 0;
|
|
291
297
|
private compressions = 0; private categoryHits = new Map<string, number>();
|
|
292
298
|
/** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
|
|
293
299
|
private _bloomDirtyCount = 0;
|
|
@@ -310,7 +316,10 @@ export class SmartMemoryCache {
|
|
|
310
316
|
this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
|
|
311
317
|
this.categoryPrefixes = Object.keys(opts.categories).filter(k => k !== 'default');
|
|
312
318
|
if (opts.admissionPolicy === 'wtinylfu') {
|
|
313
|
-
this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch
|
|
319
|
+
this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch, 0.01, 0.80, key => {
|
|
320
|
+
const entry = this.cache.get(key);
|
|
321
|
+
return !entry || entry.priority !== 4 || entry.expiresAt <= Date.now();
|
|
322
|
+
});
|
|
314
323
|
}
|
|
315
324
|
|
|
316
325
|
if (existing) {
|
|
@@ -346,7 +355,7 @@ export class SmartMemoryCache {
|
|
|
346
355
|
|
|
347
356
|
private getCategory(key: string): string {
|
|
348
357
|
for (const prefix of this.categoryPrefixes) {
|
|
349
|
-
if (key.startsWith(prefix)) return prefix;
|
|
358
|
+
if (key.startsWith(prefix, this.opts.keyPrefixLength ?? 0)) return prefix;
|
|
350
359
|
}
|
|
351
360
|
return 'default';
|
|
352
361
|
}
|
|
@@ -367,7 +376,7 @@ export class SmartMemoryCache {
|
|
|
367
376
|
this._bloomDirtyCount++;
|
|
368
377
|
const deleted = this.cache.delete(key);
|
|
369
378
|
if (deleted && this.opts.onEviction) {
|
|
370
|
-
try { this.opts.onEviction(key, reason); } catch { /* never crash cache */ }
|
|
379
|
+
try { void Promise.resolve(this.opts.onEviction(key, reason)).catch(() => {}); } catch { /* never crash cache */ }
|
|
371
380
|
}
|
|
372
381
|
return deleted;
|
|
373
382
|
}
|
|
@@ -403,6 +412,7 @@ export class SmartMemoryCache {
|
|
|
403
412
|
const MAX_EVICT_PASSES = 64;
|
|
404
413
|
let passes = 0;
|
|
405
414
|
do {
|
|
415
|
+
const before = this.cache.size;
|
|
406
416
|
this.smartEvict(category, catOvf);
|
|
407
417
|
const lim2 = this.getCategoryLimit(category);
|
|
408
418
|
const catCnt2 = this.categoryCount.get(category) ?? 0;
|
|
@@ -410,6 +420,7 @@ export class SmartMemoryCache {
|
|
|
410
420
|
catOvf = catCnt2 >= lim2.maxEntries || catSz2 + neededSize > lim2.maxSizeBytes;
|
|
411
421
|
glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
|
|
412
422
|
passes++;
|
|
423
|
+
if (this.cache.size === before) break; // Only protected entries remain.
|
|
413
424
|
} while ((catOvf || glbOvf) && passes < MAX_EVICT_PASSES);
|
|
414
425
|
}
|
|
415
426
|
|
|
@@ -538,16 +549,12 @@ export class SmartMemoryCache {
|
|
|
538
549
|
|
|
539
550
|
get(key: string): CacheHit | null {
|
|
540
551
|
this.bloomChecks++;
|
|
541
|
-
if (!this.bloom.mightContain(key)) return null;
|
|
552
|
+
if (!this.bloom.mightContain(key)) { this.bloomAbsentChecks++; return null; }
|
|
542
553
|
const entry = this.cache.get(key);
|
|
543
|
-
if (!entry) { this.bloomFalsePos++; return null; }
|
|
554
|
+
if (!entry) { this.bloomFalsePos++; this.bloomAbsentChecks++; return null; }
|
|
544
555
|
const now = Date.now();
|
|
545
556
|
if (entry.expiresAt < now) { this._delete(key, 'ttl'); return null; }
|
|
546
|
-
entry
|
|
547
|
-
entry.lastAccess = now;
|
|
548
|
-
// Sample sketch at 25 % — eviction scoring only needs relative frequency, not exact counts.
|
|
549
|
-
if ((entry.hits & 3) === 0) this.sketch.increment(key);
|
|
550
|
-
this.wtinyPolicy?.onAccess(key);
|
|
557
|
+
this.recordAccess(key, entry, now);
|
|
551
558
|
// value is cached at write time — hot reads return the live object directly,
|
|
552
559
|
// skipping unpack. Falls back to decode for entries restored from disk/snapshot.
|
|
553
560
|
const value = entry.value !== undefined ? entry.value : this.codec.decode(entry.data as Buffer);
|
|
@@ -564,10 +571,22 @@ export class SmartMemoryCache {
|
|
|
564
571
|
fetchedAt: now,
|
|
565
572
|
tagVersions: entry.tagVersions,
|
|
566
573
|
setAt: entry.setAt,
|
|
574
|
+
revision: entry.revision,
|
|
575
|
+
tags: entry.tags,
|
|
576
|
+
dependsOn: entry.dependsOn,
|
|
567
577
|
};
|
|
568
578
|
return hit;
|
|
569
579
|
}
|
|
570
580
|
|
|
581
|
+
/** Shared policy accounting for scalar and batch reads. */
|
|
582
|
+
recordAccess(key: string, entry: SmartCacheEntry, now = Date.now()): void {
|
|
583
|
+
if (this.cache.get(key) !== entry) return;
|
|
584
|
+
entry.hits++;
|
|
585
|
+
entry.lastAccess = now;
|
|
586
|
+
if ((entry.hits & 3) === 0) this.sketch.increment(key);
|
|
587
|
+
this.wtinyPolicy?.onAccess(key);
|
|
588
|
+
}
|
|
589
|
+
|
|
571
590
|
set(
|
|
572
591
|
key: string,
|
|
573
592
|
data: unknown,
|
|
@@ -577,10 +596,42 @@ export class SmartMemoryCache {
|
|
|
577
596
|
delta?: number,
|
|
578
597
|
tagVersions?: Record<string, number>,
|
|
579
598
|
setAt?: number,
|
|
580
|
-
|
|
599
|
+
tags?: string[],
|
|
600
|
+
dependsOn?: string[],
|
|
601
|
+
revision: string = randomUUID(),
|
|
602
|
+
): boolean {
|
|
581
603
|
// Single serialization pass — always msgpackr. Eliminates the prior JSON.stringify
|
|
582
604
|
// "size probe" that was discarded for large payloads (the double-pass).
|
|
583
|
-
|
|
605
|
+
return this.setPacked(key, this.codec.encode(data), data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn, revision);
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/**
|
|
609
|
+
* Store a value when its codec representation is already available.
|
|
610
|
+
* CacheService uses this to share one MessagePack encoding between L1 and
|
|
611
|
+
* Redis/disk writes on an origin fill. The buffer is treated as immutable.
|
|
612
|
+
*/
|
|
613
|
+
setPacked(
|
|
614
|
+
key: string,
|
|
615
|
+
packed: Buffer,
|
|
616
|
+
data: unknown,
|
|
617
|
+
ttlMs: number,
|
|
618
|
+
priority: CachePriority = 2 /* NORMAL */,
|
|
619
|
+
staleAt?: number,
|
|
620
|
+
delta?: number,
|
|
621
|
+
tagVersions?: Record<string, number>,
|
|
622
|
+
setAt?: number,
|
|
623
|
+
tags?: string[],
|
|
624
|
+
dependsOn?: string[],
|
|
625
|
+
revision: string = randomUUID(),
|
|
626
|
+
): boolean {
|
|
627
|
+
return this.storePacked(key, packed, data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn, revision);
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
private storePacked(
|
|
631
|
+
key: string, packed: Buffer, data: unknown, ttlMs: number, priority: CachePriority,
|
|
632
|
+
staleAt?: number, delta?: number, tagVersions?: Record<string, number>, setAt?: number,
|
|
633
|
+
tags?: string[], dependsOn?: string[], revision?: string,
|
|
634
|
+
): boolean {
|
|
584
635
|
const size = packed.byteLength;
|
|
585
636
|
this.compressions++;
|
|
586
637
|
this.sketch.increment(key);
|
|
@@ -588,9 +639,11 @@ export class SmartMemoryCache {
|
|
|
588
639
|
const cat = this.getCategory(key);
|
|
589
640
|
const lim = this.getCategoryLimit(cat);
|
|
590
641
|
|
|
591
|
-
if (
|
|
642
|
+
if (!Number.isFinite(ttlMs) || ttlMs <= 0 || this.opts.maxEntries <= 0 || lim.maxEntries <= 0 ||
|
|
643
|
+
size > this.opts.maxBytes || size > lim.maxSizeBytes * 0.5) {
|
|
644
|
+
this.delete(key); // An oversized replacement must not leave the old value readable.
|
|
592
645
|
this.opts.logger.debug('SmartMemoryCache: entry too large, skipping', { key, sizeBytes: size });
|
|
593
|
-
return;
|
|
646
|
+
return false;
|
|
594
647
|
}
|
|
595
648
|
|
|
596
649
|
// Single Map.get replaces Map.has + _delete's Map.get (saves one lookup on overwrite).
|
|
@@ -623,10 +676,13 @@ export class SmartMemoryCache {
|
|
|
623
676
|
ttlMs,
|
|
624
677
|
delta,
|
|
625
678
|
setAt: setAt ?? now,
|
|
679
|
+
revision,
|
|
626
680
|
tagVersions,
|
|
681
|
+
tags,
|
|
682
|
+
dependsOn,
|
|
627
683
|
});
|
|
628
684
|
}
|
|
629
|
-
return;
|
|
685
|
+
return false;
|
|
630
686
|
} else if (decision.candidateKey) {
|
|
631
687
|
// An older window candidate was rejected to make room for key
|
|
632
688
|
const candEntry = this.cache.get(decision.candidateKey);
|
|
@@ -644,21 +700,28 @@ export class SmartMemoryCache {
|
|
|
644
700
|
this._delete(decision.evictKey, 'capacity');
|
|
645
701
|
}
|
|
646
702
|
|
|
647
|
-
//
|
|
703
|
+
// Count and byte limits apply to TinyLFU too, including category quotas.
|
|
648
704
|
const catSz = this.categorySize.get(cat) ?? 0;
|
|
649
|
-
if (
|
|
705
|
+
if ((this.categoryCount.get(cat) ?? 0) >= lim.maxEntries || this.cache.size >= this.opts.maxEntries ||
|
|
706
|
+
catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
|
|
650
707
|
this.ensureCapacity(cat, size);
|
|
651
708
|
}
|
|
652
709
|
} else {
|
|
653
710
|
this.ensureCapacity(cat, size);
|
|
654
711
|
}
|
|
655
712
|
|
|
713
|
+
if (this.cache.size >= this.opts.maxEntries || (this.categoryCount.get(cat) ?? 0) >= lim.maxEntries ||
|
|
714
|
+
this.totalSize + size > this.opts.maxBytes || (this.categorySize.get(cat) ?? 0) + size > lim.maxSizeBytes) {
|
|
715
|
+
this.wtinyPolicy?.onDelete(key);
|
|
716
|
+
return false;
|
|
717
|
+
}
|
|
718
|
+
|
|
656
719
|
const now = Date.now();
|
|
657
720
|
// Only cache the live object for small entries — large entries would store the packed
|
|
658
721
|
// buffer AND a potentially much-larger deserialized object simultaneously (double-heap).
|
|
659
722
|
// For large entries, get() falls back to the unpack() path transparently.
|
|
660
723
|
const liveValue = size <= LARGE_VALUE_BYTES ? data : undefined;
|
|
661
|
-
this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: setAt ?? now, tagVersions });
|
|
724
|
+
this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: setAt ?? now, revision, tagVersions, tags, dependsOn });
|
|
662
725
|
// Only add new keys to the bloom — overwrites already have their bits set.
|
|
663
726
|
// Re-adding inflates the insertions counter, delaying trigger-2 phantom detection.
|
|
664
727
|
if (!existingEntry) this.bloom.add(key);
|
|
@@ -669,6 +732,7 @@ export class SmartMemoryCache {
|
|
|
669
732
|
let ks = this.categoryKeys.get(cat);
|
|
670
733
|
if (!ks) { ks = new Set(); this.categoryKeys.set(cat, ks); }
|
|
671
734
|
ks.add(key);
|
|
735
|
+
return true;
|
|
672
736
|
}
|
|
673
737
|
|
|
674
738
|
delete(key: string): boolean {
|
|
@@ -688,7 +752,7 @@ export class SmartMemoryCache {
|
|
|
688
752
|
// the Set during the subsequent iteration are safe.
|
|
689
753
|
if (pattern.endsWith('*') && pattern.indexOf('*') === pattern.length - 1) {
|
|
690
754
|
const prefix = pattern.slice(0, -1);
|
|
691
|
-
const catKeys = this.categoryKeys.get(prefix);
|
|
755
|
+
const catKeys = this.categoryKeys.get(prefix.slice(this.opts.keyPrefixLength ?? 0));
|
|
692
756
|
if (catKeys !== undefined) return Array.from(catKeys);
|
|
693
757
|
}
|
|
694
758
|
|
|
@@ -838,7 +902,7 @@ export class SmartMemoryCache {
|
|
|
838
902
|
}
|
|
839
903
|
|
|
840
904
|
/**
|
|
841
|
-
* Evict all
|
|
905
|
+
* Evict all L1 entries that were written before `cutoffMs`, at every priority.
|
|
842
906
|
*
|
|
843
907
|
* Called by the backplane staleness fence when the Pub/Sub subscriber
|
|
844
908
|
* reconnects after a disconnect gap that exceeded `backplaneMaxStalenessMs`.
|
|
@@ -858,8 +922,6 @@ export class SmartMemoryCache {
|
|
|
858
922
|
let evicted = 0;
|
|
859
923
|
for (const [key, entry] of this.cache) {
|
|
860
924
|
// Never evict live CRITICAL entries — auth tokens, active sessions, etc.
|
|
861
|
-
if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > Date.now()) continue;
|
|
862
|
-
|
|
863
925
|
// Prefer the explicit setAt timestamp; fall back to approximation for older entries.
|
|
864
926
|
const setAt = entry.setAt ?? (entry.ttlMs != null ? entry.expiresAt - entry.ttlMs : 0);
|
|
865
927
|
|
|
@@ -877,8 +939,7 @@ export class SmartMemoryCache {
|
|
|
877
939
|
|
|
878
940
|
/**
|
|
879
941
|
* Delete a key only if its write timestamp (`setAt`) is <= `cutoffMs`.
|
|
880
|
-
*
|
|
881
|
-
* guaranteeing that a newer value written by a concurrent revalidation is never wiped out.
|
|
942
|
+
* This is a time-based eviction policy; use deleteIfRevision for write identity.
|
|
882
943
|
*/
|
|
883
944
|
deleteIfSetBefore(key: string, cutoffMs: number): boolean {
|
|
884
945
|
const entry = this.cache.get(key);
|
|
@@ -892,6 +953,11 @@ export class SmartMemoryCache {
|
|
|
892
953
|
return false;
|
|
893
954
|
}
|
|
894
955
|
|
|
956
|
+
/** Remove exactly the observed write, even when another write shares its timestamp. */
|
|
957
|
+
deleteIfRevision(key: string, revision: string): boolean {
|
|
958
|
+
if (!isWriteRevision(revision) || this.cache.get(key)?.revision !== revision) return false;
|
|
959
|
+
return this.delete(key);
|
|
960
|
+
}
|
|
895
961
|
|
|
896
962
|
|
|
897
963
|
exportEntries(forbiddenPrefixes: readonly string[]): Array<{ key: string; entry: SmartCacheEntry }> {
|
|
@@ -901,7 +967,8 @@ export class SmartMemoryCache {
|
|
|
901
967
|
if (entry.expiresAt <= now) continue;
|
|
902
968
|
if (entry.priority === 4 /* CRITICAL */) continue;
|
|
903
969
|
if (forbiddenPrefixes.some(p => key.startsWith(p))) continue;
|
|
904
|
-
|
|
970
|
+
const { value: _value, ...stored } = entry;
|
|
971
|
+
out.push({ key, entry: { ...stored } });
|
|
905
972
|
}
|
|
906
973
|
return out;
|
|
907
974
|
}
|
|
@@ -909,24 +976,31 @@ export class SmartMemoryCache {
|
|
|
909
976
|
importEntries(entries: Array<{ key: string; entry: SmartCacheEntry }>, forbiddenPrefixes: readonly string[]): number {
|
|
910
977
|
const now = Date.now();
|
|
911
978
|
let loaded = 0;
|
|
912
|
-
for (const
|
|
913
|
-
if (
|
|
979
|
+
for (const item of entries) {
|
|
980
|
+
if (!item || typeof item.key !== 'string' || !item.entry) continue;
|
|
981
|
+
const { key, entry } = item;
|
|
982
|
+
if (entry.revision !== undefined && !isWriteRevision(entry.revision)) continue;
|
|
983
|
+
if (!Number.isFinite(entry.expiresAt) || entry.expiresAt <= now) continue;
|
|
914
984
|
if (forbiddenPrefixes.some(p => key.startsWith(p))) continue;
|
|
915
985
|
if (this.cache.has(key)) continue;
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
986
|
+
try {
|
|
987
|
+
const rawData = entry.data;
|
|
988
|
+
const data = !entry.isCompressed
|
|
989
|
+
? this.codec.encode(JSON.parse(rawData as unknown as string))
|
|
990
|
+
: rawData instanceof Uint8Array ? Buffer.from(rawData) : null;
|
|
991
|
+
if (!data) continue;
|
|
992
|
+
const value = data.length <= LARGE_VALUE_BYTES ? this.codec.decode(data) : undefined;
|
|
993
|
+
if (this.storePacked(key, data, value, entry.expiresAt - now, entry.priority, entry.staleAt,
|
|
994
|
+
entry.delta, entry.tagVersions, entry.setAt, entry.tags, entry.dependsOn, entry.revision)) {
|
|
995
|
+
const restored = this.cache.get(key)!;
|
|
996
|
+
restored.expiresAt = entry.expiresAt;
|
|
997
|
+
restored.ttlMs = entry.ttlMs ?? entry.expiresAt - now;
|
|
998
|
+
restored.hits = Number.isFinite(entry.hits) ? Math.max(1, entry.hits) : 1;
|
|
999
|
+
restored.lastAccess = Number.isFinite(entry.lastAccess) ? entry.lastAccess : now;
|
|
1000
|
+
loaded++;
|
|
1001
|
+
}
|
|
1002
|
+
} catch { /* One corrupt snapshot entry must not discard the healthy entries. */ }
|
|
928
1003
|
}
|
|
929
|
-
this.recalculateStats();
|
|
930
1004
|
return loaded;
|
|
931
1005
|
}
|
|
932
1006
|
|
|
@@ -1019,6 +1093,7 @@ export class SmartMemoryCache {
|
|
|
1019
1093
|
bloom: {
|
|
1020
1094
|
checks: this.bloomChecks,
|
|
1021
1095
|
falsePositives: this.bloomFalsePos,
|
|
1096
|
+
absentChecks: this.bloomAbsentChecks,
|
|
1022
1097
|
},
|
|
1023
1098
|
compression: {
|
|
1024
1099
|
compressed: this.compressions,
|
|
@@ -1071,11 +1146,13 @@ export class SmartMemoryCache {
|
|
|
1071
1146
|
* Add additional milliseconds to a key's existing expiry (for stale-if-error).
|
|
1072
1147
|
* Returns `false` if the key is absent or already expired.
|
|
1073
1148
|
*/
|
|
1074
|
-
bumpExpiry(key: string, additionalMs: number): boolean {
|
|
1149
|
+
bumpExpiry(key: string, additionalMs: number, maximumExpiry = Infinity): boolean {
|
|
1075
1150
|
const entry = this.cache.get(key);
|
|
1076
1151
|
if (!entry) return false;
|
|
1077
1152
|
if (entry.expiresAt <= Date.now()) return false;
|
|
1078
|
-
entry.expiresAt
|
|
1153
|
+
const next = Math.min(entry.expiresAt + additionalMs, maximumExpiry);
|
|
1154
|
+
if (next <= entry.expiresAt) return false;
|
|
1155
|
+
entry.expiresAt = next;
|
|
1079
1156
|
return true;
|
|
1080
1157
|
}
|
|
1081
1158
|
|