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

server.ts

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