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

server.ts

186 lines7.7 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 presentEnvironmentConnection,
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 } 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 = Option.getOrNull(
72 AsyncResult.value(get(serverEnvironment.configProjection(target))),
73 );
74 const welcome = Option.getOrNull(AsyncResult.value(get(serverEnvironment.welcome(target))));
75​
76 return {
77 config: get(serverEnvironment.configValueAtom(environmentId)),
78 latestEvent: configProjection?.latestEvent ?? null,
79 welcome,
80 };
81}).pipe(Atom.withLabel("web-primary-server-state"));
82​
83export const primaryServerConfigAtom = Atom.make(
84 (get): ServerConfig | null => get(primaryServerStateAtom).config,
85).pipe(Atom.withLabel("web-primary-server-config"));
86​
87export const primaryServerConfigEventAtom = Atom.make(
88 (get): ServerConfigStreamEvent | null => get(primaryServerStateAtom).latestEvent,
89).pipe(Atom.withLabel("web-primary-server-config-event"));
90​
91export const primaryServerWelcomeAtom = Atom.make(
92 (get): ServerLifecycleWelcomePayload | null => get(primaryServerStateAtom).welcome,
93).pipe(Atom.withLabel("web-primary-server-welcome"));
94​
95export const primaryServerLegacyThreadMigrationAtom = Atom.make(
96 (get): ServerLifecycleLegacyThreadMigrationPayload | null => {
97 const environmentId = get(primaryEnvironmentIdAtom);
98 if (environmentId === null) {
99 return null;
100 }
101 return Option.getOrNull(
102 AsyncResult.value(get(serverEnvironment.legacyThreadMigration({ environmentId, input: {} }))),
103 );
104 },
105).pipe(Atom.withLabel("web-primary-server-legacy-thread-migration"));
106​
107export const primaryServerSettingsAtom = Atom.make(
108 (get): ServerSettings => get(primaryServerConfigAtom)?.settings ?? DEFAULT_SERVER_SETTINGS,
109).pipe(Atom.withLabel("web-primary-server-settings"));
110​
111export const primaryServerProvidersAtom = Atom.make(
112 (get): ReadonlyArray<ServerProvider> =>
113 get(primaryServerConfigAtom)?.providers ?? EMPTY_SERVER_PROVIDERS,
114).pipe(Atom.withLabel("web-primary-server-providers"));
115​
116/** Without a primary, global shortcuts follow unscoped Settings. */
117export function createShortcutKeybindingsAtom(input: {
118 readonly primaryEnvironmentIdAtom: Atom.Atom<EnvironmentId | null>;
119 readonly primaryConfigAtom: Atom.Atom<ServerConfig | null>;
120 readonly environmentsAtom: Atom.Atom<
121 ReadonlyMap<EnvironmentId, Pick<EnvironmentPresentation, "connection" | "serverConfig">>
122 >;
123}) {
124 // Selected before merging, so unrelated config updates keep the merged array.
125 const customAtom = Atom.make((get) => {
126 if (get(input.primaryEnvironmentIdAtom) !== null) {
127 // A primary stays authoritative while its config loads.
128 return get(input.primaryConfigAtom)?.keybindings ?? null;
129 }
130 const environments = [...get(input.environmentsAtom).values()];
131 return environments.find(isConnectedWithConfig)?.serverConfig?.keybindings ?? null;
132 });
133 return Atom.make((get): ServerConfig["keybindings"] =>
134 mergeWithDefaultKeybindings(get(customAtom) ?? []),
135 );
137​
138// Settings' presentations import this module; mirror their catalog order and
139// connection presentation here to avoid a cycle.
140const environmentConnectionsAtom = Atom.make((get) => {
141 const environments = new Map<
142 EnvironmentId,
143 Pick<EnvironmentPresentation, "connection" | "serverConfig">
144 >();
145 for (const [environmentId, entry] of get(environmentCatalog.catalogValueAtom).entries) {
146 const state = Option.getOrElse(
147 AsyncResult.value(get(environmentCatalog.stateAtom(environmentId))),
148 () => AVAILABLE_CONNECTION_STATE,
149 );
150 environments.set(environmentId, {
151 connection:
152 entry.unsupportedReason === undefined
153 ? presentEnvironmentConnection(state)
154 : { phase: "unsupported", error: entry.unsupportedReason, traceId: null },
155 serverConfig: get(serverEnvironment.configValueAtom(environmentId)),
156 });
157 }
158 return environments;
159});
160​
161export const primaryServerKeybindingsAtom = createShortcutKeybindingsAtom({
162 primaryEnvironmentIdAtom,
163 primaryConfigAtom: primaryServerConfigAtom,
164 environmentsAtom: environmentConnectionsAtom,
165}).pipe(Atom.withLabel("web-primary-server-keybindings"));
166​
167export const primaryServerAvailableEditorsAtom = Atom.make(
168 (get): ReadonlyArray<EditorId> =>
169 get(primaryServerConfigAtom)?.availableEditors ?? EMPTY_AVAILABLE_EDITORS,
170).pipe(Atom.withLabel("web-primary-server-available-editors"));
171​
172const EMPTY_ENVIRONMENT_THEMES: ReadonlyArray<EnvironmentTheme> = [];
173​
174export const primaryServerEnvironmentThemesAtom = Atom.make(
175 (get): ReadonlyArray<EnvironmentTheme> =>
176 get(primaryServerConfigAtom)?.environmentThemes ?? EMPTY_ENVIRONMENT_THEMES,
177).pipe(Atom.withLabel("web-primary-server-environment-themes"));
178​
179export const providersIgnoringCheckedAtAtom = Atom.family((environmentId: EnvironmentId) =>
180 Atom.make((get): ReadonlyArray<ServerProvider> =>
181 reuseProvidersIgnoringCheckedAt(
182 Option.getOrNull(get.self<ReadonlyArray<ServerProvider>>()),
183 get(serverEnvironment.providersValueAtom(environmentId)) ?? EMPTY_SERVER_PROVIDERS,
184 ),
185 ).pipe(Atom.withLabel(`web-providers-ignoring-checked-at:${environmentId}`)),
186);