MCPcopy Create free account
hub / github.com/agegr/pi-web / loadModelsWithCache

Function loadModelsWithCache

lib/models-cache.ts:40–75  ·  view source on GitHub ↗
(cwd: string, loader: () => Promise<ModelsData>)

Source from the content-addressed store, hash-verified

38}
39
40export function loadModelsWithCache(cwd: string, loader: () => Promise<ModelsData>): Promise<ModelsData> {
41 const state = getModelsCacheState();
42 const cached = state.entries.get(cwd);
43 if (cached) {
44 if (cached.expiresAt > Date.now()) return Promise.resolve(cached.data);
45 state.entries.delete(cwd);
46 }
47
48 const existingLoad = state.inFlight.get(cwd);
49 if (existingLoad) return existingLoad;
50
51 const generation = state.generation;
52 const loadPromise: Promise<ModelsData> = Promise.resolve()
53 .then(loader)
54 .then((data) => {
55 if (state.generation === generation && state.inFlight.get(cwd) === loadPromise) {
56 const now = Date.now();
57 for (const [key, entry] of state.entries) {
58 if (entry.expiresAt <= now) state.entries.delete(key);
59 }
60 while (state.entries.size >= MAX_MODELS_CACHE_ENTRIES) {
61 const oldestKey = state.entries.keys().next().value;
62 if (oldestKey === undefined) break;
63 state.entries.delete(oldestKey);
64 }
65 state.entries.set(cwd, { data, expiresAt: now + MODELS_CACHE_TTL_MS });
66 }
67 return data;
68 })
69 .finally(() => {
70 if (state.inFlight.get(cwd) === loadPromise) state.inFlight.delete(cwd);
71 });
72
73 state.inFlight.set(cwd, loadPromise);
74 return loadPromise;
75}

Callers 2

GETFunction · 0.90

Calls 1

getModelsCacheStateFunction · 0.85

Tested by

no test coverage detected