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

server.ts

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