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

server.ts

786 lines27.3 KB

1import {
2 type EnvironmentId,
3 type ServerConfig,
4 type ServerConfigStreamEvent,
5 type ServerLifecycleWelcomePayload,
6 type ServerLifecycleStreamReadyEvent,
7 type ServerSelfUpdateProgressEvent,
8 type ServerSelfUpdateResult,
9 WS_METHODS,
10} from "@t3tools/contracts";
11import * as Cause from "effect/Cause";
12import * as Duration from "effect/Duration";
13import * as Effect from "effect/Effect";
14import * as Exit from "effect/Exit";
15import * as Option from "effect/Option";
16import * as Queue from "effect/Queue";
17import * as Ref from "effect/Ref";
18import * as Result from "effect/Result";
19import * as Schema from "effect/Schema";
20import * as Stream from "effect/Stream";
21import * as SubscriptionRef from "effect/SubscriptionRef";
22import { AsyncResult, Atom } from "effect/unstable/reactivity";
23​
24import {
25 createAtomCommandScheduler,
26 createEnvironmentRpcCommand,
27 createEnvironmentRpcQueryAtomFamily,
28 createEnvironmentRpcSubscriptionAtomFamily,
29 createRuntimeCommand,
30 scheduleAtomCommandEffect,
31} from "./runtime.ts";
32import { EnvironmentRegistry } from "../connection/registry.ts";
33import { EnvironmentSupervisor } from "../connection/supervisor.ts";
34import { safeErrorLogAttributes } from "../errors/safeLog.ts";
35import { EnvironmentCacheStore } from "../platform/persistence.ts";
36import {
37 isRpcClientError,
38 request,
39 runStream,
40 subscribe,
41 type EnvironmentRpcInput,
42} from "../rpc/client.ts";
43import { followStreamInEnvironment } from "./runtime.ts";
44​
45export type ServerUpdateStage = "downloading" | "installing" | "resuming";
46​
47export type ServerUpdateState =
48 | { readonly status: "idle" }
49 | {
50 readonly status: "running";
51 readonly stage: ServerUpdateStage;
52 readonly fromVersion: string;
53 readonly targetVersion: string;
54 }
55 | {
56 readonly status: "failed";
57 readonly stage: ServerUpdateStage;
58 readonly fromVersion: string;
59 readonly targetVersion: string;
60 readonly message: string;
61 };
62​
63export interface ServerUpdateTarget {
64 readonly environmentId: EnvironmentId;
65 readonly input: EnvironmentRpcInput<typeof WS_METHODS.serverUpdateServer>;
67​
68const IDLE_SERVER_UPDATE_STATE: ServerUpdateState = { status: "idle" };
69const EMPTY_SERVER_UPDATE_STATE_ATOM = Atom.make<ServerUpdateState>(IDLE_SERVER_UPDATE_STATE).pipe(
70 Atom.withLabel("environment-data:server:update-state:empty"),
71);
72const serverUpdateStateAtom = Atom.family((environmentId: EnvironmentId) =>
73 Atom.make<ServerUpdateState>(IDLE_SERVER_UPDATE_STATE).pipe(
74 Atom.withLabel(`environment-data:server:update-state:${environmentId}`),
75 ),
76);
77​
78export class ServerUpdateResumeTimeoutError extends Schema.TaggedErrorClass<ServerUpdateResumeTimeoutError>()(
79 "ServerUpdateResumeTimeoutError",
80 {
81 environmentId: Schema.String,
82 targetVersion: Schema.String,
83 },
84) {
85 override get message(): string {
86 return `The server did not resume on t3@${this.targetVersion}.`;
87 }
89​
90export class ServerUpdateProgressIncompleteError extends Schema.TaggedErrorClass<ServerUpdateProgressIncompleteError>()(
91 "ServerUpdateProgressIncompleteError",
92 {
93 targetVersion: Schema.String,
94 },
95) {
96 override get message(): string {
97 return `The t3@${this.targetVersion} update ended before the server accepted the restart.`;
98 }
100​
101export class ServerUpdateTerminalError extends Schema.TaggedErrorClass<ServerUpdateTerminalError>()(
102 "ServerUpdateTerminalError",
103 {
104 targetVersion: Schema.String,
105 status: Schema.Literals(["committed", "rolled-back", "failed"]),
106 reason: Schema.optional(Schema.String),
107 },
108) {
109 override get message(): string {
110 return this.reason ?? `The t3@${this.targetVersion} update ${this.status}.`;
111 }
113​
114// Covers the 120-second trial deadline and a final restart of the previous
115// version when the trial rolls back.
116const SERVER_UPDATE_RESUME_TIMEOUT = Duration.minutes(4);
117​
118export function matchesServerUpdateReadyEvent(
119 result: ServerSelfUpdateResult,
120 event: ServerLifecycleStreamReadyEvent,
121): boolean {
122 return result.updateId === undefined
123 ? event.payload.environment.serverVersion === result.targetVersion
124 : event.payload.updateOutcome?.id === result.updateId;
126​
127export function validateServerUpdateReadyEvent(
128 result: ServerSelfUpdateResult,
129 event: ServerLifecycleStreamReadyEvent,
130): Effect.Effect<void, ServerUpdateTerminalError> {
131 if (result.updateId === undefined) return Effect.void;
132 const outcome = event.payload.updateOutcome;
133 if (
134 outcome?.id === result.updateId &&
135 outcome.status === "committed" &&
136 outcome.targetVersion === result.targetVersion &&
137 event.payload.environment.serverVersion === result.targetVersion
138 ) {
139 return Effect.void;
140 }
141 return Effect.fail(
142 new ServerUpdateTerminalError({
143 targetVersion: result.targetVersion,
144 status: outcome?.status ?? "failed",
145 reason:
146 outcome?.reason ??
147 "The service launcher resumed without committing the requested server version.",
148 }),
149 );
151​
152/**
153 * Keeps reconnect attempts ~1s apart for the whole update restart.
154 *
155 * A restart takes the server down for ~15 seconds, but the supervisor's normal
156 * backoff ladder (1/2/4/8/16s) assumes an unexpected failure and lands attempts
157 * at ~3, 5, 9, 17 and 33 seconds — so a 15-second restart is observed as a
158 * 33-second "Resuming". Nudging on every backoff entry (not just the first)
159 * holds the retry cadence flat until the server answers again. The sleep before
160 * each nudge is the pacer: a connection that fails instantly re-enters backoff
161 * immediately and would otherwise spin a tight retry loop.
162 *
163 * A newly restarted server can also reject the first environment credential.
164 * Authentication blocks need the same paced retry during this known restart;
165 * permission and configuration failures remain blocked.
166 *
167 * Callers fork this as a child of the update command so it is interrupted as
168 * soon as the update settles, whether it succeeds, fails, or times out.
169 */
170export function nudgeReconnectDuringUpdateRestart(input: {
171 readonly stateChanges: Stream.Stream<
172 {
173 readonly phase: string;
174 readonly lastFailure?: { readonly reason: string } | null;
175 },
176 unknown
177 >;
178 readonly retryNow: Effect.Effect<void>;
179 readonly interval?: Duration.Duration;
180}): Effect.Effect<void> {
181 return input.stateChanges.pipe(
182 Stream.filter(
183 (state) =>
184 state.phase === "backoff" ||
185 (state.phase === "blocked" && state.lastFailure?.reason === "authentication"),
186 ),
187 Stream.runForEach(() =>
188 Effect.sleep(input.interval ?? Duration.seconds(1)).pipe(Effect.andThen(input.retryNow)),
189 ),
190 Effect.timeoutOption(SERVER_UPDATE_RESUME_TIMEOUT),
191 Effect.ignore,
192 );
194​
195export function serverUpdateStateForProgressEvent(
196 fromVersion: string,
197 targetVersion: string,
198 event: ServerSelfUpdateProgressEvent,
199): Extract<ServerUpdateState, { status: "running" }> {
200 return {
201 status: "running",
202 stage: event.type === "complete" ? "resuming" : event.stage,
203 fromVersion,
204 targetVersion,
205 };
207​
208export function serverUpdateStateForServerVersion(
209 state: ServerUpdateState,
210 serverVersion: string | null,
211): ServerUpdateState {
212 return state.status === "idle" ||
213 state.status === "running" ||
214 serverVersion === null ||
215 state.fromVersion === serverVersion
216 ? state
217 : IDLE_SERVER_UPDATE_STATE;
219​
220function serverUpdateFailureMessage(error: unknown): string {
221 return error instanceof Error ? error.message : "Server update failed.";
223​
224function isRpcSocketError(error: unknown): boolean {
225 if (!isRpcClientError(error)) {
226 return false;
227 }
228 switch (error.reason._tag) {
229 case "SocketReadError":
230 case "SocketWriteError":
231 case "SocketCloseError":
232 return true;
233 default:
234 return false;
235 }
237​
238export function isLegacyUpdateHandoffLoss(cause: Cause.Cause<unknown>): boolean {
239 if (Cause.hasInterruptsOnly(cause)) {
240 return true;
241 }
242 return (
243 cause.reasons.length > 0 &&
244 cause.reasons.every((reason) => Cause.isFailReason(reason) && isRpcSocketError(reason.error))
245 );
247​
248export function resolveServerUpdateProgressResult<E>(
249 targetVersion: string,
250 terminal: Option.Option<ServerSelfUpdateResult>,
251 streamExit: Exit.Exit<void, E>,
252): Effect.Effect<ServerSelfUpdateResult, E | ServerUpdateProgressIncompleteError> {
253 if (
254 Option.isSome(terminal) &&
255 (Exit.isSuccess(streamExit) || isLegacyUpdateHandoffLoss(streamExit.cause))
256 ) {
257 return Effect.succeed(terminal.value);
258 }
259 if (Exit.isFailure(streamExit)) {
260 return Effect.failCause(streamExit.cause);
261 }
262 return Effect.fail(new ServerUpdateProgressIncompleteError({ targetVersion }));
264​
265export interface ServerConfigProjection {
266 readonly config: ServerConfig;
267 readonly latestEvent: ServerConfigStreamEvent;
268 readonly source: "cache" | "live";
270​
271export function applyServerConfigProjection(
272 current: Option.Option<ServerConfigProjection>,
273 event: ServerConfigStreamEvent,
274): Option.Option<ServerConfigProjection> {
275 switch (event.type) {
276 case "snapshot":
277 return Option.some({
278 config: event.config,
279 latestEvent: event,
280 source: "live",
281 });
282 case "keybindingsUpdated":
283 return Option.map(current, (projection) => ({
284 config: {
285 ...projection.config,
286 keybindings: event.payload.keybindings,
287 issues: event.payload.issues,
288 },
289 latestEvent: event,
290 source: "live",
291 }));
292 case "providerStatuses":
293 return Option.map(current, (projection) => ({
294 config: {
295 ...projection.config,
296 providers: event.payload.providers,
297 },
298 latestEvent: event,
299 source: "live",
300 }));
301 case "settingsUpdated":
302 return Option.map(current, (projection) => ({
303 config: {
304 ...projection.config,
305 settings: event.payload.settings,
306 },
307 latestEvent: event,
308 source: "live",
309 }));
310 }
312​
313export function projectServerConfig(
314 current: Option.Option<ServerConfigProjection>,
315 event: ServerConfigStreamEvent,
316): readonly [Option.Option<ServerConfigProjection>, ReadonlyArray<ServerConfigProjection>] {
317 const next = applyServerConfigProjection(current, event);
318 return [next, Option.toArray(next)];
320​
321const cachedConfigSnapshotEvent = (config: ServerConfig): ServerConfigStreamEvent => ({
322 version: 1,
323 type: "snapshot",
324 config,
325});
326​
327/**
328 * Keeps a complete server configuration available during reconnects. Server
329 * config carries the provider/model catalogue used by task creation, so it is
330 * useful—and safe—to retain after a transport session ends.
331 */
332export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConfigState.make")(
333 function* () {
334 const supervisor = yield* EnvironmentSupervisor;
335 const cache = yield* EnvironmentCacheStore;
336 const environmentId = supervisor.target.environmentId;
337 const cachedConfig = yield* cache.loadServerConfig(environmentId).pipe(
338 Effect.catch((error) =>
339 Effect.logWarning("Could not load cached server configuration.").pipe(
340 Effect.annotateLogs({
341 environmentId,
342 ...safeErrorLogAttributes(error),
343 }),
344 Effect.as(Option.none<ServerConfig>()),
345 ),
346 ),
347 );
348 const state = yield* SubscriptionRef.make<Option.Option<ServerConfigProjection>>(
349 Option.map(cachedConfig, (config) => ({
350 config,
351 latestEvent: cachedConfigSnapshotEvent(config),
352 source: "cache" as const,
353 })),
354 );
355 const persistence = yield* Queue.sliding<ServerConfig>(1);
356 const pendingPersistence = yield* Ref.make<Option.Option<ServerConfig>>(Option.none());
357​
358 const persist = Effect.fn("EnvironmentServerConfigState.persist")(function* (
359 config: ServerConfig,
360 ) {
361 return yield* cache.saveServerConfig(environmentId, config).pipe(
362 Effect.as(true),
363 Effect.catch((error) =>
364 Effect.logWarning("Could not persist cached server configuration.").pipe(
365 Effect.annotateLogs({
366 environmentId,
367 ...safeErrorLogAttributes(error),
368 }),
369 Effect.as(false),
370 ),
371 ),
372 );
373 });
374​
375 const persistPending = Effect.fn("EnvironmentServerConfigState.persistPending")(function* (
376 config: ServerConfig,
377 ) {
378 if (!(yield* persist(config))) {
379 return;
380 }
381 yield* Ref.update(pendingPersistence, (pending) =>
382 Option.isSome(pending) && pending.value === config ? Option.none() : pending,
383 );
384 });
385​
386 yield* Stream.fromQueue(persistence).pipe(
387 Stream.debounce("500 millis"),
388 Stream.runForEach(persistPending),
389 Effect.forkScoped,
390 );
391​
392 yield* subscribe(WS_METHODS.subscribeServerConfig, {}).pipe(
393 Stream.runForEach((event) =>
394 Effect.gen(function* () {
395 const next = applyServerConfigProjection(yield* SubscriptionRef.get(state), event);
396 if (Option.isNone(next)) {
397 return;
398 }
399 yield* Ref.set(pendingPersistence, Option.some(next.value.config));
400 yield* SubscriptionRef.set(state, next);
401 yield* Queue.offer(persistence, next.value.config);
402 }),
403 ),
404 Effect.forkScoped,
405 );
406​
407 yield* Effect.addFinalizer(() =>
408 Ref.get(pendingPersistence).pipe(
409 Effect.flatMap(
410 Option.match({
411 onNone: () => Effect.void,
412 onSome: (config) => persist(config).pipe(Effect.asVoid),
413 }),
414 ),
415 ),
416 );
417​
418 return state;
419 },
420);
421​
422export function serverConfigStateChanges(environmentId: EnvironmentId) {
423 return followStreamInEnvironment(
424 environmentId,
425 Stream.unwrap(
426 makeEnvironmentServerConfigState().pipe(
427 Effect.map((state) =>
428 SubscriptionRef.changes(state).pipe(
429 Stream.filterMap((projection) =>
430 Option.match(projection, {
431 onNone: () => Result.failVoid,
432 onSome: (value) => Result.succeed(value),
433 }),
434 ),
435 ),
436 ),
437 ),
438 ),
439 );
441​
442export function projectServerWelcome(
443 current: Option.Option<ServerLifecycleWelcomePayload>,
444 event: {
445 readonly type: "welcome" | "ready";
446 readonly payload: unknown;
447 },
448): readonly [
449 Option.Option<ServerLifecycleWelcomePayload>,
450 ReadonlyArray<ServerLifecycleWelcomePayload>,
451] {
452 if (event.type !== "welcome") {
453 return [current, []];
454 }
455 const welcome = event.payload as ServerLifecycleWelcomePayload;
456 return [Option.some(welcome), [welcome]];
458​
459export function resolveServerConfigValue(
460 projection: ServerConfigProjection | null,
461 initialConfig: ServerConfig | null,
462): ServerConfig | null {
463 if (
464 projection?.source === "live" &&
465 (initialConfig === null ||
466 projection.config.environment.serverVersion === initialConfig.environment.serverVersion)
467 ) {
468 return projection.config;
469 }
470 return initialConfig ?? projection?.config ?? null;
472​
473export function createServerEnvironmentAtoms<R, E>(
474 runtime: Atom.AtomRuntime<EnvironmentRegistry | EnvironmentCacheStore | R, E>,
475 options: {
476 readonly initialConfigValueAtom: (
477 environmentId: EnvironmentId,
478 ) => Atom.Atom<ServerConfig | null>;
479 },
480) {
481 const configScheduler = createAtomCommandScheduler();
482 // Updates stay serial end-to-end, but only their handoff phase occupies the config lane.
483 const updateScheduler = createAtomCommandScheduler();
484 const configConcurrency = {
485 mode: "serial" as const,
486 key: ({ environmentId }: { readonly environmentId: string }) => environmentId,
487 };
488 const configProjectionFamily = Atom.family((environmentId: EnvironmentId) =>
489 runtime
490 .atom(serverConfigStateChanges(environmentId))
491 .pipe(
492 Atom.setIdleTTL(5 * 60_000),
493 Atom.withLabel(`environment-data:server:config-projection:${environmentId}`),
494 ),
495 );
496 const configProjection = (target: {
497 readonly environmentId: EnvironmentId;
498 readonly input: EnvironmentRpcInput<typeof WS_METHODS.subscribeServerConfig>;
499 }) => configProjectionFamily(target.environmentId);
500 const emptyConfigAtom = Atom.make<ServerConfig | null>(null).pipe(
501 Atom.withLabel("environment-data:server:config:empty"),
502 );
503 const configValueAtom = Atom.family((environmentId: EnvironmentId | null) => {
504 if (environmentId === null) {
505 return emptyConfigAtom;
506 }
507 return Atom.make((get): ServerConfig | null => {
508 const projection = Option.getOrNull(
509 AsyncResult.value(get(configProjection({ environmentId, input: {} }))),
510 );
511 return resolveServerConfigValue(
512 projection,
513 get(options.initialConfigValueAtom(environmentId)),
514 );
515 }).pipe(Atom.withLabel(`environment-data:server:config:${environmentId}`));
516 });
517 const updateStateValueAtom = Atom.family((environmentId: EnvironmentId) =>
518 Atom.make((get) =>
519 serverUpdateStateForServerVersion(
520 get(serverUpdateStateAtom(environmentId)),
521 get(configValueAtom(environmentId))?.environment.serverVersion ?? null,
522 ),
523 ).pipe(Atom.withLabel(`environment-data:server:update-state-value:${environmentId}`)),
524 );
525 const updateStateAtom = (environmentId: EnvironmentId | null) =>
526 environmentId === null ? EMPTY_SERVER_UPDATE_STATE_ATOM : updateStateValueAtom(environmentId);
527 const updateServer = createRuntimeCommand<
528 EnvironmentRegistry | EnvironmentCacheStore | R,
529 E,
530 ServerUpdateTarget,
531 ServerSelfUpdateResult,
532 unknown
533 >(runtime, {
534 label: "environment-data:server:update-server",
535 scheduler: updateScheduler,
536 concurrency: configConcurrency,
537 execute: (target, atomRegistry) => {
538 const stateAtom = serverUpdateStateAtom(target.environmentId);
539 const targetVersion = target.input.targetVersion;
540 let fromVersion =
541 atomRegistry.get(configValueAtom(target.environmentId))?.environment.serverVersion ??
542 targetVersion;
543 let currentStage: ServerUpdateStage = "downloading";
544 atomRegistry.set(stateAtom, {
545 status: "running",
546 stage: currentStage,
547 fromVersion,
548 targetVersion,
549 });
550​
551 return Effect.gen(function* () {
552 const environmentRegistry = yield* EnvironmentRegistry;
553 const result = yield* scheduleAtomCommandEffect(
554 atomRegistry,
555 configScheduler,
556 configConcurrency,
557 target,
558 Effect.gen(function* () {
559 const currentConfig = atomRegistry.get(configValueAtom(target.environmentId));
560 fromVersion = currentConfig?.environment.serverVersion ?? targetVersion;
561 atomRegistry.set(stateAtom, {
562 status: "running",
563 stage: currentStage,
564 fromVersion,
565 targetVersion,
566 });
567​
568 const supportsProgress =
569 currentConfig?.environment.capabilities.serverSelfUpdateProgress === true;
570 const updateResult: ServerSelfUpdateResult = supportsProgress
571 ? yield* Effect.gen(function* () {
572 const terminal = yield* Ref.make<Option.Option<ServerSelfUpdateResult>>(
573 Option.none(),
574 );
575 const streamExit = yield* environmentRegistry
576 .runStream(
577 target.environmentId,
578 runStream(WS_METHODS.serverUpdateServerWithProgress, target.input),
579 )
580 .pipe(
581 Stream.runForEach((event) =>
582 Effect.sync(() => {
583 currentStage = event.type === "complete" ? "resuming" : event.stage;
584 atomRegistry.set(
585 stateAtom,
586 serverUpdateStateForProgressEvent(fromVersion, targetVersion, event),
587 );
588 }).pipe(
589 Effect.andThen(
590 event.type === "complete"
591 ? Ref.set(terminal, Option.some(event.result))
592 : Effect.void,
593 ),
594 ),
595 ),
596 Effect.exit,
597 );
598 return yield* resolveServerUpdateProgressResult(
599 targetVersion,
600 yield* Ref.get(terminal),
601 streamExit,
602 );
603 })
604 : yield* Effect.gen(function* () {
605 const selfUpdateMethod = currentConfig?.environment.capabilities.serverSelfUpdate;
606 const exit = yield* environmentRegistry
607 .run(target.environmentId, request(WS_METHODS.serverUpdateServer, target.input))
608 .pipe(Effect.exit);
609 if (Exit.isSuccess(exit)) {
610 return exit.value;
611 }
612 if (
613 (selfUpdateMethod === "boot-service" || selfUpdateMethod === "respawn") &&
614 isLegacyUpdateHandoffLoss(exit.cause)
615 ) {
616 // Older servers can tear down the transport before their
617 // unary acknowledgement arrives. Treat only that transport
618 // loss as a handoff, then prove it by waiting for target ready.
619 return { targetVersion, method: selfUpdateMethod };
620 }
621 return yield* Effect.failCause(exit.cause);
622 });
623​
624 currentStage = "resuming";
625 atomRegistry.set(stateAtom, {
626 status: "running",
627 stage: currentStage,
628 fromVersion,
629 targetVersion,
630 });
631 return updateResult;
632 }),
633 );
634​
635 // The update restart is intentional and the server stays unreachable
636 // for the whole restart, so hold the retry cadence flat instead of
637 // letting the supervisor climb its backoff ladder.
638 yield* nudgeReconnectDuringUpdateRestart({
639 stateChanges: environmentRegistry.stateChanges(target.environmentId),
640 retryNow: environmentRegistry.retryNow(target.environmentId),
641 }).pipe(Effect.forkChild);
642​
643 const resumed = yield* environmentRegistry
644 .followStream(target.environmentId, subscribe(WS_METHODS.subscribeServerLifecycle, {}))
645 .pipe(
646 Stream.filter(
647 (event): event is ServerLifecycleStreamReadyEvent =>
648 event.type === "ready" && matchesServerUpdateReadyEvent(result, event),
649 ),
650 Stream.runHead,
651 Effect.timeoutOption(SERVER_UPDATE_RESUME_TIMEOUT),
652 Effect.map(Option.flatten),
653 );
654 if (Option.isNone(resumed)) {
655 return yield* new ServerUpdateResumeTimeoutError({
656 environmentId: target.environmentId,
657 targetVersion,
658 });
659 }
660 yield* validateServerUpdateReadyEvent(result, resumed.value);
661​
662 atomRegistry.set(stateAtom, IDLE_SERVER_UPDATE_STATE);
663 return result;
664 }).pipe(
665 Effect.onExit((exit) =>
666 Effect.sync(() => {
667 if (Exit.isSuccess(exit)) {
668 return;
669 }
670 if (Cause.hasInterruptsOnly(exit.cause)) {
671 atomRegistry.set(stateAtom, IDLE_SERVER_UPDATE_STATE);
672 return;
673 }
674 atomRegistry.set(stateAtom, {
675 status: "failed",
676 stage: currentStage,
677 fromVersion,
678 targetVersion,
679 message: serverUpdateFailureMessage(Cause.squash(exit.cause)),
680 });
681 }),
682 ),
683 );
684 },
685 });
686 const settingsValueAtom = Atom.family((environmentId: EnvironmentId) =>
687 Atom.make((get) => get(configValueAtom(environmentId))?.settings ?? null).pipe(
688 Atom.withLabel(`environment-data:server:settings:${environmentId}`),
689 ),
690 );
691 const providersValueAtom = Atom.family((environmentId: EnvironmentId) =>
692 Atom.make((get) => get(configValueAtom(environmentId))?.providers ?? null).pipe(
693 Atom.withLabel(`environment-data:server:providers:${environmentId}`),
694 ),
695 );
696​
697 return {
698 configValueAtom,
699 updateStateAtom,
700 settingsValueAtom,
701 providersValueAtom,
702 traceDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
703 label: "environment-data:server:trace-diagnostics",
704 tag: WS_METHODS.serverGetTraceDiagnostics,
705 }),
706 processDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
707 label: "environment-data:server:process-diagnostics",
708 tag: WS_METHODS.serverGetProcessDiagnostics,
709 }),
710 processResourceHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
711 label: "environment-data:server:process-resource-history",
712 tag: WS_METHODS.serverGetProcessResourceHistory,
713 }),
714 resourceTelemetry: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
715 label: "environment-data:server:resource-telemetry",
716 tag: WS_METHODS.subscribeResourceTelemetry,
717 idleTtlMs: 0,
718 }),
719 resourceTelemetryHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
720 label: "environment-data:server:resource-telemetry-history",
721 tag: WS_METHODS.serverGetResourceTelemetryHistory,
722 staleTimeMs: 5_000,
723 }),
724 // A cold transcript scan is measured in seconds, so keep the result around
725 // long enough that switching windows or re-rendering does not rescan.
726 usageSummary: createEnvironmentRpcQueryAtomFamily(runtime, {
727 label: "environment-data:server:usage-summary",
728 tag: WS_METHODS.serverGetUsageSummary,
729 staleTimeMs: 60_000,
730 }),
731 configProjection,
732 welcome: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
733 label: "environment-data:server:welcome",
734 tag: WS_METHODS.subscribeServerLifecycle,
735 transform: (stream) =>
736 stream.pipe(
737 Stream.mapAccum(Option.none<ServerLifecycleWelcomePayload>, projectServerWelcome),
738 ),
739 }),
740 refreshProviders: createEnvironmentRpcCommand(runtime, {
741 label: "environment-data:server:refresh-providers",
742 tag: WS_METHODS.serverRefreshProviders,
743 concurrency: {
744 mode: "singleFlight",
745 key: ({ environmentId }) => environmentId,
746 },
747 }),
748 updateProvider: createEnvironmentRpcCommand(runtime, {
749 label: "environment-data:server:update-provider",
750 tag: WS_METHODS.serverUpdateProvider,
751 scheduler: configScheduler,
752 concurrency: configConcurrency,
753 }),
754 updateServer,
755 upsertKeybinding: createEnvironmentRpcCommand(runtime, {
756 label: "environment-data:server:upsert-keybinding",
757 tag: WS_METHODS.serverUpsertKeybinding,
758 scheduler: configScheduler,
759 concurrency: configConcurrency,
760 }),
761 removeKeybinding: createEnvironmentRpcCommand(runtime, {
762 label: "environment-data:server:remove-keybinding",
763 tag: WS_METHODS.serverRemoveKeybinding,
764 scheduler: configScheduler,
765 concurrency: configConcurrency,
766 }),
767 updateSettings: createEnvironmentRpcCommand(runtime, {
768 label: "environment-data:server:update-settings",
769 tag: WS_METHODS.serverUpdateSettings,
770 scheduler: configScheduler,
771 concurrency: configConcurrency,
772 }),
773 signalProcess: createEnvironmentRpcCommand(runtime, {
774 label: "environment-data:server:signal-process",
775 tag: WS_METHODS.serverSignalProcess,
776 }),
777 retryResourceTelemetry: createEnvironmentRpcCommand(runtime, {
778 label: "environment-data:server:retry-resource-telemetry",
779 tag: WS_METHODS.serverRetryResourceTelemetry,
780 concurrency: {
781 mode: "singleFlight",
782 key: ({ environmentId }) => environmentId,
783 },
784 }),
785 };