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

serverState.ts

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