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

server.ts

974 lines35.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 interface ServerConfigSubscriptionOptions {
357 readonly environmentThemes?: boolean;
358 readonly usageLimitSources?: boolean;
360​
361export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConfigState.make")(
362 function* (subscription: ServerConfigSubscriptionOptions) {
363 const supervisor = yield* EnvironmentSupervisor;
364 const cache = yield* EnvironmentCacheStore;
365 const environmentId = supervisor.target.environmentId;
366 const cachedConfig = yield* cache.loadServerConfig(environmentId).pipe(
367 Effect.catch((error) =>
368 Effect.logWarning("Could not load cached server configuration.").pipe(
369 Effect.annotateLogs({
370 environmentId,
371 ...safeErrorLogAttributes(error),
372 }),
373 Effect.as(Option.none<ServerConfig>()),
374 ),
375 ),
376 );
377 const state = yield* SubscriptionRef.make<Option.Option<ServerConfigProjection>>(
378 // Stripped on load as well as on save: a cache written by an earlier
379 // build can still carry published themes.
380 Option.map(cachedConfig, (cached) => ({
381 config: withoutEnvironmentThemes(cached),
382 latestEvent: cachedConfigSnapshotEvent(withoutEnvironmentThemes(cached)),
383 source: "cache" as const,
384 })),
385 );
386 const persistence = yield* Queue.sliding<ServerConfig>(1);
387 const pendingPersistence = yield* Ref.make<Option.Option<ServerConfig>>(Option.none());
388​
389 const persist = Effect.fn("EnvironmentServerConfigState.persist")(function* (
390 config: ServerConfig,
391 ) {
392 return yield* cache.saveServerConfig(environmentId, withoutEnvironmentThemes(config)).pipe(
393 Effect.as(true),
394 Effect.catch((error) =>
395 Effect.logWarning("Could not persist cached server configuration.").pipe(
396 Effect.annotateLogs({
397 environmentId,
398 ...safeErrorLogAttributes(error),
399 }),
400 Effect.as(false),
401 ),
402 ),
403 );
404 });
405​
406 const persistPending = Effect.fn("EnvironmentServerConfigState.persistPending")(function* (
407 config: ServerConfig,
408 ) {
409 if (!(yield* persist(config))) {
410 return;
411 }
412 yield* Ref.update(pendingPersistence, (pending) =>
413 Option.isSome(pending) && pending.value === config ? Option.none() : pending,
414 );
415 });
416​
417 yield* Stream.fromQueue(persistence).pipe(
418 Stream.debounce("500 millis"),
419 Stream.runForEach(persistPending),
420 Effect.forkScoped,
421 );
422​
423 yield* subscribe(WS_METHODS.subscribeServerConfig, {
424 ...(subscription.environmentThemes === true ? { environmentThemes: true } : {}),
425 ...(subscription.usageLimitSources === true ? { usageLimitSources: true } : {}),
426 }).pipe(
427 Stream.runForEach((event) =>
428 Effect.gen(function* () {
429 const next = applyServerConfigProjection(yield* SubscriptionRef.get(state), event);
430 if (Option.isNone(next)) {
431 return;
432 }
433 yield* Ref.set(pendingPersistence, Option.some(next.value.config));
434 yield* SubscriptionRef.set(state, next);
435 yield* Queue.offer(persistence, next.value.config);
436 }),
437 ),
438 Effect.forkScoped,
439 );
440​
441 yield* Effect.addFinalizer(() =>
442 Ref.get(pendingPersistence).pipe(
443 Effect.flatMap(
444 Option.match({
445 onNone: () => Effect.void,
446 onSome: (config) => persist(config).pipe(Effect.asVoid),
447 }),
448 ),
449 ),
450 );
451​
452 return state;
453 },
454);
455​
456export function serverConfigStateChanges(
457 environmentId: EnvironmentId,
458 subscription: ServerConfigSubscriptionOptions,
459) {
460 return followStreamInEnvironment(
461 environmentId,
462 Stream.unwrap(
463 makeEnvironmentServerConfigState(subscription).pipe(
464 Effect.map((state) =>
465 SubscriptionRef.changes(state).pipe(
466 Stream.filterMap((projection) =>
467 Option.match(projection, {
468 onNone: () => Result.failVoid,
469 onSome: (value) => Result.succeed(value),
470 }),
471 ),
472 ),
473 ),
474 ),
475 ),
476 );
478​
479export function projectServerWelcome(
480 current: Option.Option<ServerLifecycleWelcomePayload>,
481 event: {
482 readonly type: "welcome" | "ready";
483 readonly payload: unknown;
484 },
485): readonly [
486 Option.Option<ServerLifecycleWelcomePayload>,
487 ReadonlyArray<ServerLifecycleWelcomePayload>,
488] {
489 if (event.type !== "welcome") {
490 return [current, []];
491 }
492 const welcome = event.payload as ServerLifecycleWelcomePayload;
493 return [Option.some(welcome), [welcome]];
495​
496export function resolveServerConfigValue(
497 projection: ServerConfigProjection | null,
498 initialConfig: ServerConfig | null,
499): ServerConfig | null {
500 if (
501 projection?.source === "live" &&
502 (initialConfig === null ||
503 projection.config.environment.serverVersion === initialConfig.environment.serverVersion)
504 ) {
505 return projection.config;
506 }
507 return initialConfig ?? projection?.config ?? null;
509​
510export function createServerEnvironmentAtoms<R, E>(
511 runtime: Atom.AtomRuntime<EnvironmentRegistry | EnvironmentCacheStore | R, E>,
512 options: {
513 readonly initialConfigValueAtom: (
514 environmentId: EnvironmentId,
515 ) => Atom.Atom<ServerConfig | null>;
516 /**
517 * Whether this surface renders themes the environment publishes. Mobile
518 * keeps its own appearance settings, so it neither asks for the stream nor
519 * receives the payload.
520 */
521 readonly environmentThemes?: boolean;
522 /** Whether this surface renders quota from configured usage-limit sources. */
523 readonly usageLimitSources?: boolean;
524 },
525) {
526 const configScheduler = createAtomCommandScheduler();
527 // Updates stay serial end-to-end, but only their handoff phase occupies the config lane.
528 const updateScheduler = createAtomCommandScheduler();
529 const configConcurrency = {
530 mode: "serial" as const,
531 key: ({ environmentId }: { readonly environmentId: string }) => environmentId,
532 };
533 const configProjectionFamily = Atom.family((environmentId: EnvironmentId) =>
534 runtime
535 .atom(
536 serverConfigStateChanges(environmentId, {
537 ...(options.environmentThemes === true ? { environmentThemes: true } : {}),
538 ...(options.usageLimitSources === true ? { usageLimitSources: true } : {}),
539 }),
540 )
541 .pipe(
542 Atom.setIdleTTL(5 * 60_000),
543 Atom.withLabel(`environment-data:server:config-projection:${environmentId}`),
544 ),
545 );
546 const configProjection = (target: {
547 readonly environmentId: EnvironmentId;
548 readonly input: EnvironmentRpcInput<typeof WS_METHODS.subscribeServerConfig>;
549 }) => configProjectionFamily(target.environmentId);
550 const emptyConfigAtom = Atom.make<ServerConfig | null>(null).pipe(
551 Atom.withLabel("environment-data:server:config:empty"),
552 );
553 const configValueAtom = Atom.family((environmentId: EnvironmentId | null) => {
554 if (environmentId === null) {
555 return emptyConfigAtom;
556 }
557 return Atom.make((get): ServerConfig | null => {
558 const projection = Option.getOrNull(
559 AsyncResult.value(get(configProjection({ environmentId, input: {} }))),
560 );
561 return resolveServerConfigValue(
562 projection,
563 get(options.initialConfigValueAtom(environmentId)),
564 );
565 }).pipe(Atom.withLabel(`environment-data:server:config:${environmentId}`));
566 });
567 const updateStateValueAtom = Atom.family((environmentId: EnvironmentId) =>
568 Atom.make((get) =>
569 serverUpdateStateForServerVersion(
570 get(serverUpdateStateAtom(environmentId)),
571 get(configValueAtom(environmentId))?.environment.serverVersion ?? null,
572 ),
573 ).pipe(Atom.withLabel(`environment-data:server:update-state-value:${environmentId}`)),
574 );
575 const updateStateAtom = (environmentId: EnvironmentId | null) =>
576 environmentId === null ? EMPTY_SERVER_UPDATE_STATE_ATOM : updateStateValueAtom(environmentId);
577 const updateServer = createRuntimeCommand<
578 EnvironmentRegistry | EnvironmentCacheStore | R,
579 E,
580 ServerUpdateTarget,
581 ServerSelfUpdateResult,
582 unknown
583 >(runtime, {
584 label: "environment-data:server:update-server",
585 scheduler: updateScheduler,
586 concurrency: configConcurrency,
587 execute: (target, atomRegistry) => {
588 const stateAtom = serverUpdateStateAtom(target.environmentId);
589 let targetVersion = target.input.targetVersion;
590 let fromVersion =
591 atomRegistry.get(configValueAtom(target.environmentId))?.environment.serverVersion ??
592 targetVersion;
593 let currentStage: ServerUpdateStage = "downloading";
594 let desktopCommitLostTransport = false;
595 atomRegistry.set(stateAtom, {
596 status: "running",
597 stage: currentStage,
598 fromVersion,
599 targetVersion,
600 });
601​
602 return Effect.gen(function* () {
603 const environmentRegistry = yield* EnvironmentRegistry;
604 const desktopCommitStarting = yield* Deferred.make<void>();
605 const desktopReconnectObserverArmed = yield* Deferred.make<void>();
606 const desktopReconnected = yield* Deferred.make<void>();
607 yield* Deferred.await(desktopCommitStarting).pipe(
608 Effect.andThen(
609 environmentRegistry.stateChanges(target.environmentId).pipe(
610 Stream.tap(() => Deferred.succeed(desktopReconnectObserverArmed, undefined)),
611 Stream.dropWhile((state) => state.phase === "connected"),
612 Stream.filter((state) => state.phase === "connected"),
613 Stream.runHead,
614 ),
615 ),
616 Effect.andThen(Deferred.succeed(desktopReconnected, undefined)),
617 Effect.forkChild,
618 );
619 const result = yield* scheduleAtomCommandEffect(
620 atomRegistry,
621 configScheduler,
622 configConcurrency,
623 target,
624 Effect.gen(function* () {
625 const currentConfig = atomRegistry.get(configValueAtom(target.environmentId));
626 fromVersion = currentConfig?.environment.serverVersion ?? targetVersion;
627 atomRegistry.set(stateAtom, {
628 status: "running",
629 stage: currentStage,
630 fromVersion,
631 targetVersion,
632 });
633​
634 const supportsProgress =
635 currentConfig?.environment.capabilities.serverSelfUpdateProgress === true;
636 const updateResult: ServerSelfUpdateResult = supportsProgress
637 ? yield* Effect.gen(function* () {
638 const terminal = yield* Ref.make<Option.Option<ServerSelfUpdateResult>>(
639 Option.none(),
640 );
641 const streamExit = yield* environmentRegistry
642 .runStream(
643 target.environmentId,
644 runStream(WS_METHODS.serverUpdateServerWithProgress, target.input),
645 )
646 .pipe(
647 Stream.runForEach((event) =>
648 Effect.sync(() => {
649 currentStage = event.type === "complete" ? "resuming" : event.stage;
650 atomRegistry.set(
651 stateAtom,
652 serverUpdateStateForProgressEvent(fromVersion, targetVersion, event),
653 );
654 }).pipe(
655 Effect.andThen(
656 event.type === "complete"
657 ? Ref.set(terminal, Option.some(event.result))
658 : Effect.void,
659 ),
660 ),
661 ),
662 Effect.exit,
663 );
664 return yield* resolveServerUpdateProgressResult(
665 targetVersion,
666 yield* Ref.get(terminal),
667 streamExit,
668 );
669 })
670 : yield* Effect.gen(function* () {
671 const selfUpdateMethod = currentConfig?.environment.capabilities.serverSelfUpdate;
672 const exit = yield* environmentRegistry
673 .run(target.environmentId, request(WS_METHODS.serverUpdateServer, target.input))
674 .pipe(Effect.exit);
675 if (Exit.isSuccess(exit)) {
676 return exit.value;
677 }
678 if (
679 (selfUpdateMethod === "boot-service" || selfUpdateMethod === "respawn") &&
680 isLegacyUpdateHandoffLoss(exit.cause)
681 ) {
682 // Older servers can tear down the transport before their
683 // unary acknowledgement arrives. Treat only that transport
684 // loss as a handoff, then prove it by waiting for target ready.
685 return { targetVersion, method: selfUpdateMethod };
686 }
687 return yield* Effect.failCause(exit.cause);
688 });
689​
690 if (
691 updateResult.method === "desktop-app" &&
692 updateResult.desktopUpdateToken !== undefined
693 ) {
694 yield* Deferred.succeed(desktopCommitStarting, undefined);
695 yield* Deferred.await(desktopReconnectObserverArmed);
696 const commitExit = yield* environmentRegistry
697 .run(
698 target.environmentId,
699 request(WS_METHODS.serverCommitDesktopUpdate, {
700 requestId: updateResult.desktopUpdateToken,
701 }),
702 )
703 .pipe(Effect.exit);
704 if (Exit.isFailure(commitExit) && !isLegacyUpdateHandoffLoss(commitExit.cause)) {
705 return yield* Effect.failCause(commitExit.cause);
706 }
707 desktopCommitLostTransport = Exit.isFailure(commitExit);
708 }
709​
710 targetVersion = updateResult.targetVersion;
711​
712 currentStage = "resuming";
713 atomRegistry.set(stateAtom, {
714 status: "running",
715 stage: currentStage,
716 fromVersion,
717 targetVersion,
718 });
719 return updateResult;
720 }),
721 );
722​
723 // The update restart is intentional and the server stays unreachable
724 // for the whole restart, so hold the retry cadence flat instead of
725 // letting the supervisor climb its backoff ladder.
726 yield* nudgeReconnectDuringUpdateRestart({
727 stateChanges: environmentRegistry.stateChanges(target.environmentId),
728 retryNow: environmentRegistry.retryNow(target.environmentId),
729 }).pipe(Effect.forkChild);
730​
731 if (result.method === "desktop-app" && desktopCommitLostTransport) {
732 yield* Deferred.await(desktopReconnected).pipe(
733 Effect.timeout(SERVER_UPDATE_RESUME_TIMEOUT),
734 );
735 }
736​
737 const waitForReady = environmentRegistry
738 .followStream(target.environmentId, subscribe(WS_METHODS.subscribeServerLifecycle, {}))
739 .pipe(
740 Stream.filter(
741 (event): event is ServerLifecycleStreamReadyEvent =>
742 event.type === "ready" && matchesServerUpdateResumeEvent(result, event),
743 ),
744 Stream.runHead,
745 Effect.timeoutOption(SERVER_UPDATE_RESUME_TIMEOUT),
746 Effect.map(Option.flatten),
747 );
748 const nextReady = waitForReady.pipe(
749 Effect.flatMap(
750 Option.match({
751 onNone: () =>
752 new ServerUpdateResumeTimeoutError({
753 environmentId: target.environmentId,
754 targetVersion,
755 }),
756 onSome: Effect.succeed,
757 }),
758 ),
759 );
760 const desktopUpdateToken = result.desktopUpdateToken;
761 const resumed =
762 result.method === "desktop-app" && desktopUpdateToken !== undefined
763 ? yield* waitForDesktopUpdateTarget(
764 result.targetVersion,
765 nextReady,
766 runDesktopCommitWithReconnectObserver(
767 environmentRegistry.stateChanges(target.environmentId),
768 environmentRegistry
769 .run(
770 target.environmentId,
771 request(WS_METHODS.serverCommitDesktopUpdate, {
772 requestId: desktopUpdateToken,
773 }),
774 )
775 .pipe(Effect.asVoid),
776 ),
777 )
778 : yield* nextReady;
779 yield* validateServerUpdateReadyEvent(result, resumed);
780​
781 atomRegistry.set(stateAtom, IDLE_SERVER_UPDATE_STATE);
782 return result;
783 }).pipe(
784 Effect.onExit((exit) =>
785 Effect.sync(() => {
786 if (Exit.isSuccess(exit)) {
787 return;
788 }
789 if (Cause.hasInterruptsOnly(exit.cause)) {
790 atomRegistry.set(stateAtom, IDLE_SERVER_UPDATE_STATE);
791 return;
792 }
793 atomRegistry.set(stateAtom, {
794 status: "failed",
795 stage: currentStage,
796 fromVersion,
797 targetVersion,
798 message: serverUpdateFailureMessage(Cause.squash(exit.cause)),
799 });
800 }),
801 ),
802 );
803 },
804 });
805 const settingsValueAtom = Atom.family((environmentId: EnvironmentId) =>
806 Atom.make((get) => get(configValueAtom(environmentId))?.settings ?? null).pipe(
807 Atom.withLabel(`environment-data:server:settings:${environmentId}`),
808 ),
809 );
810 const providersValueAtom = Atom.family((environmentId: EnvironmentId) =>
811 Atom.make((get) => get(configValueAtom(environmentId))?.providers ?? null).pipe(
812 Atom.withLabel(`environment-data:server:providers:${environmentId}`),
813 ),
814 );
815​
816 return {
817 configValueAtom,
818 updateStateAtom,
819 settingsValueAtom,
820 providersValueAtom,
821 providerAuthState: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
822 label: "environment-data:provider:auth-state",
823 tag: WS_METHODS.providerAuthSubscribe,
824 idleTtlMs: 0,
825 }),
826 startProviderAuth: createEnvironmentRpcCommand(runtime, {
827 label: "environment-data:provider:auth-start",
828 tag: WS_METHODS.providerAuthStart,
829 concurrency: {
830 mode: "singleFlight",
831 key: ({ environmentId, input }) => JSON.stringify([environmentId, input.instanceId]),
832 },
833 }),
834 completeProviderAuth: createEnvironmentRpcCommand(runtime, {
835 label: "environment-data:provider:auth-complete",
836 tag: WS_METHODS.providerAuthComplete,
837 }),
838 cancelProviderAuth: createEnvironmentRpcCommand(runtime, {
839 label: "environment-data:provider:auth-cancel",
840 tag: WS_METHODS.providerAuthCancel,
841 }),
842 logoutProviderAuth: createEnvironmentRpcCommand(runtime, {
843 label: "environment-data:provider:auth-logout",
844 tag: WS_METHODS.providerAuthLogout,
845 }),
846 providerInstallState: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
847 label: "environment-data:provider:install-state",
848 tag: WS_METHODS.providerInstallSubscribe,
849 idleTtlMs: 0,
850 }),
851 startProviderInstall: createEnvironmentRpcCommand(runtime, {
852 label: "environment-data:provider:install-start",
853 tag: WS_METHODS.providerInstallStart,
854 concurrency: {
855 mode: "singleFlight",
856 key: ({ environmentId }) => environmentId,
857 },
858 }),
859 cancelProviderInstall: createEnvironmentRpcCommand(runtime, {
860 label: "environment-data:provider:install-cancel",
861 tag: WS_METHODS.providerInstallCancel,
862 }),
863 removeProviderInstallation: createEnvironmentRpcCommand(runtime, {
864 label: "environment-data:provider:install-remove",
865 tag: WS_METHODS.providerInstallRemove,
866 }),
867 traceDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
868 label: "environment-data:server:trace-diagnostics",
869 tag: WS_METHODS.serverGetTraceDiagnostics,
870 }),
871 processDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
872 label: "environment-data:server:process-diagnostics",
873 tag: WS_METHODS.serverGetProcessDiagnostics,
874 }),
875 processResourceHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
876 label: "environment-data:server:process-resource-history",
877 tag: WS_METHODS.serverGetProcessResourceHistory,
878 }),
879 resourceTelemetry: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
880 label: "environment-data:server:resource-telemetry",
881 tag: WS_METHODS.subscribeResourceTelemetry,
882 idleTtlMs: 0,
883 }),
884 resourceTelemetryHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
885 label: "environment-data:server:resource-telemetry-history",
886 tag: WS_METHODS.serverGetResourceTelemetryHistory,
887 staleTimeMs: 5_000,
888 }),
889 // A cold transcript scan is measured in seconds, so keep the result around
890 // long enough that switching windows or re-rendering does not rescan.
891 usageSummary: createEnvironmentRpcQueryAtomFamily(runtime, {
892 label: "environment-data:server:usage-summary",
893 tag: WS_METHODS.serverGetUsageSummary,
894 staleTimeMs: 60_000,
895 }),
896 configProjection,
897 welcome: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
898 label: "environment-data:server:welcome",
899 tag: WS_METHODS.subscribeServerLifecycle,
900 transform: (stream) =>
901 stream.pipe(
902 Stream.mapAccum(Option.none<ServerLifecycleWelcomePayload>, projectServerWelcome),
903 ),
904 }),
905 consumeResetCredit: createEnvironmentRpcCommand(runtime, {
906 label: "environment-data:server:consume-reset-credit",
907 tag: WS_METHODS.providerConsumeResetCredit,
908 concurrency: {
909 mode: "singleFlight",
910 // Both ids are free-form strings; a delimiter could collide.
911 key: ({ environmentId, input }) => JSON.stringify([environmentId, input.instanceId]),
912 },
913 }),
914 refreshProviders: createEnvironmentRpcCommand(runtime, {
915 label: "environment-data:server:refresh-providers",
916 tag: WS_METHODS.serverRefreshProviders,
917 concurrency: {
918 mode: "singleFlight",
919 key: ({ environmentId, input }) =>
920 JSON.stringify([
921 environmentId,
922 input.instanceId ?? null,
923 input.cwd ?? null,
924 input.refreshModels ?? false,
925 ]),
926 },
927 }),
928 updateProvider: createEnvironmentRpcCommand(runtime, {
929 label: "environment-data:server:update-provider",
930 tag: WS_METHODS.serverUpdateProvider,
931 scheduler: configScheduler,
932 concurrency: configConcurrency,
933 }),
934 updateServer,
935 upsertKeybinding: createEnvironmentRpcCommand(runtime, {
936 label: "environment-data:server:upsert-keybinding",
937 tag: WS_METHODS.serverUpsertKeybinding,
938 scheduler: configScheduler,
939 concurrency: configConcurrency,
940 }),
941 removeKeybinding: createEnvironmentRpcCommand(runtime, {
942 label: "environment-data:server:remove-keybinding",
943 tag: WS_METHODS.serverRemoveKeybinding,
944 scheduler: configScheduler,
945 concurrency: configConcurrency,
946 }),
947 updateSettings: createEnvironmentRpcCommand(runtime, {
948 label: "environment-data:server:update-settings",
949 tag: WS_METHODS.serverUpdateSettings,
950 scheduler: configScheduler,
951 concurrency: configConcurrency,
952 }),
953 signalProcess: createEnvironmentRpcCommand(runtime, {
954 label: "environment-data:server:signal-process",
955 tag: WS_METHODS.serverSignalProcess,
956 }),
957 refreshUsageRates: createEnvironmentRpcCommand(runtime, {
958 label: "environment-data:server:refresh-usage-rates",
959 tag: WS_METHODS.serverRefreshUsageRates,
960 concurrency: {
961 mode: "singleFlight",
962 key: ({ environmentId }) => environmentId,
963 },
964 }),
965 retryResourceTelemetry: createEnvironmentRpcCommand(runtime, {
966 label: "environment-data:server:retry-resource-telemetry",
967 tag: WS_METHODS.serverRetryResourceTelemetry,
968 concurrency: {
969 mode: "singleFlight",
970 key: ({ environmentId }) => environmentId,
971 },
972 }),
973 };