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

selfUpdate.ts

331 lines13.1 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, crossesReleaseTrack } 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 { databaseMigrationHead } from "../persistence/databaseMigrationHead.ts";
29import * as ProcessRunner from "../processRunner.ts";
30import {
31 ensurePinnedRuntimeInstalled,
32 pinnedRuntimeCommand,
33 PinnedRuntimeInstallError,
34 pinnedRuntimePaths,
35 PinnedRuntimePreflightBlockedError,
36 prunePinnedRuntimes,
37} from "./pinnedRuntime.ts";
38import { decodeServicePreflightResult } from "./servicePreflight.ts";
39import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
40import { isExactServiceVersion, SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
41​
42const PREFLIGHT_TIMEOUT = Duration.seconds(30);
43​
44export function resolveServerSelfUpdateCapability(input: {
45 readonly desktopManaged: boolean;
46 readonly launcherManaged: boolean;
47}): ServerSelfUpdateCapability | null {
48 if (input.desktopManaged) return "desktop-managed" as const;
49 return input.launcherManaged ? ("boot-service" as const) : null;
51​
52export class ServerSelfUpdate extends Context.Service<
53 ServerSelfUpdate,
54 {
55 readonly update: (
56 input: ServerSelfUpdateInput,
57 reportProgress?: (
58 stage: ServerSelfUpdateProgressStage,
59 ) => Effect.Effect<void, ServerSelfUpdateError>,
60 onHandoffAccepted?: () => Effect.Effect<void>,
61 ) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;
62 readonly commitDesktopUpdate: (
63 requestId: string,
64 onHandoffAccepted?: () => Effect.Effect<void>,
65 ) => Effect.Effect<never, ServerSelfUpdateError>;
66 }
67>()("t3/cloud/selfUpdate/ServerSelfUpdate") {}
68​
69/**
70 * A server starting from the runtime its launcher settled on means runtimes left by earlier
71 * updates can go. The boot service says so through its IPC context. The SSH launcher and the
72 * install script's `t3` start this home's pinned runtime directly, without one.
73 */
74export const pruneRuntimesOnStart = Effect.fn("cloud.server_self_update.prune_on_start")(
75 function* (input: { readonly baseDir: string; readonly managed: boolean }) {
76 const fs = yield* FileSystem.FileSystem;
77 const path = yield* Path.Path;
78 const platform = yield* HostProcess.Platform;
79 const executablePath = yield* HostProcess.ExecutablePath;
80 const { entryPath } = pinnedRuntimePaths(path, input.baseDir, packageJson.version, platform);
81 // The executable path is resolved, so it names the real path of a symlinked T3 home.
82 const realEntryPath = yield* fs.realPath(entryPath).pipe(Effect.orElseSucceed(() => entryPath));
83 if (!input.managed && executablePath !== entryPath && executablePath !== realEntryPath) {
84 return [];
85 }
86 const removed = yield* prunePinnedRuntimes({
87 baseDir: input.baseDir,
88 keep: [packageJson.version],
89 });
90 if (removed.length > 0) {
91 yield* Effect.logInfo("Removed unused t3 runtimes.", { versions: removed });
92 }
93 return removed;
94 },
95);
96​
97/** The client checks this when planning; the host checks again because its database may have
98 * moved on since (another client updated it). Stable and Nightly each build their own commits,
99 * so crossing tracks needs the target release to know every migration this database holds. */
100export function trackSwitchBlockReason(input: {
101 readonly serverVersion: string;
102 readonly targetVersion: string;
103 readonly targetDatabaseMigration: number | undefined;
104 /** Read only for a crossing; undefined when the database cannot be read. */
105 readonly databaseMigration: () => number | undefined;
106}): string | null {
107 if (!crossesReleaseTrack(input.serverVersion, input.targetVersion)) return null;
108 const databaseMigration = input.databaseMigration();
109 if (input.targetDatabaseMigration === undefined || databaseMigration === undefined) {
110 return `Cannot confirm this database works with t3@${input.targetVersion}. Switch tracks from Settings → About → Update track, which checks it first.`;
111 }
112 return input.targetDatabaseMigration < databaseMigration
113 ? `This database has changes t3@${input.targetVersion} does not support yet; it stays on this release.`
114 : null;
116​
117export const make = Effect.fn("cloud.server_self_update.make")(function* () {
118 const serverConfig = yield* ServerConfig.ServerConfig;
119 const desktopAppUpdate = yield* DesktopAppUpdate.DesktopAppUpdate;
120 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
121 const runner = yield* ProcessRunner.ProcessRunner;
122 const fs = yield* FileSystem.FileSystem;
123 const path = yield* Path.Path;
124 const platform = yield* HostProcess.Platform;
125 const arch = yield* HostProcess.Architecture;
126 const httpClient = yield* HttpClient.HttpClient;
127 const releaseBaseUrl = Option.getOrUndefined(
128 yield* Config.String(CLI_RELEASE_BASE_URL_ENV).pipe(Config.option),
129 );
130 const inFlight = yield* Ref.make(false);
131​
132 yield* pruneRuntimesOnStart({ baseDir: serverConfig.baseDir, managed: launcher.managed }).pipe(
133 Effect.forkScoped,
134 );
135​
136 const capability: ServerSelfUpdateCapability | null =
137 serverConfig.mode === "desktop" ? "desktop-managed" : launcher.managed ? "boot-service" : null;
138 const failWith = (reason: string, cause?: unknown) =>
139 cause === undefined
140 ? new ServerSelfUpdateError({ reason })
141 : new ServerSelfUpdateError({ reason, cause });
142​
143 const crossesTrackUnsafely = (input: ServerSelfUpdateInput) =>
144 trackSwitchBlockReason({
145 serverVersion: packageJson.version,
146 targetVersion: input.targetVersion,
147 targetDatabaseMigration: input.targetDatabaseMigration,
148 databaseMigration: () => databaseMigrationHead(serverConfig.dbPath),
149 });
150​
151 const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
152 "cloud.server_self_update.update",
153 )(function* (input, reportProgress = () => Effect.void, onHandoffAccepted = () => Effect.void) {
154 if (capability === "desktop-managed") {
155 const unsafeCrossing = input.channel === undefined ? null : crossesTrackUnsafely(input);
156 if (unsafeCrossing !== null) return yield* failWith(unsafeCrossing);
157 if (desktopAppUpdate.available) {
158 return yield* desktopAppUpdate.run(
159 reportProgress,
160 input.channel === undefined
161 ? undefined
162 : { channel: input.channel, targetVersion: input.targetVersion },
163 );
164 }
165 return yield* failWith(
166 "This server is managed by the T3 Code desktop app on its machine; update the desktop app to update it.",
167 );
168 }
169 if (capability === null) {
170 return yield* failWith(
171 "Remote updates require the T3 Code background service. Run `t3 service install` on the server machine.",
172 );
173 }
174​
175 const unsafeCrossing = crossesTrackUnsafely(input);
176 if (unsafeCrossing !== null) return yield* failWith(unsafeCrossing);
177 const targetVersion = input.targetVersion.trim();
178 if (!isExactServiceVersion(targetVersion)) {
179 return yield* failWith(`'${targetVersion}' is not an exact t3 version.`);
180 }
181 if (yield* Ref.getAndSet(inFlight, true)) {
182 return yield* failWith("A server update is already in progress.");
183 }
184​
185 return yield* Effect.gen(function* () {
186 yield* reportProgress("downloading");
187 const paths = yield* ensurePinnedRuntimeInstalled({
188 baseDir: serverConfig.baseDir,
189 version: targetVersion,
190 fs,
191 path,
192 runner,
193 httpClient,
194 platform,
195 arch,
196 releaseBaseUrl,
197 validate: (runtime) =>
198 runner
199 .run({
200 command: pinnedRuntimeCommand(runtime).command,
201 args: [
202 ...pinnedRuntimeCommand(runtime).args,
203 "__service-preflight",
204 "--database-path",
205 serverConfig.dbPath,
206 "--launcher-protocol",
207 String(SERVICE_LAUNCHER_PROTOCOL),
208 ],
209 timeout: PREFLIGHT_TIMEOUT,
210 })
211 .pipe(
212 Effect.mapError(
213 (cause) =>
214 new PinnedRuntimeInstallError({
215 step: "running the staged service preflight",
216 cause,
217 }),
218 ),
219 Effect.flatMap(
220 (
221 result,
222 ): Effect.Effect<
223 void,
224 PinnedRuntimeInstallError | PinnedRuntimePreflightBlockedError
225 > => {
226 if (result.code !== 0) {
227 return Effect.fail(
228 new PinnedRuntimeInstallError({
229 step: "running the staged service preflight",
230 exitCode: Number(result.code),
231 stdoutLength: result.stdout.length,
232 stderrLength: result.stderr.length,
233 }),
234 );
235 }
236 let parsed: unknown;
237 try {
238 parsed = JSON.parse(result.stdout.trim());
239 } catch (cause) {
240 return Effect.fail(
241 new PinnedRuntimeInstallError({
242 step: "decoding the staged service preflight",
243 cause,
244 }),
245 );
246 }
247 const preflight = decodeServicePreflightResult(parsed);
248 if (preflight === undefined || preflight.version !== targetVersion) {
249 return Effect.fail(
250 new PinnedRuntimeInstallError({
251 step: "verifying the staged service preflight",
252 }),
253 );
254 }
255 return preflight.status === "ready"
256 ? Effect.void
257 : Effect.fail(
258 new PinnedRuntimePreflightBlockedError({
259 version: targetVersion,
260 reason: preflight.reason,
261 }),
262 );
263 },
264 ),
265 ),
266 }).pipe(
267 Effect.mapError((error) =>
268 error._tag === "PinnedRuntimePreflightBlockedError"
269 ? failWith(error.reason, error)
270 : failWith(`Could not prepare t3@${targetVersion}.`, error),
271 ),
272 );
273​
274 yield* reportProgress("installing");
275 const updateId = yield* Effect.uninterruptible(
276 launcher.requestUpdate({ targetVersion, dbPath: serverConfig.dbPath }).pipe(
277 Effect.mapError((error) =>
278 failWith(
279 error._tag === "ServiceLauncherRejectedError"
280 ? error.reason
281 : "Could not ask the service launcher to activate the prepared update.",
282 error,
283 ),
284 ),
285 Effect.tap(() => onHandoffAccepted()),
286 ),
287 );
288​
289 yield* Effect.logInfo("Server update prepared; handing off to the service launcher.", {
290 updateId,
291 targetVersion,
292 runtimePath: paths.entryPath,
293 });
294 return { targetVersion, method: "boot-service" as const, updateId };
295 }).pipe(Effect.onError(() => Ref.set(inFlight, false)));
296 });
297​
298 return ServerSelfUpdate.of({
299 update,
300 commitDesktopUpdate: Effect.fn("ServerSelfUpdate.commitDesktopUpdate")(
301 function (requestId, onHandoffAccepted) {
302 return desktopAppUpdate.commit(requestId, onHandoffAccepted);
303 },
304 ),
305 });
306});
307​
308export const layer = Layer.effect(ServerSelfUpdate, make()).pipe(
309 Layer.provide(ProcessRunner.layer),
310);
311​
312// The update outlives client sockets; progress offers to a closed queue are ignored.
313export const updateProgressStream = (
314 selfUpdate: ServerSelfUpdate["Service"],
315 input: ServerSelfUpdateInput,
316) =>
317 Stream.callback<ServerSelfUpdateProgressEvent, ServerSelfUpdateError>((queue) => {
318 const offer = (event: ServerSelfUpdateProgressEvent) =>
319 Queue.offer(queue, event).pipe(Effect.ignore);
320​
321 return selfUpdate
322 .update(input, (stage) => offer({ type: "progress", stage }))
323 .pipe(
324 Effect.flatMap((result) => offer({ type: "complete", result })),
325 Effect.catchTags({
326 ServerSelfUpdateError: (error) => Queue.fail(queue, error).pipe(Effect.ignore),
327 }),
328 Effect.andThen(Queue.end(queue).pipe(Effect.ignore)),
329 Effect.forkDetach,
330 );
331 });