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

selfUpdate.ts

293 lines11.0 KB

1import {
2 ServerSelfUpdateError,
3 type ServerSelfUpdateCapability,
4 type ServerSelfUpdateInput,
5 type ServerSelfUpdateProgressEvent,
6 type ServerSelfUpdateProgressStage,
7 type ServerSelfUpdateResult,
8} from "@t3tools/contracts";
9import * as HostProcess from "@t3tools/shared/HostProcess";
10import * as Config from "effect/Config";
11import * as Context from "effect/Context";
12import * as Duration from "effect/Duration";
13import * as Effect from "effect/Effect";
14import * as Option from "effect/Option";
15import * as Ref from "effect/Ref";
16import * as FileSystem from "effect/FileSystem";
17import * as Layer from "effect/Layer";
18import * as Path from "effect/Path";
19import * as Queue from "effect/Queue";
20import * as Stream from "effect/Stream";
21import { HttpClient } from "effect/http";
22​
23import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease";
24​
25import packageJson from "../../package.json" with { type: "json" };
26import * as ServerConfig from "../config.ts";
27import * as DesktopAppUpdate from "../desktopUpdate/DesktopAppUpdate.ts";
28import * as ProcessRunner from "../processRunner.ts";
29import {
30 ensurePinnedRuntimeInstalled,
31 pinnedRuntimeCommand,
32 PinnedRuntimeInstallError,
33 pinnedRuntimePaths,
34 PinnedRuntimePreflightBlockedError,
35 prunePinnedRuntimes,
36} from "./pinnedRuntime.ts";
37import { decodeServicePreflightResult } from "./servicePreflight.ts";
38import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
39import { isExactServiceVersion, SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
40​
41const PREFLIGHT_TIMEOUT = Duration.seconds(30);
42​
43export function resolveServerSelfUpdateCapability(input: {
44 readonly desktopManaged: boolean;
45 readonly launcherManaged: boolean;
46}): ServerSelfUpdateCapability | null {
47 if (input.desktopManaged) return "desktop-managed" as const;
48 return input.launcherManaged ? ("boot-service" as const) : null;
50​
51export class ServerSelfUpdate extends Context.Service<
52 ServerSelfUpdate,
53 {
54 readonly update: (
55 input: ServerSelfUpdateInput,
56 reportProgress?: (
57 stage: ServerSelfUpdateProgressStage,
58 ) => Effect.Effect<void, ServerSelfUpdateError>,
59 onHandoffAccepted?: () => Effect.Effect<void>,
60 ) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;
61 readonly commitDesktopUpdate: (
62 requestId: string,
63 onHandoffAccepted?: () => Effect.Effect<void>,
64 ) => Effect.Effect<never, ServerSelfUpdateError>;
65 }
66>()("t3/cloud/selfUpdate/ServerSelfUpdate") {}
67​
68/**
69 * A server starting from the runtime its launcher settled on means runtimes left by earlier
70 * updates can go. The boot service says so through its IPC context. The SSH launcher and the
71 * install script's `t3` start this home's pinned runtime directly, without one.
72 */
73export const pruneRuntimesOnStart = Effect.fn("cloud.server_self_update.prune_on_start")(
74 function* (input: { readonly baseDir: string; readonly managed: boolean }) {
75 const fs = yield* FileSystem.FileSystem;
76 const path = yield* Path.Path;
77 const platform = yield* HostProcess.Platform;
78 const executablePath = yield* HostProcess.ExecutablePath;
79 const { entryPath } = pinnedRuntimePaths(path, input.baseDir, packageJson.version, platform);
80 // The executable path is resolved, so it names the real path of a symlinked T3 home.
81 const realEntryPath = yield* fs.realPath(entryPath).pipe(Effect.orElseSucceed(() => entryPath));
82 if (!input.managed && executablePath !== entryPath && executablePath !== realEntryPath) {
83 return [];
84 }
85 const removed = yield* prunePinnedRuntimes({
86 baseDir: input.baseDir,
87 keep: [packageJson.version],
88 });
89 if (removed.length > 0) {
90 yield* Effect.logInfo("Removed unused t3 runtimes.", { versions: removed });
91 }
92 return removed;
93 },
94);
95​
96export const make = Effect.fn("cloud.server_self_update.make")(function* () {
97 const serverConfig = yield* ServerConfig.ServerConfig;
98 const desktopAppUpdate = yield* DesktopAppUpdate.DesktopAppUpdate;
99 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
100 const runner = yield* ProcessRunner.ProcessRunner;
101 const fs = yield* FileSystem.FileSystem;
102 const path = yield* Path.Path;
103 const platform = yield* HostProcess.Platform;
104 const arch = yield* HostProcess.Architecture;
105 const httpClient = yield* HttpClient.HttpClient;
106 const releaseBaseUrl = Option.getOrUndefined(
107 yield* Config.String(CLI_RELEASE_BASE_URL_ENV).pipe(Config.option),
108 );
109 const inFlight = yield* Ref.make(false);
110​
111 yield* pruneRuntimesOnStart({ baseDir: serverConfig.baseDir, managed: launcher.managed }).pipe(
112 Effect.forkScoped,
113 );
114​
115 const capability: ServerSelfUpdateCapability | null =
116 serverConfig.mode === "desktop" ? "desktop-managed" : launcher.managed ? "boot-service" : null;
117 const failWith = (reason: string, cause?: unknown) =>
118 cause === undefined
119 ? new ServerSelfUpdateError({ reason })
120 : new ServerSelfUpdateError({ reason, cause });
121​
122 const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
123 "cloud.server_self_update.update",
124 )(function* (input, reportProgress = () => Effect.void, onHandoffAccepted = () => Effect.void) {
125 if (capability === "desktop-managed") {
126 if (desktopAppUpdate.available) {
127 return yield* desktopAppUpdate.run(reportProgress);
128 }
129 return yield* failWith(
130 "This server is managed by the T3 Code desktop app on its machine; update the desktop app to update it.",
131 );
132 }
133 if (capability === null) {
134 return yield* failWith(
135 "Remote updates require the T3 Code background service. Run `t3 service install` on the server machine.",
136 );
137 }
138​
139 const targetVersion = input.targetVersion.trim();
140 if (!isExactServiceVersion(targetVersion)) {
141 return yield* failWith(`'${targetVersion}' is not an exact t3 version.`);
142 }
143 if (yield* Ref.getAndSet(inFlight, true)) {
144 return yield* failWith("A server update is already in progress.");
145 }
146​
147 return yield* Effect.gen(function* () {
148 yield* reportProgress("downloading");
149 const paths = yield* ensurePinnedRuntimeInstalled({
150 baseDir: serverConfig.baseDir,
151 version: targetVersion,
152 fs,
153 path,
154 runner,
155 httpClient,
156 platform,
157 arch,
158 releaseBaseUrl,
159 validate: (runtime) =>
160 runner
161 .run({
162 command: pinnedRuntimeCommand(runtime).command,
163 args: [
164 ...pinnedRuntimeCommand(runtime).args,
165 "__service-preflight",
166 "--database-path",
167 serverConfig.dbPath,
168 "--launcher-protocol",
169 String(SERVICE_LAUNCHER_PROTOCOL),
170 ],
171 timeout: PREFLIGHT_TIMEOUT,
172 })
173 .pipe(
174 Effect.mapError(
175 (cause) =>
176 new PinnedRuntimeInstallError({
177 step: "running the staged service preflight",
178 cause,
179 }),
180 ),
181 Effect.flatMap(
182 (
183 result,
184 ): Effect.Effect<
185 void,
186 PinnedRuntimeInstallError | PinnedRuntimePreflightBlockedError
187 > => {
188 if (result.code !== 0) {
189 return Effect.fail(
190 new PinnedRuntimeInstallError({
191 step: "running the staged service preflight",
192 exitCode: Number(result.code),
193 stdoutLength: result.stdout.length,
194 stderrLength: result.stderr.length,
195 }),
196 );
197 }
198 let parsed: unknown;
199 try {
200 parsed = JSON.parse(result.stdout.trim());
201 } catch (cause) {
202 return Effect.fail(
203 new PinnedRuntimeInstallError({
204 step: "decoding the staged service preflight",
205 cause,
206 }),
207 );
208 }
209 const preflight = decodeServicePreflightResult(parsed);
210 if (preflight === undefined || preflight.version !== targetVersion) {
211 return Effect.fail(
212 new PinnedRuntimeInstallError({
213 step: "verifying the staged service preflight",
214 }),
215 );
216 }
217 return preflight.status === "ready"
218 ? Effect.void
219 : Effect.fail(
220 new PinnedRuntimePreflightBlockedError({
221 version: targetVersion,
222 reason: preflight.reason,
223 }),
224 );
225 },
226 ),
227 ),
228 }).pipe(
229 Effect.mapError((error) =>
230 error._tag === "PinnedRuntimePreflightBlockedError"
231 ? failWith(error.reason, error)
232 : failWith(`Could not prepare t3@${targetVersion}.`, error),
233 ),
234 );
235​
236 yield* reportProgress("installing");
237 const updateId = yield* Effect.uninterruptible(
238 launcher.requestUpdate({ targetVersion, dbPath: serverConfig.dbPath }).pipe(
239 Effect.mapError((error) =>
240 failWith(
241 error._tag === "ServiceLauncherRejectedError"
242 ? error.reason
243 : "Could not ask the service launcher to activate the prepared update.",
244 error,
245 ),
246 ),
247 Effect.tap(() => onHandoffAccepted()),
248 ),
249 );
250​
251 yield* Effect.logInfo("Server update prepared; handing off to the service launcher.", {
252 updateId,
253 targetVersion,
254 runtimePath: paths.entryPath,
255 });
256 return { targetVersion, method: "boot-service" as const, updateId };
257 }).pipe(Effect.onError(() => Ref.set(inFlight, false)));
258 });
259​
260 return ServerSelfUpdate.of({
261 update,
262 commitDesktopUpdate: Effect.fn("ServerSelfUpdate.commitDesktopUpdate")(
263 function (requestId, onHandoffAccepted) {
264 return desktopAppUpdate.commit(requestId, onHandoffAccepted);
265 },
266 ),
267 });
268});
269​
270export const layer = Layer.effect(ServerSelfUpdate, make()).pipe(
271 Layer.provide(ProcessRunner.layer),
272);
273​
274// The update outlives client sockets; progress offers to a closed queue are ignored.
275export const updateProgressStream = (
276 selfUpdate: ServerSelfUpdate["Service"],
277 input: ServerSelfUpdateInput,
278) =>
279 Stream.callback<ServerSelfUpdateProgressEvent, ServerSelfUpdateError>((queue) => {
280 const offer = (event: ServerSelfUpdateProgressEvent) =>
281 Queue.offer(queue, event).pipe(Effect.ignore);
282​
283 return selfUpdate
284 .update(input, (stage) => offer({ type: "progress", stage }))
285 .pipe(
286 Effect.flatMap((result) => offer({ type: "complete", result })),
287 Effect.catchTags({
288 ServerSelfUpdateError: (error) => Queue.fail(queue, error).pipe(Effect.ignore),
289 }),
290 Effect.andThen(Queue.end(queue).pipe(Effect.ignore)),
291 Effect.forkDetach,
292 );
293 });