forked from Lilly-Protocol/agentlily-runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime-state.ts
More file actions
60 lines (50 loc) · 1.56 KB
/
Copy pathruntime-state.ts
File metadata and controls
60 lines (50 loc) · 1.56 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
export interface RuntimeStateStore {
put(key: string, value: unknown): Promise<void>;
get<TValue>(key: string): Promise<TValue | undefined>;
delete?(key: string): Promise<boolean>;
has?(key: string): Promise<boolean>;
clear?(): Promise<void>;
size?(): Promise<number>;
keys?(): Promise<string[]>;
}
export interface InMemoryRuntimeStateStoreOptions {
maxEntries?: number;
}
export class InMemoryRuntimeStateStore implements RuntimeStateStore {
private readonly store = new Map<string, unknown>();
private readonly maxEntries: number;
public constructor(options: InMemoryRuntimeStateStoreOptions = {}) {
this.maxEntries = options.maxEntries ?? 10_000;
}
public async put(key: string, value: unknown): Promise<void> {
if (
this.maxEntries > 0 &&
!this.store.has(key) &&
this.store.size >= this.maxEntries
) {
const oldestKey = this.store.keys().next().value;
if (oldestKey !== undefined) {
this.store.delete(oldestKey);
}
}
this.store.set(key, value);
}
public async get<TValue>(key: string): Promise<TValue | undefined> {
return this.store.get(key) as TValue | undefined;
}
public async delete(key: string): Promise<boolean> {
return this.store.delete(key);
}
public async has(key: string): Promise<boolean> {
return this.store.has(key);
}
public async clear(): Promise<void> {
this.store.clear();
}
public async size(): Promise<number> {
return this.store.size;
}
public async keys(): Promise<string[]> {
return Array.from(this.store.keys());
}
}