Open History to see the last commit
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>;
66}
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 }
88}
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 }
99}
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 }
112}
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;
125}
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 );
150}
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 );
193}
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 };
206}
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;
218}
219
220function serverUpdateFailureMessage(error: unknown): string {
221 return error instanceof Error ? error.message : "Server update failed.";
222}
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 }
236}
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 );
246}
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 }));
263}
264
265export interface ServerConfigProjection {
266 readonly config: ServerConfig;
267 readonly latestEvent: ServerConfigStreamEvent;
268 readonly source: "cache" | "live";
269}
270
271export function applyServerConfigProjection(
272 current: Option.Option<ServerConfigProjection>,
273 event: ServerConfigStreamEvent,
274): Option.Option<ServerConfigProjection> {
275 switch (event.type) {
276 case "snapshot": {
277 // A snapshot never carries published themes -- the theme stream owns
278 // them -- so taking it wholesale would clear the set on every reconnect
279 // and repaint anyone wearing one until the follow-up event landed.
280 // Only from a server that still streams them. Reconnecting to one that
281 // predates the feature must drop the set rather than leave a palette on
282 // screen that nothing will ever update again.
283 const carried =
284 event.config.environment.capabilities.environmentThemes === true && Option.isSome(current)
285 ? current.value.config.environmentThemes
286 : undefined;
287 return Option.some({
288 config:
289 carried === undefined ? event.config : { ...event.config, environmentThemes: carried },
290 latestEvent: event,
291 source: "live" as const,
292 });
293 }
294 case "keybindingsUpdated":
295 return Option.map(current, (projection) => ({
296 config: {
297 ...projection.config,
298 keybindings: event.payload.keybindings,
299 issues: event.payload.issues,
300 },
301 latestEvent: event,
302 source: "live",
303 }));
304 case "providerStatuses":
305 return Option.map(current, (projection) => ({
306 config: {
307 ...projection.config,
308 providers: event.payload.providers,
309 },
310 latestEvent: event,
311 source: "live",
312 }));
313 case "settingsUpdated":
314 return Option.map(current, (projection) => ({
315 config: {
316 ...projection.config,
317 settings: event.payload.settings,
318 },
319 latestEvent: event,
320 source: "live",
321 }));
322 case "environmentThemesUpdated":
323 return Option.map(current, (projection) => ({
324 config: {
325 ...projection.config,
326 environmentThemes: event.payload.themes.length > 0 ? event.payload.themes : undefined,
327 },
328 latestEvent: event,
329 source: "live",
330 }));
331 }
332}
333
334export function projectServerConfig(
335 current: Option.Option<ServerConfigProjection>,
336 event: ServerConfigStreamEvent,
337): readonly [Option.Option<ServerConfigProjection>, ReadonlyArray<ServerConfigProjection>] {
338 const next = applyServerConfigProjection(current, event);
339 return [next, Option.toArray(next)];
340}
341
342const cachedConfigSnapshotEvent = (config: ServerConfig): ServerConfigStreamEvent => ({
343 version: 1,
344 type: "snapshot",
345 config,
346});
347
348/**
349 * Keeps a complete server configuration available during reconnects. Server
350 * config carries the provider/model catalogue used by task creation, so it is
351 * useful—and safe—to retain after a transport session ends.
352 */
353/**
354 * Published themes live only as long as the machine publishes them, so they
355 * must not survive in the config cache: a restart or an offline load would
356 * otherwise hand clients palettes the environment has already dropped.
357 */
358function withoutEnvironmentThemes(config: ServerConfig): ServerConfig {
359 if (config.environmentThemes === undefined) return config;
360 const { environmentThemes: _ephemeral, ...rest } = config;
361 return rest;
362}
363
364export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConfigState.make")(
365 function* (environmentThemes?: boolean) {
366 const supervisor = yield* EnvironmentSupervisor;
367 const cache = yield* EnvironmentCacheStore;
368 const environmentId = supervisor.target.environmentId;
369 const cachedConfig = yield* cache.loadServerConfig(environmentId).pipe(
370 Effect.catch((error) =>
371 Effect.logWarning("Could not load cached server configuration.").pipe(
372 Effect.annotateLogs({
373 environmentId,
374 ...safeErrorLogAttributes(error),
375 }),
376 Effect.as(Option.none<ServerConfig>()),
377 ),
378 ),
379 );
380 const state = yield* SubscriptionRef.make<Option.Option<ServerConfigProjection>>(
381 // Stripped on load as well as on save: a cache written by an earlier
382 // build can still carry published themes.
383 Option.map(cachedConfig, (cached) => ({
384 config: withoutEnvironmentThemes(cached),
385 latestEvent: cachedConfigSnapshotEvent(withoutEnvironmentThemes(cached)),
386 source: "cache" as const,
387 })),
388 );
389 const persistence = yield* Queue.sliding<ServerConfig>(1);
390 const pendingPersistence = yield* Ref.make<Option.Option<ServerConfig>>(Option.none());
391
392 const persist = Effect.fn("EnvironmentServerConfigState.persist")(function* (
393 config: ServerConfig,
394 ) {
395 return yield* cache.saveServerConfig(environmentId, withoutEnvironmentThemes(config)).pipe(
396 Effect.as(true),
397 Effect.catch((error) =>
398 Effect.logWarning("Could not persist cached server configuration.").pipe(
399 Effect.annotateLogs({
400 environmentId,
401 ...safeErrorLogAttributes(error),
402 }),
403 Effect.as(false),
404 ),
405 ),
406 );
407 });
408
409 const persistPending = Effect.fn("EnvironmentServerConfigState.persistPending")(function* (
410 config: ServerConfig,
411 ) {
412 if (!(yield* persist(config))) {
413 return;
414 }
415 yield* Ref.update(pendingPersistence, (pending) =>
416 Option.isSome(pending) && pending.value === config ? Option.none() : pending,
417 );
418 });
419
420 yield* Stream.fromQueue(persistence).pipe(
421 Stream.debounce("500 millis"),
422 Stream.runForEach(persistPending),
423 Effect.forkScoped,
424 );
425
426 yield* subscribe(
427 WS_METHODS.subscribeServerConfig,
428 environmentThemes === true ? { environmentThemes: true } : {},
429 ).pipe(
430 Stream.runForEach((event) =>
431 Effect.gen(function* () {
432 const next = applyServerConfigProjection(yield* SubscriptionRef.get(state), event);
433 if (Option.isNone(next)) {
434 return;
435 }
436 yield* Ref.set(pendingPersistence, Option.some(next.value.config));
437 yield* SubscriptionRef.set(state, next);
438 yield* Queue.offer(persistence, next.value.config);
439 }),
440 ),
441 Effect.forkScoped,
442 );
443
444 yield* Effect.addFinalizer(() =>
445 Ref.get(pendingPersistence).pipe(
446 Effect.flatMap(
447 Option.match({
448 onNone: () => Effect.void,
449 onSome: (config) => persist(config).pipe(Effect.asVoid),
450 }),
451 ),
452 ),
453 );
454
455 return state;
456 },
457);
458
459export function serverConfigStateChanges(
460 environmentId: EnvironmentId,
461 environmentThemes?: boolean,
462) {
463 return followStreamInEnvironment(
464 environmentId,
465 Stream.unwrap(
466 makeEnvironmentServerConfigState(environmentThemes).pipe(
467 Effect.map((state) =>
468 SubscriptionRef.changes(state).pipe(
469 Stream.filterMap((projection) =>
470 Option.match(projection, {
471 onNone: () => Result.failVoid,
472 onSome: (value) => Result.succeed(value),
473 }),
474 ),
475 ),
476 ),
477 ),
478 ),
479 );
480}
481
482export function projectServerWelcome(
483 current: Option.Option<ServerLifecycleWelcomePayload>,
484 event: {
485 readonly type: "welcome" | "ready";
486 readonly payload: unknown;
487 },
488): readonly [
489 Option.Option<ServerLifecycleWelcomePayload>,
490 ReadonlyArray<ServerLifecycleWelcomePayload>,
491] {
492 if (event.type !== "welcome") {
493 return [current, []];
494 }
495 const welcome = event.payload as ServerLifecycleWelcomePayload;
496 return [Option.some(welcome), [welcome]];
497}
498
499export function resolveServerConfigValue(
500 projection: ServerConfigProjection | null,
501 initialConfig: ServerConfig | null,
502): ServerConfig | null {
503 if (
504 projection?.source === "live" &&
505 (initialConfig === null ||
506 projection.config.environment.serverVersion === initialConfig.environment.serverVersion)
507 ) {
508 return projection.config;
509 }
510 return initialConfig ?? projection?.config ?? null;
511}
512
513export function createServerEnvironmentAtoms<R, E>(
514 runtime: Atom.AtomRuntime<EnvironmentRegistry | EnvironmentCacheStore | R, E>,
515 options: {
516 readonly initialConfigValueAtom: (
517 environmentId: EnvironmentId,
518 ) => Atom.Atom<ServerConfig | null>;
519 /**
520 * Whether this surface renders themes the environment publishes. Mobile
521 * keeps its own appearance settings, so it neither asks for the stream nor
522 * receives the payload.
523 */
524 readonly environmentThemes?: boolean;
525 },
526) {
527 const configScheduler = createAtomCommandScheduler();
528 // Updates stay serial end-to-end, but only their handoff phase occupies the config lane.
529 const updateScheduler = createAtomCommandScheduler();
530 const configConcurrency = {
531 mode: "serial" as const,
532 key: ({ environmentId }: { readonly environmentId: string }) => environmentId,
533 };
534 const configProjectionFamily = Atom.family((environmentId: EnvironmentId) =>
535 runtime
536 .atom(serverConfigStateChanges(environmentId, options.environmentThemes))
537 .pipe(
538 Atom.setIdleTTL(5 * 60_000),
539 Atom.withLabel(`environment-data:server:config-projection:${environmentId}`),
540 ),
541 );
542 const configProjection = (target: {
543 readonly environmentId: EnvironmentId;
544 readonly input: EnvironmentRpcInput<typeof WS_METHODS.subscribeServerConfig>;
545 }) => configProjectionFamily(target.environmentId);
546 const emptyConfigAtom = Atom.make<ServerConfig | null>(null).pipe(
547 Atom.withLabel("environment-data:server:config:empty"),
548 );
549 const configValueAtom = Atom.family((environmentId: EnvironmentId | null) => {
550 if (environmentId === null) {
551 return emptyConfigAtom;
552 }
553 return Atom.make((get): ServerConfig | null => {
554 const projection = Option.getOrNull(
555 AsyncResult.value(get(configProjection({ environmentId, input: {} }))),
556 );
557 return resolveServerConfigValue(
558 projection,
559 get(options.initialConfigValueAtom(environmentId)),
560 );
561 }).pipe(Atom.withLabel(`environment-data:server:config:${environmentId}`));
562 });
563 const updateStateValueAtom = Atom.family((environmentId: EnvironmentId) =>
564 Atom.make((get) =>
565 serverUpdateStateForServerVersion(
566 get(serverUpdateStateAtom(environmentId)),
567 get(configValueAtom(environmentId))?.environment.serverVersion ?? null,
568 ),
569 ).pipe(Atom.withLabel(`environment-data:server:update-state-value:${environmentId}`)),
570 );
571 const updateStateAtom = (environmentId: EnvironmentId | null) =>
572 environmentId === null ? EMPTY_SERVER_UPDATE_STATE_ATOM : updateStateValueAtom(environmentId);
573 const updateServer = createRuntimeCommand<
574 EnvironmentRegistry | EnvironmentCacheStore | R,
575 E,
576 ServerUpdateTarget,
577 ServerSelfUpdateResult,
578 unknown
579 >(runtime, {
580 label: "environment-data:server:update-server",
581 scheduler: updateScheduler,
582 concurrency: configConcurrency,
583 execute: (target, atomRegistry) => {
584 const stateAtom = serverUpdateStateAtom(target.environmentId);
585 const targetVersion = target.input.targetVersion;
586 let fromVersion =
587 atomRegistry.get(configValueAtom(target.environmentId))?.environment.serverVersion ??
588 targetVersion;
589 let currentStage: ServerUpdateStage = "downloading";
590 atomRegistry.set(stateAtom, {
591 status: "running",
592 stage: currentStage,
593 fromVersion,
594 targetVersion,
595 });
596
597 return Effect.gen(function* () {
598 const environmentRegistry = yield* EnvironmentRegistry;
599 const result = yield* scheduleAtomCommandEffect(
600 atomRegistry,
601 configScheduler,
602 configConcurrency,
603 target,
604 Effect.gen(function* () {
605 const currentConfig = atomRegistry.get(configValueAtom(target.environmentId));
606 fromVersion = currentConfig?.environment.serverVersion ?? targetVersion;
607 atomRegistry.set(stateAtom, {
608 status: "running",
609 stage: currentStage,
610 fromVersion,
611 targetVersion,
612 });
613
614 const supportsProgress =
615 currentConfig?.environment.capabilities.serverSelfUpdateProgress === true;
616 const updateResult: ServerSelfUpdateResult = supportsProgress
617 ? yield* Effect.gen(function* () {
618 const terminal = yield* Ref.make<Option.Option<ServerSelfUpdateResult>>(
619 Option.none(),
620 );
621 const streamExit = yield* environmentRegistry
622 .runStream(
623 target.environmentId,
624 runStream(WS_METHODS.serverUpdateServerWithProgress, target.input),
625 )
626 .pipe(
627 Stream.runForEach((event) =>
628 Effect.sync(() => {
629 currentStage = event.type === "complete" ? "resuming" : event.stage;
630 atomRegistry.set(
631 stateAtom,
632 serverUpdateStateForProgressEvent(fromVersion, targetVersion, event),
633 );
634 }).pipe(
635 Effect.andThen(
636 event.type === "complete"
637 ? Ref.set(terminal, Option.some(event.result))
638 : Effect.void,
639 ),
640 ),
641 ),
642 Effect.exit,
643 );
644 return yield* resolveServerUpdateProgressResult(
645 targetVersion,
646 yield* Ref.get(terminal),
647 streamExit,
648 );
649 })
650 : yield* Effect.gen(function* () {
651 const selfUpdateMethod = currentConfig?.environment.capabilities.serverSelfUpdate;
652 const exit = yield* environmentRegistry
653 .run(target.environmentId, request(WS_METHODS.serverUpdateServer, target.input))
654 .pipe(Effect.exit);
655 if (Exit.isSuccess(exit)) {
656 return exit.value;
657 }
658 if (
659 (selfUpdateMethod === "boot-service" || selfUpdateMethod === "respawn") &&
660 isLegacyUpdateHandoffLoss(exit.cause)
661 ) {
662 // Older servers can tear down the transport before their
663 // unary acknowledgement arrives. Treat only that transport
664 // loss as a handoff, then prove it by waiting for target ready.
665 return { targetVersion, method: selfUpdateMethod };
666 }
667 return yield* Effect.failCause(exit.cause);
668 });
669
670 currentStage = "resuming";
671 atomRegistry.set(stateAtom, {
672 status: "running",
673 stage: currentStage,
674 fromVersion,
675 targetVersion,
676 });
677 return updateResult;
678 }),
679 );
680
681 // The update restart is intentional and the server stays unreachable
682 // for the whole restart, so hold the retry cadence flat instead of
683 // letting the supervisor climb its backoff ladder.
684 yield* nudgeReconnectDuringUpdateRestart({
685 stateChanges: environmentRegistry.stateChanges(target.environmentId),
686 retryNow: environmentRegistry.retryNow(target.environmentId),
687 }).pipe(Effect.forkChild);
688
689 const resumed = yield* environmentRegistry
690 .followStream(target.environmentId, subscribe(WS_METHODS.subscribeServerLifecycle, {}))
691 .pipe(
692 Stream.filter(
693 (event): event is ServerLifecycleStreamReadyEvent =>
694 event.type === "ready" && matchesServerUpdateReadyEvent(result, event),
695 ),
696 Stream.runHead,
697 Effect.timeoutOption(SERVER_UPDATE_RESUME_TIMEOUT),
698 Effect.map(Option.flatten),
699 );
700 if (Option.isNone(resumed)) {
701 return yield* new ServerUpdateResumeTimeoutError({
702 environmentId: target.environmentId,
703 targetVersion,
704 });
705 }
706 yield* validateServerUpdateReadyEvent(result, resumed.value);
707
708 atomRegistry.set(stateAtom, IDLE_SERVER_UPDATE_STATE);
709 return result;
710 }).pipe(
711 Effect.onExit((exit) =>
712 Effect.sync(() => {
713 if (Exit.isSuccess(exit)) {
714 return;
715 }
716 if (Cause.hasInterruptsOnly(exit.cause)) {
717 atomRegistry.set(stateAtom, IDLE_SERVER_UPDATE_STATE);
718 return;
719 }
720 atomRegistry.set(stateAtom, {
721 status: "failed",
722 stage: currentStage,
723 fromVersion,
724 targetVersion,
725 message: serverUpdateFailureMessage(Cause.squash(exit.cause)),
726 });
727 }),
728 ),
729 );
730 },
731 });
732 const settingsValueAtom = Atom.family((environmentId: EnvironmentId) =>
733 Atom.make((get) => get(configValueAtom(environmentId))?.settings ?? null).pipe(
734 Atom.withLabel(`environment-data:server:settings:${environmentId}`),
735 ),
736 );
737 const providersValueAtom = Atom.family((environmentId: EnvironmentId) =>
738 Atom.make((get) => get(configValueAtom(environmentId))?.providers ?? null).pipe(
739 Atom.withLabel(`environment-data:server:providers:${environmentId}`),
740 ),
741 );
742
743 return {
744 configValueAtom,
745 updateStateAtom,
746 settingsValueAtom,
747 providersValueAtom,
748 traceDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
749 label: "environment-data:server:trace-diagnostics",
750 tag: WS_METHODS.serverGetTraceDiagnostics,
751 }),
752 processDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
753 label: "environment-data:server:process-diagnostics",
754 tag: WS_METHODS.serverGetProcessDiagnostics,
755 }),
756 processResourceHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
757 label: "environment-data:server:process-resource-history",
758 tag: WS_METHODS.serverGetProcessResourceHistory,
759 }),
760 resourceTelemetry: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
761 label: "environment-data:server:resource-telemetry",
762 tag: WS_METHODS.subscribeResourceTelemetry,
763 idleTtlMs: 0,
764 }),
765 resourceTelemetryHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
766 label: "environment-data:server:resource-telemetry-history",
767 tag: WS_METHODS.serverGetResourceTelemetryHistory,
768 staleTimeMs: 5_000,
769 }),
770 // A cold transcript scan is measured in seconds, so keep the result around
771 // long enough that switching windows or re-rendering does not rescan.
772 usageSummary: createEnvironmentRpcQueryAtomFamily(runtime, {
773 label: "environment-data:server:usage-summary",
774 tag: WS_METHODS.serverGetUsageSummary,
775 staleTimeMs: 60_000,
776 }),
777 configProjection,
778 welcome: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
779 label: "environment-data:server:welcome",
780 tag: WS_METHODS.subscribeServerLifecycle,
781 transform: (stream) =>
782 stream.pipe(
783 Stream.mapAccum(Option.none<ServerLifecycleWelcomePayload>, projectServerWelcome),
784 ),
785 }),
786 refreshProviders: createEnvironmentRpcCommand(runtime, {
787 label: "environment-data:server:refresh-providers",
788 tag: WS_METHODS.serverRefreshProviders,
789 concurrency: {
790 mode: "singleFlight",
791 key: ({ environmentId }) => environmentId,
792 },
793 }),
794 updateProvider: createEnvironmentRpcCommand(runtime, {
795 label: "environment-data:server:update-provider",
796 tag: WS_METHODS.serverUpdateProvider,
797 scheduler: configScheduler,
798 concurrency: configConcurrency,
799 }),
800 updateServer,
801 upsertKeybinding: createEnvironmentRpcCommand(runtime, {
802 label: "environment-data:server:upsert-keybinding",
803 tag: WS_METHODS.serverUpsertKeybinding,
804 scheduler: configScheduler,
805 concurrency: configConcurrency,
806 }),
807 removeKeybinding: createEnvironmentRpcCommand(runtime, {
808 label: "environment-data:server:remove-keybinding",
809 tag: WS_METHODS.serverRemoveKeybinding,
810 scheduler: configScheduler,
811 concurrency: configConcurrency,
812 }),
813 updateSettings: createEnvironmentRpcCommand(runtime, {
814 label: "environment-data:server:update-settings",
815 tag: WS_METHODS.serverUpdateSettings,
816 scheduler: configScheduler,
817 concurrency: configConcurrency,
818 }),
819 signalProcess: createEnvironmentRpcCommand(runtime, {
820 label: "environment-data:server:signal-process",
821 tag: WS_METHODS.serverSignalProcess,
822 }),
823 retryResourceTelemetry: createEnvironmentRpcCommand(runtime, {
824 label: "environment-data:server:retry-resource-telemetry",
825 tag: WS_METHODS.serverRetryResourceTelemetry,
826 concurrency: {
827 mode: "singleFlight",
828 key: ({ environmentId }) => environmentId,
829 },
830 }),
831 };
832}