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

server.ts

873 lines30.2 KB

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