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