Files
nanobot/webui/src/lib/webui-thread-cache.ts
T

63 lines
2.1 KiB
TypeScript
Raw Normal View History

2026-09-12 04:37:37 +08:00
import { MemoryLruCache } from "./memory-lru-cache";
import { parseWebuiThreadPayload } from "./api";
import { readReloadCache, removeReloadCache, writeReloadCache } from "./reload-cache";
2026-09-12 04:37:37 +08:00
import type { WebuiThreadPersistedPayload } from "./types";
/** Bounded canonical replay cache; the most recent snapshot also survives tab reloads. */
2026-09-12 04:37:37 +08:00
export class WebuiThreadCache extends MemoryLruCache<WebuiThreadPersistedPayload> {
private readonly listeners = new Map<string, Set<(body: WebuiThreadPersistedPayload) => void>>();
2026-09-12 04:37:37 +08:00
constructor(
maxBytes = 16 * 1024 * 1024,
maxEntries = 12,
) {
super(maxBytes, maxEntries);
}
override get(key: string): WebuiThreadPersistedPayload | undefined {
const cached = super.get(key);
if (cached) return cached;
const stored = readReloadCache("thread");
if (!stored || typeof stored !== "object" || !("key" in stored)
|| stored.key !== key || !("body" in stored)) return undefined;
try {
const body = parseWebuiThreadPayload(stored.body);
this.set(key, body);
return super.get(key);
} catch {
removeReloadCache("thread");
return undefined;
}
}
override set(key: string, body: WebuiThreadPersistedPayload): void {
super.set(key, body);
if (super.get(key)) writeReloadCache("thread", { key, body });
for (const listener of this.listeners.get(key) ?? []) listener(body);
}
subscribe(key: string, listener: (body: WebuiThreadPersistedPayload) => void): () => void {
const listeners = this.listeners.get(key) ?? new Set();
listeners.add(listener);
this.listeners.set(key, listeners);
return () => {
listeners.delete(listener);
if (listeners.size === 0) this.listeners.delete(key);
};
}
override delete(key: string): void {
super.delete(key);
const stored = readReloadCache("thread");
if (stored && typeof stored === "object" && "key" in stored && stored.key === key) {
removeReloadCache("thread");
}
}
override clear(): void {
super.clear();
removeReloadCache("thread");
}
2026-09-12 04:37:37 +08:00
}
export const webuiThreadCache = new WebuiThreadCache();