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

server.ts

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