Open History to see the last commit
1import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
2import type { EnvironmentId } from "@t3tools/contracts";
3
4import { environmentCatalog } from "../connection/catalog";
5import { isAppActive, subscribeAppState } from "../lib/appState";
6import { appAtomRegistry } from "../state/atom-registry";
7import { environmentPresentations } from "../state/presentation";
8import { serverEnvironment } from "../state/server";
9import { createWidgetRefresher, WIDGET_REFRESH_INTERVAL } from "./subscriptionUsageSnapshot";
10
11/**
12 * App-lifetime worker that keeps provider quotas fresh for the usage widget:
13 * on resume, on every connection change, and on a fixed interval while active.
14 * Each environment is refreshed at most once per interval.
15 */
16export function installSubscriptionUsageRefresh(): () => void {
17 const refresh = createWidgetRefresher((environmentId: EnvironmentId) =>
18 runAtomCommand(
19 appAtomRegistry,
20 serverEnvironment.refreshProviders,
21 { environmentId, input: {} },
22 { label: serverEnvironment.refreshProviders.label, reportFailure: false },
23 ),
24 );
25 const update = () => {
26 if (!isAppActive() || !appAtomRegistry.get(environmentCatalog.catalogValueAtom).isReady) return;
27 const connected = [...appAtomRegistry.get(environmentPresentations.presentationsAtom)]
28 .filter(([, presentation]) => presentation.connection.phase === "connected")
29 .map(([id]) => id);
30 void refresh(connected, Date.now());
31 };
32
33 const unsubscribeCatalog = appAtomRegistry.subscribe(environmentCatalog.catalogValueAtom, update);
34 const unsubscribePresentations = appAtomRegistry.subscribe(
35 environmentPresentations.presentationsAtom,
36 update,
37 { immediate: true },
38 );
39 const unsubscribeAppState = subscribeAppState(update);
40 const timer = setInterval(update, WIDGET_REFRESH_INTERVAL);
41 return () => {
42 unsubscribeCatalog();
43 unsubscribePresentations();
44 unsubscribeAppState();
45 clearInterval(timer);
46 };
47}