Open History to see the last commit
1import {
2 ORCHESTRATION_PROTOCOL_VERSION,
3 type EnvironmentId,
4 type ExecutionEnvironmentDescriptor,
5 type ServerSelfUpdateInput,
6 type ServerSelfUpdateResult,
7 WS_METHODS,
8} from "@t3tools/contracts";
9import * as Duration from "effect/Duration";
10import * as Effect from "effect/Effect";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13import * as Ref from "effect/Ref";
14import * as Schedule from "effect/Schedule";
15import * as Schema from "effect/Schema";
16import * as Stream from "effect/Stream";
17import * as SubscriptionRef from "effect/SubscriptionRef";
18import * as HttpClient from "effect/http/HttpClient";
19import * as RpcClient from "effect/rpc/RpcClient";
20import * as RpcSerialization from "effect/rpc/RpcSerialization";
21import * as Socket from "effect/socket/Socket";
22
23import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
24import { makeWsRpcProtocolClient, PING_TIMEOUT } from "../rpc/protocol.ts";
25import { isLegacyUpdateHandoffLoss, resolveServerUpdateProgressResult } from "../state/server.ts";
26import * as RelayEnvironmentDiscovery from "../relay/discovery.ts";
27import * as ConnectionResolver from "./resolver.ts";
28import * as EnvironmentRegistry from "./registry.ts";
29import { connectionRoutes, hasRelayRoute, routeEntry, routeHttpBaseUrl } from "./routes.ts";
30
31// A v1 host restarting into v2 runs migrations before its descriptor answers again.
32const OUTDATED_HOST_RESTART_TIMEOUT = Duration.minutes(4);
33const SOCKET_OPEN_TIMEOUT = "15 seconds";
34
35export class OutdatedHostUpdateError extends Schema.TaggedError<OutdatedHostUpdateError>()(
36 "OutdatedHostUpdateError",
37 {
38 environmentId: Schema.String,
39 message: Schema.String,
40 },
41) {}
42
43export type OutdatedHostUpdateStage = "downloading" | "installing" | "resuming";
44
45/**
46 * The normal session refuses to open against such a host, so this opens a bare
47 * socket and calls only the self-update RPCs, whose wire shape has not changed
48 * across protocol versions.
49 */
50export const updateOutdatedHost = Effect.fn("clientRuntime.connection.updateOutdatedHost")(
51 function* (
52 environmentId: EnvironmentId,
53 input: ServerSelfUpdateInput,
54 onStage: (stage: OutdatedHostUpdateStage) => Effect.Effect<void>,
55 ) {
56 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
57 const resolver = yield* ConnectionResolver.ConnectionResolver;
58 const webSocketConstructor = yield* Socket.WebSocketConstructor;
59 const httpClient = yield* HttpClient.HttpClient;
60 const entry = (yield* SubscriptionRef.get(registry.entries)).get(environmentId);
61 if (entry === undefined) {
62 return yield* new EnvironmentRegistry.EnvironmentNotRegisteredError({ environmentId });
63 }
64 const { prepared, descriptor } = yield* Effect.firstSuccessOf(
65 connectionRoutes(entry).map((route) => resolver.prepareForUpdate(routeEntry(entry, route))),
66 );
67 const capabilities = descriptor.capabilities;
68 if (
69 capabilities.serverSelfUpdate === undefined ||
70 (capabilities.serverSelfUpdate === "desktop-managed" &&
71 capabilities.desktopAppUpdate !== true)
72 ) {
73 return yield* new OutdatedHostUpdateError({
74 environmentId,
75 message: `Update T3 Code on ${descriptor.label} manually; it cannot update itself.`,
76 });
77 }
78
79 const result = yield* Effect.scoped(
80 Effect.gen(function* () {
81 const protocolContext = yield* Layer.build(
82 Layer.effect(
83 RpcClient.Protocol,
84 RpcClient.makeProtocolSocket({
85 pingTimeout: PING_TIMEOUT,
86 retryTransientErrors: false,
87 retryPolicy: Schedule.recurs(0),
88 }),
89 ).pipe(
90 Layer.provide(
91 Layer.mergeAll(
92 Socket.layerWebSocket(prepared.socketUrl, {
93 openTimeout: SOCKET_OPEN_TIMEOUT,
94 }).pipe(
95 Layer.provide(Layer.succeed(Socket.WebSocketConstructor, webSocketConstructor)),
96 ),
97 RpcSerialization.layerJson,
98 ),
99 ),
100 ),
101 );
102 const client = yield* makeWsRpcProtocolClient.pipe(Effect.provide(protocolContext));
103
104 const updateResult: ServerSelfUpdateResult =
105 capabilities.serverSelfUpdateProgress === true
106 ? yield* Effect.gen(function* () {
107 const terminal = yield* Ref.make(Option.none<ServerSelfUpdateResult>());
108 const streamExit = yield* client[WS_METHODS.serverUpdateServerWithProgress](
109 input,
110 ).pipe(
111 Stream.runForEach((event) =>
112 event.type === "complete"
113 ? Ref.set(terminal, Option.some(event.result))
114 : onStage(event.stage),
115 ),
116 Effect.exit,
117 );
118 return yield* resolveServerUpdateProgressResult(
119 input.targetVersion,
120 yield* Ref.get(terminal),
121 streamExit,
122 );
123 })
124 : yield* client[WS_METHODS.serverUpdateServer](input).pipe(
125 // Older servers can drop the socket before acknowledging the restart.
126 Effect.catchCauseIf(
127 (cause) =>
128 (capabilities.serverSelfUpdate === "boot-service" ||
129 capabilities.serverSelfUpdate === "respawn") &&
130 isLegacyUpdateHandoffLoss(cause),
131 () =>
132 Effect.succeed({
133 targetVersion: input.targetVersion,
134 method: capabilities.serverSelfUpdate as "boot-service" | "respawn",
135 } satisfies ServerSelfUpdateResult),
136 ),
137 );
138
139 if (
140 updateResult.method === "desktop-app" &&
141 updateResult.desktopUpdateToken !== undefined
142 ) {
143 // The commit relaunches the desktop app, so a dropped socket is success.
144 yield* client[WS_METHODS.serverCommitDesktopUpdate]({
145 requestId: updateResult.desktopUpdateToken,
146 }).pipe(
147 Effect.catchCauseIf(
148 (cause) => isLegacyUpdateHandoffLoss(cause),
149 () => Effect.void,
150 ),
151 );
152 }
153 return updateResult;
154 }),
155 );
156
157 yield* onStage("resuming");
158 const pollUrls = [
159 prepared.httpBaseUrl,
160 ...connectionRoutes(entry).flatMap((route) => routeHttpBaseUrl(route) ?? []),
161 ].filter((url, index, all) => all.indexOf(url) === index);
162 const resumed = yield* Effect.firstSuccessOf(
163 pollUrls.map((httpBaseUrl) =>
164 fetchRemoteEnvironmentDescriptor({ httpBaseUrl }).pipe(
165 Effect.filterOrFail(
166 (descriptor) =>
167 descriptor.environmentId === environmentId && isCompatibleDescriptor(descriptor),
168 () => "not-ready" as const,
169 ),
170 ),
171 ),
172 ).pipe(
173 Effect.provideService(HttpClient.HttpClient, httpClient),
174 Effect.option,
175 Effect.repeat({
176 schedule: Schedule.spaced(Duration.seconds(1)),
177 until: (current) => Option.exists(current, isCompatibleDescriptor),
178 }),
179 Effect.timeoutOption(OUTDATED_HOST_RESTART_TIMEOUT),
180 Effect.map(Option.flatten),
181 );
182 if (Option.isNone(resumed)) {
183 return yield* new OutdatedHostUpdateError({
184 environmentId,
185 message: `${descriptor.label} did not come back on a compatible T3 Code version.`,
186 });
187 }
188
189 // Discovery still holds the old relay descriptor and would re-block the
190 // environment from it, so replace that before clearing the block.
191 if (hasRelayRoute(entry)) {
192 const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery;
193 yield* discovery.refresh;
194 }
195 yield* registry.setCompatibility(environmentId, null);
196 yield* registry.setEnabled(environmentId, true);
197 return { ...result, targetVersion: resumed.value.serverVersion };
198 },
199);
200
201function isCompatibleDescriptor(descriptor: ExecutionEnvironmentDescriptor): boolean {
202 return (descriptor.orchestrationProtocolVersion ?? 1) === ORCHESTRATION_PROTOCOL_VERSION;
203}