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