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

server.ts

197 lines8.1 KB

1import {
2 DEFAULT_SERVER_SETTINGS,
3 type EditorId,
4 type EnvironmentId,
5 type EnvironmentTheme,
6 type ServerConfig,
7 type ServerConfigStreamEvent,
8 type ServerLifecycleLegacyThreadMigrationPayload,
9 type ServerLifecycleWelcomePayload,
10 type ServerProvider,
11 type ServerSettings,
12} from "@t3tools/contracts";
13import {
14 AVAILABLE_CONNECTION_STATE,
15 presentConnectionState,
16 type EnvironmentPresentation,
17} from "@t3tools/client-runtime/connection";
18import { createServerEnvironmentAtoms } from "@t3tools/client-runtime/state/server";
19import { createOutdatedServerUpdateCommand } from "@t3tools/client-runtime/state/outdatedServerUpdate";
20import { createEnvironmentServerConfigsAtom } from "@t3tools/client-runtime/state/shell";
21import { mergeWithDefaultKeybindings } from "@t3tools/shared/keybindings";
22import * as Option from "effect/Option";
23import { AsyncResult, Atom } from "effect/reactivity";
24​
25import { isConnectedWithConfig } from "../components/settings/scopedSettings";
26import { environmentCatalog } from "../connection/catalog";
27import { connectionAtomRuntime } from "../connection/runtime";
28import { environmentAtomList } from "./environmentAtomList";
29import { primaryEnvironmentIdAtom, themeEnvironmentIdAtom } from "./primaryEnvironment";
30import { environmentSession } from "./session";
31import { reuseProvidersIgnoringCheckedAt } from "./serverProviders.logic";
32​
33// Subscribe to every environment's themes; primary can change without reconnecting or updating the subscription.
34export const serverEnvironment = createServerEnvironmentAtoms(connectionAtomRuntime, {
35 initialConfigValueAtom: environmentSession.initialConfigValueAtom,
36 environmentThemes: true,
37 usageLimitSources: true,
38 usageLimitsCommand: true,
39});
40export const environmentUpdateStatesAtom = environmentAtomList(
41 "web-environment-update-states",
42 serverEnvironment.updateStateAtom,
43);
44export const updateOutdatedServer = createOutdatedServerUpdateCommand(connectionAtomRuntime);
45export const environmentServerConfigsAtom = createEnvironmentServerConfigsAtom({
46 catalogValueAtom: environmentCatalog.catalogValueAtom,
47 serverConfigValueAtom: serverEnvironment.configValueAtom,
48});
49​
50interface PrimaryServerState {
51 readonly config: ServerConfig | null;
52 readonly latestEvent: ServerConfigStreamEvent | null;
53 readonly welcome: ServerLifecycleWelcomePayload | null;
55​
56const EMPTY_AVAILABLE_EDITORS: ReadonlyArray<EditorId> = [];
57export const EMPTY_SERVER_PROVIDERS: ReadonlyArray<ServerProvider> = [];
58const EMPTY_PRIMARY_SERVER_STATE: PrimaryServerState = {
59 config: null,
60 latestEvent: null,
61 welcome: null,
62};
63​
64const primaryServerStateAtom = Atom.make((get): PrimaryServerState => {
65 const environmentId = get(primaryEnvironmentIdAtom);
66 if (environmentId === null) {
67 return EMPTY_PRIMARY_SERVER_STATE;
68 }
69​
70 const target = { environmentId, input: {} };
71 const configProjection = AsyncResult.getOrElse(
72 get(serverEnvironment.configProjection(target)),
73 () => null,
74 );
75 const welcome = AsyncResult.getOrElse(get(serverEnvironment.welcome(target)), () => null);
76​
77 return {
78 config: get(serverEnvironment.configValueAtom(environmentId)),
79 latestEvent: configProjection?.latestEvent ?? null,
80 welcome,
81 };
82}).pipe(Atom.withLabel("web-primary-server-state"));
83​
84export const primaryServerConfigAtom = Atom.make(
85 (get): ServerConfig | null => get(primaryServerStateAtom).config,
86).pipe(Atom.withLabel("web-primary-server-config"));
87​
88export const primaryServerConfigEventAtom = Atom.make(
89 (get): ServerConfigStreamEvent | null => get(primaryServerStateAtom).latestEvent,
90).pipe(Atom.withLabel("web-primary-server-config-event"));
91​
92export const primaryServerWelcomeAtom = Atom.make(
93 (get): ServerLifecycleWelcomePayload | null => get(primaryServerStateAtom).welcome,
94).pipe(Atom.withLabel("web-primary-server-welcome"));
95​
96export const primaryServerLegacyThreadMigrationAtom = Atom.make(
97 (get): ServerLifecycleLegacyThreadMigrationPayload | null => {
98 const environmentId = get(primaryEnvironmentIdAtom);
99 if (environmentId === null) {
100 return null;
101 }
102 return AsyncResult.getOrElse(
103 get(serverEnvironment.legacyThreadMigration({ environmentId, input: {} })),
104 () => null,
105 );
106 },
107).pipe(Atom.withLabel("web-primary-server-legacy-thread-migration"));
108​
109export const primaryServerSettingsAtom = Atom.make(
110 (get): ServerSettings => get(primaryServerConfigAtom)?.settings ?? DEFAULT_SERVER_SETTINGS,
111).pipe(Atom.withLabel("web-primary-server-settings"));
112​
113export const primaryServerProvidersAtom = Atom.make(
114 (get): ReadonlyArray<ServerProvider> =>
115 get(primaryServerConfigAtom)?.providers ?? EMPTY_SERVER_PROVIDERS,
116).pipe(Atom.withLabel("web-primary-server-providers"));
117​
118/** Without a primary, global shortcuts follow unscoped Settings. */
119export function createShortcutKeybindingsAtom(input: {
120 readonly primaryEnvironmentIdAtom: Atom.Atom<EnvironmentId | null>;
121 readonly primaryConfigAtom: Atom.Atom<ServerConfig | null>;
122 readonly environmentsAtom: Atom.Atom<
123 ReadonlyMap<EnvironmentId, Pick<EnvironmentPresentation, "connection" | "serverConfig">>
124 >;
125}) {
126 // Selected before merging, so unrelated config updates keep the merged array.
127 const customAtom = Atom.make((get) => {
128 if (get(input.primaryEnvironmentIdAtom) !== null) {
129 // A primary stays authoritative while its config loads.
130 return get(input.primaryConfigAtom)?.keybindings ?? null;
131 }
132 const environments = [...get(input.environmentsAtom).values()];
133 return environments.find(isConnectedWithConfig)?.serverConfig?.keybindings ?? null;
134 });
135 return Atom.make((get): ServerConfig["keybindings"] =>
136 mergeWithDefaultKeybindings(get(customAtom) ?? []),
137 );
139​
140// Settings' presentations import this module; mirror their catalog order and
141// connection presentation here to avoid a cycle.
142const environmentConnectionsAtom = Atom.make((get) => {
143 const environments = new Map<
144 EnvironmentId,
145 Pick<EnvironmentPresentation, "connection" | "serverConfig">
146 >();
147 for (const [environmentId, entry] of get(environmentCatalog.catalogValueAtom).entries) {
148 const state = AsyncResult.getOrElse(
149 get(environmentCatalog.stateAtom(environmentId)),
150 () => AVAILABLE_CONNECTION_STATE,
151 );
152 environments.set(environmentId, {
153 connection:
154 entry.unsupportedReason === undefined
155 ? presentConnectionState(state)
156 : { phase: "unsupported", error: entry.unsupportedReason, traceId: null },
157 serverConfig: get(serverEnvironment.configValueAtom(environmentId)),
158 });
159 }
160 return environments;
161});
162​
163export const primaryServerKeybindingsAtom = createShortcutKeybindingsAtom({
164 primaryEnvironmentIdAtom,
165 primaryConfigAtom: primaryServerConfigAtom,
166 environmentsAtom: environmentConnectionsAtom,
167}).pipe(Atom.withLabel("web-primary-server-keybindings"));
168​
169export const primaryServerAvailableEditorsAtom = Atom.make(
170 (get): ReadonlyArray<EditorId> =>
171 get(primaryServerConfigAtom)?.availableEditors ?? EMPTY_AVAILABLE_EDITORS,
172).pipe(Atom.withLabel("web-primary-server-available-editors"));
173​
174const EMPTY_ENVIRONMENT_THEMES: ReadonlyArray<EnvironmentTheme> = [];
175​
176const themeServerConfigAtom = Atom.make((get): ServerConfig | null => {
177 const environmentId = get(themeEnvironmentIdAtom);
178 return environmentId === null ? null : get(serverEnvironment.configValueAtom(environmentId));
179}).pipe(Atom.withLabel("web-theme-server-config"));
180​
181export const themeServerEnvironmentThemesAtom = Atom.make(
182 (get): ReadonlyArray<EnvironmentTheme> =>
183 get(themeServerConfigAtom)?.environmentThemes ?? EMPTY_ENVIRONMENT_THEMES,
184).pipe(Atom.withLabel("web-theme-server-environment-themes"));
185​
186export const themeServerSettingsAtom = Atom.make(
187 (get): ServerSettings => get(themeServerConfigAtom)?.settings ?? DEFAULT_SERVER_SETTINGS,
188).pipe(Atom.withLabel("web-theme-server-settings"));
189​
190export const providersIgnoringCheckedAtAtom = Atom.family((environmentId: EnvironmentId) =>
191 Atom.make((get): ReadonlyArray<ServerProvider> =>
192 reuseProvidersIgnoringCheckedAt(
193 Option.getOrNull(get.self<ReadonlyArray<ServerProvider>>()),
194 get(serverEnvironment.providersValueAtom(environmentId)) ?? EMPTY_SERVER_PROVIDERS,
195 ),
196 ).pipe(Atom.withLabel(`web-providers-ignoring-checked-at:${environmentId}`)),
197);