Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

serverState.ts

299 lines8.7 KB

1import { useAtomSubscribe, useAtomValue } from "@effect/atom-react";
2import {
3 DEFAULT_SERVER_SETTINGS,
4 type EditorId,
5 type ServerConfig,
6 type ServerConfigStreamEvent,
7 type ServerConfigUpdatedPayload,
8 type ServerLifecycleWelcomePayload,
9 type ServerProvider,
10 type ServerProviderUpdatedPayload,
11 type ServerSettings,
12} from "@workbench/contracts";
13import { Atom } from "effect/unstable/reactivity";
14import { useCallback, useRef } from "react";
15​
16import type { WsRpcClient } from "./wsRpcClient";
17import { appAtomRegistry, resetAppAtomRegistryForTests } from "./atomRegistry";
18​
19export type ServerConfigUpdateSource = ServerConfigStreamEvent["type"];
20​
21export interface ServerConfigUpdatedNotification {
22 readonly id: number;
23 readonly payload: ServerConfigUpdatedPayload;
24 readonly source: ServerConfigUpdateSource;
26​
27type ServerStateClient = Pick<
28 WsRpcClient["server"],
29 "getConfig" | "subscribeConfig" | "subscribeLifecycle"
30>;
31​
32function makeStateAtom<A>(label: string, initialValue: A) {
33 return Atom.make(initialValue).pipe(Atom.keepAlive, Atom.withLabel(label));
35​
36function toServerConfigUpdatedPayload(config: ServerConfig): ServerConfigUpdatedPayload {
37 return {
38 issues: config.issues,
39 providers: config.providers,
40 settings: config.settings,
41 };
43​
44const EMPTY_AVAILABLE_EDITORS: ReadonlyArray<EditorId> = [];
45const EMPTY_KEYBINDINGS: ServerConfig["keybindings"] = [];
46const EMPTY_SERVER_PROVIDERS: ReadonlyArray<ServerProvider> = [];
47​
48const selectAvailableEditors = (config: ServerConfig | null): ReadonlyArray<EditorId> =>
49 config?.availableEditors ?? EMPTY_AVAILABLE_EDITORS;
50const selectKeybindings = (config: ServerConfig | null) => config?.keybindings ?? EMPTY_KEYBINDINGS;
51const selectKeybindingsConfigPath = (config: ServerConfig | null) =>
52 config?.keybindingsConfigPath ?? null;
53const selectObservability = (config: ServerConfig | null) => config?.observability ?? null;
54const selectProviders = (config: ServerConfig | null) =>
55 config?.providers ?? EMPTY_SERVER_PROVIDERS;
56const selectSettings = (config: ServerConfig | null): ServerSettings =>
57 config?.settings ?? DEFAULT_SERVER_SETTINGS;
58​
59export const welcomeAtom = makeStateAtom<ServerLifecycleWelcomePayload | null>(
60 "server-welcome",
61 null,
62);
63export const serverConfigAtom = makeStateAtom<ServerConfig | null>("server-config", null);
64export const serverConfigUpdatedAtom = makeStateAtom<ServerConfigUpdatedNotification | null>(
65 "server-config-updated",
66 null,
67);
68export const providersUpdatedAtom = makeStateAtom<ServerProviderUpdatedPayload | null>(
69 "server-providers-updated",
70 null,
71);
72​
73export function getServerConfig(): ServerConfig | null {
74 return appAtomRegistry.get(serverConfigAtom);
76​
77export function getServerConfigUpdatedNotification(): ServerConfigUpdatedNotification | null {
78 return appAtomRegistry.get(serverConfigUpdatedAtom);
80​
81export function setServerConfigSnapshot(config: ServerConfig): void {
82 resolveServerConfig(config);
83 emitProvidersUpdated({ providers: config.providers });
84 emitServerConfigUpdated(toServerConfigUpdatedPayload(config), "snapshot");
86​
87export function applyServerConfigEvent(event: ServerConfigStreamEvent): void {
88 switch (event.type) {
89 case "snapshot": {
90 setServerConfigSnapshot(event.config);
91 return;
92 }
93 case "keybindingsUpdated": {
94 const latestServerConfig = getServerConfig();
95 if (!latestServerConfig) {
96 return;
97 }
98 const nextConfig = {
99 ...latestServerConfig,
100 issues: event.payload.issues,
101 } satisfies ServerConfig;
102 resolveServerConfig(nextConfig);
103 emitServerConfigUpdated(toServerConfigUpdatedPayload(nextConfig), event.type);
104 return;
105 }
106 case "providerStatuses": {
107 applyProvidersUpdated(event.payload);
108 return;
109 }
110 case "settingsUpdated": {
111 applySettingsUpdated(event.payload.settings);
112 return;
113 }
114 }
116​
117export function applyProvidersUpdated(payload: ServerProviderUpdatedPayload): void {
118 const latestServerConfig = getServerConfig();
119 emitProvidersUpdated(payload);
120​
121 if (!latestServerConfig) {
122 return;
123 }
124​
125 const nextConfig = {
126 ...latestServerConfig,
127 providers: payload.providers,
128 } satisfies ServerConfig;
129 resolveServerConfig(nextConfig);
130 emitServerConfigUpdated(toServerConfigUpdatedPayload(nextConfig), "providerStatuses");
132​
133export function applySettingsUpdated(settings: ServerSettings): void {
134 const latestServerConfig = getServerConfig();
135 if (!latestServerConfig) {
136 return;
137 }
138​
139 const nextConfig = {
140 ...latestServerConfig,
141 settings,
142 } satisfies ServerConfig;
143 resolveServerConfig(nextConfig);
144 emitServerConfigUpdated(toServerConfigUpdatedPayload(nextConfig), "settingsUpdated");
146​
147export function emitWelcome(payload: ServerLifecycleWelcomePayload): void {
148 appAtomRegistry.set(welcomeAtom, payload);
150​
151export function onWelcome(listener: (payload: ServerLifecycleWelcomePayload) => void): () => void {
152 return subscribeLatest(welcomeAtom, listener);
154​
155export function onServerConfigUpdated(
156 listener: (payload: ServerConfigUpdatedPayload, source: ServerConfigUpdateSource) => void,
157): () => void {
158 return subscribeLatest(serverConfigUpdatedAtom, (notification) => {
159 listener(notification.payload, notification.source);
160 });
162​
163export function onProvidersUpdated(
164 listener: (payload: ServerProviderUpdatedPayload) => void,
165): () => void {
166 return subscribeLatest(providersUpdatedAtom, listener);
168​
169export function startServerStateSync(client: ServerStateClient): () => void {
170 let disposed = false;
171 const cleanups = [
172 client.subscribeLifecycle((event) => {
173 if (event.type === "welcome") {
174 emitWelcome(event.payload);
175 }
176 }),
177 client.subscribeConfig((event) => {
178 applyServerConfigEvent(event);
179 }),
180 ];
181​
182 if (getServerConfig() === null) {
183 void client
184 .getConfig()
185 .then((config) => {
186 if (disposed || getServerConfig() !== null) {
187 return;
188 }
189 setServerConfigSnapshot(config);
190 })
191 .catch(() => undefined);
192 }
193​
194 return () => {
195 disposed = true;
196 for (const cleanup of cleanups) {
197 cleanup();
198 }
199 };
201​
202export function resetServerStateForTests() {
203 resetAppAtomRegistryForTests();
204 nextServerConfigUpdatedNotificationId = 1;
206​
207let nextServerConfigUpdatedNotificationId = 1;
208​
209function resolveServerConfig(config: ServerConfig): void {
210 appAtomRegistry.set(serverConfigAtom, config);
212​
213function emitProvidersUpdated(payload: ServerProviderUpdatedPayload): void {
214 appAtomRegistry.set(providersUpdatedAtom, payload);
216​
217function emitServerConfigUpdated(
218 payload: ServerConfigUpdatedPayload,
219 source: ServerConfigUpdateSource,
220): void {
221 appAtomRegistry.set(serverConfigUpdatedAtom, {
222 id: nextServerConfigUpdatedNotificationId++,
223 payload,
224 source,
225 });
227​
228function subscribeLatest<A>(
229 atom: Atom.Atom<A | null>,
230 listener: (value: NonNullable<A>) => void,
231): () => void {
232 return appAtomRegistry.subscribe(
233 atom,
234 (value) => {
235 if (value === null) {
236 return;
237 }
238 listener(value as NonNullable<A>);
239 },
240 { immediate: true },
241 );
243​
244function useLatestAtomSubscription<A>(
245 atom: Atom.Atom<A | null>,
246 listener: (value: NonNullable<A>) => void,
247): void {
248 const listenerRef = useRef(listener);
249 listenerRef.current = listener;
250​
251 const stableListener = useCallback((value: A | null) => {
252 if (value === null) {
253 return;
254 }
255 listenerRef.current(value as NonNullable<A>);
256 }, []);
257​
258 useAtomSubscribe(atom, stableListener, { immediate: true });
260​
261export function useServerConfig(): ServerConfig | null {
262 return useAtomValue(serverConfigAtom);
264​
265export function useServerSettings(): ServerSettings {
266 return useAtomValue(serverConfigAtom, selectSettings);
268​
269export function useServerProviders(): ReadonlyArray<ServerProvider> {
270 return useAtomValue(serverConfigAtom, selectProviders);
272​
273export function useServerKeybindings(): ServerConfig["keybindings"] {
274 return useAtomValue(serverConfigAtom, selectKeybindings);
276​
277export function useServerAvailableEditors(): ReadonlyArray<EditorId> {
278 return useAtomValue(serverConfigAtom, selectAvailableEditors);
280​
281export function useServerKeybindingsConfigPath(): string | null {
282 return useAtomValue(serverConfigAtom, selectKeybindingsConfigPath);
284​
285export function useServerObservability(): ServerConfig["observability"] | null {
286 return useAtomValue(serverConfigAtom, selectObservability);
288​
289export function useServerWelcomeSubscription(
290 listener: (payload: ServerLifecycleWelcomePayload) => void,
291): void {
292 useLatestAtomSubscription(welcomeAtom, listener);
294​
295export function useServerConfigUpdatedSubscription(
296 listener: (notification: ServerConfigUpdatedNotification) => void,
297): void {
298 useLatestAtomSubscription(serverConfigUpdatedAtom, listener);