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

server.ts

211 lines8.8 KB

1import {
2 DEFAULT_SERVER_SETTINGS,
3 type EnvironmentId,
4 type EnvironmentTheme,
5 type ServerConfig,
6 type ServerConfigStreamEvent,
7 type ServerLifecycleLegacyThreadMigrationPayload,
8 type ServerLifecycleWelcomePayload,
9 type ServerProvider,
10 type ServerSettings,
11} from "@t3tools/contracts";
12import {
13 AVAILABLE_CONNECTION_STATE,
14 presentConnectionState,
15 type EnvironmentPresentation,
16} from "@t3tools/client-runtime/connection";
17import { createServerEnvironmentAtoms } from "@t3tools/client-runtime/state/server";
18import { createOutdatedServerUpdateCommand } from "@t3tools/client-runtime/state/outdatedServerUpdate";
19import { createEnvironmentServerConfigsAtom } from "@t3tools/client-runtime/state/shell";
20import { mergeWithDefaultKeybindings } from "@t3tools/shared/keybindings";
21import * as Option from "effect/Option";
22import { AsyncResult, Atom } from "effect/reactivity";
23​
24import { isConnectedWithConfig } from "../components/settings/scopedSettings";
25import { environmentCatalog } from "../connection/catalog";
26import { connectionAtomRuntime } from "../connection/runtime";
27import { environmentAtomList } from "./environmentAtomList";
28import { primaryEnvironmentIdAtom, localEnvironmentIdAtom } from "./primaryEnvironment";
29import { environmentSession } from "./session";
30import { reuseProvidersIgnoringCheckedAt } from "./serverProviders.logic";
31​
32// Subscribe to every environment's themes; primary can change without reconnecting or updating the subscription.
33export const serverEnvironment = createServerEnvironmentAtoms(connectionAtomRuntime, {
34 initialConfigValueAtom: environmentSession.initialConfigValueAtom,
35 environmentThemes: true,
36 usageLimitSources: true,
37 hostPressure: 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​
56export const EMPTY_SERVER_PROVIDERS: ReadonlyArray<ServerProvider> = [];
57const EMPTY_PRIMARY_SERVER_STATE: PrimaryServerState = {
58 config: null,
59 latestEvent: null,
60 welcome: null,
61};
62​
63const primaryServerStateAtom = Atom.make((get): PrimaryServerState => {
64 const environmentId = get(primaryEnvironmentIdAtom);
65 if (environmentId === null) {
66 return EMPTY_PRIMARY_SERVER_STATE;
67 }
68​
69 const target = { environmentId, input: {} };
70 const configProjection = AsyncResult.getOrElse(
71 get(serverEnvironment.configProjection(target)),
72 () => null,
73 );
74 const welcome = AsyncResult.getOrElse(get(serverEnvironment.welcome(target)), () => null);
75​
76 return {
77 config: get(serverEnvironment.configValueAtom(environmentId)),
78 // A cached snapshot can carry keybinding issues the user fixed while the app was closed.
79 latestEvent: configProjection?.source === "live" ? 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​
88// The config cache can outlive the session and predate an opt-out.
89export const primaryRelayTracingAllowedAtom = Atom.make((get): boolean | null => {
90 const environmentId = get(primaryEnvironmentIdAtom);
91 const config =
92 environmentId === null ? null : get(environmentSession.initialConfigValueAtom(environmentId));
93 return config === null ? null : config.observability.relayTracingAllowed !== false;
94}).pipe(Atom.withLabel("web-primary-relay-tracing-allowed"));
95​
96export const primaryServerConfigEventAtom = Atom.make(
97 (get): ServerConfigStreamEvent | null => get(primaryServerStateAtom).latestEvent,
98).pipe(Atom.withLabel("web-primary-server-config-event"));
99​
100export const primaryServerWelcomeAtom = Atom.make(
101 (get): ServerLifecycleWelcomePayload | null => get(primaryServerStateAtom).welcome,
102).pipe(Atom.withLabel("web-primary-server-welcome"));
103​
104export const primaryServerLegacyThreadMigrationAtom = Atom.make(
105 (get): ServerLifecycleLegacyThreadMigrationPayload | null => {
106 const environmentId = get(primaryEnvironmentIdAtom);
107 if (environmentId === null) {
108 return null;
109 }
110 return AsyncResult.getOrElse(
111 get(serverEnvironment.legacyThreadMigration({ environmentId, input: {} })),
112 () => null,
113 );
114 },
115).pipe(Atom.withLabel("web-primary-server-legacy-thread-migration"));
116​
117export const primaryServerSettingsAtom = Atom.make(
118 (get): ServerSettings => get(primaryServerConfigAtom)?.settings ?? DEFAULT_SERVER_SETTINGS,
119).pipe(Atom.withLabel("web-primary-server-settings"));
120​
121export const primaryServerProvidersAtom = Atom.make(
122 (get): ReadonlyArray<ServerProvider> =>
123 get(primaryServerConfigAtom)?.providers ?? EMPTY_SERVER_PROVIDERS,
124).pipe(Atom.withLabel("web-primary-server-providers"));
125​
126/** Without a primary, global shortcuts follow unscoped Settings. */
127export function createShortcutKeybindingsAtom(input: {
128 readonly primaryEnvironmentIdAtom: Atom.Atom<EnvironmentId | null>;
129 readonly primaryConfigAtom: Atom.Atom<ServerConfig | null>;
130 readonly environmentsAtom: Atom.Atom<
131 ReadonlyMap<EnvironmentId, Pick<EnvironmentPresentation, "connection" | "serverConfig">>
132 >;
133}) {
134 // Selected before merging, so unrelated config updates keep the merged array.
135 const customAtom = Atom.make((get) => {
136 if (get(input.primaryEnvironmentIdAtom) !== null) {
137 // A primary stays authoritative while its config loads.
138 return get(input.primaryConfigAtom)?.keybindings ?? null;
139 }
140 const environments = [...get(input.environmentsAtom).values()];
141 return environments.find(isConnectedWithConfig)?.serverConfig?.keybindings ?? null;
142 });
143 return Atom.make((get): ServerConfig["keybindings"] =>
144 mergeWithDefaultKeybindings(get(customAtom) ?? []),
145 );
147​
148// Settings' presentations import this module; mirror their catalog order and
149// connection presentation here to avoid a cycle.
150const environmentConnectionsAtom = Atom.make((get) => {
151 const environments = new Map<
152 EnvironmentId,
153 Pick<EnvironmentPresentation, "connection" | "serverConfig">
154 >();
155 for (const [environmentId, entry] of get(environmentCatalog.catalogValueAtom).entries) {
156 const state = AsyncResult.getOrElse(
157 get(environmentCatalog.stateAtom(environmentId)),
158 () => AVAILABLE_CONNECTION_STATE,
159 );
160 environments.set(environmentId, {
161 connection:
162 entry.unsupportedReason === undefined
163 ? presentConnectionState(state)
164 : { phase: "unsupported", error: entry.unsupportedReason, traceId: null },
165 serverConfig: get(serverEnvironment.configValueAtom(environmentId)),
166 });
167 }
168 return environments;
169});
170​
171export const primaryServerKeybindingsAtom = createShortcutKeybindingsAtom({
172 primaryEnvironmentIdAtom,
173 primaryConfigAtom: primaryServerConfigAtom,
174 environmentsAtom: environmentConnectionsAtom,
175}).pipe(Atom.withLabel("web-primary-server-keybindings"));
176​
177const EMPTY_ENVIRONMENT_THEMES: ReadonlyArray<EnvironmentTheme> = [];
178​
179const themeServerConfigAtom = Atom.make((get): ServerConfig | null => {
180 const environmentId = get(localEnvironmentIdAtom);
181 return environmentId === null ? null : get(serverEnvironment.configValueAtom(environmentId));
182}).pipe(Atom.withLabel("web-theme-server-config"));
183​
184/**
185 * Null until the theme environment says what it publishes. Cached configs and
186 * snapshots never carry themes, so a capable server has none until its theme
187 * event lands.
188 */
189export const themeServerEnvironmentThemesAtom = Atom.make(
190 (get): ReadonlyArray<EnvironmentTheme> | null => {
191 const config = get(themeServerConfigAtom);
192 if (config === null) return null;
193 if (config.environmentThemes !== undefined) return config.environmentThemes;
194 return config.environment.capabilities.environmentThemes === true
195 ? null
196 : EMPTY_ENVIRONMENT_THEMES;
197 },
198).pipe(Atom.withLabel("web-theme-server-environment-themes"));
199​
200export const themeServerSettingsAtom = Atom.make(
201 (get): ServerSettings => get(themeServerConfigAtom)?.settings ?? DEFAULT_SERVER_SETTINGS,
202).pipe(Atom.withLabel("web-theme-server-settings"));
203​
204export const providersIgnoringCheckedAtAtom = Atom.family((environmentId: EnvironmentId) =>
205 Atom.make((get): ReadonlyArray<ServerProvider> =>
206 reuseProvidersIgnoringCheckedAt(
207 Option.getOrNull(get.self<ReadonlyArray<ServerProvider>>()),
208 get(serverEnvironment.providersValueAtom(environmentId)) ?? EMPTY_SERVER_PROVIDERS,
209 ),
210 ).pipe(Atom.withLabel(`web-providers-ignoring-checked-at:${environmentId}`)),
211);