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