forked from Vero-protocol/vero-core-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchain-state-cache.ts
More file actions
109 lines (96 loc) · 2.84 KB
/
Copy pathchain-state-cache.ts
File metadata and controls
109 lines (96 loc) · 2.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import { RpcClient } from "./rpc-client";
export interface SwrOptions {
staleTimeMs?: number;
}
interface CacheItem<T> {
data: T;
updatedAt: number;
isRevalidating: boolean;
}
/**
* chain-state-cache.ts — Stale-While-Revalidate (SWR) caching for chain state.
*
* Implements SWR caching to solve slow load times when fetching chain state.
* Returns stale data immediately while fetching fresh data in the background.
* Cache is bounded by maxEntries via LRU eviction to prevent unbounded growth.
*/
export class ChainStateCache {
private cache = new Map<string, CacheItem<any>>();
constructor(
private readonly rpc: RpcClient,
private readonly defaultStaleTimeMs: number = 2000,
private readonly maxEntries: number = Infinity
) {}
private touch(key: string): void {
if (this.cache.has(key)) {
const item = this.cache.get(key)!;
this.cache.delete(key);
this.cache.set(key, item);
}
}
private evictIfNeeded(): void {
while (this.cache.size > this.maxEntries) {
const lruKey = this.cache.keys().next().value;
if (lruKey !== undefined) {
this.cache.delete(lruKey);
}
}
}
/**
* Fetches data using SWR strategy.
* @param key Unique cache key
* @param fetcher Async function to fetch fresh data
* @param options SWR options
*/
async getSwr<T>(
key: string,
fetcher: (rpc: RpcClient) => Promise<T>,
options?: SwrOptions
): Promise<T> {
const staleTimeMs = options?.staleTimeMs ?? this.defaultStaleTimeMs;
const now = Date.now();
const item = this.cache.get(key) as CacheItem<T> | undefined;
if (item) {
this.touch(key);
const isStale = now - item.updatedAt > staleTimeMs;
if (isStale && !item.isRevalidating) {
item.isRevalidating = true;
// Background revalidation (fire and forget)
this.revalidate(key, fetcher).catch(err => {
console.error(`[ChainStateCache] SWR revalidation failed for ${key}:`, err);
});
}
return item.data;
}
// Cache miss, fetch synchronously
const data = await fetcher(this.rpc);
this.cache.set(key, { data, updatedAt: Date.now(), isRevalidating: false });
this.evictIfNeeded();
return data;
}
private async revalidate<T>(
key: string,
fetcher: (rpc: RpcClient) => Promise<T>
): Promise<void> {
try {
const data = await fetcher(this.rpc);
this.cache.set(key, { data, updatedAt: Date.now(), isRevalidating: false });
} catch (error) {
const item = this.cache.get(key);
if (item) {
item.isRevalidating = false; // Reset flag so it can try again
}
throw error;
}
}
/**
* Manually invalidate a cache key
*/
invalidate(key: string): void {
this.cache.delete(key);
}
/** Evict all entries */
clear(): void {
this.cache.clear();
}
}