Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

outdatedHostUpdate.ts

254 lines9.9 KB

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