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

server.ts

224 lines8.1 KB

1import {
2 type EnvironmentId,
3 type ServerConfig,
4 type ServerConfigStreamEvent,
5 type ServerLifecycleWelcomePayload,
6 WS_METHODS,
7} from "@t3tools/contracts";
8import * as Option from "effect/Option";
9import * as Stream from "effect/Stream";
10import { AsyncResult, Atom } from "effect/unstable/reactivity";
11​
12import {
13 createAtomCommandScheduler,
14 createEnvironmentRpcCommand,
15 createEnvironmentRpcQueryAtomFamily,
16 createEnvironmentRpcSubscriptionAtomFamily,
17} from "./runtime.ts";
18import type { EnvironmentRegistry } from "../connection/registry.ts";
19​
20export interface ServerConfigProjection {
21 readonly config: ServerConfig;
22 readonly latestEvent: ServerConfigStreamEvent;
24​
25export function applyServerConfigProjection(
26 current: Option.Option<ServerConfigProjection>,
27 event: ServerConfigStreamEvent,
28): Option.Option<ServerConfigProjection> {
29 switch (event.type) {
30 case "snapshot":
31 return Option.some({
32 config: event.config,
33 latestEvent: event,
34 });
35 case "keybindingsUpdated":
36 return Option.map(current, (projection) => ({
37 config: {
38 ...projection.config,
39 keybindings: event.payload.keybindings,
40 issues: event.payload.issues,
41 },
42 latestEvent: event,
43 }));
44 case "providerStatuses":
45 return Option.map(current, (projection) => ({
46 config: {
47 ...projection.config,
48 providers: event.payload.providers,
49 },
50 latestEvent: event,
51 }));
52 case "settingsUpdated":
53 return Option.map(current, (projection) => ({
54 config: {
55 ...projection.config,
56 settings: event.payload.settings,
57 },
58 latestEvent: event,
59 }));
60 }
62​
63export function projectServerConfig(
64 current: Option.Option<ServerConfigProjection>,
65 event: ServerConfigStreamEvent,
66): readonly [Option.Option<ServerConfigProjection>, ReadonlyArray<ServerConfigProjection>] {
67 const next = applyServerConfigProjection(current, event);
68 return [next, Option.toArray(next)];
70​
71export function projectServerWelcome(
72 current: Option.Option<ServerLifecycleWelcomePayload>,
73 event: {
74 readonly type: "welcome" | "ready";
75 readonly payload: unknown;
76 },
77): readonly [
78 Option.Option<ServerLifecycleWelcomePayload>,
79 ReadonlyArray<ServerLifecycleWelcomePayload>,
80] {
81 if (event.type !== "welcome") {
82 return [current, []];
83 }
84 const welcome = event.payload as ServerLifecycleWelcomePayload;
85 return [Option.some(welcome), [welcome]];
87​
88export function createServerEnvironmentAtoms<R, E>(
89 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
90 options: {
91 readonly initialConfigValueAtom: (
92 environmentId: EnvironmentId,
93 ) => Atom.Atom<ServerConfig | null>;
94 },
95) {
96 const configScheduler = createAtomCommandScheduler();
97 const configConcurrency = {
98 mode: "serial" as const,
99 key: ({ environmentId }: { readonly environmentId: string }) => environmentId,
100 };
101 const configProjection = createEnvironmentRpcSubscriptionAtomFamily(runtime, {
102 label: "environment-data:server:config-projection",
103 tag: WS_METHODS.subscribeServerConfig,
104 transform: (stream) =>
105 stream.pipe(Stream.mapAccum(Option.none<ServerConfigProjection>, projectServerConfig)),
106 });
107 const emptyConfigAtom = Atom.make<ServerConfig | null>(null).pipe(
108 Atom.withLabel("environment-data:server:config:empty"),
109 );
110 const configValueAtom = Atom.family((environmentId: EnvironmentId | null) => {
111 if (environmentId === null) {
112 return emptyConfigAtom;
113 }
114 return Atom.make((get): ServerConfig | null => {
115 const projection = Option.getOrNull(
116 AsyncResult.value(get(configProjection({ environmentId, input: {} }))),
117 );
118 return projection?.config ?? get(options.initialConfigValueAtom(environmentId));
119 }).pipe(Atom.withLabel(`environment-data:server:config:${environmentId}`));
120 });
121 const settingsValueAtom = Atom.family((environmentId: EnvironmentId) =>
122 Atom.make((get) => get(configValueAtom(environmentId))?.settings ?? null).pipe(
123 Atom.withLabel(`environment-data:server:settings:${environmentId}`),
124 ),
125 );
126 const providersValueAtom = Atom.family((environmentId: EnvironmentId) =>
127 Atom.make((get) => get(configValueAtom(environmentId))?.providers ?? null).pipe(
128 Atom.withLabel(`environment-data:server:providers:${environmentId}`),
129 ),
130 );
131​
132 return {
133 configValueAtom,
134 settingsValueAtom,
135 providersValueAtom,
136 traceDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
137 label: "environment-data:server:trace-diagnostics",
138 tag: WS_METHODS.serverGetTraceDiagnostics,
139 }),
140 processDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
141 label: "environment-data:server:process-diagnostics",
142 tag: WS_METHODS.serverGetProcessDiagnostics,
143 }),
144 processResourceHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
145 label: "environment-data:server:process-resource-history",
146 tag: WS_METHODS.serverGetProcessResourceHistory,
147 }),
148 /** Live scheduled-task list: snapshot on subscribe, fresh list after every server-side change. */
149 scheduledTasksLive: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
150 label: "environment-data:server:scheduled-tasks:live",
151 tag: WS_METHODS.scheduledTasksSubscribe,
152 }),
153 configProjection,
154 welcome: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
155 label: "environment-data:server:welcome",
156 tag: WS_METHODS.subscribeServerLifecycle,
157 transform: (stream) =>
158 stream.pipe(
159 Stream.mapAccum(Option.none<ServerLifecycleWelcomePayload>, projectServerWelcome),
160 ),
161 }),
162 refreshProviders: createEnvironmentRpcCommand(runtime, {
163 label: "environment-data:server:refresh-providers",
164 tag: WS_METHODS.serverRefreshProviders,
165 concurrency: {
166 mode: "singleFlight",
167 key: ({ environmentId }) => environmentId,
168 },
169 }),
170 updateProvider: createEnvironmentRpcCommand(runtime, {
171 label: "environment-data:server:update-provider",
172 tag: WS_METHODS.serverUpdateProvider,
173 scheduler: configScheduler,
174 concurrency: configConcurrency,
175 }),
176 upsertKeybinding: createEnvironmentRpcCommand(runtime, {
177 label: "environment-data:server:upsert-keybinding",
178 tag: WS_METHODS.serverUpsertKeybinding,
179 scheduler: configScheduler,
180 concurrency: configConcurrency,
181 }),
182 removeKeybinding: createEnvironmentRpcCommand(runtime, {
183 label: "environment-data:server:remove-keybinding",
184 tag: WS_METHODS.serverRemoveKeybinding,
185 scheduler: configScheduler,
186 concurrency: configConcurrency,
187 }),
188 updateSettings: createEnvironmentRpcCommand(runtime, {
189 label: "environment-data:server:update-settings",
190 tag: WS_METHODS.serverUpdateSettings,
191 scheduler: configScheduler,
192 concurrency: configConcurrency,
193 }),
194 signalProcess: createEnvironmentRpcCommand(runtime, {
195 label: "environment-data:server:signal-process",
196 tag: WS_METHODS.serverSignalProcess,
197 }),
198 upsertScheduledTask: createEnvironmentRpcCommand(runtime, {
199 label: "environment-data:server:scheduled-task:upsert",
200 tag: WS_METHODS.scheduledTasksUpsert,
201 scheduler: configScheduler,
202 concurrency: configConcurrency,
203 }),
204 setScheduledTaskEnabled: createEnvironmentRpcCommand(runtime, {
205 label: "environment-data:server:scheduled-task:set-enabled",
206 tag: WS_METHODS.scheduledTasksSetEnabled,
207 scheduler: configScheduler,
208 concurrency: configConcurrency,
209 }),
210 deleteScheduledTask: createEnvironmentRpcCommand(runtime, {
211 label: "environment-data:server:scheduled-task:delete",
212 tag: WS_METHODS.scheduledTasksDelete,
213 scheduler: configScheduler,
214 concurrency: configConcurrency,
215 }),
216 // Deliberately not on the config lane: run-now blocks until the run is
217 // dispatched, and a slow run must not stall settings/keybinding/provider
218 // mutations (or other scheduled-task edits) queued behind it.
219 runScheduledTaskNow: createEnvironmentRpcCommand(runtime, {
220 label: "environment-data:server:scheduled-task:run-now",
221 tag: WS_METHODS.scheduledTasksRunNow,
222 }),
223 };