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 const capabilities = descriptor.capabilities;
74 if (
75 capabilities.serverSelfUpdate === undefined ||
76 (capabilities.serverSelfUpdate === "desktop-managed" &&
77 capabilities.desktopAppUpdate !== true)
78 ) {
79 return yield* new OutdatedHostUpdateError({
80 environmentId,
81 message: `Update T3 Code on ${descriptor.label} manually; it cannot update itself.`,
82 });
83 }
84
85 const result = yield* Effect.scoped(
86 Effect.gen(function* () {
87 const protocolContext = yield* Layer.build(
88 Layer.effect(
89 RpcClient.Protocol,
90 RpcClient.makeProtocolSocket({
91 pingTimeout: PING_TIMEOUT,
92 retryTransientErrors: false,
93 retryPolicy: Schedule.recurs(0),
94 }),
95 ).pipe(
96 Layer.provide(
97 Layer.mergeAll(
98 Socket.layerWebSocket(prepared.socketUrl, {
99 openTimeout: SOCKET_OPEN_TIMEOUT,
100 }).pipe(
101 Layer.provide(Layer.succeed(Socket.WebSocketConstructor, webSocketConstructor)),
102 ),
103 RpcSerialization.layerJson,
104 ),
105 ),
106 ),
107 );
108 const client = yield* makeWsRpcProtocolClient.pipe(Effect.provide(protocolContext));
109
110 const updateResult: ServerSelfUpdateResult =
111 capabilities.serverSelfUpdateProgress === true
112 ? yield* Effect.gen(function* () {
113 const terminal = yield* Ref.make(Option.none<ServerSelfUpdateResult>());
114 const streamExit = yield* client[WS_METHODS.serverUpdateServerWithProgress](
115 input,
116 ).pipe(
117 Stream.runForEach((event) =>
118 event.type === "complete"
119 ? Ref.set(terminal, Option.some(event.result))
120 : onStage(event.stage),
121 ),
122 Effect.exit,
123 );
124 return yield* resolveServerUpdateProgressResult(
125 input.targetVersion,
126 yield* Ref.get(terminal),
127 streamExit,
128 );
129 })
130 : yield* client[WS_METHODS.serverUpdateServer](input).pipe(
131 // Older servers can drop the socket before acknowledging the restart.
132 Effect.catchCauseIf(
133 (cause) =>
134 (capabilities.serverSelfUpdate === "boot-service" ||
135 capabilities.serverSelfUpdate === "respawn") &&
136 isLegacyUpdateHandoffLoss(cause),
137 () =>
138 Effect.succeed({
139 targetVersion: input.targetVersion,
140 method: capabilities.serverSelfUpdate as "boot-service" | "respawn",
141 } satisfies ServerSelfUpdateResult),
142 ),
143 );
144
145 if (
146 updateResult.method === "desktop-app" &&
147 updateResult.desktopUpdateToken !== undefined
148 ) {
149 // The commit relaunches the desktop app, so a dropped socket is success.
150 yield* client[WS_METHODS.serverCommitDesktopUpdate]({
151 requestId: updateResult.desktopUpdateToken,
152 }).pipe(
153 Effect.catchCauseIf(
154 (cause) => isLegacyUpdateHandoffLoss(cause),
155 () => Effect.void,
156 ),
157 );
158 }
159 return updateResult;
160 }),
161 );
162
163 yield* onStage("resuming");
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}