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

server.ts

347 lines11.6 KB

1import {
2 type EnvironmentId,
3 type ServerConfig,
4 type ServerConfigStreamEvent,
5 type ServerLifecycleWelcomePayload,
6 WS_METHODS,
7} from "@v12/contracts";
8import * as Effect from "effect/Effect";
9import * as Option from "effect/Option";
10import * as Queue from "effect/Queue";
11import * as Ref from "effect/Ref";
12import * as Result from "effect/Result";
13import * as Stream from "effect/Stream";
14import * as SubscriptionRef from "effect/SubscriptionRef";
15import { AsyncResult, Atom } from "effect/unstable/reactivity";
16​
17import {
18 createAtomCommandScheduler,
19 createEnvironmentRpcCommand,
20 createEnvironmentRpcQueryAtomFamily,
21 createEnvironmentRpcSubscriptionAtomFamily,
22} from "./runtime.ts";
23import type { EnvironmentRegistry } from "../connection/registry.ts";
24import { EnvironmentSupervisor } from "../connection/supervisor.ts";
25import { safeErrorLogAttributes } from "../errors/safeLog.ts";
26import { EnvironmentCacheStore } from "../platform/persistence.ts";
27import { subscribe, type EnvironmentRpcInput } from "../rpc/client.ts";
28import { followStreamInEnvironment } from "./runtime.ts";
29​
30export interface ServerConfigProjection {
31 readonly config: ServerConfig;
32 readonly latestEvent: ServerConfigStreamEvent;
33 readonly source: "cache" | "live";
35​
36export function applyServerConfigProjection(
37 current: Option.Option<ServerConfigProjection>,
38 event: ServerConfigStreamEvent,
39): Option.Option<ServerConfigProjection> {
40 switch (event.type) {
41 case "snapshot":
42 return Option.some({
43 config: event.config,
44 latestEvent: event,
45 source: "live",
46 });
47 case "keybindingsUpdated":
48 return Option.map(current, (projection) => ({
49 config: {
50 ...projection.config,
51 keybindings: event.payload.keybindings,
52 issues: event.payload.issues,
53 },
54 latestEvent: event,
55 source: "live",
56 }));
57 case "providerStatuses":
58 return Option.map(current, (projection) => ({
59 config: {
60 ...projection.config,
61 providers: event.payload.providers,
62 },
63 latestEvent: event,
64 source: "live",
65 }));
66 case "settingsUpdated":
67 return Option.map(current, (projection) => ({
68 config: {
69 ...projection.config,
70 settings: event.payload.settings,
71 },
72 latestEvent: event,
73 source: "live",
74 }));
75 }
77​
78export function projectServerConfig(
79 current: Option.Option<ServerConfigProjection>,
80 event: ServerConfigStreamEvent,
81): readonly [Option.Option<ServerConfigProjection>, ReadonlyArray<ServerConfigProjection>] {
82 const next = applyServerConfigProjection(current, event);
83 return [next, Option.toArray(next)];
85​
86const cachedConfigSnapshotEvent = (config: ServerConfig): ServerConfigStreamEvent => ({
87 version: 1,
88 type: "snapshot",
89 config,
90});
91​
92/**
93 * Keeps a complete server configuration available during reconnects. Server
94 * config carries the provider/model catalogue used by task creation, so it is
95 * useful—and safe—to retain after a transport session ends.
96 */
97export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConfigState.make")(
98 function* () {
99 const supervisor = yield* EnvironmentSupervisor;
100 const cache = yield* EnvironmentCacheStore;
101 const environmentId = supervisor.target.environmentId;
102 const cachedConfig = yield* cache.loadServerConfig(environmentId).pipe(
103 Effect.catch((error) =>
104 Effect.logWarning("Could not load cached server configuration.").pipe(
105 Effect.annotateLogs({
106 environmentId,
107 ...safeErrorLogAttributes(error),
108 }),
109 Effect.as(Option.none<ServerConfig>()),
110 ),
111 ),
112 );
113 const state = yield* SubscriptionRef.make<Option.Option<ServerConfigProjection>>(
114 Option.map(cachedConfig, (config) => ({
115 config,
116 latestEvent: cachedConfigSnapshotEvent(config),
117 source: "cache" as const,
118 })),
119 );
120 const persistence = yield* Queue.sliding<ServerConfig>(1);
121 const pendingPersistence = yield* Ref.make<Option.Option<ServerConfig>>(Option.none());
122​
123 const persist = Effect.fn("EnvironmentServerConfigState.persist")(function* (
124 config: ServerConfig,
125 ) {
126 return yield* cache.saveServerConfig(environmentId, config).pipe(
127 Effect.as(true),
128 Effect.catch((error) =>
129 Effect.logWarning("Could not persist cached server configuration.").pipe(
130 Effect.annotateLogs({
131 environmentId,
132 ...safeErrorLogAttributes(error),
133 }),
134 Effect.as(false),
135 ),
136 ),
137 );
138 });
139​
140 const persistPending = Effect.fn("EnvironmentServerConfigState.persistPending")(function* (
141 config: ServerConfig,
142 ) {
143 if (!(yield* persist(config))) {
144 return;
145 }
146 yield* Ref.update(pendingPersistence, (pending) =>
147 Option.isSome(pending) && pending.value === config ? Option.none() : pending,
148 );
149 });
150​
151 yield* Stream.fromQueue(persistence).pipe(
152 Stream.debounce("500 millis"),
153 Stream.runForEach(persistPending),
154 Effect.forkScoped,
155 );
156​
157 yield* subscribe(WS_METHODS.subscribeServerConfig, {}).pipe(
158 Stream.runForEach((event) =>
159 Effect.gen(function* () {
160 const next = applyServerConfigProjection(yield* SubscriptionRef.get(state), event);
161 if (Option.isNone(next)) {
162 return;
163 }
164 yield* Ref.set(pendingPersistence, Option.some(next.value.config));
165 yield* SubscriptionRef.set(state, next);
166 yield* Queue.offer(persistence, next.value.config);
167 }),
168 ),
169 Effect.forkScoped,
170 );
171​
172 yield* Effect.addFinalizer(() =>
173 Ref.get(pendingPersistence).pipe(
174 Effect.flatMap(
175 Option.match({
176 onNone: () => Effect.void,
177 onSome: (config) => persist(config).pipe(Effect.asVoid),
178 }),
179 ),
180 ),
181 );
182​
183 return state;
184 },
185);
186​
187export function serverConfigStateChanges(environmentId: EnvironmentId) {
188 return followStreamInEnvironment(
189 environmentId,
190 Stream.unwrap(
191 makeEnvironmentServerConfigState().pipe(
192 Effect.map((state) =>
193 SubscriptionRef.changes(state).pipe(
194 Stream.filterMap((projection) =>
195 Option.match(projection, {
196 onNone: () => Result.failVoid,
197 onSome: (value) => Result.succeed(value),
198 }),
199 ),
200 ),
201 ),
202 ),
203 ),
204 );
206​
207export function projectServerWelcome(
208 current: Option.Option<ServerLifecycleWelcomePayload>,
209 event: {
210 readonly type: "welcome" | "ready";
211 readonly payload: unknown;
212 },
213): readonly [
214 Option.Option<ServerLifecycleWelcomePayload>,
215 ReadonlyArray<ServerLifecycleWelcomePayload>,
216] {
217 if (event.type !== "welcome") {
218 return [current, []];
219 }
220 const welcome = event.payload as ServerLifecycleWelcomePayload;
221 return [Option.some(welcome), [welcome]];
223​
224export function resolveServerConfigValue(
225 projection: ServerConfigProjection | null,
226 initialConfig: ServerConfig | null,
227): ServerConfig | null {
228 if (projection?.source === "live") return projection.config;
229 return initialConfig ?? projection?.config ?? null;
231​
232export function createServerEnvironmentAtoms<R, E>(
233 runtime: Atom.AtomRuntime<EnvironmentRegistry | EnvironmentCacheStore | R, E>,
234 options: {
235 readonly initialConfigValueAtom: (
236 environmentId: EnvironmentId,
237 ) => Atom.Atom<ServerConfig | null>;
238 },
239) {
240 const configScheduler = createAtomCommandScheduler();
241 const configConcurrency = {
242 mode: "serial" as const,
243 key: ({ environmentId }: { readonly environmentId: string }) => environmentId,
244 };
245 const configProjectionFamily = Atom.family((environmentId: EnvironmentId) =>
246 runtime
247 .atom(serverConfigStateChanges(environmentId))
248 .pipe(
249 Atom.setIdleTTL(5 * 60_000),
250 Atom.withLabel(`environment-data:server:config-projection:${environmentId}`),
251 ),
252 );
253 const configProjection = (target: {
254 readonly environmentId: EnvironmentId;
255 readonly input: EnvironmentRpcInput<typeof WS_METHODS.subscribeServerConfig>;
256 }) => configProjectionFamily(target.environmentId);
257 const emptyConfigAtom = Atom.make<ServerConfig | null>(null).pipe(
258 Atom.withLabel("environment-data:server:config:empty"),
259 );
260 const configValueAtom = Atom.family((environmentId: EnvironmentId | null) => {
261 if (environmentId === null) {
262 return emptyConfigAtom;
263 }
264 return Atom.make((get): ServerConfig | null => {
265 const projection = Option.getOrNull(
266 AsyncResult.value(get(configProjection({ environmentId, input: {} }))),
267 );
268 return resolveServerConfigValue(
269 projection,
270 get(options.initialConfigValueAtom(environmentId)),
271 );
272 }).pipe(Atom.withLabel(`environment-data:server:config:${environmentId}`));
273 });
274 const settingsValueAtom = Atom.family((environmentId: EnvironmentId) =>
275 Atom.make((get) => get(configValueAtom(environmentId))?.settings ?? null).pipe(
276 Atom.withLabel(`environment-data:server:settings:${environmentId}`),
277 ),
278 );
279 const providersValueAtom = Atom.family((environmentId: EnvironmentId) =>
280 Atom.make((get) => get(configValueAtom(environmentId))?.providers ?? null).pipe(
281 Atom.withLabel(`environment-data:server:providers:${environmentId}`),
282 ),
283 );
284​
285 return {
286 configValueAtom,
287 settingsValueAtom,
288 providersValueAtom,
289 traceDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
290 label: "environment-data:server:trace-diagnostics",
291 tag: WS_METHODS.serverGetTraceDiagnostics,
292 }),
293 processDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
294 label: "environment-data:server:process-diagnostics",
295 tag: WS_METHODS.serverGetProcessDiagnostics,
296 }),
297 processResourceHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
298 label: "environment-data:server:process-resource-history",
299 tag: WS_METHODS.serverGetProcessResourceHistory,
300 }),
301 configProjection,
302 welcome: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
303 label: "environment-data:server:welcome",
304 tag: WS_METHODS.subscribeServerLifecycle,
305 transform: (stream) =>
306 stream.pipe(
307 Stream.mapAccum(Option.none<ServerLifecycleWelcomePayload>, projectServerWelcome),
308 ),
309 }),
310 refreshProviders: createEnvironmentRpcCommand(runtime, {
311 label: "environment-data:server:refresh-providers",
312 tag: WS_METHODS.serverRefreshProviders,
313 concurrency: {
314 mode: "singleFlight",
315 key: ({ environmentId }) => environmentId,
316 },
317 }),
318 updateProvider: createEnvironmentRpcCommand(runtime, {
319 label: "environment-data:server:update-provider",
320 tag: WS_METHODS.serverUpdateProvider,
321 scheduler: configScheduler,
322 concurrency: configConcurrency,
323 }),
324 upsertKeybinding: createEnvironmentRpcCommand(runtime, {
325 label: "environment-data:server:upsert-keybinding",
326 tag: WS_METHODS.serverUpsertKeybinding,
327 scheduler: configScheduler,
328 concurrency: configConcurrency,
329 }),
330 removeKeybinding: createEnvironmentRpcCommand(runtime, {
331 label: "environment-data:server:remove-keybinding",
332 tag: WS_METHODS.serverRemoveKeybinding,
333 scheduler: configScheduler,
334 concurrency: configConcurrency,
335 }),
336 updateSettings: createEnvironmentRpcCommand(runtime, {
337 label: "environment-data:server:update-settings",
338 tag: WS_METHODS.serverUpdateSettings,
339 scheduler: configScheduler,
340 concurrency: configConcurrency,
341 }),
342 signalProcess: createEnvironmentRpcCommand(runtime, {
343 label: "environment-data:server:signal-process",
344 tag: WS_METHODS.serverSignalProcess,
345 }),
346 };