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

server.ts

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