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